diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index a4c720847e..3ec390f55e 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -67,8 +67,8 @@ jobs: # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | - echo "Run, Build Application using script" - gradle clean build + # echo "Run, Build Application using script" + # gradle clean build - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 diff --git a/.gitignore b/.gitignore index 72ab296f63..6c3cd331f6 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ *.swp *.iml */*.iml +*.ipr +*.iws bin/ build/ @@ -22,7 +24,7 @@ pg/*.bak pg/*.bpg pg/*.txt -.idea +.idea/ codesigning.jks diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4f7b3f73fd..832bffa0fc 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -2,6 +2,8 @@ stages: - check - build - test + - publish + - sync check-code: stage: check @@ -30,33 +32,13 @@ ant-build: - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/build_1_8.sh\"" -test-code-8: +test-code: stage: test needs: [ "check-code" ] script: - "ecr_login" - "ecr_pull vm_base_intel latest" - - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/test_8.sh\"" - artifacts: - when: always - reports: - junit: - - "core/build/test-results/**/*.xml" - - "prov/build/test-results/**/*.xml" - - "pg/build/test-results/**/*.xml" - - "pkix/build/test-results/**/*.xml" - - "mail/build/test-results/**/*.xml" - - "util/build/test-results/**/*.xml" - - "tls/build/test-results/**/*.xml" - - "mls/build/test-results/**/*.xml" - -test-code-11: - stage: test - needs: [ "check-code" ] - script: - - "ecr_login" - - "ecr_pull vm_base_intel latest" - - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/test_11.sh\"" + - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/test.sh\"" artifacts: when: always reports: @@ -71,43 +53,15 @@ test-code-11: - "mls/build/test-results/**/*.xml" -test-code-17: - stage: test - needs: [ "check-code" ] +publish: + stage: publish script: + - "apply_overlay bc-java-pub ./" - "ecr_login" - "ecr_pull vm_base_intel latest" - - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/test_17.sh\"" - artifacts: - when: always - reports: - junit: - - "core/build/test-results/**/*.xml" - - "prov/build/test-results/**/*.xml" - - "pg/build/test-results/**/*.xml" - - "pkix/build/test-results/**/*.xml" - - "mail/build/test-results/**/*.xml" - - "util/build/test-results/**/*.xml" - - "tls/build/test-results/**/*.xml" - - "mls/build/test-results/**/*.xml" - + - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/pub.sh\"" -test-code-21: - stage: test - needs: [ "check-code" ] +spongycastle: + stage: "sync" script: - - "ecr_login" - - "ecr_pull vm_base_intel latest" - - "ci_docker_run \"vm_base_intel:latest\" \"bc-java\" \"/workspace/bc-java/ci/test_21.sh\"" - artifacts: - when: always - reports: - junit: - - "core/build/test-results/**/*.xml" - - "prov/build/test-results/**/*.xml" - - "pg/build/test-results/**/*.xml" - - "pkix/build/test-results/**/*.xml" - - "mail/build/test-results/**/*.xml" - - "util/build/test-results/**/*.xml" - - "tls/build/test-results/**/*.xml" - - "mls/build/test-results/**/*.xml" + - "syncpongy.sh" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..771bf2884b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Bouncy Castle Contributing Guidelines + +Thank you for contributing to Bouncy Castle! + +In this guide, you get an overview of the contribution workflow from starting a discussion or opening an issue, to creating, reviewing, and merging a pull request. + +For an overview of the project, see [README](README.md). + +### Start a discussion +If you have a question or problem, you can [search in discussions](https://github.com/bcgit/bc-java/discussions), if someone has already found a solution to your problem. + +Or you can [start a new discussion](https://github.com/bcgit/bc-java/discussions/new/choose) and ask your question. + +### Create an issue + +If you find a problem with Bouncy Castle, [search if an issue already exists](https://github.com/bcgit/bc-java/issues). + +> **_NOTE:_** If the issue is a __potential security problem__, please contact us +before posting anything public. See [Security Policy](SECURITY.md). + +If a related discussion or issue doesn't exist, and the issue is not security related, you can [open a new issue](https://github.com/bcgit/bc-java/issues/new). An issue can be converted into a discussion if regarded as one. + +### Contribute to the code + +For substantial, non-trivial contributions, you may be asked to sign a contributor assignment agreement. Optionally, you can also have your name and contact information listed in [Contributors](https://www.bouncycastle.org/contributors.html). + +Please note we are unable to accept contributions which cannot be released under the [Bouncy Castle License](https://www.bouncycastle.org/licence.html). Issuing a pull request on our public github mirror is taken as agreement to issuing under the Bouncy Castle License. + +#### Create a pull request + +> **_NOTE:_** If the issue is a __potential security problem__, please contact us. See [Security Policy](SECURITY.md). + +You are welcome to send patches, under the Bouncy Castle License, as pull requests. For more information, see [Creating a pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). For minor updates, you can instead choose to create an issue with short snippets of code. See above. + +* For contributions touching multiple files try and split up the pull request, smaller changes are easier to review and test, as well as being less likely to run into merge issues. +* Create a test cases for your change, it may be a simple addition to an existing test. If you do not know how to do this, ask us and we will help you. +* If you run into any merge issues, check out this [git tutorial](https://github.com/skills/resolve-merge-conflicts) to help you resolve merge conflicts and other issues. + +For more information, refer to the Bouncy Castle documentation on [Getting Started with Bouncy Castle](https://doc.primekey.com/bouncycastle/introduction#Introduction-GettingStartedwithBouncyCastle). + +#### Self-review + +Don't forget to self-review. Please follow these simple guidelines: +* Keep the patch limited, only change the parts related to your patch. +* Do not change other lines, such as whitespace, adding line breaks to Java doc, etc. It will make it very hard for us to review the patch. + + +#### Your pull request is merged + +For acceptance, pull requests need to meet specific quality criteria, including tests for anything substantial. Someone on the Bouncy Castle core team will review the pull request when there is time, and let you know if something is missing or suggest improvements. If it is a useful and generic feature it will be integrated in Bouncy Castle to be available in a later release. + diff --git a/CONTRIBUTORS.html b/CONTRIBUTORS.html index 12e559629f..ba9ab62d06 100644 --- a/CONTRIBUTORS.html +++ b/CONTRIBUTORS.html @@ -447,16 +447,15 @@
  • Adam Vartanian <https://github.com/flooey> use of ShortBuffer exception and buffer size pre-check in Cipher.doFinal().
  • Bernd <https://github.com/ecki> Fix to make PGPUtil.pipeFileContents use buffer and not leak file handle.
  • Shartung <https://github.com/shartung> Additional EC Key Agreement algorithms in support of German BSI TR-03111.
  • -
  • Paul Schaub <https://github.com/vanitasvitae> bringing PGPSecretKey.getUserIds() into line with PGPPublicKey.getUserIds(). Exception message fix in BcPublicKeyDataDecryptorFactory. Additional tests on PGP key ring generation. Improved functionality of PGPSignatureSubpacketGenerator, PGPPublicKeyRing. Tweaks to PGPDataEncryptorBuilder interface, fix for JcaPGP/BcPGP Ed25519 private key conversion. Added configurable CRC detection to ArmoredInputStream, additional control character skipping in ArmoredInputStream. Rewind code for PGPPBEEncryptedData, addition of PGPSignature.getDigestPrefix(). Wrong list traversal fix in PGPSecretKeyRing. Further improvement to use of generics in PGP API. General interop improvements. PGP Public / Secure keyring ignore marker packets when reading. Initial work on PGP session key handling, filtering literal data for canoncialization. Addition of direct key identified key-ring construction. PGPSecretKeyRing.insertOrReplacePublicKey addition. Addition of utility methods for joining/merging signatures and public keys. Addition of PGP regexp packet, PolicyURI packet handling, UTF8 comment testing. Efficiency improvements to TruncatedStream. Initial Argon2 support for OpenPGP. General cleanups. Fast CRC24 implementation, SHA3 addtions to BcImplProvider, improvements to One Pass Signature support, signatue validation, read() consistency in BCPGInputStream. Contributions to AEAD support (v6 & v5) in PGP API. Addition of PGP WildCard ID, moving the PGP example code into the 21st century. Security patches for encrypted data generation, initial thread safe certification verification. Support for V6 EC keys, PGP packet criticality, and Preferred AEAD CipherSuites sigsubpacket support.
  • +
  • Paul Schaub <https://github.com/vanitasvitae> bringing PGPSecretKey.getUserIds() into line with PGPPublicKey.getUserIds(). Exception message fix in BcPublicKeyDataDecryptorFactory. Additional tests on PGP key ring generation. Improved functionality of PGPSignatureSubpacketGenerator, PGPPublicKeyRing. Tweaks to PGPDataEncryptorBuilder interface, fix for JcaPGP/BcPGP Ed25519 private key conversion. Added configurable CRC detection to ArmoredInputStream, additional control character skipping in ArmoredInputStream. Rewind code for PGPPBEEncryptedData, addition of PGPSignature.getDigestPrefix(). Wrong list traversal fix in PGPSecretKeyRing. Further improvement to use of generics in PGP API. General interop improvements. PGP Public / Secure keyring ignore marker packets when reading. Initial work on PGP session key handling, filtering literal data for canoncialization. Addition of direct key identified key-ring construction. PGPSecretKeyRing.insertOrReplacePublicKey addition. Addition of utility methods for joining/merging signatures and public keys. Addition of PGP regexp packet, PolicyURI packet handling, UTF8 comment testing. Efficiency improvements to TruncatedStream. Initial Argon2 support for OpenPGP. General cleanups. Fast CRC24 implementation, SHA3 addtions to BcImplProvider, improvements to One Pass Signature support, signatue validation, read() consistency in BCPGInputStream. Contributions to AEAD support (v6 & v5) in PGP API. Addition of PGP WildCard ID, moving the PGP example code into the 21st century. Security patches for encrypted data generation, initial thread safe certification verification. Support for V6 EC keys, V6 signatures, V6 encryption, V6 PKESK, PGP packet criticality, and Preferred AEAD CipherSuites sigsubpacket support. Introduce high-level OpenPGP API for message creation/consumption and certificate evaluation
  • Nick of Nexxar <https://github.com/nros> update to OpenPGP package to handle a broader range of EC curves.
  • catbref <https://github.com/catbref> sample implementation of RFC 7748/Ed25519 (incorporated work from github users Valodim and str4d as well).
  • gerlion <https://github.com/gerlion> detection of concurrency issue with pre-1.60 EC math library.
  • fgrieu <fgrieu@gmail.com> identification and suggested fixes for possible timing vulnerability in OAEPEncoding and RSACoreEngine.
  • MTG <https://github.com/mtgag> patch for decoding issues in PKIPublicationInfo and CertifiedKeyPair, patch for adding jurisdiction{C,ST,L} to X500 name style.
  • Andreas Gadermaier <up.gadermaier@gmail.com> initial version of Argon2 PBKDF algorithm.
  • -
  • Tony Washer <tony.washer@yahoo.co.uk> review of qTesla, Java 1.9 module code, additional test code and debugging for GOST, DSTU, and ECNR algorithms. Initial lightweight implementation of the ZUC ciphers and macs. Additions to LMS/HSS API implementations, fix for truncation issue with big HSS keys, contributions to optimization of LMS/HSS. Patch for XDH/EdDSA key handling and mcEliece decryption using kobaraImai. Initial GCM-SIV, Blake3, and Kangaroo implementation.
  • +
  • Tony Washer <https://github.com/tonywasher> ECIESKeyEncapsulation fix for use of OldCofactor mode. Submitted ChaCha20Poly1305 prototype. Remove support for maxXofLen in Kangaroo. Police Blake3 output limit. Add LEAEngine. Review of qTesla, Java 1.9 module code, additional test code and debugging for GOST, DSTU, and ECNR algorithms. Initial lightweight implementation of the ZUC ciphers and macs. Additions to LMS/HSS API implementations, fix for truncation issue with big HSS keys, contributions to optimization of LMS/HSS. Patch for XDH/EdDSA key handling and mcEliece decryption using kobaraImai. Initial GCM-SIV, Blake3, and Kangaroo implementation. Corrections to length outputs for getUpdateOutputSize()/doFinal() in ISAP, PhotonBeetle, and Xoodyak. Fix GCFB reset. Fix Elephant multi-part process. Fix AsconXof support multi-part outputs.
  • Vincent Bouckaert <https://github.com/veebee> initial version of RFC 4998 ASN.1 classes. Debugging and testing of high level RFC 4998 implementation.
  • -
  • Tony Washer <https://github.com/tonywasher> ECIESKeyEncapsulation fix for use of OldCofactor mode. Submitted ChaCha20Poly1305 prototype. Remove support for maxXofLen in Kangaroo. Police Blake3 output limit. Add LEAEngine.
  • Aurimas Liutikas <https://github.com/liutikas> JavaDoc patches to ReasonsMask.
  • Gabriel Sroka <https://github.com/gabrielsroka> corrected comments in RSA validation.
  • sarah-mdv <https://github.com/sarah-mdv> improvements to JceKeyTransRecipientInfoGenerator, tests for JournalingSecureRandom, initial implementation of JournaledAlgorithm.
  • @@ -543,10 +542,28 @@
  • Bing Shi <roadicing@gmail.com> - addition of F2m bounds checking for imported EC F2m curves.
  • Phil Brown <https://github.com/brownp2k> - additional ant targets for building util and pkix.
  • Tamas Cservenak <https://github.com/cstamas> - initial patch for supporting Ed25519 keys in GnuPG S-expressions.
  • -
  • chchen-scholar <https://github.com/chchen-scholar> - encoding fix for EccP256CurvePoint.
  • +
  • chchen-scholar <https://github.com/chchen-scholar> - encoding fix for EccP256CurvePoint, fix missing extension EtsiTs102941TypesAuthorization.InnerAtRequest
  • Seung Yeon <https://github.com/seungyeonpark> - addition of Memoable method implementations to CertPathValidationContext and CertificatePoliciesValidation.
  • yuhh0328 <https://github.com/yuhh0328> - initial patch for adding ML-KEM support to TLS.
  • -
  • Jan Oupický <https://github.com/Honzaik> - update to draft 13 of composite PQC signatures.
  • +
  • Jan Oupický <https://github.com/Honzaik> - update to draft 13 of composite PQC signatures, patch for human readable algorithm name for composite private keys.
  • +
  • Karsten Otto <https://github.com/ottoka> - finished the support for jdk.tls.server.defaultDHEParameters.
  • +
  • Markus Sommer <https://github.com/marsom> - BCStyle lookup table fix for jurisdiction values.
  • +
  • Jared Crawford <https://github.com/jmcrawford45> - Abstracting cire KEM functionality out of DHKEM to allow for use of alternative KEMs with HPKE.
  • +
  • TaZbon <https://github.com/TaZbon> - Optional lax parsing patch for PEM parser.
  • +
  • han-ji <https://github.com/han-jl> - Fix to sign extension issue in CTR random seek code.
  • +
  • https://github.com/crlorentzen <https://github.com/crlorentzen> - Addition of system property for configuring GCM ciphers in 1.2 FIPS mode in the JSSE.
  • +
  • Jakub Zelenka <https://github.com/bukka> - Initial SMIMEAuthEnvelopedData classes.
  • +
  • rde-infologic <https://github.com/rde-infologic> - Initial SMIMEEnvelopedUtil class.
  • +
  • moonfruit <https://github.com/moonfruit> - Patch to allow for extensions of GMSignatureSpi.
  • +
  • Marcono1234 <https://github.com/Marcono1234> - Updates to OpenBSDBCrypt JavaDoc.
  • +
  • DawidM <https://github.com/dawmit> - Implementation of EC J-PAKE.
  • +
  • Syed Quasim <https://github.com/HawkItzme> - lint checker fix for EST getTrustAllTrustManager().
  • +
  • winfriedgerlach <https://github.com/winfriedgerlach> - patch to SecretKeyUtil class, patch to DigestFactory cloner for SHA-1.
  • +
  • feuxfollets1013 <https://github.com/feuxfollets1013> - Initial add JDK21 KEM API implementation for HQC algorithm.
  • +
  • cragkhit <https://github.com/cragkhit> - addition of null check in some test utility methods to avoid needless exceptions.
  • +
  • zhsnew <https://github.com/zhsnew> - correct AsconCXof128 implementation and add test vectors
  • +
  • mt-johan <https://github.com/mt-johan> - patch to preserve PRF on initializing from protectionAlgorithm with PBMAC1.
  • +
  • oscerd <https://github.com/oscerd> - comment corrections in GMSSRootSig.java.
  • diff --git a/HOWTO.md b/HOWTO.md new file mode 100644 index 0000000000..c728d84096 --- /dev/null +++ b/HOWTO.md @@ -0,0 +1,129 @@ +# Bouncy Castle Java API How To +## Using Bouncy Castle with GraalVM Native Image +### Problem: Provider Not Registered at Build Time with `UnsupportedFeatureError` Exception +#### Error message +```text +Trying to verify a provider that was not registered at build time: BC version... +``` +#### Cause: +Bouncy Castle security provider isn't properly registered during GraalVM native image build process. + +### Solution 1: Static Initializer Approach (No GraalVM SDK) +#### Step 1. Create Initializer Class +```java +package com.yourpackage.crypto; // ← Replace with your actual package + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import java.security.Security; + +public class BCInitializer { + static { + // Force provider registration during image build + Security.addProvider(new BouncyCastleProvider()); + } +} +``` + +#### Step 2. And then in the native-image build configuration +For Maven (`pom.xml`) +```xml + + org.graalvm.buildtools + native-maven-plugin + 0.9.28 + + + + --initialize-at-build-time=org.bouncycastle,com.yourpackage.crypto.BCInitializer + + --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$Default,org.bouncycastle.jcajce.provider.drbg.DRBG$NonceAndIV + + + +``` + +For Gradle (`build.gradle`), +```gradle + buildArgs.add('--initialize-at-build-time=com.yourpackage.crypto.BCInitializer') + buildArgs.add("--initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG\$Default,org.bouncycastle.jcajce.provider.drbg.DRBG\$NonceAndIV") +``` +# Key Configuration + +| Argument | Purpose | +| ------------------------------- |-----------------------------------------------------------------| +| `--initialize-at-build-time` | Forces inclusion of BC classes and triggers static initializer. | +| `--initialize-at-run-time` | Solves stateful SecureRandom initialization issues. | +|`--enable-all-security-services` | (optional) Enables JCE security infrastructure | + + +### Solution 2: GraalVM Feature Approach (With SDK) + +#### Step 1: Create a Native Image Feature +```java +package com.yourpackage.crypto; // ← Replace with your actual package + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.graalvm.nativeimage.hosted.Feature; + +import java.security.Security; + +/** + * A GraalVM Feature that registers the Bouncy Castle provider. + * This is required so that native image builds verify and include the provider. + */ +public class BouncyCastleFeature implements Feature { + + @Override + public void afterRegistration(AfterRegistrationAccess access) { + // Register the Bouncy Castle provider + Security.addProvider(new BouncyCastleProvider()); + } +} +``` + +#### Step 2: Configure Dependencies and Build +##### 2.1 add dependency +```xml + + org.graalvm.sdk + graal-sdk + 21.0.0 + provided + +``` +##### 2.2 add plugin +```xml + + org.graalvm.buildtools + native-maven-plugin + 0.9.28 + + + --features=com.yourpackage.crypto.BouncyCastleFeature + --initialize-at-build-time=org.bouncycastle + --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$Default,org.bouncycastle.jcajce.provider.drbg.DRBG$NonceAndIV + + + +``` +Key Configuration Explanations: +`--features=...` +- Registers custom feature class that adds BouncyCastle provider at build time +- Required for JCE security provider verification + +### Troubleshooting +#### Common Issues +##### Classpath Conflicts: + +```text +Error: Class-path entry contains class from image builder +``` +Fix: Add `-H:+AllowDeprecatedBuilderClassesOnImageClasspath` (temporary) or ensure graal-sdk has provided scope + +##### Missing Algorithms: +Example of the error message: +```text +No such algorithm: AES/CBC/PKCS5Padding +``` + +Fix: Verify `--initialize-at-build-time` includes `org.bouncycastle` \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000..277dcd1ebb --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,13 @@ +Copyright (c) 2000-2024 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org). +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sub license, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: The above copyright notice and this +permission notice shall be included in all copies or substantial portions of the Software. + +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.** diff --git a/README.md b/README.md index d6a1c3ba51..401dc8a9fb 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ # The Bouncy Castle Crypto Package For Java -[![Build Status](https://travis-ci.org/bcgit/bc-java.svg?branch=master)](https://travis-ci.org/bcgit/bc-java) - 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](https://www.bouncycastle.org). The Legion also gratefully acknowledges the contributions made to this package by others (see [here](https://www.bouncycastle.org/contributors.html) 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](https://www.bouncycastle.org/donate), sponsor some specific work, or purchase a support contract through [Crypto Workshop](https://www.keyfactor.com/platform/bouncy-castle-support/) (now part of Keyfactor). @@ -12,17 +10,39 @@ Except where otherwise stated, this software is distributed under a license base **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 [office@bouncycastle.org](mailto:office@bouncycastle.org). +## Maven Public Key + +The file [bc_maven_public_key.asc](bc_maven_public_key.asc) contains the public key used to sign our artifacts on Maven Central. You will need to use + +``` +gpg -o bc_maven_public_key.gpg --dearmor bc_maven_public_key.asc +``` + +to dearmor the key before use. Once that is done, a file can be verified by using: + +``` +gpg --no-default-keyring --keyring ./bc_maven_public_key.gpg --verify file_name.jar.asc file_name.jar +``` + +Note: the ./ is required in front of the key file name to tell gpg to look locally. + +## Building overview + +This project can now be built and tested with JDK21. + +If the build script detects BC_JDK8, BC_JDK11, BC_JDK17 it will add to the usual test task a dependency on test tasks +that specifically use the JVMs addressed by those environmental variables. The script relies on JAVA_HOME for picking up Java 21 if it is use. + +We support testing on specific JVMs as it is the only way to be certain the library is compatible. ## Environmental Variables -Before invoking gradlew you need to ensure the following environmental variables are defined and point -to valid JAVA_HOMEs for each JVM version: +The following environmental variables can optionally point to the JAVA_HOME for each JVM version. ``` export BC_JDK8=/path/to/java8 export BC_JDK11=/path/to/java11 export BC_JDK17=/path/to/java17 -export BC_JDK21=/path/to/java21 ``` ## Building @@ -32,7 +52,8 @@ The project now uses ```gradlew``` which can be invoked for example: ``` # from the root of the project -# Ensure JAVA_HOME points to JDK 17 or higher JAVA_HOME +# Ensure JAVA_HOME points to JDK 21 or higher JAVA_HOME or that +# gradlew can find a java 21 installation to use. ./gradlew clean build @@ -43,19 +64,17 @@ The gradle script will endeavour to verify their existence but not the correctne ## Multi-release jars and testing -Some subprojects produce multi-release jars and these jars are tested in different jvm versions. -Default testing on these projects is done on java 1.8 and there are specific test tasks for other versions. - -1. test11 test on java 11 JVM -2. test17 test on java 17 JVM -3. test21 test on java 21 JVM - -To run all of them: +Some subprojects produce multi-release jars and these jars are can be tested on different jvm versions specifically. +If the env vars are defined: ``` -./gradlew clean build test11 test17 test21 +export BC_JDK8=/path/to/java8 +export BC_JDK11=/path/to/java11 +export BC_JDK17=/path/to/java17 ``` +If only a Java 21 JDK is present then the normal test task and test21 are run only. + ## Code Organisation diff --git a/SECURITY.md b/SECURITY.md index c365182c2f..3813599af0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,5 +1,17 @@ -# Reporting a security issue +# Security Policy -If you would like to report something you believe to be a security issue -then please use feedback-crypto@bouncycastle.org. -We can provide a PGP key if required. +## Reporting a Vulnerability + +If you think that you have found a security vulnerability, please report it to this email address: [feedback-crypto@bouncycastle.org](mailto:feedback-crypto@bouncycastle.org) + +Describe the issue including all details, for example: +* Short summary of the problem +* Steps to reproduce +* Affected API versions +* Logs if available + +The Bouncy Castle team will send a response indicating the next steps in handling your report. You may be asked to provide additional information or guidance. + +If the issue is confirmed as a vulnerability, we will open a Security Advisory and acknowledge your contributions as part of it. Optionally, you can have your name and contact information listed in [Contributors](https://www.bouncycastle.org/contributors.html) as well. + +Please note we endeavor to issue patched releases that deal with security issues as soon as they are made known to us, ideally prior to issuing a Security Advisory where otherwise possible. In some cases, particularly if it relates to a FIPS release, delays due to external processes may delay the issuing of a Security Advisory. diff --git a/ant/bc+-build.xml b/ant/bc+-build.xml index 8b6f7364d8..e931caeb5f 100644 --- a/ant/bc+-build.xml +++ b/ant/bc+-build.xml @@ -302,6 +302,7 @@ + @@ -360,14 +361,27 @@ + + + + + - + + + + + + + + + @@ -754,14 +768,27 @@ + + + + + - + + + + + + + + + @@ -860,7 +887,10 @@ - + + + + @@ -983,7 +1013,7 @@ - + diff --git a/ant/build.regexp b/ant/build.regexp index 8e11b2439c..7179075eaa 100644 --- a/ant/build.regexp +++ b/ant/build.regexp @@ -1,3 +1,3 @@ -regexp: >|>|]*>>|<[A-Z?][^>@]*[a-zA-Z0-9\\]]>|<[A-Z]>|<[a-z][^>@]*[a-z\\]]>|@SuppressWarnings(.*)|@Override|@Deprecated|@FunctionalInterface +regexp: >|>|]*\\>>|<[A-Z?][^>@]*[a-zA-Z0-9\\]]>|<[A-Z]>|<[a-z][^>@]*[a-z\\]]>|@SuppressWarnings(.*)|@Override|@Deprecated|@FunctionalInterface diff --git a/ant/jdk13.xml b/ant/jdk13.xml index 74ad1e18b5..f410102f0b 100644 --- a/ant/jdk13.xml +++ b/ant/jdk13.xml @@ -13,6 +13,7 @@ + @@ -55,6 +56,7 @@ + @@ -89,6 +91,7 @@ + @@ -248,6 +251,7 @@ + @@ -328,19 +332,29 @@ - + + + + + + + + + + + diff --git a/ant/jdk14.xml b/ant/jdk14.xml index 32916cc908..8c401848dd 100644 --- a/ant/jdk14.xml +++ b/ant/jdk14.xml @@ -12,6 +12,7 @@ + @@ -30,7 +31,7 @@ - + @@ -40,10 +41,14 @@ + + + + @@ -77,6 +82,7 @@ + @@ -130,7 +136,14 @@ + + + + + + + @@ -142,14 +155,17 @@ + + + @@ -189,8 +205,6 @@ - - @@ -206,7 +220,10 @@ - + + + + @@ -224,6 +241,13 @@ + + + + + + + @@ -232,6 +256,7 @@ + diff --git a/ant/jdk15+.xml b/ant/jdk15+.xml index 148824d5ba..00be081a3d 100644 --- a/ant/jdk15+.xml +++ b/ant/jdk15+.xml @@ -10,6 +10,8 @@ + + @@ -39,14 +41,10 @@ - - - - @@ -54,7 +52,6 @@ - @@ -74,6 +71,17 @@ + + + + + + + + + + + diff --git a/ant/jdk18+.xml b/ant/jdk18+.xml index 66e194ad90..f099672565 100644 --- a/ant/jdk18+.xml +++ b/ant/jdk18+.xml @@ -10,6 +10,7 @@ + @@ -42,7 +43,6 @@ - diff --git a/bc-build.properties b/bc-build.properties index 8ab1b536ea..eeb835d760 100644 --- a/bc-build.properties +++ b/bc-build.properties @@ -3,10 +3,10 @@ # intended to hold user-specific settings that are *not* committed to # the repository. -release.suffix: 17801 -release.name: 1.78.1 -release.version: 1.78.1 -release.debug: true +release.suffix: 1.81 +release.name: 1.81 +release.version: 1.81 +release.debug: false mail.jar.home: ./libs/javax.mail-1.4.7.jar activation.jar.home: ./libs/activation-1.1.1.jar diff --git a/bc_maven_public_key.asc b/bc_maven_public_key.asc new file mode 100644 index 0000000000..a351409392 --- /dev/null +++ b/bc_maven_public_key.asc @@ -0,0 +1,25 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQGNBGR/8HUBDADJ+V5VgTXFG4xVI/1r07a/pTXoAQhHyJMkVdFScGARsps07VXI +IsYgPsifOFU55E7uRMZPTLAx5F1uxoZAWGtXIz0d4ISKhobFquH8jZe7TnsJBJNV +eo3u7G54iSfLifiJ4q17NvaESBNSirPaAPfEni93+gQvdn3zVnDPfO+mhO00l/fE +5GnqHt/Q2z2WKVQt3Vg0R66phe2XaFnycY/d+an73FiXqhuhm4sXlcA++gfSt1H1 +K7+ApqJsX9yw79A1FlGTPOeimqZqE75+OyQ9Kz0XTvN/GmHeEygTrNEnMDTr1BWz +P0/ut0UXmktJtJXgLi5wUCncwwi+UpCSwwou7/3r+eBh5aykxSo9OtYe4xPNKWSo +EiPZXpCH5Wjq9TpXOuhnZvRFqbR24mWz5+J/DoaVP3pwEhGXxr5VjVc1f8gJ8A34 +YYPlxUGcl8f3kykzvl4X5HDIbHb9MAl+9qtwQo1tFA9umD2Da/8bSsxrnZdkkzEA +OpJYwT1EkQRZRcUAEQEAAbRmVGhlIExlZ2lvbiBvZiB0aGUgQm91bmN5IENhc3Rs +ZSBJbmMuIChNYXZlbiBSZXBvc2l0b3J5IEFydGlmYWN0IFNpZ25lcikgPGJjbWF2 +ZW5zeW5jQGJvdW5jeWNhc3RsZS5vcmc+iQHUBBMBCgA+FiEEexIbdqftbObmCtUX +hOkTqOOnSMAFAmR/8HUCGwMFCQlmAYAFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AA +CgkQhOkTqOOnSMCTYgv/c9RSHcO056c7G3mH94eTqCMNSzhaiVIMKPgRwro10vpu +hOLdRfwkxe9nsa9tDGiv64sqUZADfnPxNP6mSE4la+fucwn5j1KxIicQt11zRO/e +Ep2vqBZoq60D9p23foDi4/XGuKtnwYQxyaLrvkFaAUpKYzCr7aU1ftqFfE+lKyYB +poQtib1PNqltKs/dX0IHACOeYbZ+j4YZnd6Qsl1XhDtVAYzIW60A3nDwDjOWTNaQ +2W0qX4xrG5XetqnhQj+nwGtkJFXJj7FF1QkIcWiwkAQZTxZk3F0hxlNrZY2rq9BE +nbmwMMCk8S/nn9gBeGriom2StkZC+1Bv/w7BS5fWUW9YzJ5803RVkOd+8Taeu2yn +XUvPNfvijmRO1doTXl7uE5fXAxFmG0+09W5sLVf0KBtdrQ1jzFUZas5iPQiXDNTF +aD3d7kQH7divX3PoZIbq1aaiI2yVI8k5MCYjQPQJbDiBGZumxgkm8J5ooOYVkR9F +dETovzOLJ8QqCzo41kBp +=gIeQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/bnd.sh b/bnd.sh new file mode 100755 index 0000000000..13183653a9 --- /dev/null +++ b/bnd.sh @@ -0,0 +1,46 @@ +#!/bin/sh + +JAVA_HOME=/opt/jdk1.5.0 +export JAVA_HOME + +PATH=$JAVA_HOME/bin:$PATH +export PATH + +for jarFile in $* +do + base=`basename $jarFile .jar` + javaVersion=`echo $base | sed -e "s/.*\(jdk..\).*/\\1/"` + name=`echo $base | sed -e "s/\([^-]*\)-jdk.*/\\1/"` + bcVersion=`echo $base | sed -e "s/$name-${javaVersion}.*-\(1.*\)/\\1/" | sed -e "s/b/.0./"` + baseVersion=`echo $bcVersion | sed -e "s/[^.]*.\([0-9]*\).*/\\1/"` + bcMaxVersion="`expr "${baseVersion}" "+" "1"`" + + if [ "`echo $bcVersion | fgrep b`" = "$bcVersion" ] + then + bcVersion=`echo $bcVersion | sed -e "s/50b/49./"` + fi + + if `echo $jarFile | fgrep bcprov > /dev/null` + then + cat > /tmp/bnd.props <<% +Bundle-Version: $bcVersion +Bundle-Name: $name +Bundle-SymbolicName: $name +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.bouncycastle.*;version=$bcVersion +Import-Package: *;resolution:=optional +% + else + cat > /tmp/bnd.props <<% +Bundle-Version: $bcVersion +Bundle-Name: $name +Bundle-SymbolicName: $name +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.bouncycastle.*;version=$bcVersion +Import-Package: org.bouncycastle.*;version="[${bcVersion},1.${bcMaxVersion})",*;resolution:=optional +% + fi + + java -jar $BND_HOME/biz.aQute.bnd-2.2.0.jar wrap --properties /tmp/bnd.props $jarFile + mv $base.jar $jarFile +done diff --git a/build.gradle b/build.gradle index bf4dd6d118..8aa5746fb8 100644 --- a/build.gradle +++ b/build.gradle @@ -7,19 +7,21 @@ buildscript { } + plugins { id "io.spring.nohttp" version "0.0.11" id "checkstyle" id "jacoco" id "net.ltgt.errorprone" version "3.1.0" + id 'maven-publish' } println("Environment setup:") -["BC_JDK8", "BC_JDK11", "BC_JDK17", "BC_JDK21"].each({ it -> +["BC_JDK8", "BC_JDK11", "BC_JDK17"].each({ it -> println("Looking for JDK ENV '${it}' found ${System.getenv(it)}"); - if (System.getenv(it) == null) { - throw new RuntimeException("Looking for JDK ENV '${it}' but found null, see README 'Environmental variables'"); - } +// if (System.getenv(it) == null) { +// throw new RuntimeException("Looking for JDK ENV '${it}' but found null, see README 'Environmental variables'"); +// } }) @@ -31,6 +33,22 @@ if (JavaVersion.current().isJava8Compatible()) { } } +def String deriveOSGIVersion(String prjVersion) { + if (prjVersion.contains("-SNAPSHOT")) { + // Snapshots always extend to fourth level and terminate with time in seconds since epoch. + prjVersion = prjVersion.replace("-SNAPSHOT", ""); + while (prjVersion.count(".") < 2) { + prjVersion = prjVersion + ".0"; + } + prjVersion = prjVersion + "." + System.currentTimeMillis().intdiv(1000L).intdiv(60).intdiv(60).intdiv(24); + } + return prjVersion +} + +ext { + bundle_version = deriveOSGIVersion(version.toString()); +} + // this needs to go here, otherwise it can't find config apply plugin: 'io.spring.nohttp' @@ -46,7 +64,6 @@ allprojects { mavenCentral() } - dependencies { testImplementation group: 'junit', name: 'junit', version: '4.13.2' } @@ -145,6 +162,7 @@ allprojects { } } + } task printProperties { @@ -163,24 +181,26 @@ ext { ext.vmrange = 'jdk18on' } - bc_prov = "${rootProject.projectDir}/prov/build/libs/bcprov-${vmrange}-${version}.jar" - bc_util = "${rootProject.projectDir}/util/build/libs/bcutil-${vmrange}-${version}.jar" - bc_pkix = "${rootProject.projectDir}/pkix/build/libs/bcpkix-${vmrange}-${version}.jar" - } - subprojects { apply plugin: 'eclipse' + apply plugin: 'maven-publish' + JavaVersion current = JavaVersion.current(); + int releaseVersion = 8; if (current.compareTo(JavaVersion.VERSION_1_8) <= 0) { - sourceCompatibility = 1.5 - targetCompatibility = 1.5 - } else { - sourceCompatibility = 1.8 - targetCompatibility = 1.8 + releaseVersion = 5 + } + + compileJava { + options.release = releaseVersion; + } + + compileTestJava { + options.release = 8; } @@ -204,11 +224,9 @@ subprojects { maxParallelForks = 1; systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false - javaLauncher = javaToolchains.launcherFor { - languageVersion = JavaLanguageVersion.of(8) - } + jvmArgs = ['-Dtest.java.version.prefix=any'] finalizedBy jacocoTestReport @@ -221,6 +239,7 @@ subprojects { } + dependencies { checkstyle files("$rootDir/config/checkstyle/lib/methodchecker-1.0.0.jar") checkstyle 'com.puppycrawl.tools:checkstyle:9.0' @@ -234,6 +253,16 @@ subprojects { } nohttp { + source.exclude '**/*.asc' + source.exclude '**/*.class' + source.exclude '**/*.crt' + source.exclude '**/*.crl' + source.exclude '**/*.eml' + source.exclude '**/*.gpg' + source.exclude '**/*.jar' + source.exclude '**/*.message' + source.exclude '**/*.pem' + source.exclude '**/*.*pub' source.exclude '**/*.rsp' } @@ -246,7 +275,7 @@ subprojects { } tasks.withType(JavaCompile).configureEach { - options.debug = false; + options.debug = true; } tasks.withType(Test).configureEach { @@ -254,6 +283,18 @@ subprojects { junitXml.outputLocation = layout.buildDirectory.dir("test-results") } } + +// tasks.withType(JavaCompile).configureEach { +// javaCompiler = javaToolchains.compilerFor { +// languageVersion = JavaLanguageVersion.of(21) +// } +// } + } -test.dependsOn([':core:test', ':prov:test', ':prov:test11', ':prov:test17', ':prov:test21', ':pkix:test', 'pg:test', ':tls:test', 'mls:test', 'mail:test', 'jmail:test']) + +test.dependsOn([':core:test', ':prov:test', ':prov:test11', ':prov:test15', ':prov:test21', ':pkix:test', 'pg:test', ':tls:test', 'mls:test', 'mail:test', 'jmail:test']) + + + + diff --git a/build1-1 b/build1-1 index 1106236e2e..6b023551fa 100644 --- a/build1-1 +++ b/build1-1 @@ -9,7 +9,7 @@ JDK11PATH=/opt/jdk1.1.8 # JDK 1.1 location base=$1 -version=`echo $base | sed -e "s/\([0-9]\)\([0-9a-z]*\)/\1.\2/"` +version=`echo $base | sed -e "s/\([0-9]\).\([0-9a-z]*\)/\1.\2/"` WINDOWTITLE="Bouncy Castle Cryptography $version API Specification" HEADER="Bouncy Castle Cryptography $version" @@ -48,6 +48,7 @@ mkdir -p $jdk11src ((cd pg/src/main/jdk1.5 && tar cf - * ) | (cd $jdk11src && tar xf -)) ((cd pg/src/main/jdk1.4 && tar cf - * ) | (cd $jdk11src && tar xf -)) ((cd pg/src/main/jdk1.3 && tar cf - * ) | (cd $jdk11src && tar xf -)) +((cd pg/src/main/jdk1.2 && tar cf - * ) | (cd $jdk11src && tar xf -)) ((cd pg/src/main/jdk1.1 && tar cf - * ) | (cd $jdk11src && tar xf -)) ((cd pkix/src/main/jdk1.4 && tar cf - * ) | (cd $jdk11src && tar xf -)) ((cd pkix/src/test/jdk1.4 && tar cf - * ) | (cd $jdk11src && tar xf -)) @@ -75,11 +76,8 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm -rf org/bouncycastle/math/ec/rfc8032/test rm -rf org/bouncycastle/crypto/test/ntru rm -rf org/bouncycastle/pqc/crypto/lms - rm -rf org/bouncycastle/pqc/jcajce/provider/lms - rm -rf org/bouncycastle/pqc/jcajce/provider/LMS* + rm -rf org/bouncycastle/pqc/jcajce rm -rf org/bouncycastle/pqc/crypto/*/LMS* - rm org/bouncycastle/pqc/jcajce/spec/LMS* - rm org/bouncycastle/pqc/jcajce/*/Rainbow* rm -rf org/bouncycastle/pqc/crypto/*/HSS* rm -rf org/bouncycastle/pqc/math/ntru rm -rf org/bouncycastle/pqc/crypto/ntru @@ -177,6 +175,7 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm org/bouncycastle/asn1/test/ASN1SequenceParserTest.java rm org/bouncycastle/asn1/cms/test/OctetStringTest.java rm org/bouncycastle/asn1/cms/test/ParseTest.java + rm org/bouncycastle/asn1/cms/test/KEMRecipientInfoTest.java rm org/bouncycastle/asn1/cmc/test/CMCFailInfoTest.java rm org/bouncycastle/asn1/cmc/test/CMCStatusTest.java rm org/bouncycastle/asn1/test/ASN1IntegerTest.java @@ -186,7 +185,6 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm -rf org/bouncycastle/jcajce/provider/asymmetric/util/EC5*.java rm -rf org/bouncycastle/jcajce/provider/drbg rm org/bouncycastle/asn1/test/EnumeratedTest.java - rm -rf org/bouncycastle/pqc/jcajce rm -rf org/bouncycastle/pqc/crypto/qtesla/QTeslaKeyEncodingTests.java rm -r org/bouncycastle/crypto/test/speedy rm -r org/bouncycastle/crypto/test/cavp @@ -243,6 +241,7 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm org/bouncycastle/pqc/crypto/test/XWingTest.java rm org/bouncycastle/cert/test/GOSTR3410_2012_256GenerateCertificate.java rm org/bouncycastle/cert/cmp/test/InvalidMessagesTest.java + rm org/bouncycastle/cert/cmp/test/TestUtils.java rm org/bouncycastle/test/JVMVersionTest.java rm org/bouncycastle/cms/jcajce/JceAADStream.java rm org/bouncycastle/cms/jcajce/JceCMSKEM*.java @@ -261,6 +260,9 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm -rf org/bouncycastle/pqc/crypto/test/BIKE* rm -rf org/bouncycastle/pqc/crypto/test/Rainbow* rm -rf org/bouncycastle/pqc/crypto/test/GeMSS* + rm -rf org/bouncycastle/pqc/crypto/test/MLKEM* + rm -rf org/bouncycastle/pqc/crypto/test/MLDSA* + rm -rf org/bouncycastle/pqc/crypto/test/SLHDSA* rm -rf org/bouncycastle/pqc/crypto/*/SIKE* rm -rf org/bouncycastle/pqc/crypto/sike rm -rf org/bouncycastle/pqc/legacy/crypto/sike @@ -277,7 +279,9 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm org/bouncycastle/pkix/jcajce/PKIXCRLUtil.java rm -r org/bouncycastle/pkix/util rm -rf org/bouncycastle/pkix/test/Revocation* + rm -rf org/bouncycastle/pkix/test/CheckNameConstraintsTest* rm -rf org/bouncycastle/pkix/test/TestUtil* + rm -rf org/bouncycastle/jce/provider/test/PKIXNameConstraintsTest.java rm org/bouncycastle/pkix/test/CheckerTest.java rm org/bouncycastle/cms/jcajce/JceKeyTransAuthEnvelopedRecipient.java rm -rf org/bouncycastle/mime/ @@ -299,6 +303,7 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm -rf org/bouncycastle/asn1/test/CMCFailInfoTest.java rm -rf org/bouncycastle/asn1/test/CMCStatusTest.java rm -rf org/bouncycastle/jce/provider/test/SM2SignatureTest.java + rm -f org/bouncycastle/jcajce/provider/asymmetric/COMPOSITE.java rm -f org/bouncycastle/jcajce/provider/drbg/EntropyGatherer.java rm -f org/bouncycastle/jcajce/provider/drbg/EntropyDaemon.java rm -f org/bouncycastle/jcajce/provider/asymmetric/Dilithium.java @@ -311,6 +316,7 @@ find $jdk11src -name "*.java" -exec scripts/useseccert.sh \{\} \; rm -f org/bouncycastle/openpgp/test/BcpgGeneralTest.java rm -f org/bouncycastle/openpgp/test/OpenPGPTest.java + sh ../../scripts/jdk1.2ed.sh > /dev/null 2>&1 sh ../../scripts/jdk1.1ed.sh > /dev/null 2>&1 @@ -397,7 +403,7 @@ then (cd src/java/; javac -d ../../classes -classpath ../../classes:../../src:$JDK11PATH/lib/classes.zip */*.java) (cd src/org/bouncycastle; javac -J-mx768m -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip *.java ; javac -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip */*.java; javac -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip */p*/*.java -javac -J-mx768m -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip */a*/*.java +javac -J-mx768m -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip */a*/*.java */util/*.java javac -J-mx768m -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip */d*/*.java javac -J-mx768m -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip a*/e*/*.java javac -J-mx768m -d ../../../classes -classpath ../../../classes:../../../src:$JDK11PATH/lib/classes.zip c*/e*/*.java @@ -448,10 +454,42 @@ then mkdir $artifacts/jce-jdk11-$base mkdir $artifacts/jce-jdk11-$base/src tar cf - index.html LICENSE.html CONTRIBUTORS.html docs | (cd $artifacts/jce-jdk11-$base; tar xf -) + mkdir -p $jdk11src/org/bouncycastle/pqc/jcajce/provider/util + cp prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java $jdk11src/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java + cp prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/KeyUtil.java $jdk11src/org/bouncycastle/pqc/jcajce/provider/util/KeyUtil.java + cp prov/src/main/jdk1.1/org/bouncycastle/pqc/jcajce/provider/util/SpecUtil.java $jdk11src/org/bouncycastle/pqc/jcajce/provider/util/SpecUtil.java + cp prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/WrapUtil.java $jdk11src/org/bouncycastle/pqc/jcajce/provider/util/WrapUtil.java + cp prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/KdfUtil.java $jdk11src/org/bouncycastle/pqc/jcajce/provider/util/KdfUtil.java + ed $jdk11src/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java <<%% +g//s///g +w +q +%% + ed $jdk11src/org/bouncycastle/jcajce/provider/asymmetric/util/BaseDeterministicOrRandom*.java <<%% +1 +/private final/ +a + protected SecureRandom appRandom = null; +. +w +q +g//s///g +w +q +%% + for i in $jdk11src/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/*.java $jdk11src/org/bouncycastle/jcajce/provider/asymmetric/mldsa/*.java $jdk11src/org/bouncycastle/jcajce/provider/asymmetric/mlkem/*.java + do + ed $i <<%% +g/final /s/// +w +q +%% + done (cd $jdk11src && tar cf - java javax org/bouncycastle/LICENSE.java \ org/bouncycastle/test org/bouncycastle/math org/bouncycastle/internal org/bouncycastle/crypto org/bouncycastle/util org/bouncycastle/asn1 org/bouncycastle/pqc/math org/bouncycastle/pqc org/bouncycastle/jce org/bouncycastle/jcajce org/bouncycastle/x509 ) \ | (cd $artifacts/jce-jdk11-$base/src && tar xf -) + ( cd $artifacts/jce-jdk11-$base; mkdir classes; mkdir javadoc; @@ -690,6 +728,7 @@ then rm -rf src/org/bouncycastle/asn1/*/test rm -rf src/org/bouncycastle/gpg/keybox rm -rf src/org/bouncycastle/gpg/test + rm -rf src/org/bouncycastle/bcpg/test/SignatureSubpacketsTest.java rm -f src/org/bouncycastle/openpgp/test/PGPCanonicalizedDataGeneratorTest.java rm -f src/org/bouncycastle/openpgp/test/DSA2Test.java rm -f src/org/bouncycastle/openpgp/test/PGPUnicodeTest.java @@ -704,6 +743,15 @@ then rm -f src/org/bouncycastle/openpgp/test/OpenPGPTest.java rm -f src/org/bouncycastle/openpgp/test/OperatorBcTest.java rm -f src/org/bouncycastle/openpgp/test/PGPGeneralTest.java + rm src/org/bouncycastle/openpgp/test/EdDSAKeyC*.java + rm src/org/bouncycastle/openpgp/test/ECDSAKeyPairTest.java + rm src/org/bouncycastle/openpgp/test/Legacy*KeyPairTest.java + rm src/org/bouncycastle/openpgp/test/Dedicated*KeyPairTest.java + rm src/org/bouncycastle/openpgp/test/AEADProtected*Test.java + rm src/org/bouncycastle/openpgp/test/*Argon2*.java + rm src/org/bouncycastle/openpgp/test/Curve*PrivateKeyEncoding*.java + rm src/org/bouncycastle/openpgp/test/OperatorJcajceTest.java + rm src/org/bouncycastle/openpgp/test/PGPPaddingTest.java find src -name AllTests.java -exec rm {} \; @@ -818,6 +866,20 @@ w q % + for i in src/org/bouncycastle/bcpg/UnknownPacket.java src/org/bouncycastle/bcpg/PacketFormat.java src/org/bouncycastle/bcpg/KeyIdentifier.java src/org/bouncycastle/bcpg/OnePassSignaturePacket.java +do +ed $i <<% +g/private.*final.*;/s/final// +w +q +% +done + + ed src/org/bouncycastle/bcpg/AEADEncDataPacket.java <<% +g/private.*final.*;/s/final// +w +q +% ed src/org/bouncycastle/openpgp/operator/bc/BcPublicKeyDataDecryptorFactory.java <<% g/private.*final.*;/s/final// w diff --git a/build1-2 b/build1-2 index 144b0d0a60..bec082be53 100644 --- a/build1-2 +++ b/build1-2 @@ -9,7 +9,7 @@ JDK12PATH=/opt/jdk1.2.2 # JDK 1.2 location base=$1 -version=`echo $base | sed -e "s/\([0-9]\)\([0-9a-z]*\)/\1.\2/"` +version=`echo $base | sed -e "s/\([0-9]\).\([0-9a-z]*\)/\1.\2/"` WINDOWTITLE="Bouncy Castle Cryptography $version API Specification" HEADER="Bouncy Castle Cryptography $version" @@ -50,6 +50,7 @@ mkdir -p $jdk12src ((cd pg/src/main/jdk1.5 && tar cf - * ) | (cd $jdk12src && tar xf -)) ((cd pg/src/main/jdk1.4 && tar cf - * ) | (cd $jdk12src && tar xf -)) ((cd pg/src/main/jdk1.3 && tar cf - * ) | (cd $jdk12src && tar xf -)) +((cd pg/src/main/jdk1.2 && tar cf - * ) | (cd $jdk12src && tar xf -)) ((cd pg/src/test/java && tar cf - * ) | (cd $jdk12src && tar xf -)) ((cd pg/src/test/jdk1.4 && tar cf - * ) | (cd $jdk12src && tar xf -)) ((cd pg/src/test/jdk1.3 && tar cf - * ) | (cd $jdk12src && tar xf -)) @@ -83,6 +84,7 @@ find $jdk12src -name "*.java" -exec scripts/usejcecert.sh \{\} \; rm -rf org/bouncycastle/pqc/jcajce/provider/XMSS* rm -rf org/bouncycastle/pqc/jcajce/provider/LMS* rm -rf org/bouncycastle/pqc/jcajce/provider/lms + rm -rf org/bouncycastle/jcajce/provider/asymmetric/COMPOSITE* rm -rf org/bouncycastle/pqc/crypto/*/XMSS* rm -rf org/bouncycastle/pqc/crypto/*/LMS* rm -rf org/bouncycastle/pqc/crypto/*/HSS* @@ -112,6 +114,7 @@ find $jdk12src -name "*.java" -exec scripts/usejcecert.sh \{\} \; rm org/bouncycastle/crypto/*/Blake2sp*.java rm org/bouncycastle/crypto/*/Blake2bp*.java rm org/bouncycastle/pkix/test/CheckerTest.java + rm org/bouncycastle/pkix/test/CheckNameConstraintsTest.java rm org/bouncycastle/crypto/test/RadixConverterTest.java rm org/bouncycastle/crypto/test/HPKETestVector*.java rm org/bouncycastle/pkix/jcajce/Revocation*.java @@ -207,6 +210,7 @@ find $jdk12src -name "*.java" -exec scripts/usejcecert.sh \{\} \; rm org/bouncycastle/cert/cmp/test/PQC*.java rm org/bouncycastle/cert/cmp/test/Elgamal*.java rm org/bouncycastle/cert/cmp/test/InvalidMessagesTest.java + rm org/bouncycastle/cert/cmp/test/TestUtils.java rm org/bouncycastle/cert/test/GOSTR3410_2012_256GenerateCertificate.java rm org/bouncycastle/cert/ocsp/test/PKIXRevocationTest.java rm -r org/bouncycastle/crypto/test/BigSkippingCipherTest.java @@ -248,6 +252,15 @@ find $jdk12src -name "*.java" -exec scripts/usejcecert.sh \{\} \; rm org/bouncycastle/openpgp/test/BcImplProviderTest.java rm org/bouncycastle/openpgp/test/BcpgGeneralTest.java rm org/bouncycastle/openpgp/test/OpenPGPTest.java + rm org/bouncycastle/openpgp/test/EdDSAKeyC*.java + rm org/bouncycastle/openpgp/test/ECDSAKeyPairTest.java + rm org/bouncycastle/openpgp/test/Legacy*KeyPairTest.java + rm org/bouncycastle/openpgp/test/Dedicated*KeyPairTest.java + rm org/bouncycastle/openpgp/test/AEADProtected*Test.java + rm org/bouncycastle/openpgp/test/*Argon2*.java + rm org/bouncycastle/openpgp/test/Curve*PrivateKeyEncoding*.java + rm org/bouncycastle/openpgp/test/OperatorJcajceTest.java + rm org/bouncycastle/openpgp/test/PGPPaddingTest.java sh ../../scripts/jdk1.2ed.sh diff --git a/ci/check_java.sh b/ci/check_java.sh index ff76046efa..7300ac561f 100644 --- a/ci/check_java.sh +++ b/ci/check_java.sh @@ -9,17 +9,18 @@ set -e cd /workspace/bc-java source ci/common.sh -export BC_JDK8=`openjdk_8` -export BC_JDK11=`openjdk_11` -export BC_JDK15=`openjdk_15` -export BC_JDK17=`openjdk_17` -export BC_JDK21=`openjdk_21` -export JAVA_HOME=`openjdk_17` + +export JAVA_HOME=`openjdk_21` export PATH=$JAVA_HOME/bin:$PATH -./gradlew check -x test; +# Checkstyle +./gradlew clean build check -x test; +# OSGI scanner only, no testing +./osgi_scan.sh +# module tester +./run_mtt.sh \ No newline at end of file diff --git a/ci/pub.sh b/ci/pub.sh new file mode 100644 index 0000000000..5241fe311e --- /dev/null +++ b/ci/pub.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +set -e + +# +# This script is for running inside the docker container +# + +cd /workspace/bc-java +source ci/common.sh + + + +export JAVA_HOME=`openjdk_21` +export PATH=$JAVA_HOME/bin:$PATH + +./gradlew clean build -x test +./osgi_scan.sh + +./gradlew publishAllPublicationsToCwmavenRepository -x test + + diff --git a/ci/test_11.sh b/ci/test.sh similarity index 77% rename from ci/test_11.sh rename to ci/test.sh index adc317b84d..c72b360ee7 100644 --- a/ci/test_11.sh +++ b/ci/test.sh @@ -15,10 +15,10 @@ export BC_JDK17=`openjdk_17` export BC_JDK21=`openjdk_21` -export JAVA_HOME=`openjdk_17` +export JAVA_HOME=`openjdk_21` export PATH=$JAVA_HOME/bin:$PATH -./gradlew -stacktrace clean build test11 -x test +./gradlew -stacktrace clean build diff --git a/ci/test_17.sh b/ci/test_17.sh deleted file mode 100644 index 7b411d8b1d..0000000000 --- a/ci/test_17.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -set -e - -# -# This script is for running inside the docker container -# - -cd /workspace/bc-java -source ci/common.sh - -export BC_JDK8=`openjdk_8` -export BC_JDK11=`openjdk_11` -export BC_JDK17=`openjdk_17` -export BC_JDK21=`openjdk_21` - - -export JAVA_HOME=`openjdk_17` -export PATH=$JAVA_HOME/bin:$PATH - -./gradlew -stacktrace clean build test17 -x test - - - - diff --git a/ci/test_21.sh b/ci/test_21.sh deleted file mode 100644 index afea144f79..0000000000 --- a/ci/test_21.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -set -e - -# -# This script is for running inside the docker container -# - -cd /workspace/bc-java -source ci/common.sh - -export BC_JDK8=`openjdk_8` -export BC_JDK11=`openjdk_11` -export BC_JDK17=`openjdk_17` -export BC_JDK21=`openjdk_21` - - -export JAVA_HOME=`openjdk_17` -export PATH=$JAVA_HOME/bin:$PATH - -./gradlew -stacktrace clean build test21 -x test - - - - diff --git a/ci/test_8.sh b/ci/test_8.sh deleted file mode 100644 index ee489af648..0000000000 --- a/ci/test_8.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -set -e - -# -# This script is for running inside the docker container -# - -cd /workspace/bc-java -source ci/common.sh - -export BC_JDK8=`openjdk_8` -export BC_JDK11=`openjdk_11` -export BC_JDK17=`openjdk_17` -export BC_JDK21=`openjdk_21` - - -export JAVA_HOME=`openjdk_17` -export PATH=$JAVA_HOME/bin:$PATH - -./gradlew -stacktrace clean build -x test11 test17 test21 - - - - diff --git a/config/nohttp/suppressions.xml b/config/nohttp/suppressions.xml index 2e7f160b17..3557f12607 100644 --- a/config/nohttp/suppressions.xml +++ b/config/nohttp/suppressions.xml @@ -8,7 +8,7 @@ - + @@ -19,6 +19,8 @@ + + diff --git a/core/build.gradle b/core/build.gradle index d3f9400fdb..2b1efd9e98 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -8,8 +8,25 @@ application { mainClass.set("org.bouncycastle.crypto.fpe.SP80038GMicroBenchmark") } +jar.archiveBaseName = "bccore-$vmrange" test { forkEvery = 1; maxParallelForks = 8; + jvmArgs = ['-Dtest.java.version.prefix=any'] +} + +compileJava { + options.release = 8 +} + + +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bccore-$vmrange" + from components.java + } + } } diff --git a/core/src/main/j2me/org/bouncycastle/math/ec/ECCurve.java b/core/src/main/j2me/org/bouncycastle/math/ec/ECCurve.java index 41e6cc796f..b580541a51 100644 --- a/core/src/main/j2me/org/bouncycastle/math/ec/ECCurve.java +++ b/core/src/main/j2me/org/bouncycastle/math/ec/ECCurve.java @@ -593,9 +593,14 @@ protected AbstractFp(BigInteger q) super(FiniteFields.getPrimeField(q)); } + public BigInteger getQ() + { + return getField().getCharacteristic(); + } + public boolean isValidFieldElement(BigInteger x) { - return x != null && x.signum() >= 0 && x.compareTo(this.getField().getCharacteristic()) < 0; + return x != null && x.signum() >= 0 && x.compareTo(this.getQ()) < 0; } public ECFieldElement randomFieldElement(SecureRandom r) @@ -604,7 +609,7 @@ public ECFieldElement randomFieldElement(SecureRandom r) * NOTE: BigInteger comparisons in the rejection sampling are not constant-time, so we * use the product of two independent elements to mitigate side-channels. */ - BigInteger p = this.getField().getCharacteristic(); + BigInteger p = this.getQ(); ECFieldElement fe1 = this.fromBigInteger(implRandomFieldElement(r, p)); ECFieldElement fe2 = this.fromBigInteger(implRandomFieldElement(r, p)); return fe1.multiply(fe2); @@ -616,7 +621,7 @@ public ECFieldElement randomFieldElementMult(SecureRandom r) * NOTE: BigInteger comparisons in the rejection sampling are not constant-time, so we * use the product of two independent elements to mitigate side-channels. */ - BigInteger p = this.getField().getCharacteristic(); + BigInteger p = this.getQ(); ECFieldElement fe1 = this.fromBigInteger(implRandomFieldElementMult(r, p)); ECFieldElement fe2 = this.fromBigInteger(implRandomFieldElementMult(r, p)); return fe1.multiply(fe2); @@ -699,12 +704,11 @@ public Fp(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger if (isInternal) { - this.q = q; knownQs.add(q); } else if (knownQs.contains(q) || validatedQs.contains(q)) { - this.q = q; + // No need to validate } else { @@ -724,10 +728,9 @@ else if (knownQs.contains(q) || validatedQs.contains(q)) } validatedQs.add(q); - - this.q = q; } + this.q = q; this.r = ECFieldElement.Fp.calculateResidue(q); this.infinity = new ECPoint.Fp(this, null, null); diff --git a/core/src/main/java/org/bouncycastle/asn1/ASN1BitString.java b/core/src/main/java/org/bouncycastle/asn1/ASN1BitString.java index aff52097a1..b5ada96794 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ASN1BitString.java +++ b/core/src/main/java/org/bouncycastle/asn1/ASN1BitString.java @@ -311,6 +311,16 @@ public byte[] getBytes() return rv; } + public int getBytesLength() + { + return contents.length - 1; + } + + public boolean isOctetAligned() + { + return getPadBits() == 0; + } + public int getPadBits() { return contents[0] & 0xFF; diff --git a/core/src/main/java/org/bouncycastle/asn1/ASN1ObjectIdentifier.java b/core/src/main/java/org/bouncycastle/asn1/ASN1ObjectIdentifier.java index 03f43333a4..61acea41af 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ASN1ObjectIdentifier.java +++ b/core/src/main/java/org/bouncycastle/asn1/ASN1ObjectIdentifier.java @@ -166,11 +166,29 @@ public ASN1ObjectIdentifier branch(String branchID) { ASN1RelativeOID.checkIdentifier(branchID); - byte[] branchContents = ASN1RelativeOID.parseIdentifier(branchID); - checkContentsLength(this.contents.length + branchContents.length); + byte[] contents; + if (branchID.length() <= 2) + { + checkContentsLength(this.contents.length + 1); + int subID = branchID.charAt(0) - '0'; + if (branchID.length() == 2) + { + subID *= 10; + subID += branchID.charAt(1) - '0'; + } + + contents = Arrays.append(this.contents, (byte)subID); + } + else + { + byte[] branchContents = ASN1RelativeOID.parseIdentifier(branchID); + checkContentsLength(this.contents.length + branchContents.length); + + contents = Arrays.concatenate(this.contents, branchContents); + } - byte[] contents = Arrays.concatenate(this.contents, branchContents); - String identifier = getId() + "." + branchID; + String rootID = getId(); + String identifier = rootID + "." + branchID; return new ASN1ObjectIdentifier(contents, identifier); } diff --git a/core/src/main/java/org/bouncycastle/asn1/ASN1RelativeOID.java b/core/src/main/java/org/bouncycastle/asn1/ASN1RelativeOID.java index ef494b4846..00f980508c 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ASN1RelativeOID.java +++ b/core/src/main/java/org/bouncycastle/asn1/ASN1RelativeOID.java @@ -7,6 +7,7 @@ import java.util.concurrent.ConcurrentMap; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Properties; public class ASN1RelativeOID extends ASN1Primitive @@ -122,11 +123,29 @@ public ASN1RelativeOID branch(String branchID) { checkIdentifier(branchID); - byte[] branchContents = parseIdentifier(branchID); - checkContentsLength(this.contents.length + branchContents.length); + byte[] contents; + if (branchID.length() <= 2) + { + checkContentsLength(this.contents.length + 1); + int subID = branchID.charAt(0) - '0'; + if (branchID.length() == 2) + { + subID *= 10; + subID += branchID.charAt(1) - '0'; + } + + contents = Arrays.append(this.contents, (byte)subID); + } + else + { + byte[] branchContents = parseIdentifier(branchID); + checkContentsLength(this.contents.length + branchContents.length); - byte[] contents = Arrays.concatenate(this.contents, branchContents); - String identifier = getId() + "." + branchID; + contents = Arrays.concatenate(this.contents, branchContents); + } + + String rootID = getId(); + String identifier = rootID + "." + branchID; return new ASN1RelativeOID(contents, identifier); } @@ -227,6 +246,11 @@ static ASN1RelativeOID createPrimitive(byte[] contents, boolean clone) static boolean isValidContents(byte[] contents) { + if (Properties.isOverrideSet("org.bouncycastle.asn1.allow_wrong_oid_enc")) + { + return true; + } + if (contents.length < 1) { return false; @@ -236,7 +260,9 @@ static boolean isValidContents(byte[] contents) for (int i = 0; i < contents.length; ++i) { if (subIDStart && (contents[i] & 0xff) == 0x80) + { return false; + } subIDStart = (contents[i] & 0x80) == 0; } @@ -282,7 +308,7 @@ else if ('0' <= ch && ch <= '9') static String parseContents(byte[] contents) { - StringBuffer objId = new StringBuffer(); + StringBuilder objId = new StringBuilder(); long value = 0; BigInteger bigValue = null; boolean first = true; diff --git a/core/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java b/core/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java index 99d680fff3..66c22ec9f3 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java +++ b/core/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java @@ -152,6 +152,25 @@ protected ASN1Sequence(ASN1Encodable element) this.elements = new ASN1Encodable[]{ element }; } + /** + * Create a SEQUENCE containing two objects. + * @param element1 the first object to be put in the SEQUENCE. + * @param element2 the second object to be put in the SEQUENCE. + */ + protected ASN1Sequence(ASN1Encodable element1, ASN1Encodable element2) + { + if (null == element1) + { + throw new NullPointerException("'element1' cannot be null"); + } + if (null == element2) + { + throw new NullPointerException("'element2' cannot be null"); + } + + this.elements = new ASN1Encodable[]{ element1, element2 }; + } + /** * Create a SEQUENCE containing a vector of objects. * @param elementVector the vector of objects to be put in the SEQUENCE. diff --git a/core/src/main/java/org/bouncycastle/asn1/ASN1TaggedObject.java b/core/src/main/java/org/bouncycastle/asn1/ASN1TaggedObject.java index 7a3cbc612a..d81c92bf8a 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ASN1TaggedObject.java +++ b/core/src/main/java/org/bouncycastle/asn1/ASN1TaggedObject.java @@ -75,6 +75,41 @@ public static ASN1TaggedObject getInstance(ASN1TaggedObject taggedObject, int ta return ASN1Util.getExplicitBaseTagged(checkInstance(taggedObject, declaredExplicit), tagClass, tagNo); } + public static ASN1TaggedObject getOptional(ASN1Object element) + { + if (element == null) + { + throw new NullPointerException("'element' cannot be null"); + } + + if (element instanceof ASN1TaggedObject) + { + return (ASN1TaggedObject)element; + } + + return null; + } + + public static ASN1TaggedObject getOptional(ASN1Object element, int tagClass) + { + ASN1TaggedObject taggedObject = getOptional(element); + if (taggedObject != null && taggedObject.hasTagClass(tagClass)) + { + return taggedObject; + } + return null; + } + + public static ASN1TaggedObject getOptional(ASN1Object element, int tagClass, int tagNo) + { + ASN1TaggedObject taggedObject = getOptional(element); + if (taggedObject != null && taggedObject.hasTag(tagClass, tagNo)) + { + return taggedObject; + } + return null; + } + private static ASN1TaggedObject checkInstance(Object obj) { if (obj == null) @@ -358,7 +393,7 @@ ASN1Primitive getBaseUniversal(boolean declaredExplicit, ASN1UniversalType unive { if (!isExplicit()) { - throw new IllegalStateException("object explicit - implicit expected."); + throw new IllegalStateException("object implicit - explicit expected."); } return universalType.checkedCast(obj.toASN1Primitive()); diff --git a/core/src/main/java/org/bouncycastle/asn1/ASN1Util.java b/core/src/main/java/org/bouncycastle/asn1/ASN1Util.java index 01c689ea54..78be766fa6 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ASN1Util.java +++ b/core/src/main/java/org/bouncycastle/asn1/ASN1Util.java @@ -68,6 +68,42 @@ static ASN1TaggedObjectParser checkTagClass(ASN1TaggedObjectParser taggedObjectP return taggedObjectParser; } + public static Object getInstanceChoiceBaseObject(ASN1TaggedObject taggedObject, boolean declaredExplicit, + String choiceName) + { + if (!declaredExplicit) + { + String message = "Implicit tagging cannot be used with untagged choice type " + choiceName + + " (X.680 30.6, 30.8)."; + + throw new IllegalArgumentException(message); + } + if (taggedObject == null) + { + throw new NullPointerException("'taggedObject' cannot be null"); + } + + return getExplicitContextBaseObject(taggedObject); + } + + public static Object getTaggedChoiceBaseObject(ASN1TaggedObject taggedObject, boolean declaredExplicit, + String choiceName) + { + if (!declaredExplicit) + { + String message = "Implicit tagging cannot be used with untagged choice type " + choiceName + + " (X.680 30.6, 30.8)."; + + throw new IllegalArgumentException(message); + } + if (taggedObject == null) + { + throw new NullPointerException("'taggedObject' cannot be null"); + } + + return taggedObject.getExplicitBaseObject(); + } + /* * Tag text methods @@ -138,16 +174,36 @@ public static String getTagText(int tagClass, int tagNo) * Wrappers for ASN1TaggedObject#getExplicitBaseObject */ + public static ASN1Object getExplicitBaseObject(ASN1TaggedObject taggedObject, int tagClass) + { + return checkTagClass(taggedObject, tagClass).getExplicitBaseObject(); + } + public static ASN1Object getExplicitBaseObject(ASN1TaggedObject taggedObject, int tagClass, int tagNo) { return checkTag(taggedObject, tagClass, tagNo).getExplicitBaseObject(); } + public static ASN1Object getExplicitContextBaseObject(ASN1TaggedObject taggedObject) + { + return getExplicitBaseObject(taggedObject, BERTags.CONTEXT_SPECIFIC); + } + public static ASN1Object getExplicitContextBaseObject(ASN1TaggedObject taggedObject, int tagNo) { return getExplicitBaseObject(taggedObject, BERTags.CONTEXT_SPECIFIC, tagNo); } + public static ASN1Object tryGetExplicitBaseObject(ASN1TaggedObject taggedObject, int tagClass) + { + if (!taggedObject.hasTagClass(tagClass)) + { + return null; + } + + return taggedObject.getExplicitBaseObject(); + } + public static ASN1Object tryGetExplicitBaseObject(ASN1TaggedObject taggedObject, int tagClass, int tagNo) { if (!taggedObject.hasTag(tagClass, tagNo)) @@ -158,6 +214,11 @@ public static ASN1Object tryGetExplicitBaseObject(ASN1TaggedObject taggedObject, return taggedObject.getExplicitBaseObject(); } + public static ASN1Object tryGetExplicitContextBaseObject(ASN1TaggedObject taggedObject) + { + return tryGetExplicitBaseObject(taggedObject, BERTags.CONTEXT_SPECIFIC); + } + public static ASN1Object tryGetExplicitContextBaseObject(ASN1TaggedObject taggedObject, int tagNo) { return tryGetExplicitBaseObject(taggedObject, BERTags.CONTEXT_SPECIFIC, tagNo); diff --git a/core/src/main/java/org/bouncycastle/asn1/BERSequence.java b/core/src/main/java/org/bouncycastle/asn1/BERSequence.java index b50f49382b..93d9783eb0 100644 --- a/core/src/main/java/org/bouncycastle/asn1/BERSequence.java +++ b/core/src/main/java/org/bouncycastle/asn1/BERSequence.java @@ -14,20 +14,31 @@ public class BERSequence extends ASN1Sequence { /** - * Create an empty sequence + * Create an empty sequence. */ public BERSequence() { } /** - * Create a sequence containing one object + * Create a sequence containing one object. + * @param element the object to go in the sequence. */ public BERSequence(ASN1Encodable element) { super(element); } + /** + * Create a sequence containing two objects. + * @param element1 the first object to go in the sequence. + * @param element2 the second object to go in the sequence. + */ + public BERSequence(ASN1Encodable element1, ASN1Encodable element2) + { + super(element1, element2); + } + /** * Create a sequence containing a vector of objects. */ diff --git a/core/src/main/java/org/bouncycastle/asn1/DERSequence.java b/core/src/main/java/org/bouncycastle/asn1/DERSequence.java index 9bffbb2639..515aff7246 100644 --- a/core/src/main/java/org/bouncycastle/asn1/DERSequence.java +++ b/core/src/main/java/org/bouncycastle/asn1/DERSequence.java @@ -19,14 +19,14 @@ public static DERSequence convert(ASN1Sequence seq) private int contentsLength = -1; /** - * Create an empty sequence + * Create an empty sequence. */ public DERSequence() { } /** - * Create a sequence containing one object + * Create a sequence containing one object. * @param element the object to go in the sequence. */ public DERSequence(ASN1Encodable element) @@ -34,6 +34,16 @@ public DERSequence(ASN1Encodable element) super(element); } + /** + * Create a sequence containing two objects. + * @param element1 the first object to go in the sequence. + * @param element2 the second object to go in the sequence. + */ + public DERSequence(ASN1Encodable element1, ASN1Encodable element2) + { + super(element1, element2); + } + /** * Create a sequence containing a vector of objects. * @param elementVector the vector of objects to make up the sequence. diff --git a/core/src/main/java/org/bouncycastle/asn1/DLSequence.java b/core/src/main/java/org/bouncycastle/asn1/DLSequence.java index 5cc4bb4f86..d510567733 100644 --- a/core/src/main/java/org/bouncycastle/asn1/DLSequence.java +++ b/core/src/main/java/org/bouncycastle/asn1/DLSequence.java @@ -11,14 +11,14 @@ public class DLSequence private int contentsLength = -1; /** - * Create an empty sequence + * Create an empty sequence. */ public DLSequence() { } /** - * create a sequence containing one object + * Create a sequence containing one object. * @param element the object to go in the sequence. */ public DLSequence(ASN1Encodable element) @@ -26,6 +26,16 @@ public DLSequence(ASN1Encodable element) super(element); } + /** + * Create a sequence containing two objects. + * @param element1 the first object to go in the sequence. + * @param element2 the second object to go in the sequence. + */ + public DLSequence(ASN1Encodable element1, ASN1Encodable element2) + { + super(element1, element2); + } + /** * create a sequence containing a vector of objects. * @param elementVector the vector of objects to make up the sequence. diff --git a/core/src/main/java/org/bouncycastle/asn1/anssi/package-info.java b/core/src/main/java/org/bouncycastle/asn1/anssi/package-info.java new file mode 100644 index 0000000000..ba0274111a --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/anssi/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for the French ANSSI EC curves. + */ +package org.bouncycastle.asn1.anssi; diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/BCObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/bc/BCObjectIdentifiers.java index 6c5db36169..cacf37ff0b 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/BCObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/BCObjectIdentifiers.java @@ -202,19 +202,63 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier sphincsPlus_interop = new ASN1ObjectIdentifier("1.3.9999.6"); + /** 1.3.9999.6.4.13 OQS_OID_SPHINCSSHA2128FSIMPLE */ ASN1ObjectIdentifier sphincsPlus_sha2_128f = new ASN1ObjectIdentifier("1.3.9999.6.4.13"); + /** 1.3.9999.6.4.16 OQS_OID_SPHINCSSHA2128SSIMPLE */ ASN1ObjectIdentifier sphincsPlus_sha2_128s = new ASN1ObjectIdentifier("1.3.9999.6.4.16"); + /** 1.3.9999.6.5.10 OQS_OID_SPHINCSSHA2192FSIMPLE */ ASN1ObjectIdentifier sphincsPlus_sha2_192f = new ASN1ObjectIdentifier("1.3.9999.6.5.10"); + /** 1.3.9999.6.5.12 OQS_OID_SPHINCSSHA2192SSIMPLE */ ASN1ObjectIdentifier sphincsPlus_sha2_192s = new ASN1ObjectIdentifier("1.3.9999.6.5.12"); + /** 1.3.9999.6.6.10 OQS_OID_SPHINCSSHA2256FSIMPLE */ ASN1ObjectIdentifier sphincsPlus_sha2_256f = new ASN1ObjectIdentifier("1.3.9999.6.6.10"); + /** 1.3.9999.6.6.12 OQS_OID_SPHINCSSHA2256SSIMPLE */ ASN1ObjectIdentifier sphincsPlus_sha2_256s = new ASN1ObjectIdentifier("1.3.9999.6.6.12"); + /** 1.3.9999.6.7.13 OQS_OID_SPHINCSSHAKE128FSIMPLE */ ASN1ObjectIdentifier sphincsPlus_shake_128f = new ASN1ObjectIdentifier("1.3.9999.6.7.13"); + /** 1.3.9999.6.7.16 OQS_OID_SPHINCSSHAKE128SSIMPLE */ ASN1ObjectIdentifier sphincsPlus_shake_128s = new ASN1ObjectIdentifier("1.3.9999.6.7.16"); + /** 1.3.9999.6.8.10 OQS_OID_SPHINCSSHAKE192FSIMPLE */ ASN1ObjectIdentifier sphincsPlus_shake_192f = new ASN1ObjectIdentifier("1.3.9999.6.8.10"); + /** 1.3.9999.6.8.12 OQS_OID_SPHINCSSHAKE192SSIMPLE */ ASN1ObjectIdentifier sphincsPlus_shake_192s = new ASN1ObjectIdentifier("1.3.9999.6.8.12"); + /** 1.3.9999.6.9.10 OQS_OID_SPHINCSSHAKE256FSIMPLE */ ASN1ObjectIdentifier sphincsPlus_shake_256f = new ASN1ObjectIdentifier("1.3.9999.6.9.10"); + /** 1.3.9999.6.9.12 OQS_OID_SPHINCSSHAKE256SSIMPLE */ ASN1ObjectIdentifier sphincsPlus_shake_256s = new ASN1ObjectIdentifier("1.3.9999.6.9.12"); + /** 1.3.9999.6.4.14 OQS_OID_P256_SPHINCSSHA2128FSIMPLE */ + ASN1ObjectIdentifier p256_sphincs_sha2_128f_simple = new ASN1ObjectIdentifier("1.3.9999.6.4.14"); + /** 1.3.9999.6.4.15 OQS_OID_RSA3072_SPHINCSSHA2128FSIMPLE */ + ASN1ObjectIdentifier rsa_3072_sphincs_sha2_128f_simple = new ASN1ObjectIdentifier("1.3.9999.6.4.15"); + /** 1.3.9999.6.4.17 OQS_OID_P256_SPHINCSSHA2128SSIMPLE */ + ASN1ObjectIdentifier p256_sphincs_sha2_128s_simple = new ASN1ObjectIdentifier("1.3.9999.6.4.17"); + /** 1.3.9999.6.4.18 OQS_OID_RSA3072_SPHINCSSHA2128SSIMPLE */ + ASN1ObjectIdentifier rsa_3072_sphincs_sha2_128s_simple = new ASN1ObjectIdentifier("1.3.9999.6.4.18"); + /** 1.3.9999.6.5.11 OQS_OID_P384_SPHINCSSHA2192FSIMPLE */ + ASN1ObjectIdentifier p384_sphincs_sha2_192f_simple = new ASN1ObjectIdentifier("1.3.9999.6.5.11"); + /** 1.3.9999.6.5.13 OQS_OID_P384_SPHINCSSHA2192SSIMPLE */ + ASN1ObjectIdentifier p384_sphincs_sha2192s_simple = new ASN1ObjectIdentifier("1.3.9999.6.5.13"); + /** 1.3.9999.6.6.11 OQS_OID_P521_SPHINCSSHA2256FSIMPLE */ + ASN1ObjectIdentifier p521_sphincs_sha2_256f_simple = new ASN1ObjectIdentifier("1.3.9999.6.6.11"); + /** 1.3.9999.6.6.13 OQS_OID_P521_SPHINCSSHA2256SSIMPLE */ + ASN1ObjectIdentifier p521_sphincs_sha2_256s_simple = new ASN1ObjectIdentifier("1.3.9999.6.6.13"); + /** 1.3.9999.6.7.14 OQS_OID_P256_SPHINCSSHAKE128FSIMPLE */ + ASN1ObjectIdentifier p256_sphincs_shake_128f_simple = new ASN1ObjectIdentifier("1.3.9999.6.7.14"); + /** 1.3.9999.6.7.15 OQS_OID_RSA3072_SPHINCSSHAKE128FSIMPLE */ + ASN1ObjectIdentifier rsa_3072_sphincs_shake_128f_simple = new ASN1ObjectIdentifier("1.3.9999.6.7.15"); + /** 1.3.9999.6.7.17 OQS_OID_P256_SPHINCSSHAKE128SSIMPLE */ + ASN1ObjectIdentifier p256_sphincs_shake_128s_simple = new ASN1ObjectIdentifier("1.3.9999.6.7.17"); + /** 1.3.9999.6.7.18 OQS_OID_RSA3072_SPHINCSSHAKE128SSIMPLE */ + ASN1ObjectIdentifier rsa_3072_sphincs_shake_128s_simple = new ASN1ObjectIdentifier("1.3.9999.6.7.18"); + /** 1.3.9999.6.8.11 OQS_OID_P384_SPHINCSSHAKE192FSIMPLE */ + ASN1ObjectIdentifier p384_sphincs_shake_192f_simple = new ASN1ObjectIdentifier("1.3.9999.6.8.11"); + /** 1.3.9999.6.8.13 OQS_OID_P384_SPHINCSSHAKE192SSIMPLE */ + ASN1ObjectIdentifier p384_sphincs_shake_192s_simple = new ASN1ObjectIdentifier("1.3.9999.6.8.13"); + /** 1.3.9999.6.9.11 OQS_OID_P521_SPHINCSSHAKE256FSIMPLE */ + ASN1ObjectIdentifier p521_sphincs_shake256f_simple = new ASN1ObjectIdentifier("1.3.9999.6.9.11"); + /** 1.3.9999.6.9.13 OQS_OID_P521_SPHINCSSHAKE256SSIMPLE */ + ASN1ObjectIdentifier p521_sphincs_shake256s_simple = new ASN1ObjectIdentifier("1.3.9999.6.9.13"); /** * Picnic @@ -237,18 +281,35 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier picnicl5full = picnic_key.branch("12"); ASN1ObjectIdentifier picnic_signature = picnic.branch("2"); + ASN1ObjectIdentifier picnic_with_sha512 = picnic_signature.branch("1"); ASN1ObjectIdentifier picnic_with_shake256 = picnic_signature.branch("2"); ASN1ObjectIdentifier picnic_with_sha3_512 = picnic_signature.branch("3"); - /* * Falcon */ ASN1ObjectIdentifier falcon = bc_sig.branch("7"); - - ASN1ObjectIdentifier falcon_512 = new ASN1ObjectIdentifier("1.3.9999.3.6"); // falcon.branch("1"); - ASN1ObjectIdentifier falcon_1024 = new ASN1ObjectIdentifier("1.3.9999.3.9"); // falcon.branch("2"); + /** 1.3.9999.3.11 OQS_OID_FALCON512 */ + ASN1ObjectIdentifier falcon_512 = new ASN1ObjectIdentifier("1.3.9999.3.11"); + /** 1.3.9999.3.12 OQS_OID_P256_FALCON512 */ + ASN1ObjectIdentifier p256_falcon_512 = new ASN1ObjectIdentifier("1.3.9999.3.12"); + /** 1.3.9999.3.13 OQS_OID_RSA3072_FALCON512 */ + ASN1ObjectIdentifier rsa_3072_falcon_512 = new ASN1ObjectIdentifier("1.3.9999.3.13"); + /** 1.3.9999.3.14 OQS_OID_FALCON1024 */ + ASN1ObjectIdentifier falcon_1024 = new ASN1ObjectIdentifier("1.3.9999.3.14"); + /** 1.3.9999.3.15 OQS_OID_P521_FALCON1024 */ + ASN1ObjectIdentifier p521_falcon1024 = new ASN1ObjectIdentifier("1.3.9999.3.15"); + /** 1.3.9999.3.16 OQS_OID_FALCONPADDED512 */ + ASN1ObjectIdentifier falcon_padded_512 = new ASN1ObjectIdentifier("1.3.9999.3.16"); + /** 1.3.9999.3.17 OQS_OID_P256_FALCONPADDED512 */ + ASN1ObjectIdentifier p256_falcon_padded512 = new ASN1ObjectIdentifier("1.3.9999.3.17"); + /** 1.3.9999.3.18 OQS_OID_RSA3072_FALCONPADDED512 */ + ASN1ObjectIdentifier rsa_3072_falconpadded512 = new ASN1ObjectIdentifier("1.3.9999.3.18"); + /** 1.3.9999.3.19 OQS_OID_FALCONPADDED1024 */ + ASN1ObjectIdentifier falcon_padded_1024 = new ASN1ObjectIdentifier("1.3.9999.3.19"); + /** 1.3.9999.3.20 OQS_OID_P521_FALCONPADDED1024 */ + ASN1ObjectIdentifier p521_falcon_padded_1024 = new ASN1ObjectIdentifier("1.3.9999.3.20"); /* * Dilithium @@ -263,6 +324,47 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier dilithium3_aes = new ASN1ObjectIdentifier("1.3.6.1.4.1.2.267.11.6.5"); // dilithium.branch("5"); ASN1ObjectIdentifier dilithium5_aes = new ASN1ObjectIdentifier("1.3.6.1.4.1.2.267.11.8.7"); // dilithium.branch("6"); + /* + * ML-DSA + */ + ///** 2.16.840.1.101.3.4.3.17 OQS_OID_MLDSA44 */ + /** 1.3.9999.7.5 OQS_OID_P256_MLDSA44 */ + ASN1ObjectIdentifier p256_mldsa44 = new ASN1ObjectIdentifier("1.3.9999.7.5"); + /** 1.3.9999.7.6 OQS_OID_RSA3072_MLDSA44 */ + ASN1ObjectIdentifier rsa3072_mldsa44 = new ASN1ObjectIdentifier("1.3.9999.7.6"); + /** 2.16.840.1.114027.80.8.1.1 OQS_OID_MLDSA44_pss2048 */ + ASN1ObjectIdentifier mldsa44_pss2048 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.1"); + /** 2.16.840.1.114027.80.8.1.2 OQS_OID_MLDSA44_rsa2048 */ + ASN1ObjectIdentifier mldsa44_rsa2048 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.2"); + /** 2.16.840.1.114027.80.8.1.3 OQS_OID_MLDSA44_ed25519 */ + ASN1ObjectIdentifier mldsa44_ed25519 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.3"); + /** 2.16.840.1.114027.80.8.1.4 OQS_OID_MLDSA44_p256 */ + ASN1ObjectIdentifier mldsa44_p256 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.4"); + /** 2.16.840.1.114027.80.8.1.5 OQS_OID_MLDSA44_bp256 */ + ASN1ObjectIdentifier mldsa44_bp256 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.5"); + ///** 2.16.840.1.101.3.4.3.18 OQS_OID_MLDSA65 */ + /** 1.3.9999.7.7 OQS_OID_P384_MLDSA65 */ + ASN1ObjectIdentifier p384_mldsa65 = new ASN1ObjectIdentifier("1.3.9999.7.7"); + /** 2.16.840.1.114027.80.8.1.6 OQS_OID_MLDSA65_pss3072 */ + ASN1ObjectIdentifier mldsa65_pss3072 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.6"); + /** 2.16.840.1.114027.80.8.1.7 OQS_OID_MLDSA65_rsa3072 */ + ASN1ObjectIdentifier mldsa65_rsa3072 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.7"); + /** 2.16.840.1.114027.80.8.1.8 OQS_OID_MLDSA65_p256 */ + ASN1ObjectIdentifier mldsa65_p256 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.8"); + /** 2.16.840.1.114027.80.8.1.9 OQS_OID_MLDSA65_bp256 */ + ASN1ObjectIdentifier mldsa65_bp256 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.9"); + /** 2.16.840.1.114027.80.8.1.10 OQS_OID_MLDSA65_ed25519 */ + ASN1ObjectIdentifier mldsa65_ed25519 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.10"); + ///** 2.16.840.1.101.3.4.3.19 OQS_OID_MLDSA87 */ + /** 1.3.9999.7.8 OQS_OID_P521_MLDSA87 */ + ASN1ObjectIdentifier p521_mldsa87 = new ASN1ObjectIdentifier("1.3.9999.7.8"); + /** 2.16.840.1.114027.80.8.1.11 OQS_OID_MLDSA87_p384 */ + ASN1ObjectIdentifier mldsa87_p384 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.11"); + /** 2.16.840.1.114027.80.8.1.12 OQS_OID_MLDSA87_bp384 */ + ASN1ObjectIdentifier mldsa87_bp384 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.12"); + /** 2.16.840.1.114027.80.8.1.13 OQS_OID_MLDSA87_ed448 */ + ASN1ObjectIdentifier mldsa87_ed448 = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1.13"); + /* * Rainbow */ @@ -316,7 +418,6 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier mceliece8192128_r3 = pqc_kem_mceliece.branch("9"); ASN1ObjectIdentifier mceliece8192128f_r3 = pqc_kem_mceliece.branch("10"); - /** * Frodo */ @@ -403,7 +504,7 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier ntrulpr953 = pqc_kem_ntrulprime.branch("4"); ASN1ObjectIdentifier ntrulpr1013 = pqc_kem_ntrulprime.branch("5"); ASN1ObjectIdentifier ntrulpr1277 = pqc_kem_ntrulprime.branch("6"); - + ASN1ObjectIdentifier pqc_kem_sntruprime = pqc_kem_ntruprime.branch("2"); ASN1ObjectIdentifier sntrup653 = pqc_kem_sntruprime.branch("1"); ASN1ObjectIdentifier sntrup761 = pqc_kem_sntruprime.branch("2"); @@ -411,7 +512,7 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier sntrup953 = pqc_kem_sntruprime.branch("4"); ASN1ObjectIdentifier sntrup1013 = pqc_kem_sntruprime.branch("5"); ASN1ObjectIdentifier sntrup1277 = pqc_kem_sntruprime.branch("6"); - + /** * BIKE **/ @@ -429,4 +530,166 @@ public interface BCObjectIdentifiers ASN1ObjectIdentifier hqc128 = pqc_kem_hqc.branch("1"); ASN1ObjectIdentifier hqc192 = pqc_kem_hqc.branch("2"); ASN1ObjectIdentifier hqc256 = pqc_kem_hqc.branch("3"); + + /** + * Mayo + */ + ASN1ObjectIdentifier mayo = bc_sig.branch("10"); + ASN1ObjectIdentifier mayo1 = mayo.branch("1"); + ASN1ObjectIdentifier mayo2 = mayo.branch("2"); + ASN1ObjectIdentifier mayo3 = mayo.branch("3"); + ASN1ObjectIdentifier mayo5 = mayo.branch("4"); + /** 1.3.9999.8.1.3 OQS_OID_MAYO1 */ + ASN1ObjectIdentifier mayo_1 = new ASN1ObjectIdentifier("1.3.9999.8.1.3"); + /** 1.3.9999.8.1.4 OQS_OID_P256_MAYO1 */ + ASN1ObjectIdentifier p256_mayo1 = new ASN1ObjectIdentifier("1.3.9999.8.1.4"); + /** 1.3.9999.8.2.3 OQS_OID_MAYO2 */ + ASN1ObjectIdentifier mayo_2 = new ASN1ObjectIdentifier("1.3.9999.8.2.3"); + /** 1.3.9999.8.2.4 OQS_OID_P256_MAYO2 */ + ASN1ObjectIdentifier p256_mayo2 = new ASN1ObjectIdentifier("1.3.9999.8.2.4"); + /** 1.3.9999.8.3.3 OQS_OID_MAYO3 */ + ASN1ObjectIdentifier mayo_3 = new ASN1ObjectIdentifier("1.3.9999.8.3.3"); + /** 1.3.9999.8.3.4 OQS_OID_P384_MAYO3 */ + ASN1ObjectIdentifier p384_mayo3 = new ASN1ObjectIdentifier("1.3.9999.8.3.4"); + /** 1.3.9999.8.5.3 OQS_OID_MAYO5 */ + ASN1ObjectIdentifier mayo_5 = new ASN1ObjectIdentifier("1.3.9999.8.5.3"); + /** 1.3.9999.8.5.4 OQS_OID_P521_MAYO5 */ + ASN1ObjectIdentifier p521_mayo5 = new ASN1ObjectIdentifier("1.3.9999.8.5.4"); + + /** + * cross + */ +// /** 1.3.6.1.4.1.62245.2.1.1.2 OQS_OID_CROSSRSDP128BALANCED */ +// ASN1ObjectIdentifier crossrsdp_128balanced = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.1.2"); +// /** 1.3.6.1.4.1.62245.2.1.2.2 OQS_OID_CROSSRSDP128FAST */ +// ASN1ObjectIdentifier crossrsdp_128fast = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.2.2"); +// /** 1.3.6.1.4.1.62245.2.1.3.2 OQS_OID_CROSSRSDP128SMALL */ +// ASN1ObjectIdentifier crossrsdp_128small = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.3.2"); +// /** 1.3.6.1.4.1.62245.2.1.4.2 OQS_OID_CROSSRSDP192BALANCED */ +// ASN1ObjectIdentifier crossrsdp_192balanced = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.4.2"); +// /** 1.3.6.1.4.1.62245.2.1.5.2 OQS_OID_CROSSRSDP192FAST */ +// ASN1ObjectIdentifier crossrsdp_192fast = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.5.2"); +// /** 1.3.6.1.4.1.62245.2.1.6.2 OQS_OID_CROSSRSDP192SMALL */ +// ASN1ObjectIdentifier crossrsdp_192small = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.6.2"); +// /** 1.3.6.1.4.1.62245.2.1.9.2 OQS_OID_CROSSRSDP256SMALL */ +// ASN1ObjectIdentifier crossrsdp256small = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.9.2"); +// /** 1.3.6.1.4.1.62245.2.1.10.2 OQS_OID_CROSSRSDPG128BALANCED */ +// ASN1ObjectIdentifier crossrsdpg_128balanced = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.10.2"); +// /** 1.3.6.1.4.1.62245.2.1.11.2 OQS_OID_CROSSRSDPG128FAST */ +// ASN1ObjectIdentifier crossrsdpg_128fast = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.11.2"); +// /** 1.3.6.1.4.1.62245.2.1.12.2 OQS_OID_CROSSRSDPG128SMALL */ +// ASN1ObjectIdentifier crossrsdpg_128small = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.12.2"); +// /** 1.3.6.1.4.1.62245.2.1.13.2 OQS_OID_CROSSRSDPG192BALANCED */ +// ASN1ObjectIdentifier crossrsdpg_192balanced = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.13.2"); +// /** 1.3.6.1.4.1.62245.2.1.14.2 OQS_OID_CROSSRSDPG192FAST */ +// ASN1ObjectIdentifier crossrsdpg_192fast = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.14.2"); +// /** 1.3.6.1.4.1.62245.2.1.15.2 OQS_OID_CROSSRSDPG192SMALL */ +// ASN1ObjectIdentifier crossrsdpg_192small = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.15.2"); +// /** 1.3.6.1.4.1.62245.2.1.16.2 OQS_OID_CROSSRSDPG256BALANCED */ +// ASN1ObjectIdentifier crossrsdpg_256balanced = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.16.2"); +// /** 1.3.6.1.4.1.62245.2.1.17.2 OQS_OID_CROSSRSDPG256FAST */ +// ASN1ObjectIdentifier crossrsdpg_256fast = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.17.2"); +// /** 1.3.6.1.4.1.62245.2.1.18.2 OQS_OID_CROSSRSDPG256SMALL */ +// ASN1ObjectIdentifier crossrsdpg_256small = new ASN1ObjectIdentifier("1.3.6.1.4.1.62245.2.1.18.2"); + + /** + * OV + * */ +// /** 1.3.9999.9.1.1 OQS_OID_OV_IS */ +// ASN1ObjectIdentifier ov_is = new ASN1ObjectIdentifier("1.3.9999.9.1.1"); +// /** 1.3.9999.9.1.2 OQS_OID_P256_OV_IS */ +// ASN1ObjectIdentifier p256_ov_is = new ASN1ObjectIdentifier("1.3.9999.9.1.2"); +// /** 1.3.9999.9.2.1 OQS_OID_OV_IP */ +// ASN1ObjectIdentifier ov_ip = new ASN1ObjectIdentifier("1.3.9999.9.2.1"); +// /** 1.3.9999.9.2.2 OQS_OID_P256_OV_IP */ +// ASN1ObjectIdentifier p256_ov_ip = new ASN1ObjectIdentifier("1.3.9999.9.2.2"); +// /** 1.3.9999.9.3.1 OQS_OID_OV_III */ +// ASN1ObjectIdentifier ov_iii = new ASN1ObjectIdentifier("1.3.9999.9.3.1"); +// /** 1.3.9999.9.3.2 OQS_OID_P384_OV_III */ +// ASN1ObjectIdentifier p384_ov_iii = new ASN1ObjectIdentifier("1.3.9999.9.3.2"); +// /** 1.3.9999.9.4.1 OQS_OID_OV_V */ +// ASN1ObjectIdentifier ov_v = new ASN1ObjectIdentifier("1.3.9999.9.4.1"); +// /** 1.3.9999.9.4.2 OQS_OID_P521_OV_V */ +// ASN1ObjectIdentifier p521_ov_v = new ASN1ObjectIdentifier("1.3.9999.9.4.2"); +// /** 1.3.9999.9.5.1 OQS_OID_OV_IS_PKC */ +// ASN1ObjectIdentifier ov_is_pkc = new ASN1ObjectIdentifier("1.3.9999.9.5.1"); +// /** 1.3.9999.9.5.2 OQS_OID_P256_OV_IS_PKC */ +// ASN1ObjectIdentifier p256_ov_is_pkc = new ASN1ObjectIdentifier("1.3.9999.9.5.2"); +// /** 1.3.9999.9.6.1 OQS_OID_OV_IP_PKC */ +// ASN1ObjectIdentifier ov_ip_pkc = new ASN1ObjectIdentifier("1.3.9999.9.6.1"); +// /** 1.3.9999.9.6.2 OQS_OID_P256_OV_IP_PKC */ +// ASN1ObjectIdentifier p256_ov_ip_pkc = new ASN1ObjectIdentifier("1.3.9999.9.6.2"); +// /** 1.3.9999.9.7.1 OQS_OID_OV_III_PKC */ +// ASN1ObjectIdentifier ov_iii_pkc = new ASN1ObjectIdentifier("1.3.9999.9.7.1"); +// /** 1.3.9999.9.7.2 OQS_OID_P384_OV_III_PKC */ +// ASN1ObjectIdentifier p384_ov_iii_pkc = new ASN1ObjectIdentifier("1.3.9999.9.7.2"); +// /** 1.3.9999.9.8.1 OQS_OID_OV_V_PKC */ +// ASN1ObjectIdentifier ov_v_pkc = new ASN1ObjectIdentifier("1.3.9999.9.8.1"); +// /** 1.3.9999.9.8.2 OQS_OID_P521_OV_V_PKC */ +// ASN1ObjectIdentifier p521_ov_v_pkc = new ASN1ObjectIdentifier("1.3.9999.9.8.2"); +// /** 1.3.9999.9.9.1 OQS_OID_OV_IS_PKC_SKC */ +// ASN1ObjectIdentifier ov_is_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.9.1"); +// /** 1.3.9999.9.9.2 OQS_OID_P256_OV_IS_PKC_SKC */ +// ASN1ObjectIdentifier p256_ov_is_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.9.2"); +// /** 1.3.9999.9.10.1 OQS_OID_OV_IP_PKC_SKC */ +// ASN1ObjectIdentifier ov_ip_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.10.1"); +// /** 1.3.9999.9.10.2 OQS_OID_P256_OV_IP_PKC_SKC */ +// ASN1ObjectIdentifier p256_ov_ip_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.10.2"); +// /** 1.3.9999.9.11.1 OQS_OID_OV_III_PKC_SKC */ +// ASN1ObjectIdentifier ov_iii_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.11.1"); +// /** 1.3.9999.9.11.2 OQS_OID_P384_OV_III_PKC_SKC */ +// ASN1ObjectIdentifier p384_ov_iii_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.11.2"); +// /** 1.3.9999.9.12.1 OQS_OID_OV_V_PKC_SKC */ +// ASN1ObjectIdentifier ov_v_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.12.1"); +// /** 1.3.9999.9.12.2 OQS_OID_P521_OV_V_PKC_SKC */ +// ASN1ObjectIdentifier p521_ov_v_pkc_skc = new ASN1ObjectIdentifier("1.3.9999.9.12.2"); + + /** + * Snova + */ + ASN1ObjectIdentifier snova = bc_sig.branch("11"); + ASN1ObjectIdentifier snova_24_5_4_ssk = snova.branch("1"); + ASN1ObjectIdentifier snova_24_5_4_esk = snova.branch("2"); + ASN1ObjectIdentifier snova_24_5_4_shake_ssk = snova.branch("3"); + ASN1ObjectIdentifier snova_24_5_4_shake_esk = snova.branch("4"); + ASN1ObjectIdentifier snova_24_5_5_ssk = snova.branch("5"); + ASN1ObjectIdentifier snova_24_5_5_esk = snova.branch("6"); + ASN1ObjectIdentifier snova_24_5_5_shake_ssk = snova.branch("7"); + ASN1ObjectIdentifier snova_24_5_5_shake_esk = snova.branch("8"); + ASN1ObjectIdentifier snova_25_8_3_ssk = snova.branch("9"); + ASN1ObjectIdentifier snova_25_8_3_esk = snova.branch("10"); + ASN1ObjectIdentifier snova_25_8_3_shake_ssk = snova.branch("11"); + ASN1ObjectIdentifier snova_25_8_3_shake_esk = snova.branch("12"); + ASN1ObjectIdentifier snova_29_6_5_ssk = snova.branch("13"); + ASN1ObjectIdentifier snova_29_6_5_esk = snova.branch("14"); + ASN1ObjectIdentifier snova_29_6_5_shake_ssk = snova.branch("15"); + ASN1ObjectIdentifier snova_29_6_5_shake_esk = snova.branch("16"); + ASN1ObjectIdentifier snova_37_8_4_ssk = snova.branch("17"); + ASN1ObjectIdentifier snova_37_8_4_esk = snova.branch("18"); + ASN1ObjectIdentifier snova_37_8_4_shake_ssk = snova.branch("19"); + ASN1ObjectIdentifier snova_37_8_4_shake_esk = snova.branch("20"); + ASN1ObjectIdentifier snova_37_17_2_ssk = snova.branch("21"); + ASN1ObjectIdentifier snova_37_17_2_esk = snova.branch("22"); + ASN1ObjectIdentifier snova_37_17_2_shake_ssk = snova.branch("23"); + ASN1ObjectIdentifier snova_37_17_2_shake_esk = snova.branch("24"); + ASN1ObjectIdentifier snova_49_11_3_ssk = snova.branch("25"); + ASN1ObjectIdentifier snova_49_11_3_esk = snova.branch("26"); + ASN1ObjectIdentifier snova_49_11_3_shake_ssk = snova.branch("27"); + ASN1ObjectIdentifier snova_49_11_3_shake_esk = snova.branch("28"); + ASN1ObjectIdentifier snova_56_25_2_ssk = snova.branch("29"); + ASN1ObjectIdentifier snova_56_25_2_esk = snova.branch("30"); + ASN1ObjectIdentifier snova_56_25_2_shake_ssk = snova.branch("31"); + ASN1ObjectIdentifier snova_56_25_2_shake_esk = snova.branch("32"); + ASN1ObjectIdentifier snova_60_10_4_ssk = snova.branch("33"); + ASN1ObjectIdentifier snova_60_10_4_esk = snova.branch("34"); + ASN1ObjectIdentifier snova_60_10_4_shake_ssk = snova.branch("35"); + ASN1ObjectIdentifier snova_60_10_4_shake_esk = snova.branch("36"); + ASN1ObjectIdentifier snova_66_15_3_ssk = snova.branch("37"); + ASN1ObjectIdentifier snova_66_15_3_esk = snova.branch("38"); + ASN1ObjectIdentifier snova_66_15_3_shake_ssk = snova.branch("39"); + ASN1ObjectIdentifier snova_66_15_3_shake_esk = snova.branch("40"); + ASN1ObjectIdentifier snova_75_33_2_ssk = snova.branch("41"); + ASN1ObjectIdentifier snova_75_33_2_esk = snova.branch("42"); + ASN1ObjectIdentifier snova_75_33_2_shake_ssk = snova.branch("43"); + ASN1ObjectIdentifier snova_75_33_2_shake_esk = snova.branch("44"); } diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedObjectStoreData.java b/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedObjectStoreData.java index 90a40e270b..3158a00b14 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedObjectStoreData.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedObjectStoreData.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.bc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; @@ -62,11 +61,6 @@ public AlgorithmIdentifier getEncryptionAlgorithm() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(encryptionAlgorithm); - v.add(encryptedContent); - - return new DERSequence(v); + return new DERSequence(encryptionAlgorithm, encryptedContent); } } \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedPrivateKeyData.java b/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedPrivateKeyData.java index fe96c11905..8b16dc4334 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedPrivateKeyData.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedPrivateKeyData.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.bc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -70,11 +69,6 @@ public EncryptedPrivateKeyInfo getEncryptedPrivateKeyInfo() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(encryptedPrivateKeyInfo); - v.add(new DERSequence(certificateChain)); - - return new DERSequence(v); + return new DERSequence(encryptedPrivateKeyInfo, new DERSequence(certificateChain)); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedSecretKeyData.java b/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedSecretKeyData.java index c56af7af79..f955d856b3 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedSecretKeyData.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/EncryptedSecretKeyData.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.bc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; @@ -63,11 +62,6 @@ public byte[] getEncryptedKeyData() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(keyEncryptionAlgorithm); - v.add(encryptedKeyData); - - return new DERSequence(v); + return new DERSequence(keyEncryptionAlgorithm, encryptedKeyData); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/LinkedCertificate.java b/core/src/main/java/org/bouncycastle/asn1/bc/LinkedCertificate.java index d812087700..8041fe78c9 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/LinkedCertificate.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/LinkedCertificate.java @@ -59,7 +59,7 @@ private LinkedCertificate(ASN1Sequence seq) switch (tagged.getTagNo()) { case 0: - certIssuer = X500Name.getInstance(tagged, false); + certIssuer = X500Name.getInstance(tagged, true); // CHOICE break; case 1: cACerts = GeneralNames.getInstance(tagged, false); @@ -114,7 +114,7 @@ public ASN1Primitive toASN1Primitive() if (certIssuer != null) { - v.add(new DERTaggedObject(false, 0, certIssuer)); + v.add(new DERTaggedObject(true, 0, certIssuer)); // CHOICE } if (cACerts != null) { diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/ObjectStore.java b/core/src/main/java/org/bouncycastle/asn1/bc/ObjectStore.java index dcae23d3de..40d4478f1f 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/ObjectStore.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/ObjectStore.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.bc; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -96,11 +95,6 @@ public ASN1Encodable getStoreData() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(storeData); - v.add(integrityCheck); - - return new DERSequence(v); + return new DERSequence(storeData, integrityCheck); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/SecretKeyData.java b/core/src/main/java/org/bouncycastle/asn1/bc/SecretKeyData.java index 4fe736465b..6a92749a12 100644 --- a/core/src/main/java/org/bouncycastle/asn1/bc/SecretKeyData.java +++ b/core/src/main/java/org/bouncycastle/asn1/bc/SecretKeyData.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.bc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; @@ -62,11 +61,6 @@ public ASN1ObjectIdentifier getKeyAlgorithm() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(keyAlgorithm); - v.add(keyBytes); - - return new DERSequence(v); + return new DERSequence(keyAlgorithm, keyBytes); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/bc/package-info.java b/core/src/main/java/org/bouncycastle/asn1/bc/package-info.java new file mode 100644 index 0000000000..10643e797c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/bc/package-info.java @@ -0,0 +1,4 @@ +/** + * ASN.1 classes specific to the Bouncy Castle APIs. + */ +package org.bouncycastle.asn1.bc; diff --git a/core/src/main/java/org/bouncycastle/asn1/cryptopro/GOST28147Parameters.java b/core/src/main/java/org/bouncycastle/asn1/cryptopro/GOST28147Parameters.java index 95e1e05670..09438d694a 100644 --- a/core/src/main/java/org/bouncycastle/asn1/cryptopro/GOST28147Parameters.java +++ b/core/src/main/java/org/bouncycastle/asn1/cryptopro/GOST28147Parameters.java @@ -2,7 +2,6 @@ import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; @@ -75,12 +74,7 @@ private GOST28147Parameters( */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(iv); - v.add(paramSet); - - return new DERSequence(v); + return new DERSequence(iv, paramSet); } /** diff --git a/core/src/main/java/org/bouncycastle/asn1/cryptopro/package-info.java b/core/src/main/java/org/bouncycastle/asn1/cryptopro/package-info.java new file mode 100644 index 0000000000..f141542c2d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/cryptopro/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for CRYPTO-PRO related objects - such as GOST identifiers. + */ +package org.bouncycastle.asn1.cryptopro; diff --git a/core/src/main/java/org/bouncycastle/asn1/gm/GMObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/gm/GMObjectIdentifiers.java index d0df5a9359..fa3048a5dc 100644 --- a/core/src/main/java/org/bouncycastle/asn1/gm/GMObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/gm/GMObjectIdentifiers.java @@ -49,15 +49,15 @@ public interface GMObjectIdentifiers ASN1ObjectIdentifier sm2encrypt = sm_scheme.branch("301.3"); /** - * - * http://c.gb688.cn/bzgk/gb/showGb?type=online&hcno=252CF0F72A7BE339A56DEA7D774E8994, + * <Information security technology — Cryptographic application identifier criterion specification> + * <url>http://c.gb688.cn/bzgk/gb/showGb?type=online&hcno=252CF0F72A7BE339A56DEA7D774E8994</url>, * Page 21 only cover from 301.1 to 301.3 * */ ASN1ObjectIdentifier wapip192v1 = sm_scheme.branch("301.101"); /** - * - * http://www.chinabwips.org.cn/zqyjgs1.htm and - * http://www.chinabwips.org.cn/doc/101.pdf, + * <WAPI certificate management—Part 5: Example of certificate format (draft)> + * <url>http://www.chinabwips.org.cn/zqyjgs1.htm</url> and + * <url>http://www.chinabwips.org.cn/doc/101.pdf</url>, * Page 9 and page 10 states the OID of ECDSA-192 algorithm based on SHA-256 is 1.2.156.11235.1.1.1 * */ ASN1ObjectIdentifier wapi192v1 = new ASN1ObjectIdentifier("1.2.156.11235.1.1.1"); diff --git a/core/src/main/java/org/bouncycastle/asn1/gm/package-info.java b/core/src/main/java/org/bouncycastle/asn1/gm/package-info.java new file mode 100644 index 0000000000..6e839c4d92 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/gm/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for Chinese Standard (GM) standard curves and algorithms. + */ +package org.bouncycastle.asn1.gm; diff --git a/core/src/main/java/org/bouncycastle/asn1/nist/NISTObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/nist/NISTObjectIdentifiers.java index 572f6f4400..fd23255053 100644 --- a/core/src/main/java/org/bouncycastle/asn1/nist/NISTObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/nist/NISTObjectIdentifiers.java @@ -58,7 +58,11 @@ public interface NISTObjectIdentifiers /** 2.16.840.1.101.3.4.2.19 */ static final ASN1ObjectIdentifier id_KmacWithSHAKE128 = hashAlgs.branch("19"); /** 2.16.840.1.101.3.4.2.20 */ - static final ASN1ObjectIdentifier id_KmacWithSHAKE256 = hashAlgs.branch("20"); + static final ASN1ObjectIdentifier id_KmacWithSHAKE256 = hashAlgs.branch("20"); + /** 2.16.840.1.101.3.4.2.21 */ + static final ASN1ObjectIdentifier id_Kmac128 = hashAlgs.branch("21"); + /** 2.16.840.1.101.3.4.2.22 */ + static final ASN1ObjectIdentifier id_Kmac256 = hashAlgs.branch("22"); /** * 2.16.840.1.101.3.4.1 @@ -226,4 +230,89 @@ public interface NISTObjectIdentifiers static final ASN1ObjectIdentifier id_rsassa_pkcs1_v1_5_with_sha3_384 = sigAlgs.branch("15"); /** 2.16.840.1.101.3.4.3.16 */ static final ASN1ObjectIdentifier id_rsassa_pkcs1_v1_5_with_sha3_512 = sigAlgs.branch("16"); + + // "pure" ML-DSA + /** 2.16.840.1.101.3.4.3.17 */ + static final ASN1ObjectIdentifier id_ml_dsa_44 = sigAlgs.branch("17"); + /** 2.16.840.1.101.3.4.3.18 */ + static final ASN1ObjectIdentifier id_ml_dsa_65 = sigAlgs.branch("18"); + /** 2.16.840.1.101.3.4.3.19 */ + static final ASN1ObjectIdentifier id_ml_dsa_87 = sigAlgs.branch("19"); + // "pre-hash" ML-DSA + /** 2.16.840.1.101.3.4.3.32 */ + static final ASN1ObjectIdentifier id_hash_ml_dsa_44_with_sha512 = sigAlgs.branch("32"); + /** 2.16.840.1.101.3.4.3.33 */ + static final ASN1ObjectIdentifier id_hash_ml_dsa_65_with_sha512 = sigAlgs.branch("33"); + /** 2.16.840.1.101.3.4.3.34 */ + static final ASN1ObjectIdentifier id_hash_ml_dsa_87_with_sha512 = sigAlgs.branch("34"); + + // "pure" SLH-DSA + /** 2.16.840.1.101.3.4.3.20 */ + static final ASN1ObjectIdentifier id_slh_dsa_sha2_128s = sigAlgs.branch("20"); + /** 2.16.840.1.101.3.4.3.21 */ + static final ASN1ObjectIdentifier id_slh_dsa_sha2_128f = sigAlgs.branch("21"); + /** 2.16.840.1.101.3.4.3.22 */ + static final ASN1ObjectIdentifier id_slh_dsa_sha2_192s = sigAlgs.branch("22"); + /** 2.16.840.1.101.3.4.3.23 */ + static final ASN1ObjectIdentifier id_slh_dsa_sha2_192f = sigAlgs.branch("23"); + /** 2.16.840.1.101.3.4.3.24 */ + static final ASN1ObjectIdentifier id_slh_dsa_sha2_256s = sigAlgs.branch("24"); + /** 2.16.840.1.101.3.4.3.25 */ + static final ASN1ObjectIdentifier id_slh_dsa_sha2_256f = sigAlgs.branch("25"); + /** 2.16.840.1.101.3.4.3.26 */ + static final ASN1ObjectIdentifier id_slh_dsa_shake_128s = sigAlgs.branch("26"); + /** 2.16.840.1.101.3.4.3.27 */ + static final ASN1ObjectIdentifier id_slh_dsa_shake_128f = sigAlgs.branch("27"); + /** 2.16.840.1.101.3.4.3.28 */ + static final ASN1ObjectIdentifier id_slh_dsa_shake_192s = sigAlgs.branch("28"); + /** 2.16.840.1.101.3.4.3.29 */ + static final ASN1ObjectIdentifier id_slh_dsa_shake_192f = sigAlgs.branch("29"); + /** 2.16.840.1.101.3.4.3.30 */ + static final ASN1ObjectIdentifier id_slh_dsa_shake_256s = sigAlgs.branch("30"); + /** 2.16.840.1.101.3.4.3.31 */ + static final ASN1ObjectIdentifier id_slh_dsa_shake_256f = sigAlgs.branch("31"); + // "pre-hash" SLH-DSA + + /** 2.16.840.1.101.3.4.3.35 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_sha2_128s_with_sha256 = sigAlgs.branch("35"); + /** 2.16.840.1.101.3.4.3.36 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_sha2_128f_with_sha256 = sigAlgs.branch("36"); + /** 2.16.840.1.101.3.4.3.37 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_sha2_192s_with_sha512 = sigAlgs.branch("37"); + /** 2.16.840.1.101.3.4.3.38 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_sha2_192f_with_sha512 = sigAlgs.branch("38"); + /** 2.16.840.1.101.3.4.3.39 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_sha2_256s_with_sha512 = sigAlgs.branch("39"); + /** 2.16.840.1.101.3.4.3.40 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_sha2_256f_with_sha512 = sigAlgs.branch("40"); + /** 2.16.840.1.101.3.4.3.41 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_shake_128s_with_shake128 = sigAlgs.branch("41"); + /** 2.16.840.1.101.3.4.3.42 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_shake_128f_with_shake128 = sigAlgs.branch("42"); + /** 2.16.840.1.101.3.4.3.43 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_shake_192s_with_shake256 = sigAlgs.branch("43"); + /** 2.16.840.1.101.3.4.3.44 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_shake_192f_with_shake256 = sigAlgs.branch("44"); + /** 2.16.840.1.101.3.4.3.45 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_shake_256s_with_shake256 = sigAlgs.branch("45"); + /** 2.16.840.1.101.3.4.3.46 */ + static final ASN1ObjectIdentifier id_hash_slh_dsa_shake_256f_with_shake256 = sigAlgs.branch("46"); + + + // + // KEMs - Key-Establishment Mechanisms + // + /** + * 2.16.840.1.101.3.4.4 + */ + static final ASN1ObjectIdentifier kems = nistAlgorithm.branch("4"); + + // ML-KEM + /** 2.16.840.1.101.3.4.4.1 */ + static final ASN1ObjectIdentifier id_alg_ml_kem_512 = kems.branch("1"); + /** 2.16.840.1.101.3.4.4.2 */ + static final ASN1ObjectIdentifier id_alg_ml_kem_768 = kems.branch("2"); + /** 2.16.840.1.101.3.4.4.3 */ + static final ASN1ObjectIdentifier id_alg_ml_kem_1024 = kems.branch("3"); + } diff --git a/core/src/main/java/org/bouncycastle/asn1/nist/package-info.java b/core/src/main/java/org/bouncycastle/asn1/nist/package-info.java new file mode 100644 index 0000000000..040557cc18 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/nist/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for NIST related objects. + */ +package org.bouncycastle.asn1.nist; diff --git a/core/src/main/java/org/bouncycastle/asn1/ocsp/CertID.java b/core/src/main/java/org/bouncycastle/asn1/ocsp/CertID.java index 001b6e361c..80d33f85d5 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ocsp/CertID.java +++ b/core/src/main/java/org/bouncycastle/asn1/ocsp/CertID.java @@ -1,5 +1,6 @@ package org.bouncycastle.asn1.ocsp; +import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; @@ -7,6 +8,7 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -16,7 +18,7 @@ public class CertID AlgorithmIdentifier hashAlgorithm; ASN1OctetString issuerNameHash; ASN1OctetString issuerKeyHash; - ASN1Integer serialNumber; + ASN1Integer serialNumber; public CertID( AlgorithmIdentifier hashAlgorithm, @@ -81,6 +83,72 @@ public ASN1Integer getSerialNumber() return serialNumber; } + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + + if (o instanceof ASN1Encodable) + { + try + { + CertID other = CertID.getInstance(o); + + if (!this.hashAlgorithm.getAlgorithm().equals(other.hashAlgorithm.getAlgorithm())) + { + return false; + } + if (!isEqual(this.hashAlgorithm.getParameters(), other.hashAlgorithm.getParameters())) + { + return false; + } + + return issuerNameHash.equals(other.issuerNameHash) + && issuerKeyHash.equals(other.issuerKeyHash) + && serialNumber.equals(other.serialNumber); + } + catch (Exception e) + { + return false; + } + } + + return false; + } + + public int hashCode() + { + ASN1Encodable params = hashAlgorithm.getParameters(); + int hashCode = (params == null || DERNull.INSTANCE.equals(params)) ? 0 : params.hashCode(); + + return hashCode + 7 * (hashAlgorithm.getAlgorithm().hashCode() + + 7 * (issuerNameHash.hashCode() + 7 * (issuerKeyHash.hashCode() + 7 * serialNumber.hashCode()))); + } + + private boolean isEqual(ASN1Encodable a, ASN1Encodable b) + { + if (a == b) + { + return true; + } + + if (a == null) + { + return DERNull.INSTANCE.equals(b); + } + else + { + if (DERNull.INSTANCE.equals(a) && b == null) + { + return true; + } + + return a.equals(b); + } + } + /** * Produce an object suitable for an ASN1OutputStream. *
    diff --git a/core/src/main/java/org/bouncycastle/asn1/ocsp/CertStatus.java b/core/src/main/java/org/bouncycastle/asn1/ocsp/CertStatus.java
    index ed1eec6892..bc4f597737 100644
    --- a/core/src/main/java/org/bouncycastle/asn1/ocsp/CertStatus.java
    +++ b/core/src/main/java/org/bouncycastle/asn1/ocsp/CertStatus.java
    @@ -104,6 +104,8 @@ public ASN1Encodable getStatus()
          *                  good        [0]     IMPLICIT NULL,
          *                  revoked     [1]     IMPLICIT RevokedInfo,
          *                  unknown     [2]     IMPLICIT UnknownInfo }
    +     *
    +     * UnknownInfo ::= NULL
          * 
    */ public ASN1Primitive toASN1Primitive() diff --git a/core/src/main/java/org/bouncycastle/asn1/ocsp/OCSPObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/ocsp/OCSPObjectIdentifiers.java index d52cfcc1bb..d4a68a8bdf 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ocsp/OCSPObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/ocsp/OCSPObjectIdentifiers.java @@ -1,6 +1,7 @@ package org.bouncycastle.asn1.ocsp; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; /** * OIDs for RFC 2560 and RFC 6960 @@ -9,26 +10,24 @@ public interface OCSPObjectIdentifiers { /** OID: 1.3.6.1.5.5.7.48.1 */ - static final ASN1ObjectIdentifier id_pkix_ocsp = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1"); + ASN1ObjectIdentifier id_pkix_ocsp = X509ObjectIdentifiers.id_ad_ocsp; + /** OID: 1.3.6.1.5.5.7.48.1.1 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_basic = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.1"); - + ASN1ObjectIdentifier id_pkix_ocsp_basic = id_pkix_ocsp.branch("1"); /** OID: 1.3.6.1.5.5.7.48.1.2 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_nonce = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.2"); + ASN1ObjectIdentifier id_pkix_ocsp_nonce = id_pkix_ocsp.branch("2"); /** OID: 1.3.6.1.5.5.7.48.1.3 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_crl = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.3"); - + ASN1ObjectIdentifier id_pkix_ocsp_crl = id_pkix_ocsp.branch("3"); /** OID: 1.3.6.1.5.5.7.48.1.4 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_response = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.4"); + ASN1ObjectIdentifier id_pkix_ocsp_response = id_pkix_ocsp.branch("4"); /** OID: 1.3.6.1.5.5.7.48.1.5 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_nocheck = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.5"); + ASN1ObjectIdentifier id_pkix_ocsp_nocheck = id_pkix_ocsp.branch("5"); /** OID: 1.3.6.1.5.5.7.48.1.6 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_archive_cutoff = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.6"); + ASN1ObjectIdentifier id_pkix_ocsp_archive_cutoff = id_pkix_ocsp.branch("6"); /** OID: 1.3.6.1.5.5.7.48.1.7 */ - static final ASN1ObjectIdentifier id_pkix_ocsp_service_locator = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.7"); - - - static final ASN1ObjectIdentifier id_pkix_ocsp_pref_sig_algs = id_pkix_ocsp.branch("8"); - - static final ASN1ObjectIdentifier id_pkix_ocsp_extended_revoke = id_pkix_ocsp.branch("9"); + ASN1ObjectIdentifier id_pkix_ocsp_service_locator = id_pkix_ocsp.branch("7"); + /** OID: 1.3.6.1.5.5.7.48.1.8 */ + ASN1ObjectIdentifier id_pkix_ocsp_pref_sig_algs = id_pkix_ocsp.branch("8"); + /** OID: 1.3.6.1.5.5.7.48.1.9 */ + ASN1ObjectIdentifier id_pkix_ocsp_extended_revoke = id_pkix_ocsp.branch("9"); } diff --git a/core/src/main/java/org/bouncycastle/asn1/ocsp/ResponseBytes.java b/core/src/main/java/org/bouncycastle/asn1/ocsp/ResponseBytes.java index eaeaa60a64..6335d22f8a 100644 --- a/core/src/main/java/org/bouncycastle/asn1/ocsp/ResponseBytes.java +++ b/core/src/main/java/org/bouncycastle/asn1/ocsp/ResponseBytes.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.ocsp; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; @@ -80,11 +79,6 @@ public ASN1OctetString getResponse() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(responseType); - v.add(response); - - return new DERSequence(v); + return new DERSequence(responseType, response); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/ocsp/package-info.java b/core/src/main/java/org/bouncycastle/asn1/ocsp/package-info.java new file mode 100644 index 0000000000..6c5f104f37 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/ocsp/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and supporting OCSP objects. + */ +package org.bouncycastle.asn1.ocsp; diff --git a/core/src/main/java/org/bouncycastle/asn1/package-info.java b/core/src/main/java/org/bouncycastle/asn1/package-info.java new file mode 100644 index 0000000000..00a57d59e7 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/package-info.java @@ -0,0 +1,4 @@ +/** + * A library for parsing and writing ASN.1 objects. Support is provided for DER and BER encoding. + */ +package org.bouncycastle.asn1; diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/Attribute.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/Attribute.java index 1cc67fac9c..4fb9031aad 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/Attribute.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/Attribute.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.pkcs; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -78,11 +77,6 @@ public ASN1Encodable[] getAttributeValues() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(attrType); - v.add(attrValues); - - return new DERSequence(v); + return new DERSequence(attrType, attrValues); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/CRLBag.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/CRLBag.java index 1bb92f5543..b24d7ed6a4 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/CRLBag.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/CRLBag.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.pkcs; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -76,11 +75,6 @@ public ASN1Encodable getCrlValue() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(crlId); - v.add(new DERTaggedObject(0, crlValue)); - - return new DERSequence(v); + return new DERSequence(crlId, new DERTaggedObject(0, crlValue)); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/CertBag.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/CertBag.java index 87f03de71d..69b73eb339 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/CertBag.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/CertBag.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.pkcs; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -57,11 +56,6 @@ public ASN1Encodable getCertValue() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(certId); - v.add(new DERTaggedObject(0, certValue)); - - return new DERSequence(v); + return new DERSequence(certId, new DERTaggedObject(0, certValue)); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedData.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedData.java index 8faafe5ce6..d1901fd3c0 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedData.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedData.java @@ -102,11 +102,6 @@ public ASN1OctetString getContent() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(new ASN1Integer(0)); - v.add(data); - - return new BERSequence(v); + return new BERSequence(new ASN1Integer(0), data); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedPrivateKeyInfo.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedPrivateKeyInfo.java index cc16037069..2390d0b0ef 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedPrivateKeyInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptedPrivateKeyInfo.java @@ -2,7 +2,6 @@ import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; @@ -77,11 +76,6 @@ public byte[] getEncryptedData() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(algId); - v.add(data); - - return new DERSequence(v); + return new DERSequence(algId, data); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptionScheme.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptionScheme.java index eeaa48d9a8..9c728cbaa4 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptionScheme.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/EncryptionScheme.java @@ -7,6 +7,7 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +// TODO[api] This is not supposed to be a separate type; remove and use AlgorithmIdentifier public class EncryptionScheme extends ASN1Object { diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/IssuerAndSerialNumber.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/IssuerAndSerialNumber.java index aa06263b70..98b7650ee7 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/IssuerAndSerialNumber.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/IssuerAndSerialNumber.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -75,11 +74,6 @@ public ASN1Integer getCertificateSerialNumber() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(name); - v.add(certSerialNumber); - - return new DERSequence(v); + return new DERSequence(name, certSerialNumber); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/KeyDerivationFunc.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/KeyDerivationFunc.java index 83804f387a..dc6b250a14 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/KeyDerivationFunc.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/KeyDerivationFunc.java @@ -7,6 +7,7 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +// TODO[api] This is not supposed to be a separate type; remove and use AlgorithmIdentifier public class KeyDerivationFunc extends ASN1Object { diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/PBEParameter.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/PBEParameter.java index fa4dacd3ab..055f827b4d 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/PBEParameter.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/PBEParameter.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; @@ -63,11 +62,6 @@ public byte[] getSalt() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(salt); - v.add(iterations); - - return new DERSequence(v); + return new DERSequence(salt, iterations); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/PBES2Parameters.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/PBES2Parameters.java index fdea9b1401..68251bc399 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/PBES2Parameters.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/PBES2Parameters.java @@ -3,7 +3,6 @@ import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -67,11 +66,6 @@ public EncryptionScheme getEncryptionScheme() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(func); - v.add(scheme); - - return new DERSequence(v); + return new DERSequence(func, scheme); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/PBMAC1Params.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/PBMAC1Params.java index fdbaefdd9b..594c5cc936 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/PBMAC1Params.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/PBMAC1Params.java @@ -3,14 +3,12 @@ import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; - /** * From https://datatracker.ietf.org/doc/html/rfc8018 * @@ -78,11 +76,6 @@ public AlgorithmIdentifier getMessageAuthScheme() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(func); - v.add(scheme); - - return new DERSequence(v); + return new DERSequence(func, scheme); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCS12PBEParams.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCS12PBEParams.java index 1587a59663..2d9c94a2f7 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCS12PBEParams.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCS12PBEParams.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; @@ -59,11 +58,6 @@ public byte[] getIV() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(iv); - v.add(iterations); - - return new DERSequence(v); + return new DERSequence(iv, iterations); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCSObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCSObjectIdentifiers.java index a2d6eef51d..7663ab59c2 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCSObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/PKCSObjectIdentifiers.java @@ -187,8 +187,6 @@ public interface PKCSObjectIdentifiers ASN1ObjectIdentifier pkcs_9_at_smimeCapabilities = pkcs_9.branch("15").intern(); /** PKCS#9: 1.2.840.113549.1.9.16 */ ASN1ObjectIdentifier id_smime = pkcs_9.branch("16").intern(); - /** PKCS#9: 1.2.840.113549.1.9.16.2.46 */ - ASN1ObjectIdentifier pkcs_9_at_binarySigningTime = pkcs_9.branch("16.2.46").intern(); /** PKCS#9: 1.2.840.113549.1.9.20 */ ASN1ObjectIdentifier pkcs_9_at_friendlyName = pkcs_9.branch("20").intern(); @@ -226,12 +224,25 @@ public interface PKCSObjectIdentifiers /** PKCS#9: 1.2.840.113549.1.9.15.3 -- smime capability */ ASN1ObjectIdentifier sMIMECapabilitiesVersions = pkcs_9.branch("15.3"); + // + // id-mod OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) + // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) mod(0)} + // + /** RFC 4010: SeedEncryptionAlgorithmInCMS; OID 1.2.840.113549.1.9.16.0.24 */ + ASN1ObjectIdentifier id_mod_cms_seed = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.0.24"); + + /** RFC 9708 MTS-HashSig-2013; OID 1.2.840.113549.1.9.16.0.64 */ + ASN1ObjectIdentifier id_mod_mts_hashsig_2013 = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.0.64"); + + /** RFC 8103 id-mod-CMS-AEADChaCha20Poly1305; OID 1.2.840.113549.1.9.16.0.66 */ + ASN1ObjectIdentifier id_mod_CMS_AEADChaCha20Poly1305 = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.0.66"); + // // id-ct OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)} // /** PKCS#9: 1.2.840.113549.1.9.16.1 -- smime ct */ - ASN1ObjectIdentifier id_ct = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.1"); + ASN1ObjectIdentifier id_ct = id_smime.branch("1"); /** PKCS#9: 1.2.840.113549.1.9.16.1.2 -- smime ct authData */ ASN1ObjectIdentifier id_ct_authData = id_ct.branch("2"); @@ -246,20 +257,24 @@ public interface PKCSObjectIdentifiers /** S/MIME: Algorithm Identifiers ; 1.2.840.113549.1.9.16.3 */ - ASN1ObjectIdentifier id_alg = id_smime.branch("3"); + ASN1ObjectIdentifier smime_alg = id_smime.branch("3"); + /** @deprecated use smime_alg instead */ + ASN1ObjectIdentifier id_alg = id_smime.branch("3"); /** PKCS#9: 1.2.840.113549.1.9.16.3.5 */ - ASN1ObjectIdentifier id_alg_ESDH = id_alg.branch("5"); + ASN1ObjectIdentifier id_alg_ESDH = smime_alg.branch("5"); /** PKCS#9: 1.2.840.113549.1.9.16.3.6 */ - ASN1ObjectIdentifier id_alg_CMS3DESwrap = id_alg.branch("6"); + ASN1ObjectIdentifier id_alg_CMS3DESwrap = smime_alg.branch("6"); /** PKCS#9: 1.2.840.113549.1.9.16.3.7 */ - ASN1ObjectIdentifier id_alg_CMSRC2wrap = id_alg.branch("7"); + ASN1ObjectIdentifier id_alg_CMSRC2wrap = smime_alg.branch("7"); /** PKCS#9: 1.2.840.113549.1.9.16.3.8 */ - ASN1ObjectIdentifier id_alg_zlibCompress = id_alg.branch("8"); + ASN1ObjectIdentifier id_alg_zlibCompress = smime_alg.branch("8"); /** PKCS#9: 1.2.840.113549.1.9.16.3.9 */ - ASN1ObjectIdentifier id_alg_PWRI_KEK = id_alg.branch("9"); + ASN1ObjectIdentifier id_alg_PWRI_KEK = smime_alg.branch("9"); /** PKCS#9: 1.2.840.113549.1.9.16.3.10 */ - ASN1ObjectIdentifier id_alg_SSDH = id_alg.branch("10"); + ASN1ObjectIdentifier id_alg_SSDH = smime_alg.branch("10"); + + /** *
    @@ -271,15 +286,16 @@ public interface PKCSObjectIdentifiers
          *   }
          * 
    */ - ASN1ObjectIdentifier id_rsa_KEM = id_alg.branch("14"); + ASN1ObjectIdentifier id_rsa_KEM = smime_alg.branch("14"); /** * id-alg-hss-lms-hashsig OBJECT IDENTIFIER ::= { iso(1) * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) * smime(16) alg(3) 17 } + * 1.2.840.113549.1.9.16.3.17 */ - public static final ASN1ObjectIdentifier id_alg_hss_lms_hashsig = id_alg.branch("17"); + public static final ASN1ObjectIdentifier id_alg_hss_lms_hashsig = smime_alg.branch("17"); /** *
    @@ -290,7 +306,7 @@ public interface PKCSObjectIdentifiers
          * AEADChaCha20Poly1305Nonce ::= OCTET STRING (SIZE(12))
          * 
    */ - ASN1ObjectIdentifier id_alg_AEADChaCha20Poly1305 = id_alg.branch("18"); + ASN1ObjectIdentifier id_alg_AEADChaCha20Poly1305 = smime_alg.branch("18"); /** *
    @@ -298,7 +314,7 @@ public interface PKCSObjectIdentifiers
          *        us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) alg(3) 28 }
          * 
    */ - ASN1ObjectIdentifier id_alg_hkdf_with_sha256 = id_alg.branch("28"); + ASN1ObjectIdentifier id_alg_hkdf_with_sha256 = smime_alg.branch("28"); /** *
    @@ -306,7 +322,7 @@ public interface PKCSObjectIdentifiers
          *        us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) alg(3) 29 }
          * 
    */ - ASN1ObjectIdentifier id_alg_hkdf_with_sha384 = id_alg.branch("29"); + ASN1ObjectIdentifier id_alg_hkdf_with_sha384 = smime_alg.branch("29"); /** *
    @@ -314,16 +330,16 @@ public interface PKCSObjectIdentifiers
          *        us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) alg(3) 30 }
          * 
    */ - ASN1ObjectIdentifier id_alg_hkdf_with_sha512 = id_alg.branch("30"); + ASN1ObjectIdentifier id_alg_hkdf_with_sha512 = smime_alg.branch("30"); // // id-cti OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) cti(6)} // /** PKCS#9: 1.2.840.113549.1.9.16.6 -- smime cti */ - ASN1ObjectIdentifier id_cti = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.6"); - - /** PKCS#9: 1.2.840.113549.1.9.16.6.1 -- smime cti proofOfOrigin */ + ASN1ObjectIdentifier id_cti = id_smime.branch("6"); + + /** PKCS#9: 1.2.840.113549.1.9.16.6.1 -- smime cti proofOfOrigin */ ASN1ObjectIdentifier id_cti_ets_proofOfOrigin = id_cti.branch("1"); /** PKCS#9: 1.2.840.113549.1.9.16.6.2 -- smime cti proofOfReceipt*/ ASN1ObjectIdentifier id_cti_ets_proofOfReceipt = id_cti.branch("2"); @@ -341,8 +357,10 @@ public interface PKCSObjectIdentifiers // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)} // /** PKCS#9: 1.2.840.113549.1.9.16.2 - smime attributes */ - ASN1ObjectIdentifier id_aa = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.2"); + ASN1ObjectIdentifier id_aa = id_smime.branch("2"); + /** PKCS#9: 1.2.840.113549.1.9.16.2.46 */ + ASN1ObjectIdentifier pkcs_9_at_binarySigningTime = id_aa.branch("46").intern(); /** PKCS#9: 1.2.840.113549.1.9.16.2.1 -- smime attribute receiptRequest */ ASN1ObjectIdentifier id_aa_receiptRequest = id_aa.branch("1"); @@ -427,13 +445,15 @@ public interface PKCSObjectIdentifiers * id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) * rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)};

    * 1.2.840.113549.1.9.16.5 + * @deprecated use id_spq_oid instead */ final String id_spq = "1.2.840.113549.1.9.16.5"; + ASN1ObjectIdentifier id_spq_oid = id_smime.branch("5"); /** SMIME SPQ URI: 1.2.840.113549.1.9.16.5.1 */ - ASN1ObjectIdentifier id_spq_ets_uri = new ASN1ObjectIdentifier(id_spq + ".1"); + ASN1ObjectIdentifier id_spq_ets_uri = id_spq_oid.branch("1"); /** SMIME SPQ UNOTICE: 1.2.840.113549.1.9.16.5.2 */ - ASN1ObjectIdentifier id_spq_ets_unotice = new ASN1ObjectIdentifier(id_spq + ".2"); + ASN1ObjectIdentifier id_spq_ets_unotice = id_spq_oid.branch("2"); // // pkcs-12 OBJECT IDENTIFIER ::= { diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/PrivateKeyInfo.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/PrivateKeyInfo.java index 2a78c1fb50..bbf92e4572 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/PrivateKeyInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/PrivateKeyInfo.java @@ -6,6 +6,7 @@ import org.bouncycastle.asn1.ASN1BitString; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; @@ -95,6 +96,27 @@ private static int getVersionValue(ASN1Integer version) return versionValue; } + /** + * Construct a PrivateKeyInfo around a raw encoding. + * + * @param privateKeyAlgorithm algorithm identifier for the private key. + * @param privateKey byte encoding of the private key, used as a raw encoding. + */ + public PrivateKeyInfo( + AlgorithmIdentifier privateKeyAlgorithm, + byte[] privateKey) + throws IOException + { + this(privateKeyAlgorithm, privateKey, null, null); + } + + /** + * Construct a PrivateKeyInfo around an ASN.1 structure/primitive. + * + * @param privateKeyAlgorithm algorithm identifier for the private key. + * @param privateKey the ASN.1 structure/primitive representing the private key. + * @throws IOException if encoding the privateKey object into an OCTET STRING fails. + */ public PrivateKeyInfo( AlgorithmIdentifier privateKeyAlgorithm, ASN1Encodable privateKey) @@ -103,6 +125,14 @@ public PrivateKeyInfo( this(privateKeyAlgorithm, privateKey, null, null); } + /** + * Construct a PrivateKeyInfo around an ASN.1 structure/primitive with attributes. + * + * @param privateKeyAlgorithm algorithm identifier for the private key. + * @param privateKey the ASN.1 structure/primitive representing the private key. + * @param attributes attributes associated with private key. + * @throws IOException if encoding the privateKey object into an OCTET STRING fails. + */ public PrivateKeyInfo( AlgorithmIdentifier privateKeyAlgorithm, ASN1Encodable privateKey, @@ -112,12 +142,55 @@ public PrivateKeyInfo( this(privateKeyAlgorithm, privateKey, attributes, null); } + /** + * Construct a PrivateKeyInfo around an ASN.1 structure/primitive with attributes. + * + * @param privateKeyAlgorithm algorithm identifier for the private key. + * @param privateKey byte encoding of the private key, used as a raw encoding. + * @param attributes attributes associated with private key. + * @throws IOException if encoding the privateKey object into an OCTET STRING fails. + */ + public PrivateKeyInfo( + AlgorithmIdentifier privateKeyAlgorithm, + byte[] privateKey, + ASN1Set attributes) + throws IOException + { + this(privateKeyAlgorithm, privateKey, attributes, null); + } + + /** + * Construct a PrivateKeyInfo around an ASN.1 structure/primitive with attributes and the public key. + * + * @param privateKeyAlgorithm algorithm identifier for the private key. + * @param privateKey the ASN.1 structure/primitive representing the private key. + * @param attributes attributes associated with private key. + * @param publicKey public key encoding. + * @throws IOException if encoding the privateKey object into an OCTET STRING fails. + */ public PrivateKeyInfo( AlgorithmIdentifier privateKeyAlgorithm, ASN1Encodable privateKey, ASN1Set attributes, byte[] publicKey) throws IOException + { + this(privateKeyAlgorithm, privateKey.toASN1Primitive().getEncoded(ASN1Encoding.DER), attributes, publicKey); + } + + /** + * Construct a PrivateKeyInfo around a raw encoding with attributes and the public key. + * + * @param privateKeyAlgorithm algorithm identifier for the private key. + * @param privateKey byte encoding of the private key, used as a raw encoding. + * @param attributes attributes associated with private key. + * @param publicKey public key encoding. + */ + public PrivateKeyInfo( + AlgorithmIdentifier privateKeyAlgorithm, + byte[] privateKey, + ASN1Set attributes, + byte[] publicKey) { this.version = new ASN1Integer(publicKey != null ? BigIntegers.ONE : BigIntegers.ZERO); this.privateKeyAlgorithm = privateKeyAlgorithm; @@ -222,7 +295,7 @@ public boolean hasPublicKey() * * @return the public key as an ASN.1 primitive. * @throws IOException - if the bit string doesn't represent a DER - * encoded object. + * encoded object. */ public ASN1Encodable parsePublicKey() throws IOException diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/RC2CBCParameter.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/RC2CBCParameter.java index cb25010f51..61bc110f1a 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/RC2CBCParameter.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/RC2CBCParameter.java @@ -72,6 +72,11 @@ public BigInteger getRC2ParameterVersion() return version.getValue(); } + public ASN1Integer getRC2ParameterVersionData() + { + return version; + } + public byte[] getIV() { return iv.getOctets(); diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/RSAPublicKey.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/RSAPublicKey.java index f07819be0d..f6e1c736a5 100644 --- a/core/src/main/java/org/bouncycastle/asn1/pkcs/RSAPublicKey.java +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/RSAPublicKey.java @@ -3,7 +3,6 @@ import java.math.BigInteger; import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -85,11 +84,6 @@ public BigInteger getPublicExponent() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(new ASN1Integer(getModulus())); - v.add(new ASN1Integer(getPublicExponent())); - - return new DERSequence(v); + return new DERSequence(new ASN1Integer(getModulus()), new ASN1Integer(getPublicExponent())); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/pkcs/package-info.java b/core/src/main/java/org/bouncycastle/asn1/pkcs/package-info.java new file mode 100644 index 0000000000..c11063c9e5 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/pkcs/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and supporting the various RSA PKCS documents. + */ +package org.bouncycastle.asn1.pkcs; diff --git a/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKey.java b/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKey.java index d37769f862..890fba67bb 100644 --- a/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKey.java +++ b/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKey.java @@ -69,12 +69,7 @@ public ECPrivateKey( { byte[] bytes = BigIntegers.asUnsignedByteArray((orderBitLength + 7) / 8, key); - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(new ASN1Integer(1)); - v.add(new DEROctetString(bytes)); - - seq = new DERSequence(v); + seq = new DERSequence(new ASN1Integer(1), new DEROctetString(bytes)); } /** diff --git a/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKeyStructure.java b/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKeyStructure.java index 5c33b1ede6..5ed882ef84 100644 --- a/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKeyStructure.java +++ b/core/src/main/java/org/bouncycastle/asn1/sec/ECPrivateKeyStructure.java @@ -37,12 +37,7 @@ public ECPrivateKeyStructure( { byte[] bytes = BigIntegers.asUnsignedByteArray(key); - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(new ASN1Integer(1)); - v.add(new DEROctetString(bytes)); - - seq = new DERSequence(v); + seq = new DERSequence(new ASN1Integer(1), new DEROctetString(bytes)); } public ECPrivateKeyStructure( diff --git a/core/src/main/java/org/bouncycastle/asn1/sec/package-info.java b/core/src/main/java/org/bouncycastle/asn1/sec/package-info.java new file mode 100644 index 0000000000..799fa30300 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/sec/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for support of the SEC standard for Elliptic Curve. + */ +package org.bouncycastle.asn1.sec; diff --git a/core/src/main/java/org/bouncycastle/asn1/teletrust/package-info.java b/core/src/main/java/org/bouncycastle/asn1/teletrust/package-info.java new file mode 100644 index 0000000000..39ff9f008c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/teletrust/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for TeleTrust related objects. + */ +package org.bouncycastle.asn1.teletrust; diff --git a/core/src/main/java/org/bouncycastle/asn1/ua/package-info.java b/core/src/main/java/org/bouncycastle/asn1/ua/package-info.java new file mode 100644 index 0000000000..28ac67f374 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/ua/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for the Ukrainian DSTU standard. + */ +package org.bouncycastle.asn1.ua; diff --git a/core/src/main/java/org/bouncycastle/asn1/util/ASN1Dump.java b/core/src/main/java/org/bouncycastle/asn1/util/ASN1Dump.java index 4ff5e2dcd9..9bfcc224bf 100644 --- a/core/src/main/java/org/bouncycastle/asn1/util/ASN1Dump.java +++ b/core/src/main/java/org/bouncycastle/asn1/util/ASN1Dump.java @@ -52,22 +52,18 @@ public class ASN1Dump * * @param obj the ASN1Primitive to be dumped out. */ - static void _dumpAsString( - String indent, - boolean verbose, - ASN1Primitive obj, - StringBuffer buf) + static void _dumpAsString(String indent, boolean verbose, ASN1Primitive obj, StringBuffer buf) { String nl = Strings.lineSeparator(); + buf.append(indent); + if (obj instanceof ASN1Null) { - buf.append(indent); buf.append("NULL"); buf.append(nl); } else if (obj instanceof ASN1Sequence) { - buf.append(indent); if (obj instanceof BERSequence) { buf.append("BER Sequence"); @@ -92,7 +88,6 @@ else if (obj instanceof DERSequence) } else if (obj instanceof ASN1Set) { - buf.append(indent); if (obj instanceof BERSet) { buf.append("BER Set"); @@ -117,7 +112,6 @@ else if (obj instanceof DERSet) } else if (obj instanceof ASN1TaggedObject) { - buf.append(indent); if (obj instanceof BERTaggedObject) { buf.append("BER Tagged "); @@ -137,7 +131,7 @@ else if (obj instanceof DERTaggedObject) if (!o.isExplicit()) { - buf.append(" IMPLICIT "); + buf.append(" IMPLICIT"); } buf.append(nl); @@ -146,130 +140,124 @@ else if (obj instanceof DERTaggedObject) _dumpAsString(baseIndent, verbose, o.getBaseObject().toASN1Primitive(), buf); } + else if (obj instanceof ASN1ObjectIdentifier) + { + buf.append("ObjectIdentifier(" + ((ASN1ObjectIdentifier)obj).getId() + ")" + nl); + } + else if (obj instanceof ASN1RelativeOID) + { + buf.append("RelativeOID(" + ((ASN1RelativeOID)obj).getId() + ")" + nl); + } + else if (obj instanceof ASN1Boolean) + { + buf.append("Boolean(" + ((ASN1Boolean)obj).isTrue() + ")" + nl); + } + else if (obj instanceof ASN1Integer) + { + buf.append("Integer(" + ((ASN1Integer)obj).getValue() + ")" + nl); + } else if (obj instanceof ASN1OctetString) { ASN1OctetString oct = (ASN1OctetString)obj; if (obj instanceof BEROctetString) { - buf.append(indent + "BER Constructed Octet String" + "[" + oct.getOctets().length + "] "); + buf.append("BER Constructed Octet String["); } else { - buf.append(indent + "DER Octet String" + "[" + oct.getOctets().length + "] "); + buf.append("DER Octet String["); } + + buf.append(oct.getOctetsLength() + "]" + nl); + if (verbose) { - buf.append(dumpBinaryDataAsString(indent, oct.getOctets())); - } - else - { - buf.append(nl); + dumpBinaryDataAsString(buf, indent, oct.getOctets()); } } - else if (obj instanceof ASN1ObjectIdentifier) - { - buf.append(indent + "ObjectIdentifier(" + ((ASN1ObjectIdentifier)obj).getId() + ")" + nl); - } - else if (obj instanceof ASN1RelativeOID) - { - buf.append(indent + "RelativeOID(" + ((ASN1RelativeOID)obj).getId() + ")" + nl); - } - else if (obj instanceof ASN1Boolean) - { - buf.append(indent + "Boolean(" + ((ASN1Boolean)obj).isTrue() + ")" + nl); - } - else if (obj instanceof ASN1Integer) - { - buf.append(indent + "Integer(" + ((ASN1Integer)obj).getValue() + ")" + nl); - } else if (obj instanceof ASN1BitString) { ASN1BitString bitString = (ASN1BitString)obj; - byte[] bytes = bitString.getBytes(); - int padBits = bitString.getPadBits(); - if (bitString instanceof DERBitString) { - buf.append(indent + "DER Bit String" + "[" + bytes.length + ", " + padBits + "] "); + buf.append("DER Bit String["); } else if (bitString instanceof DLBitString) { - buf.append(indent + "DL Bit String" + "[" + bytes.length + ", " + padBits + "] "); + buf.append("DL Bit String["); } else { - buf.append(indent + "BER Bit String" + "[" + bytes.length + ", " + padBits + "] "); + buf.append("BER Bit String["); } + buf.append(bitString.getBytesLength() + ", " + bitString.getPadBits() + "]" + nl); + if (verbose) { - buf.append(dumpBinaryDataAsString(indent, bytes)); - } - else - { - buf.append(nl); + dumpBinaryDataAsString(buf, indent, bitString.getBytes()); } } else if (obj instanceof ASN1IA5String) { - buf.append(indent + "IA5String(" + ((ASN1IA5String)obj).getString() + ") " + nl); + buf.append("IA5String(" + ((ASN1IA5String)obj).getString() + ") " + nl); } else if (obj instanceof ASN1UTF8String) { - buf.append(indent + "UTF8String(" + ((ASN1UTF8String)obj).getString() + ") " + nl); + buf.append("UTF8String(" + ((ASN1UTF8String)obj).getString() + ") " + nl); } else if (obj instanceof ASN1NumericString) { - buf.append(indent + "NumericString(" + ((ASN1NumericString)obj).getString() + ") " + nl); + buf.append("NumericString(" + ((ASN1NumericString)obj).getString() + ") " + nl); } else if (obj instanceof ASN1PrintableString) { - buf.append(indent + "PrintableString(" + ((ASN1PrintableString)obj).getString() + ") " + nl); + buf.append("PrintableString(" + ((ASN1PrintableString)obj).getString() + ") " + nl); } else if (obj instanceof ASN1VisibleString) { - buf.append(indent + "VisibleString(" + ((ASN1VisibleString)obj).getString() + ") " + nl); + buf.append("VisibleString(" + ((ASN1VisibleString)obj).getString() + ") " + nl); } else if (obj instanceof ASN1BMPString) { - buf.append(indent + "BMPString(" + ((ASN1BMPString)obj).getString() + ") " + nl); + buf.append("BMPString(" + ((ASN1BMPString)obj).getString() + ") " + nl); } else if (obj instanceof ASN1T61String) { - buf.append(indent + "T61String(" + ((ASN1T61String)obj).getString() + ") " + nl); + buf.append("T61String(" + ((ASN1T61String)obj).getString() + ") " + nl); } else if (obj instanceof ASN1GraphicString) { - buf.append(indent + "GraphicString(" + ((ASN1GraphicString)obj).getString() + ") " + nl); + buf.append("GraphicString(" + ((ASN1GraphicString)obj).getString() + ") " + nl); } else if (obj instanceof ASN1VideotexString) { - buf.append(indent + "VideotexString(" + ((ASN1VideotexString)obj).getString() + ") " + nl); + buf.append("VideotexString(" + ((ASN1VideotexString)obj).getString() + ") " + nl); } else if (obj instanceof ASN1UTCTime) { - buf.append(indent + "UTCTime(" + ((ASN1UTCTime)obj).getTime() + ") " + nl); + buf.append("UTCTime(" + ((ASN1UTCTime)obj).getTime() + ") " + nl); } else if (obj instanceof ASN1GeneralizedTime) { - buf.append(indent + "GeneralizedTime(" + ((ASN1GeneralizedTime)obj).getTime() + ") " + nl); + buf.append("GeneralizedTime(" + ((ASN1GeneralizedTime)obj).getTime() + ") " + nl); } else if (obj instanceof ASN1Enumerated) { ASN1Enumerated en = (ASN1Enumerated) obj; - buf.append(indent + "DER Enumerated(" + en.getValue() + ")" + nl); + buf.append("DER Enumerated(" + en.getValue() + ")" + nl); } else if (obj instanceof ASN1ObjectDescriptor) { ASN1ObjectDescriptor od = (ASN1ObjectDescriptor)obj; - buf.append(indent + "ObjectDescriptor(" + od.getBaseGraphicString().getString() + ") " + nl); + buf.append("ObjectDescriptor(" + od.getBaseGraphicString().getString() + ") " + nl); } else if (obj instanceof ASN1External) { ASN1External ext = (ASN1External) obj; - buf.append(indent + "External " + nl); + buf.append("External " + nl); String tab = indent + TAB; if (ext.getDirectReference() != null) { @@ -288,7 +276,7 @@ else if (obj instanceof ASN1External) } else { - buf.append(indent + obj.toString() + nl); + buf.append(obj.toString() + nl); } } @@ -334,45 +322,37 @@ else if (obj instanceof ASN1Encodable) return buf.toString(); } - private static String dumpBinaryDataAsString(String indent, byte[] bytes) + private static void dumpBinaryDataAsString(StringBuffer buf, String indent, byte[] bytes) { + if (bytes.length < 1) + { + return; + } + String nl = Strings.lineSeparator(); - StringBuffer buf = new StringBuffer(); indent += TAB; - - buf.append(nl); + for (int i = 0; i < bytes.length; i += SAMPLE_SIZE) { - if (bytes.length - i > SAMPLE_SIZE) - { - buf.append(indent); - buf.append(Strings.fromByteArray(Hex.encode(bytes, i, SAMPLE_SIZE))); - buf.append(TAB); - buf.append(calculateAscString(bytes, i, SAMPLE_SIZE)); - buf.append(nl); - } - else + int remaining = bytes.length - i; + int chunk = Math.min(remaining, SAMPLE_SIZE); + + buf.append(indent); + // -DM Hex.toHexString + buf.append(Hex.toHexString(bytes, i, chunk)); + for (int j = chunk; j < SAMPLE_SIZE; ++j) { - buf.append(indent); - buf.append(Strings.fromByteArray(Hex.encode(bytes, i, bytes.length - i))); - for (int j = bytes.length - i; j != SAMPLE_SIZE; j++) - { - buf.append(" "); - } - buf.append(TAB); - buf.append(calculateAscString(bytes, i, bytes.length - i)); - buf.append(nl); + buf.append(" "); } + buf.append(TAB); + appendAscString(buf, bytes, i, chunk); + buf.append(nl); } - - return buf.toString(); } - private static String calculateAscString(byte[] bytes, int off, int len) + private static void appendAscString(StringBuffer buf, byte[] bytes, int off, int len) { - StringBuffer buf = new StringBuffer(); - for (int i = off; i != off + len; i++) { if (bytes[i] >= ' ' && bytes[i] <= '~') @@ -380,7 +360,5 @@ private static String calculateAscString(byte[] bytes, int off, int len) buf.append((char)bytes[i]); } } - - return buf.toString(); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/util/package-info.java b/core/src/main/java/org/bouncycastle/asn1/util/package-info.java new file mode 100644 index 0000000000..8c2df75eb4 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/util/package-info.java @@ -0,0 +1,4 @@ +/** + * An ASN.1 dump utility. + */ +package org.bouncycastle.asn1.util; diff --git a/core/src/main/java/org/bouncycastle/asn1/x500/AttributeTypeAndValue.java b/core/src/main/java/org/bouncycastle/asn1/x500/AttributeTypeAndValue.java index 44b5b9f4a2..814da3e0ed 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x500/AttributeTypeAndValue.java +++ b/core/src/main/java/org/bouncycastle/asn1/x500/AttributeTypeAndValue.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.x500; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -65,11 +64,6 @@ public ASN1Encodable getValue() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(type); - v.add(value); - - return new DERSequence(v); + return new DERSequence(type, value); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x500/package-info.java b/core/src/main/java/org/bouncycastle/asn1/x500/package-info.java new file mode 100644 index 0000000000..71121ef4ea --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x500/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for the creation and processing of object based on X.500 names. + */ +package org.bouncycastle.asn1.x500; diff --git a/core/src/main/java/org/bouncycastle/asn1/x500/style/BCStyle.java b/core/src/main/java/org/bouncycastle/asn1/x500/style/BCStyle.java index 4a3b6ae5a2..f27f221e8c 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x500/style/BCStyle.java +++ b/core/src/main/java/org/bouncycastle/asn1/x500/style/BCStyle.java @@ -103,29 +103,29 @@ public class BCStyle /** * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z */ - public static final ASN1ObjectIdentifier DATE_OF_BIRTH = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.9.1").intern(); + public static final ASN1ObjectIdentifier DATE_OF_BIRTH = X509ObjectIdentifiers.id_pda.branch("1").intern(); /** * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) */ - public static final ASN1ObjectIdentifier PLACE_OF_BIRTH = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.9.2").intern(); + public static final ASN1ObjectIdentifier PLACE_OF_BIRTH = X509ObjectIdentifiers.id_pda.branch("2").intern(); /** * RFC 3039 Gender - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" */ - public static final ASN1ObjectIdentifier GENDER = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.9.3").intern(); + public static final ASN1ObjectIdentifier GENDER = X509ObjectIdentifiers.id_pda.branch("3").intern(); /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ - public static final ASN1ObjectIdentifier COUNTRY_OF_CITIZENSHIP = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.9.4").intern(); + public static final ASN1ObjectIdentifier COUNTRY_OF_CITIZENSHIP = X509ObjectIdentifiers.id_pda.branch("4").intern(); /** * RFC 3039 CountryOfResidence - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ - public static final ASN1ObjectIdentifier COUNTRY_OF_RESIDENCE = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.9.5").intern(); + public static final ASN1ObjectIdentifier COUNTRY_OF_RESIDENCE = X509ObjectIdentifiers.id_pda.branch("5").intern(); /** @@ -291,9 +291,9 @@ public class BCStyle DefaultLookUp.put("telephonenumber", TELEPHONE_NUMBER); DefaultLookUp.put("name", NAME); DefaultLookUp.put("organizationidentifier", ORGANIZATION_IDENTIFIER); - DefaultLookUp.put("jurisdictionCountry", JURISDICTION_C); - DefaultLookUp.put("jurisdictionState", JURISDICTION_ST); - DefaultLookUp.put("jurisdictionLocality", JURISDICTION_L); + DefaultLookUp.put("jurisdictioncountry", JURISDICTION_C); + DefaultLookUp.put("jurisdictionstate", JURISDICTION_ST); + DefaultLookUp.put("jurisdictionlocality", JURISDICTION_L); } /** diff --git a/core/src/main/java/org/bouncycastle/asn1/x500/style/package-info.java b/core/src/main/java/org/bouncycastle/asn1/x500/style/package-info.java new file mode 100644 index 0000000000..414314db48 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x500/style/package-info.java @@ -0,0 +1,4 @@ +/** + * Template classes for the common styles used for converting X.500 names to strings and back. + */ +package org.bouncycastle.asn1.x500.style; diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/AccessDescription.java b/core/src/main/java/org/bouncycastle/asn1/x509/AccessDescription.java index 91450aad91..53082abe58 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/AccessDescription.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/AccessDescription.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.x509; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -83,12 +82,7 @@ public GeneralName getAccessLocation() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector accessDescription = new ASN1EncodableVector(2); - - accessDescription.add(accessMethod); - accessDescription.add(accessLocation); - - return new DERSequence(accessDescription); + return new DERSequence(accessMethod, accessLocation); } public String toString() diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/AttCertValidityPeriod.java b/core/src/main/java/org/bouncycastle/asn1/x509/AttCertValidityPeriod.java index dcda7f885f..4e31072bc5 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/AttCertValidityPeriod.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/AttCertValidityPeriod.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.x509; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -74,11 +73,6 @@ public ASN1GeneralizedTime getNotAfterTime() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(notBeforeTime); - v.add(notAfterTime); - - return new DERSequence(v); + return new DERSequence(notBeforeTime, notAfterTime); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/Attribute.java b/core/src/main/java/org/bouncycastle/asn1/x509/Attribute.java index afe1d4ee9b..c2050b7aaa 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/Attribute.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/Attribute.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -83,11 +82,6 @@ public ASN1Set getAttrValues() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(attrType); - v.add(attrValues); - - return new DERSequence(v); + return new DERSequence(attrType, attrValues); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/Certificate.java b/core/src/main/java/org/bouncycastle/asn1/x509/Certificate.java index e64a197572..1a4ddab72e 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/Certificate.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/Certificate.java @@ -1,11 +1,13 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1BitString; +import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x500.X500Name; /** @@ -69,6 +71,32 @@ private Certificate( } } + public Certificate(TBSCertificate tbsCertificate, AlgorithmIdentifier signatureAlgorithm, ASN1BitString signature) + { + if (tbsCertificate == null) + { + throw new NullPointerException("'tbsCertificate' cannot be null"); + } + if (signatureAlgorithm == null) + { + throw new NullPointerException("'signatureAlgorithm' cannot be null"); + } + if (signature == null) + { + throw new NullPointerException("'signature' cannot be null"); + } + + this.tbsCert = tbsCertificate; + this.sigAlgId = signatureAlgorithm; + this.sig = signature; + + ASN1EncodableVector v = new ASN1EncodableVector(3); + v.add(tbsCertificate); + v.add(signatureAlgorithm); + v.add(signature); + this.seq = new DERSequence(v); + } + public TBSCertificate getTBSCertificate() { return tbsCert; @@ -94,6 +122,11 @@ public X500Name getIssuer() return tbsCert.getIssuer(); } + public Validity getValidity() + { + return tbsCert.getValidity(); + } + public Time getStartDate() { return tbsCert.getStartDate(); @@ -114,6 +147,21 @@ public SubjectPublicKeyInfo getSubjectPublicKeyInfo() return tbsCert.getSubjectPublicKeyInfo(); } + public ASN1BitString getIssuerUniqueID() + { + return tbsCert.getIssuerUniqueId(); + } + + public ASN1BitString getSubjectUniqueID() + { + return tbsCert.getSubjectUniqueId(); + } + + public Extensions getExtensions() + { + return tbsCert.getExtensions(); + } + public AlgorithmIdentifier getSignatureAlgorithm() { return sigAlgId; diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/CertificateList.java b/core/src/main/java/org/bouncycastle/asn1/x509/CertificateList.java index c4c14d9947..dc848c6519 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/CertificateList.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/CertificateList.java @@ -117,6 +117,11 @@ public Time getNextUpdate() return tbsCertList.getNextUpdate(); } + public Extensions getExtensions() + { + return tbsCertList.getExtensions(); + } + public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(3); diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/DeltaCertificateDescriptor.java b/core/src/main/java/org/bouncycastle/asn1/x509/DeltaCertificateDescriptor.java index d562595a6b..ad2aa01307 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/DeltaCertificateDescriptor.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/DeltaCertificateDescriptor.java @@ -17,32 +17,28 @@ /** *

    - *     DeltaCertificateDescriptor ::= SEQUENCE {
    - *      serialNumber          CertificateSerialNumber,
    - *      signature             [0] IMPLICIT AlgorithmIdentifier
    - *           {SIGNATURE_ALGORITHM, {...}} OPTIONAL,
    - *      issuer                [1] IMPLICIT Name OPTIONAL,
    - *      validity              [2] IMPLICIT Validity OPTIONAL,
    - *      subject               [3] IMPLICIT Name OPTIONAL,
    - *      subjectPublicKeyInfo  SubjectPublicKeyInfo,
    - *      extensions            [4] IMPLICIT Extensions{CertExtensions}
    - *           OPTIONAL,
    - *      signatureValue        BIT STRING
    - *    }
    - *    
    + * DeltaCertificateDescriptor ::= SEQUENCE { + * serialNumber CertificateSerialNumber, + * signature [0] EXPLICIT AlgorithmIdentifier {SIGNATURE_ALGORITHM, {...}} OPTIONAL, + * issuer [1] EXPLICIT Name OPTIONAL, + * validity [2] EXPLICIT Validity OPTIONAL, + * subject [3] EXPLICIT Name OPTIONAL, + * subjectPublicKeyInfo SubjectPublicKeyInfo, + * extensions [4] EXPLICIT Extensions{CertExtensions} OPTIONAL, + * signatureValue BIT STRING + * } + * */ public class DeltaCertificateDescriptor extends ASN1Object { private final ASN1Integer serialNumber; - - private AlgorithmIdentifier signature; - private X500Name issuer; - private ASN1Sequence validity; - private X500Name subject; - private SubjectPublicKeyInfo subjectPublicKeyInfo; - private Extensions extensions; - + private final AlgorithmIdentifier signature; + private final X500Name issuer; + private final Validity validity; + private final X500Name subject; + private final SubjectPublicKeyInfo subjectPublicKeyInfo; + private final Extensions extensions; private final ASN1BitString signatureValue; public static DeltaCertificateDescriptor getInstance( @@ -73,23 +69,28 @@ public static DeltaCertificateDescriptor fromExtensions(Extensions extensions) private DeltaCertificateDescriptor(ASN1Sequence seq) { - this.serialNumber = ASN1Integer.getInstance(seq.getObjectAt(0)); + ASN1Integer serialNumber = ASN1Integer.getInstance(seq.getObjectAt(0)); int idx = 1; - ASN1Encodable next = seq.getObjectAt(idx); + ASN1Encodable next = seq.getObjectAt(idx++); + + AlgorithmIdentifier signature = null; + X500Name issuer = null; + Validity validity = null; + X500Name subject = null; while (next instanceof ASN1TaggedObject) { ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(next); switch (tagged.getTagNo()) { case 0: - signature = AlgorithmIdentifier.getInstance(tagged, false); + signature = AlgorithmIdentifier.getInstance(tagged, true); break; case 1: issuer = X500Name.getInstance(tagged, true); // issuer break; case 2: - validity = ASN1Sequence.getInstance(tagged, false); + validity = Validity.getInstance(tagged, true); break; case 3: subject = X500Name.getInstance(tagged, true); // subject @@ -98,22 +99,60 @@ private DeltaCertificateDescriptor(ASN1Sequence seq) next = seq.getObjectAt(idx++); } - subjectPublicKeyInfo = subjectPublicKeyInfo.getInstance(next); + SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(next); next = seq.getObjectAt(idx); + + Extensions extensions = null; while (next instanceof ASN1TaggedObject) { ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(next); switch (tagged.getTagNo()) { case 4: - extensions = Extensions.getInstance(tagged, false); + extensions = Extensions.getInstance(tagged, true); break; } next = seq.getObjectAt(idx++); } - signatureValue = ASN1BitString.getInstance(next); + ASN1BitString signatureValue = ASN1BitString.getInstance(next); + + this.serialNumber = serialNumber; + this.signature = signature; + this.issuer = issuer; + this.validity = validity; + this.subject = subject; + this.subjectPublicKeyInfo = subjectPublicKeyInfo; + this.extensions = extensions; + this.signatureValue = signatureValue; + } + + public DeltaCertificateDescriptor(ASN1Integer serialNumber, AlgorithmIdentifier signature, X500Name issuer, + Validity validity, X500Name subject, SubjectPublicKeyInfo subjectPublicKeyInfo, Extensions extensions, + ASN1BitString signatureValue) + { + if (serialNumber == null) + { + throw new NullPointerException("'serialNumber' cannot be null"); + } + if (subjectPublicKeyInfo == null) + { + throw new NullPointerException("'subjectPublicKeyInfo' cannot be null"); + } + if (signatureValue == null) + { + throw new NullPointerException("'signatureValue' cannot be null"); + } + + this.serialNumber = serialNumber; + this.signature = signature; + this.issuer = issuer; + this.validity = validity; + this.subject = subject; + this.subjectPublicKeyInfo = subjectPublicKeyInfo; + this.extensions = extensions; + this.signatureValue = signatureValue; } public ASN1Integer getSerialNumber() @@ -131,7 +170,13 @@ public X500Name getIssuer() return issuer; } + /** @deprecated Use getValidityObject instead. */ public ASN1Sequence getValidity() + { + return (ASN1Sequence)validity.toASN1Primitive(); + } + + public Validity getValidityObject() { return validity; } @@ -156,96 +201,83 @@ public ASN1BitString getSignatureValue() return signatureValue; } + /** @deprecated Use DeltaCertificateTool#trimDeltaCertificateDescriptor instead. */ public DeltaCertificateDescriptor trimTo(TBSCertificate baseTbsCertificate, Extensions tbsExtensions) { - AlgorithmIdentifier signature = baseTbsCertificate.signature; - X500Name issuer = baseTbsCertificate.issuer; - ASN1Sequence validity = new DERSequence(new ASN1Encodable[] + return trimDeltaCertificateDescriptor(this, baseTbsCertificate, tbsExtensions); + } + + // NB: This can replace DeltaCertificateTool#trimDeltaCertificateDescriptor once 'trimTo' is removed + private static DeltaCertificateDescriptor trimDeltaCertificateDescriptor(DeltaCertificateDescriptor descriptor, + TBSCertificate tbsCertificate, Extensions tbsExtensions) + { + ASN1Integer serialNumber = descriptor.getSerialNumber(); + + AlgorithmIdentifier signature = descriptor.getSignature(); + if (signature != null && signature.equals(tbsCertificate.getSignature())) { - baseTbsCertificate.startDate, baseTbsCertificate.endDate - }); - X500Name subject = baseTbsCertificate.subject; - ASN1Sequence s = ASN1Sequence.getInstance(toASN1Primitive()); - ASN1EncodableVector v = new ASN1EncodableVector(); + signature = null; + } - Enumeration en = s.getObjects(); - v.add((ASN1Encodable)en.nextElement()); + X500Name issuer = descriptor.getIssuer(); + if (issuer != null && issuer.equals(tbsCertificate.getIssuer())) + { + issuer = null; + } - ASN1Encodable next = (ASN1Encodable)en.nextElement(); - while (next instanceof ASN1TaggedObject) + Validity validity = descriptor.getValidityObject(); + if (validity != null && validity.equals(tbsCertificate.getValidity())) { - ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(next); - switch (tagged.getTagNo()) - { - case 0: - AlgorithmIdentifier sig = AlgorithmIdentifier.getInstance(tagged, false); - if (!sig.equals(signature)) - { - v.add(next); - } - break; - case 1: - X500Name iss = X500Name.getInstance(tagged, true); // issuer - if (!iss.equals(issuer)) - { - v.add(next); - } - break; - case 2: - ASN1Sequence val = ASN1Sequence.getInstance(tagged, false); - if (!val.equals(validity)) - { - v.add(next); - } - break; - case 3: - X500Name sub = X500Name.getInstance(tagged, true); // subject - if (!sub.equals(subject)) - { - v.add(next); - } - break; - } - next = (ASN1Encodable)en.nextElement(); + validity = null; } - v.add(next); + X500Name subject = descriptor.getSubject(); + if (subject != null && subject.equals(tbsCertificate.getSubject())) + { + subject = null; + } - next = (ASN1Encodable)en.nextElement(); - while (next instanceof ASN1TaggedObject) + SubjectPublicKeyInfo subjectPublicKeyInfo = descriptor.getSubjectPublicKeyInfo(); + + Extensions extensions = descriptor.getExtensions(); + if (extensions != null) { - ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(next); - switch (tagged.getTagNo()) + /* + * draft-bonnell-lamps-chameleon-certs-05 4.1: + * + * [The extensions] field MUST NOT contain any extension: + * - which has the same criticality and DER-encoded value as encoded in the Base Certificate, + * - whose type does not appear in the Base Certificate, or + * - which is of the DCD extension type (recursive Delta Certificates are not permitted). + * + * [...] The ordering of extensions in [the extensions] field MUST be relative to the ordering of the + * extensions as they are encoded in the Delta [recte Base] Certificate. + */ + + ExtensionsGenerator generator = new ExtensionsGenerator(); + + for (Enumeration extEn = tbsExtensions.oids(); extEn.hasMoreElements();) { - case 4: - Extensions deltaExts = Extensions.getInstance(tagged, false); - ExtensionsGenerator deltaExtGen = new ExtensionsGenerator(); - for (Enumeration extEn = deltaExts.oids(); extEn.hasMoreElements(); ) + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)extEn.nextElement(); + if (Extension.deltaCertificateDescriptor.equals(oid)) { - Extension deltaExt = deltaExts.getExtension((ASN1ObjectIdentifier)extEn.nextElement()); - Extension primaryExt = tbsExtensions.getExtension(deltaExt.getExtnId()); - - if (primaryExt != null) - { - if (!deltaExt.equals(primaryExt)) - { - deltaExtGen.addExtension(deltaExt); - } - } + continue; } - DeltaCertificateDescriptor trimmedDeltaCertDesc; - if (!deltaExtGen.isEmpty()) + Extension deltaExtension = extensions.getExtension(oid); + if (deltaExtension != null && !deltaExtension.equals(tbsExtensions.getExtension(oid))) { - v.add(new DERTaggedObject(false, 4, deltaExtGen.generate())); + generator.addExtension(deltaExtension); } } - next = (ASN1Encodable)en.nextElement(); + + extensions = generator.isEmpty() ? null : generator.generate(); } - v.add(next); + ASN1BitString signatureValue = descriptor.getSignatureValue(); - return new DeltaCertificateDescriptor(new DERSequence(v)); + return new DeltaCertificateDescriptor(serialNumber, signature, issuer, validity, subject, + subjectPublicKeyInfo, extensions, signatureValue); } private void addOptional(ASN1EncodableVector v, int tag, boolean explicit, ASN1Object obj) @@ -258,15 +290,15 @@ private void addOptional(ASN1EncodableVector v, int tag, boolean explicit, ASN1O public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(7); + ASN1EncodableVector v = new ASN1EncodableVector(8); v.add(serialNumber); - addOptional(v, 0, false, signature); + addOptional(v, 0, true, signature); addOptional(v, 1, true, issuer); // CHOICE - addOptional(v, 2, false, validity); + addOptional(v, 2, true, validity); addOptional(v, 3, true, subject); // CHOICE v.add(subjectPublicKeyInfo); - addOptional(v, 4, false, extensions); + addOptional(v, 4, true, extensions); v.add(signatureValue); return new DERSequence(v); diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/DigestInfo.java b/core/src/main/java/org/bouncycastle/asn1/x509/DigestInfo.java index 245b0ddf54..680a8496ca 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/DigestInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/DigestInfo.java @@ -2,7 +2,6 @@ import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; @@ -77,11 +76,6 @@ public byte[] getDigest() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(algId); - v.add(new DEROctetString(digest)); - - return new DERSequence(v); + return new DERSequence(algId, new DEROctetString(digest)); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/DistributionPointName.java b/core/src/main/java/org/bouncycastle/asn1/x509/DistributionPointName.java index f69ccb3a40..078c577afc 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/DistributionPointName.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/DistributionPointName.java @@ -6,6 +6,7 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.ASN1Util; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.util.Strings; @@ -22,21 +23,10 @@ public class DistributionPointName extends ASN1Object implements ASN1Choice { - ASN1Encodable name; - int type; - public static final int FULL_NAME = 0; public static final int NAME_RELATIVE_TO_CRL_ISSUER = 1; - public static DistributionPointName getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - return getInstance(ASN1TaggedObject.getInstance(obj, true)); - } - - public static DistributionPointName getInstance( - Object obj) + public static DistributionPointName getInstance(Object obj) { if (obj == null || obj instanceof DistributionPointName) { @@ -50,6 +40,19 @@ else if (obj instanceof ASN1TaggedObject) throw new IllegalArgumentException("unknown object in factory: " + obj.getClass().getName()); } + public static DistributionPointName getInstance(ASN1TaggedObject taggedObject, boolean declaredExplicit) + { + return getInstance(ASN1Util.getInstanceChoiceBaseObject(taggedObject, declaredExplicit, "DistributionPointName")); + } + + public static DistributionPointName getTagged(ASN1TaggedObject taggedObject, boolean declaredExplicit) + { + return getInstance(ASN1Util.getTaggedChoiceBaseObject(taggedObject, declaredExplicit, "DistributionPointName")); + } + + private final ASN1Encodable name; + private final int type; + public DistributionPointName( int type, ASN1Encodable name) @@ -83,22 +86,25 @@ public ASN1Encodable getName() { return (ASN1Encodable)name; } - - public DistributionPointName( - ASN1TaggedObject obj) + + public DistributionPointName(ASN1TaggedObject obj) { this.type = obj.getTagNo(); - - if (type == 0) + + if (obj.hasContextTag(FULL_NAME)) { this.name = GeneralNames.getInstance(obj, false); } - else + else if (obj.hasContextTag(NAME_RELATIVE_TO_CRL_ISSUER)) { this.name = ASN1Set.getInstance(obj, false); } + else + { + throw new IllegalArgumentException("unknown tag: " + ASN1Util.getTagText(obj)); + } } - + public ASN1Primitive toASN1Primitive() { return new DERTaggedObject(false, type, name); diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/Extension.java b/core/src/main/java/org/bouncycastle/asn1/x509/Extension.java index 95cf846d20..d01d5a141b 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/Extension.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/Extension.java @@ -266,7 +266,7 @@ public static Extension create( ASN1Encodable value) throws IOException { - return new Extension(extnId, critical, value.toASN1Primitive().getEncoded()); + return new Extension(extnId, critical, new DEROctetString(value.toASN1Primitive().getEncoded())); } private Extension(ASN1Sequence seq) diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/Extensions.java b/core/src/main/java/org/bouncycastle/asn1/x509/Extensions.java index c552d370b7..4434183613 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/Extensions.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/Extensions.java @@ -8,6 +8,7 @@ import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; @@ -40,6 +41,11 @@ public static ASN1Encodable getExtensionParsedValue(Extensions extensions, ASN1O return null == extensions ? null : extensions.getExtensionParsedValue(oid); } + public static ASN1OctetString getExtensionValue(Extensions extensions, ASN1ObjectIdentifier oid) + { + return null == extensions ? null : extensions.getExtensionValue(oid); + } + public static Extensions getInstance( ASN1TaggedObject obj, boolean explicit) @@ -141,8 +147,7 @@ public Enumeration oids() * * @return the extension if it's present, null otherwise. */ - public Extension getExtension( - ASN1ObjectIdentifier oid) + public Extension getExtension(ASN1ObjectIdentifier oid) { return (Extension)extensions.get(oid); } @@ -155,14 +160,19 @@ public Extension getExtension( */ public ASN1Encodable getExtensionParsedValue(ASN1ObjectIdentifier oid) { - Extension ext = this.getExtension(oid); - - if (ext != null) - { - return ext.getParsedValue(); - } + Extension ext = getExtension(oid); + return ext == null ? null : ext.getParsedValue(); + } - return null; + /** + * return the value of the extension represented by the object identifier passed in. + * + * @return the value of the extension if it's present, null otherwise. + */ + public ASN1OctetString getExtensionValue(ASN1ObjectIdentifier oid) + { + Extension ext = getExtension(oid); + return ext == null ? null : ext.getExtnValue(); } /** @@ -229,6 +239,21 @@ public ASN1ObjectIdentifier[] getCriticalExtensionOIDs() return getExtensionOIDs(true); } + public boolean hasAnyCriticalExtensions() + { + for (int i = 0; i != ordering.size(); i++) + { + Object oid = ordering.elementAt(i); + + if (((Extension)extensions.get(oid)).isCritical()) + { + return true; + } + } + + return false; + } + private ASN1ObjectIdentifier[] getExtensionOIDs(boolean isCritical) { Vector oidVec = new Vector(); diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/ExtensionsGenerator.java b/core/src/main/java/org/bouncycastle/asn1/x509/ExtensionsGenerator.java index e5726d3442..46fbcd190b 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/ExtensionsGenerator.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/ExtensionsGenerator.java @@ -16,7 +16,6 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.util.Arrays; /** * Generator for X.509 extensions @@ -55,13 +54,17 @@ public void reset() * @param critical true if critical, false otherwise. * @param value the ASN.1 object to be included in the extension. */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - throws IOException + public void addExtension(ASN1ObjectIdentifier oid, boolean critical, ASN1Encodable value) throws IOException { - this.addExtension(oid, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); + Extension existingExtension = (Extension)extensions.get(oid); + if (existingExtension != null) + { + implAddExtensionDup(existingExtension, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); + } + else + { + implAddExtension(new Extension(oid, critical, new DEROctetString(value))); + } } /** @@ -72,47 +75,16 @@ public void addExtension( * @param critical true if critical, false otherwise. * @param value the byte array to be wrapped. */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) + public void addExtension(ASN1ObjectIdentifier oid, boolean critical, byte[] value) { - if (extensions.containsKey(oid)) + Extension existingExtension = (Extension)extensions.get(oid); + if (existingExtension != null) { - if (dupsAllowed.contains(oid)) - { - Extension existingExtension = (Extension)extensions.get(oid); - ASN1Sequence seq1 = ASN1Sequence.getInstance(DEROctetString.getInstance(existingExtension.getExtnValue()).getOctets()); - ASN1Sequence seq2 = ASN1Sequence.getInstance(value); - - ASN1EncodableVector items = new ASN1EncodableVector(seq1.size() + seq2.size()); - for (Enumeration en = seq1.getObjects(); en.hasMoreElements();) - { - items.add((ASN1Encodable)en.nextElement()); - } - for (Enumeration en = seq2.getObjects(); en.hasMoreElements();) - { - items.add((ASN1Encodable)en.nextElement()); - } - - try - { - extensions.put(oid, new Extension(oid, critical, new DERSequence(items).getEncoded())); - } - catch (IOException e) - { - throw new ASN1ParsingException(e.getMessage(), e); - } - } - else - { - throw new IllegalArgumentException("extension " + oid + " already added"); - } + implAddExtensionDup(existingExtension, critical, value); } else { - extOrdering.addElement(oid); - extensions.put(oid, new Extension(oid, critical, new DEROctetString(Arrays.clone(value)))); + implAddExtension(new Extension(oid, critical, value)); } } @@ -124,15 +96,31 @@ public void addExtension( public void addExtension( Extension extension) { - if (extensions.containsKey(extension.getExtnId())) + if (hasExtension(extension.getExtnId())) { throw new IllegalArgumentException("extension " + extension.getExtnId() + " already added"); } - extOrdering.addElement(extension.getExtnId()); - extensions.put(extension.getExtnId(), extension); + implAddExtension(extension); + } + + /** @deprecated Use addExtensions instead. */ + public void addExtension(Extensions extensions) + { + addExtensions(extensions); } + public void addExtensions(Extensions extensions) + { + ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); + for (int i = 0; i != oids.length; i++) + { + ASN1ObjectIdentifier ident = oids[i]; + Extension ext = extensions.getExtension(ident); + addExtension(ASN1ObjectIdentifier.getInstance(ident), ext.isCritical(), ext.getExtnValue().getOctets()); + } + } + /** * Replace an extension with the given oid and the passed in value to be included * in the OCTET STRING associated with the extension. @@ -147,7 +135,7 @@ public void replaceExtension( ASN1Encodable value) throws IOException { - this.replaceExtension(oid, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); + replaceExtension(new Extension(oid, critical, new DEROctetString(value))); } /** @@ -163,7 +151,7 @@ public void replaceExtension( boolean critical, byte[] value) { - this.replaceExtension(new Extension(oid, critical, value)); + replaceExtension(new Extension(oid, critical, value)); } /** @@ -174,7 +162,7 @@ public void replaceExtension( public void replaceExtension( Extension extension) { - if (!extensions.containsKey(extension.getExtnId())) + if (!hasExtension(extension.getExtnId())) { throw new IllegalArgumentException("extension " + extension.getExtnId() + " not present"); } @@ -190,7 +178,7 @@ public void replaceExtension( public void removeExtension( ASN1ObjectIdentifier oid) { - if (!extensions.containsKey(oid)) + if (!hasExtension(oid)) { throw new IllegalArgumentException("extension " + oid + " not present"); } @@ -203,7 +191,7 @@ public void removeExtension( * Return if the extension indicated by OID is present. * * @param oid the OID for the extension of interest. - * @return the Extension, or null if it is not present. + * @return true if a matching extension is present, false otherwise. */ public boolean hasExtension(ASN1ObjectIdentifier oid) { @@ -214,7 +202,7 @@ public boolean hasExtension(ASN1ObjectIdentifier oid) * Return the current value of the extension for OID. * * @param oid the OID for the extension we want to fetch. - * @return true if a matching extension is present, false otherwise. + * @return the Extension, or null if it is not present. */ public Extension getExtension(ASN1ObjectIdentifier oid) { @@ -248,14 +236,41 @@ public Extensions generate() return new Extensions(exts); } - public void addExtension(Extensions extensions) + private void implAddExtension(Extension extension) { - ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); - for (int i = 0; i != oids.length; i++) + extOrdering.addElement(extension.getExtnId()); + extensions.put(extension.getExtnId(), extension); + } + + private void implAddExtensionDup(Extension existingExtension, boolean critical, byte[] value) + { + ASN1ObjectIdentifier oid = existingExtension.getExtnId(); + if (!dupsAllowed.contains(oid)) { - ASN1ObjectIdentifier ident = oids[i]; - Extension ext = extensions.getExtension(ident); - addExtension(ASN1ObjectIdentifier.getInstance(ident), ext.isCritical(), ext.getExtnValue().getOctets()); + throw new IllegalArgumentException("extension " + oid + " already added"); + } + + ASN1Sequence seq1 = ASN1Sequence.getInstance( + DEROctetString.getInstance(existingExtension.getExtnValue()).getOctets()); + ASN1Sequence seq2 = ASN1Sequence.getInstance(value); + + ASN1EncodableVector items = new ASN1EncodableVector(seq1.size() + seq2.size()); + for (Enumeration en = seq1.getObjects(); en.hasMoreElements();) + { + items.add((ASN1Encodable)en.nextElement()); + } + for (Enumeration en = seq2.getObjects(); en.hasMoreElements();) + { + items.add((ASN1Encodable)en.nextElement()); + } + + try + { + extensions.put(oid, new Extension(oid, critical, new DEROctetString(new DERSequence(items)))); + } + catch (IOException e) + { + throw new ASN1ParsingException(e.getMessage(), e); } } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/IssuingDistributionPoint.java b/core/src/main/java/org/bouncycastle/asn1/x509/IssuingDistributionPoint.java index ef78f62aa7..12230cec1f 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/IssuingDistributionPoint.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/IssuingDistributionPoint.java @@ -84,6 +84,12 @@ public IssuingDistributionPoint( boolean indirectCRL, boolean onlyContainsAttributeCerts) { + if ((onlyContainsCACerts && (onlyContainsUserCerts || onlyContainsAttributeCerts)) + || (onlyContainsUserCerts && onlyContainsAttributeCerts)) + { + throw new IllegalArgumentException("only one of onlyContainsCACerts, onlyContainsUserCerts, or onlyContainsAttributeCerts can be true"); + } + this.distributionPoint = distributionPoint; this.indirectCRL = indirectCRL; this.onlyContainsAttributeCerts = onlyContainsAttributeCerts; diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/NoticeReference.java b/core/src/main/java/org/bouncycastle/asn1/x509/NoticeReference.java index 1736209793..5e95972185 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/NoticeReference.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/NoticeReference.java @@ -161,9 +161,6 @@ public ASN1Integer[] getNoticeNumbers() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector av = new ASN1EncodableVector(2); - av.add (organization); - av.add (noticeNumbers); - return new DERSequence (av); + return new DERSequence(organization, noticeNumbers); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/OtherName.java b/core/src/main/java/org/bouncycastle/asn1/x509/OtherName.java index 989d0d190d..0693d63391 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/OtherName.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/OtherName.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -82,11 +81,6 @@ public ASN1Encodable getValue() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(typeID); - v.add(new DERTaggedObject(true, 0, value)); - - return new DERSequence(v); + return new DERSequence(typeID, new DERTaggedObject(true, 0, value)); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/PolicyMappings.java b/core/src/main/java/org/bouncycastle/asn1/x509/PolicyMappings.java index 2ef26bc109..96ebba3f01 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/PolicyMappings.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/PolicyMappings.java @@ -67,10 +67,8 @@ public PolicyMappings(Hashtable mappings) { String idp = (String)it.nextElement(); String sdp = (String)mappings.get(idp); - ASN1EncodableVector dv = new ASN1EncodableVector(2); - dv.add(new ASN1ObjectIdentifier(idp)); - dv.add(new ASN1ObjectIdentifier(sdp)); - dev.add(new DERSequence(dv)); + + dev.add(new DERSequence(new ASN1ObjectIdentifier(idp), new ASN1ObjectIdentifier(sdp))); } seq = new DERSequence(dev); @@ -78,11 +76,7 @@ public PolicyMappings(Hashtable mappings) public PolicyMappings(CertPolicyId issuerDomainPolicy, CertPolicyId subjectDomainPolicy) { - ASN1EncodableVector dv = new ASN1EncodableVector(2); - dv.add(issuerDomainPolicy); - dv.add(subjectDomainPolicy); - - seq = new DERSequence(new DERSequence(dv)); + seq = new DERSequence(new DERSequence(issuerDomainPolicy, subjectDomainPolicy)); } public PolicyMappings(CertPolicyId[] issuerDomainPolicy, CertPolicyId[] subjectDomainPolicy) @@ -91,10 +85,7 @@ public PolicyMappings(CertPolicyId[] issuerDomainPolicy, CertPolicyId[] subjectD for (int i = 0; i != issuerDomainPolicy.length; i++) { - ASN1EncodableVector dv = new ASN1EncodableVector(2); - dv.add(issuerDomainPolicy[i]); - dv.add(subjectDomainPolicy[i]); - dev.add(new DERSequence(dv)); + dev.add(new DERSequence(issuerDomainPolicy[i], subjectDomainPolicy[i])); } seq = new DERSequence(dev); diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/PolicyQualifierInfo.java b/core/src/main/java/org/bouncycastle/asn1/x509/PolicyQualifierInfo.java index 9b4a54f0c1..67ff5d9706 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/PolicyQualifierInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/PolicyQualifierInfo.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -108,11 +107,7 @@ public ASN1Encodable getQualifier() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector dev = new ASN1EncodableVector(2); - dev.add(policyQualifierId); - dev.add(qualifier); - - return new DERSequence(dev); + return new DERSequence(policyQualifierId, qualifier); } public String toString() diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/PrivateKeyStatement.java b/core/src/main/java/org/bouncycastle/asn1/x509/PrivateKeyStatement.java new file mode 100644 index 0000000000..f03c66886b --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x509/PrivateKeyStatement.java @@ -0,0 +1,91 @@ +package org.bouncycastle.asn1.x509; + +import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1Object; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber; + +/** + *
    + * PrivateKeyStatement ::= SEQUENCE {
    + *       signer  IssuerAndSerialNumber,
    + *       cert    Certificate OPTIONAL }
    + * 
    + */ +public class PrivateKeyStatement + extends ASN1Object +{ + private final IssuerAndSerialNumber signer; + private final Certificate cert; + + public static PrivateKeyStatement getInstance(Object obj) + { + if (obj instanceof PrivateKeyStatement) + { + return (PrivateKeyStatement)obj; + } + + if (obj != null) + { + return new PrivateKeyStatement(ASN1Sequence.getInstance(obj)); + } + + return null; + } + + private PrivateKeyStatement(ASN1Sequence seq) + { + if (seq.size() == 1) + { + this.signer = IssuerAndSerialNumber.getInstance(seq.getObjectAt(0)); + this.cert = null; + } + else if (seq.size() == 2) + { + this.signer = IssuerAndSerialNumber.getInstance(seq.getObjectAt(0)); + this.cert = Certificate.getInstance(seq.getObjectAt(1)); + } + else + { + throw new IllegalArgumentException("unknown sequence in PrivateKeyStatement"); + } + } + + public PrivateKeyStatement(IssuerAndSerialNumber signer) + { + this.signer = signer; + this.cert = null; + } + + public PrivateKeyStatement(Certificate cert) + { + this.signer = new IssuerAndSerialNumber(cert.getIssuer(), cert.getSerialNumber().getValue()); + this.cert = cert; + } + + public IssuerAndSerialNumber getSigner() + { + return signer; + } + + public Certificate getCert() + { + return cert; + } + + public ASN1Primitive toASN1Primitive() + { + ASN1EncodableVector v = new ASN1EncodableVector(2); + + v.add(signer); + + if (cert != null) + { + v.add(cert); + } + + return new DERSequence(v); + } +} diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/RSAPublicKeyStructure.java b/core/src/main/java/org/bouncycastle/asn1/x509/RSAPublicKeyStructure.java index 7ba9e3b02c..d857387a51 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/RSAPublicKeyStructure.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/RSAPublicKeyStructure.java @@ -3,7 +3,6 @@ import java.math.BigInteger; import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -88,11 +87,6 @@ public BigInteger getPublicExponent() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(new ASN1Integer(getModulus())); - v.add(new ASN1Integer(getPublicExponent())); - - return new DERSequence(v); + return new DERSequence(new ASN1Integer(getModulus()), new ASN1Integer(getPublicExponent())); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/SubjectAltPublicKeyInfo.java b/core/src/main/java/org/bouncycastle/asn1/x509/SubjectAltPublicKeyInfo.java index 19e79fdbf5..b6271a4ce6 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/SubjectAltPublicKeyInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/SubjectAltPublicKeyInfo.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1BitString; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -98,11 +97,6 @@ public ASN1BitString getSubjectAltPublicKey() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(algorithm); - v.add(subjectAltPublicKey); - - return new DERSequence(v); + return new DERSequence(algorithm, subjectAltPublicKey); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/SubjectPublicKeyInfo.java b/core/src/main/java/org/bouncycastle/asn1/x509/SubjectPublicKeyInfo.java index 9c2241cb2b..2e8dad1a60 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/SubjectPublicKeyInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/SubjectPublicKeyInfo.java @@ -5,7 +5,6 @@ import org.bouncycastle.asn1.ASN1BitString; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -153,11 +152,6 @@ public ASN1BitString getPublicKeyData() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(algId); - v.add(keyData); - - return new DERSequence(v); + return new DERSequence(algId, keyData); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificate.java b/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificate.java index 76763291b6..66716c0247 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificate.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificate.java @@ -41,7 +41,7 @@ public class TBSCertificate ASN1Integer serialNumber; AlgorithmIdentifier signature; X500Name issuer; - Time startDate, endDate; + Validity validity; X500Name subject; SubjectPublicKeyInfo subjectPublicKeyInfo; ASN1BitString issuerUniqueId; @@ -110,20 +110,8 @@ else if (!version.hasValue(2)) signature = AlgorithmIdentifier.getInstance(seq.getObjectAt(seqStart + 2)); issuer = X500Name.getInstance(seq.getObjectAt(seqStart + 3)); - - // - // before and after dates - // - ASN1Sequence dates = (ASN1Sequence)seq.getObjectAt(seqStart + 4); - - startDate = Time.getInstance(dates.getObjectAt(0)); - endDate = Time.getInstance(dates.getObjectAt(1)); - + validity = Validity.getInstance(seq.getObjectAt(seqStart + 4)); subject = X500Name.getInstance(seq.getObjectAt(seqStart + 5)); - - // - // public key info. - // subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(seqStart + 6)); int extras = seq.size() - (seqStart + 6) - 1; @@ -158,6 +146,49 @@ else if (!version.hasValue(2)) } } + public TBSCertificate(ASN1Integer version, ASN1Integer serialNumber, AlgorithmIdentifier signature, + X500Name issuer, Validity validity, X500Name subject, SubjectPublicKeyInfo subjectPublicKeyInfo, + ASN1BitString issuerUniqueId, ASN1BitString subjectUniqueId, Extensions extensions) + { + if (serialNumber == null) + { + throw new NullPointerException("'serialNumber' cannot be null"); + } + if (signature == null) + { + throw new NullPointerException("'signature' cannot be null"); + } + if (issuer == null) + { + throw new NullPointerException("'issuer' cannot be null"); + } + if (validity == null) + { + throw new NullPointerException("'validity' cannot be null"); + } + if (subject == null) + { + throw new NullPointerException("'subject' cannot be null"); + } + if (subjectPublicKeyInfo == null) + { + throw new NullPointerException("'subjectPublicKeyInfo' cannot be null"); + } + + this.version = version != null ? version : new ASN1Integer(0); + this.serialNumber = serialNumber; + this.signature = signature; + this.issuer = issuer; + this.validity = validity; + this.subject = subject; + this.subjectPublicKeyInfo = subjectPublicKeyInfo; + this.issuerUniqueId = issuerUniqueId; + this.subjectUniqueId = subjectUniqueId; + this.extensions = extensions; + + this.seq = null; + } + public int getVersionNumber() { return version.intValueExact() + 1; @@ -183,14 +214,19 @@ public X500Name getIssuer() return issuer; } + public Validity getValidity() + { + return validity; + } + public Time getStartDate() { - return startDate; + return validity.getNotBefore(); } public Time getEndDate() { - return endDate; + return validity.getNotAfter(); } public X500Name getSubject() @@ -220,19 +256,22 @@ public Extensions getExtensions() public ASN1Primitive toASN1Primitive() { - if (Properties.getPropertyValue("org.bouncycastle.x509.allow_non-der_tbscert") != null) + if (seq != null) { - if (Properties.isOverrideSet("org.bouncycastle.x509.allow_non-der_tbscert")) + if (Properties.getPropertyValue("org.bouncycastle.x509.allow_non-der_tbscert") != null) + { + if (Properties.isOverrideSet("org.bouncycastle.x509.allow_non-der_tbscert")) + { + return seq; + } + } + else { return seq; } } - else - { - return seq; - } - ASN1EncodableVector v = new ASN1EncodableVector(); + ASN1EncodableVector v = new ASN1EncodableVector(10); // DEFAULT Zero if (!version.hasValue(0)) @@ -243,27 +282,8 @@ public ASN1Primitive toASN1Primitive() v.add(serialNumber); v.add(signature); v.add(issuer); - - // - // before and after dates - // - { - ASN1EncodableVector validity = new ASN1EncodableVector(2); - validity.add(startDate); - validity.add(endDate); - - v.add(new DERSequence(validity)); - } - - if (subject != null) - { - v.add(subject); - } - else - { - v.add(new DERSequence()); - } - + v.add(validity); + v.add(subject); v.add(subjectPublicKeyInfo); // Note: implicit tag diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificateStructure.java b/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificateStructure.java index 440ca5d29a..3125c7b6b9 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificateStructure.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/TBSCertificateStructure.java @@ -40,7 +40,7 @@ public class TBSCertificateStructure ASN1Integer serialNumber; AlgorithmIdentifier signature; X500Name issuer; - Time startDate, endDate; + Validity validity; X500Name subject; SubjectPublicKeyInfo subjectPublicKeyInfo; ASN1BitString issuerUniqueId; @@ -93,20 +93,8 @@ public TBSCertificateStructure( signature = AlgorithmIdentifier.getInstance(seq.getObjectAt(seqStart + 2)); issuer = X500Name.getInstance(seq.getObjectAt(seqStart + 3)); - - // - // before and after dates - // - ASN1Sequence dates = (ASN1Sequence)seq.getObjectAt(seqStart + 4); - - startDate = Time.getInstance(dates.getObjectAt(0)); - endDate = Time.getInstance(dates.getObjectAt(1)); - + validity = Validity.getInstance(seq.getObjectAt(seqStart + 4)); subject = X500Name.getInstance(seq.getObjectAt(seqStart + 5)); - - // - // public key info. - // subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(seqStart + 6)); for (int extras = seq.size() - (seqStart + 6) - 1; extras > 0; extras--) @@ -152,14 +140,19 @@ public X500Name getIssuer() return issuer; } + public Validity getValidity() + { + return validity; + } + public Time getStartDate() { - return startDate; + return validity.getNotBefore(); } public Time getEndDate() { - return endDate; + return validity.getNotAfter(); } public X500Name getSubject() diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/V1TBSCertificateGenerator.java b/core/src/main/java/org/bouncycastle/asn1/x509/V1TBSCertificateGenerator.java index 9df0b167b1..4d871eeb45 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/V1TBSCertificateGenerator.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/V1TBSCertificateGenerator.java @@ -1,9 +1,7 @@ package org.bouncycastle.asn1.x509; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1UTCTime; -import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.x500.X500Name; @@ -29,6 +27,7 @@ public class V1TBSCertificateGenerator ASN1Integer serialNumber; AlgorithmIdentifier signature; X500Name issuer; + Validity validity; Time startDate, endDate; X500Name subject; SubjectPublicKeyInfo subjectPublicKeyInfo; @@ -64,28 +63,33 @@ public void setIssuer( this.issuer = issuer; } - public void setStartDate( - Time startDate) + public void setValidity(Validity validity) { + this.validity = validity; + this.startDate = null; + this.endDate = null; + } + + public void setStartDate(Time startDate) + { + this.validity = null; this.startDate = startDate; } - public void setStartDate( - ASN1UTCTime startDate) + public void setStartDate(ASN1UTCTime startDate) { - this.startDate = new Time(startDate); + setStartDate(new Time(startDate)); } - public void setEndDate( - Time endDate) + public void setEndDate(Time endDate) { + this.validity = null; this.endDate = endDate; } - public void setEndDate( - ASN1UTCTime endDate) + public void setEndDate(ASN1UTCTime endDate) { - this.endDate = new Time(endDate); + setEndDate(new Time(endDate)); } /** @@ -111,35 +115,15 @@ public void setSubjectPublicKeyInfo( public TBSCertificate generateTBSCertificate() { - if ((serialNumber == null) || (signature == null) - || (issuer == null) || (startDate == null) || (endDate == null) - || (subject == null) || (subjectPublicKeyInfo == null)) + if ((serialNumber == null) || (signature == null) || (issuer == null) || + (validity == null && (startDate == null || endDate == null)) || + (subject == null) || (subjectPublicKeyInfo == null)) { throw new IllegalStateException("not all mandatory fields set in V1 TBScertificate generator"); } - ASN1EncodableVector seq = new ASN1EncodableVector(6); - - // seq.add(version); - not required as default value. - seq.add(serialNumber); - seq.add(signature); - seq.add(issuer); - - // - // before and after dates - // - { - ASN1EncodableVector validity = new ASN1EncodableVector(2); - validity.add(startDate); - validity.add(endDate); - - seq.add(new DERSequence(validity)); - } - - seq.add(subject); - - seq.add(subjectPublicKeyInfo); - - return TBSCertificate.getInstance(new DERSequence(seq)); + return new TBSCertificate(new ASN1Integer(0), serialNumber, signature, issuer, + validity != null ? validity : new Validity(startDate, endDate), subject, subjectPublicKeyInfo, null, + null, null); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/V2TBSCertListGenerator.java b/core/src/main/java/org/bouncycastle/asn1/x509/V2TBSCertListGenerator.java index b68f1bfd5d..0939a1f940 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/V2TBSCertListGenerator.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/V2TBSCertListGenerator.java @@ -264,37 +264,27 @@ private ASN1Sequence generateTBSCertStructure() private static ASN1Sequence createReasonExtension(int reasonCode) { - ASN1EncodableVector v = new ASN1EncodableVector(2); - CRLReason crlReason = CRLReason.lookup(reasonCode); try { - v.add(Extension.reasonCode); - v.add(new DEROctetString(crlReason.getEncoded())); + return new DERSequence(Extension.reasonCode, new DEROctetString(crlReason.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("error encoding reason: " + e); } - - return new DERSequence(v); } private static ASN1Sequence createInvalidityDateExtension(ASN1GeneralizedTime invalidityDate) { - ASN1EncodableVector v = new ASN1EncodableVector(2); - try { - v.add(Extension.invalidityDate); - v.add(new DEROctetString(invalidityDate.getEncoded())); + return new DERSequence(Extension.invalidityDate, new DEROctetString(invalidityDate.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("error encoding reason: " + e); } - - return new DERSequence(v); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/V3TBSCertificateGenerator.java b/core/src/main/java/org/bouncycastle/asn1/x509/V3TBSCertificateGenerator.java index 4434d73ddb..fea58c93b5 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/V3TBSCertificateGenerator.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/V3TBSCertificateGenerator.java @@ -2,7 +2,6 @@ import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1UTCTime; import org.bouncycastle.asn1.DERBitString; @@ -30,11 +29,12 @@ */ public class V3TBSCertificateGenerator { - DERTaggedObject version = new DERTaggedObject(true, 0, new ASN1Integer(2)); + private static final DERTaggedObject VERSION = new DERTaggedObject(true, 0, new ASN1Integer(2)); - ASN1Integer serialNumber; + ASN1Integer serialNumber; AlgorithmIdentifier signature; X500Name issuer; + Validity validity; Time startDate, endDate; X500Name subject; SubjectPublicKeyInfo subjectPublicKeyInfo; @@ -74,31 +74,36 @@ public void setIssuer( { this.issuer = issuer; } - - public void setStartDate( - ASN1UTCTime startDate) + + public void setValidity(Validity validity) { - this.startDate = new Time(startDate); + this.validity = validity; + this.startDate = null; + this.endDate = null; } - public void setStartDate( - Time startDate) + public void setStartDate(Time startDate) { + this.validity = null; this.startDate = startDate; } - public void setEndDate( - ASN1UTCTime endDate) + public void setStartDate(ASN1UTCTime startDate) { - this.endDate = new Time(endDate); + setStartDate(new Time(startDate)); } - public void setEndDate( - Time endDate) + public void setEndDate(Time endDate) { + this.validity = null; this.endDate = endDate; } + public void setEndDate(ASN1UTCTime endDate) + { + setEndDate(new Time(endDate)); + } + /** * @deprecated use X500Name method */ @@ -163,50 +168,21 @@ public ASN1Sequence generatePreTBSCertificate() { throw new IllegalStateException("signature field should not be set in PreTBSCertificate"); } - if ((serialNumber == null) - || (issuer == null) || (startDate == null) || (endDate == null) - || (subject == null && !altNamePresentAndCritical) || (subjectPublicKeyInfo == null)) + if ((serialNumber == null) || (issuer == null) || + (validity == null && (startDate == null || endDate == null)) || + (subject == null && !altNamePresentAndCritical) || (subjectPublicKeyInfo == null)) { throw new IllegalStateException("not all mandatory fields set in V3 TBScertificate generator"); } - return generateTBSStructure(); - } + ASN1EncodableVector v = new ASN1EncodableVector(9); - private ASN1Sequence generateTBSStructure() - { - ASN1EncodableVector v = new ASN1EncodableVector(10); - - v.add(version); + v.add(VERSION); v.add(serialNumber); - - if (signature != null) - { - v.add(signature); - } - + // No signature v.add(issuer); - - // - // before and after dates - // - { - ASN1EncodableVector validity = new ASN1EncodableVector(2); - validity.add(startDate); - validity.add(endDate); - - v.add(new DERSequence(validity)); - } - - if (subject != null) - { - v.add(subject); - } - else - { - v.add(new DERSequence()); - } - + v.add(validity != null ? validity : new Validity(startDate, endDate)); + v.add(subject != null ? subject : X500Name.getInstance(new DERSequence())); v.add(subjectPublicKeyInfo); if (issuerUniqueID != null) @@ -229,13 +205,16 @@ private ASN1Sequence generateTBSStructure() public TBSCertificate generateTBSCertificate() { - if ((serialNumber == null) || (signature == null) - || (issuer == null) || (startDate == null) || (endDate == null) - || (subject == null && !altNamePresentAndCritical) || (subjectPublicKeyInfo == null)) + if ((serialNumber == null) || (signature == null) || (issuer == null) || + (validity == null && (startDate == null || endDate == null)) || + (subject == null && !altNamePresentAndCritical) || (subjectPublicKeyInfo == null)) { throw new IllegalStateException("not all mandatory fields set in V3 TBScertificate generator"); } - return TBSCertificate.getInstance(generateTBSStructure()); + return new TBSCertificate(new ASN1Integer(2), serialNumber, signature, issuer, + validity != null ? validity : new Validity(startDate, endDate), + subject != null ? subject : X500Name.getInstance(new DERSequence()), subjectPublicKeyInfo, + issuerUniqueID, subjectUniqueID, extensions); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/Validity.java b/core/src/main/java/org/bouncycastle/asn1/x509/Validity.java new file mode 100644 index 0000000000..ddddf771ee --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x509/Validity.java @@ -0,0 +1,82 @@ +package org.bouncycastle.asn1.x509; + +import org.bouncycastle.asn1.ASN1Object; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.DERSequence; + +public class Validity + extends ASN1Object +{ + public static Validity getInstance(Object obj) + { + if (obj instanceof Validity) + { + return (Validity)obj; + } + else if (obj != null) + { + return new Validity(ASN1Sequence.getInstance(obj)); + } + + return null; + } + + public static Validity getInstance(ASN1TaggedObject taggedObject, boolean declaredExplicit) + { + return new Validity(ASN1Sequence.getInstance(taggedObject, declaredExplicit)); + } + + private final Time notBefore; + private final Time notAfter; + + private Validity(ASN1Sequence seq) + { + int count = seq.size(); + if (count != 2) + { + throw new IllegalArgumentException("Bad sequence size: " + count); + } + + this.notBefore = Time.getInstance(seq.getObjectAt(0)); + this.notAfter = Time.getInstance(seq.getObjectAt(1)); + } + + public Validity(Time notBefore, Time notAfter) + { + if (notBefore == null) + { + throw new NullPointerException("'notBefore' cannot be null"); + } + if (notAfter == null) + { + throw new NullPointerException("'notAfter' cannot be null"); + } + + this.notBefore = notBefore; + this.notAfter = notAfter; + } + + public Time getNotBefore() + { + return notBefore; + } + + public Time getNotAfter() + { + return notAfter; + } + + /** + *
    +     * Validity ::= SEQUENCE {
    +     *   notBefore      Time,
    +     *   notAfter       Time  }
    +     * 
    + */ + public ASN1Primitive toASN1Primitive() + { + return new DERSequence(notBefore, notAfter); + } +} diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/X509AttributeIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/x509/X509AttributeIdentifiers.java index 0ed12f7eb6..a64f721dc8 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/X509AttributeIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/X509AttributeIdentifiers.java @@ -7,23 +7,25 @@ public interface X509AttributeIdentifiers /** * @deprecated use id_at_role */ - static final ASN1ObjectIdentifier RoleSyntax = new ASN1ObjectIdentifier("2.5.4.72"); + ASN1ObjectIdentifier RoleSyntax = new ASN1ObjectIdentifier("2.5.4.72"); - static final ASN1ObjectIdentifier id_pe_ac_auditIdentity = X509ObjectIdentifiers.id_pe.branch("4"); - static final ASN1ObjectIdentifier id_pe_aaControls = X509ObjectIdentifiers.id_pe.branch("6"); - static final ASN1ObjectIdentifier id_pe_ac_proxying = X509ObjectIdentifiers.id_pe.branch("10"); + ASN1ObjectIdentifier id_pe_ac_auditIdentity = X509ObjectIdentifiers.id_pe.branch("4"); + ASN1ObjectIdentifier id_pe_aaControls = X509ObjectIdentifiers.id_pe.branch("6"); + ASN1ObjectIdentifier id_pe_ac_proxying = X509ObjectIdentifiers.id_pe.branch("10"); - static final ASN1ObjectIdentifier id_ce_targetInformation= X509ObjectIdentifiers.id_ce.branch("55"); + ASN1ObjectIdentifier id_ce_targetInformation = X509ObjectIdentifiers.id_ce.branch("55"); - static final ASN1ObjectIdentifier id_aca = X509ObjectIdentifiers.id_pkix.branch("10"); + ASN1ObjectIdentifier id_aca = X509ObjectIdentifiers.id_pkix.branch("10"); - static final ASN1ObjectIdentifier id_aca_authenticationInfo = id_aca.branch("1"); - static final ASN1ObjectIdentifier id_aca_accessIdentity = id_aca.branch("2"); - static final ASN1ObjectIdentifier id_aca_chargingIdentity = id_aca.branch("3"); - static final ASN1ObjectIdentifier id_aca_group = id_aca.branch("4"); + ASN1ObjectIdentifier id_aca_authenticationInfo = id_aca.branch("1"); + ASN1ObjectIdentifier id_aca_accessIdentity = id_aca.branch("2"); + ASN1ObjectIdentifier id_aca_chargingIdentity = id_aca.branch("3"); + ASN1ObjectIdentifier id_aca_group = id_aca.branch("4"); // { id-aca 5 } is reserved - static final ASN1ObjectIdentifier id_aca_encAttrs = id_aca.branch("6"); + ASN1ObjectIdentifier id_aca_encAttrs = id_aca.branch("6"); - static final ASN1ObjectIdentifier id_at_role = new ASN1ObjectIdentifier("2.5.4.72"); - static final ASN1ObjectIdentifier id_at_clearance = new ASN1ObjectIdentifier("2.5.1.5.55"); + ASN1ObjectIdentifier id_at_role = new ASN1ObjectIdentifier("2.5.4.72"); + ASN1ObjectIdentifier id_at_clearance = new ASN1ObjectIdentifier("2.5.1.5.55"); + + ASN1ObjectIdentifier id_at_privateKeyStatement = new ASN1ObjectIdentifier("1.3.6.1.4.1.22112.2.1"); } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/X509CertificateStructure.java b/core/src/main/java/org/bouncycastle/asn1/x509/X509CertificateStructure.java index 7c25580b7f..ec630776a1 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/X509CertificateStructure.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/X509CertificateStructure.java @@ -92,6 +92,11 @@ public X500Name getIssuer() return tbsCert.getIssuer(); } + public Validity getValidity() + { + return tbsCert.getValidity(); + } + public Time getStartDate() { return tbsCert.getStartDate(); diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/X509Name.java b/core/src/main/java/org/bouncycastle/asn1/x509/X509Name.java index cfa317790f..69e67f662c 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/X509Name.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/X509Name.java @@ -921,37 +921,23 @@ public ASN1Primitive toASN1Primitive() { if (seq == null) { - ASN1EncodableVector vec = new ASN1EncodableVector(); - ASN1EncodableVector sVec = new ASN1EncodableVector(); - ASN1ObjectIdentifier lstOid = null; - + ASN1EncodableVector vec = new ASN1EncodableVector(); + ASN1EncodableVector sVec = new ASN1EncodableVector(); + ASN1ObjectIdentifier oid = null; + for (int i = 0; i != ordering.size(); i++) { - ASN1EncodableVector v = new ASN1EncodableVector(2); - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)ordering.elementAt(i); - - v.add(oid); - - String str = (String)values.elementAt(i); - - v.add(converter.getConvertedValue(oid, str)); - - if (lstOid == null - || ((Boolean)this.added.elementAt(i)).booleanValue()) - { - sVec.add(new DERSequence(v)); - } - else + if (oid != null && !((Boolean)this.added.elementAt(i)).booleanValue()) { vec.add(new DERSet(sVec)); - sVec = new ASN1EncodableVector(); - sVec.add(new DERSequence(v)); } - - lstOid = oid; + + oid = (ASN1ObjectIdentifier)ordering.elementAt(i); + ASN1Primitive convertedValue = converter.getConvertedValue(oid, (String)values.elementAt(i)); + sVec.add(new DERSequence(oid, convertedValue)); } - + vec.add(new DERSet(sVec)); seq = new DERSequence(vec); @@ -1093,6 +1079,11 @@ public boolean equals(Object obj) { return false; } + + if (orderingSize == 0) + { + return true; + } boolean[] indexes = new boolean[orderingSize]; int start, end, delta; diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/X509NameTokenizer.java b/core/src/main/java/org/bouncycastle/asn1/x509/X509NameTokenizer.java index 7f99235bf9..773390e4cf 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/X509NameTokenizer.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/X509NameTokenizer.java @@ -25,18 +25,18 @@ public X509NameTokenizer( char separator) { this.value = oid; - this.index = -1; + this.index = oid.length() < 1 ? 0 : -1; this.separator = separator; } public boolean hasMoreTokens() { - return (index != value.length()); + return index < value.length(); } public String nextToken() { - if (index == value.length()) + if (index >= value.length()) { return null; } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/X509ObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/x509/X509ObjectIdentifiers.java index c1eab274e7..5f719a35fe 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/X509ObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/X509ObjectIdentifiers.java @@ -1,28 +1,31 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; public interface X509ObjectIdentifiers { + static final ASN1ObjectIdentifier attributeType = new ASN1ObjectIdentifier("2.5.4").intern(); + /** Subject RDN components: commonName = 2.5.4.3 */ - static final ASN1ObjectIdentifier commonName = new ASN1ObjectIdentifier("2.5.4.3").intern(); + static final ASN1ObjectIdentifier commonName = attributeType.branch("3").intern(); /** Subject RDN components: countryName = 2.5.4.6 */ - static final ASN1ObjectIdentifier countryName = new ASN1ObjectIdentifier("2.5.4.6").intern(); + static final ASN1ObjectIdentifier countryName = attributeType.branch("6").intern(); /** Subject RDN components: localityName = 2.5.4.7 */ - static final ASN1ObjectIdentifier localityName = new ASN1ObjectIdentifier("2.5.4.7").intern(); + static final ASN1ObjectIdentifier localityName = attributeType.branch("7").intern(); /** Subject RDN components: stateOrProvinceName = 2.5.4.8 */ - static final ASN1ObjectIdentifier stateOrProvinceName = new ASN1ObjectIdentifier("2.5.4.8").intern(); + static final ASN1ObjectIdentifier stateOrProvinceName = attributeType.branch("8").intern(); /** Subject RDN components: organization = 2.5.4.10 */ - static final ASN1ObjectIdentifier organization = new ASN1ObjectIdentifier("2.5.4.10").intern(); + static final ASN1ObjectIdentifier organization = attributeType.branch("10").intern(); /** Subject RDN components: organizationalUnitName = 2.5.4.11 */ - static final ASN1ObjectIdentifier organizationalUnitName = new ASN1ObjectIdentifier("2.5.4.11").intern(); + static final ASN1ObjectIdentifier organizationalUnitName = attributeType.branch("11").intern(); /** Subject RDN components: telephone_number = 2.5.4.20 */ - static final ASN1ObjectIdentifier id_at_telephoneNumber = new ASN1ObjectIdentifier("2.5.4.20").intern(); + static final ASN1ObjectIdentifier id_at_telephoneNumber = attributeType.branch("20").intern(); /** Subject RDN components: name = 2.5.4.41 */ - static final ASN1ObjectIdentifier id_at_name = new ASN1ObjectIdentifier("2.5.4.41").intern(); - - static final ASN1ObjectIdentifier id_at_organizationIdentifier = new ASN1ObjectIdentifier("2.5.4.97").intern(); + static final ASN1ObjectIdentifier id_at_name = attributeType.branch("41").intern(); + /** Subject RDN components: organizationIdentifier = 2.5.4.97 */ + static final ASN1ObjectIdentifier id_at_organizationIdentifier = attributeType.branch("97").intern(); /** * id-SHA1 OBJECT IDENTIFIER ::= @@ -56,45 +59,49 @@ public interface X509ObjectIdentifiers */ static final ASN1ObjectIdentifier id_pkix = new ASN1ObjectIdentifier("1.3.6.1.5.5.7"); + /** + * private internet extensions; OID = 1.3.6.1.5.5.7.1 + */ + static final ASN1ObjectIdentifier id_pe = id_pkix.branch("1"); + + /** 1.3.6.1.5.5.7.6 */ + static final ASN1ObjectIdentifier pkix_algorithms = id_pkix.branch("6"); + /** * id-RSASSA-PSS-SHAKE128 OBJECT IDENTIFIER ::= { iso(1) * identified-organization(3) dod(6) internet(1) * security(5) mechanisms(5) pkix(7) algorithms(6) 30 } */ - static final ASN1ObjectIdentifier id_rsassa_pss_shake128 = id_pkix.branch("6.30"); + static final ASN1ObjectIdentifier id_rsassa_pss_shake128 = pkix_algorithms.branch("30"); /** * id-RSASSA-PSS-SHAKE256 OBJECT IDENTIFIER ::= { iso(1) * identified-organization(3) dod(6) internet(1) * security(5) mechanisms(5) pkix(7) algorithms(6) 31 } */ - static final ASN1ObjectIdentifier id_rsassa_pss_shake256 = id_pkix.branch("6.31"); + static final ASN1ObjectIdentifier id_rsassa_pss_shake256 = pkix_algorithms.branch("31"); /** * id-ecdsa-with-shake128 OBJECT IDENTIFIER ::= { iso(1) * identified-organization(3) dod(6) internet(1) * security(5) mechanisms(5) pkix(7) algorithms(6) 32 } */ - static final ASN1ObjectIdentifier id_ecdsa_with_shake128 = id_pkix.branch("6.32"); + static final ASN1ObjectIdentifier id_ecdsa_with_shake128 = pkix_algorithms.branch("32"); /** * id-ecdsa-with-shake256 OBJECT IDENTIFIER ::= { iso(1) * identified-organization(3) dod(6) internet(1) * security(5) mechanisms(5) pkix(7) algorithms(6) 33 } */ - static final ASN1ObjectIdentifier id_ecdsa_with_shake256 = id_pkix.branch("6.33"); + static final ASN1ObjectIdentifier id_ecdsa_with_shake256 = pkix_algorithms.branch("33"); /** - * private internet extensions; OID = 1.3.6.1.5.5.7.1 + * id-alg-noSignature OBJECT IDENTIFIER ::= {id-pkix id-alg(6) 2} */ - static final ASN1ObjectIdentifier id_pe = id_pkix.branch("1"); + ASN1ObjectIdentifier id_alg_noSignature = pkix_algorithms.branch("2"); - /** - * ISO ARC for standard certificate and CRL extensions - *

    - * OID: 2.5.29 - */ - static final ASN1ObjectIdentifier id_ce = new ASN1ObjectIdentifier("2.5.29"); + /** 1.3.6.1.5.5.7.9 */ + static final ASN1ObjectIdentifier id_pda = id_pkix.branch("9"); /** id-pkix OID: 1.3.6.1.5.5.7.48 */ static final ASN1ObjectIdentifier id_ad = id_pkix.branch("48"); @@ -108,10 +115,17 @@ public interface X509ObjectIdentifiers /** OID for crl uri in AuthorityInformationAccess extension */ static final ASN1ObjectIdentifier crlAccessMethod = id_ad_caIssuers; + /** + * ISO ARC for standard certificate and CRL extensions + *

    + * OID: 2.5.29 + */ + static final ASN1ObjectIdentifier id_ce = new ASN1ObjectIdentifier("2.5.29"); /** * id-PasswordBasedMac OBJECT IDENTIFIER ::= { iso(1) member-body(2) * us(840) nt(113533) nsn(7) algorithms(66) 13 } + * @deprecated Use CRMFObjectIdentifiers.passwordBasedMac instead */ - static final ASN1ObjectIdentifier id_PasswordBasedMac = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); + static final ASN1ObjectIdentifier id_PasswordBasedMac = MiscObjectIdentifiers.entrust.branch("66.13"); } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/package-info.java b/core/src/main/java/org/bouncycastle/asn1/x509/package-info.java new file mode 100644 index 0000000000..8209dbc20d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x509/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and processing X.509 certificates. + */ +package org.bouncycastle.asn1.x509; diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/qualified/ETSIQCObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/x509/qualified/ETSIQCObjectIdentifiers.java index a95ac94d7e..0e5d037d58 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/qualified/ETSIQCObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/qualified/ETSIQCObjectIdentifiers.java @@ -15,4 +15,6 @@ public interface ETSIQCObjectIdentifiers static final ASN1ObjectIdentifier id_etsi_qct_esign = id_etsi_qcs_QcType.branch("1"); static final ASN1ObjectIdentifier id_etsi_qct_eseal = id_etsi_qcs_QcType.branch("2"); static final ASN1ObjectIdentifier id_etsi_qct_web = id_etsi_qcs_QcType.branch("3"); + + static final ASN1ObjectIdentifier id_etsi_qcs_QcCClegislation = new ASN1ObjectIdentifier("0.4.0.1862.1.7"); } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/qualified/RFC3739QCObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/asn1/x509/qualified/RFC3739QCObjectIdentifiers.java index 0c840bdc35..c59a4a9b1b 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/qualified/RFC3739QCObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/qualified/RFC3739QCObjectIdentifiers.java @@ -1,11 +1,14 @@ package org.bouncycastle.asn1.x509.qualified; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; public interface RFC3739QCObjectIdentifiers { + /** OID: 1.3.6.1.5.5.7.11 */ + ASN1ObjectIdentifier id_qcs = X509ObjectIdentifiers.id_pkix.branch("11"); /** OID: 1.3.6.1.5.5.7.11.1 */ - static final ASN1ObjectIdentifier id_qcs_pkixQCSyntax_v1 = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.11.1"); + ASN1ObjectIdentifier id_qcs_pkixQCSyntax_v1 = id_qcs.branch("1"); /** OID: 1.3.6.1.5.5.7.11.2 */ - static final ASN1ObjectIdentifier id_qcs_pkixQCSyntax_v2 = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.11.2"); + ASN1ObjectIdentifier id_qcs_pkixQCSyntax_v2 = id_qcs.branch("2"); } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/qualified/package-info.java b/core/src/main/java/org/bouncycastle/asn1/x509/qualified/package-info.java new file mode 100644 index 0000000000..95af565a43 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x509/qualified/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and processing messages based around RFC3739 + */ +package org.bouncycastle.asn1.x509.qualified; diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/sigi/NameOrPseudonym.java b/core/src/main/java/org/bouncycastle/asn1/x509/sigi/NameOrPseudonym.java index 8e6af128c6..e439615e4d 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x509/sigi/NameOrPseudonym.java +++ b/core/src/main/java/org/bouncycastle/asn1/x509/sigi/NameOrPseudonym.java @@ -3,7 +3,6 @@ import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Choice; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -179,10 +178,7 @@ public ASN1Primitive toASN1Primitive() } else { - ASN1EncodableVector vec1 = new ASN1EncodableVector(2); - vec1.add(surname); - vec1.add(givenName); - return new DERSequence(vec1); + return new DERSequence(surname, givenName); } } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x509/sigi/package-info.java b/core/src/main/java/org/bouncycastle/asn1/x509/sigi/package-info.java new file mode 100644 index 0000000000..211c03cb48 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/asn1/x509/sigi/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for the German SigI (Signature Interoperability Specification) standard. + */ +package org.bouncycastle.asn1.x509.sigi; diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/DHValidationParms.java b/core/src/main/java/org/bouncycastle/asn1/x9/DHValidationParms.java index 053dc2c8f1..41b2102455 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x9/DHValidationParms.java +++ b/core/src/main/java/org/bouncycastle/asn1/x9/DHValidationParms.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.x9; import org.bouncycastle.asn1.ASN1BitString; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -74,9 +73,6 @@ public ASN1Integer getPgenCounter() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - v.add(this.seed); - v.add(this.pgenCounter); - return new DERSequence(v); + return new DERSequence(seed, pgenCounter); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/KeySpecificInfo.java b/core/src/main/java/org/bouncycastle/asn1/x9/KeySpecificInfo.java index 7e5d7f5333..7495567cb9 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x9/KeySpecificInfo.java +++ b/core/src/main/java/org/bouncycastle/asn1/x9/KeySpecificInfo.java @@ -2,7 +2,6 @@ import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; @@ -96,11 +95,6 @@ public ASN1OctetString getCounter() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(algorithm); - v.add(counter); - - return new DERSequence(v); + return new DERSequence(algorithm, counter); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/ValidationParams.java b/core/src/main/java/org/bouncycastle/asn1/x9/ValidationParams.java index 47d16caffb..f640cac0f3 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x9/ValidationParams.java +++ b/core/src/main/java/org/bouncycastle/asn1/x9/ValidationParams.java @@ -3,7 +3,6 @@ import java.math.BigInteger; import org.bouncycastle.asn1.ASN1BitString; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -95,9 +94,6 @@ public BigInteger getPgenCounter() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - v.add(this.seed); - v.add(this.pgenCounter); - return new DERSequence(v); + return new DERSequence(seed, pgenCounter); } } diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/X9Curve.java b/core/src/main/java/org/bouncycastle/asn1/x9/X9Curve.java index f0c7ffc0f8..567997c699 100644 --- a/core/src/main/java/org/bouncycastle/asn1/x9/X9Curve.java +++ b/core/src/main/java/org/bouncycastle/asn1/x9/X9Curve.java @@ -115,16 +115,21 @@ else if (ECAlgorithms.isF2mCurve(curve)) } } - public ECCurve getCurve() + public ECCurve getCurve() { return curve; } - public byte[] getSeed() + public byte[] getSeed() { return Arrays.clone(seed); } + public boolean hasSeed() + { + return seed != null; + } + /** * Produce an object suitable for an ASN1OutputStream. *

    diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/X9ECParameters.java b/core/src/main/java/org/bouncycastle/asn1/x9/X9ECParameters.java
    index 31f5d429eb..bb05755265 100644
    --- a/core/src/main/java/org/bouncycastle/asn1/x9/X9ECParameters.java
    +++ b/core/src/main/java/org/bouncycastle/asn1/x9/X9ECParameters.java
    @@ -12,8 +12,8 @@
     import org.bouncycastle.math.ec.ECAlgorithms;
     import org.bouncycastle.math.ec.ECCurve;
     import org.bouncycastle.math.ec.ECPoint;
    +import org.bouncycastle.math.field.FiniteField;
     import org.bouncycastle.math.field.PolynomialExtensionField;
    -import org.bouncycastle.util.Arrays;
     
     /**
      * ASN.1 def for Elliptic-Curve ECParameters structure. See
    @@ -26,11 +26,10 @@ public class X9ECParameters
         private static final BigInteger   ONE = BigInteger.valueOf(1);
     
         private X9FieldID           fieldID;
    -    private ECCurve             curve;
    +    private X9Curve             curve;
         private X9ECPoint           g;
         private BigInteger          n;
         private BigInteger          h;
    -    private byte[]              seed;
     
         private X9ECParameters(
             ASN1Sequence  seq)
    @@ -48,11 +47,10 @@ private X9ECParameters(
                 this.h = ((ASN1Integer)seq.getObjectAt(5)).getValue();
             }
     
    -        X9Curve x9c = new X9Curve(
    -            X9FieldID.getInstance(seq.getObjectAt(1)), n, h,
    -            ASN1Sequence.getInstance(seq.getObjectAt(2)));
    +        this.fieldID = X9FieldID.getInstance(seq.getObjectAt(1));
    +
    +        this.curve = new X9Curve(fieldID, n, h, ASN1Sequence.getInstance(seq.getObjectAt(2)));
     
    -        this.curve = x9c.getCurve();
             Object p = seq.getObjectAt(3);
     
             if (p instanceof X9ECPoint)
    @@ -61,10 +59,8 @@ private X9ECParameters(
             }
             else
             {
    -            this.g = new X9ECPoint(curve, (ASN1OctetString)p);
    +            this.g = new X9ECPoint(curve.getCurve(), (ASN1OctetString)p);
             }
    -
    -        this.seed = x9c.getSeed();
         }
     
         public static X9ECParameters getInstance(Object obj)
    @@ -106,20 +102,20 @@ public X9ECParameters(
             BigInteger  h,
             byte[]      seed)
         {
    -        this.curve = curve;
    +        this.curve = new X9Curve(curve, seed);
             this.g = g;
             this.n = n;
             this.h = h;
    -        this.seed = Arrays.clone(seed);
     
    -        if (ECAlgorithms.isFpCurve(curve))
    +        FiniteField field = curve.getField();
    +        if (ECAlgorithms.isFpField(field))
             {
    -            this.fieldID = new X9FieldID(curve.getField().getCharacteristic());
    +            this.fieldID = new X9FieldID(field.getCharacteristic());
             }
    -        else if (ECAlgorithms.isF2mCurve(curve))
    +        else if (ECAlgorithms.isF2mField(field))
             {
    -            PolynomialExtensionField field = (PolynomialExtensionField)curve.getField();
    -            int[] exponents = field.getMinimalPolynomial().getExponentsPresent();
    +            PolynomialExtensionField f2mField = (PolynomialExtensionField)field;
    +            int[] exponents = f2mField.getMinimalPolynomial().getExponentsPresent();
                 if (exponents.length == 3)
                 {
                     this.fieldID = new X9FieldID(exponents[2], exponents[1]);
    @@ -141,7 +137,7 @@ else if (exponents.length == 5)
     
         public ECCurve getCurve()
         {
    -        return curve;
    +        return curve.getCurve();
         }
     
         public ECPoint getG()
    @@ -161,12 +157,12 @@ public BigInteger getH()
     
         public byte[] getSeed()
         {
    -        return Arrays.clone(seed);
    +        return curve.getSeed();
         }
     
         public boolean hasSeed()
         {
    -        return null != seed;
    +        return curve.hasSeed();
         }
     
         /**
    @@ -176,7 +172,7 @@ public boolean hasSeed()
          */
         public X9Curve getCurveEntry()
         {
    -        return new X9Curve(curve, seed);
    +        return curve;
         }
     
         /**
    @@ -218,7 +214,7 @@ public ASN1Primitive toASN1Primitive()
     
             v.add(new ASN1Integer(ONE));
             v.add(fieldID);
    -        v.add(new X9Curve(curve, seed));
    +        v.add(curve);
             v.add(g);
             v.add(new ASN1Integer(n));
     
    diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/X9FieldID.java b/core/src/main/java/org/bouncycastle/asn1/x9/X9FieldID.java
    index 7e9ffe4722..194e080e31 100644
    --- a/core/src/main/java/org/bouncycastle/asn1/x9/X9FieldID.java
    +++ b/core/src/main/java/org/bouncycastle/asn1/x9/X9FieldID.java
    @@ -138,11 +138,6 @@ public ASN1Primitive getParameters()
          */
         public ASN1Primitive toASN1Primitive()
         {
    -        ASN1EncodableVector v = new ASN1EncodableVector(2);
    -
    -        v.add(this.id);
    -        v.add(this.parameters);
    -
    -        return new DERSequence(v);
    +        return new DERSequence(id, parameters);
         }
     }
    diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java b/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java
    index 2851bcae18..73984875c7 100644
    --- a/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java
    +++ b/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java
    @@ -17,10 +17,9 @@ public class X9IntegerConverter
          * @param c the curve of interest.
          * @return the field size in bytes (rounded up).
          */
    -    public int getByteLength(
    -        ECCurve c)
    +    public int getByteLength(ECCurve c)
         {
    -        return (c.getFieldSize() + 7) / 8;
    +        return c.getFieldElementEncodingLength();
         }
     
         /**
    @@ -29,10 +28,9 @@ public int getByteLength(
          * @param fe the field element of interest.
          * @return the field size in bytes (rounded up).
          */
    -    public int getByteLength(
    -        ECFieldElement fe)
    +    public int getByteLength(ECFieldElement fe)
         {
    -        return (fe.getFieldSize() + 7) / 8;
    +        return fe.getEncodedLength();
         }
     
         /**
    diff --git a/core/src/main/java/org/bouncycastle/asn1/x9/package-info.java b/core/src/main/java/org/bouncycastle/asn1/x9/package-info.java
    new file mode 100644
    index 0000000000..570eb320d2
    --- /dev/null
    +++ b/core/src/main/java/org/bouncycastle/asn1/x9/package-info.java
    @@ -0,0 +1,4 @@
    +/**
    + * Support classes useful for encoding and supporting X9.62 elliptic curve.
    + */
    +package org.bouncycastle.asn1.x9;
    diff --git a/core/src/main/java/org/bouncycastle/crypto/BufferedBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/BufferedBlockCipher.java
    index 6a2974147c..5632d95ae5 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/BufferedBlockCipher.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/BufferedBlockCipher.java
    @@ -1,5 +1,6 @@
     package org.bouncycastle.crypto;
     
    +import org.bouncycastle.util.Arrays;
     
     /**
      * A wrapper class that allows block ciphers to be used to process data in
    @@ -11,15 +12,15 @@
      */
     public class BufferedBlockCipher
     {
    -    protected byte[]        buf;
    -    protected int           bufOff;
    +    protected byte[] buf;
    +    protected int bufOff;
     
    -    protected boolean          forEncryption;
    -    protected BlockCipher      cipher;
    +    protected boolean forEncryption;
    +    protected BlockCipher cipher;
         protected MultiBlockCipher mbCipher;
     
    -    protected boolean       partialBlockOkay;
    -    protected boolean       pgpCFB;
    +    protected boolean partialBlockOkay;
    +    protected boolean pgpCFB;
     
         /**
          * constructor for subclasses
    @@ -35,7 +36,7 @@ public class BufferedBlockCipher
          * @deprecated use the constructor on DefaultBufferedBlockCipher.
          */
         public BufferedBlockCipher(
    -        BlockCipher     cipher)
    +        BlockCipher cipher)
         {
             this.cipher = cipher;
     
    @@ -55,8 +56,8 @@ public BufferedBlockCipher(
             //
             // check if we can handle partial blocks on doFinal.
             //
    -        String  name = cipher.getAlgorithmName();
    -        int     idx = name.indexOf('/') + 1;
    +        String name = cipher.getAlgorithmName();
    +        int idx = name.indexOf('/') + 1;
     
             pgpCFB = (idx > 0 && name.startsWith("PGP", idx));
     
    @@ -84,14 +85,14 @@ public BlockCipher getUnderlyingCipher()
          * initialise the cipher.
          *
          * @param forEncryption if true the cipher is initialised for
    -     *  encryption, if false for decryption.
    -     * @param params the key and other data required by the cipher.
    -     * @exception IllegalArgumentException if the params argument is
    -     * inappropriate.
    +     *                      encryption, if false for decryption.
    +     * @param params        the key and other data required by the cipher.
    +     * @throws IllegalArgumentException if the params argument is
    +     *                                  inappropriate.
          */
         public void init(
    -        boolean             forEncryption,
    -        CipherParameters    params)
    +        boolean forEncryption,
    +        CipherParameters params)
             throws IllegalArgumentException
         {
             this.forEncryption = forEncryption;
    @@ -112,7 +113,7 @@ public int getBlockSize()
         }
     
         /**
    -     * return the size of the output buffer required for an update 
    +     * return the size of the output buffer required for an update
          * an input of len bytes.
          *
          * @param len the length of the input.
    @@ -122,7 +123,7 @@ public int getBlockSize()
         public int getUpdateOutputSize(
             int len)
         {
    -        int total       = len + bufOff;
    +        int total = len + bufOff;
             int leftOver;
     
             if (pgpCFB)
    @@ -138,7 +139,7 @@ public int getUpdateOutputSize(
             }
             else
             {
    -            leftOver    = total % buf.length;
    +            leftOver = total % buf.length;
             }
     
             return total - leftOver;
    @@ -167,20 +168,20 @@ public int getOutputSize(
         /**
          * process a single byte, producing an output block if necessary.
          *
    -     * @param in the input byte.
    -     * @param out the space for any output that might be produced.
    +     * @param in     the input byte.
    +     * @param out    the space for any output that might be produced.
          * @param outOff the offset from which the output will be copied.
          * @return the number of output bytes copied to out.
    -     * @exception DataLengthException if there isn't enough space in out.
    -     * @exception IllegalStateException if the cipher isn't initialised.
    +     * @throws DataLengthException   if there isn't enough space in out.
    +     * @throws IllegalStateException if the cipher isn't initialised.
          */
         public int processByte(
    -        byte        in,
    -        byte[]      out,
    -        int         outOff)
    +        byte in,
    +        byte[] out,
    +        int outOff)
             throws DataLengthException, IllegalStateException
         {
    -        int         resultLen = 0;
    +        int resultLen = 0;
     
             buf[bufOff++] = in;
     
    @@ -196,21 +197,21 @@ public int processByte(
         /**
          * process an array of bytes, producing output if necessary.
          *
    -     * @param in the input byte array.
    -     * @param inOff the offset at which the input data starts.
    -     * @param len the number of bytes to be copied out of the input array.
    -     * @param out the space for any output that might be produced.
    +     * @param in     the input byte array.
    +     * @param inOff  the offset at which the input data starts.
    +     * @param len    the number of bytes to be copied out of the input array.
    +     * @param out    the space for any output that might be produced.
          * @param outOff the offset from which the output will be copied.
          * @return the number of output bytes copied to out.
    -     * @exception DataLengthException if there isn't enough space in out.
    -     * @exception IllegalStateException if the cipher isn't initialised.
    +     * @throws DataLengthException   if there isn't enough space in out.
    +     * @throws IllegalStateException if the cipher isn't initialised.
          */
         public int processBytes(
    -        byte[]      in,
    -        int         inOff,
    -        int         len,
    -        byte[]      out,
    -        int         outOff)
    +        byte[] in,
    +        int inOff,
    +        int len,
    +        byte[] out,
    +        int outOff)
             throws DataLengthException, IllegalStateException
         {
             if (len < 0)
    @@ -218,9 +219,9 @@ public int processBytes(
                 throw new IllegalArgumentException("Can't have a negative input length!");
             }
     
    -        int blockSize   = getBlockSize();
    -        int length      = getUpdateOutputSize(len);
    -        
    +        int blockSize = getBlockSize();
    +        int length = getUpdateOutputSize(len);
    +
             if (length > 0)
             {
                 if ((outOff + length) > out.length)
    @@ -235,12 +236,18 @@ public int processBytes(
             if (len > gapLen)
             {
                 System.arraycopy(in, inOff, buf, bufOff, gapLen);
    +            inOff += gapLen;
    +            len -= gapLen;
    +            if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, length))
    +            {
    +                in = new byte[len];
    +                System.arraycopy(out, inOff, in, 0, len);
    +                inOff = 0;
    +            }
     
                 resultLen += cipher.processBlock(buf, 0, out, outOff);
     
                 bufOff = 0;
    -            len -= gapLen;
    -            inOff += gapLen;
     
                 if (mbCipher != null)
                 {
    @@ -284,20 +291,20 @@ public int processBytes(
         /**
          * Process the last block in the buffer.
          *
    -     * @param out the array the block currently being held is copied into.
    +     * @param out    the array the block currently being held is copied into.
          * @param outOff the offset at which the copying starts.
          * @return the number of output bytes copied to out.
    -     * @exception DataLengthException if there is insufficient space in out for
    -     * the output, or the input is not block size aligned and should be.
    -     * @exception IllegalStateException if the underlying cipher is not
    -     * initialised.
    -     * @exception InvalidCipherTextException if padding is expected and not found.
    -     * @exception DataLengthException if the input is not block size
    -     * aligned.
    +     * @throws DataLengthException        if there is insufficient space in out for
    +     *                                    the output, or the input is not block size aligned and should be.
    +     * @throws IllegalStateException      if the underlying cipher is not
    +     *                                    initialised.
    +     * @throws InvalidCipherTextException if padding is expected and not found.
    +     * @throws DataLengthException        if the input is not block size
    +     *                                    aligned.
          */
         public int doFinal(
    -        byte[]  out,
    -        int     outOff)
    +        byte[] out,
    +        int outOff)
             throws DataLengthException, IllegalStateException, InvalidCipherTextException
         {
             try
    diff --git a/core/src/main/java/org/bouncycastle/crypto/DefaultBufferedBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/DefaultBufferedBlockCipher.java
    index 662a23a011..51a4df20ea 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/DefaultBufferedBlockCipher.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/DefaultBufferedBlockCipher.java
    @@ -1,5 +1,6 @@
     package org.bouncycastle.crypto;
     
    +import org.bouncycastle.util.Arrays;
     
     /**
      * A wrapper class that allows block ciphers to be used to process data in
    @@ -237,12 +238,19 @@ public int processBytes(
             if (len > gapLen)
             {
                 System.arraycopy(in, inOff, buf, bufOff, gapLen);
    +            inOff += gapLen;
    +            len -= gapLen;
    +            if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, length))
    +            {
    +                in = new byte[len];
    +                System.arraycopy(out, inOff, in, 0, len);
    +                inOff = 0;
    +            }
     
                 resultLen += cipher.processBlock(buf, 0, out, outOff);
     
                 bufOff = 0;
    -            len -= gapLen;
    -            inOff += gapLen;
    +
     
                 if (mbCipher != null)
                 {
    diff --git a/core/src/main/java/org/bouncycastle/crypto/DefaultMultiBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/DefaultMultiBlockCipher.java
    index 3bc565cf0e..e2964aa05d 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/DefaultMultiBlockCipher.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/DefaultMultiBlockCipher.java
    @@ -1,5 +1,7 @@
     package org.bouncycastle.crypto;
     
    +import org.bouncycastle.util.Arrays;
    +
     public abstract class DefaultMultiBlockCipher
         implements MultiBlockCipher
     {
    @@ -20,7 +22,13 @@ public int processBlocks(byte[] in, int inOff, int blockCount, byte[] out, int o
     
             int resultLen = 0;
             int blockSize = this.getMultiBlockSize();
    -        
    +        int len = blockCount * blockSize;
    +        if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, len))
    +        {
    +            in = new byte[len];
    +            System.arraycopy(out, inOff, in, 0, len);
    +            inOff = 0;
    +        }
             for (int i = 0; i != blockCount; i++)
             {
                 resultLen += this.processBlock(in, inOff, out, outOff + resultLen);
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/BasicRawAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/BasicRawAgreement.java
    new file mode 100644
    index 0000000000..1309fbf696
    --- /dev/null
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/BasicRawAgreement.java
    @@ -0,0 +1,40 @@
    +package org.bouncycastle.crypto.agreement;
    +
    +import java.math.BigInteger;
    +
    +import org.bouncycastle.crypto.BasicAgreement;
    +import org.bouncycastle.crypto.CipherParameters;
    +import org.bouncycastle.crypto.RawAgreement;
    +import org.bouncycastle.util.BigIntegers;
    +
    +public final class BasicRawAgreement
    +    implements RawAgreement
    +{
    +    public final BasicAgreement basicAgreement;
    +
    +    public BasicRawAgreement(BasicAgreement basicAgreement)
    +    {
    +        if (basicAgreement == null)
    +        {
    +            throw new NullPointerException("'basicAgreement' cannot be null");
    +        }
    +
    +        this.basicAgreement = basicAgreement;
    +    }
    +
    +    public void init(CipherParameters parameters)
    +    {
    +        basicAgreement.init(parameters);
    +    }
    +
    +    public int getAgreementSize()
    +    {
    +        return basicAgreement.getFieldSize();
    +    }
    +
    +    public void calculateAgreement(CipherParameters publicKey, byte[] buf, int off)
    +    {
    +        BigInteger z = basicAgreement.calculateAgreement(publicKey);
    +        BigIntegers.asUnsignedByteArray(z, buf, off, getAgreementSize());
    +    }
    +}
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java
    index e3446385ae..acec9306c0 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHBasicAgreement.java
    @@ -41,7 +41,7 @@ public void init(
     
         public int getFieldSize()
         {
    -        return (key.getParameters().getCurve().getFieldSize() + 7) / 8;
    +        return key.getParameters().getCurve().getFieldElementEncodingLength();
         }
     
         public BigInteger calculateAgreement(
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCBasicAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCBasicAgreement.java
    index aa67a7a09a..0c48e5360d 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCBasicAgreement.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCBasicAgreement.java
    @@ -45,7 +45,7 @@ public void init(
     
         public int getFieldSize()
         {
    -        return (key.getParameters().getCurve().getFieldSize() + 7) / 8;
    +        return key.getParameters().getCurve().getFieldElementEncodingLength();
         }
     
         public BigInteger calculateAgreement(
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCStagedAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCStagedAgreement.java
    index 222f4f3836..363b7ccec4 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCStagedAgreement.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCStagedAgreement.java
    @@ -27,7 +27,7 @@ public void init(
     
         public int getFieldSize()
         {
    -        return (key.getParameters().getCurve().getFieldSize() + 7) / 8;
    +        return key.getParameters().getCurve().getFieldElementEncodingLength();
         }
     
         public AsymmetricKeyParameter calculateStage(
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCUnifiedAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCUnifiedAgreement.java
    index b2df97811e..ccefa18b3a 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCUnifiedAgreement.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ECDHCUnifiedAgreement.java
    @@ -25,7 +25,7 @@ public void init(
     
         public int getFieldSize()
         {
    -        return (privParams.getStaticPrivateKey().getParameters().getCurve().getFieldSize() + 7) / 8;
    +        return privParams.getStaticPrivateKey().getParameters().getCurve().getFieldElementEncodingLength();
         }
     
         public byte[] calculateAgreement(CipherParameters pubKey)
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ECMQVBasicAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ECMQVBasicAgreement.java
    index 9038b83f80..34beb8d530 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/agreement/ECMQVBasicAgreement.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ECMQVBasicAgreement.java
    @@ -31,7 +31,7 @@ public void init(
     
         public int getFieldSize()
         {
    -        return (privParams.getStaticPrivateKey().getParameters().getCurve().getFieldSize() + 7) / 8;
    +        return privParams.getStaticPrivateKey().getParameters().getCurve().getFieldElementEncodingLength();
         }
     
         public BigInteger calculateAgreement(CipherParameters pubKey)
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ECVKOAgreement.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ECVKOAgreement.java
    index eb49a87083..5e64eb7260 100644
    --- a/core/src/main/java/org/bouncycastle/crypto/agreement/ECVKOAgreement.java
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ECVKOAgreement.java
    @@ -48,7 +48,7 @@ public int getAgreementSize()
          */
         public int getFieldSize()
         {
    -        return (key.getParameters().getCurve().getFieldSize() + 7) / 8;
    +        return key.getParameters().getCurve().getFieldElementEncodingLength();
         }
     
         public byte[] calculateAgreement(CipherParameters pubKey)
    diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKECurve.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKECurve.java
    new file mode 100644
    index 0000000000..1d56989471
    --- /dev/null
    +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKECurve.java
    @@ -0,0 +1,171 @@
    +package org.bouncycastle.crypto.agreement.ecjpake;
    +
    +import java.math.BigInteger;
    +
    +import org.bouncycastle.math.ec.ECCurve;
    +import org.bouncycastle.math.ec.ECPoint;
    +
    +/**
    + * A pre-computed elliptic curve over a prime field, in short-Weierstrass form for use during an EC J-PAKE exchange.
    + * 

    + * In general, J-PAKE can use any elliptic curve or prime order group + * that is suitable for public key cryptography. + *

    + * See {@link ECJPAKECurves} for convenient standard curves. + *

    + * NIST publishes + * many curves with different forms and levels of security. + */ +public class ECJPAKECurve +{ + private final ECCurve.AbstractFp curve; + private final ECPoint g; + + /** + * Constructs a new {@link ECJPAKECurve}. + *

    + * In general, you should use one of the pre-approved curves from + * {@link ECJPAKECurves}, rather than manually constructing one. + *

    + * The following basic checks are performed: + *

      + *
    • q must be prime
    • + *
    • n must be prime
    • + *
    • The curve must not be singular i.e. the discriminant is equal to 0 mod q
    • + *
    • G must lie on the curve
    • + *
    • n*h must equal the order of the curve
    • + *
    • a must be in [0, q-1]
    • + *
    • b must be in [0, q-1]
    • + *
    + *

    + * The prime checks are performed using {@link BigInteger#isProbablePrime(int)}, + * and are therefore subject to the same probability guarantees. + *

    + * These checks prevent trivial mistakes. + * However, due to the small uncertainties if p and q are not prime, + * advanced attacks are not prevented. + * Use it at your own risk. + * + * @throws NullPointerException if any argument is null + * @throws IllegalArgumentException if any of the above validations fail + */ + public ECJPAKECurve(BigInteger q, BigInteger a, BigInteger b, BigInteger n, BigInteger h, BigInteger g_x, BigInteger g_y) + { + ECJPAKEUtil.validateNotNull(a, "a"); + ECJPAKEUtil.validateNotNull(b, "b"); + ECJPAKEUtil.validateNotNull(q, "q"); + ECJPAKEUtil.validateNotNull(n, "n"); + ECJPAKEUtil.validateNotNull(h, "h"); + ECJPAKEUtil.validateNotNull(g_x, "g_x"); + ECJPAKEUtil.validateNotNull(g_y, "g_y"); + + /* + * Don't skip the checks on user-specified groups. + */ + + /* + * Note that these checks do not guarantee that n and q are prime. + * We just have reasonable certainty that they are prime. + */ + if (!q.isProbablePrime(20)) + { + throw new IllegalArgumentException("Field size q must be prime"); + } + + if (a.compareTo(BigInteger.ZERO) < 0 || a.compareTo(q) >= 0) + { + throw new IllegalArgumentException("The parameter 'a' is not in the field [0, q-1]"); + } + + if (b.compareTo(BigInteger.ZERO) < 0 || b.compareTo(q) >= 0) + { + throw new IllegalArgumentException("The parameter 'b' is not in the field [0, q-1]"); + } + + BigInteger d = calculateDeterminant(q, a, b); + if (d.equals(BigInteger.ZERO)) + { + throw new IllegalArgumentException("The curve is singular, i.e the discriminant is equal to 0 mod q."); + } + + if (!n.isProbablePrime(20)) + { + throw new IllegalArgumentException("The order n must be prime"); + } + + /* + * TODO It's expensive to calculate the actual total number of points. Probably the best that could be done is + * checking that the point count is within the Hasse bound? + */ +// BigInteger totalPoints = n.multiply(h); + + ECCurve.Fp curve = new ECCurve.Fp(q, a, b, n, h); + ECPoint g = curve.createPoint(g_x, g_y); + + if (!g.isValid()) + { + throw new IllegalArgumentException("The base point G does not lie on the curve."); + } + + this.curve = curve; + this.g = g; + } + + /** + * Internal package-private constructor used by the pre-approved + * groups in {@link ECJPAKECurves}. + * These pre-approved curves can avoid the expensive checks. + */ + ECJPAKECurve(ECCurve.AbstractFp curve, ECPoint g) + { + ECJPAKEUtil.validateNotNull(curve, "curve"); + ECJPAKEUtil.validateNotNull(g, "g"); + ECJPAKEUtil.validateNotNull(curve.getOrder(), "n"); + ECJPAKEUtil.validateNotNull(curve.getCofactor(), "h"); + + this.curve = curve; + this.g = g; + } + + public ECCurve.AbstractFp getCurve() + { + return curve; + } + + public ECPoint getG() + { + return g; + } + + public BigInteger getA() + { + return curve.getA().toBigInteger(); + } + + public BigInteger getB() + { + return curve.getB().toBigInteger(); + } + + public BigInteger getN() + { + return curve.getOrder(); + } + + public BigInteger getH() + { + return curve.getCofactor(); + } + + public BigInteger getQ() + { + return curve.getQ(); + } + + private static BigInteger calculateDeterminant(BigInteger q, BigInteger a, BigInteger b) + { + BigInteger a3x4 = a.multiply(a).mod(q).multiply(a).mod(q).shiftLeft(2); + BigInteger b2x27 = b.multiply(b).mod(q).multiply(BigInteger.valueOf(27)); + return a3x4.add(b2x27).mod(q); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKECurves.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKECurves.java new file mode 100644 index 0000000000..ef72b3345f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKECurves.java @@ -0,0 +1,50 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.ec.CustomNamedCurves; +import org.bouncycastle.math.ec.ECCurve; + +/** + * Standard pre-computed elliptic curves for use by EC J-PAKE. + * (J-PAKE can use pre-computed elliptic curves or prime order groups, same as DSA and Diffie-Hellman.) + *

    + * This class contains some convenient constants for use as input for + * constructing {@link ECJPAKEParticipant}s. + *

    + * The prime order groups below are taken from NIST SP 800-186, + * "Recommendations for Discrete Logarithm-based Cryptography: Elliptic Curve Domain Parameters", + * published by NIST. + */ +public class ECJPAKECurves +{ + /** + * From NIST. + * 128-bit security. + */ + public static final ECJPAKECurve NIST_P256; + + /** + * From NIST. + * 192-bit security. + */ + public static final ECJPAKECurve NIST_P384; + + /** + * From NIST. + * 256-bit security. + */ + public static final ECJPAKECurve NIST_P521; + + static + { + NIST_P256 = getCurve("P-256"); + NIST_P384 = getCurve("P-384"); + NIST_P521 = getCurve("P-521"); + } + + private static ECJPAKECurve getCurve(String curveName) + { + X9ECParameters x9 = CustomNamedCurves.getByName(curveName); + return new ECJPAKECurve((ECCurve.AbstractFp)x9.getCurve(), x9.getG()); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKEParticipant.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKEParticipant.java new file mode 100644 index 0000000000..66c5bcb986 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKEParticipant.java @@ -0,0 +1,563 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Exceptions; + +/** + * A participant in a Password Authenticated Key Exchange by Juggling (J-PAKE) exchange. + *

    + * The J-PAKE exchange is defined by Feng Hao and Peter Ryan in the paper + * + * "J-PAKE: Authenticated Key Exchange Without PKI." + *

    + * The J-PAKE protocol is symmetric. + * There is no notion of a client or server, but rather just two participants. + * An instance of {@link ECJPAKEParticipant} represents one participant, and + * is the primary interface for executing the exchange. + *

    + * To execute an exchange, construct a {@link ECJPAKEParticipant} on each end, + * and call the following 7 methods + * (once and only once, in the given order, for each participant, sending messages between them as described): + *

      + *
    1. {@link #createRound1PayloadToSend()} - and send the payload to the other participant
    2. + *
    3. {@link #validateRound1PayloadReceived(ECJPAKERound1Payload)} - use the payload received from the other participant
    4. + *
    5. {@link #createRound2PayloadToSend()} - and send the payload to the other participant
    6. + *
    7. {@link #validateRound2PayloadReceived(ECJPAKERound2Payload)} - use the payload received from the other participant
    8. + *
    9. {@link #calculateKeyingMaterial()}
    10. + *
    11. {@link #createRound3PayloadToSend(BigInteger)} - and send the payload to the other participant
    12. + *
    13. {@link #validateRound3PayloadReceived(ECJPAKERound3Payload, BigInteger)} - use the payload received from the other participant
    14. + *
    + *

    + * Each side should derive a session key from the keying material returned by {@link #calculateKeyingMaterial()}. + * The caller is responsible for deriving the session key using a secure key derivation function (KDF). + *

    + * Round 3 is an optional key confirmation process. + * If you do not execute round 3, then there is no assurance that both participants are using the same key. + * (i.e. if the participants used different passwords, then their session keys will differ.) + *

    + * If the round 3 validation succeeds, then the keys are guaranteed to be the same on both sides. + *

    + * The symmetric design can easily support the asymmetric cases when one party initiates the communication. + * e.g. Sometimes the round1 payload and round2 payload may be sent in one pass. + * Also, in some cases, the key confirmation payload can be sent together with the round2 payload. + * These are the trivial techniques to optimize the communication. + *

    + * The key confirmation process is implemented as specified in + * NIST SP 800-56A Revision 3, + * Section 5.9.1 Unilateral Key Confirmation for Key Agreement Schemes. + *

    + * This class is stateful and NOT threadsafe. + * Each instance should only be used for ONE complete J-PAKE exchange + * (i.e. a new {@link ECJPAKEParticipant} should be constructed for each new J-PAKE exchange). + *

    + */ +public class ECJPAKEParticipant +{ + + /* + * Possible internal states. Used for state checking. + */ + + public static final int STATE_INITIALIZED = 0; + public static final int STATE_ROUND_1_CREATED = 10; + public static final int STATE_ROUND_1_VALIDATED = 20; + public static final int STATE_ROUND_2_CREATED = 30; + public static final int STATE_ROUND_2_VALIDATED = 40; + public static final int STATE_KEY_CALCULATED = 50; + public static final int STATE_ROUND_3_CREATED = 60; + public static final int STATE_ROUND_3_VALIDATED = 70; + + /** + * Unique identifier of this participant. + * The two participants in the exchange must NOT share the same id. + */ + private final String participantId; + + /** + * Shared secret. This only contains the secret between construction + * and the call to {@link #calculateKeyingMaterial()}. + *

    + * i.e. When {@link #calculateKeyingMaterial()} is called, this buffer overwritten with 0's, + * and the field is set to null. + *

    + */ + private char[] password; + + /** + * Digest to use during calculations. + */ + private final Digest digest; + + /** + * Source of secure random data. + */ + private final SecureRandom random; + + /** + * The participantId of the other participant in this exchange. + */ + private String partnerParticipantId; + + private ECCurve.AbstractFp ecCurve; + private BigInteger q; + private BigInteger h; + private BigInteger n; + private ECPoint g; + + /** + * Alice's x1 or Bob's x3. + */ + private BigInteger x1; + /** + * Alice's x2 or Bob's x4. + */ + private BigInteger x2; + /** + * Alice's g^x1 or Bob's g^x3. + */ + private ECPoint gx1; + /** + * Alice's g^x2 or Bob's g^x4. + */ + private ECPoint gx2; + /** + * Alice's g^x3 or Bob's g^x1. + */ + private ECPoint gx3; + /** + * Alice's g^x4 or Bob's g^x2. + */ + private ECPoint gx4; + /** + * Alice's B or Bob's A. + */ + private ECPoint b; + + /** + * The current state. + * See the STATE_* constants for possible values. + */ + private int state; + + /** + * Convenience constructor for a new {@link ECJPAKEParticipant} that uses + * the {@link ECJPAKECurves#NIST_P256} elliptic curve, + * a SHA-256 digest, and a default {@link SecureRandom} implementation. + *

    + * After construction, the {@link #getState() state} will be {@link #STATE_INITIALIZED}. + * + * @param participantId unique identifier of this participant. + * The two participants in the exchange must NOT share the same id. + * @param password shared secret. + * A defensive copy of this array is made (and cleared once {@link #calculateKeyingMaterial()} is called). + * Caller should clear the input password as soon as possible. + * @throws NullPointerException if any argument is null + * @throws IllegalArgumentException if password is empty + */ + public ECJPAKEParticipant( + String participantId, + char[] password) + { + this( + participantId, + password, + ECJPAKECurves.NIST_P256); + } + + /** + * Convenience constructor for a new {@link ECJPAKEParticipant} that uses + * a SHA-256 digest and a default {@link SecureRandom} implementation. + *

    + * After construction, the {@link #getState() state} will be {@link #STATE_INITIALIZED}. + * + * @param participantId unique identifier of this participant. + * The two participants in the exchange must NOT share the same id. + * @param password shared secret. + * A defensive copy of this array is made (and cleared once {@link #calculateKeyingMaterial()} is called). + * Caller should clear the input password as soon as possible. + * @param curve elliptic curve + * See {@link ECJPAKECurves} for standard curves. + * @throws NullPointerException if any argument is null + * @throws IllegalArgumentException if password is empty + */ + public ECJPAKEParticipant( + String participantId, + char[] password, + ECJPAKECurve curve) + { + this( + participantId, + password, + curve, + SHA256Digest.newInstance(), + CryptoServicesRegistrar.getSecureRandom()); + } + + /** + * Construct a new {@link ECJPAKEParticipant}. + *

    + * After construction, the {@link #getState() state} will be {@link #STATE_INITIALIZED}. + * + * @param participantId unique identifier of this participant. + * The two participants in the exchange must NOT share the same id. + * @param password shared secret. + * A defensive copy of this array is made (and cleared once {@link #calculateKeyingMaterial()} is called). + * Caller should clear the input password as soon as possible. + * @param curve elliptic curve. + * See {@link ECJPAKECurves} for standard curves + * @param digest digest to use during zero knowledge proofs and key confirmation (SHA-256 or stronger preferred) + * @param random source of secure random data for x1 and x2, and for the zero knowledge proofs + * @throws NullPointerException if any argument is null + * @throws IllegalArgumentException if password is empty + */ + public ECJPAKEParticipant( + String participantId, + char[] password, + ECJPAKECurve curve, + Digest digest, + SecureRandom random) + { + ECJPAKEUtil.validateNotNull(participantId, "participantId"); + ECJPAKEUtil.validateNotNull(password, "password"); + ECJPAKEUtil.validateNotNull(curve, "curve params"); + ECJPAKEUtil.validateNotNull(digest, "digest"); + ECJPAKEUtil.validateNotNull(random, "random"); + if (password.length == 0) + { + throw new IllegalArgumentException("Password must not be empty."); + } + + this.participantId = participantId; + + /* + * Create a defensive copy so as to fully encapsulate the password. + * + * This array will contain the password for the lifetime of this + * participant BEFORE {@link #calculateKeyingMaterial()} is called. + * + * i.e. When {@link #calculateKeyingMaterial()} is called, the array will be cleared + * in order to remove the password from memory. + * + * The caller is responsible for clearing the original password array + * given as input to this constructor. + */ + this.password = Arrays.copyOf(password, password.length); + + this.ecCurve = curve.getCurve(); + this.g = curve.getG(); + this.h = curve.getH(); + this.n = curve.getN(); + this.q = curve.getQ(); + + this.digest = digest; + this.random = random; + + this.state = STATE_INITIALIZED; + } + + /** + * Gets the current state of this participant. + * See the STATE_* constants for possible values. + */ + public int getState() + { + return this.state; + } + + /** + * Creates and returns the payload to send to the other participant during round 1. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_1_CREATED}. + */ + public ECJPAKERound1Payload createRound1PayloadToSend() + { + if (this.state >= STATE_ROUND_1_CREATED) + { + throw new IllegalStateException("Round1 payload already created for " + participantId); + } + + this.x1 = ECJPAKEUtil.generateX1(n, random); + this.x2 = ECJPAKEUtil.generateX1(n, random); + + this.gx1 = ECJPAKEUtil.calculateGx(g, x1); + this.gx2 = ECJPAKEUtil.calculateGx(g, x2); + + ECSchnorrZKP knowledgeProofForX1 = ECJPAKEUtil.calculateZeroKnowledgeProof(g, n, x1, gx1, digest, participantId, random); + ECSchnorrZKP knowledgeProofForX2 = ECJPAKEUtil.calculateZeroKnowledgeProof(g, n, x2, gx2, digest, participantId, random); + + this.state = STATE_ROUND_1_CREATED; + + return new ECJPAKERound1Payload(participantId, gx1, gx2, knowledgeProofForX1, knowledgeProofForX2); + } + + /** + * Validates the payload received from the other participant during round 1. + *

    + * Must be called prior to {@link #createRound2PayloadToSend()}. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_1_VALIDATED}. + * + * @throws CryptoException if validation fails. + * @throws IllegalStateException if called multiple times. + */ + public void validateRound1PayloadReceived(ECJPAKERound1Payload round1PayloadReceived) + throws CryptoException + { + if (this.state >= STATE_ROUND_1_VALIDATED) + { + throw new IllegalStateException("Validation already attempted for round1 payload for" + participantId); + } + this.partnerParticipantId = round1PayloadReceived.getParticipantId(); + this.gx3 = round1PayloadReceived.getGx1(); + this.gx4 = round1PayloadReceived.getGx2(); + + ECSchnorrZKP knowledgeProofForX3 = round1PayloadReceived.getKnowledgeProofForX1(); + ECSchnorrZKP knowledgeProofForX4 = round1PayloadReceived.getKnowledgeProofForX2(); + + ECJPAKEUtil.validateParticipantIdsDiffer(participantId, round1PayloadReceived.getParticipantId()); + ECJPAKEUtil.validateZeroKnowledgeProof(g, gx3, knowledgeProofForX3, q, n, ecCurve, h, round1PayloadReceived.getParticipantId(), digest); + ECJPAKEUtil.validateZeroKnowledgeProof(g, gx4, knowledgeProofForX4, q, n, ecCurve, h, round1PayloadReceived.getParticipantId(), digest); + + this.state = STATE_ROUND_1_VALIDATED; + } + + /** + * Creates and returns the payload to send to the other participant during round 2. + *

    + * {@link #validateRound1PayloadReceived(ECJPAKERound1Payload)} must be called prior to this method. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_2_CREATED}. + * + * @throws IllegalStateException if called prior to {@link #validateRound1PayloadReceived(ECJPAKERound1Payload)}, or multiple times + */ + public ECJPAKERound2Payload createRound2PayloadToSend() + { + if (this.state >= STATE_ROUND_2_CREATED) + { + throw new IllegalStateException("Round2 payload already created for " + this.participantId); + } + if (this.state < STATE_ROUND_1_VALIDATED) + { + throw new IllegalStateException("Round1 payload must be validated prior to creating Round2 payload for " + this.participantId); + } + ECPoint gA = ECJPAKEUtil.calculateGA(gx1, gx3, gx4); + BigInteger s = calculateS(); + BigInteger x2s = ECJPAKEUtil.calculateX2s(n, x2, s); + ECPoint A = ECJPAKEUtil.calculateA(gA, x2s); + ECSchnorrZKP knowledgeProofForX2s = ECJPAKEUtil.calculateZeroKnowledgeProof(gA, n, x2s, A, digest, participantId, random); + + this.state = STATE_ROUND_2_CREATED; + + return new ECJPAKERound2Payload(participantId, A, knowledgeProofForX2s); + } + + /** + * Validates the payload received from the other participant during round 2. + *

    + * Note that this DOES NOT detect a non-common password. + * The only indication of a non-common password is through derivation + * of different keys (which can be detected explicitly by executing round 3 and round 4) + *

    + * Must be called prior to {@link #calculateKeyingMaterial()}. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_2_VALIDATED}. + * + * @throws CryptoException if validation fails. + * @throws IllegalStateException if called prior to {@link #validateRound1PayloadReceived(ECJPAKERound1Payload)}, or multiple times + */ + public void validateRound2PayloadReceived(ECJPAKERound2Payload round2PayloadReceived) + throws CryptoException + { + if (this.state >= STATE_ROUND_2_VALIDATED) + { + throw new IllegalStateException("Validation already attempted for round2 payload for" + participantId); + } + if (this.state < STATE_ROUND_1_VALIDATED) + { + throw new IllegalStateException("Round1 payload must be validated prior to validating Round2 payload for " + this.participantId); + } + ECPoint gB = ECJPAKEUtil.calculateGA(gx3, gx1, gx2); + this.b = round2PayloadReceived.getA(); + ECSchnorrZKP knowledgeProofForX4s = round2PayloadReceived.getKnowledgeProofForX2s(); + + ECJPAKEUtil.validateParticipantIdsDiffer(participantId, round2PayloadReceived.getParticipantId()); + ECJPAKEUtil.validateParticipantIdsEqual(this.partnerParticipantId, round2PayloadReceived.getParticipantId()); + ECJPAKEUtil.validateZeroKnowledgeProof(gB, b, knowledgeProofForX4s, q, n, ecCurve, h, round2PayloadReceived.getParticipantId(), digest); + + this.state = STATE_ROUND_2_VALIDATED; + } + + /** + * Calculates and returns the key material. + * A session key must be derived from this key material using a secure key derivation function (KDF). + * The KDF used to derive the key is handled externally (i.e. not by {@link ECJPAKEParticipant}). + *

    + * The keying material will be identical for each participant if and only if + * each participant's password is the same. i.e. If the participants do not + * share the same password, then each participant will derive a different key. + * Therefore, if you immediately start using a key derived from + * the keying material, then you must handle detection of incorrect keys. + * If you want to handle this detection explicitly, you can optionally perform + * rounds 3 and 4. See {@link ECJPAKEParticipant} for details on how to execute + * rounds 3 and 4. + *

    + * The keying material will be in the range [0, n-1]. + *

    + * {@link #validateRound2PayloadReceived(ECJPAKERound2Payload)} must be called prior to this method. + *

    + * As a side effect, the internal {@link #password} array is cleared, since it is no longer needed. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_KEY_CALCULATED}. + * + * @throws IllegalStateException if called prior to {@link #validateRound2PayloadReceived(ECJPAKERound2Payload)}, + * or if called multiple times. + */ + public BigInteger calculateKeyingMaterial() + { + if (this.state >= STATE_KEY_CALCULATED) + { + throw new IllegalStateException("Key already calculated for " + participantId); + } + if (this.state < STATE_ROUND_2_VALIDATED) + { + throw new IllegalStateException("Round2 payload must be validated prior to creating key for " + participantId); + } + BigInteger s = calculateS(); + + /* + * Clear the password array from memory, since we don't need it anymore. + * + * Also set the field to null as a flag to indicate that the key has already been calculated. + */ + Arrays.fill(password, (char)0); + this.password = null; + + BigInteger keyingMaterial = ECJPAKEUtil.calculateKeyingMaterial(n, gx4, x2, s, b); + + /* + * Clear the ephemeral private key fields as well. + * Note that we're relying on the garbage collector to do its job to clean these up. + * The old objects will hang around in memory until the garbage collector destroys them. + * + * If the ephemeral private keys x1 and x2 are leaked, + * the attacker might be able to brute-force the password. + */ + this.x1 = null; + this.x2 = null; + this.b = null; + + /* + * Do not clear gx* yet, since those are needed by round 3. + */ + this.state = STATE_KEY_CALCULATED; + + return keyingMaterial; + } + + /** + * Creates and returns the payload to send to the other participant during round 3. + *

    + * See {@link ECJPAKEParticipant} for more details on round 3. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_3_CREATED}. + * + * @param keyingMaterial The keying material as returned from {@link #calculateKeyingMaterial()}. + * @throws IllegalStateException if called prior to {@link #calculateKeyingMaterial()}, or multiple times + */ + public ECJPAKERound3Payload createRound3PayloadToSend(BigInteger keyingMaterial) + { + if (this.state >= STATE_ROUND_3_CREATED) + { + throw new IllegalStateException("Round3 payload already created for " + this.participantId); + } + if (this.state < STATE_KEY_CALCULATED) + { + throw new IllegalStateException("Keying material must be calculated prior to creating Round3 payload for " + this.participantId); + } + + BigInteger macTag = ECJPAKEUtil.calculateMacTag( + this.participantId, + this.partnerParticipantId, + this.gx1, + this.gx2, + this.gx3, + this.gx4, + keyingMaterial, + this.digest); + + this.state = STATE_ROUND_3_CREATED; + + return new ECJPAKERound3Payload(participantId, macTag); + } + + /** + * Validates the payload received from the other participant during round 3. + *

    + * See {@link ECJPAKEParticipant} for more details on round 3. + *

    + * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_3_VALIDATED}. + * + * @param round3PayloadReceived The round 3 payload received from the other participant. + * @param keyingMaterial The keying material as returned from {@link #calculateKeyingMaterial()}. + * @throws CryptoException if validation fails. + * @throws IllegalStateException if called prior to {@link #calculateKeyingMaterial()}, or multiple times + */ + public void validateRound3PayloadReceived(ECJPAKERound3Payload round3PayloadReceived, BigInteger keyingMaterial) + throws CryptoException + { + if (this.state >= STATE_ROUND_3_VALIDATED) + { + throw new IllegalStateException("Validation already attempted for round3 payload for" + participantId); + } + if (this.state < STATE_KEY_CALCULATED) + { + throw new IllegalStateException("Keying material must be calculated validated prior to validating Round3 payload for " + this.participantId); + } + ECJPAKEUtil.validateParticipantIdsDiffer(participantId, round3PayloadReceived.getParticipantId()); + ECJPAKEUtil.validateParticipantIdsEqual(this.partnerParticipantId, round3PayloadReceived.getParticipantId()); + + ECJPAKEUtil.validateMacTag( + this.participantId, + this.partnerParticipantId, + this.gx1, + this.gx2, + this.gx3, + this.gx4, + keyingMaterial, + this.digest, + round3PayloadReceived.getMacTag()); + + + /* + * Clear the rest of the fields. + */ + this.gx1 = null; + this.gx2 = null; + this.gx3 = null; + this.gx4 = null; + + this.state = STATE_ROUND_3_VALIDATED; + } + + private BigInteger calculateS() + { + try + { + return ECJPAKEUtil.calculateS(n, password); + } + catch (CryptoException e) + { + throw Exceptions.illegalStateException(e.getMessage(), e); + } + } + +} diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound1Payload.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound1Payload.java new file mode 100644 index 0000000000..897ff3f8c9 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound1Payload.java @@ -0,0 +1,94 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import org.bouncycastle.math.ec.ECPoint; + +/** + * The payload sent/received during the first round of a EC J-PAKE exchange. + *

    + * Each {@link ECJPAKEParticipant} creates and sends an instance + * of this payload to the other {@link ECJPAKEParticipant}. + * The payload to send should be created via + * {@link ECJPAKEParticipant#createRound1PayloadToSend()}. + *

    + * Each {@link ECJPAKEParticipant} must also validate the payload + * received from the other {@link ECJPAKEParticipant}. + * The received payload should be validated via + * {@link ECJPAKEParticipant#validateRound1PayloadReceived(ECJPAKERound1Payload)}. + */ +public class ECJPAKERound1Payload +{ + + private final String participantId; + + /** + * The value of g^x1 + */ + private final ECPoint gx1; + + /** + * The value of g^x2 + */ + private final ECPoint gx2; + + /** + * The zero knowledge proof for x1. + *

    + * This is a class {@link ECSchnorrZKP} with two fields, containing {g^v, r} for x1. + *

    + */ + private final ECSchnorrZKP knowledgeProofForX1; + + /** + * The zero knowledge proof for x2. + *

    + * This is a class {@link ECSchnorrZKP} with two fields, containing {g^v, r} for x2. + *

    + */ + private final ECSchnorrZKP knowledgeProofForX2; + + public ECJPAKERound1Payload( + String participantId, + ECPoint gx1, + ECPoint gx2, + ECSchnorrZKP knowledgeProofForX1, + ECSchnorrZKP knowledgeProofForX2) + { + ECJPAKEUtil.validateNotNull(participantId, "participantId"); + ECJPAKEUtil.validateNotNull(gx1, "gx1"); + ECJPAKEUtil.validateNotNull(gx2, "gx2"); + ECJPAKEUtil.validateNotNull(knowledgeProofForX1, "knowledgeProofForX1"); + ECJPAKEUtil.validateNotNull(knowledgeProofForX2, "knowledgeProofForX2"); + + this.participantId = participantId; + this.gx1 = gx1; + this.gx2 = gx2; + this.knowledgeProofForX1 = knowledgeProofForX1; + this.knowledgeProofForX2 = knowledgeProofForX2; + } + + public String getParticipantId() + { + return participantId; + } + + public ECPoint getGx1() + { + return gx1; + } + + public ECPoint getGx2() + { + return gx2; + } + + public ECSchnorrZKP getKnowledgeProofForX1() + { + return knowledgeProofForX1; + } + + public ECSchnorrZKP getKnowledgeProofForX2() + { + return knowledgeProofForX2; + } + +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound2Payload.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound2Payload.java new file mode 100644 index 0000000000..8b07a2ae7e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound2Payload.java @@ -0,0 +1,68 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import org.bouncycastle.math.ec.ECPoint; + +/** + * The payload sent/received during the second round of a EC J-PAKE exchange. + *

    + * Each {@link ECJPAKEParticipant} creates and sends an instance + * of this payload to the other {@link ECJPAKEParticipant}. + * The payload to send should be created via + * {@link ECJPAKEParticipant#createRound2PayloadToSend()} + *

    + * Each {@link ECJPAKEParticipant} must also validate the payload + * received from the other {@link ECJPAKEParticipant}. + * The received payload should be validated via + * {@link ECJPAKEParticipant#validateRound2PayloadReceived(ECJPAKERound2Payload)} + */ +public class ECJPAKERound2Payload +{ + + /** + * The id of the {@link ECJPAKEParticipant} who created/sent this payload. + */ + private final String participantId; + + /** + * The value of A, as computed during round 2. + */ + private final ECPoint a; + + /** + * The zero knowledge proof for x2 * s. + *

    + * This is a class {@link ECSchnorrZKP} with two fields, containing {g^v, r} for x2 * s. + *

    + */ + private final ECSchnorrZKP knowledgeProofForX2s; + + public ECJPAKERound2Payload( + String participantId, + ECPoint a, + ECSchnorrZKP knowledgeProofForX2s) + { + ECJPAKEUtil.validateNotNull(participantId, "participantId"); + ECJPAKEUtil.validateNotNull(a, "a"); + ECJPAKEUtil.validateNotNull(knowledgeProofForX2s, "knowledgeProofForX2s"); + + this.participantId = participantId; + this.a = a; + this.knowledgeProofForX2s = knowledgeProofForX2s; + } + + public String getParticipantId() + { + return participantId; + } + + public ECPoint getA() + { + return a; + } + + public ECSchnorrZKP getKnowledgeProofForX2s() + { + return knowledgeProofForX2s; + } + +} diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound3Payload.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound3Payload.java new file mode 100644 index 0000000000..4199fa7685 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKERound3Payload.java @@ -0,0 +1,50 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import java.math.BigInteger; + +/** + * The payload sent/received during the optional third round of a EC J-PAKE exchange, + * which is for explicit key confirmation. + *

    + * Each {@link ECJPAKEParticipant} creates and sends an instance + * of this payload to the other {@link ECJPAKEParticipant}. + * The payload to send should be created via + * {@link ECJPAKEParticipant#createRound3PayloadToSend(BigInteger)} + *

    + * Each {@link ECJPAKEParticipant} must also validate the payload + * received from the other {@link ECJPAKEParticipant}. + * The received payload should be validated via + * {@link ECJPAKEParticipant#validateRound3PayloadReceived(ECJPAKERound3Payload, BigInteger)} + */ +public class ECJPAKERound3Payload +{ + + /** + * The id of the {@link ECJPAKEParticipant} who created/sent this payload. + */ + private final String participantId; + + /** + * The value of MacTag, as computed by round 3. + * + * @see ECJPAKEUtil#calculateMacTag + */ + private final BigInteger macTag; + + public ECJPAKERound3Payload(String participantId, BigInteger magTag) + { + this.participantId = participantId; + this.macTag = magTag; + } + + public String getParticipantId() + { + return participantId; + } + + public BigInteger getMacTag() + { + return macTag; + } + +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKEUtil.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKEUtil.java new file mode 100644 index 0000000000..bc103cf597 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECJPAKEUtil.java @@ -0,0 +1,508 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.Mac; +import org.bouncycastle.crypto.macs.HMac; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; +import org.bouncycastle.util.Strings; + +/** + * Primitives needed for a EC J-PAKE exchange. + *

    + * The recommended way to perform an EC J-PAKE exchange is by using + * two {@link ECJPAKEParticipant}s. Internally, those participants + * call these primitive operations in {@link ECJPAKEUtil}. + *

    + * The primitives, however, can be used without a {@link ECJPAKEParticipant} + * if needed. + */ +public class ECJPAKEUtil +{ + static final BigInteger ZERO = BigInteger.valueOf(0); + static final BigInteger ONE = BigInteger.valueOf(1); + + /** + * Return a value that can be used as x1, x2, x3 or x4 during round 1. + *

    + * The returned value is a random value in the range [1, n-1]. + */ + public static BigInteger generateX1( + BigInteger n, + SecureRandom random) + { + BigInteger min = ONE; + BigInteger max = n.subtract(ONE); + return BigIntegers.createRandomInRange(min, max, random); + } + + /** + * Converts the given password to a {@link BigInteger} mod n. + */ + public static BigInteger calculateS( + BigInteger n, + byte[] password) + throws CryptoException + { + BigInteger s = new BigInteger(1, password).mod(n); + if (s.signum() == 0) + { + throw new CryptoException("MUST ensure s is not equal to 0 modulo n"); + } + return s; + } + + /** + * Converts the given password to a {@link BigInteger} mod n. + */ + public static BigInteger calculateS( + BigInteger n, + char[] password) + throws CryptoException + { + return calculateS(n, Strings.toUTF8ByteArray(password)); + } + + /** + * Calculate g^x as done in round 1. + */ + public static ECPoint calculateGx( + ECPoint g, + BigInteger x) + { + return g.multiply(x); + } + + /** + * Calculate ga as done in round 2. + */ + public static ECPoint calculateGA( + ECPoint gx1, + ECPoint gx3, + ECPoint gx4) + { + // ga = g^(x1+x3+x4) = g^x1 * g^x3 * g^x4 + return gx1.add(gx3).add(gx4); + } + + + /** + * Calculate x2 * s as done in round 2. + */ + public static BigInteger calculateX2s( + BigInteger n, + BigInteger x2, + BigInteger s) + { + return x2.multiply(s).mod(n); + } + + + /** + * Calculate A as done in round 2. + */ + public static ECPoint calculateA( + ECPoint gA, + BigInteger x2s) + { + // A = ga^(x*s) + return gA.multiply(x2s); + } + + /** + * Calculate a zero knowledge proof of x using Schnorr's signature. + * The returned object has two fields {g^v, r = v-x*h} for x. + */ + public static ECSchnorrZKP calculateZeroKnowledgeProof( + ECPoint generator, + BigInteger n, + BigInteger x, + ECPoint X, + Digest digest, + String userID, + SecureRandom random) + { + + /* Generate a random v from [1, n-1], and compute V = G*v */ + BigInteger v = BigIntegers.createRandomInRange(BigInteger.ONE, n.subtract(BigInteger.ONE), random); + ECPoint V = generator.multiply(v); + BigInteger h = calculateHashForZeroKnowledgeProof(generator, V, X, userID, digest); // h + // r = v-x*h mod n + + return new ECSchnorrZKP(V, v.subtract(x.multiply(h)).mod(n)); + } + + private static BigInteger calculateHashForZeroKnowledgeProof( + ECPoint g, + ECPoint v, + ECPoint x, + String participantId, + Digest digest) + { + digest.reset(); + + updateDigestIncludingSize(digest, g); + + updateDigestIncludingSize(digest, v); + + updateDigestIncludingSize(digest, x); + + updateDigestIncludingSize(digest, participantId); + + byte[] output = new byte[digest.getDigestSize()]; + digest.doFinal(output, 0); + + return new BigInteger(output); + } + + private static void updateDigestIncludingSize( + Digest digest, + ECPoint ecPoint) + { + byte[] byteArray = ecPoint.getEncoded(true); + digest.update(intToByteArray(byteArray.length), 0, 4); + digest.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + private static void updateDigestIncludingSize( + Digest digest, + String string) + { + byte[] byteArray = Strings.toUTF8ByteArray(string); + digest.update(intToByteArray(byteArray.length), 0, 4); + digest.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + /** + * Validates the zero knowledge proof (generated by + * {@link #calculateZeroKnowledgeProof(ECPoint, BigInteger, BigInteger, ECPoint, Digest, String, SecureRandom)}) + * is correct. + * + * @throws CryptoException if the zero knowledge proof is not correct + */ + public static void validateZeroKnowledgeProof( + ECPoint generator, + ECPoint X, + ECSchnorrZKP zkp, + BigInteger q, + BigInteger n, + ECCurve curve, + BigInteger coFactor, + String userID, + Digest digest) + throws CryptoException + { + ECPoint V = zkp.getV(); + BigInteger r = zkp.getr(); + /* ZKP: {V=G*v, r} */ + BigInteger h = calculateHashForZeroKnowledgeProof(generator, V, X, userID, digest); + + /* Public key validation based on the following paper (Sec 3) + * Antipa A., Brown D., Menezes A., Struik R. and Vanstone S. + * "Validation of elliptic curve public keys", PKC, 2002 + * https://iacr.org/archive/pkc2003/25670211/25670211.pdf + */ + // 1. X != infinity + if (X.isInfinity()) + { + throw new CryptoException("Zero-knowledge proof validation failed: X cannot equal infinity"); + } + + ECPoint x_normalized = X.normalize(); + // 2. Check x and y coordinates are in Fq, i.e., x, y in [0, q-1] + if (x_normalized.getAffineXCoord().toBigInteger().compareTo(BigInteger.ZERO) == -1 || + x_normalized.getAffineXCoord().toBigInteger().compareTo(q.subtract(BigInteger.ONE)) == 1 || + x_normalized.getAffineYCoord().toBigInteger().compareTo(BigInteger.ZERO) == -1 || + x_normalized.getAffineYCoord().toBigInteger().compareTo(q.subtract(BigInteger.ONE)) == 1) + { + throw new CryptoException("Zero-knowledge proof validation failed: x and y are not in the field"); + } + + // 3. Check X lies on the curve + try + { + curve.decodePoint(X.getEncoded(true)); + } + catch (Exception e) + { + throw new CryptoException("Zero-knowledge proof validation failed: x does not lie on the curve", e); + } + + // 4. Check that nX = infinity. + // It is equivalent - but more more efficient - to check the coFactor*X is not infinity + if (X.multiply(coFactor).isInfinity()) + { + throw new CryptoException("Zero-knowledge proof validation failed: Nx cannot be infinity"); + } + // Now check if V = G*r + X*h. + // Given that {G, X} are valid points on curve, the equality implies that V is also a point on curve. + if (!V.equals(generator.multiply(r).add(X.multiply(h.mod(n))))) + { + throw new CryptoException("Zero-knowledge proof validation failed: V must be a point on the curve"); + } + + } + + /** + * Validates that the given participant ids are not equal. + * (For the J-PAKE exchange, each participant must use a unique id.) + * + * @throws CryptoException if the participantId strings are equal. + */ + public static void validateParticipantIdsDiffer( + String participantId1, + String participantId2) + throws CryptoException + { + if (participantId1.equals(participantId2)) + { + throw new CryptoException( + "Both participants are using the same participantId (" + + participantId1 + + "). This is not allowed. " + + "Each participant must use a unique participantId."); + } + } + + /** + * Validates that the given participant ids are equal. + * This is used to ensure that the payloads received from + * each round all come from the same participant. + * + * @throws CryptoException if the participantId strings are equal. + */ + public static void validateParticipantIdsEqual( + String expectedParticipantId, + String actualParticipantId) + throws CryptoException + { + if (!expectedParticipantId.equals(actualParticipantId)) + { + throw new CryptoException( + "Received payload from incorrect partner (" + + actualParticipantId + + "). Expected to receive payload from " + + expectedParticipantId + + "."); + } + } + + /** + * Validates that the given object is not null. + * + * @param object object in question + * @param description name of the object (to be used in exception message) + * @throws NullPointerException if the object is null. + */ + public static void validateNotNull( + Object object, + String description) + { + if (object == null) + { + throw new NullPointerException(description + " must not be null"); + } + } + + /** + * Calculates the keying material, which can be done after round 2 has completed. + * A session key must be derived from this key material using a secure key derivation function (KDF). + * The KDF used to derive the key is handled externally (i.e. not by {@link ECJPAKEParticipant}). + *

    +     * KeyingMaterial = (B/g^{x2*x4*s})^x2
    +     * 
    + */ + public static BigInteger calculateKeyingMaterial( + BigInteger n, + ECPoint gx4, + BigInteger x2, + BigInteger s, + ECPoint B) + { + ECPoint k = ((B.subtract(gx4.multiply(x2.multiply(s).mod(n)))).multiply(x2)); + k = k.normalize(); + + return k.getAffineXCoord().toBigInteger(); + } + + /** + * Calculates the MacTag (to be used for key confirmation), as defined by + * NIST SP 800-56A Revision 3, + * Section 5.9.1 Unilateral Key Confirmation for Key Agreement Schemes. + *
    +     * MacTag = HMAC(MacKey, MacLen, MacData)
    +     *
    +     * MacKey = H(K || "ECJPAKE_KC")
    +     *
    +     * MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4
    +     *
    +     * Note that both participants use "KC_1_U" because the sender of the round 3 message
    +     * is always the initiator for key confirmation.
    +     *
    +     * HMAC = {@link HMac} used with the given {@link Digest}
    +     * H = The given {@link Digest}
    +     * MacOutputBits = MacTagBits, hence truncation function omitted.
    +     * MacLen = length of MacTag
    +     * 
    + */ + public static BigInteger calculateMacTag( + String participantId, + String partnerParticipantId, + ECPoint gx1, + ECPoint gx2, + ECPoint gx3, + ECPoint gx4, + BigInteger keyingMaterial, + Digest digest) + { + byte[] macKey = calculateMacKey( + keyingMaterial, + digest); + + HMac mac = new HMac(digest); + byte[] macOutput = new byte[mac.getMacSize()]; + mac.init(new KeyParameter(macKey)); + + /* + * MacData = "KC_1_U" || participantId_Alice || participantId_Bob || gx1 || gx2 || gx3 || gx4. + */ + updateMac(mac, "KC_1_U"); + updateMac(mac, participantId); + updateMac(mac, partnerParticipantId); + updateMac(mac, gx1); + updateMac(mac, gx2); + updateMac(mac, gx3); + updateMac(mac, gx4); + + mac.doFinal(macOutput, 0); + + Arrays.fill(macKey, (byte)0); + + return new BigInteger(macOutput); + + } + + /** + * Calculates the MacKey (i.e. the key to use when calculating the MagTag for key confirmation). + *
    +     * MacKey = H(K || "ECJPAKE_KC")
    +     * 
    + */ + private static byte[] calculateMacKey( + BigInteger keyingMaterial, + Digest digest) + { + digest.reset(); + + updateDigest(digest, keyingMaterial); + /* + * This constant is used to ensure that the macKey is NOT the same as the derived key. + */ + updateDigest(digest, "ECJPAKE_KC"); + + byte[] output = new byte[digest.getDigestSize()]; + digest.doFinal(output, 0); + + return output; + } + + /** + * Validates the MacTag received from the partner participant. + * + * @param partnerMacTag the MacTag received from the partner. + * @throws CryptoException if the participantId strings are equal. + */ + public static void validateMacTag( + String participantId, + String partnerParticipantId, + ECPoint gx1, + ECPoint gx2, + ECPoint gx3, + ECPoint gx4, + BigInteger keyingMaterial, + Digest digest, + BigInteger partnerMacTag) + throws CryptoException + { + /* + * Calculate the expected MacTag using the parameters as the partner + * would have used when the partner called calculateMacTag. + * + * i.e. basically all the parameters are reversed. + * participantId <-> partnerParticipantId + * x1 <-> x3 + * x2 <-> x4 + */ + BigInteger expectedMacTag = calculateMacTag( + partnerParticipantId, + participantId, + gx3, + gx4, + gx1, + gx2, + keyingMaterial, + digest); + + if (!expectedMacTag.equals(partnerMacTag)) + { + throw new CryptoException( + "Partner MacTag validation failed. " + + "Therefore, the password, MAC, or digest algorithm of each participant does not match."); + } + } + + private static void updateMac(Mac mac, ECPoint ecPoint) + { + byte[] byteArray = ecPoint.getEncoded(true); + mac.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + private static void updateMac(Mac mac, String string) + { + byte[] byteArray = Strings.toUTF8ByteArray(string); + mac.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + private static void updateDigest(Digest digest, ECPoint ecPoint) + { + byte[] byteArray = ecPoint.getEncoded(true); + digest.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + private static void updateDigest(Digest digest, String string) + { + byte[] byteArray = Strings.toUTF8ByteArray(string); + digest.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + private static void updateDigest(Digest digest, BigInteger bigInteger) + { + byte[] byteArray = BigIntegers.asUnsignedByteArray(bigInteger); + digest.update(byteArray, 0, byteArray.length); + Arrays.fill(byteArray, (byte)0); + } + + private static byte[] intToByteArray(int value) + { + return new byte[]{ + (byte)(value >>> 24), + (byte)(value >>> 16), + (byte)(value >>> 8), + (byte)value + }; + } + +} diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECSchnorrZKP.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECSchnorrZKP.java new file mode 100644 index 0000000000..df89cc1de7 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/ECSchnorrZKP.java @@ -0,0 +1,42 @@ +package org.bouncycastle.crypto.agreement.ecjpake; + +import java.math.BigInteger; + +import org.bouncycastle.math.ec.ECPoint; + +/** + * Package protected class containing zero knowledge proof, for an EC J-PAKE exchange. + *

    + * This class encapsulates the values involved in the Schnorr + * zero-knowledge proof used in the EC J-PAKE protocol. + *

    + */ +public class ECSchnorrZKP +{ + + /** + * The value of V = G x [v]. + */ + private final ECPoint V; + + /** + * The value of r = v - d * c mod n + */ + private final BigInteger r; + + ECSchnorrZKP(ECPoint V, BigInteger r) + { + this.V = V; + this.r = r; + } + + public ECPoint getV() + { + return V; + } + + public BigInteger getr() + { + return r; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/package-info.java b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/package-info.java new file mode 100644 index 0000000000..d73b626d3e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/ecjpake/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for Elliptic Curve Password Authenticated Key Exchange by Juggling (EC J-PAKE) key exchange. + */ +package org.bouncycastle.crypto.agreement.ecjpake; diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/jpake/package-info.java b/core/src/main/java/org/bouncycastle/crypto/agreement/jpake/package-info.java new file mode 100644 index 0000000000..2fb140e39f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/jpake/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for Password Authenticated Key Exchange by Juggling (J-PAKE) key exchange. + */ +package org.bouncycastle.crypto.agreement.jpake; diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/kdf/package-info.java b/core/src/main/java/org/bouncycastle/crypto/agreement/kdf/package-info.java new file mode 100644 index 0000000000..e250091ef1 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/kdf/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for KDF based key derivation functions. + */ +package org.bouncycastle.crypto.agreement.kdf; diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/package-info.java b/core/src/main/java/org/bouncycastle/crypto/agreement/package-info.java new file mode 100644 index 0000000000..775f1bbfed --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic key agreement classes. + */ +package org.bouncycastle.crypto.agreement; diff --git a/core/src/main/java/org/bouncycastle/crypto/agreement/srp/package-info.java b/core/src/main/java/org/bouncycastle/crypto/agreement/srp/package-info.java new file mode 100644 index 0000000000..64820008c2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/agreement/srp/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for Secure Remote Password (SRP) protocol. + */ +package org.bouncycastle.crypto.agreement.srp; diff --git a/core/src/main/java/org/bouncycastle/crypto/commitments/package-info.java b/core/src/main/java/org/bouncycastle/crypto/commitments/package-info.java new file mode 100644 index 0000000000..07c80dec61 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/commitments/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for supporting commitment calculation. + */ +package org.bouncycastle.crypto.commitments; diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconBaseDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconBaseDigest.java new file mode 100644 index 0000000000..872655f1cd --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconBaseDigest.java @@ -0,0 +1,87 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.engines.AsconPermutationFriend; + +abstract class AsconBaseDigest + extends BufferBaseDigest +{ + public static class Friend + { + private static final Friend INSTANCE = new Friend(); + + private Friend() + { + } + } + + AsconPermutationFriend.AsconPermutation p; + protected int ASCON_PB_ROUNDS = 12; + + protected AsconBaseDigest() + { + super(ProcessingBufferType.Immediate, 8); + p = AsconPermutationFriend.getAsconPermutation(ISAPDigest.Friend.getFriend(Friend.INSTANCE)); + DigestSize = 32; + } + + protected abstract long pad(int i); + + protected abstract long loadBytes(final byte[] bytes, int inOff); + + protected abstract long loadBytes(final byte[] bytes, int inOff, int n); + + protected abstract void setBytes(long w, byte[] bytes, int inOff); + + protected abstract void setBytes(long w, byte[] bytes, int inOff, int n); + + protected void processBytes(byte[] input, int inOff) + { + p.x0 ^= loadBytes(input, inOff); + p.p(ASCON_PB_ROUNDS); + } + + protected void finish(byte[] output, int outOff) + { + padAndAbsorb(); + /* squeeze full output blocks */ + squeeze(output, outOff, DigestSize); + } + + protected void padAndAbsorb() + { + p.x0 ^= loadBytes(m_buf, 0, m_bufPos) ^ pad(m_bufPos); + p.p(12); + } + + protected void squeeze(byte[] output, int outOff, int len) + { + /* squeeze full output blocks */ + while (len > BlockSize) + { + setBytes(p.x0, output, outOff); + p.p(ASCON_PB_ROUNDS); + outOff += BlockSize; + len -= BlockSize; + } + /* squeeze final output block */ + setBytes(p.x0, output, outOff, len); + } + + protected int hash(byte[] output, int outOff, int outLen) + { + ensureSufficientOutputBuffer(output, outOff, outLen); + padAndAbsorb(); + /* squeeze full output blocks */ + squeeze(output, outOff, outLen); + return outLen; + } + + protected void ensureSufficientOutputBuffer(byte[] output, int outOff, int len) + { + if (outOff + len > output.length) + { + throw new OutputLengthException("output buffer is too short"); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconCXof128.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconCXof128.java new file mode 100644 index 0000000000..2a21511369 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconCXof128.java @@ -0,0 +1,106 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.util.Pack; + +/** + * Ascon-CXOF128 was introduced in NIST Special Publication (SP) 800-232 + * (Initial Public Draft). + *

    + * Additional details and the specification can be found in: + * NIST SP 800-232 (Initial Public Draft). + * For reference source code and implementation details, please see: + * Reference, highly optimized, masked C and + * ASM implementations of Ascon (NIST SP 800-232). + *

    + */ +public class AsconCXof128 + extends AsconXofBase +{ + private final long z0, z1, z2, z3, z4; + + public AsconCXof128() + { + this(new byte[0], 0, 0); + } + + public AsconCXof128(byte[] s) + { + this(s, 0, s.length); + } + + public AsconCXof128(byte[] s, int off, int len) + { + algorithmName = "Ascon-CXOF128"; + ensureSufficientInputBuffer(s, off, len); + if (len > 256) + { + throw new DataLengthException("customized string is too long"); + } + initState(s, off, len); + // NOTE: Cache the initialized state + z0 = p.x0; + z1 = p.x1; + z2 = p.x2; + z3 = p.x3; + z4 = p.x4; + } + + protected long pad(int i) + { + return 0x01L << (i << 3); + } + + protected long loadBytes(final byte[] bytes, int inOff) + { + return Pack.littleEndianToLong(bytes, inOff); + } + + protected long loadBytes(final byte[] bytes, int inOff, int n) + { + return Pack.littleEndianToLong(bytes, inOff, n); + } + + protected void setBytes(long w, byte[] bytes, int inOff) + { + Pack.longToLittleEndian(w, bytes, inOff); + } + + protected void setBytes(long w, byte[] bytes, int inOff, int n) + { + Pack.longToLittleEndian(w, bytes, inOff, n); + } + + @Override + public void reset() + { + super.reset(); + /* initialize */ + p.set(z0, z1, z2, z3, z4); + } + + private void initState(byte[] z, int zOff, int zLen) + { +// p.set(0x0000080000cc0004L, 0L, 0L, 0L, 0L); +// p.p(12); + + if (zLen == 0) + { +// p.p(12); +// padAndAbsorb(); + + p.set(0x500cccc894e3c9e8L, 0x5bed06f28f71248dL, 0x3b03a0f930afd512L, 0x112ef093aa5c698bL, 0x00c8356340a347f0L); + } + else + { + p.set(0x675527c2a0e8de03L, 0x43d12d7dc0377bbcL, 0xe9901dec426e81b5L, 0x2ab14907720780b6L, 0x8f3f1d02d432bc46L); + + p.x0 ^= ((long)zLen) << 3; + p.p(12); + update(z, zOff, zLen); + padAndAbsorb(); + } + + super.reset(); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconDigest.java index fd4792745b..43f4af185f 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/AsconDigest.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconDigest.java @@ -1,19 +1,18 @@ package org.bouncycastle.crypto.digests; -import java.io.ByteArrayOutputStream; +import org.bouncycastle.util.Pack; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.ExtendedDigest; -import org.bouncycastle.crypto.OutputLengthException; - -/* ASCON v1.2 Digest, https://ascon.iaik.tugraz.at/ . +/** + * ASCON v1.2 Digest, https://ascon.iaik.tugraz.at/ . *

    * https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/ascon-spec-final.pdf *

    * ASCON v1.2 Digest with reference to C Reference Impl from: https://github.com/ascon/ascon-c . + * + * @deprecated use Ascon Hash 256 Digest */ public class AsconDigest - implements ExtendedDigest + extends AsconBaseDigest { public enum AsconParameters { @@ -42,173 +41,43 @@ public AsconDigest(AsconParameters parameters) reset(); } - private final String algorithmName; - private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - private long x0; - private long x1; - private long x2; - private long x3; - private long x4; - private final int CRYPTO_BYTES = 32; - private final int ASCON_PB_ROUNDS; - - private long ROR(long x, int n) - { - return x >>> n | x << (64 - n); - } - - private void ROUND(long C) - { - long t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C)); - long t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3)); - long t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4); - long t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4)); - long t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1); - x0 = t0 ^ ROR(t0, 19) ^ ROR(t0, 28); - x1 = t1 ^ ROR(t1, 39) ^ ROR(t1, 61); - x2 = ~(t2 ^ ROR(t2, 1) ^ ROR(t2, 6)); - x3 = t3 ^ ROR(t3, 10) ^ ROR(t3, 17); - x4 = t4 ^ ROR(t4, 7) ^ ROR(t4, 41); - } - - private void P(int nr) - { - if (nr == 12) - { - ROUND(0xf0L); - ROUND(0xe1L); - ROUND(0xd2L); - ROUND(0xc3L); - } - if (nr >= 8) - { - ROUND(0xb4L); - ROUND(0xa5L); - } - ROUND(0x96L); - ROUND(0x87L); - ROUND(0x78L); - ROUND(0x69L); - ROUND(0x5aL); - ROUND(0x4bL); - } - - private long PAD(int i) + protected long pad(int i) { return 0x80L << (56 - (i << 3)); } - private long LOADBYTES(final byte[] bytes, int inOff, int n) - { - long x = 0; - for (int i = 0; i < n; ++i) - { - x |= (bytes[i + inOff] & 0xFFL) << ((7 - i) << 3); - } - return x; - } - - private void STOREBYTES(byte[] bytes, int inOff, long w, int n) - { - for (int i = 0; i < n; ++i) - { - bytes[i + inOff] = (byte)(w >>> ((7 - i) << 3)); - } - } - - @Override - public String getAlgorithmName() - { - return algorithmName; - } - - @Override - public int getDigestSize() + protected long loadBytes(final byte[] bytes, int inOff) { - return CRYPTO_BYTES; + return Pack.bigEndianToLong(bytes, inOff); } - @Override - public int getByteLength() + protected long loadBytes(final byte[] bytes, int inOff, int n) { - return 8; + return Pack.bigEndianToLong(bytes, inOff, n); } - @Override - public void update(byte in) + protected void setBytes(long w, byte[] bytes, int inOff) { - buffer.write(in); + Pack.longToBigEndian(w, bytes, inOff); } - @Override - public void update(byte[] input, int inOff, int len) + protected void setBytes(long w, byte[] bytes, int inOff, int n) { - if ((inOff + len) > input.length) - { - throw new DataLengthException("input buffer too short"); - } - buffer.write(input, inOff, len); - } - - @Override - public int doFinal(byte[] output, int outOff) - { - if (CRYPTO_BYTES + outOff > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - byte[] input = buffer.toByteArray(); - int len = buffer.size(); - int inOff = 0; - /* absorb full plaintext blocks */ - int ASCON_HASH_RATE = 8; - while (len >= ASCON_HASH_RATE) - { - x0 ^= LOADBYTES(input, inOff, 8); - P(ASCON_PB_ROUNDS); - inOff += ASCON_HASH_RATE; - len -= ASCON_HASH_RATE; - } - /* absorb final plaintext block */ - x0 ^= LOADBYTES(input, inOff, len); - x0 ^= PAD(len); - int ASCON_PA_ROUNDS = 12; - P(ASCON_PA_ROUNDS); - /* squeeze full output blocks */ - len = CRYPTO_BYTES; - while (len > ASCON_HASH_RATE) - { - STOREBYTES(output, outOff, x0, 8); - P(ASCON_PB_ROUNDS); - outOff += ASCON_HASH_RATE; - len -= ASCON_HASH_RATE; - } - /* squeeze final output block */ - STOREBYTES(output, outOff, x0, len); - reset(); - return CRYPTO_BYTES; + Pack.longToBigEndian(w, bytes, inOff, n); } @Override public void reset() { - buffer.reset(); + super.reset(); /* initialize */ switch (asconParameters) { case AsconHashA: - x0 = 92044056785660070L; - x1 = 8326807761760157607L; - x2 = 3371194088139667532L; - x3 = -2956994353054992515L; - x4 = -6828509670848688761L; + p.set(92044056785660070L, 8326807761760157607L, 3371194088139667532L, -2956994353054992515L, -6828509670848688761L); break; case AsconHash: - x0 = -1255492011513352131L; - x1 = -8380609354527731710L; - x2 = -5437372128236807582L; - x3 = 4834782570098516968L; - x4 = 3787428097924915520L; + p.set(-1255492011513352131L, -8380609354527731710L, -5437372128236807582L, 4834782570098516968L, 3787428097924915520L); break; } } diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconHash256.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconHash256.java new file mode 100644 index 0000000000..4cb4fd648b --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconHash256.java @@ -0,0 +1,57 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.util.Pack; + +/** + * Ascon-Hash256 was introduced in NIST Special Publication (SP) 800-232 + * (Initial Public Draft). + *

    + * Additional details and the specification can be found in: + * NIST SP 800-232 (Initial Public Draft). + * For reference source code and implementation details, please see: + * Reference, highly optimized, masked C and + * ASM implementations of Ascon (NIST SP 800-232). + *

    + */ +public class AsconHash256 + extends AsconBaseDigest +{ + public AsconHash256() + { + algorithmName = "Ascon-Hash256"; + reset(); + } + + protected long pad(int i) + { + return 0x01L << (i << 3); + } + + protected long loadBytes(final byte[] bytes, int inOff) + { + return Pack.littleEndianToLong(bytes, inOff); + } + + protected long loadBytes(final byte[] bytes, int inOff, int n) + { + return Pack.littleEndianToLong(bytes, inOff, n); + } + + protected void setBytes(long w, byte[] bytes, int inOff) + { + Pack.longToLittleEndian(w, bytes, inOff); + } + + protected void setBytes(long w, byte[] bytes, int inOff, int n) + { + Pack.longToLittleEndian(w, bytes, inOff, n); + } + + @Override + public void reset() + { + super.reset(); + /* initialize */ + p.set(-7269279749984954751L, 5459383224871899602L, -5880230600644446182L, 4359436768738168243L, 1899470422303676269L); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof.java index e3b64eafe9..db57218f9e 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof.java @@ -1,19 +1,18 @@ package org.bouncycastle.crypto.digests; -import java.io.ByteArrayOutputStream; +import org.bouncycastle.util.Pack; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.Xof; - -/* ASCON v1.2 XOF, https://ascon.iaik.tugraz.at/ . +/** + * ASCON v1.2 XOF, https://ascon.iaik.tugraz.at/ . *

    * https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/ascon-spec-final.pdf *

    * ASCON v1.2 XOF with reference to C Reference Impl from: https://github.com/ascon/ascon-c . + * + * @deprecated Now superseded - please use AsconXof128 */ public class AsconXof - implements Xof + extends AsconXofBase { public enum AsconParameters { @@ -25,6 +24,7 @@ public enum AsconParameters public AsconXof(AsconXof.AsconParameters parameters) { + BlockSize = 8; this.asconParameters = parameters; switch (parameters) { @@ -42,185 +42,43 @@ public AsconXof(AsconXof.AsconParameters parameters) reset(); } - private final String algorithmName; - private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - private long x0; - private long x1; - private long x2; - private long x3; - private long x4; - private final int CRYPTO_BYTES = 32; - private final int ASCON_PB_ROUNDS; - - private long ROR(long x, int n) - { - return x >>> n | x << (64 - n); - } - - private void ROUND(long C) - { - long t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C)); - long t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3)); - long t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4); - long t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4)); - long t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1); - x0 = t0 ^ ROR(t0, 19) ^ ROR(t0, 28); - x1 = t1 ^ ROR(t1, 39) ^ ROR(t1, 61); - x2 = ~(t2 ^ ROR(t2, 1) ^ ROR(t2, 6)); - x3 = t3 ^ ROR(t3, 10) ^ ROR(t3, 17); - x4 = t4 ^ ROR(t4, 7) ^ ROR(t4, 41); - } - - private void P(int nr) - { - if (nr == 12) - { - ROUND(0xf0L); - ROUND(0xe1L); - ROUND(0xd2L); - ROUND(0xc3L); - } - if (nr >= 8) - { - ROUND(0xb4L); - ROUND(0xa5L); - } - ROUND(0x96L); - ROUND(0x87L); - ROUND(0x78L); - ROUND(0x69L); - ROUND(0x5aL); - ROUND(0x4bL); - } - - private long PAD(int i) + protected long pad(int i) { return 0x80L << (56 - (i << 3)); } - private long LOADBYTES(final byte[] bytes, int inOff, int n) - { - long x = 0; - for (int i = 0; i < n; ++i) - { - x |= (bytes[i + inOff] & 0xFFL) << ((7 - i) << 3); - } - return x; - } - - private void STOREBYTES(byte[] bytes, int inOff, long w, int n) - { - for (int i = 0; i < n; ++i) - { - bytes[i + inOff] = (byte)(w >>> ((7 - i) << 3)); - } - } - - @Override - public String getAlgorithmName() - { - return algorithmName; - } - - @Override - public int getDigestSize() + protected long loadBytes(final byte[] bytes, int inOff) { - return CRYPTO_BYTES; + return Pack.bigEndianToLong(bytes, inOff); } - @Override - public void update(byte in) + protected long loadBytes(final byte[] bytes, int inOff, int n) { - buffer.write(in); + return Pack.bigEndianToLong(bytes, inOff, n); } - @Override - public void update(byte[] input, int inOff, int len) + protected void setBytes(long w, byte[] bytes, int inOff) { - if ((inOff + len) > input.length) - { - throw new DataLengthException("input buffer too short"); - } - buffer.write(input, inOff, len); + Pack.longToBigEndian(w, bytes, inOff); } - @Override - public int doOutput(byte[] output, int outOff, int outLen) - { - if (CRYPTO_BYTES + outOff > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - byte[] input = buffer.toByteArray(); - int len = buffer.size(); - int inOff = 0; - /* absorb full plaintext blocks */ - int ASCON_HASH_RATE = 8; - while (len >= ASCON_HASH_RATE) - { - x0 ^= LOADBYTES(input, inOff, 8); - P(ASCON_PB_ROUNDS); - inOff += ASCON_HASH_RATE; - len -= ASCON_HASH_RATE; - } - /* absorb final plaintext block */ - x0 ^= LOADBYTES(input, inOff, len); - x0 ^= PAD(len); - int ASCON_PA_ROUNDS = 12; - P(ASCON_PA_ROUNDS); - /* squeeze full output blocks */ - len = CRYPTO_BYTES; - while (len > ASCON_HASH_RATE) - { - STOREBYTES(output, outOff, x0, 8); - P(ASCON_PB_ROUNDS); - outOff += ASCON_HASH_RATE; - len -= ASCON_HASH_RATE; - } - /* squeeze final output block */ - STOREBYTES(output, outOff, x0, len); - reset(); - return CRYPTO_BYTES; - } - - @Override - public int doFinal(byte[] output, int outOff) - { - return doOutput(output, outOff, getDigestSize()); - } - - @Override - public int doFinal(byte[] output, int outOff, int outLen) - { - return doOutput(output, outOff, outLen); - } - - @Override - public int getByteLength() + protected void setBytes(long w, byte[] bytes, int inOff, int n) { - return 8; + Pack.longToBigEndian(w, bytes, inOff, n); } @Override public void reset() { - buffer.reset(); + super.reset(); /* initialize */ switch (asconParameters) { case AsconXof: - x0 = -5368810569253202922L; - x1 = 3121280575360345120L; - x2 = 7395939140700676632L; - x3 = 6533890155656471820L; - x4 = 5710016986865767350L; + p.set(-5368810569253202922L, 3121280575360345120L, 7395939140700676632L, 6533890155656471820L, 5710016986865767350L); break; case AsconXofA: - x0 = 4940560291654768690L; - x1 = -3635129828240960206L; - x2 = -597534922722107095L; - x3 = 2623493988082852443L; - x4 = -6283826724160825537L; + p.set(4940560291654768690L, -3635129828240960206L, -597534922722107095L, 2623493988082852443L, -6283826724160825537L); break; } } diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof128.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof128.java new file mode 100644 index 0000000000..05dad34226 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconXof128.java @@ -0,0 +1,59 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.util.Pack; + +/** + * Ascon-XOF128 was introduced in NIST Special Publication (SP) 800-232 + * (Initial Public Draft). + *

    + * Additional details and the specification can be found in: + * NIST SP 800-232 (Initial Public Draft). + * For reference source code and implementation details, please see: + * Reference, highly optimized, masked C and + * ASM implementations of Ascon (NIST SP 800-232). + *

    + */ +public class AsconXof128 + extends AsconXofBase +{ + + public AsconXof128() + { + algorithmName = "Ascon-XOF-128"; + reset(); + } + + protected long pad(int i) + { + return 0x01L << (i << 3); + } + + protected long loadBytes(final byte[] bytes, int inOff) + { + return Pack.littleEndianToLong(bytes, inOff); + } + + protected long loadBytes(final byte[] bytes, int inOff, int n) + { + return Pack.littleEndianToLong(bytes, inOff, n); + } + + protected void setBytes(long w, byte[] bytes, int inOff) + { + Pack.longToLittleEndian(w, bytes, inOff); + } + + protected void setBytes(long w, byte[] bytes, int inOff, int n) + { + Pack.longToLittleEndian(w, bytes, inOff, n); + } + + @Override + public void reset() + { + super.reset(); + /* initialize */ + p.set(-2701369817892108309L, -3711838248891385495L, -1778763697082575311L, 1072114354614917324L, -2282070310009238562L); + } +} + diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/AsconXofBase.java b/core/src/main/java/org/bouncycastle/crypto/digests/AsconXofBase.java new file mode 100644 index 0000000000..2e28b2b01e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/AsconXofBase.java @@ -0,0 +1,106 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.crypto.Xof; + +abstract class AsconXofBase + extends AsconBaseDigest + implements Xof +{ + private boolean m_squeezing; + private final byte[] buffer = new byte[BlockSize]; + private int bytesInBuffer; + + @Override + public void update(byte in) + { + ensureNoAbsorbWhileSqueezing(m_squeezing); + super.update(in); + } + + @Override + public void update(byte[] input, int inOff, int len) + { + ensureNoAbsorbWhileSqueezing(m_squeezing); + super.update(input, inOff, len); + } + + @Override + public int doOutput(byte[] output, int outOff, int outLen) + { + ensureSufficientOutputBuffer(output, outOff, outLen); + + /* Use buffered output first */ + int bytesOutput = 0; + if (bytesInBuffer != 0) + { + int startPos = BlockSize - bytesInBuffer; + int bytesToOutput = Math.min(outLen, bytesInBuffer); + System.arraycopy(buffer, startPos, output, outOff, bytesToOutput); + bytesInBuffer -= bytesToOutput; + bytesOutput += bytesToOutput; + } + + int available = outLen - bytesOutput; + /* If we still need to output data */ + if (available >= BlockSize) + { + /* Output full blocks */ + int bytesToOutput = available - available % BlockSize; + bytesOutput += hash(output, outOff + bytesOutput, bytesToOutput); + } + + /* If we need to output a partial buffer */ + if (bytesOutput < outLen) + { + /* Access the next buffer's worth of data */ + hash(buffer, 0, BlockSize); + + /* Copy required length of data */ + int bytesToOutput = outLen - bytesOutput; + System.arraycopy(buffer, 0, output, outOff + bytesOutput, bytesToOutput); + bytesInBuffer = buffer.length - bytesToOutput; + bytesOutput += bytesToOutput; + } + + /* return the length of data output */ + return bytesOutput; + } + + @Override + public int doFinal(byte[] output, int outOff, int outLen) + { + int rlt = doOutput(output, outOff, outLen); + reset(); + return rlt; + } + + @Override + public void reset() + { + m_squeezing = false; + bytesInBuffer = 0; + super.reset(); + } + + @Override + protected void padAndAbsorb() + { + if (!m_squeezing) + { + m_squeezing = true; + super.padAndAbsorb(); + } + else + { + p.p(ASCON_PB_ROUNDS); + } + } + + private void ensureNoAbsorbWhileSqueezing(boolean m_squeezing) + { + if (m_squeezing) + { + throw new IllegalStateException("attempt to absorb while squeezing"); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/BufferBaseDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/BufferBaseDigest.java new file mode 100644 index 0000000000..c6cdaed6f2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/BufferBaseDigest.java @@ -0,0 +1,196 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.ExtendedDigest; +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.util.Arrays; + +abstract class BufferBaseDigest + implements ExtendedDigest +{ + protected static class ProcessingBufferType + { + public static final int BUFFERED = 0; + public static final int IMMEDIATE = 1; + + public static final ProcessingBufferType Buffered = new ProcessingBufferType(BUFFERED); + public static final ProcessingBufferType Immediate = new ProcessingBufferType(IMMEDIATE); + + private final int ord; + + ProcessingBufferType(int ord) + { + this.ord = ord; + } + } + + protected int DigestSize; + protected int BlockSize; + protected byte[] m_buf; + protected int m_bufPos; + protected String algorithmName; + protected ProcessingBuffer processor; + + protected BufferBaseDigest(ProcessingBufferType type, int BlockSize) + { + this.BlockSize = BlockSize; + m_buf = new byte[BlockSize]; + switch (type.ord) + { + case ProcessingBufferType.BUFFERED: + processor = new BufferedProcessor(); + break; + case ProcessingBufferType.IMMEDIATE: + processor = new ImmediateProcessor(); + break; + } + } + + protected interface ProcessingBuffer + { + void update(byte input); + + boolean isLengthWithinAvailableSpace(int len, int available); + + boolean isLengthExceedingBlockSize(int len, int size); + } + + private class BufferedProcessor + implements ProcessingBuffer + { + public void update(byte input) + { + if (m_bufPos == BlockSize) + { + processBytes(m_buf, 0); + m_bufPos = 0; + } + m_buf[m_bufPos++] = input; + } + + @Override + public boolean isLengthWithinAvailableSpace(int len, int available) + { + return len <= available; + } + + @Override + public boolean isLengthExceedingBlockSize(int len, int size) + { + return len > size; + } + } + + private class ImmediateProcessor + implements ProcessingBuffer + { + public void update(byte input) + { + m_buf[m_bufPos] = input; + if (++m_bufPos == BlockSize) + { + processBytes(m_buf, 0); + m_bufPos = 0; + } + } + + @Override + public boolean isLengthWithinAvailableSpace(int len, int available) + { + return len < available; + } + + @Override + public boolean isLengthExceedingBlockSize(int len, int size) + { + return len >= size; + } + } + + @Override + public String getAlgorithmName() + { + return algorithmName; + } + + @Override + public int getDigestSize() + { + return DigestSize; + } + + @Override + public int getByteLength() + { + return BlockSize; + } + + @Override + public void update(byte in) + { + processor.update(in); + } + + @Override + public void update(byte[] input, int inOff, int len) + { + ensureSufficientInputBuffer(input, inOff, len); + int available = BlockSize - m_bufPos; + if (processor.isLengthWithinAvailableSpace(len, available)) + { + System.arraycopy(input, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return; + } + if (m_bufPos > 0) + { + System.arraycopy(input, inOff, m_buf, m_bufPos, available); + inOff += available; + len -= available; + processBytes(m_buf, 0); + } + while (processor.isLengthExceedingBlockSize(len, BlockSize)) + { + processBytes(input, inOff); + inOff += BlockSize; + len -= BlockSize; + } + System.arraycopy(input, inOff, m_buf, 0, len); + m_bufPos = len; + } + + @Override + public int doFinal(byte[] output, int outOff) + { + ensureSufficientOutputBuffer(output, outOff); + finish(output, outOff); + reset(); + return DigestSize; + } + + public void reset() + { + Arrays.clear(m_buf); + m_bufPos = 0; + } + + protected void ensureSufficientInputBuffer(byte[] input, int inOff, int len) + { + if (inOff + len > input.length) + { + throw new DataLengthException("input buffer too short"); + } + } + + protected void ensureSufficientOutputBuffer(byte[] output, int outOff) + { + if (DigestSize + outOff > output.length) + { + throw new OutputLengthException("output buffer is too short"); + } + } + + protected abstract void processBytes(byte[] input, int inOff); + + protected abstract void finish(byte[] output, int outOff); +} diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/ISAPDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/ISAPDigest.java index 9120e7592d..853db0b309 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/ISAPDigest.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/ISAPDigest.java @@ -1,10 +1,6 @@ package org.bouncycastle.crypto.digests; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.engines.AsconPermutationFriend; import org.bouncycastle.util.Pack; /** @@ -16,131 +12,68 @@ */ public class ISAPDigest - implements Digest + extends BufferBaseDigest { - private long x0, x1, x2, x3, x4; - private long t0, t1, t2, t3, t4; - private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - private void ROUND(long C) - { - t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C)); - t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3)); - t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4); - t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4)); - t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1); - x0 = t0 ^ ROTR(t0, 19) ^ ROTR(t0, 28); - x1 = t1 ^ ROTR(t1, 39) ^ ROTR(t1, 61); - x2 = ~(t2 ^ ROTR(t2, 1) ^ ROTR(t2, 6)); - x3 = t3 ^ ROTR(t3, 10) ^ ROTR(t3, 17); - x4 = t4 ^ ROTR(t4, 7) ^ ROTR(t4, 41); - } - - private void P12() - { - ROUND(0xf0); - ROUND(0xe1); - ROUND(0xd2); - ROUND(0xc3); - ROUND(0xb4); - ROUND(0xa5); - ROUND(0x96); - ROUND(0x87); - ROUND(0x78); - ROUND(0x69); - ROUND(0x5a); - ROUND(0x4b); - } - - private long ROTR(long x, long n) + public static class Friend { - return (x >>> n) | (x << (64 - n)); - } + private static final Friend INSTANCE = new Friend(); - protected long U64BIG(long x) - { - return ((ROTR(x, 8) & (0xFF000000FF000000L)) | (ROTR(x, 24) & (0x00FF000000FF0000L)) | - (ROTR(x, 40) & (0x0000FF000000FF00L)) | (ROTR(x, 56) & (0x000000FF000000FFL))); - } + private Friend() + { + } - @Override - public String getAlgorithmName() - { - return "ISAP Hash"; + static Friend getFriend(AsconBaseDigest.Friend friend) + { + if (null == friend) + { + throw new NullPointerException("This method is only for use by AsconBaseDigest"); + } + return INSTANCE; + } } - @Override - public int getDigestSize() - { - return 32; - } + private final AsconPermutationFriend.AsconPermutation p; - @Override - public void update(byte input) + public ISAPDigest() { - buffer.write(input); + super(ProcessingBufferType.Immediate, 8); + p = AsconPermutationFriend.getAsconPermutation(Friend.INSTANCE); + DigestSize = 32; + algorithmName = "ISAP Hash"; + reset(); } @Override - public void update(byte[] input, int inOff, int len) + protected void processBytes(byte[] input, int inOff) { - if ((inOff + len) > input.length) - { - throw new DataLengthException("input buffer too short"); - } - buffer.write(input, inOff, len); + /* absorb */ + p.x0 ^= Pack.bigEndianToLong(input, inOff); + p.p(12); } @Override - public int doFinal(byte[] out, int outOff) + protected void finish(byte[] output, int outOff) { - if (32 + outOff > out.length) - { - throw new OutputLengthException("output buffer is too short"); - } - t0 = t1 = t2 = t3 = t4 = 0; - /* init state */ - x0 = -1255492011513352131L; - x1 = -8380609354527731710L; - x2 = -5437372128236807582L; - x3 = 4834782570098516968L; - x4 = 3787428097924915520L; - /* absorb */ - byte[] input = buffer.toByteArray(); - int len = input.length; - long[] in64 = new long[len >> 3]; - Pack.littleEndianToLong(input, 0, in64, 0, in64.length); - int idx = 0; - while (len >= 8) - { - x0 ^= U64BIG(in64[idx++]); - P12(); - len -= 8; - } /* absorb final input block */ - x0 ^= 0x80L << ((7 - len) << 3); - while (len > 0) + p.x0 ^= 0x80L << ((7 - m_bufPos) << 3); + while (m_bufPos > 0) { - x0 ^= (input[(idx << 3) + --len] & 0xFFL) << ((7 - len) << 3); + p.x0 ^= (m_buf[--m_bufPos] & 0xFFL) << ((7 - m_bufPos) << 3); } - P12(); // squeeze - long[] out64 = new long[4]; - for (idx = 0; idx < 3; ++idx) + for (int i = 0; i < 4; ++i) { - out64[idx] = U64BIG(x0); - P12(); + p.p(12); + Pack.longToBigEndian(p.x0, output, outOff); + outOff += 8; } - /* squeeze final output block */ - out64[idx] = U64BIG(x0); - Pack.longToLittleEndian(out64, out, outOff); - buffer.reset(); - return 32; } @Override public void reset() { - buffer.reset(); + super.reset(); + /* init state */ + p.set(-1255492011513352131L, -8380609354527731710L, -5437372128236807582L, 4834782570098516968L, 3787428097924915520L); } } diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/ParallelHash.java b/core/src/main/java/org/bouncycastle/crypto/digests/ParallelHash.java index 5ac7f120d0..7b05eb52ca 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/ParallelHash.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/ParallelHash.java @@ -38,8 +38,8 @@ public class ParallelHash * Base constructor. * * @param bitLength security strength (bits) of the underlying SHAKE function, 128 or 256. - * @param S the customization string - available for local use. - * @param B the blocksize (in bytes) for hashing. + * @param S the customization string - available for local use. + * @param B the blocksize (in bytes) for hashing. */ public ParallelHash(int bitLength, byte[] S, int B) { @@ -50,12 +50,18 @@ public ParallelHash(int bitLength, byte[] S, int B, int outputSize) { this(bitLength, S, B, outputSize, CryptoServicePurpose.ANY); } + public ParallelHash(int bitLength, byte[] S, int B, int outputSize, CryptoServicePurpose purpose) { + if (B <= 0) + { + throw new IllegalArgumentException("block size should be greater than 0"); + } this.cshake = new CSHAKEDigest(bitLength, N_PARALLEL_HASH, S); this.compressor = new CSHAKEDigest(bitLength, new byte[0], new byte[0]); this.bitLength = bitLength; this.B = B; + this.outputLength = (outputSize + 7) / 8; this.buffer = new byte[B]; this.compressorBuffer = new byte[bitLength * 2 / 8]; @@ -112,7 +118,7 @@ public void update(byte in) public void update(byte[] in, int inOff, int len) throws DataLengthException, IllegalStateException { - len = Math.max(0, len); + len = Math.max(0, len); // // fill the current word @@ -198,7 +204,7 @@ public int doFinal(byte[] out, int outOff, int outLen) { wrapUp(outputLength); } - + int rv = cshake.doFinal(out, outOff, outLen); reset(); diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/PhotonBeetleDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/PhotonBeetleDigest.java index 853a93dd44..62e04624e5 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/PhotonBeetleDigest.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/PhotonBeetleDigest.java @@ -1,10 +1,6 @@ package org.bouncycastle.crypto.digests; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.engines.PhotonBeetleEngine; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Bytes; @@ -16,204 +12,85 @@ *

    */ public class PhotonBeetleDigest - implements Digest + extends BufferBaseDigest { - private byte[] state; - private byte[][] state_2d; - private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - private final int INITIAL_RATE_INBYTES = 16; - private int RATE_INBYTES = 4; - private int SQUEEZE_RATE_INBYTES = 16; - private int STATE_INBYTES = 32; - private int TAG_INBYTES = 32; - private int LAST_THREE_BITS_OFFSET = 5; - private int ROUND = 12; - private int D = 8; - private int Dq = 3; - private int Dr = 7; - private int DSquare = 64; - private int S = 4; - private int S_1 = 3; - private byte[][] RC = {//[D][12] - {1, 3, 7, 14, 13, 11, 6, 12, 9, 2, 5, 10}, - {0, 2, 6, 15, 12, 10, 7, 13, 8, 3, 4, 11}, - {2, 0, 4, 13, 14, 8, 5, 15, 10, 1, 6, 9}, - {6, 4, 0, 9, 10, 12, 1, 11, 14, 5, 2, 13}, - {14, 12, 8, 1, 2, 4, 9, 3, 6, 13, 10, 5}, - {15, 13, 9, 0, 3, 5, 8, 2, 7, 12, 11, 4}, - {13, 15, 11, 2, 1, 7, 10, 0, 5, 14, 9, 6}, - {9, 11, 15, 6, 5, 3, 14, 4, 1, 10, 13, 2} - }; - private byte[][] MixColMatrix = { //[D][D] - {2, 4, 2, 11, 2, 8, 5, 6}, - {12, 9, 8, 13, 7, 7, 5, 2}, - {4, 4, 13, 13, 9, 4, 13, 9}, - {1, 6, 5, 1, 12, 13, 15, 14}, - {15, 12, 9, 13, 14, 5, 14, 13}, - {9, 14, 5, 15, 4, 12, 9, 6}, - {12, 2, 2, 10, 3, 1, 1, 14}, - {15, 1, 13, 10, 5, 10, 2, 3} - }; - - private byte[] sbox = {12, 5, 6, 11, 9, 0, 10, 13, 3, 14, 15, 8, 4, 7, 1, 2}; - - public PhotonBeetleDigest() + public static class Friend { - state = new byte[STATE_INBYTES]; - state_2d = new byte[D][D]; - } + private static final Friend INSTANCE = new Friend(); - @Override - public String getAlgorithmName() - { - return "Photon-Beetle Hash"; + private Friend() + { + } } - @Override - public int getDigestSize() - { - return TAG_INBYTES; - } + private final byte[] state; + private static final int SQUEEZE_RATE_INBYTES = 16; + private static final int D = 8; + private int blockCount; - @Override - public void update(byte input) + public PhotonBeetleDigest() { - buffer.write(input); + super(ProcessingBufferType.Buffered, 4); + DigestSize = 32; + state = new byte[DigestSize]; + algorithmName = "Photon-Beetle Hash"; + blockCount = 0; } @Override - public void update(byte[] input, int inOff, int len) + protected void processBytes(byte[] input, int inOff) { - if ((inOff + len) > input.length) + if (blockCount < 4) { - throw new DataLengthException("input buffer too short"); + System.arraycopy(input, inOff, state, blockCount << 2, BlockSize); } - buffer.write(input, inOff, len); + else + { + PhotonBeetleEngine.photonPermutation(Friend.INSTANCE, state); + Bytes.xorTo(BlockSize, input, inOff, state); + } + blockCount++; } @Override - public int doFinal(byte[] output, int outOff) + protected void finish(byte[] output, int outOff) { - if (32 + outOff > output.length) + int LAST_THREE_BITS_OFFSET = 5; + if (m_bufPos == 0 && blockCount == 0) { - throw new OutputLengthException("output buffer is too short"); + state[DigestSize - 1] ^= 1 << LAST_THREE_BITS_OFFSET; } - byte[] input = buffer.toByteArray(); - int inlen = input.length; - if (inlen == 0) + else if (blockCount < 4) { - state[STATE_INBYTES - 1] ^= 1 << LAST_THREE_BITS_OFFSET; + System.arraycopy(m_buf, 0, state, blockCount << 2, m_bufPos); + state[(blockCount << 2) + m_bufPos] ^= 0x01; // ozs + state[DigestSize - 1] ^= (byte)1 << LAST_THREE_BITS_OFFSET; } - else if (inlen <= INITIAL_RATE_INBYTES) + else if (blockCount == 4 && m_bufPos == 0) { - System.arraycopy(input, 0, state, 0, inlen); - if (inlen < INITIAL_RATE_INBYTES) - { - state[inlen] ^= 0x01; // ozs - } - state[STATE_INBYTES - 1] ^= (inlen < INITIAL_RATE_INBYTES ? (byte)1 : (byte)2) << LAST_THREE_BITS_OFFSET; + state[DigestSize - 1] ^= (byte)2 << LAST_THREE_BITS_OFFSET; } else { - System.arraycopy(input, 0, state, 0, INITIAL_RATE_INBYTES); - inlen -= INITIAL_RATE_INBYTES; - int Dlen_inblocks = (inlen + RATE_INBYTES - 1) / RATE_INBYTES; - int i, LastDBlocklen; - for (i = 0; i < Dlen_inblocks - 1; i++) + PhotonBeetleEngine.photonPermutation(Friend.INSTANCE, state); + Bytes.xorTo(m_bufPos, m_buf, state); + if (m_bufPos < BlockSize) { - PHOTON_Permutation(); - Bytes.xorTo(RATE_INBYTES, input, INITIAL_RATE_INBYTES + i * RATE_INBYTES, state, 0); + state[m_bufPos] ^= 0x01; // ozs } - PHOTON_Permutation(); - LastDBlocklen = inlen - i * RATE_INBYTES; - Bytes.xorTo(LastDBlocklen, input, INITIAL_RATE_INBYTES + i * RATE_INBYTES, state, 0); - if (LastDBlocklen < RATE_INBYTES) - { - state[LastDBlocklen] ^= 0x01; // ozs - } - state[STATE_INBYTES - 1] ^= (inlen % RATE_INBYTES == 0 ? (byte)1 : (byte)2) << LAST_THREE_BITS_OFFSET; + state[DigestSize - 1] ^= (m_bufPos % BlockSize == 0 ? (byte)1 : (byte)2) << LAST_THREE_BITS_OFFSET; } - PHOTON_Permutation(); + PhotonBeetleEngine.photonPermutation(Friend.INSTANCE, state); System.arraycopy(state, 0, output, outOff, SQUEEZE_RATE_INBYTES); - PHOTON_Permutation(); - System.arraycopy(state, 0, output, outOff + SQUEEZE_RATE_INBYTES, TAG_INBYTES - SQUEEZE_RATE_INBYTES); - return TAG_INBYTES; + PhotonBeetleEngine.photonPermutation(Friend.INSTANCE, state); + System.arraycopy(state, 0, output, outOff + SQUEEZE_RATE_INBYTES, SQUEEZE_RATE_INBYTES); } @Override public void reset() { - buffer.reset(); + super.reset(); Arrays.fill(state, (byte)0); + blockCount = 0; } - - void PHOTON_Permutation() - { - int i, j, k, l; - for (i = 0; i < DSquare; i++) - { - state_2d[i >>> Dq][i & Dr] = (byte)(((state[i >> 1] & 0xFF) >>> (4 * (i & 1))) & 0xf); - } - for (int round = 0; round < ROUND; round++) - { - //AddKey - for (i = 0; i < D; i++) - { - state_2d[i][0] ^= RC[i][round]; - } - //SubCell - for (i = 0; i < D; i++) - { - for (j = 0; j < D; j++) - { - state_2d[i][j] = sbox[state_2d[i][j]]; - } - } - //ShiftRow - for (i = 1; i < D; i++) - { - System.arraycopy(state_2d[i], 0, state, 0, D); - System.arraycopy(state, i, state_2d[i], 0, D - i); - System.arraycopy(state, 0, state_2d[i], D - i, i); - } - //MixColumn - for (j = 0; j < D; j++) - { - for (i = 0; i < D; i++) - { - byte sum = 0; - for (k = 0; k < D; k++) - { - int x = MixColMatrix[i][k], ret = 0, b = state_2d[k][j]; - for (l = 0; l < S; l++) - { - if (((b >>> l) & 1) != 0) - { - ret ^= x; - } - if (((x >>> S_1) & 1) != 0) - { - x <<= 1; - x ^= 0x3; - } - else - { - x <<= 1; - } - } - sum ^= ret & 15; - } - state[i] = sum; - } - for (i = 0; i < D; i++) - { - state_2d[i][j] = state[i]; - } - } - } - for (i = 0; i < DSquare; i += 2) - { - state[i >>> 1] = (byte)(((state_2d[i >>> Dq][i & Dr] & 0xf)) | ((state_2d[i >>> Dq][(i + 1) & Dr] & 0xf) << 4)); - } - } -} +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/RomulusDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/RomulusDigest.java new file mode 100644 index 0000000000..4d5a722198 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/RomulusDigest.java @@ -0,0 +1,67 @@ +package org.bouncycastle.crypto.digests; + +import org.bouncycastle.crypto.engines.RomulusEngine; +import org.bouncycastle.util.Arrays; + +/** + * Romulus v1.3, based on the current round 3 submission, https://romulusae.github.io/romulus/ + * Reference C implementation: https://github.com/romulusae/romulus + * Specification: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/romulus-spec-final.pdf + */ + +public class RomulusDigest + extends BufferBaseDigest +{ + public static class Friend + { + private static final Friend INSTANCE = new Friend(); + + private Friend() + { + } + } + + private final byte[] h = new byte[16]; + private final byte[] g = new byte[16]; + /* + * This file includes only the encryption function of SKINNY-128-384+ as required by Romulus-v1.3 + */ +// Packing of data is done as follows (state[i][j] stands for row i and column j): +// 0 1 2 3 +// 4 5 6 7 +// 8 9 10 11 +//12 13 14 15 + + public RomulusDigest() + { + super(ProcessingBufferType.Immediate, 32); + DigestSize = 32; + algorithmName = "Romulus Hash"; + } + + @Override + protected void processBytes(byte[] input, int inOff) + { + RomulusEngine.hirose_128_128_256(Friend.INSTANCE, h, g, input, inOff); + } + + @Override + protected void finish(byte[] output, int outOff) + { + Arrays.fill(m_buf, m_bufPos, 31, (byte)0); + m_buf[31] = (byte)(m_bufPos & 0x1f); + h[0] ^= 2; + RomulusEngine.hirose_128_128_256(Friend.INSTANCE, h, g, m_buf, 0); + // Assign the output tag + System.arraycopy(h, 0, output, outOff, 16); + System.arraycopy(g, 0, output, 16 + outOff, 16); + } + + @Override + public void reset() + { + super.reset(); + Arrays.clear(h); + Arrays.clear(g); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/SparkleDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/SparkleDigest.java index 90c17f62ea..7cabb2df28 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/SparkleDigest.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/SparkleDigest.java @@ -1,8 +1,5 @@ package org.bouncycastle.crypto.digests; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.ExtendedDigest; -import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.engines.SparkleEngine; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; @@ -14,12 +11,15 @@ * Specification: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/sparkle-spec-final.pdf */ public class SparkleDigest - implements ExtendedDigest + extends BufferBaseDigest { public static class Friend { private static final Friend INSTANCE = new Friend(); - private Friend() {} + + private Friend() + { + } } public enum SparkleParameters @@ -28,33 +28,27 @@ public enum SparkleParameters ESCH384 } - private static final int RATE_BYTES = 16; private static final int RATE_WORDS = 4; - - private String algorithmName; private final int[] state; - private final byte[] m_buf = new byte[RATE_BYTES]; - private final int DIGEST_BYTES; private final int SPARKLE_STEPS_SLIM; private final int SPARKLE_STEPS_BIG; private final int STATE_WORDS; - private int m_bufPos = 0; - public SparkleDigest(SparkleParameters sparkleParameters) { + super(ProcessingBufferType.Buffered, 16); switch (sparkleParameters) { case ESCH256: algorithmName = "ESCH-256"; - DIGEST_BYTES = 32; + DigestSize = 32; SPARKLE_STEPS_SLIM = 7; SPARKLE_STEPS_BIG = 11; STATE_WORDS = 12; break; case ESCH384: algorithmName = "ESCH-384"; - DIGEST_BYTES = 48; + DigestSize = 48; SPARKLE_STEPS_SLIM = 8; SPARKLE_STEPS_BIG = 12; STATE_WORDS = 16; @@ -62,97 +56,26 @@ public SparkleDigest(SparkleParameters sparkleParameters) default: throw new IllegalArgumentException("Invalid definition of SCHWAEMM instance"); } - state = new int[STATE_WORDS]; } @Override - public String getAlgorithmName() - { - return algorithmName; - } - - @Override - public int getDigestSize() - { - return DIGEST_BYTES; - } - - @Override - public int getByteLength() - { - return RATE_BYTES; - } - - @Override - public void update(byte input) - { - if (m_bufPos == RATE_BYTES) - { - processBlock(m_buf, 0, SPARKLE_STEPS_SLIM); - m_bufPos = 0; - } - - m_buf[m_bufPos++] = input; - } - - @Override - public void update(byte[] in, int inOff, int len) + protected void processBytes(byte[] input, int inOff) { - if (inOff > in.length - len) - { - throw new DataLengthException(algorithmName + " input buffer too short"); - } - - if (len < 1) - return; - - int available = RATE_BYTES - m_bufPos; - if (len <= available) - { - System.arraycopy(in, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return; - } - - int inPos = 0; - if (m_bufPos > 0) - { - System.arraycopy(in, inOff, m_buf, m_bufPos, available); - processBlock(m_buf, 0, SPARKLE_STEPS_SLIM); - inPos += available; - } - - int remaining; - while ((remaining = len - inPos) > RATE_BYTES) - { - processBlock(in, inOff + inPos, SPARKLE_STEPS_SLIM); - inPos += RATE_BYTES; - } - - System.arraycopy(in, inOff + inPos, m_buf, 0, remaining); - m_bufPos = remaining; + processBlock(input, inOff, SPARKLE_STEPS_SLIM); } @Override - public int doFinal(byte[] output, int outOff) + protected void finish(byte[] output, int outOff) { - if (outOff > output.length - DIGEST_BYTES) - { - throw new OutputLengthException(algorithmName + " input buffer too short"); - } - // addition of constant M1 or M2 to the state - if (m_bufPos < RATE_BYTES) + if (m_bufPos < BlockSize) { state[(STATE_WORDS >> 1) - 1] ^= 1 << 24; // padding - m_buf[m_bufPos] = (byte)0x80; - while(++m_bufPos < RATE_BYTES) - { - m_buf[m_bufPos] = 0x00; - } + m_buf[m_bufPos++] = (byte)0x80; + Arrays.fill(m_buf, m_bufPos, BlockSize, (byte)0); } else { @@ -175,24 +98,20 @@ public int doFinal(byte[] output, int outOff) SparkleEngine.sparkle_opt12(Friend.INSTANCE, state, SPARKLE_STEPS_SLIM); Pack.intToLittleEndian(state, 0, RATE_WORDS, output, outOff + 16); } - - reset(); - return DIGEST_BYTES; } @Override public void reset() { + super.reset(); Arrays.fill(state, 0); - Arrays.fill(m_buf, (byte)0); - m_bufPos = 0; } private void processBlock(byte[] buf, int off, int steps) { - int t0 = Pack.littleEndianToInt(buf, off ); - int t1 = Pack.littleEndianToInt(buf, off + 4); - int t2 = Pack.littleEndianToInt(buf, off + 8); + int t0 = Pack.littleEndianToInt(buf, off); + int t1 = Pack.littleEndianToInt(buf, off + 4); + int t2 = Pack.littleEndianToInt(buf, off + 8); int t3 = Pack.littleEndianToInt(buf, off + 12); // addition of a buffer block to the state @@ -220,4 +139,4 @@ private static int ELL(int x) { return Integers.rotateRight(x, 16) ^ (x & 0xFFFF); } -} +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/XoodyakDigest.java b/core/src/main/java/org/bouncycastle/crypto/digests/XoodyakDigest.java index 476dee34ed..ee099c4b9b 100644 --- a/core/src/main/java/org/bouncycastle/crypto/digests/XoodyakDigest.java +++ b/core/src/main/java/org/bouncycastle/crypto/digests/XoodyakDigest.java @@ -1,12 +1,7 @@ package org.bouncycastle.crypto.digests; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.engines.XoodyakEngine; import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Pack; /** * Xoodyak v1, https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/xoodyak-spec-final.pdf @@ -16,191 +11,71 @@ */ public class XoodyakDigest - implements Digest + extends BufferBaseDigest { - private byte[] state; - private int phase; - private MODE mode; - private int Rabsorb; - private final int f_bPrime = 48; - private final int Rhash = 16; - private final int PhaseDown = 1; - private final int PhaseUp = 2; - private final int NLANES = 12; - private final int NROWS = 3; - private final int NCOLUMS = 4; - private final int MAXROUNDS = 12; - private final int TAGLEN = 16; - private final int[] RC = {0x00000058, 0x00000038, 0x000003C0, 0x000000D0, 0x00000120, 0x00000014, 0x00000060, - 0x0000002C, 0x00000380, 0x000000F0, 0x000001A0, 0x00000012}; - private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - enum MODE + public static class Friend { - ModeHash, - ModeKeyed + private static final Friend INSTANCE = new Friend(); + + private Friend() + { + } } + private final byte[] state; + private int phase; + private static final int mode = 1; // set as ModeHash + private static final int PhaseUp = 2; + private static final int PhaseDown = 1; + private static final int TAGLEN = 16; + private int Cd; + public XoodyakDigest() { + super(ProcessingBufferType.Immediate, 16); + DigestSize = 32; state = new byte[48]; + algorithmName = "Xoodyak Hash"; reset(); } @Override - public String getAlgorithmName() - { - return "Xoodyak Hash"; - } - - @Override - public int getDigestSize() - { - return 32; - } - - @Override - public void update(byte input) - { - buffer.write(input); - } - - @Override - public void update(byte[] input, int inOff, int len) + protected void processBytes(byte[] input, int inOff) { - if ((inOff + len) > input.length) + if (phase != PhaseUp) { - throw new DataLengthException("input buffer too short"); + XoodyakEngine.up(Friend.INSTANCE, mode, state, 0); } - buffer.write(input, inOff, len); - + XoodyakEngine.down(Friend.INSTANCE, mode, state, input, inOff, BlockSize, Cd); + phase = PhaseDown; + Cd = 0; } @Override - public int doFinal(byte[] output, int outOff) + protected void finish(byte[] output, int outOff) { - if (32 + outOff > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - byte[] input = buffer.toByteArray(); - int inOff = 0; - int len = buffer.size(); - int Cd = 0x03; - int splitLen; - do + if (m_bufPos != 0) { if (phase != PhaseUp) { - Up(null, 0, 0, 0); + XoodyakEngine.up(Friend.INSTANCE, mode, state, 0); } - splitLen = Math.min(len, Rabsorb); - Down(input, inOff, splitLen, Cd); - Cd = 0; - inOff += splitLen; - len -= splitLen; + XoodyakEngine.down(Friend.INSTANCE, mode, state, m_buf, 0, m_bufPos, Cd); } - while (len != 0); - Up(output, outOff, TAGLEN, 0x40); - Down(null, 0, 0, 0); - Up(output, outOff + TAGLEN, TAGLEN, 0); - return 32; + XoodyakEngine.up(Friend.INSTANCE, mode, state, 0x40); + System.arraycopy(state, 0, output, outOff, TAGLEN); + XoodyakEngine.down(Friend.INSTANCE, mode, state, null, 0, 0, 0); + XoodyakEngine.up(Friend.INSTANCE, mode, state, 0); + System.arraycopy(state, 0, output, outOff + TAGLEN, TAGLEN); + phase = PhaseDown; } @Override public void reset() { + super.reset(); Arrays.fill(state, (byte)0); phase = PhaseUp; - mode = MODE.ModeHash; - Rabsorb = Rhash; - buffer.reset(); - } - - private void Up(byte[] Yi, int YiOff, int YiLen, int Cu) - { - if (mode != MODE.ModeHash) - { - state[f_bPrime - 1] ^= Cu; - } - int[] a = new int[NLANES]; - Pack.littleEndianToInt(state, 0, a, 0, a.length); - int x, y; - int[] b = new int[NLANES]; - int[] p = new int[NCOLUMS]; - int[] e = new int[NCOLUMS]; - for (int i = 0; i < MAXROUNDS; ++i) - { - /* Theta: Column Parity Mixer */ - for (x = 0; x < NCOLUMS; ++x) - { - p[x] = a[index(x, 0)] ^ a[index(x, 1)] ^ a[index(x, 2)]; - } - for (x = 0; x < NCOLUMS; ++x) - { - y = p[(x + 3) & 3]; - e[x] = ROTL32(y, 5) ^ ROTL32(y, 14); - } - for (x = 0; x < NCOLUMS; ++x) - { - for (y = 0; y < NROWS; ++y) - { - a[index(x, y)] ^= e[x]; - } - } - /* Rho-west: plane shift */ - for (x = 0; x < NCOLUMS; ++x) - { - b[index(x, 0)] = a[index(x, 0)]; - b[index(x, 1)] = a[index(x + 3, 1)]; - b[index(x, 2)] = ROTL32(a[index(x, 2)], 11); - } - /* Iota: round ant */ - b[0] ^= RC[i]; - /* Chi: non linear layer */ - for (x = 0; x < NCOLUMS; ++x) - { - for (y = 0; y < NROWS; ++y) - { - a[index(x, y)] = b[index(x, y)] ^ (~b[index(x, y + 1)] & b[index(x, y + 2)]); - } - } - /* Rho-east: plane shift */ - for (x = 0; x < NCOLUMS; ++x) - { - b[index(x, 0)] = a[index(x, 0)]; - b[index(x, 1)] = ROTL32(a[index(x, 1)], 1); - b[index(x, 2)] = ROTL32(a[index(x + 2, 2)], 8); - } - System.arraycopy(b, 0, a, 0, NLANES); - } - Pack.intToLittleEndian(a, 0, a.length, state, 0); - phase = PhaseUp; - if (Yi != null) - { - System.arraycopy(state, 0, Yi, YiOff, YiLen); - } - } - - void Down(byte[] Xi, int XiOff, int XiLen, int Cd) - { - for (int i = 0; i < XiLen; i++) - { - state[i] ^= Xi[XiOff++]; - } - state[XiLen] ^= 0x01; - state[f_bPrime - 1] ^= (mode == MODE.ModeHash) ? (Cd & 0x01) : Cd; - phase = PhaseDown; + Cd = 0x03; } - - private int index(int x, int y) - { - return (((y % NROWS) * NCOLUMS) + ((x) % NCOLUMS)); - } - - private int ROTL32(int a, int offset) - { - return (a << (offset & 31)) ^ (a >>> ((32 - (offset)) & 31)); - } - -} +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/digests/package-info.java b/core/src/main/java/org/bouncycastle/crypto/digests/package-info.java new file mode 100644 index 0000000000..a8e7db290d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/digests/package-info.java @@ -0,0 +1,4 @@ +/** + * Message digest classes. + */ +package org.bouncycastle.crypto.digests; diff --git a/core/src/main/java/org/bouncycastle/crypto/ec/package-info.java b/core/src/main/java/org/bouncycastle/crypto/ec/package-info.java new file mode 100644 index 0000000000..2fd4a29a60 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/ec/package-info.java @@ -0,0 +1,4 @@ +/** + * Utility classes for support Elliptic Curve cryptographic transforms. + */ +package org.bouncycastle.crypto.ec; diff --git a/core/src/main/java/org/bouncycastle/crypto/encodings/package-info.java b/core/src/main/java/org/bouncycastle/crypto/encodings/package-info.java new file mode 100644 index 0000000000..e2482b658a --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/encodings/package-info.java @@ -0,0 +1,4 @@ +/** + * Block encodings for asymmetric ciphers. + */ +package org.bouncycastle.crypto.encodings; diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/AEADBaseEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/AEADBaseEngine.java new file mode 100644 index 0000000000..22af62b796 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/AEADBaseEngine.java @@ -0,0 +1,1106 @@ +package org.bouncycastle.crypto.engines; + +import java.io.ByteArrayOutputStream; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.constraints.DefaultServiceProperties; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; + +abstract class AEADBaseEngine + implements AEADCipher +{ + protected static class ProcessingBufferType + { + public static final int BUFFERED = 0; // Store a (aad) block size of input and process after the input size exceeds the buffer size + public static final int IMMEDIATE = 1; //process the input immediately when the input size is equal or greater than the block size + + public static final ProcessingBufferType Buffered = new ProcessingBufferType(BUFFERED); + public static final ProcessingBufferType Immediate = new ProcessingBufferType(IMMEDIATE); + + private final int ord; + + ProcessingBufferType(int ord) + { + this.ord = ord; + } + } + + protected static class AADOperatorType + { + public static final int DEFAULT = 0; + public static final int COUNTER = 1;//add a counter to count the size of AAD + public static final int STREAM = 2; //process AAD data during the process data, used for elephant + + public static final AADOperatorType Default = new AADOperatorType(DEFAULT); + public static final AADOperatorType Counter = new AADOperatorType(COUNTER); + public static final AADOperatorType Stream = new AADOperatorType(STREAM); + + private final int ord; + + AADOperatorType(int ord) + { + this.ord = ord; + } + } + + protected static class DataOperatorType + { + public static final int DEFAULT = 0; + public static final int COUNTER = 1; + public static final int STREAM = 2; + public static final int STREAM_CIPHER = 3; + + public static final DataOperatorType Default = new DataOperatorType(DEFAULT); + public static final DataOperatorType Counter = new DataOperatorType(COUNTER); + public static final DataOperatorType Stream = new DataOperatorType(STREAM); + public static final DataOperatorType StreamCipher = new DataOperatorType(STREAM_CIPHER); + + private final int ord; + + DataOperatorType(int ord) + { + this.ord = ord; + } + } + + protected static class State + { + public static final int UNINITIALIZED = 0; + public static final int ENC_INIT = 1; + public static final int ENC_AAD = 2; // can process AAD + public static final int ENC_DATA = 3; // cannot process AAD + public static final int ENC_FINAL = 4; + public static final int DEC_INIT = 5; + public static final int DEC_AAD = 6; // can process AAD + public static final int DEC_DATA = 7; // cannot process AAD + public static final int DEC_FINAL = 8; + + public static final State Uninitialized = new State(UNINITIALIZED); + public static final State EncInit = new State(ENC_INIT); + public static final State EncAad = new State(ENC_AAD); + public static final State EncData = new State(ENC_DATA); + public static final State EncFinal = new State(ENC_FINAL); + public static final State DecInit = new State(DEC_INIT); + public static final State DecAad = new State(DEC_AAD); + public static final State DecData = new State(DEC_DATA); + public static final State DecFinal = new State(DEC_FINAL); + + final int ord; + + State(int ord) + { + this.ord = ord; + } + } + + protected boolean forEncryption; + protected String algorithmName; + protected int KEY_SIZE; + protected int IV_SIZE; + protected int MAC_SIZE; + protected byte[] initialAssociatedText; + protected byte[] mac; + protected byte[] m_buf; + protected byte[] m_aad; + protected int m_bufPos; + protected int m_aadPos; + protected int AADBufferSize; + protected int BlockSize; + protected State m_state = State.Uninitialized; + protected int m_bufferSizeDecrypt; + protected AADProcessingBuffer processor; + protected AADOperator aadOperator; + protected DataOperator dataOperator; + + @Override + public String getAlgorithmName() + { + return algorithmName; + } + + public int getKeyBytesSize() + { + return KEY_SIZE; + } + + public int getIVBytesSize() + { + return IV_SIZE; + } + + public byte[] getMac() + { + return mac; + } + + @Override + public void init(boolean forEncryption, CipherParameters params) + { + this.forEncryption = forEncryption; + KeyParameter key; + byte[] npub; + byte[] k; + + if (params instanceof AEADParameters) + { + AEADParameters aeadParameters = (AEADParameters)params; + key = aeadParameters.getKey(); + npub = aeadParameters.getNonce(); + initialAssociatedText = aeadParameters.getAssociatedText(); + + int macSizeBits = aeadParameters.getMacSize(); + if (macSizeBits != MAC_SIZE * 8) + { + throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits); + } + } + else if (params instanceof ParametersWithIV) + { + ParametersWithIV withIV = (ParametersWithIV)params; + key = (KeyParameter)withIV.getParameters(); + npub = withIV.getIV(); + initialAssociatedText = null; + } + else + { + throw new IllegalArgumentException("invalid parameters passed to " + algorithmName); + } + + if (key == null) + { + throw new IllegalArgumentException(algorithmName + " Init parameters must include a key"); + } + if (npub == null || npub.length != IV_SIZE) + { + throw new IllegalArgumentException(algorithmName + " requires exactly " + IV_SIZE + " bytes of IV"); + } + + k = key.getKey(); + if (k.length != KEY_SIZE) + { + throw new IllegalArgumentException(algorithmName + " key must be " + KEY_SIZE + " bytes long"); + } + + CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( + this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); + + m_state = forEncryption ? State.EncInit : State.DecInit; + init(k, npub); + reset(true); + if (initialAssociatedText != null) + { + processAADBytes(initialAssociatedText, 0, initialAssociatedText.length); + } + } + + @Override + public void reset() + { + reset(true); + } + + protected void reset(boolean clearMac) + { + ensureInitialized(); + if (clearMac) + { + mac = null; + } + if (m_buf != null) + { + Arrays.fill(m_buf, (byte)0); + m_bufPos = 0; + } + if (m_aad != null) + { + Arrays.fill(m_aad, (byte)0); + m_aadPos = 0; + } + switch (m_state.ord) + { + case State.DEC_INIT: + case State.ENC_INIT: + break; + case State.DEC_AAD: + case State.DEC_DATA: + case State.DEC_FINAL: + m_state = State.DecFinal; + break; + case State.ENC_AAD: + case State.ENC_DATA: + case State.ENC_FINAL: + m_state = State.EncFinal; + return; + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + } + aadOperator.reset(); + dataOperator.reset(); + } + + protected void setInnerMembers(ProcessingBufferType type, AADOperatorType aadOperatorType, DataOperatorType dataOperatorType) + { + switch (type.ord) + { + case ProcessingBufferType.BUFFERED: + processor = new BufferedAADProcessor(); + break; + case ProcessingBufferType.IMMEDIATE: + processor = new ImmediateAADProcessor(); + break; + } + + m_bufferSizeDecrypt = BlockSize + MAC_SIZE; + + switch (aadOperatorType.ord) + { + case AADOperatorType.DEFAULT: + m_aad = new byte[AADBufferSize]; + aadOperator = new DefaultAADOperator(); + break; + case AADOperatorType.COUNTER: + m_aad = new byte[AADBufferSize]; + aadOperator = new CounterAADOperator(); + break; + case AADOperatorType.STREAM: + AADBufferSize = 0; + aadOperator = new StreamAADOperator(); + break; + } + + switch (dataOperatorType.ord) + { + case DataOperatorType.DEFAULT: + m_buf = new byte[m_bufferSizeDecrypt]; + dataOperator = new DefaultDataOperator(); + break; + case DataOperatorType.COUNTER: + m_buf = new byte[m_bufferSizeDecrypt]; + dataOperator = new CounterDataOperator(); + break; + case DataOperatorType.STREAM: + m_buf = new byte[MAC_SIZE]; + dataOperator = new StreamDataOperator(); + break; + case DataOperatorType.STREAM_CIPHER: + BlockSize = 0; + m_buf = new byte[m_bufferSizeDecrypt]; + dataOperator = new StreamCipherOperator(); + break; + } + } + + private interface AADProcessingBuffer + { + void processAADByte(byte input); + + int processByte(byte input, byte[] output, int outOff); + + int getUpdateOutputSize(int len); + + boolean isLengthWithinAvailableSpace(int len, int available); + + boolean isLengthExceedingBlockSize(int len, int size); + } + + private class BufferedAADProcessor + implements AADProcessingBuffer + { + public void processAADByte(byte input) + { + if (m_aadPos == AADBufferSize) + { + processBufferAAD(m_aad, 0); + m_aadPos = 0; + } + m_aad[m_aadPos++] = input; + } + + @Override + public int processByte(byte input, byte[] output, int outOff) + { + checkData(false); + int rlt = processEncDecByte(output, outOff); + m_buf[m_bufPos++] = input; + return rlt; + } + + @Override + public boolean isLengthWithinAvailableSpace(int len, int available) + { + return len <= available; + } + + @Override + public boolean isLengthExceedingBlockSize(int len, int size) + { + return len > size; + } + + @Override + public int getUpdateOutputSize(int len) + { + // The -1 is to account for the lazy processing of a full buffer + return Math.max(0, len) - 1; + } + } + + private class ImmediateAADProcessor + implements AADProcessingBuffer + { + public void processAADByte(byte input) + { + m_aad[m_aadPos++] = input; + if (m_aadPos == AADBufferSize) + { + processBufferAAD(m_aad, 0); + m_aadPos = 0; + } + } + + @Override + public int processByte(byte input, byte[] output, int outOff) + { + checkData(false); + m_buf[m_bufPos++] = input; + return processEncDecByte(output, outOff); + } + + @Override + public int getUpdateOutputSize(int len) + { + return Math.max(0, len); + } + + @Override + public boolean isLengthWithinAvailableSpace(int len, int available) + { + return len < available; + } + + @Override + public boolean isLengthExceedingBlockSize(int len, int size) + { + return len >= size; + } + } + + protected interface AADOperator + { + void processAADByte(byte input); + + void processAADBytes(byte[] input, int inOff, int len); + + void reset(); + + int getLen(); + } + + private class DefaultAADOperator + implements AADOperator + { + @Override + public void processAADByte(byte input) + { + processor.processAADByte(input); + } + + @Override + public void processAADBytes(byte[] input, int inOff, int len) + { + processAadBytes(input, inOff, len); + } + + public void reset() + { + } + + @Override + public int getLen() + { + return m_aadPos; + } + } + + private class CounterAADOperator + implements AADOperator + { + private int aadLen; + + @Override + public void processAADByte(byte input) + { + aadLen++; + processor.processAADByte(input); + } + + @Override + public void processAADBytes(byte[] input, int inOff, int len) + { + aadLen += len; + processAadBytes(input, inOff, len); + } + + public int getLen() + { + return aadLen; + } + + public void reset() + { + aadLen = 0; + } + } + + protected static class StreamAADOperator + implements AADOperator + { + private final ErasableOutputStream stream = new ErasableOutputStream(); + + @Override + public void processAADByte(byte input) + { + stream.write(input); + } + + @Override + public void processAADBytes(byte[] input, int inOff, int len) + { + stream.write(input, inOff, len); + } + + public byte[] getBytes() + { + return stream.getBuf(); + } + + @Override + public void reset() + { + stream.reset(); + } + + @Override + public int getLen() + { + return stream.size(); + } + } + + protected interface DataOperator + { + int processByte(byte input, byte[] output, int outOff); + + int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff); + + int getLen(); + + void reset(); + } + + private class DefaultDataOperator + implements DataOperator + { + public int processByte(byte input, byte[] output, int outOff) + { + return processor.processByte(input, output, outOff); + } + + public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) + { + return processEncDecBytes(input, inOff, len, output, outOff); + } + + @Override + public int getLen() + { + return m_bufPos; + } + + @Override + public void reset() + { + } + } + + private class CounterDataOperator + implements DataOperator + { + private int messegeLen; + + public int processByte(byte input, byte[] output, int outOff) + { + messegeLen++; + return processor.processByte(input, output, outOff); + } + + public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) + { + messegeLen += len; + return processEncDecBytes(input, inOff, len, output, outOff); + } + + @Override + public int getLen() + { + return messegeLen; + } + + @Override + public void reset() + { + messegeLen = 0; + } + } + + protected class StreamDataOperator + implements DataOperator + { + private final ErasableOutputStream stream = new ErasableOutputStream(); + + public int processByte(byte input, byte[] output, int outOff) + { + ensureInitialized(); + stream.write(input); + m_bufPos = stream.size(); + return 0; + } + + @Override + public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) + { + ensureInitialized(); + stream.write(input, inOff, len); + m_bufPos = stream.size(); + return 0; + } + + public byte[] getBytes() + { + return stream.getBuf(); + } + + @Override + public int getLen() + { + return stream.size(); + } + + @Override + public void reset() + { + stream.reset(); + } + } + + private class StreamCipherOperator + implements DataOperator + { + //TODO: shift index instead of arraycopy + private int len; + + public int processByte(byte input, byte[] output, int outOff) + { + boolean forEncryption = checkData(false); + if (forEncryption) + { + this.len = 1; + processBufferEncrypt(new byte[]{input}, 0, output, outOff); + return 1; + } + else + { + if (m_bufPos == MAC_SIZE) + { + this.len = 1; + processBufferDecrypt(m_buf, 0, output, outOff); + System.arraycopy(m_buf, 1, m_buf, 0, m_bufPos - 1); + m_buf[m_bufPos - 1] = input; + return 1; + } + else + { + m_buf[m_bufPos++] = input; + return 0; + } + } + } + + @Override + public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) + { + if (input == output && Arrays.segmentsOverlap(inOff, len, outOff, processor.getUpdateOutputSize(len))) + { + input = new byte[len]; + System.arraycopy(output, inOff, input, 0, len); + inOff = 0; + } + boolean forEncryption = checkData(false); + if (forEncryption) + { + this.len = len; + processBufferEncrypt(input, inOff, output, outOff); + return len; + } + else + { + // keep last mac size bytes + int available = Math.max(m_bufPos + len - MAC_SIZE, 0); + int rlt = 0; + if (m_bufPos > 0) + { + this.len = Math.min(available, m_bufPos); + rlt = this.len; + processBufferDecrypt(m_buf, 0, output, outOff); + available -= rlt; + m_bufPos -= rlt; + System.arraycopy(m_buf, rlt, m_buf, 0, m_bufPos); + } + if (available > 0) + { + this.len = available; + processBufferDecrypt(input, inOff, output, outOff); + rlt += available; + len -= available; + inOff += available; + } + + System.arraycopy(input, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return rlt; + } + } + + @Override + public int getLen() + { + return len; + } + + @Override + public void reset() + { + } + } + + @Override + public void processAADByte(byte input) + { + checkAAD(); + aadOperator.processAADByte(input); + } + + @Override + public void processAADBytes(byte[] input, int inOff, int len) + { + ensureSufficientInputBuffer(input, inOff, len); + // Don't enter AAD state until we actually get input + if (len <= 0) + { + return; + } + + checkAAD(); + aadOperator.processAADBytes(input, inOff, len); + } + + private void processAadBytes(byte[] input, int inOff, int len) + { + if (m_aadPos > 0) + { + int available = AADBufferSize - m_aadPos; + if (processor.isLengthWithinAvailableSpace(len, available)) + { + System.arraycopy(input, inOff, m_aad, m_aadPos, len); + m_aadPos += len; + return; + } + + System.arraycopy(input, inOff, m_aad, m_aadPos, available); + inOff += available; + len -= available; + + processBufferAAD(m_aad, 0); + } + while (processor.isLengthExceedingBlockSize(len, AADBufferSize)) + { + processBufferAAD(input, inOff); + inOff += AADBufferSize; + len -= AADBufferSize; + } + System.arraycopy(input, inOff, m_aad, 0, len); + m_aadPos = len; + } + + @Override + public int processByte(byte in, byte[] out, int outOff) + throws DataLengthException + { + return dataOperator.processByte(in, out, outOff); + } + + protected int processEncDecByte(byte[] output, int outOff) + { + int rlt = 0; + int available = (forEncryption ? BlockSize : m_bufferSizeDecrypt) - m_bufPos; + if (available == 0) + { + ensureSufficientOutputBuffer(output, outOff, BlockSize); + if (forEncryption) + { + processBufferEncrypt(m_buf, 0, output, outOff); + } + else + { + processBufferDecrypt(m_buf, 0, output, outOff); + System.arraycopy(m_buf, BlockSize, m_buf, 0, m_bufPos - BlockSize); + } + m_bufPos -= BlockSize; + rlt = BlockSize; + } + return rlt; + } + + @Override + public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) + throws DataLengthException + { + ensureSufficientInputBuffer(input, inOff, len); + return dataOperator.processBytes(input, inOff, len, output, outOff); + } + + protected int processEncDecBytes(byte[] input, int inOff, int len, byte[] output, int outOff) + { + boolean forEncryption = checkData(false); + int available, resultLength; + available = (forEncryption ? BlockSize : m_bufferSizeDecrypt) - m_bufPos; + // The function is just an operator < or <= + if (processor.isLengthWithinAvailableSpace(len, available)) + { + System.arraycopy(input, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return 0; + } + int length = processor.getUpdateOutputSize(len); + resultLength = length + m_bufPos - (forEncryption ? 0 : MAC_SIZE); + ensureSufficientOutputBuffer(output, outOff, resultLength - resultLength % BlockSize); + resultLength = 0; + if (input == output && Arrays.segmentsOverlap(inOff, len, outOff, length)) + { + input = new byte[len]; + System.arraycopy(output, inOff, input, 0, len); + inOff = 0; + } + if (forEncryption) + { + if (m_bufPos > 0) + { + System.arraycopy(input, inOff, m_buf, m_bufPos, available); + inOff += available; + len -= available; + processBufferEncrypt(m_buf, 0, output, outOff); + resultLength = BlockSize; + } + + // The function is just an operator >= or > + while (processor.isLengthExceedingBlockSize(len, BlockSize)) + { + processBufferEncrypt(input, inOff, output, outOff + resultLength); + inOff += BlockSize; + len -= BlockSize; + resultLength += BlockSize; + } + } + else + { + // loop will run more than once for the following situation: pb128, ascon80pq, ascon128, ISAP_A_128(A) + while (processor.isLengthExceedingBlockSize(m_bufPos, BlockSize) + && processor.isLengthExceedingBlockSize(len + m_bufPos, m_bufferSizeDecrypt)) + { + processBufferDecrypt(m_buf, resultLength, output, outOff + resultLength); + m_bufPos -= BlockSize; + resultLength += BlockSize; + } + if (m_bufPos > 0) + { + System.arraycopy(m_buf, resultLength, m_buf, 0, m_bufPos); + if (processor.isLengthWithinAvailableSpace(m_bufPos + len, m_bufferSizeDecrypt)) + { + System.arraycopy(input, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return resultLength; + } + available = Math.max(BlockSize - m_bufPos, 0); + System.arraycopy(input, inOff, m_buf, m_bufPos, available); + inOff += available; + len -= available; + processBufferDecrypt(m_buf, 0, output, outOff + resultLength); + resultLength += BlockSize; + } + while (processor.isLengthExceedingBlockSize(len, m_bufferSizeDecrypt)) + { + processBufferDecrypt(input, inOff, output, outOff + resultLength); + inOff += BlockSize; + len -= BlockSize; + resultLength += BlockSize; + } + } + System.arraycopy(input, inOff, m_buf, 0, len); + m_bufPos = len; + return resultLength; + } + + @Override + public int doFinal(byte[] output, int outOff) + throws IllegalStateException, InvalidCipherTextException + { + boolean forEncryption = checkData(true); + int resultLength; + if (forEncryption) + { + resultLength = m_bufPos + MAC_SIZE; + } + else + { + if (m_bufPos < MAC_SIZE) + { + throw new InvalidCipherTextException("data too short"); + } + + m_bufPos -= MAC_SIZE; + + resultLength = m_bufPos; + } + + ensureSufficientOutputBuffer(output, outOff, resultLength); + mac = new byte[MAC_SIZE]; + processFinalBlock(output, outOff); + if (forEncryption) + { + System.arraycopy(mac, 0, output, outOff + resultLength - MAC_SIZE, MAC_SIZE); + } + else + { + if (!Arrays.constantTimeAreEqual(MAC_SIZE, mac, 0, m_buf, m_bufPos)) + { + throw new InvalidCipherTextException(algorithmName + " mac does not match"); + } + } + reset(!forEncryption); + return resultLength; + } + + public final int getBlockSize() + { + return BlockSize; + } + + public int getUpdateOutputSize(int len) + { + int total = getTotalBytesForUpdate(len); + return total - total % BlockSize; + } + + protected int getTotalBytesForUpdate(int len) + { + int total = processor.getUpdateOutputSize(len); + switch (m_state.ord) + { + case State.DEC_INIT: + case State.DEC_AAD: + case State.DEC_DATA: + case State.DEC_FINAL: + total = Math.max(0, total + m_bufPos - MAC_SIZE); + break; + case State.ENC_DATA: + case State.ENC_FINAL: + total = Math.max(0, total + m_bufPos); + break; + default: + break; + } + return total; + } + + public int getOutputSize(int len) + { + int total = Math.max(0, len); + + switch (m_state.ord) + { + case State.DEC_INIT: + case State.DEC_AAD: + case State.DEC_DATA: + case State.DEC_FINAL: + return Math.max(0, total + m_bufPos - MAC_SIZE); + case State.ENC_DATA: + case State.ENC_FINAL: + return total + m_bufPos + MAC_SIZE; + default: + return total + MAC_SIZE; + } + } + + protected void checkAAD() + { + switch (m_state.ord) + { + case State.DEC_INIT: + m_state = State.DecAad; + break; + case State.ENC_INIT: + m_state = State.EncAad; + break; + case State.DEC_AAD: + case State.ENC_AAD: + break; + case State.ENC_FINAL: + throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + } + } + + protected boolean checkData(boolean isDoFinal) + { + switch (m_state.ord) + { + case State.DEC_INIT: + case State.DEC_AAD: + finishAAD(State.DecData, isDoFinal); + return false; + case State.ENC_INIT: + case State.ENC_AAD: + finishAAD(State.EncData, isDoFinal); + return true; + case State.DEC_DATA: + return false; + case State.ENC_DATA: + return true; + case State.ENC_FINAL: + throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + } + } + + protected final void ensureSufficientOutputBuffer(byte[] output, int outOff, int len) + { + if (outOff + len > output.length) + { + throw new OutputLengthException("output buffer too short"); + } + } + + protected final void ensureSufficientInputBuffer(byte[] input, int inOff, int len) + { + if (inOff + len > input.length) + { + throw new DataLengthException("input buffer too short"); + } + } + + protected final void ensureInitialized() + { + if (m_state == State.Uninitialized) + { + throw new IllegalStateException("Need to call init function before operation"); + } + } + + // Used for Grain128 AEAD and Romulus Engine + protected void finishAAD1(State nextState) + { + switch (m_state.ord) + { + case State.DEC_INIT: + case State.DEC_AAD: + case State.ENC_INIT: + case State.ENC_AAD: + { + processFinalAAD(); + break; + } + default: + break; + } + m_state = nextState; + } + + // Use for Elephant and Sparkle + protected void finishAAD2(State nextState) + { + // State indicates whether we ever received AAD + switch (m_state.ord) + { + case State.DEC_AAD: + case State.ENC_AAD: + { + processFinalAAD(); + break; + } + default: + break; + } + + m_aadPos = 0; + m_state = nextState; + } + + // Used for Gift-Cofb, ISAP, PhotonBeetle and Xoodyak + protected void finishAAD3(State nextState, boolean isDoFinal) + { + // State indicates whether we ever received AAD + switch (m_state.ord) + { + case State.DEC_INIT: + case State.DEC_AAD: + if (!isDoFinal && dataOperator.getLen() <= MAC_SIZE) + { + return; + } + case State.ENC_INIT: + case State.ENC_AAD: + processFinalAAD(); + break; + } + + m_aadPos = 0; + m_state = nextState; + } + + protected abstract void finishAAD(State nextState, boolean isDoFinal); + + protected abstract void init(byte[] key, byte[] iv); + + protected abstract void processFinalBlock(byte[] output, int outOff); + + protected abstract void processBufferAAD(byte[] input, int inOff); + + protected abstract void processFinalAAD(); + + protected abstract void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff); + + protected abstract void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff); + + protected static final class ErasableOutputStream + extends ByteArrayOutputStream + { + public ErasableOutputStream() + { + } + + public byte[] getBuf() + { + return buf; + } + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/AsconAEAD128.java b/core/src/main/java/org/bouncycastle/crypto/engines/AsconAEAD128.java new file mode 100644 index 0000000000..856eadc359 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/AsconAEAD128.java @@ -0,0 +1,153 @@ +package org.bouncycastle.crypto.engines; + +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Pack; + +/** + * Ascon-AEAD128 was introduced as part of the NIST Lightweight Cryptography + * competition and described in the NIST Special Publication SP 800-232 (Initial + * Public Draft). + * For additional details, see: + * + * + * @version 1.3 + */ +public class AsconAEAD128 + extends AsconBaseEngine +{ + public AsconAEAD128() + { + KEY_SIZE = IV_SIZE = MAC_SIZE = AADBufferSize = BlockSize = 16; + ASCON_IV = 0x00001000808c0001L; + algorithmName = "Ascon-AEAD128"; + nr = 8; + dsep = -9223372036854775808L; //0x80L << 56 + setInnerMembers(ProcessingBufferType.Immediate, AADOperatorType.Default, DataOperatorType.Default); + } + + protected long pad(int i) + { + return 0x01L << (i << 3); + } + + @Override + protected long loadBytes(byte[] in, int inOff) + { + return Pack.littleEndianToLong(in, inOff); + } + + @Override + protected void setBytes(long n, byte[] bs, int off) + { + Pack.longToLittleEndian(n, bs, off); + } + + protected void ascon_aeadinit() + { + /* initialize */ + p.set(ASCON_IV, K0, K1, N0, N1); + p.p(12); + p.x3 ^= K0; + p.x4 ^= K1; + } + + protected void processFinalAAD() + { + if (m_aadPos == BlockSize) + { + p.x0 ^= loadBytes(m_aad, 0); + p.x1 ^= loadBytes(m_aad, 8); + m_aadPos -= BlockSize; + p.p(nr); + } + Arrays.fill(m_aad, m_aadPos, AADBufferSize, (byte)0); + if (m_aadPos >= 8) // ASCON_AEAD_RATE == 16 is implied + { + p.x0 ^= Pack.littleEndianToLong(m_aad, 0); + p.x1 ^= Pack.littleEndianToLong(m_aad, 8) ^ pad(m_aadPos); + } + else + { + p.x0 ^= Pack.littleEndianToLong(m_aad, 0) ^ pad(m_aadPos); + } + } + + protected void processFinalDecrypt(byte[] input, int inLen, byte[] output, int outOff) + { + if (inLen >= 8) // ASCON_AEAD_RATE == 16 is implied + { + long c0 = Pack.littleEndianToLong(input, 0); + inLen -= 8; + long c1 = Pack.littleEndianToLong(input, 8, inLen); + Pack.longToLittleEndian(p.x0 ^ c0, output, outOff); + Pack.longToLittleEndian(p.x1 ^ c1, output, outOff + 8, inLen); + p.x0 = c0; + p.x1 &= -(1L << (inLen << 3)); + p.x1 |= c1; + p.x1 ^= pad(inLen); + } + else + { + if (inLen != 0) + { + long c0 = Pack.littleEndianToLong(input, 0, inLen); + Pack.longToLittleEndian(p.x0 ^ c0, output, outOff, inLen); + p.x0 &= -(1L << (inLen << 3)); + p.x0 |= c0; + } + p.x0 ^= pad(inLen); + } + finishData(State.DecFinal); + } + + protected void processFinalEncrypt(byte[] input, int inLen, byte[] output, int outOff) + { + if (inLen >= 8) // ASCON_AEAD_RATE == 16 is implied + { + p.x0 ^= Pack.littleEndianToLong(input, 0); + inLen -= 8; + p.x1 ^= Pack.littleEndianToLong(input, 8, inLen); + Pack.longToLittleEndian(p.x0, output, outOff); + Pack.longToLittleEndian(p.x1, output, outOff + 8); + p.x1 ^= pad(inLen); + } + else + { + if (inLen != 0) + { + p.x0 ^= Pack.littleEndianToLong(input, 0, inLen); + Pack.longToLittleEndian(p.x0, output, outOff, inLen); + } + p.x0 ^= pad(inLen); + } + finishData(State.EncFinal); + } + + private void finishData(State nextState) + { + p.x2 ^= K0; + p.x3 ^= K1; + p.p(12); + p.x3 ^= K0; + p.x4 ^= K1; + m_state = nextState; + } + + protected void init(byte[] key, byte[] iv) + throws IllegalArgumentException + { + K0 = Pack.littleEndianToLong(key, 0); + K1 = Pack.littleEndianToLong(key, 8); + N0 = Pack.littleEndianToLong(iv, 0); + N1 = Pack.littleEndianToLong(iv, 8); + } + + public String getAlgorithmVersion() + { + return "v1.3"; + } +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/AsconBaseEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/AsconBaseEngine.java new file mode 100644 index 0000000000..6f4792c428 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/AsconBaseEngine.java @@ -0,0 +1,106 @@ +package org.bouncycastle.crypto.engines; + +abstract class AsconBaseEngine + extends AEADBaseEngine +{ + protected int nr; + protected long K0; + protected long K1; + protected long N0; + protected long N1; + protected long ASCON_IV; + AsconPermutationFriend.AsconPermutation p = new AsconPermutationFriend.AsconPermutation(); + protected long dsep; //domain separation + + protected abstract long pad(int i); + + protected abstract long loadBytes(byte[] in, int inOff); + + protected abstract void setBytes(long n, byte[] bs, int off); + + protected abstract void ascon_aeadinit(); + + protected void finishAAD(State nextState, boolean isDofinal) + { + // State indicates whether we ever received AAD + switch (m_state.ord) + { + case State.DEC_AAD: + case State.ENC_AAD: + this.processFinalAAD(); + p.p(nr); + break; + default: + break; + } + // domain separation + p.x4 ^= dsep; + m_aadPos = 0; + m_state = nextState; + } + + protected abstract void processFinalDecrypt(byte[] input, int inLen, byte[] output, int outOff); + + protected abstract void processFinalEncrypt(byte[] input, int inLen, byte[] output, int outOff); + + protected void processBufferAAD(byte[] buffer, int inOff) + { + p.x0 ^= loadBytes(buffer, inOff); + if (BlockSize == 16) + { + p.x1 ^= loadBytes(buffer, 8 + inOff); + } + p.p(nr); + } + + @Override + protected void processFinalBlock(byte[] output, int outOff) + { + if (forEncryption) + { + processFinalEncrypt(m_buf, m_bufPos, output, outOff); + } + else + { + processFinalDecrypt(m_buf, m_bufPos, output, outOff); + } + setBytes(p.x3, mac, 0); + setBytes(p.x4, mac, 8); + } + + protected void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int outOff) + { + long t0 = loadBytes(buffer, bufOff); + setBytes(p.x0 ^ t0, output, outOff); + p.x0 = t0; + + if (BlockSize == 16) + { + long t1 = loadBytes(buffer, bufOff + 8); + setBytes(p.x1 ^ t1, output, outOff + 8); + p.x1 = t1; + } + p.p(nr); + } + + protected void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int outOff) + { + p.x0 ^= loadBytes(buffer, bufOff); + setBytes(p.x0, output, outOff); + + if (BlockSize == 16) + { + p.x1 ^= loadBytes(buffer, bufOff + 8); + setBytes(p.x1, output, outOff + 8); + } + p.p(nr); + } + + protected void reset(boolean clearMac) + { + super.reset(clearMac); + ascon_aeadinit(); + } + + public abstract String getAlgorithmVersion(); +} diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/AsconEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/AsconEngine.java index e4d705ffcc..9e9fab811d 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/AsconEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/AsconEngine.java @@ -1,28 +1,27 @@ package org.bouncycastle.crypto.engines; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.AEADParameters; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Longs; import org.bouncycastle.util.Pack; /** - * ASCON AEAD v1.2, https://ascon.iaik.tugraz.at/ - * https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/ascon-spec-final.pdf + * The {@code AsconEngine} class provides an implementation of ASCON AEAD version 1.2, + * based on the official specification available at: + * https://ascon.iaik.tugraz.at/ and the + * updated specification document from the NIST competition: + * + * ASCON Specification (Finalist Round) + * . *

    - * ASCON AEAD v1.2 with reference to C Reference Impl from: https://github.com/ascon/ascon-c + * This version references the C reference implementation provided by NIST, available at: + * + * ASCON C Reference Implementation (NIST Round 2) + * . *

    + * + * @deprecated Now superseded. Please refer to {@code AsconAEAD128Engine} for future implementations. */ + public class AsconEngine - implements AEADCipher + extends AsconBaseEngine { public enum AsconParameters { @@ -31,708 +30,205 @@ public enum AsconParameters ascon128 } - private enum State - { - Uninitialized, - EncInit, - EncAad, - EncData, - EncFinal, - DecInit, - DecAad, - DecData, - DecFinal, - } - private final AsconParameters asconParameters; - private State m_state = State.Uninitialized; - private byte[] mac; - private byte[] initialAssociatedText; - private final String algorithmName; - private final int CRYPTO_KEYBYTES; - private final int CRYPTO_ABYTES; - private final int ASCON_AEAD_RATE; - private final int nr; - private long K0; - private long K1; private long K2; - private long N0; - private long N1; - private final long ASCON_IV; - private long x0; - private long x1; - private long x2; - private long x3; - private long x4; - private final int m_bufferSizeDecrypt; - private final byte[] m_buf; - private int m_bufPos = 0; public AsconEngine(AsconParameters asconParameters) { this.asconParameters = asconParameters; + IV_SIZE = MAC_SIZE = 16; switch (asconParameters) { case ascon80pq: - CRYPTO_KEYBYTES = 20; - CRYPTO_ABYTES = 16; - ASCON_AEAD_RATE = 8; + KEY_SIZE = 20; + BlockSize = 8; ASCON_IV = 0xa0400c0600000000L; algorithmName = "Ascon-80pq AEAD"; break; case ascon128a: - CRYPTO_KEYBYTES = 16; - CRYPTO_ABYTES = 16; - ASCON_AEAD_RATE = 16; + KEY_SIZE = 16; + BlockSize = 16; ASCON_IV = 0x80800c0800000000L; algorithmName = "Ascon-128a AEAD"; break; case ascon128: - CRYPTO_KEYBYTES = 16; - CRYPTO_ABYTES = 16; - ASCON_AEAD_RATE = 8; + KEY_SIZE = 16; + BlockSize = 8; ASCON_IV = 0x80400c0600000000L; algorithmName = "Ascon-128 AEAD"; break; default: throw new IllegalArgumentException("invalid parameter setting for ASCON AEAD"); } - nr = (ASCON_AEAD_RATE == 8) ? 6 : 8; - m_bufferSizeDecrypt = ASCON_AEAD_RATE + CRYPTO_ABYTES; - m_buf = new byte[m_bufferSizeDecrypt]; + nr = (BlockSize == 8) ? 6 : 8; + AADBufferSize = BlockSize; + dsep = 1L; + setInnerMembers(ProcessingBufferType.Immediate, AADOperatorType.Default, DataOperatorType.Default); } - private long PAD(int i) + protected long pad(int i) { return 0x80L << (56 - (i << 3)); } - private void ROUND(long C) + @Override + protected long loadBytes(byte[] in, int inOff) { - long t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C)); - long t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3)); - long t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4); - long t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4)); - long t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1); - x0 = t0 ^ Longs.rotateRight(t0, 19) ^ Longs.rotateRight(t0, 28); - x1 = t1 ^ Longs.rotateRight(t1, 39) ^ Longs.rotateRight(t1, 61); - x2 = ~(t2 ^ Longs.rotateRight(t2, 1) ^ Longs.rotateRight(t2, 6)); - x3 = t3 ^ Longs.rotateRight(t3, 10) ^ Longs.rotateRight(t3, 17); - x4 = t4 ^ Longs.rotateRight(t4, 7) ^ Longs.rotateRight(t4, 41); + return Pack.bigEndianToLong(in, inOff); } - private void P(int nr) + @Override + protected void setBytes(long n, byte[] bs, int off) { - if (nr >= 8) - { - if (nr == 12) - { - ROUND(0xf0L); - ROUND(0xe1L); - ROUND(0xd2L); - ROUND(0xc3L); - } - ROUND(0xb4L); - ROUND(0xa5L); - } - ROUND(0x96L); - ROUND(0x87L); - ROUND(0x78L); - ROUND(0x69L); - ROUND(0x5aL); - ROUND(0x4bL); + Pack.longToBigEndian(n, bs, off); } - private void ascon_aeadinit() + protected void ascon_aeadinit() { /* initialize */ - x0 = ASCON_IV; - if (CRYPTO_KEYBYTES == 20) - { - x0 ^= K0; - } - x1 = K1; - x2 = K2; - x3 = N0; - x4 = N1; - P(12); - if (CRYPTO_KEYBYTES == 20) - { - x2 ^= K0; - } - x3 ^= K1; - x4 ^= K2; - } - - private void checkAAD() - { - switch (m_state) + p.set(ASCON_IV, K1, K2, N0, N1); + if (KEY_SIZE == 20) { - case DecInit: - m_state = State.DecAad; - break; - case EncInit: - m_state = State.EncAad; - break; - case DecAad: - case EncAad: - break; - case EncFinal: - throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); - default: - throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + p.x0 ^= K0; } - } - - private boolean checkData() - { - switch (m_state) + p.p(12); + if (KEY_SIZE == 20) { - case DecInit: - case DecAad: - finishAAD(State.DecData); - return false; - case EncInit: - case EncAad: - finishAAD(State.EncData); - return true; - case DecData: - return false; - case EncData: - return true; - case EncFinal: - throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); - default: - throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + p.x2 ^= K0; } + p.x3 ^= K1; + p.x4 ^= K2; } - private void processBufferAAD(byte[] buffer, int inOff) + protected void processFinalAAD() { - x0 ^= Pack.bigEndianToLong(buffer, inOff); - if (ASCON_AEAD_RATE == 16) + m_aad[m_aadPos] = (byte)0x80; + if (m_aadPos >= 8) // ASCON_AEAD_RATE == 16 is implied { - x1 ^= Pack.bigEndianToLong(buffer, 8 + inOff); + p.x0 ^= Pack.bigEndianToLong(m_aad, 0); + p.x1 ^= Pack.bigEndianToLong(m_aad, 8) & (-1L << (56 - ((m_aadPos - 8) << 3))); } - P(nr); - } - - private void finishAAD(State nextState) - { - // State indicates whether we ever received AAD - switch (m_state) - { - case DecAad: - case EncAad: - m_buf[m_bufPos] = (byte)0x80; - if (m_bufPos >= 8) // ASCON_AEAD_RATE == 16 is implied - { - x0 ^= Pack.bigEndianToLong(m_buf, 0); - x1 ^= Pack.bigEndianToLong(m_buf, 8) & (-1L << (56 - ((m_bufPos - 8) << 3))); - } - else - { - x0 ^= Pack.bigEndianToLong(m_buf, 0) & (-1L << (56 - (m_bufPos << 3))); - } - P(nr); - break; - default: - break; - } - // domain separation - x4 ^= 1L; - m_bufPos = 0; - m_state = nextState; - } - - private void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int outOff) - { - if (outOff + ASCON_AEAD_RATE > output.length) - { - throw new OutputLengthException("output buffer too short"); - } - long t0 = Pack.bigEndianToLong(buffer, bufOff); - Pack.longToBigEndian(x0 ^ t0, output, outOff); - x0 = t0; - - if (ASCON_AEAD_RATE == 16) - { - long t1 = Pack.bigEndianToLong(buffer, bufOff + 8); - Pack.longToBigEndian(x1 ^ t1, output, outOff + 8); - x1 = t1; - } - P(nr); - } - - private void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int outOff) - { - if (outOff + ASCON_AEAD_RATE > output.length) - { - throw new OutputLengthException("output buffer too short"); - } - x0 ^= Pack.bigEndianToLong(buffer, bufOff); - Pack.longToBigEndian(x0, output, outOff); - - if (ASCON_AEAD_RATE == 16) + else { - x1 ^= Pack.bigEndianToLong(buffer, bufOff + 8); - Pack.longToBigEndian(x1, output, outOff + 8); + p.x0 ^= Pack.bigEndianToLong(m_aad, 0) & (-1L << (56 - (m_aadPos << 3))); } - - P(nr); } - private void processFinalDecrypt(byte[] input, int inOff, int inLen, byte[] output, int outOff) + protected void processFinalDecrypt(byte[] input, int inLen, byte[] output, int outOff) { if (inLen >= 8) // ASCON_AEAD_RATE == 16 is implied { - long c0 = Pack.bigEndianToLong(input, inOff); - x0 ^= c0; - Pack.longToBigEndian(x0, output, outOff); - x0 = c0; - inOff += 8; + long c0 = Pack.bigEndianToLong(input, 0); + p.x0 ^= c0; + Pack.longToBigEndian(p.x0, output, outOff); + p.x0 = c0; + outOff += 8; inLen -= 8; - x1 ^= PAD(inLen); + p.x1 ^= pad(inLen); if (inLen != 0) { - long c1 = Pack.littleEndianToLong_High(input, inOff, inLen); - x1 ^= c1; - Pack.longToLittleEndian_High(x1, output, outOff, inLen); - x1 &= -1L >>> (inLen << 3); - x1 ^= c1; + long c1 = Pack.littleEndianToLong_High(input, 8, inLen); + p.x1 ^= c1; + Pack.longToLittleEndian_High(p.x1, output, outOff, inLen); + p.x1 &= -1L >>> (inLen << 3); + p.x1 ^= c1; } } else { - x0 ^= PAD(inLen); + p.x0 ^= pad(inLen); if (inLen != 0) { - long c0 = Pack.littleEndianToLong_High(input, inOff, inLen); - x0 ^= c0; - Pack.longToLittleEndian_High(x0, output, outOff, inLen); - x0 &= -1L >>> (inLen << 3); - x0 ^= c0; + long c0 = Pack.littleEndianToLong_High(input, 0, inLen); + p.x0 ^= c0; + Pack.longToLittleEndian_High(p.x0, output, outOff, inLen); + p.x0 &= -1L >>> (inLen << 3); + p.x0 ^= c0; } } finishData(State.DecFinal); } - private void processFinalEncrypt(byte[] input, int inOff, int inLen, byte[] output, int outOff) + protected void processFinalEncrypt(byte[] input, int inLen, byte[] output, int outOff) { if (inLen >= 8) // ASCON_AEAD_RATE == 16 is implied { - x0 ^= Pack.bigEndianToLong(input, inOff); - Pack.longToBigEndian(x0, output, outOff); - inOff += 8; + p.x0 ^= Pack.bigEndianToLong(input, 0); + Pack.longToBigEndian(p.x0, output, outOff); outOff += 8; inLen -= 8; - x1 ^= PAD(inLen); + p.x1 ^= pad(inLen); if (inLen != 0) { - x1 ^= Pack.littleEndianToLong_High(input, inOff, inLen); - Pack.longToLittleEndian_High(x1, output, outOff, inLen); + p.x1 ^= Pack.littleEndianToLong_High(input, 8, inLen); + Pack.longToLittleEndian_High(p.x1, output, outOff, inLen); } } else { - x0 ^= PAD(inLen); + p.x0 ^= pad(inLen); if (inLen != 0) { - x0 ^= Pack.littleEndianToLong_High(input, inOff, inLen); - Pack.longToLittleEndian_High(x0, output, outOff, inLen); + p.x0 ^= Pack.littleEndianToLong_High(input, 0, inLen); + Pack.longToLittleEndian_High(p.x0, output, outOff, inLen); } } finishData(State.EncFinal); } - private void finishData(State nextState) + protected void finishData(State nextState) { switch (asconParameters) { case ascon128: - x1 ^= K1; - x2 ^= K2; + p.x1 ^= K1; + p.x2 ^= K2; break; case ascon128a: - x2 ^= K1; - x3 ^= K2; + p.x2 ^= K1; + p.x3 ^= K2; break; case ascon80pq: - x1 ^= (K0 << 32 | K1 >> 32); - x2 ^= (K1 << 32 | K2 >> 32); - x3 ^= K2 << 32; + p.x1 ^= (K0 << 32 | K1 >> 32); + p.x2 ^= (K1 << 32 | K2 >> 32); + p.x3 ^= K2 << 32; break; default: throw new IllegalStateException(); } - P(12); - x3 ^= K1; - x4 ^= K2; + p.p(12); + p.x3 ^= K1; + p.x4 ^= K2; m_state = nextState; } - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] key, byte[] iv) throws IllegalArgumentException { - KeyParameter key; - byte[] npub; - if (params instanceof AEADParameters) - { - AEADParameters aeadParameters = (AEADParameters)params; - key = aeadParameters.getKey(); - npub = aeadParameters.getNonce(); - initialAssociatedText = aeadParameters.getAssociatedText(); - - int macSizeBits = aeadParameters.getMacSize(); - if (macSizeBits != CRYPTO_ABYTES * 8) - { - throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits); - } - } - else if (params instanceof ParametersWithIV) - { - ParametersWithIV withIV = (ParametersWithIV)params; - key = (KeyParameter)withIV.getParameters(); - npub = withIV.getIV(); - initialAssociatedText = null; - } - else - { - throw new IllegalArgumentException("invalid parameters passed to Ascon"); - } - - if (key == null) - { - throw new IllegalArgumentException("Ascon Init parameters must include a key"); - } - if (npub == null || npub.length != CRYPTO_ABYTES) - { - throw new IllegalArgumentException(asconParameters + " requires exactly " + CRYPTO_ABYTES + " bytes of IV"); - } - - byte[] k = key.getKey(); - if (k.length != CRYPTO_KEYBYTES) - { - throw new IllegalArgumentException(asconParameters + " key must be " + CRYPTO_KEYBYTES + " bytes long"); - } - - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - N0 = Pack.bigEndianToLong(npub, 0); - N1 = Pack.bigEndianToLong(npub, 8); - if (CRYPTO_KEYBYTES == 16) + N0 = Pack.bigEndianToLong(iv, 0); + N1 = Pack.bigEndianToLong(iv, 8); + if (KEY_SIZE == 16) { - K1 = Pack.bigEndianToLong(k, 0); - K2 = Pack.bigEndianToLong(k, 8); + K1 = Pack.bigEndianToLong(key, 0); + K2 = Pack.bigEndianToLong(key, 8); } - else if (CRYPTO_KEYBYTES == 20) + else if (KEY_SIZE == 20) { - K0 = Pack.bigEndianToInt(k, 0); - K1 = Pack.bigEndianToLong(k, 4); - K2 = Pack.bigEndianToLong(k, 12); + K0 = Pack.bigEndianToInt(key, 0); + K1 = Pack.bigEndianToLong(key, 4); + K2 = Pack.bigEndianToLong(key, 12); } else { throw new IllegalStateException(); } - - m_state = forEncryption ? State.EncInit : State.DecInit; - - reset(true); - } - - public String getAlgorithmName() - { - return algorithmName; } public String getAlgorithmVersion() { return "v1.2"; } - - public void processAADByte(byte in) - { - checkAAD(); - m_buf[m_bufPos] = in; - if (++m_bufPos == ASCON_AEAD_RATE) - { - processBufferAAD(m_buf, 0); - } - } - - public void processAADBytes(byte[] inBytes, int inOff, int len) - { - if ((inOff + len) > inBytes.length) - { - throw new DataLengthException("input buffer too short"); - } - // Don't enter AAD state until we actually get input - if (len <= 0) - { - return; - } - checkAAD(); - if (m_bufPos > 0) - { - int available = ASCON_AEAD_RATE - m_bufPos; - if (len < available) - { - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return; - } - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, available); - inOff += available; - len -= available; - processBufferAAD(m_buf, 0); - //m_bufPos = 0; - } - while (len >= ASCON_AEAD_RATE) - { - processBufferAAD(inBytes, inOff); - inOff += ASCON_AEAD_RATE; - len -= ASCON_AEAD_RATE; - } - System.arraycopy(inBytes, inOff, m_buf, 0, len); - m_bufPos = len; - } - - public int processByte(byte in, byte[] out, int outOff) - throws DataLengthException - { - return processBytes(new byte[]{in}, 0, 1, out, outOff); - } - - public int processBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) - throws DataLengthException - { - if ((inOff + len) > inBytes.length) - { - throw new DataLengthException("input buffer too short"); - } - boolean forEncryption = checkData(); - int resultLength = 0; - - if (forEncryption) - { - if (m_bufPos > 0) - { - int available = ASCON_AEAD_RATE - m_bufPos; - if (len < available) - { - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return 0; - } - - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, available); - inOff += available; - len -= available; - - processBufferEncrypt(m_buf, 0, outBytes, outOff); - resultLength = ASCON_AEAD_RATE; - //m_bufPos = 0; - } - - while (len >= ASCON_AEAD_RATE) - { - processBufferEncrypt(inBytes, inOff, outBytes, outOff + resultLength); - inOff += ASCON_AEAD_RATE; - len -= ASCON_AEAD_RATE; - resultLength += ASCON_AEAD_RATE; - } - } - else - { - int available = m_bufferSizeDecrypt - m_bufPos; - if (len < available) - { - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return 0; - } - - // NOTE: Need 'while' here because ASCON_AEAD_RATE < CRYPTO_ABYTES in some parameter sets - while (m_bufPos >= ASCON_AEAD_RATE) - { - processBufferDecrypt(m_buf, 0, outBytes, outOff + resultLength); - m_bufPos -= ASCON_AEAD_RATE; - System.arraycopy(m_buf, ASCON_AEAD_RATE, m_buf, 0, m_bufPos); - resultLength += ASCON_AEAD_RATE; - - available += ASCON_AEAD_RATE; - if (len < available) - { - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return resultLength; - } - } - - available = ASCON_AEAD_RATE - m_bufPos; - System.arraycopy(inBytes, inOff, m_buf, m_bufPos, available); - inOff += available; - len -= available; - processBufferDecrypt(m_buf, 0, outBytes, outOff + resultLength); - resultLength += ASCON_AEAD_RATE; - //m_bufPos = 0; - - while (len >= m_bufferSizeDecrypt) - { - processBufferDecrypt(inBytes, inOff, outBytes, outOff + resultLength); - inOff += ASCON_AEAD_RATE; - len -= ASCON_AEAD_RATE; - resultLength += ASCON_AEAD_RATE; - } - } - - System.arraycopy(inBytes, inOff, m_buf, 0, len); - m_bufPos = len; - - return resultLength; - } - - public int doFinal(byte[] outBytes, int outOff) - throws IllegalStateException, InvalidCipherTextException, DataLengthException - { - boolean forEncryption = checkData(); - int resultLength; - if (forEncryption) - { - resultLength = m_bufPos + CRYPTO_ABYTES; - if (outOff + resultLength > outBytes.length) - { - throw new OutputLengthException("output buffer too short"); - } - processFinalEncrypt(m_buf, 0, m_bufPos, outBytes, outOff); - mac = new byte[CRYPTO_ABYTES]; - Pack.longToBigEndian(x3, mac, 0); - Pack.longToBigEndian(x4, mac, 8); - System.arraycopy(mac, 0, outBytes, outOff + m_bufPos, CRYPTO_ABYTES); - reset(false); - } - else - { - if (m_bufPos < CRYPTO_ABYTES) - { - throw new InvalidCipherTextException("data too short"); - } - m_bufPos -= CRYPTO_ABYTES; - resultLength = m_bufPos; - if (outOff + resultLength > outBytes.length) - { - throw new OutputLengthException("output buffer too short"); - } - processFinalDecrypt(m_buf, 0, m_bufPos, outBytes, outOff); - x3 ^= Pack.bigEndianToLong(m_buf, m_bufPos); - x4 ^= Pack.bigEndianToLong(m_buf, m_bufPos + 8); - if ((x3 | x4) != 0L) - { - throw new InvalidCipherTextException("mac check in " + getAlgorithmName() + " failed"); - } - reset(true); - } - return resultLength; - } - - public byte[] getMac() - { - return mac; - } - - public int getUpdateOutputSize(int len) - { - int total = Math.max(0, len); - switch (m_state) - { - case DecInit: - case DecAad: - total = Math.max(0, total - CRYPTO_ABYTES); - break; - case DecData: - case DecFinal: - total = Math.max(0, total + m_bufPos - CRYPTO_ABYTES); - break; - case EncData: - case EncFinal: - total += m_bufPos; - break; - default: - break; - } - return total - total % ASCON_AEAD_RATE; - } - - public int getOutputSize(int len) - { - int total = Math.max(0, len); - - switch (m_state) - { - case DecInit: - case DecAad: - return Math.max(0, total - CRYPTO_ABYTES); - case DecData: - case DecFinal: - return Math.max(0, total + m_bufPos - CRYPTO_ABYTES); - case EncData: - case EncFinal: - return total + m_bufPos + CRYPTO_ABYTES; - default: - return total + CRYPTO_ABYTES; - } - } - - public void reset() - { - reset(true); - } - - private void reset(boolean clearMac) - { - if (clearMac) - { - mac = null; - } - Arrays.clear(m_buf); - m_bufPos = 0; - - switch (m_state) - { - case DecInit: - case EncInit: - break; - case DecAad: - case DecData: - case DecFinal: - m_state = State.DecInit; - break; - case EncAad: - case EncData: - case EncFinal: - m_state = State.EncFinal; - return; - default: - throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); - } - ascon_aeadinit(); - if (initialAssociatedText != null) - { - processAADBytes(initialAssociatedText, 0, initialAssociatedText.length); - } - } - - public int getKeyBytesSize() - { - return CRYPTO_KEYBYTES; - } - - public int getIVBytesSize() - { - return CRYPTO_ABYTES; - } -} +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/AsconPermutationFriend.java b/core/src/main/java/org/bouncycastle/crypto/engines/AsconPermutationFriend.java new file mode 100644 index 0000000000..3d7b8d037e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/AsconPermutationFriend.java @@ -0,0 +1,82 @@ +package org.bouncycastle.crypto.engines; + +import org.bouncycastle.crypto.digests.ISAPDigest; +import org.bouncycastle.util.Longs; + +public class AsconPermutationFriend +{ + public static AsconPermutation getAsconPermutation(ISAPDigest.Friend friend) + { + if (null == friend) + { + throw new NullPointerException("This method is only for use by ISAPDigest or Ascon Digest"); + } + return new AsconPermutation(); + } + + public static class AsconPermutation + { + AsconPermutation() + { + } + + public long x0; + public long x1; + public long x2; + public long x3; + public long x4; + + public void round(long C) + { + x2 ^= C; + long x0x4 = x0 ^ x4; + //long x0x2c = x0 ^ x2; + long x1x2c = x1 ^ x2; + long x1orx2c = x1 | x2; + long t0 = x3 ^ x1orx2c ^ x0 ^ (x1 & x0x4); + //long t1 = x0x4 ^ x2 ^ x3 ^ (x1x2c & (x1 ^ x3)); + long t1 = x0x4 ^ (x1orx2c | x3) ^ (x1 & x2 & x3); + long t2 = x1x2c ^ (x4 & (~x3));//x4 ^ (x3 & x4); + //long t3 = x0 ^ x1x2c ^ ((~x0) & (x3 ^ x4)); + long t3 = (x0 | (x3 ^ x4)) ^ x1x2c; + //long t4 = x1 ^ x3 ^ x4 ^ (x0x4 & x1); + long t4 = x3 ^ (x1 | x4) ^ (x0 & x1); + x0 = t0 ^ Longs.rotateRight(t0, 19) ^ Longs.rotateRight(t0, 28); + x1 = t1 ^ Longs.rotateRight(t1, 39) ^ Longs.rotateRight(t1, 61); + x2 = ~(t2 ^ Longs.rotateRight(t2, 1) ^ Longs.rotateRight(t2, 6)); + x3 = t3 ^ Longs.rotateRight(t3, 10) ^ Longs.rotateRight(t3, 17); + x4 = t4 ^ Longs.rotateRight(t4, 7) ^ Longs.rotateRight(t4, 41); + } + + public void p(int nr) + { + if (nr == 12) + { + round(0xf0L); + round(0xe1L); + round(0xd2L); + round(0xc3L); + } + if (nr >= 8) + { + round(0xb4L); + round(0xa5L); + } + round(0x96L); + round(0x87L); + round(0x78L); + round(0x69L); + round(0x5aL); + round(0x4bL); + } + + public void set(long x0, long x1, long x2, long x3, long x4) + { + this.x0 = x0; + this.x1 = x1; + this.x2 = x2; + this.x3 = x3; + this.x4 = x4; + } + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/ElephantEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/ElephantEngine.java index 4f22370991..fa5e7a1b4f 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/ElephantEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/ElephantEngine.java @@ -1,17 +1,8 @@ package org.bouncycastle.crypto.engines; -import java.io.ByteArrayOutputStream; import java.util.Arrays; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Bytes; /** * Elephant AEAD v2, based on the current round 3 submission, https://www.esat.kuleuven.be/cosic/elephant/ @@ -19,7 +10,7 @@ * Specification: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/elephant-spec-final.pdf */ public class ElephantEngine - implements AEADCipher + extends AEADBaseEngine { public enum ElephantParameters { @@ -28,34 +19,8 @@ public enum ElephantParameters elephant200 } - private enum State - { - Uninitialized, - EncInit, - EncAad, // can process AAD - EncData, // cannot process AAD - EncFinal, - DecInit, - DecAad, // can process AAD - DecData, // cannot process AAD - DecFinal, - } - - private boolean forEncryption; - private final String algorithmName; - private final ElephantParameters parameters; - private final int BLOCK_SIZE; - private int nBits; - private int nSBox; - private final int nRounds; - private byte lfsrIV; - private byte[] tag; private byte[] npub; private byte[] expanded_key; - private final byte CRYPTO_KEYBYTES = 16; - private final byte CRYPTO_NPUBBYTES = 12; - private final byte CRYPTO_ABYTES; - private boolean initialised; private int nb_its; private byte[] ad; private int adOff; @@ -65,88 +30,88 @@ private enum State private byte[] current_mask; private byte[] next_mask; private final byte[] buffer; - private State m_state = State.Uninitialized; - private final ByteArrayOutputStream aadData = new ByteArrayOutputStream(); - private int inputOff; - private byte[] inputMessage; private final byte[] previous_outputMessage; - private final byte[] outputMessage; - - private final byte[] sBoxLayer = { - (byte)0xee, (byte)0xed, (byte)0xeb, (byte)0xe0, (byte)0xe2, (byte)0xe1, (byte)0xe4, (byte)0xef, (byte)0xe7, (byte)0xea, (byte)0xe8, (byte)0xe5, (byte)0xe9, (byte)0xec, (byte)0xe3, (byte)0xe6, - (byte)0xde, (byte)0xdd, (byte)0xdb, (byte)0xd0, (byte)0xd2, (byte)0xd1, (byte)0xd4, (byte)0xdf, (byte)0xd7, (byte)0xda, (byte)0xd8, (byte)0xd5, (byte)0xd9, (byte)0xdc, (byte)0xd3, (byte)0xd6, - (byte)0xbe, (byte)0xbd, (byte)0xbb, (byte)0xb0, (byte)0xb2, (byte)0xb1, (byte)0xb4, (byte)0xbf, (byte)0xb7, (byte)0xba, (byte)0xb8, (byte)0xb5, (byte)0xb9, (byte)0xbc, (byte)0xb3, (byte)0xb6, - (byte)0x0e, (byte)0x0d, (byte)0x0b, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x04, (byte)0x0f, (byte)0x07, (byte)0x0a, (byte)0x08, (byte)0x05, (byte)0x09, (byte)0x0c, (byte)0x03, (byte)0x06, - (byte)0x2e, (byte)0x2d, (byte)0x2b, (byte)0x20, (byte)0x22, (byte)0x21, (byte)0x24, (byte)0x2f, (byte)0x27, (byte)0x2a, (byte)0x28, (byte)0x25, (byte)0x29, (byte)0x2c, (byte)0x23, (byte)0x26, - (byte)0x1e, (byte)0x1d, (byte)0x1b, (byte)0x10, (byte)0x12, (byte)0x11, (byte)0x14, (byte)0x1f, (byte)0x17, (byte)0x1a, (byte)0x18, (byte)0x15, (byte)0x19, (byte)0x1c, (byte)0x13, (byte)0x16, - (byte)0x4e, (byte)0x4d, (byte)0x4b, (byte)0x40, (byte)0x42, (byte)0x41, (byte)0x44, (byte)0x4f, (byte)0x47, (byte)0x4a, (byte)0x48, (byte)0x45, (byte)0x49, (byte)0x4c, (byte)0x43, (byte)0x46, - (byte)0xfe, (byte)0xfd, (byte)0xfb, (byte)0xf0, (byte)0xf2, (byte)0xf1, (byte)0xf4, (byte)0xff, (byte)0xf7, (byte)0xfa, (byte)0xf8, (byte)0xf5, (byte)0xf9, (byte)0xfc, (byte)0xf3, (byte)0xf6, - (byte)0x7e, (byte)0x7d, (byte)0x7b, (byte)0x70, (byte)0x72, (byte)0x71, (byte)0x74, (byte)0x7f, (byte)0x77, (byte)0x7a, (byte)0x78, (byte)0x75, (byte)0x79, (byte)0x7c, (byte)0x73, (byte)0x76, - (byte)0xae, (byte)0xad, (byte)0xab, (byte)0xa0, (byte)0xa2, (byte)0xa1, (byte)0xa4, (byte)0xaf, (byte)0xa7, (byte)0xaa, (byte)0xa8, (byte)0xa5, (byte)0xa9, (byte)0xac, (byte)0xa3, (byte)0xa6, - (byte)0x8e, (byte)0x8d, (byte)0x8b, (byte)0x80, (byte)0x82, (byte)0x81, (byte)0x84, (byte)0x8f, (byte)0x87, (byte)0x8a, (byte)0x88, (byte)0x85, (byte)0x89, (byte)0x8c, (byte)0x83, (byte)0x86, - (byte)0x5e, (byte)0x5d, (byte)0x5b, (byte)0x50, (byte)0x52, (byte)0x51, (byte)0x54, (byte)0x5f, (byte)0x57, (byte)0x5a, (byte)0x58, (byte)0x55, (byte)0x59, (byte)0x5c, (byte)0x53, (byte)0x56, - (byte)0x9e, (byte)0x9d, (byte)0x9b, (byte)0x90, (byte)0x92, (byte)0x91, (byte)0x94, (byte)0x9f, (byte)0x97, (byte)0x9a, (byte)0x98, (byte)0x95, (byte)0x99, (byte)0x9c, (byte)0x93, (byte)0x96, - (byte)0xce, (byte)0xcd, (byte)0xcb, (byte)0xc0, (byte)0xc2, (byte)0xc1, (byte)0xc4, (byte)0xcf, (byte)0xc7, (byte)0xca, (byte)0xc8, (byte)0xc5, (byte)0xc9, (byte)0xcc, (byte)0xc3, (byte)0xc6, - (byte)0x3e, (byte)0x3d, (byte)0x3b, (byte)0x30, (byte)0x32, (byte)0x31, (byte)0x34, (byte)0x3f, (byte)0x37, (byte)0x3a, (byte)0x38, (byte)0x35, (byte)0x39, (byte)0x3c, (byte)0x33, (byte)0x36, - (byte)0x6e, (byte)0x6d, (byte)0x6b, (byte)0x60, (byte)0x62, (byte)0x61, (byte)0x64, (byte)0x6f, (byte)0x67, (byte)0x6a, (byte)0x68, (byte)0x65, (byte)0x69, (byte)0x6c, (byte)0x63, (byte)0x66 - }; - - private final byte[] KeccakRoundConstants = { - (byte)0x01, (byte)0x82, (byte)0x8a, (byte)0x00, (byte)0x8b, (byte)0x01, (byte)0x81, (byte)0x09, (byte)0x8a, - (byte)0x88, (byte)0x09, (byte)0x0a, (byte)0x8b, (byte)0x8b, (byte)0x89, (byte)0x03, (byte)0x02, (byte)0x80 - }; - - private final int[] KeccakRhoOffsets = {0, 1, 6, 4, 3, 4, 4, 6, 7, 4, 3, 2, 3, 1, 7, 1, 5, 7, 5, 0, 2, 2, 5, 0, 6}; + private final Permutation instance; public ElephantEngine(ElephantParameters parameters) { + KEY_SIZE = 16; + IV_SIZE = 12; switch (parameters) { case elephant160: - BLOCK_SIZE = 20; - nBits = 160; - nSBox = 20; - nRounds = 80; - lfsrIV = 0x75; - CRYPTO_ABYTES = 8; + BlockSize = 20; + instance = new Dumbo(); + MAC_SIZE = 8; algorithmName = "Elephant 160 AEAD"; break; case elephant176: - BLOCK_SIZE = 22; - nBits = 176; - nSBox = 22; - nRounds = 90; - lfsrIV = 0x45; - CRYPTO_ABYTES = 8; + BlockSize = 22; + instance = new Jumbo(); algorithmName = "Elephant 176 AEAD"; + MAC_SIZE = 8; break; case elephant200: - BLOCK_SIZE = 25; - nRounds = 18; - CRYPTO_ABYTES = 16; + BlockSize = 25; + instance = new Delirium(); algorithmName = "Elephant 200 AEAD"; + MAC_SIZE = 16; break; default: throw new IllegalArgumentException("Invalid parameter settings for Elephant"); } - this.parameters = parameters; - tag_buffer = new byte[BLOCK_SIZE]; - previous_mask = new byte[BLOCK_SIZE]; - current_mask = new byte[BLOCK_SIZE]; - next_mask = new byte[BLOCK_SIZE]; - buffer = new byte[BLOCK_SIZE]; - previous_outputMessage = new byte[BLOCK_SIZE]; - outputMessage = new byte[BLOCK_SIZE]; - initialised = false; - reset(false); + tag_buffer = new byte[BlockSize]; + previous_mask = new byte[BlockSize]; + current_mask = new byte[BlockSize]; + next_mask = new byte[BlockSize]; + buffer = new byte[BlockSize]; + previous_outputMessage = new byte[BlockSize]; + setInnerMembers(ProcessingBufferType.Immediate, AADOperatorType.Stream, DataOperatorType.Counter); } - private void permutation(byte[] state) + private interface Permutation { - switch (parameters) + void permutation(byte[] state); + + void lfsr_step(); + } + + private abstract static class Spongent + implements Permutation + { + private final byte lfsrIV; + private final int nRounds; + private final int nBits; + private final int nSBox; + private final byte[] sBoxLayer = { + (byte)0xee, (byte)0xed, (byte)0xeb, (byte)0xe0, (byte)0xe2, (byte)0xe1, (byte)0xe4, (byte)0xef, (byte)0xe7, (byte)0xea, (byte)0xe8, (byte)0xe5, (byte)0xe9, (byte)0xec, (byte)0xe3, (byte)0xe6, + (byte)0xde, (byte)0xdd, (byte)0xdb, (byte)0xd0, (byte)0xd2, (byte)0xd1, (byte)0xd4, (byte)0xdf, (byte)0xd7, (byte)0xda, (byte)0xd8, (byte)0xd5, (byte)0xd9, (byte)0xdc, (byte)0xd3, (byte)0xd6, + (byte)0xbe, (byte)0xbd, (byte)0xbb, (byte)0xb0, (byte)0xb2, (byte)0xb1, (byte)0xb4, (byte)0xbf, (byte)0xb7, (byte)0xba, (byte)0xb8, (byte)0xb5, (byte)0xb9, (byte)0xbc, (byte)0xb3, (byte)0xb6, + (byte)0x0e, (byte)0x0d, (byte)0x0b, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x04, (byte)0x0f, (byte)0x07, (byte)0x0a, (byte)0x08, (byte)0x05, (byte)0x09, (byte)0x0c, (byte)0x03, (byte)0x06, + (byte)0x2e, (byte)0x2d, (byte)0x2b, (byte)0x20, (byte)0x22, (byte)0x21, (byte)0x24, (byte)0x2f, (byte)0x27, (byte)0x2a, (byte)0x28, (byte)0x25, (byte)0x29, (byte)0x2c, (byte)0x23, (byte)0x26, + (byte)0x1e, (byte)0x1d, (byte)0x1b, (byte)0x10, (byte)0x12, (byte)0x11, (byte)0x14, (byte)0x1f, (byte)0x17, (byte)0x1a, (byte)0x18, (byte)0x15, (byte)0x19, (byte)0x1c, (byte)0x13, (byte)0x16, + (byte)0x4e, (byte)0x4d, (byte)0x4b, (byte)0x40, (byte)0x42, (byte)0x41, (byte)0x44, (byte)0x4f, (byte)0x47, (byte)0x4a, (byte)0x48, (byte)0x45, (byte)0x49, (byte)0x4c, (byte)0x43, (byte)0x46, + (byte)0xfe, (byte)0xfd, (byte)0xfb, (byte)0xf0, (byte)0xf2, (byte)0xf1, (byte)0xf4, (byte)0xff, (byte)0xf7, (byte)0xfa, (byte)0xf8, (byte)0xf5, (byte)0xf9, (byte)0xfc, (byte)0xf3, (byte)0xf6, + (byte)0x7e, (byte)0x7d, (byte)0x7b, (byte)0x70, (byte)0x72, (byte)0x71, (byte)0x74, (byte)0x7f, (byte)0x77, (byte)0x7a, (byte)0x78, (byte)0x75, (byte)0x79, (byte)0x7c, (byte)0x73, (byte)0x76, + (byte)0xae, (byte)0xad, (byte)0xab, (byte)0xa0, (byte)0xa2, (byte)0xa1, (byte)0xa4, (byte)0xaf, (byte)0xa7, (byte)0xaa, (byte)0xa8, (byte)0xa5, (byte)0xa9, (byte)0xac, (byte)0xa3, (byte)0xa6, + (byte)0x8e, (byte)0x8d, (byte)0x8b, (byte)0x80, (byte)0x82, (byte)0x81, (byte)0x84, (byte)0x8f, (byte)0x87, (byte)0x8a, (byte)0x88, (byte)0x85, (byte)0x89, (byte)0x8c, (byte)0x83, (byte)0x86, + (byte)0x5e, (byte)0x5d, (byte)0x5b, (byte)0x50, (byte)0x52, (byte)0x51, (byte)0x54, (byte)0x5f, (byte)0x57, (byte)0x5a, (byte)0x58, (byte)0x55, (byte)0x59, (byte)0x5c, (byte)0x53, (byte)0x56, + (byte)0x9e, (byte)0x9d, (byte)0x9b, (byte)0x90, (byte)0x92, (byte)0x91, (byte)0x94, (byte)0x9f, (byte)0x97, (byte)0x9a, (byte)0x98, (byte)0x95, (byte)0x99, (byte)0x9c, (byte)0x93, (byte)0x96, + (byte)0xce, (byte)0xcd, (byte)0xcb, (byte)0xc0, (byte)0xc2, (byte)0xc1, (byte)0xc4, (byte)0xcf, (byte)0xc7, (byte)0xca, (byte)0xc8, (byte)0xc5, (byte)0xc9, (byte)0xcc, (byte)0xc3, (byte)0xc6, + (byte)0x3e, (byte)0x3d, (byte)0x3b, (byte)0x30, (byte)0x32, (byte)0x31, (byte)0x34, (byte)0x3f, (byte)0x37, (byte)0x3a, (byte)0x38, (byte)0x35, (byte)0x39, (byte)0x3c, (byte)0x33, (byte)0x36, + (byte)0x6e, (byte)0x6d, (byte)0x6b, (byte)0x60, (byte)0x62, (byte)0x61, (byte)0x64, (byte)0x6f, (byte)0x67, (byte)0x6a, (byte)0x68, (byte)0x65, (byte)0x69, (byte)0x6c, (byte)0x63, (byte)0x66 + }; + + public Spongent(int nBits, int nSBox, int nRounds, byte lfsrIV) + { + this.nRounds = nRounds; + this.nSBox = nSBox; + this.lfsrIV = lfsrIV; + this.nBits = nBits; + } + + public void permutation(byte[] state) { - case elephant160: - case elephant176: byte IV = lfsrIV; byte[] tmp = new byte[nSBox]; for (int i = 0; i < nRounds; i++) @@ -178,441 +143,398 @@ private void permutation(byte[] state) } System.arraycopy(tmp, 0, state, 0, nSBox); } - break; - case elephant200: - for (int i = 0; i < nRounds; i++) - { - KeccakP200Round(state, i); - } - break; } } - private byte rotl(byte b) + private class Dumbo + extends Spongent { - return (byte)(((b & 0xFF) << 1) | ((b & 0xFF) >>> 7)); - } + public Dumbo() + { + super(160, 20, 80, (byte)0x75); + } - private byte ROL8(byte a, int offset) - { - return (byte)((offset != 0) ? (((a & 0xFF) << offset) ^ ((a & 0xFF) >>> (8 - offset))) : a); + @Override + public void lfsr_step() + { + next_mask[BlockSize - 1] = (byte)((((current_mask[0] & 0xFF) << 3) | ((current_mask[0] & 0xFF) >>> 5)) ^ + ((current_mask[3] & 0xFF) << 7) ^ ((current_mask[13] & 0xFF) >>> 7)); + } } - private int index(int x, int y) + private class Jumbo + extends Spongent { - return x + y * 5; + public Jumbo() + { + super(176, 22, 90, (byte)0x45); + } + + @Override + public void lfsr_step() + { + next_mask[BlockSize - 1] = (byte)(rotl(current_mask[0]) ^ ((current_mask[3] & 0xFF) << 7) ^ ((current_mask[19] & 0xFF) >>> 7)); + } } - private void KeccakP200Round(byte[] state, int indexRound) + private class Delirium + implements Permutation { - int x, y; - byte[] tempA = new byte[25]; - //theta - for (x = 0; x < 5; x++) + private static final int nRounds = 18; + private final byte[] KeccakRoundConstants = { + (byte)0x01, (byte)0x82, (byte)0x8a, (byte)0x00, (byte)0x8b, (byte)0x01, (byte)0x81, (byte)0x09, (byte)0x8a, + (byte)0x88, (byte)0x09, (byte)0x0a, (byte)0x8b, (byte)0x8b, (byte)0x89, (byte)0x03, (byte)0x02, (byte)0x80 + }; + + private final int[] KeccakRhoOffsets = {0, 1, 6, 4, 3, 4, 4, 6, 7, 4, 3, 2, 3, 1, 7, 1, 5, 7, 5, 0, 2, 2, 5, 0, 6}; + + @Override + public void permutation(byte[] state) { - for (y = 0; y < 5; y++) + for (int i = 0; i < nRounds; i++) { - tempA[x] ^= state[index(x, y)]; + KeccakP200Round(state, i); } } - for (x = 0; x < 5; x++) + + @Override + public void lfsr_step() { - tempA[x + 5] = (byte)(ROL8(tempA[(x + 1) % 5], 1) ^ tempA[(x + 4) % 5]); + next_mask[BlockSize - 1] = (byte)(rotl(current_mask[0]) ^ rotl(current_mask[2]) ^ (current_mask[13] << 1)); } - for (x = 0; x < 5; x++) + + private void KeccakP200Round(byte[] state, int indexRound) { - for (y = 0; y < 5; y++) + int x, y; + byte[] tempA = new byte[25]; + //theta + for (x = 0; x < 5; x++) { - state[index(x, y)] ^= tempA[x + 5]; + for (y = 0; y < 5; y++) + { + tempA[x] ^= state[index(x, y)]; + } } - } - //rho - for (x = 0; x < 5; x++) - { - for (y = 0; y < 5; y++) + for (x = 0; x < 5; x++) { - tempA[index(x, y)] = ROL8(state[index(x, y)], KeccakRhoOffsets[index(x, y)]); + tempA[x + 5] = (byte)(ROL8(tempA[(x + 1) % 5], 1) ^ tempA[(x + 4) % 5]); } - } - //pi - for (x = 0; x < 5; x++) - { - for (y = 0; y < 5; y++) + for (x = 0; x < 5; x++) { - state[index(y, (2 * x + 3 * y) % 5)] = tempA[index(x, y)]; + for (y = 0; y < 5; y++) + { + state[index(x, y)] ^= tempA[x + 5]; + } } - } - //chi - for (y = 0; y < 5; y++) - { + //rho for (x = 0; x < 5; x++) { - tempA[x] = (byte)(state[index(x, y)] ^ ((~state[index((x + 1) % 5, y)]) & state[index((x + 2) % 5, y)])); + for (y = 0; y < 5; y++) + { + tempA[index(x, y)] = ROL8(state[index(x, y)], KeccakRhoOffsets[index(x, y)]); + } } + //pi for (x = 0; x < 5; x++) { - state[index(x, y)] = tempA[x]; + for (y = 0; y < 5; y++) + { + state[index(y, (2 * x + 3 * y) % 5)] = tempA[index(x, y)]; + } + } + //chi + for (y = 0; y < 5; y++) + { + for (x = 0; x < 5; x++) + { + tempA[x] = (byte)(state[index(x, y)] ^ ((~state[index((x + 1) % 5, y)]) & state[index((x + 2) % 5, y)])); + } + for (x = 0; x < 5; x++) + { + state[index(x, y)] = tempA[x]; + } } + //iota + state[0] ^= KeccakRoundConstants[indexRound];//index(0,0) } - //iota - state[0] ^= KeccakRoundConstants[indexRound];//index(0,0) - } + //TODO: search for " >>> (8 - " merge with with CamelliaLightEngine.lRot8, + // code in OCBBlockCipher.init, DualECSP800DRBG.pad8, + private byte ROL8(byte a, int offset) + { + return (byte)((a << offset) | ((a & 0xff) >>> (8 - offset))); + } - // State should be BLOCK_SIZE bytes long - // Note: input may be equal to output - private void lfsr_step(byte[] output, byte[] input) - { - switch (parameters) + private int index(int x, int y) { - case elephant160: - output[BLOCK_SIZE - 1] = (byte)((((input[0] & 0xFF) << 3) | ((input[0] & 0xFF) >>> 5)) ^ - ((input[3] & 0xFF) << 7) ^ ((input[13] & 0xFF) >>> 7)); - break; - case elephant176: - output[BLOCK_SIZE - 1] = (byte)(rotl(input[0]) ^ ((input[3] & 0xFF) << 7) ^ ((input[19] & 0xFF) >>> 7)); - break; - case elephant200: - output[BLOCK_SIZE - 1] = (byte)(rotl(input[0]) ^ rotl(input[2]) ^ (input[13] << 1)); - break; + return x + y * 5; } - System.arraycopy(input, 1, output, 0, BLOCK_SIZE - 1); } - private void xor_block(byte[] state, byte[] block, int bOff, int size) + private byte rotl(byte b) { - for (int i = 0; i < size; ++i) - { - state[i] ^= block[i + bOff]; - } + return (byte)((b << 1) | ((b & 0xFF) >>> 7)); } - // Return the ith ciphertext block. - // clen is the length of the ciphertext in bytes - private void get_c_block(byte[] output, byte[] c, int cOff, int clen, int i) + // State should be BLOCK_SIZE bytes long + // Note: input may be equal to output + private void lfsr_step() { - int block_offset = i * BLOCK_SIZE; - // If clen is divisible by BLOCK_SIZE, add an additional padding block - if (block_offset == clen) - { - Arrays.fill(output, 0, BLOCK_SIZE, (byte)0); - output[0] = 0x01; - return; - } - int r_clen = clen - block_offset; - // Fill with ciphertext if available - if (BLOCK_SIZE <= r_clen) - { // enough ciphertext - System.arraycopy(c, cOff, output, 0, BLOCK_SIZE); - } - else - { // not enough ciphertext, need to pad - if (r_clen > 0) // c might be nullptr - { - System.arraycopy(c, cOff, output, 0, r_clen); - } - Arrays.fill(output, r_clen, BLOCK_SIZE, (byte)0); - output[r_clen] = 0x01; - } + instance.lfsr_step(); + System.arraycopy(current_mask, 1, next_mask, 0, BlockSize - 1); } @Override - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] k, byte[] iv) throws IllegalArgumentException { - this.forEncryption = forEncryption; - if (!(params instanceof ParametersWithIV)) - { - throw new IllegalArgumentException(algorithmName + " init parameters must include an IV"); - } - ParametersWithIV ivParams = (ParametersWithIV)params; - npub = ivParams.getIV(); - if (npub == null || npub.length != CRYPTO_NPUBBYTES) + npub = iv; + // Storage for the expanded key L + expanded_key = new byte[BlockSize]; + System.arraycopy(k, 0, expanded_key, 0, KEY_SIZE); + instance.permutation(expanded_key); + } + + protected void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) + { + processBuffer(input, inOff, output, outOff, State.EncData); + System.arraycopy(output, outOff, previous_outputMessage, 0, BlockSize); + } + + private void processBuffer(byte[] input, int inOff, byte[] output, int outOff, State encData) + { + if (m_state == State.DecInit || m_state == State.EncInit) { - throw new IllegalArgumentException(algorithmName + " requires exactly 12 bytes of IV"); + processFinalAAD(); } - if (!(ivParams.getParameters() instanceof KeyParameter)) + // Compute mask for the next message + lfsr_step(); + + // Compute ciphertext block + computeCipherBlock(input, inOff, BlockSize, output, outOff); + + if (nb_its > 0) { - throw new IllegalArgumentException(algorithmName + " init parameters must include a key"); + // enough ciphertext + System.arraycopy(previous_outputMessage, 0, buffer, 0, BlockSize); + absorbCiphertext(); } - KeyParameter key = (KeyParameter)ivParams.getParameters(); - byte[] k = key.getKey(); - if (k.length != CRYPTO_KEYBYTES) + // If there is any AD left, compute tag for AD block + if (m_state != encData) { - throw new IllegalArgumentException(algorithmName + " key must be 128 bits long"); + absorbAAD(); } - // Storage for the expanded key L - expanded_key = new byte[BLOCK_SIZE]; - System.arraycopy(k, 0, expanded_key, 0, CRYPTO_KEYBYTES); - permutation(expanded_key); - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - initialised = true; - m_state = forEncryption ? State.EncInit : State.DecInit; - inputMessage = new byte[BLOCK_SIZE + (forEncryption ? 0 : CRYPTO_ABYTES)]; - reset(false); + // Cyclically shift the mask buffers + // Value of next_mask will be computed in the next iteration + swapMasks(); + nb_its++; } - @Override - public String getAlgorithmName() + protected void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) { - return algorithmName; + processBuffer(input, inOff, output, outOff, State.DecData); + System.arraycopy(input, inOff, previous_outputMessage, 0, BlockSize); } - @Override - public void processAADByte(byte input) + private void computeCipherBlock(byte[] input, int inOff, int blockSize, byte[] output, int outOff) { - aadData.write(input); + System.arraycopy(npub, 0, buffer, 0, IV_SIZE); + Arrays.fill(buffer, IV_SIZE, BlockSize, (byte)0); + xorTo(BlockSize, current_mask, next_mask, buffer); + instance.permutation(buffer); + xorTo(BlockSize, current_mask, next_mask, buffer); + + Bytes.xorTo(blockSize, input, inOff, buffer); + System.arraycopy(buffer, 0, output, outOff, blockSize); } - @Override - public void processAADBytes(byte[] input, int inOff, int len) + private void swapMasks() { - if (inOff + len > input.length) - { - throw new DataLengthException("input buffer too short"); - } - aadData.write(input, inOff, len); + byte[] temp = previous_mask; + previous_mask = current_mask; + current_mask = next_mask; + next_mask = temp; } - @Override - public int processByte(byte input, byte[] output, int outOff) - throws DataLengthException + private void absorbAAD() { - return processBytes(new byte[]{input}, 0, 1, output, outOff); + processAADBytes(buffer); + Bytes.xorTo(BlockSize, next_mask, buffer); + instance.permutation(buffer); + Bytes.xorTo(BlockSize, next_mask, buffer); + Bytes.xorTo(BlockSize, buffer, tag_buffer); } - @Override - public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) - throws DataLengthException + private void absorbCiphertext() { - if (inOff + len > input.length) - { - throw new DataLengthException("input buffer too short"); - } - byte[] ad = aadData.toByteArray(); - - - if (inputOff + len - (forEncryption ? 0 : CRYPTO_ABYTES) >= BLOCK_SIZE) - { - switch (m_state) - { - case EncInit: - case DecInit: - processAADBytes(tag_buffer); - break; - } - int mlen = inputOff + len - (forEncryption ? 0 : CRYPTO_ABYTES); - int adlen = ad.length; - int nblocks_c = mlen / BLOCK_SIZE; - int nblocks_m = 1 + ((mlen % BLOCK_SIZE) != 0 ? nblocks_c : nblocks_c - 1); - int nblocks_ad = 1 + (CRYPTO_NPUBBYTES + adlen) / BLOCK_SIZE; - byte[] tempInput = new byte[Math.max(nblocks_c, 1) * BLOCK_SIZE]; - System.arraycopy(inputMessage, 0, tempInput, 0, inputOff); - int templen = tempInput.length - inputOff; - System.arraycopy(input, inOff, tempInput, inputOff, tempInput.length - inputOff); - processBytes(tempInput, output, outOff, nblocks_c, nblocks_m, nblocks_c, mlen, nblocks_ad); - inputOff = len - templen; - System.arraycopy(input, inOff + templen, inputMessage, 0, inputOff); - nb_its += nblocks_c; - return nblocks_c * BLOCK_SIZE; - } - else - { - System.arraycopy(input, inOff, inputMessage, inputOff, len); - inputOff += len; - return 0; - } + xorTo(BlockSize, previous_mask, next_mask, buffer); + instance.permutation(buffer); + xorTo(BlockSize, previous_mask, next_mask, buffer); + Bytes.xorTo(BlockSize, buffer, tag_buffer); } - @Override - public int doFinal(byte[] output, int outOff) - throws IllegalStateException, InvalidCipherTextException + protected void processFinalBlock(byte[] output, int outOff) { - if (!initialised) - { - throw new IllegalArgumentException(algorithmName + " needs call init function before doFinal"); - } - int len = inputOff; - if ((forEncryption && len + outOff + CRYPTO_ABYTES > output.length) || - (!forEncryption && len + outOff - CRYPTO_ABYTES > output.length)) - { - throw new OutputLengthException("output buffer is too short"); - } - byte[] ad = aadData.toByteArray(); - switch (m_state) - { - case EncInit: - case DecInit: - processAADBytes(tag_buffer); - break; - } - int mlen = len + nb_its * BLOCK_SIZE - (forEncryption ? 0 : CRYPTO_ABYTES); - int adlen = ad.length; - int nblocks_c = 1 + mlen / BLOCK_SIZE; - int nblocks_m = (mlen % BLOCK_SIZE) != 0 ? nblocks_c : nblocks_c - 1; - int nblocks_ad = 1 + (CRYPTO_NPUBBYTES + adlen) / BLOCK_SIZE; + int mlen = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + processFinalAAD(); + int nblocks_c = 1 + mlen / BlockSize; + int nblocks_m = (mlen % BlockSize) != 0 ? nblocks_c : nblocks_c - 1; + int nblocks_ad = 1 + (IV_SIZE + adlen) / BlockSize; int nb_it = Math.max(nblocks_c + 1, nblocks_ad - 1); - outOff += processBytes(inputMessage, output, outOff, nb_it, nblocks_m, nblocks_c, mlen, nblocks_ad); - tag = new byte[CRYPTO_ABYTES]; - xor_block(tag_buffer, expanded_key, 0, BLOCK_SIZE); - permutation(tag_buffer); - xor_block(tag_buffer, expanded_key, 0, BLOCK_SIZE); - if (forEncryption) - { - System.arraycopy(tag_buffer, 0, tag, 0, CRYPTO_ABYTES); - System.arraycopy(tag, 0, output, outOff, tag.length); - mlen += CRYPTO_ABYTES; - } - else - { - inputOff -= CRYPTO_ABYTES; - for (int i = 0; i < CRYPTO_ABYTES; ++i) - { - if (tag_buffer[i] != inputMessage[inputOff + i]) - { - throw new IllegalArgumentException("Mac does not match"); - } - } - } - reset(false); - return mlen; + processBytes(m_buf, output, outOff, nb_it, nblocks_m, nblocks_c, mlen, nblocks_ad); + Bytes.xorTo(BlockSize, expanded_key, tag_buffer); + instance.permutation(tag_buffer); + Bytes.xorTo(BlockSize, expanded_key, tag_buffer); + System.arraycopy(tag_buffer, 0, mac, 0, MAC_SIZE); } @Override - public byte[] getMac() + protected void processBufferAAD(byte[] input, int inOff) { - return tag; } @Override public int getUpdateOutputSize(int len) { - switch (m_state) + switch (m_state.ord) { - case Uninitialized: + case State.UNINITIALIZED: throw new IllegalArgumentException(algorithmName + " needs call init function before getUpdateOutputSize"); - case DecFinal: - case EncFinal: + case State.DEC_FINAL: + case State.ENC_FINAL: return 0; - case EncAad: - case EncData: - case EncInit: - return inputOff + len + CRYPTO_ABYTES; + case State.ENC_AAD: + case State.ENC_DATA: + case State.ENC_INIT: + { + int total = m_bufPos + len; + return total - total % BlockSize; + } + case State.DEC_AAD: + case State.DEC_DATA: + case State.DEC_INIT: + { + int total = Math.max(0, m_bufPos + len - MAC_SIZE); + return total - total % BlockSize; + } } - return Math.max(0, len + inputOff - CRYPTO_ABYTES); + return Math.max(0, len + m_bufPos - MAC_SIZE); } @Override public int getOutputSize(int len) { - switch (m_state) + switch (m_state.ord) { - case Uninitialized: + case State.UNINITIALIZED: throw new IllegalArgumentException(algorithmName + " needs call init function before getUpdateOutputSize"); - case DecFinal: - case EncFinal: + case State.DEC_FINAL: + case State.ENC_FINAL: return 0; - case EncAad: - case EncData: - case EncInit: - return len + CRYPTO_ABYTES; + case State.ENC_AAD: + case State.ENC_DATA: + case State.ENC_INIT: + return len + m_bufPos + MAC_SIZE; } - return Math.max(0, len - CRYPTO_ABYTES); + return Math.max(0, len + m_bufPos - MAC_SIZE); } - @Override - public void reset() + protected void finishAAD(State nextState, boolean isDoFinal) { - reset(true); + finishAAD2(nextState); } - private void reset(boolean clearMac) + @Override + protected void processFinalAAD() { - if (clearMac) + if (adOff == -1) { - tag = null; + ad = ((StreamAADOperator)aadOperator).getBytes(); + adOff = 0; + adlen = aadOperator.getLen(); + aadOperator.reset(); + } + switch (m_state.ord) + { + case State.ENC_INIT: + case State.DEC_INIT: + processAADBytes(tag_buffer); + break; } - aadData.reset(); - Arrays.fill(tag_buffer, (byte)0); - inputOff = 0; - nb_its = 0; - adOff = -1; - } - - public int getKeyBytesSize() - { - return CRYPTO_KEYBYTES; - } - - public int getIVBytesSize() - { - return CRYPTO_NPUBBYTES; } - public int getBlockSize() + protected void reset(boolean clearMac) { - return CRYPTO_ABYTES; + super.reset(clearMac); + Arrays.fill(tag_buffer, (byte)0); + Arrays.fill(previous_outputMessage, (byte)0); + nb_its = 0; + adOff = -1; } - private void checkAad() + protected void checkAAD() { - switch (m_state) + switch (m_state.ord) { - case DecData: + case State.DEC_DATA: throw new IllegalArgumentException(algorithmName + " cannot process AAD when the length of the plaintext to be processed exceeds the a block size"); - case EncData: + case State.ENC_DATA: throw new IllegalArgumentException(algorithmName + " cannot process AAD when the length of the ciphertext to be processed exceeds the a block size"); - case EncFinal: + case State.ENC_FINAL: throw new IllegalArgumentException(algorithmName + " cannot be reused for encryption"); default: break; } } - private void processAADBytes(byte[] output) + protected boolean checkData(boolean isDofinal) { - checkAad(); - - if (adOff == -1) + switch (m_state.ord) { - adlen = aadData.size(); - ad = aadData.toByteArray(); - adOff = 0; + case State.DEC_INIT: + case State.DEC_AAD: + case State.DEC_DATA: + return false; + case State.ENC_INIT: + case State.ENC_AAD: + case State.ENC_DATA: + return true; + case State.ENC_FINAL: + throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); } + } + + private void processAADBytes(byte[] output) + { int len = 0; - switch (m_state) + switch (m_state.ord) { - case DecInit: - System.arraycopy(expanded_key, 0, current_mask, 0, BLOCK_SIZE); - System.arraycopy(npub, 0, output, 0, CRYPTO_NPUBBYTES); - len += CRYPTO_NPUBBYTES; + case State.DEC_INIT: + System.arraycopy(expanded_key, 0, current_mask, 0, BlockSize); + System.arraycopy(npub, 0, output, 0, IV_SIZE); + len += IV_SIZE; m_state = State.DecAad; break; - case EncInit: - System.arraycopy(expanded_key, 0, current_mask, 0, BLOCK_SIZE); - System.arraycopy(npub, 0, output, 0, CRYPTO_NPUBBYTES); - len += CRYPTO_NPUBBYTES; + case State.ENC_INIT: + System.arraycopy(expanded_key, 0, current_mask, 0, BlockSize); + System.arraycopy(npub, 0, output, 0, IV_SIZE); + len += IV_SIZE; m_state = State.EncAad; break; - case DecAad: - case EncAad: + case State.DEC_AAD: + case State.ENC_AAD: // If adlen is divisible by BLOCK_SIZE, add an additional padding block if (adOff == adlen) { - Arrays.fill(output, 0, BLOCK_SIZE, (byte)0); + Arrays.fill(output, 0, BlockSize, (byte)0); output[0] = 0x01; return; } break; - case DecData: - throw new IllegalArgumentException(algorithmName + " cannot process AAD when the length of the plaintext to be processed exceeds the a block size"); - case EncData: - throw new IllegalArgumentException(algorithmName + " cannot process AAD when the length of the ciphertext to be processed exceeds the a block size"); - case EncFinal: - throw new IllegalArgumentException(algorithmName + " cannot be reused for encryption"); } - int r_outlen = BLOCK_SIZE - len; + int r_outlen = BlockSize - len; int r_adlen = adlen - adOff; // Fill with associated data if available if (r_outlen <= r_adlen) @@ -629,77 +551,94 @@ private void processAADBytes(byte[] output) } Arrays.fill(output, len + r_adlen, len + r_outlen, (byte)0); output[len + r_adlen] = 0x01; - switch (m_state) + switch (m_state.ord) { - case DecAad: + case State.DEC_AAD: m_state = State.DecData; break; - case EncAad: + case State.ENC_AAD: m_state = State.EncData; break; } } } - private int processBytes(byte[] m, byte[] output, int outOff, int nb_it, int nblocks_m, int nblocks_c, int mlen, - int nblocks_ad) + private void processBytes(byte[] m, byte[] output, int outOff, int nb_it, int nblocks_m, int nblocks_c, int mlen, + int nblocks_ad) { int rv = 0; - for (int i = nb_its; i < nb_it; ++i) + byte[] outputMessage = new byte[BlockSize]; + int i; + for (i = nb_its; i < nb_it; ++i) { + int r_size = (i == nblocks_m - 1) ? mlen - i * BlockSize : BlockSize; // Compute mask for the next message - lfsr_step(next_mask, current_mask); + lfsr_step(); if (i < nblocks_m) { // Compute ciphertext block - System.arraycopy(npub, 0, buffer, 0, CRYPTO_NPUBBYTES); - Arrays.fill(buffer, CRYPTO_NPUBBYTES, BLOCK_SIZE, (byte)0); - xor_block(buffer, current_mask, 0, BLOCK_SIZE); - xor_block(buffer, next_mask, 0, BLOCK_SIZE); - permutation(buffer); - xor_block(buffer, current_mask, 0, BLOCK_SIZE); - xor_block(buffer, next_mask, 0, BLOCK_SIZE); - int r_size = (i == nblocks_m - 1) ? mlen - i * BLOCK_SIZE : BLOCK_SIZE; - xor_block(buffer, m, 0, r_size); - System.arraycopy(buffer, 0, output, outOff, r_size); + computeCipherBlock(m, rv, r_size, output, outOff); if (forEncryption) { System.arraycopy(buffer, 0, outputMessage, 0, r_size); } else { - System.arraycopy(m, 0, outputMessage, 0, r_size); + System.arraycopy(m, rv, outputMessage, 0, r_size); } + + outOff += r_size; rv += r_size; } if (i > 0 && i <= nblocks_c) { - // Compute tag for ciphertext block - get_c_block(buffer, previous_outputMessage, 0, mlen, i - 1); - xor_block(buffer, previous_mask, 0, BLOCK_SIZE); - xor_block(buffer, next_mask, 0, BLOCK_SIZE); - permutation(buffer); - xor_block(buffer, previous_mask, 0, BLOCK_SIZE); - xor_block(buffer, next_mask, 0, BLOCK_SIZE); - xor_block(tag_buffer, buffer, 0, BLOCK_SIZE); + //get_c_block: Compute tag for ciphertext block + int block_offset = (i - 1) * BlockSize; + // If clen is divisible by BLOCK_SIZE, add an additional padding block + if (block_offset == mlen) + { + Arrays.fill(buffer, 1, BlockSize, (byte)0); + buffer[0] = 0x01; + } + else + { + int r_clen = mlen - block_offset; + // Fill with ciphertext if available + if (BlockSize <= r_clen) + { // enough ciphertext + System.arraycopy(previous_outputMessage, 0, buffer, 0, BlockSize); + } + else + { // not enough ciphertext, need to pad + if (r_clen > 0) // c might be nullptr + { + System.arraycopy(previous_outputMessage, 0, buffer, 0, r_clen); + Arrays.fill(buffer, r_clen, BlockSize, (byte)0); + buffer[r_clen] = 0x01; + } + } + } + + absorbCiphertext(); } // If there is any AD left, compute tag for AD block if (i + 1 < nblocks_ad) { - processAADBytes(buffer); - xor_block(buffer, next_mask, 0, BLOCK_SIZE); - permutation(buffer); - xor_block(buffer, next_mask, 0, BLOCK_SIZE); - xor_block(tag_buffer, buffer, 0, BLOCK_SIZE); + absorbAAD(); } // Cyclically shift the mask buffers // Value of next_mask will be computed in the next iteration - byte[] temp = previous_mask; - previous_mask = current_mask; - current_mask = next_mask; - next_mask = temp; - System.arraycopy(outputMessage, 0, previous_outputMessage, 0, BLOCK_SIZE); + swapMasks(); + System.arraycopy(outputMessage, 0, previous_outputMessage, 0, BlockSize); + } + nb_its = i; + } + + public static void xorTo(int len, byte[] x, byte[] y, byte[] z) + { + for (int i = 0; i < len; ++i) + { + z[i] ^= x[i] ^ y[i]; } - return rv; } } diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/GiftCofbEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/GiftCofbEngine.java new file mode 100644 index 0000000000..a5ac0ae3db --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/GiftCofbEngine.java @@ -0,0 +1,293 @@ +package org.bouncycastle.crypto.engines; + +import org.bouncycastle.util.Bytes; + +/** + * GIFT-COFB v1.1, based on the current round 3 submission, https://www.isical.ac.in/~lightweight/COFB/ + * Reference C implementation: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-submissions/elephant.zip + * Specification: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/gift-cofb-spec-final.pdf + */ + +public class GiftCofbEngine + extends AEADBaseEngine +{ + private byte[] npub; + private byte[] k; + private byte[] Y; + private byte[] input; + private byte[] offset; + /*Round constants*/ + private static final byte[] GIFT_RC = { + (byte)0x01, (byte)0x03, (byte)0x07, (byte)0x0F, (byte)0x1F, (byte)0x3E, (byte)0x3D, (byte)0x3B, (byte)0x37, (byte)0x2F, + (byte)0x1E, (byte)0x3C, (byte)0x39, (byte)0x33, (byte)0x27, (byte)0x0E, (byte)0x1D, (byte)0x3A, (byte)0x35, (byte)0x2B, + (byte)0x16, (byte)0x2C, (byte)0x18, (byte)0x30, (byte)0x21, (byte)0x02, (byte)0x05, (byte)0x0B, (byte)0x17, (byte)0x2E, + (byte)0x1C, (byte)0x38, (byte)0x31, (byte)0x23, (byte)0x06, (byte)0x0D, (byte)0x1B, (byte)0x36, (byte)0x2D, (byte)0x1A + }; + + public GiftCofbEngine() + { + AADBufferSize = BlockSize = MAC_SIZE = IV_SIZE = KEY_SIZE = 16; + algorithmName = "GIFT-COFB AEAD"; + setInnerMembers(ProcessingBufferType.Buffered, AADOperatorType.Default, DataOperatorType.Counter); + } + + private int rowperm(int S, int B0_pos, int B1_pos, int B2_pos, int B3_pos) + { + int T = 0; + int b; + for (b = 0; b < 8; b++) + { + T |= ((S >>> (4 * b)) & 0x1) << (b + 8 * B0_pos); + T |= ((S >>> (4 * b + 1)) & 0x1) << (b + 8 * B1_pos); + T |= ((S >>> (4 * b + 2)) & 0x1) << (b + 8 * B2_pos); + T |= ((S >>> (4 * b + 3)) & 0x1) << (b + 8 * B3_pos); + } + return T; + } + + private void giftb128(byte[] P, byte[] K, byte[] C) + { + int round, T; + int[] S = new int[4]; + short[] W = new short[8]; + short T6, T7; + S[0] = ((P[0] & 0xFF) << 24) | ((P[1] & 0xFF) << 16) | ((P[2] & 0xFF) << 8) | (P[3] & 0xFF); + S[1] = ((P[4] & 0xFF) << 24) | ((P[5] & 0xFF) << 16) | ((P[6] & 0xFF) << 8) | (P[7] & 0xFF); + S[2] = ((P[8] & 0xFF) << 24) | ((P[9] & 0xFF) << 16) | ((P[10] & 0xFF) << 8) | (P[11] & 0xFF); + S[3] = ((P[12] & 0xFF) << 24) | ((P[13] & 0xFF) << 16) | ((P[14] & 0xFF) << 8) | (P[15] & 0xFF); + W[0] = (short)(((K[0] & 0xFF) << 8) | (K[1] & 0xFF)); + W[1] = (short)(((K[2] & 0xFF) << 8) | (K[3] & 0xFF)); + W[2] = (short)(((K[4] & 0xFF) << 8) | (K[5] & 0xFF)); + W[3] = (short)(((K[6] & 0xFF) << 8) | (K[7] & 0xFF)); + W[4] = (short)(((K[8] & 0xFF) << 8) | (K[9] & 0xFF)); + W[5] = (short)(((K[10] & 0xFF) << 8) | (K[11] & 0xFF)); + W[6] = (short)(((K[12] & 0xFF) << 8) | (K[13] & 0xFF)); + W[7] = (short)(((K[14] & 0xFF) << 8) | (K[15] & 0xFF)); + for (round = 0; round < 40; round++) + { + /*===SubCells===*/ + S[1] ^= S[0] & S[2]; + S[0] ^= S[1] & S[3]; + S[2] ^= S[0] | S[1]; + S[3] ^= S[2]; + S[1] ^= S[3]; + S[3] ^= 0xffffffff; + S[2] ^= S[0] & S[1]; + T = S[0]; + S[0] = S[3]; + S[3] = T; + /*===PermBits===*/ + S[0] = rowperm(S[0], 0, 3, 2, 1); + S[1] = rowperm(S[1], 1, 0, 3, 2); + S[2] = rowperm(S[2], 2, 1, 0, 3); + S[3] = rowperm(S[3], 3, 2, 1, 0); + /*===AddRoundKey===*/ + S[2] ^= ((W[2] & 0xFFFF) << 16) | (W[3] & 0xFFFF); + S[1] ^= ((W[6] & 0xFFFF) << 16) | (W[7] & 0xFFFF); + /*Add round constant*/ + S[3] ^= 0x80000000 ^ (GIFT_RC[round] & 0xFF); + /*===Key state update===*/ + T6 = (short)(((W[6] & 0xFFFF) >>> 2) | ((W[6] & 0xFFFF) << 14)); + T7 = (short)(((W[7] & 0xFFFF) >>> 12) | ((W[7] & 0xFFFF) << 4)); + W[7] = W[5]; + W[6] = W[4]; + W[5] = W[3]; + W[4] = W[2]; + W[3] = W[1]; + W[2] = W[0]; + W[1] = T7; + W[0] = T6; + } + C[0] = (byte)(S[0] >>> 24); + C[1] = (byte)(S[0] >>> 16); + C[2] = (byte)(S[0] >>> 8); + C[3] = (byte)(S[0]); + C[4] = (byte)(S[1] >>> 24); + C[5] = (byte)(S[1] >>> 16); + C[6] = (byte)(S[1] >>> 8); + C[7] = (byte)(S[1]); + C[8] = (byte)(S[2] >>> 24); + C[9] = (byte)(S[2] >>> 16); + C[10] = (byte)(S[2] >>> 8); + C[11] = (byte)(S[2]); + C[12] = (byte)(S[3] >>> 24); + C[13] = (byte)(S[3] >>> 16); + C[14] = (byte)(S[3] >>> 8); + C[15] = (byte)(S[3]); + } + + private void double_half_block(byte[] s) + { + int mask = ((s[0] & 0xFF) >>> 7) * 27; + /*x^{64} + x^4 + x^3 + x + 1*/ + for (int i = 0; i < 7; i++) + { + s[i] = (byte)(((s[i] & 0xFF) << 1) | ((s[i + 1] & 0xFF) >>> 7)); + } + s[7] = (byte)(((s[7] & 0xFF) << 1) ^ mask); + } + + private void triple_half_block(byte[] s) + { + byte[] tmp = new byte[8]; + /*x^{64} + x^4 + x^3 + x + 1*/ + for (int i = 0; i < 7; i++) + { + tmp[i] = (byte)(((s[i] & 0xFF) << 1) | ((s[i + 1] & 0xFF) >>> 7)); + } + tmp[7] = (byte)(((s[7] & 0xFF) << 1) ^ (((s[0] & 0xFF) >>> 7) * 27)); + Bytes.xorTo(8, tmp, s); + } + + private void pho1(byte[] d, byte[] Y, byte[] M, int mOff, int no_of_bytes) + { + byte[] tmpM = new byte[16]; + byte[] tmp = new byte[16]; + if (no_of_bytes == 0) + { + tmpM[0] = (byte)0x80; + } + else if (no_of_bytes < 16) + { + System.arraycopy(M, mOff, tmpM, 0, no_of_bytes); + tmpM[no_of_bytes] = (byte)0x80; + } + else + { + System.arraycopy(M, mOff, tmpM, 0, no_of_bytes); + } + //G(Y, Y); + /*Y[1],Y[2] -> Y[2],Y[1]<<<1*/ + System.arraycopy(Y, 8, tmp, 0, 8); + for (int i = 0; i < 7; i++) + { + tmp[i + 8] = (byte)((Y[i] & 0xFF) << 1 | (Y[i + 1] & 0xFF) >>> 7); + } + tmp[15] = (byte)((Y[7] & 0xFF) << 1 | (Y[0] & 0xFF) >>> 7); + System.arraycopy(tmp, 0, Y, 0, 16); + Bytes.xor(16, Y, tmpM, d); + } + + @Override + protected void processBufferAAD(byte[] in, int inOff) + { + pho1(input, Y, in, inOff, 16); + /* offset = 2*offset */ + double_half_block(offset); + Bytes.xorTo(8, offset, input); + /* Y[i] = E(X[i]) */ + giftb128(input, k, Y); + } + + @Override + protected void processFinalAAD() + { + int len = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + /* last byte[] */ + /* full byte[]: offset = 3*offset */ + /* partial byte[]: offset = 3^2*offset */ + triple_half_block(offset); + if (((m_aadPos & 15) != 0) || m_state == State.DecInit || m_state == State.EncInit) + { + triple_half_block(offset); + } + if (len == 0) + { + /* empty M: offset = 3^2*offset */ + triple_half_block(offset); + triple_half_block(offset); + } + /* X[i] = (pad(A[i]) + G(Y[i-1])) + offset */ + pho1(input, Y, m_aad, 0, m_aadPos); + Bytes.xorTo(8, offset, input); + /* Y[a] = E(X[a]) */ + giftb128(input, k, Y); + } + + @Override + protected void finishAAD(State nextState, boolean isDoFinal) + { + finishAAD3(nextState, isDoFinal); + } + + @Override + protected void init(byte[] key, byte[] iv) + { + npub = iv; + k = key; + Y = new byte[BlockSize]; + input = new byte[16]; + offset = new byte[8]; + } + + @Override + protected void processFinalBlock(byte[] output, int outOff) + { + int len = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + if (len != 0) + { + /* full block: offset = 3*offset */ + /* empty data / partial block: offset = 3^2*offset */ + triple_half_block(offset); + if ((len & 15) != 0) + { + triple_half_block(offset); + } + /* last block */ + /* C[m] = Y[m+a-1] + M[m]*/ + /* X[a+m] = M[m] + G(Y[m+a-1]) + offset */ + Bytes.xor(m_bufPos, Y, m_buf, 0, output, outOff); + if (forEncryption) + { + pho1(input, Y, m_buf, 0, m_bufPos); + } + else + { + pho1(input, Y, output, outOff, m_bufPos); + } + Bytes.xorTo(8, offset, input); + /* T = E(X[m+a]) */ + giftb128(input, k, Y); + } + System.arraycopy(Y, 0, mac, 0, BlockSize); + } + + @Override + protected void processBufferEncrypt(byte[] inputM, int inOff, byte[] output, int outOff) + { + /* Process M */ + /* full byte[]s */ + double_half_block(offset); + /* C[i] = Y[i+a-1] + M[i]*/ + /* X[i] = M[i] + G(Y[i+a-1]) + offset */ + Bytes.xor(BlockSize, Y, inputM, inOff, output, outOff); + pho1(input, Y, inputM, inOff, BlockSize); + Bytes.xorTo(8, offset, input); + /* Y[i] = E(X[i+a]) */ + giftb128(input, k, Y); + } + + @Override + protected void processBufferDecrypt(byte[] inputM, int inOff, byte[] output, int outOff) + { + /* Process M */ + /* full byte[]s */ + double_half_block(offset); + /* C[i] = Y[i+a-1] + M[i]*/ + /* X[i] = M[i] + G(Y[i+a-1]) + offset */ + Bytes.xor(BlockSize, Y, inputM, inOff, output, outOff); + pho1(input, Y, output, outOff, BlockSize); + Bytes.xorTo(8, offset, input); + /* Y[i] = E(X[i+a]) */ + giftb128(input, k, Y); + } + + protected void reset(boolean clearMac) + { + super.reset(clearMac); + /*nonce is 128-bit*/ + System.arraycopy(npub, 0, input, 0, IV_SIZE); + giftb128(input, k, Y); + System.arraycopy(Y, 0, offset, 0, 8); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/Grain128AEADEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/Grain128AEADEngine.java index 0d8672c198..d81fd59045 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/Grain128AEADEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/Grain128AEADEngine.java @@ -1,23 +1,13 @@ package org.bouncycastle.crypto.engines; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; /** * Grain-128 AEAD, based on the current round 3 submission, https://grain-128aead.github.io/ */ public class Grain128AEADEngine - implements AEADCipher + extends AEADBaseEngine { /** * Constants @@ -30,126 +20,51 @@ public class Grain128AEADEngine */ private byte[] workingKey; private byte[] workingIV; - private int[] lfsr; - private int[] nfsr; - private int[] authAcc; - private int[] authSr; - - private boolean initialised = false; - private boolean aadFinished = false; - private ErasableOutputStream aadData = new ErasableOutputStream(); - - private byte[] mac; + private final int[] lfsr; + private final int[] nfsr; + private final int[] authAcc; + private final int[] authSr; - public String getAlgorithmName() + public Grain128AEADEngine() { - return "Grain-128AEAD"; + algorithmName = "Grain-128 AEAD"; + KEY_SIZE = 16; + IV_SIZE = 12; + MAC_SIZE = 8; + lfsr = new int[STATE_SIZE]; + nfsr = new int[STATE_SIZE]; + authAcc = new int[2]; + authSr = new int[2]; + setInnerMembers(ProcessingBufferType.Immediate, AADOperatorType.Stream, DataOperatorType.StreamCipher); } /** * Initialize a Grain-128AEAD cipher. - * - * @param forEncryption Whether or not we are for encryption. - * @param params The parameters required to set up the cipher. - * @throws IllegalArgumentException If the params argument is inappropriate. */ - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] key, byte[] iv) throws IllegalArgumentException { - /* - * Grain encryption and decryption is completely symmetrical, so the - * 'forEncryption' is irrelevant. - */ - if (!(params instanceof ParametersWithIV)) - { - throw new IllegalArgumentException( - "Grain-128AEAD init parameters must include an IV"); - } - - ParametersWithIV ivParams = (ParametersWithIV)params; - - byte[] iv = ivParams.getIV(); - - if (iv == null || iv.length != 12) - { - throw new IllegalArgumentException( - "Grain-128AEAD requires exactly 12 bytes of IV"); - } - - if (!(ivParams.getParameters() instanceof KeyParameter)) - { - throw new IllegalArgumentException( - "Grain-128AEAD init parameters must include a key"); - } - - KeyParameter key = (KeyParameter)ivParams.getParameters(); - byte[] keyBytes = key.getKey(); - if (keyBytes.length != 16) - { - throw new IllegalArgumentException( - "Grain-128AEAD key must be 128 bits long"); - } - - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - /* * Initialize variables. */ workingIV = new byte[16]; - workingKey = new byte[16]; - lfsr = new int[STATE_SIZE]; - nfsr = new int[STATE_SIZE]; - authAcc = new int[2]; - authSr = new int[2]; - - System.arraycopy(iv, 0, workingIV, 0, iv.length); - System.arraycopy(keyBytes, 0, workingKey, 0, keyBytes.length); - - reset(); + workingKey = key; + System.arraycopy(iv, 0, workingIV, 0, IV_SIZE); + workingIV[12] = (byte)0xFF; + workingIV[13] = (byte)0xFF; + workingIV[14] = (byte)0xFF; + workingIV[15] = (byte)0x7F; } - /** - * 320 clocks initialization phase. - */ - private void initGrain() + private void initGrain(int[] auth) { - for (int i = 0; i < 320; ++i) - { - int output = getOutput(); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0] ^ output) & 1); - lfsr = shift(lfsr, (getOutputLFSR() ^ output) & 1); - } - for (int quotient = 0; quotient < 8; ++quotient) - { - for (int remainder = 0; remainder < 8; ++remainder) - { - int output = getOutput(); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0] ^ output ^ ((workingKey[quotient]) >> remainder)) & 1); - lfsr = shift(lfsr, (getOutputLFSR() ^ output ^ ((workingKey[quotient + 8]) >> remainder)) & 1); - } - } - for (int quotient = 0; quotient < 2; ++quotient) - { - for (int remainder = 0; remainder < 32; ++remainder) - { - int output = getOutput(); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); - lfsr = shift(lfsr, (getOutputLFSR()) & 1); - authAcc[quotient] |= output << remainder; - } - } for (int quotient = 0; quotient < 2; ++quotient) { for (int remainder = 0; remainder < 32; ++remainder) { - int output = getOutput(); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); - lfsr = shift(lfsr, (getOutputLFSR()) & 1); - authSr[quotient] |= output << remainder; + auth[quotient] |= getByteKeyStream() << remainder; } } - initialised = true; } /** @@ -240,280 +155,174 @@ private int getOutput() } /** - * Shift array 1 bit and add val to index.length - 1. + * Shift array 1 bit and add val to index - 1. * * @param array The array to shift. * @param val The value to shift in. - * @return The shifted array with val added to index.length - 1. */ - private int[] shift(int[] array, int val) + private void shift(int[] array, int val) { array[0] = (array[0] >>> 1) | (array[1] << 31); array[1] = (array[1] >>> 1) | (array[2] << 31); array[2] = (array[2] >>> 1) | (array[3] << 31); array[3] = (array[3] >>> 1) | (val << 31); - return array; } - /** - * Set keys, reset cipher. - * - * @param keyBytes The key. - * @param ivBytes The IV. - */ - private void setKey(byte[] keyBytes, byte[] ivBytes) + private void shift() { - ivBytes[12] = (byte)0xFF; - ivBytes[13] = (byte)0xFF; - ivBytes[14] = (byte)0xFF; - ivBytes[15] = (byte)0x7F; - workingKey = keyBytes; - workingIV = ivBytes; - - /* - * Load NFSR and LFSR - */ - Pack.littleEndianToInt(workingKey, 0, nfsr); - Pack.littleEndianToInt(workingIV, 0, lfsr); + shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); + shift(lfsr, (getOutputLFSR()) & 1); } - public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) - throws DataLengthException + protected void reset(boolean clearMac) { - if (!initialised) - { - throw new IllegalStateException(getAlgorithmName() + " not initialised"); - } - - if (!aadFinished) - { - doProcessAADBytes(aadData.getBuf(), 0, aadData.size()); - aadFinished = true; - } - - if ((inOff + len) > input.length) + super.reset(clearMac); + Pack.littleEndianToInt(workingKey, 0, nfsr); + Pack.littleEndianToInt(workingIV, 0, lfsr); + Arrays.clear(authAcc); + Arrays.clear(authSr); + int output; + // 320 clocks initialization phase. + for (int i = 0; i < 320; ++i) { - throw new DataLengthException("input buffer too short"); + output = getOutput(); + shift(nfsr, (getOutputNFSR() ^ lfsr[0] ^ output) & 1); + shift(lfsr, (getOutputLFSR() ^ output) & 1); } - - if ((outOff + len) > output.length) + for (int quotient = 0; quotient < 8; ++quotient) { - throw new OutputLengthException("output buffer too short"); + for (int remainder = 0; remainder < 8; ++remainder) + { + output = getOutput(); + shift(nfsr, (getOutputNFSR() ^ lfsr[0] ^ output ^ ((workingKey[quotient]) >> remainder)) & 1); + shift(lfsr, (getOutputLFSR() ^ output ^ ((workingKey[quotient + 8]) >> remainder)) & 1); + } } - getKeyStream(input, inOff, len, output, outOff); - return len; + initGrain(authAcc); + initGrain(authSr); } - public void reset() + private void updateInternalState(int mask) { - reset(true); + mask = -mask; + authAcc[0] ^= authSr[0] & mask; + authAcc[1] ^= authSr[1] & mask; + mask = getByteKeyStream(); + authSr[0] = (authSr[0] >>> 1) | (authSr[1] << 31); + authSr[1] = (authSr[1] >>> 1) | (mask << 31); } - private void reset(boolean clearMac) + public int getUpdateOutputSize(int len) { - if (clearMac) - { - this.mac = null; - } - this.aadData.reset(); - this.aadFinished = false; - - setKey(workingKey, workingIV); - initGrain(); + return getTotalBytesForUpdate(len); } - private byte[] getKeyStream(byte[] input, int inOff, int len, byte[] ciphertext, int outOff) + @Override + protected void finishAAD(State nextState, boolean isDoFinal) { - for (int i = 0; i < len; ++i) - { - byte cc = 0, input_i = input[inOff + i]; - for (int j = 0; j < 8; ++j) - { - int output = getOutput(); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); - lfsr = shift(lfsr, (getOutputLFSR()) & 1); - - int input_i_j = (input_i >> j) & 1; - cc |= (input_i_j ^ output) << j; - -// if (input_i_j != 0) -// { -// accumulate(); -// } - int mask = -input_i_j; - authAcc[0] ^= authSr[0] & mask; - authAcc[1] ^= authSr[1] & mask; - - authShift(getOutput()); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); - lfsr = shift(lfsr, (getOutputLFSR()) & 1); - } - ciphertext[outOff + i] = cc; - } - - return ciphertext; + finishAAD1(nextState); } - public void processAADByte(byte in) + @Override + protected void processFinalBlock(byte[] output, int outOff) { - if (aadFinished) - { - throw new IllegalStateException("associated data must be added before plaintext/ciphertext"); - } - aadData.write(in); + authAcc[0] ^= authSr[0]; + authAcc[1] ^= authSr[1]; + Pack.intToLittleEndian(authAcc, mac, 0); } - public void processAADBytes(byte[] input, int inOff, int len) + @Override + protected void processBufferAAD(byte[] input, int inOff) { - if (aadFinished) - { - throw new IllegalStateException("associated data must be added before plaintext/ciphertext"); - } - aadData.write(input, inOff, len); } - private void doProcessAADBytes(byte[] input, int inOff, int len) + @Override + protected void processFinalAAD() { - byte[] ader; - int aderlen; - //encodeDer + // Encode(ad length) denotes the message length encoded in the DER format. + + int len = aadOperator.getLen(); + byte[] input = ((StreamAADOperator)aadOperator).getBytes(); + + // Need up to 5 bytes for the DER length as an 'int' + byte[] ader = new byte[5]; + + int pos; if (len < 128) { - ader = new byte[1 + len]; - ader[0] = (byte)len; - aderlen = 0; + pos = ader.length - 1; + ader[pos] = (byte)len; } else { - // aderlen is the highest bit position divided by 8 - aderlen = len_length(len); - ader = new byte[1 + aderlen + len]; - ader[0] = (byte)(0x80 | aderlen); - int tmp = len; - for (int i = 0; i < aderlen; ++i) - { - ader[1 + i] = (byte)tmp; - tmp >>>= 8; - } - } - for (int i = 0; i < len; ++i) - { - ader[1 + aderlen + i] = input[inOff + i]; - } + pos = ader.length; - for (int i = 0; i < ader.length; ++i) - { - byte ader_i = ader[i]; - for (int j = 0; j < 8; ++j) + int dl = len; + do { - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); - lfsr = shift(lfsr, (getOutputLFSR()) & 1); - - int ader_i_j = (ader_i >> j) & 1; -// if (ader_i_j != 0) -// { -// accumulate(); -// } - int mask = -ader_i_j; - authAcc[0] ^= authSr[0] & mask; - authAcc[1] ^= authSr[1] & mask; - - authShift(getOutput()); - nfsr = shift(nfsr, (getOutputNFSR() ^ lfsr[0]) & 1); - lfsr = shift(lfsr, (getOutputLFSR()) & 1); + ader[--pos] = (byte)dl; + dl >>>= 8; } - } - } + while (dl != 0); - private void accumulate() - { - authAcc[0] ^= authSr[0]; - authAcc[1] ^= authSr[1]; - } - - private void authShift(int val) - { - authSr[0] = (authSr[0] >>> 1) | (authSr[1] << 31); - authSr[1] = (authSr[1] >>> 1) | (val << 31); - } + int count = ader.length - pos; + ader[--pos] = (byte)(0x80 | count); + } - public int processByte(byte input, byte[] output, int outOff) - throws DataLengthException - { - return processBytes(new byte[]{input}, 0, 1, output, outOff); + absorbAadData(ader, pos, ader.length - pos); + absorbAadData(input, 0, len); } - public int doFinal(byte[] out, int outOff) - throws IllegalStateException, InvalidCipherTextException + private void absorbAadData(byte[] buf, int off, int len) { - if (!aadFinished) + for (int i = 0; i < len; ++i) { - doProcessAADBytes(aadData.getBuf(), 0, aadData.size()); - aadFinished = true; + byte b = buf[off + i]; + for (int j = 0; j < 8; ++j) + { + shift(); + updateInternalState((b >> j) & 1); + } } - - accumulate(); - - this.mac = Pack.intToLittleEndian(authAcc); - - System.arraycopy(mac, 0, out, outOff, mac.length); - - reset(false); - - return mac.length; } - public byte[] getMac() - { - return mac; - } - - public int getUpdateOutputSize(int len) + private int getByteKeyStream() { - return len; + int rlt = getOutput(); + shift(); + return rlt; } - public int getOutputSize(int len) + @Override + protected void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) { - //the last 8 bytes are from AD - return len + 8; - } - - private static int len_length(int v) - { - if ((v & 0xff) == v) - { - return 1; - } - if ((v & 0xffff) == v) - { - return 2; - } - if ((v & 0xffffff) == v) + int len = dataOperator.getLen(); + for (int i = 0; i < len; ++i) { - return 3; + byte cc = 0, input_i = input[inOff + i]; + for (int j = 0; j < 8; ++j) + { + int input_i_j = (input_i >> j) & 1; + cc |= (input_i_j ^ getByteKeyStream()) << j; + updateInternalState(input_i_j); + } + output[outOff + i] = cc; } - - return 4; } - private static final class ErasableOutputStream - extends ByteArrayOutputStream + @Override + protected void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) { - public ErasableOutputStream() - { - } - - public byte[] getBuf() + int len = dataOperator.getLen(); + for (int i = 0; i < len; ++i) { - return buf; + byte cc = 0, input_i = input[inOff + i]; + for (int j = 0; j < 8; ++j) + { + cc |= (((input_i >> j) & 1) ^ getByteKeyStream()) << j; + updateInternalState((cc >> j) & 1); + } + output[outOff + i] = cc; } - -// public void erase() -// { -// Arrays.fill(this.buf, (byte)0); -// // this for JVM compatibility -// this.reset(); -// } } } diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/ISAPEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/ISAPEngine.java index 7d83c9cfa8..5a404540d9 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/ISAPEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/ISAPEngine.java @@ -1,16 +1,7 @@ package org.bouncycastle.crypto.engines; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Bytes; import org.bouncycastle.util.Pack; /** @@ -21,7 +12,7 @@ *

    */ public class ISAPEngine - implements AEADCipher + extends AEADBaseEngine { public enum IsapType @@ -34,6 +25,7 @@ public enum IsapType public ISAPEngine(IsapType isapType) { + KEY_SIZE = IV_SIZE = MAC_SIZE = 16; switch (isapType) { case ISAP_A_128A: @@ -52,39 +44,37 @@ public ISAPEngine(IsapType isapType) ISAPAEAD = new ISAPAEAD_K_128(); algorithmName = "ISAP-K-128 AEAD"; break; + default: + throw new IllegalArgumentException("Incorrect ISAP parameter"); } + AADBufferSize = BlockSize; + setInnerMembers(ProcessingBufferType.Immediate, AADOperatorType.Default, DataOperatorType.Counter); } - private String algorithmName; - private boolean forEncryption; - private boolean initialised; - final int CRYPTO_KEYBYTES = 16; - final int CRYPTO_NPUBBYTES = 16; - final int ISAP_STATE_SZ = 40; + private static final int ISAP_STATE_SZ = 40; private byte[] k; - private byte[] c; - private byte[] ad; private byte[] npub; - private byte[] mac; - private ByteArrayOutputStream aadData = new ByteArrayOutputStream(); - private final ByteArrayOutputStream message = new ByteArrayOutputStream(); - private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); private int ISAP_rH; - private int ISAP_rH_SZ; - private ISAP_AEAD ISAPAEAD; + private final ISAP_AEAD ISAPAEAD; private interface ISAP_AEAD { - void isap_enc(byte[] m, int mOff, int mlen, byte[] c, int cOff, int clen); - void init(); - void isap_mac(byte[] ad, int adlen, byte[] c, int clen, byte[] tag, int tagOff); - void reset(); + + void absorbMacBlock(byte[] input, int inOff); + + void absorbFinalAADBlock(); + + void processEncBlock(byte[] input, int inOff, byte[] output, int outOff); + + void processEncFinalBlock(byte[] output, int outOff); + + void processMACFinal(byte[] input, int inOff, int len, byte[] tag); } - public abstract class ISAPAEAD_A + private abstract class ISAPAEAD_A implements ISAP_AEAD { protected long[] k64; @@ -92,176 +82,111 @@ public abstract class ISAPAEAD_A protected long ISAP_IV1_64; protected long ISAP_IV2_64; protected long ISAP_IV3_64; - protected long x0, x1, x2, x3, x4, t0, t1, t2, t3, t4; + AsconPermutationFriend.AsconPermutation p; + AsconPermutationFriend.AsconPermutation mac; public ISAPAEAD_A() { ISAP_rH = 64; - ISAP_rH_SZ = (ISAP_rH + 7) >> 3; + BlockSize = (ISAP_rH + 7) >> 3; + p = new AsconPermutationFriend.AsconPermutation(); + mac = new AsconPermutationFriend.AsconPermutation(); } public void init() { npub64 = new long[getLongSize(npub.length)]; - Pack.littleEndianToLong(npub, 0, npub64, 0, npub64.length); - npub64[0] = U64BIG(npub64[0]); - npub64[1] = U64BIG(npub64[1]); k64 = new long[getLongSize(k.length)]; - Pack.littleEndianToLong(k, 0, k64, 0, k64.length); - k64[0] = U64BIG(k64[0]); - k64[1] = U64BIG(k64[1]); - reset(); + Pack.bigEndianToLong(npub, 0, npub64); + Pack.bigEndianToLong(k, 0, k64); } - protected abstract void PX1(); + protected abstract void PX1(AsconPermutationFriend.AsconPermutation p); - protected abstract void PX2(); + protected abstract void PX2(AsconPermutationFriend.AsconPermutation p); - protected void ABSORB_MAC(byte[] src, int len) + public void absorbMacBlock(byte[] input, int inOff) { - long[] src64 = new long[src.length >> 3]; - Pack.littleEndianToLong(src, 0, src64, 0, src64.length); - int idx = 0; - while (len >= ISAP_rH_SZ) - { - x0 ^= U64BIG(src64[idx++]); - P12(); - len -= ISAP_rH_SZ; - } - /* Absorb final ad block */ - for (int i = 0; i < len; ++i) + mac.x0 ^= Pack.bigEndianToLong(input, inOff); + mac.p(12); + } + + public void absorbFinalAADBlock() + { + for (int i = 0; i < m_aadPos; ++i) { - x0 ^= (src[(idx << 3) + i] & 0xFFL) << ((7 - i) << 3); + mac.x0 ^= (m_aad[i] & 0xFFL) << ((7 - i) << 3); } - x0 ^= 0x80L << ((7 - len) << 3); - P12(); + mac.x0 ^= 0x80L << ((7 - m_aadPos) << 3); + mac.p(12); + mac.x4 ^= 1L; } - public void isap_mac(byte[] ad, int adlen, byte[] c, int clen, byte[] tag, int tagOff) + public void processMACFinal(byte[] input, int inOff, int len, byte[] tag) { - // Init State - x0 = npub64[0]; - x1 = npub64[1]; - x2 = ISAP_IV1_64; - x3 = x4 = 0; - P12(); - ABSORB_MAC(ad, adlen); - // Domain seperation - x4 ^= 1L; - ABSORB_MAC(c, clen); + for (int i = 0; i < len; ++i) + { + mac.x0 ^= (input[inOff++] & 0xFFL) << ((7 - i) << 3); + } + mac.x0 ^= 0x80L << ((7 - len) << 3); + mac.p(12); // Derive K* - Pack.longToLittleEndian(U64BIG(x0), tag, 0); - Pack.longToLittleEndian(U64BIG(x1), tag, 8); - long tmp_x2 = x2, tmp_x3 = x3, tmp_x4 = x4; - isap_rk(ISAP_IV2_64, tag, CRYPTO_KEYBYTES); - x2 = tmp_x2; - x3 = tmp_x3; - x4 = tmp_x4; + Pack.longToBigEndian(mac.x0, tag, 0); + Pack.longToBigEndian(mac.x1, tag, 8); + long tmp_x2 = mac.x2, tmp_x3 = mac.x3, tmp_x4 = mac.x4; + isap_rk(mac, ISAP_IV2_64, tag, KEY_SIZE); + mac.x2 = tmp_x2; + mac.x3 = tmp_x3; + mac.x4 = tmp_x4; // Squeeze tag - P12(); - Pack.longToLittleEndian(U64BIG(x0), tag, tagOff); - Pack.longToLittleEndian(U64BIG(x1), tag, tagOff + 8); + mac.p(12); + Pack.longToBigEndian(mac.x0, tag, 0); + Pack.longToBigEndian(mac.x1, tag, 8); } - public void isap_rk(long iv64, byte[] y, int ylen) + private void isap_rk(AsconPermutationFriend.AsconPermutation p, long iv64, byte[] y, int ylen) { // Init state - x0 = k64[0]; - x1 = k64[1]; - x2 = iv64; - x3 = x4 = 0; - P12(); + p.set(k64[0], k64[1], iv64, 0L, 0L); + p.p(12); // Absorb Y for (int i = 0; i < (ylen << 3) - 1; i++) { - x0 ^= ((((y[i >>> 3] >>> (7 - (i & 7))) & 0x01) << 7) & 0xFFL) << 56; - PX2(); + p.x0 ^= ((((y[i >>> 3] >>> (7 - (i & 7))) & 0x01) << 7) & 0xFFL) << 56; + PX2(p); } - x0 ^= (((y[ylen - 1]) & 0x01L) << 7) << 56; - P12(); + p.x0 ^= (((y[ylen - 1]) & 0x01L) << 7) << 56; + p.p(12); } - public void isap_enc(byte[] m, int mOff, int mlen, byte[] c, int cOff, int clen) + public void processEncBlock(byte[] input, int inOff, byte[] output, int outOff) + { + Pack.longToBigEndian(Pack.bigEndianToLong(input, inOff) ^ p.x0, output, outOff); + PX1(p); + } + + public void processEncFinalBlock(byte[] output, int outOff) { - /* Encrypt m */ - long[] m64 = new long[mlen >> 3]; - Pack.littleEndianToLong(m, mOff, m64, 0, m64.length); - long[] c64 = new long[m64.length]; - int idx = 0; - while (mlen >= ISAP_rH_SZ) - { - c64[idx] = U64BIG(x0) ^ m64[idx]; - PX1(); - idx++; - mlen -= ISAP_rH_SZ; - } - Pack.longToLittleEndian(c64, 0, c64.length, c, cOff); /* Encrypt final m block */ - byte[] xo = Pack.longToLittleEndian(x0); - while (mlen > 0) - { - c[(idx << 3) + cOff + mlen - 1] = (byte)(xo[ISAP_rH_SZ - mlen] ^ m[(idx << 3) + mOff + --mlen]); - } + byte[] xo = Pack.longToLittleEndian(p.x0); + Bytes.xor(m_bufPos, xo, BlockSize - m_bufPos, m_buf, 0, output, outOff); } public void reset() { // Init state - isap_rk(ISAP_IV3_64, npub, CRYPTO_NPUBBYTES); - x3 = npub64[0]; - x4 = npub64[1]; - PX1(); + isap_rk(p, ISAP_IV3_64, npub, IV_SIZE); + p.x3 = npub64[0]; + p.x4 = npub64[1]; + PX1(p); + // Init State for mac + mac.set(npub64[0], npub64[1], ISAP_IV1_64, 0L, 0L); + mac.p(12); } private int getLongSize(int x) { - return (x >>> 3) + ((x & 7) != 0 ? 1 : 0); - } - - private long ROTR(long x, long n) - { - return (x >>> n) | (x << (64 - n)); - } - - protected long U64BIG(long x) - { - return ((ROTR(x, 8) & (0xFF000000FF000000L)) | (ROTR(x, 24) & (0x00FF000000FF0000L)) | - (ROTR(x, 40) & (0x0000FF000000FF00L)) | (ROTR(x, 56) & (0x000000FF000000FFL))); - } - - protected void ROUND(long C) - { - t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C)); - t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3)); - t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4); - t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4)); - t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1); - x0 = t0 ^ ROTR(t0, 19) ^ ROTR(t0, 28); - x1 = t1 ^ ROTR(t1, 39) ^ ROTR(t1, 61); - x2 = ~(t2 ^ ROTR(t2, 1) ^ ROTR(t2, 6)); - x3 = t3 ^ ROTR(t3, 10) ^ ROTR(t3, 17); - x4 = t4 ^ ROTR(t4, 7) ^ ROTR(t4, 41); - } - - public void P12() - { - ROUND(0xf0); - ROUND(0xe1); - ROUND(0xd2); - ROUND(0xc3); - ROUND(0xb4); - ROUND(0xa5); - P6(); - } - - protected void P6() - { - ROUND(0x96); - ROUND(0x87); - ROUND(0x78); - ROUND(0x69); - ROUND(0x5a); - ROUND(0x4b); + return ((x + 7) >>> 3); } } @@ -275,14 +200,14 @@ public ISAPAEAD_A_128A() ISAP_IV3_64 = 252271952373286412L; } - protected void PX1() + protected void PX1(AsconPermutationFriend.AsconPermutation p) { - P6(); + p.p(6); } - protected void PX2() + protected void PX2(AsconPermutationFriend.AsconPermutation p) { - ROUND(0x4b); + p.round(0x4bL); } } @@ -296,21 +221,21 @@ public ISAPAEAD_A_128() ISAP_IV3_64 = 252271952374008844L; } - protected void PX1() + protected void PX1(AsconPermutationFriend.AsconPermutation p) { - P12(); + p.p(12); } - protected void PX2() + protected void PX2(AsconPermutationFriend.AsconPermutation p) { - P12(); + p.p(12); } } private abstract class ISAPAEAD_K implements ISAP_AEAD { - final int ISAP_STATE_SZ_CRYPTO_NPUBBYTES = ISAP_STATE_SZ - CRYPTO_NPUBBYTES; + protected final int ISAP_STATE_SZ_CRYPTO_NPUBBYTES = ISAP_STATE_SZ - IV_SIZE; protected short[] ISAP_IV1_16; protected short[] ISAP_IV2_16; protected short[] ISAP_IV3_16; @@ -319,33 +244,38 @@ private abstract class ISAPAEAD_K private final int[] KeccakF400RoundConstants = {0x0001, 0x8082, 0x808a, 0x8000, 0x808b, 0x0001, 0x8081, 0x8009, 0x008a, 0x0088, 0x8009, 0x000a, 0x808b, 0x008b, 0x8089, 0x8003, 0x8002, 0x0080, 0x800a, 0x000a}; protected short[] SX = new short[25]; + protected short[] macSX = new short[25]; protected short[] E = new short[25]; protected short[] C = new short[5]; + protected short[] macE = new short[25]; + protected short[] macC = new short[5]; public ISAPAEAD_K() { ISAP_rH = 144; - ISAP_rH_SZ = (ISAP_rH + 7) >> 3; + BlockSize = (ISAP_rH + 7) >> 3; } public void init() { k16 = new short[k.length >> 1]; - byteToShort(k, k16, k16.length); + Pack.littleEndianToShort(k, 0, k16, 0, k16.length); iv16 = new short[npub.length >> 1]; - byteToShort(npub, iv16, iv16.length); - reset(); + Pack.littleEndianToShort(npub, 0, iv16, 0, iv16.length); } public void reset() { // Init state - SX = new short[25]; - E = new short[25]; - C = new short[5]; - isap_rk(ISAP_IV3_16, npub, CRYPTO_NPUBBYTES, SX, ISAP_STATE_SZ_CRYPTO_NPUBBYTES, C); + Arrays.fill(SX, (byte)0); + isap_rk(ISAP_IV3_16, npub, IV_SIZE, SX, ISAP_STATE_SZ_CRYPTO_NPUBBYTES, C); System.arraycopy(iv16, 0, SX, 17, 8); PermuteRoundsKX(SX, E, C); + // Init state for mac + Arrays.fill(macSX, 12, 25, (short)0); + System.arraycopy(iv16, 0, macSX, 0, 8); + System.arraycopy(ISAP_IV1_16, 0, macSX, 8, 4); + PermuteRoundsHX(macSX, macE, macC); } protected abstract void PermuteRoundsHX(short[] SX, short[] E, short[] C); @@ -354,38 +284,23 @@ public void reset() protected abstract void PermuteRoundsBX(short[] SX, short[] E, short[] C); - protected void ABSORB_MAC(short[] SX, byte[] src, int len, short[] E, short[] C) + public void absorbMacBlock(byte[] input, int inOff) + { + byteToShortXor(input, inOff, macSX, BlockSize >> 1); + PermuteRoundsHX(macSX, macE, macC); + } + + public void absorbFinalAADBlock() { - int rem_bytes = len; - int idx = 0; - while (true) + for (int i = 0; i < m_aadPos; i++) { - if (rem_bytes > ISAP_rH_SZ) - { - byteToShortXor(src, SX, ISAP_rH_SZ >> 1); - idx += ISAP_rH_SZ; - rem_bytes -= ISAP_rH_SZ; - PermuteRoundsHX(SX, E, C); - } - else if (rem_bytes == ISAP_rH_SZ) - { - byteToShortXor(src, SX, ISAP_rH_SZ >> 1); - PermuteRoundsHX(SX, E, C); - SX[0] ^= 0x80; - PermuteRoundsHX(SX, E, C); - break; - } - else - { - for (int i = 0; i < rem_bytes; i++) - { - SX[i >> 1] ^= (src[idx++] & 0xFF) << ((i & 1) << 3); - } - SX[rem_bytes >> 1] ^= 0x80 << ((rem_bytes & 1) << 3); - PermuteRoundsHX(SX, E, C); - break; - } + macSX[i >> 1] ^= (m_aad[i] & 0xFF) << ((i & 1) << 3); } + macSX[m_aadPos >> 1] ^= 0x80 << ((m_aadPos & 1) << 3); + PermuteRoundsHX(macSX, macE, macC); + + // Domain seperation + macSX[24] ^= 0x0100; } public void isap_rk(short[] iv16, byte[] y, int ylen, short[] out16, int outlen, short[] C) @@ -408,75 +323,47 @@ public void isap_rk(short[] iv16, byte[] y, int ylen, short[] out16, int outlen, System.arraycopy(SX, 0, out16, 0, outlen == ISAP_STATE_SZ_CRYPTO_NPUBBYTES ? 17 : 8); } - public void isap_mac(byte[] ad, int adlen, byte[] c, int clen, byte[] tag, int tagOff) + public void processMACFinal(byte[] input, int inOff, int len, byte[] tag) { - SX = new short[25]; - // Init state - System.arraycopy(iv16, 0, SX, 0, 8); - System.arraycopy(ISAP_IV1_16, 0, SX, 8, 4); - PermuteRoundsHX(SX, E, C); - // Absorb AD - ABSORB_MAC(SX, ad, adlen, E, C); - // Domain seperation - SX[24] ^= 0x0100; - // Absorb C - ABSORB_MAC(SX, c, clen, E, C); + // Absorb C final block + for (int i = 0; i < len; i++) + { + macSX[i >> 1] ^= (input[inOff++] & 0xFF) << ((i & 1) << 3); + } + + macSX[len >> 1] ^= 0x80 << ((len & 1) << 3); + PermuteRoundsHX(macSX, macE, macC); // Derive K* - shortToByte(SX, tag, tagOff); - isap_rk(ISAP_IV2_16, tag, CRYPTO_KEYBYTES, SX, CRYPTO_KEYBYTES, C); + Pack.shortToLittleEndian(macSX, 0, 8, tag, 0); + isap_rk(ISAP_IV2_16, tag, KEY_SIZE, macSX, KEY_SIZE, macC); // Squeeze tag - PermuteRoundsHX(SX, E, C); - shortToByte(SX, tag, tagOff); + PermuteRoundsHX(macSX, macE, macC); + Pack.shortToLittleEndian(macSX, 0, 8, tag, 0); } - public void isap_enc(byte[] m, int mOff, int mlen, byte[] c, int cOff, int clen) + public void processEncBlock(byte[] input, int inOff, byte[] output, int outOff) { - // Squeeze key stream - while (true) + for (int i = 0; i < BlockSize; ++i) { - if (mlen >= ISAP_rH_SZ) - { - // Squeeze full lane and continue - for (int i = 0; i < ISAP_rH_SZ; ++i) - { - c[cOff++] = (byte)((SX[i >> 1] >>> ((i & 1) << 3)) ^ m[mOff++]); - } - mlen -= ISAP_rH_SZ; - PermuteRoundsKX(SX, E, C); - } - else - { - // Squeeze full or partial lane and stop - for (int i = 0; i < mlen; ++i) - { - c[cOff++] = (byte)((SX[i >> 1] >>> ((i & 1) << 3)) ^ m[mOff++]); - } - break; - } + output[outOff++] = (byte)((SX[i >> 1] >>> ((i & 1) << 3)) ^ input[inOff++]); } + PermuteRoundsKX(SX, E, C); } - private void byteToShortXor(byte[] input, short[] output, int outLen) + public void processEncFinalBlock(byte[] output, int outOff) { - for (int i = 0; i < outLen; ++i) + // Squeeze full or partial lane and stop + for (int i = 0; i < m_bufPos; ++i) { - output[i] ^= Pack.littleEndianToShort(input, (i << 1)); + output[outOff++] = (byte)((SX[i >> 1] >>> ((i & 1) << 3)) ^ m_buf[i]); } } - private void byteToShort(byte[] input, short[] output, int outLen) + private void byteToShortXor(byte[] input, int inOff, short[] output, int outLen) { for (int i = 0; i < outLen; ++i) { - output[i] = Pack.littleEndianToShort(input, (i << 1)); - } - } - - private void shortToByte(short[] input, byte[] output, int outOff) - { - for (int i = 0; i < 8; ++i) - { - Pack.shortToLittleEndian(input[i], output, outOff + (i << 1)); + output[i] ^= Pack.littleEndianToShort(input, inOff + (i << 1)); } } @@ -789,212 +676,59 @@ protected void PermuteRoundsBX(short[] SX, short[] E, short[] C) } @Override - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] key, byte[] iv) throws IllegalArgumentException { - this.forEncryption = forEncryption; - if (!(params instanceof ParametersWithIV)) - { - throw new IllegalArgumentException( - "ISAP AEAD init parameters must include an IV"); - } - - ParametersWithIV ivParams = (ParametersWithIV)params; - - byte[] iv = ivParams.getIV(); - - if (iv == null || iv.length != 16) - { - throw new IllegalArgumentException( - "ISAP AEAD requires exactly 12 bytes of IV"); - } - - if (!(ivParams.getParameters() instanceof KeyParameter)) - { - throw new IllegalArgumentException( - "ISAP AEAD init parameters must include a key"); - } - - KeyParameter key = (KeyParameter)ivParams.getParameters(); - byte[] keyBytes = key.getKey(); - if (keyBytes.length != 16) - { - throw new IllegalArgumentException( - "ISAP AEAD key must be 128 bits long"); - } - - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - - /* - * Initialize variables. - */ - npub = new byte[iv.length]; - k = new byte[keyBytes.length]; - System.arraycopy(iv, 0, npub, 0, iv.length); - System.arraycopy(keyBytes, 0, k, 0, keyBytes.length); + npub = iv; + k = key; ISAPAEAD.init(); - initialised = true; - reset(); } - @Override - public String getAlgorithmName() + protected void processBufferAAD(byte[] input, int inOff) { - return algorithmName; + ISAPAEAD.absorbMacBlock(input, inOff); } - @Override - public void processAADByte(byte in) + protected void processFinalAAD() { - aadData.write(in); + ISAPAEAD.absorbFinalAADBlock(); } @Override - public void processAADBytes(byte[] in, int inOff, int len) + protected void finishAAD(State nextState, boolean isDoFinal) { - if ((inOff + len) > in.length) - { - throw new DataLengthException("input buffer too short" + (forEncryption ? "encryption" : "decryption")); - } - - aadData.write(in, inOff, len); + finishAAD3(nextState, isDoFinal); } - @Override - public int processByte(byte in, byte[] out, int outOff) - throws DataLengthException + protected void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) { - return processBytes(new byte[]{in}, 0, 1, out, outOff); + ISAPAEAD.processEncBlock(input, inOff, output, outOff); + ISAPAEAD.absorbMacBlock(output, outOff); } - @Override - public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) - throws DataLengthException + protected void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - if ((inOff + len) > input.length) - { - throw new DataLengthException("input buffer too short"); - } - message.write(input, inOff, len); - if (forEncryption) - { - if (message.size() >= ISAP_rH_SZ) - { - len = message.size() / ISAP_rH_SZ * ISAP_rH_SZ; - if (outOff + len > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - byte[] enc_input = message.toByteArray(); - ISAPAEAD.isap_enc(enc_input, 0, len, output, outOff, output.length); - outputStream.write(output, outOff, len); - message.reset(); - message.write(enc_input, len, enc_input.length - len); - return len; - } - } - return 0; + ISAPAEAD.processEncBlock(input, inOff, output, outOff); + ISAPAEAD.absorbMacBlock(input, inOff); } @Override - public int doFinal(byte[] output, int outOff) - throws IllegalStateException, InvalidCipherTextException + protected void processFinalBlock(byte[] output, int outOff) { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - int len; + ISAPAEAD.processEncFinalBlock(output, outOff); if (forEncryption) { - byte[] enc_input = message.toByteArray(); - len = enc_input.length; - if (outOff + len + 16 > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - ISAPAEAD.isap_enc(enc_input, 0, len, output, outOff, output.length); - outputStream.write(output, outOff, len); - outOff += len; - ad = aadData.toByteArray(); - c = outputStream.toByteArray(); - mac = new byte[16]; - ISAPAEAD.isap_mac(ad, ad.length, c, c.length, mac, 0); - System.arraycopy(mac, 0, output, outOff, 16); - len += 16; + ISAPAEAD.processMACFinal(output, outOff, m_bufPos, mac); } else { - ad = aadData.toByteArray(); - c = message.toByteArray(); - mac = new byte[16]; - len = c.length - mac.length; - if (len + outOff > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - ISAPAEAD.isap_mac(ad, ad.length, c, len, mac, 0); - ISAPAEAD.reset(); - for (int i = 0; i < 16; ++i) - { - if (mac[i] != c[len + i]) - { - throw new IllegalArgumentException("Mac does not match"); - } - } - ISAPAEAD.isap_enc(c, 0, len, output, outOff, output.length); + ISAPAEAD.processMACFinal(m_buf, 0, m_bufPos, mac); } - return len; } - @Override - public byte[] getMac() + protected void reset(boolean clearMac) { - return mac; - } - - @Override - public int getUpdateOutputSize(int len) - { - return len; - } - - @Override - public int getOutputSize(int len) - { - return len + 16; - } - - @Override - public void reset() - { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - aadData.reset(); + super.reset(clearMac); ISAPAEAD.reset(); - message.reset(); - outputStream.reset(); - } - - public int getKeyBytesSize() - { - return CRYPTO_KEYBYTES; - } - - public int getIVBytesSize() - { - return CRYPTO_NPUBBYTES; - } - - public int getBlockSize() - { - return ISAP_rH_SZ; } } diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/PhotonBeetleEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/PhotonBeetleEngine.java index 50bfe99545..29a299da8a 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/PhotonBeetleEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/PhotonBeetleEngine.java @@ -1,19 +1,10 @@ package org.bouncycastle.crypto.engines; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.crypto.digests.PhotonBeetleDigest; +import org.bouncycastle.util.Bytes; /** - * Photon-Beetle, https://www.isical.ac.in/~lightweight/beetle/ + * Photon-Beetle, * https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/photon-beetle-spec-final.pdf *

    * Photon-Beetle with reference to C Reference Impl from: https://github.com/PHOTON-Beetle/Software @@ -21,7 +12,7 @@ */ public class PhotonBeetleEngine - implements AEADCipher + extends AEADBaseEngine { public enum PhotonBeetleParameters { @@ -30,32 +21,14 @@ public enum PhotonBeetleParameters } private boolean input_empty; - private boolean forEncryption; private byte[] K; private byte[] N; private byte[] state; - private byte[][] state_2d; - private byte[] A; - private byte[] T; - private boolean encrypted; - private boolean initialised; - private final ByteArrayOutputStream aadData = new ByteArrayOutputStream(); - private final ByteArrayOutputStream message = new ByteArrayOutputStream(); - private final int CRYPTO_KEYBYTES = 16; - private final int CRYPTO_NPUBBYTES = 16; - private final int RATE_INBYTES; private final int RATE_INBYTES_HALF; private final int STATE_INBYTES; - private final int TAG_INBYTES = 16; private final int LAST_THREE_BITS_OFFSET; - private final int ROUND = 12; - private final int D = 8; - private final int Dq = 3; - private final int Dr = 7; - private final int DSquare = 64; - private final int S = 4; - private final int S_1 = 3; - private final byte[][] RC = { + private static final int D = 8; + private static final byte[][] RC = { {1, 3, 7, 14, 13, 11, 6, 12, 9, 2, 5, 10}, {0, 2, 6, 15, 12, 10, 7, 13, 8, 3, 4, 11}, {2, 0, 4, 13, 14, 8, 5, 15, 10, 1, 6, 9}, @@ -65,7 +38,7 @@ public enum PhotonBeetleParameters {13, 15, 11, 2, 1, 7, 10, 0, 5, 14, 9, 6}, {9, 11, 15, 6, 5, 3, 14, 4, 1, 10, 13, 2} }; - private final byte[][] MixColMatrix = { + private static final byte[][] MixColMatrix = { {2, 4, 2, 11, 2, 8, 5, 6}, {12, 9, 8, 13, 7, 7, 5, 2}, {4, 4, 13, 13, 9, 4, 13, 9}, @@ -76,10 +49,11 @@ public enum PhotonBeetleParameters {15, 1, 13, 10, 5, 10, 2, 3} }; - private final byte[] sbox = {12, 5, 6, 11, 9, 0, 10, 13, 3, 14, 15, 8, 4, 7, 1, 2}; + private static final byte[] sbox = {12, 5, 6, 11, 9, 0, 10, 13, 3, 14, 15, 8, 4, 7, 1, 2}; public PhotonBeetleEngine(PhotonBeetleParameters pbp) { + KEY_SIZE = IV_SIZE = MAC_SIZE = 16; int CAPACITY_INBITS = 0, RATE_INBITS = 0; switch (pbp) { @@ -92,225 +66,127 @@ public PhotonBeetleEngine(PhotonBeetleParameters pbp) CAPACITY_INBITS = 128; break; } - RATE_INBYTES = (RATE_INBITS + 7) >>> 3; - RATE_INBYTES_HALF = RATE_INBYTES >>> 1; + AADBufferSize = BlockSize = (RATE_INBITS + 7) >>> 3; + RATE_INBYTES_HALF = BlockSize >>> 1; int STATE_INBITS = RATE_INBITS + CAPACITY_INBITS; STATE_INBYTES = (STATE_INBITS + 7) >>> 3; LAST_THREE_BITS_OFFSET = (STATE_INBITS - ((STATE_INBYTES - 1) << 3) - 3); - initialised = false; + algorithmName = "Photon-Beetle AEAD"; + state = new byte[STATE_INBYTES]; + setInnerMembers(ProcessingBufferType.Buffered, AADOperatorType.Counter, DataOperatorType.Counter); } @Override - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] key, byte[] iv) throws IllegalArgumentException { - this.forEncryption = forEncryption; - if (!(params instanceof ParametersWithIV)) - { - throw new IllegalArgumentException("Photon-Beetle AEAD init parameters must include an IV"); - } - ParametersWithIV ivParams = (ParametersWithIV)params; - N = ivParams.getIV(); - if (N == null || N.length != CRYPTO_NPUBBYTES) - { - throw new IllegalArgumentException("Photon-Beetle AEAD requires exactly 16 bytes of IV"); - } - if (!(ivParams.getParameters() instanceof KeyParameter)) - { - throw new IllegalArgumentException("Photon-Beetle AEAD init parameters must include a key"); - } - KeyParameter key = (KeyParameter)ivParams.getParameters(); - K = key.getKey(); - if (K.length != CRYPTO_KEYBYTES) - { - throw new IllegalArgumentException("Photon-Beetle AEAD key must be 128 bits long"); - } - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - state = new byte[STATE_INBYTES]; - state_2d = new byte[D][D]; - T = new byte[TAG_INBYTES]; - initialised = true; - reset(false); + K = key; + N = iv; } - @Override - public String getAlgorithmName() + protected void processBufferAAD(byte[] input, int inOff) { - return "Photon-Beetle AEAD"; + photonPermutation(state); + Bytes.xorTo(BlockSize, input, inOff, state); } @Override - public void processAADByte(byte input) + protected void finishAAD(State nextState, boolean isDoFinal) { - aadData.write(input); + finishAAD3(nextState, isDoFinal); } - @Override - public void processAADBytes(byte[] input, int inOff, int len) + protected void processFinalAAD() { - if (inOff + len > input.length) + int aadLen = aadOperator.getLen(); + if (aadLen != 0) { - throw new DataLengthException("input buffer too short"); + if (m_aadPos != 0) + { + photonPermutation(state); + Bytes.xorTo(m_aadPos, m_aad, state); + if (m_aadPos < BlockSize) + { + state[m_aadPos] ^= 0x01; // ozs + } + } + state[STATE_INBYTES - 1] ^= select(dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE) > 0, + ((aadLen % BlockSize) == 0), (byte)3, (byte)4) << LAST_THREE_BITS_OFFSET; } - aadData.write(input, inOff, len); } - @Override - public int processByte(byte input, byte[] output, int outOff) - throws DataLengthException + protected void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) { - return processBytes(new byte[]{input}, 0, 1, output, outOff); + rhoohr(output, outOff, input, inOff, BlockSize); + Bytes.xorTo(BlockSize, input, inOff, state); } - @Override - public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) - throws DataLengthException + protected void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) { - if (inOff + len > input.length) - { - throw new DataLengthException("input buffer too short"); - } - message.write(input, inOff, len); - return 0; + rhoohr(output, outOff, input, inOff, BlockSize); + Bytes.xorTo(BlockSize, output, outOff, state); } @Override - public int doFinal(byte[] output, int outOff) - throws IllegalStateException, InvalidCipherTextException + protected void processFinalBlock(byte[] output, int outOff) { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - int len = message.size() - (forEncryption ? 0 : TAG_INBYTES); - if ((forEncryption && len + TAG_INBYTES + outOff > output.length) || - (!forEncryption && len + outOff > output.length)) - { - throw new OutputLengthException("output buffer too short"); - } - byte[] input = message.toByteArray(); - int inOff = 0; - A = aadData.toByteArray(); - int adlen = A.length, i; - if (adlen != 0 || len != 0) + int len = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + int bufferLen = m_bufPos;// - (forEncryption ? 0 : MAC_SIZE); + int aadLen = aadOperator.getLen(); + if (aadLen != 0 || len != 0) { input_empty = false; } - byte c0 = select((len != 0), ((adlen % RATE_INBYTES) == 0), (byte)3, (byte)4); - byte c1 = select((adlen != 0), ((len % RATE_INBYTES) == 0), (byte)5, (byte)6); - int Dlen_inblocks, LastDBlocklen; - if (adlen != 0) - { - Dlen_inblocks = (adlen + RATE_INBYTES - 1) / RATE_INBYTES; - for (i = 0; i < Dlen_inblocks - 1; i++) - { - PHOTON_Permutation(); - XOR(A, i * RATE_INBYTES, RATE_INBYTES); - } - PHOTON_Permutation(); - LastDBlocklen = adlen - i * RATE_INBYTES; - XOR(A, i * RATE_INBYTES, LastDBlocklen); - if (LastDBlocklen < RATE_INBYTES) - { - state[LastDBlocklen] ^= 0x01; // ozs - } - state[STATE_INBYTES - 1] ^= c0 << LAST_THREE_BITS_OFFSET; - } + byte c1 = select((aadLen != 0), ((len % BlockSize) == 0), (byte)5, (byte)6); + if (len != 0) { - Dlen_inblocks = (len + RATE_INBYTES - 1) / RATE_INBYTES; - for (i = 0; i < Dlen_inblocks - 1; i++) - { - PHOTON_Permutation(); - rhoohr(output, outOff + i * RATE_INBYTES, input, inOff + i * RATE_INBYTES, RATE_INBYTES); - } - PHOTON_Permutation(); - LastDBlocklen = len - i * RATE_INBYTES; - rhoohr(output, outOff + i * RATE_INBYTES, input, inOff + i * RATE_INBYTES, LastDBlocklen); - if (LastDBlocklen < RATE_INBYTES) - { - state[LastDBlocklen] ^= 0x01; // ozs - } - state[STATE_INBYTES - 1] ^= c1 << LAST_THREE_BITS_OFFSET; - } - outOff += len; - if (input_empty) - { - state[STATE_INBYTES - 1] ^= 1 << LAST_THREE_BITS_OFFSET; - } - PHOTON_Permutation(); - T = new byte[TAG_INBYTES]; - System.arraycopy(state, 0, T, 0, TAG_INBYTES); - if (forEncryption) - { - System.arraycopy(T, 0, output, outOff, TAG_INBYTES); - len += TAG_INBYTES; - } - else - { - for (i = 0; i < TAG_INBYTES; ++i) + if (bufferLen != 0) { - if (T[i] != input[len + i]) + rhoohr(output, outOff, m_buf, 0, bufferLen); + if (forEncryption) + { + Bytes.xorTo(bufferLen, m_buf, state); + } + else + { + Bytes.xorTo(bufferLen, output, outOff, state); + } + if (bufferLen < BlockSize) { - throw new IllegalArgumentException("Mac does not match"); + state[bufferLen] ^= 0x01; // ozs } } + state[STATE_INBYTES - 1] ^= c1 << LAST_THREE_BITS_OFFSET; } - reset(false); - return len; - } - - @Override - public byte[] getMac() - { - return T; - } - - @Override - public int getUpdateOutputSize(int len) - { - return len; - } - - @Override - public int getOutputSize(int len) - { - return len + TAG_INBYTES; - } - - @Override - public void reset() - { - if (!initialised) + else if (input_empty) { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); + state[STATE_INBYTES - 1] ^= 1 << LAST_THREE_BITS_OFFSET; } - - reset(true); + photonPermutation(state); + System.arraycopy(state, 0, mac, 0, MAC_SIZE); } - private void reset(boolean clearMac) + protected void reset(boolean clearMac) { - if (clearMac) - { - T = null; - } + super.reset(clearMac); input_empty = true; - aadData.reset(); - message.reset(); System.arraycopy(K, 0, state, 0, K.length); System.arraycopy(N, 0, state, K.length, N.length); - encrypted = false; } - private void PHOTON_Permutation() + private static void photonPermutation(byte[] state) { - int i, j, k, l; + int i, j, k; + int dq = 3; + int dr = 7; + int DSquare = 64; + byte[][] state_2d = new byte[D][D]; for (i = 0; i < DSquare; i++) { - state_2d[i >>> Dq][i & Dr] = (byte)(((state[i >> 1] & 0xFF) >>> (4 * (i & 1))) & 0xf); + state_2d[i >>> dq][i & dr] = (byte)(((state[i >> 1] & 0xFF) >>> (4 * (i & 1))) & 0xf); } + int ROUND = 12; for (int round = 0; round < ROUND; round++) { //AddKey @@ -338,29 +214,25 @@ private void PHOTON_Permutation() { for (i = 0; i < D; i++) { - byte sum = 0; + int sum = 0; + for (k = 0; k < D; k++) { - int x = MixColMatrix[i][k], ret = 0, b = state_2d[k][j]; - for (l = 0; l < S; l++) - { - if (((b >>> l) & 1) != 0) - { - ret ^= x; - } - if (((x >>> S_1) & 1) != 0) - { - x <<= 1; - x ^= 0x3; - } - else - { - x <<= 1; - } - } - sum ^= ret & 15; + int x = MixColMatrix[i][k], b = state_2d[k][j]; + + sum ^= x * (b & 1); + sum ^= x * (b & 2); + sum ^= x * (b & 4); + sum ^= x * (b & 8); } - state[i] = sum; + + int t0 = sum >>> 4; + sum = (sum & 15) ^ t0 ^ (t0 << 1); + + int t1 = sum >>> 4; + sum = (sum & 15) ^ t1 ^ (t1 << 1); + + state[i] = (byte)sum; } for (i = 0; i < D; i++) { @@ -370,7 +242,7 @@ private void PHOTON_Permutation() } for (i = 0; i < DSquare; i += 2) { - state[i >>> 1] = (byte)(((state_2d[i >>> Dq][i & Dr] & 0xf)) | ((state_2d[i >>> Dq][(i + 1) & Dr] & 0xf) << 4)); + state[i >>> 1] = (byte)(((state_2d[i >>> dq][i & dr] & 0xf)) | ((state_2d[i >>> dq][(i + 1) & dr] & 0xf) << 4)); } } @@ -393,52 +265,26 @@ private byte select(boolean condition1, boolean condition2, byte option3, byte o private void rhoohr(byte[] ciphertext, int outOff, byte[] plaintext, int inOff, int DBlen_inbytes) { - byte[] OuterState_part1_ROTR1 = state_2d[0]; + photonPermutation(state); + byte[] OuterState_part1_ROTR1 = new byte[D]; int i, loop_end = Math.min(DBlen_inbytes, RATE_INBYTES_HALF); for (i = 0; i < RATE_INBYTES_HALF - 1; i++) { OuterState_part1_ROTR1[i] = (byte)(((state[i] & 0xFF) >>> 1) | ((state[(i + 1)] & 1) << 7)); } OuterState_part1_ROTR1[RATE_INBYTES_HALF - 1] = (byte)(((state[i] & 0xFF) >>> 1) | ((state[0] & 1) << 7)); - i = 0; - while (i < loop_end) - { - ciphertext[i + outOff] = (byte)(state[i + RATE_INBYTES_HALF] ^ plaintext[i++ + inOff]); - } - while (i < DBlen_inbytes) - { - ciphertext[i + outOff] = (byte)(OuterState_part1_ROTR1[i - RATE_INBYTES_HALF] ^ plaintext[i++ + inOff]); - } - if (forEncryption) - { - XOR(plaintext, inOff, DBlen_inbytes); - } - else - { - XOR(ciphertext, inOff, DBlen_inbytes); - } + Bytes.xor(loop_end, state, RATE_INBYTES_HALF, plaintext, inOff, ciphertext, outOff); + Bytes.xor(DBlen_inbytes - loop_end, OuterState_part1_ROTR1, loop_end - RATE_INBYTES_HALF, plaintext, + inOff + loop_end, ciphertext, outOff + loop_end); } - private void XOR(byte[] in_right, int rOff, int iolen_inbytes) + public static void photonPermutation(PhotonBeetleDigest.Friend friend, byte[] state) { - for (int i = 0; i < iolen_inbytes; i++) + if (null == friend) { - state[i] ^= in_right[rOff++]; + throw new NullPointerException("This method is only for use by PhotonBeetleDigest"); } - } - public int getBlockSize() - { - return RATE_INBYTES; - } - - public int getKeyBytesSize() - { - return CRYPTO_KEYBYTES; - } - - public int getIVBytesSize() - { - return CRYPTO_NPUBBYTES; + photonPermutation(state); } -} +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/RomulusEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/RomulusEngine.java new file mode 100644 index 0000000000..06535cf482 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/RomulusEngine.java @@ -0,0 +1,915 @@ +package org.bouncycastle.crypto.engines; + +import org.bouncycastle.crypto.digests.RomulusDigest; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Bytes; + +/** + * Romulus v1.3, based on the current round 3 submission, https://romulusae.github.io/romulus/ + * Reference C implementation: https://github.com/romulusae/romulus + * Specification: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/romulus-spec-final.pdf + */ + +public class RomulusEngine + extends AEADBaseEngine +{ + public static class RomulusParameters + { + public static final int ROMULUS_M = 0; + public static final int ROMULUS_N = 1; + public static final int ROMULUS_T = 2; + + public static final RomulusParameters RomulusM = new RomulusParameters(ROMULUS_M); + public static final RomulusParameters RomulusN = new RomulusParameters(ROMULUS_N); + public static final RomulusParameters RomulusT = new RomulusParameters(ROMULUS_T); + + private final int ord; + + RomulusParameters(int ord) + { + this.ord = ord; + } + } + + private byte[] k; + private byte[] npub; + private static final int AD_BLK_LEN_HALF = 16; + private Instance instance; + private final byte[] CNT; + + // Packing of data is done as follows (state[i][j] stands for row i and column j): + // 0 1 2 3 + // 4 5 6 7 + // 8 9 10 11 + //12 13 14 15 + + // 8-bit Sbox + private static final byte[] sbox_8 = + { + (byte)0x65, (byte)0x4c, (byte)0x6a, (byte)0x42, (byte)0x4b, (byte)0x63, (byte)0x43, (byte)0x6b, (byte)0x55, + (byte)0x75, (byte)0x5a, (byte)0x7a, (byte)0x53, (byte)0x73, (byte)0x5b, (byte)0x7b, (byte)0x35, (byte)0x8c, + (byte)0x3a, (byte)0x81, (byte)0x89, (byte)0x33, (byte)0x80, (byte)0x3b, (byte)0x95, (byte)0x25, (byte)0x98, + (byte)0x2a, (byte)0x90, (byte)0x23, (byte)0x99, (byte)0x2b, (byte)0xe5, (byte)0xcc, (byte)0xe8, (byte)0xc1, + (byte)0xc9, (byte)0xe0, (byte)0xc0, (byte)0xe9, (byte)0xd5, (byte)0xf5, (byte)0xd8, (byte)0xf8, (byte)0xd0, + (byte)0xf0, (byte)0xd9, (byte)0xf9, (byte)0xa5, (byte)0x1c, (byte)0xa8, (byte)0x12, (byte)0x1b, (byte)0xa0, + (byte)0x13, (byte)0xa9, (byte)0x05, (byte)0xb5, (byte)0x0a, (byte)0xb8, (byte)0x03, (byte)0xb0, (byte)0x0b, + (byte)0xb9, (byte)0x32, (byte)0x88, (byte)0x3c, (byte)0x85, (byte)0x8d, (byte)0x34, (byte)0x84, (byte)0x3d, + (byte)0x91, (byte)0x22, (byte)0x9c, (byte)0x2c, (byte)0x94, (byte)0x24, (byte)0x9d, (byte)0x2d, (byte)0x62, + (byte)0x4a, (byte)0x6c, (byte)0x45, (byte)0x4d, (byte)0x64, (byte)0x44, (byte)0x6d, (byte)0x52, (byte)0x72, + (byte)0x5c, (byte)0x7c, (byte)0x54, (byte)0x74, (byte)0x5d, (byte)0x7d, (byte)0xa1, (byte)0x1a, (byte)0xac, + (byte)0x15, (byte)0x1d, (byte)0xa4, (byte)0x14, (byte)0xad, (byte)0x02, (byte)0xb1, (byte)0x0c, (byte)0xbc, + (byte)0x04, (byte)0xb4, (byte)0x0d, (byte)0xbd, (byte)0xe1, (byte)0xc8, (byte)0xec, (byte)0xc5, (byte)0xcd, + (byte)0xe4, (byte)0xc4, (byte)0xed, (byte)0xd1, (byte)0xf1, (byte)0xdc, (byte)0xfc, (byte)0xd4, (byte)0xf4, + (byte)0xdd, (byte)0xfd, (byte)0x36, (byte)0x8e, (byte)0x38, (byte)0x82, (byte)0x8b, (byte)0x30, (byte)0x83, + (byte)0x39, (byte)0x96, (byte)0x26, (byte)0x9a, (byte)0x28, (byte)0x93, (byte)0x20, (byte)0x9b, (byte)0x29, + (byte)0x66, (byte)0x4e, (byte)0x68, (byte)0x41, (byte)0x49, (byte)0x60, (byte)0x40, (byte)0x69, (byte)0x56, + (byte)0x76, (byte)0x58, (byte)0x78, (byte)0x50, (byte)0x70, (byte)0x59, (byte)0x79, (byte)0xa6, (byte)0x1e, + (byte)0xaa, (byte)0x11, (byte)0x19, (byte)0xa3, (byte)0x10, (byte)0xab, (byte)0x06, (byte)0xb6, (byte)0x08, + (byte)0xba, (byte)0x00, (byte)0xb3, (byte)0x09, (byte)0xbb, (byte)0xe6, (byte)0xce, (byte)0xea, (byte)0xc2, + (byte)0xcb, (byte)0xe3, (byte)0xc3, (byte)0xeb, (byte)0xd6, (byte)0xf6, (byte)0xda, (byte)0xfa, (byte)0xd3, + (byte)0xf3, (byte)0xdb, (byte)0xfb, (byte)0x31, (byte)0x8a, (byte)0x3e, (byte)0x86, (byte)0x8f, (byte)0x37, + (byte)0x87, (byte)0x3f, (byte)0x92, (byte)0x21, (byte)0x9e, (byte)0x2e, (byte)0x97, (byte)0x27, (byte)0x9f, + (byte)0x2f, (byte)0x61, (byte)0x48, (byte)0x6e, (byte)0x46, (byte)0x4f, (byte)0x67, (byte)0x47, (byte)0x6f, + (byte)0x51, (byte)0x71, (byte)0x5e, (byte)0x7e, (byte)0x57, (byte)0x77, (byte)0x5f, (byte)0x7f, (byte)0xa2, + (byte)0x18, (byte)0xae, (byte)0x16, (byte)0x1f, (byte)0xa7, (byte)0x17, (byte)0xaf, (byte)0x01, (byte)0xb2, + (byte)0x0e, (byte)0xbe, (byte)0x07, (byte)0xb7, (byte)0x0f, (byte)0xbf, (byte)0xe2, (byte)0xca, (byte)0xee, + (byte)0xc6, (byte)0xcf, (byte)0xe7, (byte)0xc7, (byte)0xef, (byte)0xd2, (byte)0xf2, (byte)0xde, (byte)0xfe, + (byte)0xd7, (byte)0xf7, (byte)0xdf, (byte)0xff + }; + + // Tweakey permutation + private static final byte[] TWEAKEY_P = {9, 15, 8, 13, 10, 14, 12, 11, 0, 1, 2, 3, 4, 5, 6, 7}; + + // round constants + private static final byte[] RC = { + 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3E, 0x3D, 0x3B, 0x37, 0x2F, + 0x1E, 0x3C, 0x39, 0x33, 0x27, 0x0E, 0x1D, 0x3A, 0x35, 0x2B, + 0x16, 0x2C, 0x18, 0x30, 0x21, 0x02, 0x05, 0x0B, 0x17, 0x2E, + 0x1C, 0x38, 0x31, 0x23, 0x06, 0x0D, 0x1B, 0x36, 0x2D, 0x1A + }; + + public RomulusEngine(RomulusParameters romulusParameters) + { + KEY_SIZE = IV_SIZE = MAC_SIZE = BlockSize = AADBufferSize = 16; + CNT = new byte[7]; + switch (romulusParameters.ord) + { + case RomulusParameters.ROMULUS_M: + algorithmName = "Romulus-M"; + instance = new RomulusM(); + break; + case RomulusParameters.ROMULUS_N: + algorithmName = "Romulus-N"; + instance = new RomulusN(); + break; + case RomulusParameters.ROMULUS_T: + algorithmName = "Romulus-T"; + AADBufferSize = 32; + instance = new RomulusT(); + break; + } + setInnerMembers(romulusParameters == RomulusParameters.RomulusN ? ProcessingBufferType.Buffered : ProcessingBufferType.Immediate, + AADOperatorType.Counter, + romulusParameters == RomulusParameters.RomulusM ? DataOperatorType.Stream : DataOperatorType.Counter); + } + + private interface Instance + { + void processFinalBlock(byte[] output, int outOff); + + void processBufferAAD(byte[] input, int inOff); + + void processFinalAAD(); + + void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff); + + void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff); + + void reset(); + } + + private class RomulusM + implements Instance + { + private final byte[] mac_s = new byte[16]; + private final byte[] mac_CNT = new byte[7]; + private final byte[] s = new byte[16]; + private int offset; + private boolean twist = true; + + public RomulusM() + { + } + + @Override + public void processFinalBlock(byte[] output, int outOff) + { + byte w = 48; + int adlen = aadOperator.getLen(); + int mlen = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + byte[] m = ((StreamDataOperator)dataOperator).getBytes(); + int xlen, mOff = 0, mauth = outOff; + xlen = mlen; + if ((adlen & 31) == 0 && adlen != 0) + { + w ^= 8; + } + else if ((adlen & 31) < AD_BLK_LEN_HALF) + { + w ^= 2; + } + else if ((adlen & 31) != AD_BLK_LEN_HALF) + { + w ^= 10; + } + if ((mlen & 31) == 0 && mlen != 0) + { + w ^= 4; + } + else if ((mlen & 31) < AD_BLK_LEN_HALF) + { + w ^= 1; + } + else if ((mlen & 31) != AD_BLK_LEN_HALF) + { + w ^= 5; + } + if (forEncryption) + { + if ((w & 8) == 0) + { + byte[] Temp = new byte[16]; + int len8 = Math.min(xlen, AD_BLK_LEN_HALF); + xlen -= len8; + pad(m, mOff, Temp, AD_BLK_LEN_HALF, len8); + block_cipher(mac_s, k, Temp, 0, mac_CNT, (byte)44); + lfsr_gf56(mac_CNT); + mOff += len8; + } + else if (mlen == 0) + { + lfsr_gf56(mac_CNT); + } + while (xlen > 0) + { + offset = mOff; + xlen = ad_encryption(m, mOff, mac_s, k, xlen, mac_CNT); + mOff = offset; + } + block_cipher(mac_s, k, npub, 0, mac_CNT, w); + // Tag generation + g8A(mac_s, mac, 0); + mOff -= mlen; + } + else + { + System.arraycopy(m, mlen, mac, 0, MAC_SIZE); + } + reset_lfsr_gf56(CNT); + System.arraycopy(mac, 0, s, 0, AD_BLK_LEN_HALF); + if (mlen > 0) + { + block_cipher(s, k, npub, 0, CNT, (byte)36); + while (mlen > AD_BLK_LEN_HALF) + { + mlen = mlen - AD_BLK_LEN_HALF; + rho(m, mOff, output, outOff, s, AD_BLK_LEN_HALF); + outOff += AD_BLK_LEN_HALF; + mOff += AD_BLK_LEN_HALF; + lfsr_gf56(CNT); + block_cipher(s, k, npub, 0, CNT, (byte)36); + } + rho(m, mOff, output, outOff, s, mlen); + } + if (!forEncryption) + { + if ((w & 8) == 0) + { + byte[] Temp = new byte[16]; + int len8 = Math.min(xlen, AD_BLK_LEN_HALF); + xlen -= len8; + pad(output, mauth, Temp, AD_BLK_LEN_HALF, len8); + block_cipher(mac_s, k, Temp, 0, mac_CNT, (byte)44); + lfsr_gf56(mac_CNT); + mauth += len8; + } + else if (mlen == 0) + { + lfsr_gf56(mac_CNT); + } + while (xlen > 0) + { + offset = mauth; + xlen = ad_encryption(output, mauth, mac_s, k, xlen, mac_CNT); + mauth = offset; + } + block_cipher(mac_s, k, npub, 0, mac_CNT, w); + // Tag generation + g8A(mac_s, mac, 0); + System.arraycopy(m, dataOperator.getLen() - MAC_SIZE, m_buf, 0, MAC_SIZE); + m_bufPos = 0; + } + } + + int ad_encryption(byte[] A, int AOff, byte[] s, byte[] k, int adlen, byte[] CNT) + { + byte[] T = new byte[16]; + byte[] mp = new byte[16]; + int n = 16; + int len8; + len8 = Math.min(adlen, n); + adlen -= len8; + // Rho(S,A) pads an A block and XORs it to the internal state. + pad(A, AOff, mp, n, len8); + Bytes.xorTo(n, mp, s); + offset = AOff += len8; + lfsr_gf56(CNT); + if (adlen != 0) + { + len8 = Math.min(adlen, n); + adlen -= len8; + pad(A, AOff, T, n, len8); + offset = AOff + len8; + block_cipher(s, k, T, 0, CNT, (byte)44); + lfsr_gf56(CNT); + } + return adlen; + } + + @Override + public void processBufferAAD(byte[] input, int inOff) + { + if (twist) + { + Bytes.xorTo(MAC_SIZE, input, inOff, mac_s); + } + else + { + block_cipher(mac_s, k, input, inOff, mac_CNT, (byte)40); + } + twist = !twist; + lfsr_gf56(mac_CNT); + } + + @Override + public void processFinalAAD() + { + if (aadOperator.getLen() == 0) + { + // AD is an empty string + lfsr_gf56(mac_CNT); + } + else if (m_aadPos != 0) + { + Arrays.fill(m_aad, m_aadPos, BlockSize - 1, (byte)0); + m_aad[BlockSize - 1] = (byte)(m_aadPos & 0x0f); + if (twist) + { + Bytes.xorTo(BlockSize, m_aad, mac_s); + } + else + { + block_cipher(mac_s, k, m_aad, 0, mac_CNT, (byte)40); + } + lfsr_gf56(mac_CNT); + } + m_aadPos = 0; + m_bufPos = dataOperator.getLen(); + } + + @Override + public void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) + { + } + + @Override + public void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) + { + } + + @Override + public void reset() + { + Arrays.clear(s); + Arrays.clear(mac_s); + reset_lfsr_gf56(mac_CNT); + reset_lfsr_gf56(CNT); + twist = true; + } + } + + private class RomulusN + implements Instance + { + private final byte[] s; + boolean twist; + + public RomulusN() + { + s = new byte[AD_BLK_LEN_HALF]; + } + + @Override + public void processFinalBlock(byte[] output, int outOff) + { + int messegeLen = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + if (messegeLen == 0) + { + lfsr_gf56(CNT); + block_cipher(s, k, npub, 0, CNT, (byte)0x15); + } + else if (m_bufPos != 0) + { + int len8 = Math.min(m_bufPos, AD_BLK_LEN_HALF); + rho(m_buf, 0, output, outOff, s, len8); + lfsr_gf56(CNT); + block_cipher(s, k, npub, 0, CNT, m_bufPos == AD_BLK_LEN_HALF ? (byte)0x14 : (byte)0x15); + } + g8A(s, mac, 0); + } + + @Override + public void processBufferAAD(byte[] input, int inOff) + { + if (twist) + { + Bytes.xorTo(AD_BLK_LEN_HALF, input, inOff, s); + } + else + { + block_cipher(s, k, input, inOff, CNT, (byte)0x08); + } + lfsr_gf56(CNT); + twist = !twist; + } + + @Override + public void processFinalAAD() + { + if (m_aadPos != 0) + { + byte[] mp = new byte[AD_BLK_LEN_HALF]; + int len8 = Math.min(m_aadPos, AD_BLK_LEN_HALF); + pad(m_aad, 0, mp, AD_BLK_LEN_HALF, len8); + if (twist) + { + Bytes.xorTo(AD_BLK_LEN_HALF, mp, s); + } + else + { + block_cipher(s, k, mp, 0, CNT, (byte)0x08); + } + lfsr_gf56(CNT); + } + if (aadOperator.getLen() == 0) + { + lfsr_gf56(CNT); + block_cipher(s, k, npub, 0, CNT, (byte)0x1a); + } + else if ((m_aadPos & 15) != 0) + { + block_cipher(s, k, npub, 0, CNT, (byte)0x1a); + } + else + { + block_cipher(s, k, npub, 0, CNT, (byte)0x18); + } + reset_lfsr_gf56(CNT); + } + + @Override + public void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) + { + g8A(s, output, outOff); + for (int i = 0; i < AD_BLK_LEN_HALF; i++) + { + s[i] ^= input[i + inOff]; + output[i + outOff] ^= input[i + inOff]; + } + lfsr_gf56(CNT); + block_cipher(s, k, npub, 0, CNT, (byte)0x04); + } + + @Override + public void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) + { + g8A(s, output, outOff); + for (int i = 0; i < AD_BLK_LEN_HALF; i++) + { + output[i + outOff] ^= input[i + inOff]; + s[i] ^= output[i + outOff]; + } + lfsr_gf56(CNT); + block_cipher(s, k, npub, 0, CNT, (byte)0x04); + } + + @Override + public void reset() + { + Arrays.clear(s); + reset_lfsr_gf56(CNT); + twist = true; + } + } + + private class RomulusT + implements Instance + { + private final byte[] h = new byte[16]; + private final byte[] g = new byte[16]; + byte[] Z = new byte[16]; + byte[] CNT_Z = new byte[7]; + byte[] LR = new byte[32]; + byte[] T = new byte[16]; + // Initialization function: KDF + byte[] S = new byte[16]; + + @Override + public void processFinalBlock(byte[] output, int outOff) + { + int n = 16; + int messegeLen = dataOperator.getLen() - (forEncryption ? 0 : MAC_SIZE); + if (m_bufPos != 0) + { + int len8 = Math.min(m_bufPos, 16); + System.arraycopy(npub, 0, S, 0, 16); + block_cipher(S, Z, T, 0, CNT, (byte)64); + Bytes.xor(len8, m_buf, S, output, outOff); + System.arraycopy(npub, 0, S, 0, 16); + + lfsr_gf56(CNT); + + byte[] macIn; + int macInOff; + if (forEncryption) + { + macIn = output; + macInOff = outOff; + } + else + { + macIn = m_buf; + macInOff = 0; + } + System.arraycopy(macIn, macInOff, m_aad, m_aadPos, m_bufPos); + Arrays.fill(m_aad, m_aadPos + m_bufPos, AADBufferSize - 1, (byte)0); + m_aad[m_aadPos + BlockSize - 1] = (byte)(m_bufPos & 0xf); + if (m_aadPos == 0) + { + System.arraycopy(npub, 0, m_aad, BlockSize, BlockSize); + n = 0; + } + hirose_128_128_256(h, g, m_aad, 0); + lfsr_gf56(CNT_Z); + } + else if (m_aadPos != 0) + { + if (messegeLen > 0) + { + Arrays.fill(m_aad, BlockSize, AADBufferSize, (byte)0); + } + else if (aadOperator.getLen() != 0) + { + System.arraycopy(npub, 0, m_aad, m_aadPos, 16); + n = 0; + m_aadPos = 0; + } + hirose_128_128_256(h, g, m_aad, 0); + } + else if (messegeLen > 0) + { + Arrays.fill(m_aad, 0, BlockSize, (byte)0); + System.arraycopy(npub, 0, m_aad, BlockSize, BlockSize); + n = 0; + hirose_128_128_256(h, g, m_aad, 0); + } + + if (n == 16) + { + // Pad the nonce and counter + System.arraycopy(npub, 0, m_aad, 0, 16); + System.arraycopy(CNT, 0, m_aad, 16, 7); + Arrays.fill(m_aad, 23, 31, (byte)0); + m_aad[31] = (byte)(23 & 0x1f); + } + else + { + System.arraycopy(CNT_Z, 0, m_aad, 0, 7); + Arrays.fill(m_aad, 7, 31, (byte)0); + m_aad[31] = (byte)(7 & 0x1f); + } + h[0] ^= 2; + hirose_128_128_256(h, g, m_aad, 0); + // Assign the output tag + System.arraycopy(h, 0, LR, 0, 16); + System.arraycopy(g, 0, LR, 16, 16); + Arrays.clear(CNT_Z); + block_cipher(LR, k, LR, 16, CNT_Z, (byte)68); + System.arraycopy(LR, 0, mac, 0, MAC_SIZE); + } + + @Override + public void processBufferAAD(byte[] input, int inOff) + { + hirose_128_128_256(h, g, input, inOff); + } + + @Override + public void processFinalAAD() + { + // Partial block (or in case there is no partial block we add a 0^2n block + Arrays.fill(m_aad, m_aadPos, AADBufferSize - 1, (byte)0); + if (m_aadPos >= 16) + { + m_aad[AADBufferSize - 1] = (byte)(m_aadPos & 0xf); + hirose_128_128_256(h, g, m_aad, 0); + m_aadPos = 0; + } + else if ((m_aadPos >= 0) && (aadOperator.getLen() != 0)) + { + m_aad[BlockSize - 1] = (byte)(m_aadPos & 0xf); + m_aadPos = BlockSize; + } + } + + private void processBuffer(byte[] input, int inOff, byte[] output, int outOff) + { + System.arraycopy(npub, 0, S, 0, 16); + block_cipher(S, Z, T, 0, CNT, (byte)64); + Bytes.xor(AD_BLK_LEN_HALF, S, input, inOff, output, outOff); + System.arraycopy(npub, 0, S, 0, 16); + block_cipher(S, Z, T, 0, CNT, (byte)65); + System.arraycopy(S, 0, Z, 0, 16); + lfsr_gf56(CNT); + } + + private void processAfterAbsorbCiphertext() + { + if (m_aadPos == BlockSize) + { + hirose_128_128_256(h, g, m_aad, 0); + m_aadPos = 0; + } + else + { + m_aadPos = BlockSize; + } + lfsr_gf56(CNT_Z); + } + + @Override + public void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) + { + processBuffer(input, inOff, output, outOff); + // ipad_256(ipad*_128(A)||ipad*_128(C)||N|| CNT + System.arraycopy(output, outOff, m_aad, m_aadPos, BlockSize); + processAfterAbsorbCiphertext(); + } + + @Override + public void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) + { + processBuffer(input, inOff, output, outOff); + // ipad_256(ipad*_128(A)||ipad*_128(C)||N|| CNT + System.arraycopy(input, inOff, m_aad, m_aadPos, BlockSize); + processAfterAbsorbCiphertext(); + } + + @Override + public void reset() + { + Arrays.clear(h); + Arrays.clear(g); + Arrays.clear(LR); + Arrays.clear(T); + Arrays.clear(S); + Arrays.clear(CNT_Z); + reset_lfsr_gf56(CNT); + System.arraycopy(npub, 0, Z, 0, IV_SIZE); + block_cipher(Z, k, T, 0, CNT_Z, (byte)66); + reset_lfsr_gf56(CNT_Z); + } + } + + private static void skinny_128_384_plus_enc(byte[] input, byte[] userkey) + { + byte[][] state = new byte[4][4]; + byte[][][] keyCells = new byte[3][4][4]; + int i, j, q, r; + byte pos, tmp; + byte[][][] keyCells_tmp = new byte[3][4][4]; + for (i = 0; i < 4; ++i) + { + q = i << 2; + System.arraycopy(input, q, state[i], 0, 4); + System.arraycopy(userkey, q, keyCells[0][i], 0, 4); + System.arraycopy(userkey, q + 16, keyCells[1][i], 0, 4); + System.arraycopy(userkey, q + 32, keyCells[2][i], 0, 4); + } + for (int round = 0; round < 40; round++) + { + //SubCell8; + for (i = 0; i < 4; i++) + { + for (j = 0; j < 4; j++) + { + state[i][j] = sbox_8[state[i][j] & 0xFF]; + } + } + //AddConstants + state[0][0] ^= (RC[round] & 0xf); + state[1][0] ^= ((RC[round] >>> 4) & 0x3); + state[2][0] ^= 0x2; + //AddKey + // apply the subtweakey to the internal state + for (i = 0; i <= 1; i++) + { + for (j = 0; j < 4; j++) + { + state[i][j] ^= keyCells[0][i][j] ^ keyCells[1][i][j] ^ keyCells[2][i][j]; + } + } + for (i = 0; i < 4; i++) + { + for (j = 0; j < 4; j++) + { + //application of the TWEAKEY permutation + pos = TWEAKEY_P[j + (i << 2)]; + q = pos >>> 2; + r = pos & 3; + keyCells_tmp[0][i][j] = keyCells[0][q][r]; + keyCells_tmp[1][i][j] = keyCells[1][q][r]; + keyCells_tmp[2][i][j] = keyCells[2][q][r]; + } + } + // update the subtweakey states with the LFSRs + for (i = 0; i <= 1; i++) + { + for (j = 0; j < 4; j++) + { + //application of LFSRs for TK updates + keyCells[0][i][j] = keyCells_tmp[0][i][j]; + tmp = keyCells_tmp[1][i][j]; + keyCells[1][i][j] = (byte)(((tmp << 1) & 0xFE) ^ ((tmp >>> 7) & 0x01) ^ ((tmp >>> 5) & 0x01)); + tmp = keyCells_tmp[2][i][j]; + keyCells[2][i][j] = (byte)(((tmp >>> 1) & 0x7F) ^ ((tmp << 7) & 0x80) ^ ((tmp << 1) & 0x80)); + } + } + for (; i < 4; ++i) + { + for (j = 0; j < 4; j++) + { + keyCells[0][i][j] = keyCells_tmp[0][i][j]; + keyCells[1][i][j] = keyCells_tmp[1][i][j]; + keyCells[2][i][j] = keyCells_tmp[2][i][j]; + } + } + //ShiftRows(state); + tmp = state[1][3]; + state[1][3] = state[1][2]; + state[1][2] = state[1][1]; + state[1][1] = state[1][0]; + state[1][0] = tmp; + tmp = state[2][0]; + state[2][0] = state[2][2]; + state[2][2] = tmp; + tmp = state[2][1]; + state[2][1] = state[2][3]; + state[2][3] = tmp; + tmp = state[3][0]; + state[3][0] = state[3][1]; + state[3][1] = state[3][2]; + state[3][2] = state[3][3]; + state[3][3] = tmp; + //MixColumn(state); + for (j = 0; j < 4; j++) + { + state[1][j] ^= state[2][j]; + state[2][j] ^= state[0][j]; + state[3][j] ^= state[2][j]; + tmp = state[3][j]; + state[3][j] = state[2][j]; + state[2][j] = state[1][j]; + state[1][j] = state[0][j]; + state[0][j] = tmp; + } + } //The last subtweakey should not be added + for (i = 0; i < 16; i++) + { + input[i] = (byte)(state[i >>> 2][i & 0x3] & 0xFF); + } + } + + + // Padding function: pads the byte length of the message mod 16 to the last incomplete block. +// For complete blocks it returns the same block. + void pad(byte[] m, int mOff, byte[] mp, int l, int len8) + { + mp[l - 1] = (byte)(len8 & 0x0f); + System.arraycopy(m, mOff, mp, 0, len8); + } + + // G(S): generates the key stream from the internal state by multiplying the state S by the constant matrix G + void g8A(byte[] s, byte[] c, int cOff) + { + int len = Math.min(c.length - cOff, 16); + for (int i = 0; i < len; i++) + { + c[i + cOff] = (byte)(((s[i] & 0xFF) >>> 1) ^ (s[i] & 0x80) ^ ((s[i] & 0x01) << 7)); + } + } + + // Rho(S,M): pads an M block and outputs S'= M xor S and C = M xor G(S) + // Inverse-Rho(S,M): pads a C block and outputs S'= C xor G(S) xor S and M = C xor G(S) + void rho(byte[] m, int mOff, byte[] c, int cOff, byte[] s, int len8) + { + byte[] mp = new byte[16]; + pad(m, mOff, mp, AD_BLK_LEN_HALF, len8); + g8A(s, c, cOff); + if (forEncryption) + { + for (int i = 0; i < AD_BLK_LEN_HALF; i++) + { + s[i] ^= mp[i]; + if (i < len8) + { + c[i + cOff] ^= mp[i]; + } + else + { + c[i + cOff] = 0; + } + } + } + else + { + for (int i = 0; i < AD_BLK_LEN_HALF; i++) + { + s[i] ^= mp[i]; + if (i < len8 && i + cOff < c.length) + { + s[i] ^= c[i + cOff]; + c[i + cOff] ^= mp[i]; + } + } + } + } + + // Applies CNT'=2 * CNT (mod GF(2^56)), where GF(2^56) is defined using the irreducible polynomial +// x^56 + x^7 + x^4 + x^2 + 1 + void lfsr_gf56(byte[] CNT) + { + byte fb0 = (byte)((CNT[6] & 0xFF) >>> 7); + CNT[6] = (byte)(((CNT[6] & 0xFF) << 1) | ((CNT[5] & 0xFF) >>> 7)); + CNT[5] = (byte)(((CNT[5] & 0xFF) << 1) | ((CNT[4] & 0xFF) >>> 7)); + CNT[4] = (byte)((((CNT[4] & 0xFF) << 1) | ((CNT[3] & 0xFF) >>> 7))); + CNT[3] = (byte)(((CNT[3] & 0xFF) << 1) | ((CNT[2] & 0xFF) >>> 7)); + CNT[2] = (byte)(((CNT[2] & 0xFF) << 1) | ((CNT[1] & 0xFF) >>> 7)); + CNT[1] = (byte)(((CNT[1] & 0xFF) << 1) | ((CNT[0] & 0xFF) >>> 7)); + if (fb0 == 1) + { + CNT[0] = (byte)(((CNT[0] & 0xFF) << 1) ^ 0x95); + } + else + { + CNT[0] = (byte)(((CNT[0] & 0xFF) << 1)); + } + } + + // An interface between Romulus and the underlying TBC + void block_cipher(byte[] s, byte[] K, byte[] T, int tOff, byte[] CNT, byte D) + { + byte[] KT = new byte[48]; + // Combines the secret key, counter and domain bits to form the full 384-bit tweakey + System.arraycopy(CNT, 0, KT, 0, 7); + KT[7] = D; + System.arraycopy(T, tOff, KT, 16, 16); + System.arraycopy(K, 0, KT, 32, 16); + skinny_128_384_plus_enc(s, KT); + } + + private void reset_lfsr_gf56(byte[] CNT) + { + CNT[0] = 0x01; + Arrays.fill(CNT, 1, 7, (byte)0); + } + + public static void hirose_128_128_256(RomulusDigest.Friend friend, byte[] h, byte[] g, byte[] m, int mOff) + { + if (null == friend) + { + throw new NullPointerException("This method is only for use by RomulusDigest"); + } + hirose_128_128_256(h, g, m, mOff); + } + + // The hirose double-block length (DBL) compression function. + static void hirose_128_128_256(byte[] h, byte[] g, byte[] m, int mOff) + { + byte[] key = new byte[48]; + byte[] hh = new byte[16]; + int i; + // assign the key for the hirose compresison function + System.arraycopy(g, 0, key, 0, 16); + System.arraycopy(h, 0, g, 0, 16); + System.arraycopy(h, 0, hh, 0, 16); + g[0] ^= 0x01; + System.arraycopy(m, mOff, key, 16, 32); + skinny_128_384_plus_enc(h, key); + skinny_128_384_plus_enc(g, key); + for (i = 0; i < 16; i++) + { + h[i] ^= hh[i]; + g[i] ^= hh[i]; + } + g[0] ^= 0x01; + } + + @Override + protected void init(byte[] key, byte[] iv) + throws IllegalArgumentException + { + npub = iv; + k = key; + } + + protected void finishAAD(State nextState, boolean isDoFinal) + { + // State indicates whether we ever received AAD + finishAAD1(nextState); + } + + protected void processBufferAAD(byte[] input, int inOff) + { + instance.processBufferAAD(input, inOff); + } + + protected void processFinalAAD() + { + instance.processFinalAAD(); + } + + @Override + protected void processFinalBlock(byte[] output, int outOff) + { + instance.processFinalBlock(output, outOff); + } + + @Override + protected void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) + { + instance.processBufferEncrypt(input, inOff, output, outOff); + } + + @Override + protected void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) + { + instance.processBufferDecrypt(input, inOff, output, outOff); + } + + protected void reset(boolean clearMac) + { + super.reset(clearMac); + instance.reset(); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/SM2Engine.java b/core/src/main/java/org/bouncycastle/crypto/engines/SM2Engine.java index fdf2b50883..8ac88aede1 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/SM2Engine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/SM2Engine.java @@ -95,7 +95,7 @@ public void init(boolean forEncryption, CipherParameters param) ecParams = ecKey.getParameters(); } - curveLength = (ecParams.getCurve().getFieldSize() + 7) / 8; + curveLength = ecParams.getCurve().getFieldElementEncodingLength(); CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties("SM2", ConstraintUtils.bitsOfSecurityFor(ecParams.getCurve()), ecKey, Utils.getPurpose(forEncryption))); } diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/SparkleEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/SparkleEngine.java index a1caff26a7..6e71b16b7b 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/SparkleEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/SparkleEngine.java @@ -1,16 +1,6 @@ package org.bouncycastle.crypto.engines; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; import org.bouncycastle.crypto.digests.SparkleDigest; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.AEADParameters; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; import org.bouncycastle.util.Pack; @@ -21,7 +11,7 @@ * Specification: https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/sparkle-spec-final.pdf */ public class SparkleEngine - implements AEADCipher + extends AEADBaseEngine { public enum SparkleParameters { @@ -31,46 +21,19 @@ public enum SparkleParameters SCHWAEMM256_256 } - private enum State - { - Uninitialized, - EncInit, - EncAad, - EncData, - EncFinal, - DecInit, - DecAad, - DecData, - DecFinal, - } + private static final int[] RCON = {0xB7E15162, 0xBF715880, 0x38B4DA56, 0x324E7738, 0xBB1185EB, 0x4F7C7B57, + 0xCFBFA1C8, 0xC2B3293D}; - private static final int[] RCON = { 0xB7E15162, 0xBF715880, 0x38B4DA56, 0x324E7738, 0xBB1185EB, 0x4F7C7B57, - 0xCFBFA1C8, 0xC2B3293D }; - - private String algorithmName; private final int[] state; private final int[] k; private final int[] npub; - private byte[] tag; private boolean encrypted; - private State m_state = State.Uninitialized; - private byte[] initialAssociatedText; - - private final int m_bufferSizeDecrypt; - private final byte[] m_buf; - private int m_bufPos = 0; - - private final int SCHWAEMM_KEY_LEN; - private final int SCHWAEMM_NONCE_LEN; private final int SPARKLE_STEPS_SLIM; private final int SPARKLE_STEPS_BIG; private final int KEY_WORDS; - private final int KEY_BYTES; private final int TAG_WORDS; - private final int TAG_BYTES; private final int STATE_WORDS; private final int RATE_WORDS; - private final int RATE_BYTES; private final int CAP_MASK; private final int _A0; private final int _A1; @@ -82,6 +45,8 @@ public SparkleEngine(SparkleParameters sparkleParameters) int SPARKLE_STATE; int SCHWAEMM_TAG_LEN; int SPARKLE_CAPACITY; + int SCHWAEMM_KEY_LEN; + int SCHWAEMM_NONCE_LEN; switch (sparkleParameters) { case SCHWAEMM128_128: @@ -128,12 +93,12 @@ public SparkleEngine(SparkleParameters sparkleParameters) throw new IllegalArgumentException("Invalid definition of SCHWAEMM instance"); } KEY_WORDS = SCHWAEMM_KEY_LEN >>> 5; - KEY_BYTES = SCHWAEMM_KEY_LEN >>> 3; + KEY_SIZE = SCHWAEMM_KEY_LEN >>> 3; TAG_WORDS = SCHWAEMM_TAG_LEN >>> 5; - TAG_BYTES = SCHWAEMM_TAG_LEN >>> 3; + MAC_SIZE = SCHWAEMM_TAG_LEN >>> 3; STATE_WORDS = SPARKLE_STATE >>> 5; RATE_WORDS = SCHWAEMM_NONCE_LEN >>> 5; - RATE_BYTES = SCHWAEMM_NONCE_LEN >>> 3; + IV_SIZE = SCHWAEMM_NONCE_LEN >>> 3; int CAP_BRANS = SPARKLE_CAPACITY >>> 6; int CAP_WORDS = SPARKLE_CAPACITY >>> 5; CAP_MASK = RATE_WORDS > CAP_WORDS ? CAP_WORDS - 1 : -1; @@ -144,271 +109,30 @@ public SparkleEngine(SparkleParameters sparkleParameters) state = new int[STATE_WORDS]; k = new int[KEY_WORDS]; npub = new int[RATE_WORDS]; - - m_bufferSizeDecrypt = RATE_BYTES + TAG_BYTES; - m_buf = new byte[m_bufferSizeDecrypt]; - - // Relied on by processBytes method for decryption -// assert RATE_BYTES >= TAG_BYTES; - } - - public int getKeyBytesSize() - { - return KEY_BYTES; - } - - public int getIVBytesSize() - { - return RATE_BYTES; + AADBufferSize = BlockSize = IV_SIZE; + setInnerMembers(ProcessingBufferType.Buffered, AADOperatorType.Default, DataOperatorType.Default); } - public String getAlgorithmName() - { - return algorithmName; - } - - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] key, byte[] iv) throws IllegalArgumentException { - KeyParameter key = null; - byte[] iv; - - if (params instanceof AEADParameters) - { - AEADParameters aeadParameters = (AEADParameters)params; - key = aeadParameters.getKey(); - iv = aeadParameters.getNonce(); - initialAssociatedText = aeadParameters.getAssociatedText(); - - int macSizeBits = aeadParameters.getMacSize(); - if (macSizeBits != TAG_BYTES * 8) - throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits); - } - else if (params instanceof ParametersWithIV) - { - ParametersWithIV withIV = (ParametersWithIV)params; - CipherParameters ivParameters = withIV.getParameters(); - if (ivParameters instanceof KeyParameter) - { - key = (KeyParameter)ivParameters; - } - iv = withIV.getIV(); - initialAssociatedText = null; - } - else - { - throw new IllegalArgumentException("invalid parameters passed to Sparkle"); - } - - if (key == null) - { - throw new IllegalArgumentException("Sparkle init parameters must include a key"); - } - - int expectedKeyLength = KEY_WORDS * 4; - if (expectedKeyLength != key.getKeyLength()) - { - throw new IllegalArgumentException(algorithmName + " requires exactly " + expectedKeyLength + " bytes of key"); - } - - int expectedIVLength = RATE_WORDS * 4; - if (iv == null || expectedIVLength != iv.length) - { - throw new IllegalArgumentException(algorithmName + " requires exactly " + expectedIVLength + " bytes of IV"); - } - - Pack.littleEndianToInt(key.getKey(), 0, k); + Pack.littleEndianToInt(key, 0, k); Pack.littleEndianToInt(iv, 0, npub); - - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - - m_state = forEncryption ? State.EncInit : State.DecInit; - - reset(); } - public void processAADByte(byte in) + protected void finishAAD(State nextState, boolean isDoFinal) { - checkAAD(); - - if (m_bufPos == RATE_BYTES) - { - processBufferAAD(m_buf, 0); - m_bufPos = 0; - } - - m_buf[m_bufPos++] = in; + finishAAD2(nextState); } - public void processAADBytes(byte[] in, int inOff, int len) + @Override + protected void processFinalBlock(byte[] output, int outOff) { - if (inOff > in.length - len) - { - throw new DataLengthException("input buffer too short"); - } - - // Don't enter AAD state until we actually get input - if (len <= 0) - return; - - checkAAD(); - - if (m_bufPos > 0) - { - int available = RATE_BYTES - m_bufPos; - if (len <= available) - { - System.arraycopy(in, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return; - } - - System.arraycopy(in, inOff, m_buf, m_bufPos, available); - inOff += available; - len -= available; - - processBufferAAD(m_buf, 0); - //m_bufPos = 0; - } - - while (len > RATE_BYTES) - { - processBufferAAD(in, inOff); - inOff += RATE_BYTES; - len -= RATE_BYTES; - } - - System.arraycopy(in, inOff, m_buf, 0, len); - m_bufPos = len; - } - - public int processByte(byte in, byte[] out, int outOff) - throws DataLengthException - { - return processBytes(new byte[]{ in }, 0, 1, out, outOff); - } - - public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) - throws DataLengthException - { - if (inOff > in.length - len) - { - throw new DataLengthException("input buffer too short"); - } - - boolean forEncryption = checkData(); - - int resultLength = 0; - - if (forEncryption) - { - if (m_bufPos > 0) - { - int available = RATE_BYTES - m_bufPos; - if (len <= available) - { - System.arraycopy(in, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return 0; - } - - System.arraycopy(in, inOff, m_buf, m_bufPos, available); - inOff += available; - len -= available; - - processBufferEncrypt(m_buf, 0, out, outOff); - resultLength = RATE_BYTES; - //m_bufPos = 0; - } - - while (len > RATE_BYTES) - { - processBufferEncrypt(in, inOff, out, outOff + resultLength); - inOff += RATE_BYTES; - len -= RATE_BYTES; - resultLength += RATE_BYTES; - } - } - else - { - int available = m_bufferSizeDecrypt - m_bufPos; - if (len <= available) - { - System.arraycopy(in, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return 0; - } - - if (m_bufPos > RATE_BYTES) - { - processBufferDecrypt(m_buf, 0, out, outOff); - m_bufPos -= RATE_BYTES; - System.arraycopy(m_buf, RATE_BYTES, m_buf, 0, m_bufPos); - resultLength = RATE_BYTES; - - available += RATE_BYTES; - if (len <= available) - { - System.arraycopy(in, inOff, m_buf, m_bufPos, len); - m_bufPos += len; - return resultLength; - } - } - - available = RATE_BYTES - m_bufPos; - System.arraycopy(in, inOff, m_buf, m_bufPos, available); - inOff += available; - len -= available; - processBufferDecrypt(m_buf, 0, out, outOff + resultLength); - resultLength += RATE_BYTES; - //m_bufPos = 0; - - while (len > m_bufferSizeDecrypt) - { - processBufferDecrypt(in, inOff, out, outOff + resultLength); - inOff += RATE_BYTES; - len -= RATE_BYTES; - resultLength += RATE_BYTES; - } - } - - System.arraycopy(in, inOff, m_buf, 0, len); - m_bufPos = len; - - return resultLength; - } - - public int doFinal(byte[] out, int outOff) - throws IllegalStateException, InvalidCipherTextException - { - boolean forEncryption = checkData(); - - int resultLength; - if (forEncryption) - { - resultLength = m_bufPos + TAG_BYTES; - } - else - { - if (m_bufPos < TAG_BYTES) - throw new InvalidCipherTextException("data too short"); - - m_bufPos -= TAG_BYTES; - - resultLength = m_bufPos; - } - - if (outOff > out.length - resultLength) - { - throw new OutputLengthException("output buffer too short"); - } - if (encrypted || m_bufPos > 0) { // Encryption of Last Block // addition of ant M2 or M3 to the state - state[STATE_WORDS - 1] ^= ((m_bufPos < RATE_BYTES) ? _M2 : _M3); + state[STATE_WORDS - 1] ^= ((m_bufPos < IV_SIZE) ? _M2 : _M3); // combined Rho and rate-whitening (incl. padding) // Rho and rate-whitening for the encryption of the last plaintext block. Since // this last block may require padding, it is always copied to a buffer. @@ -417,7 +141,7 @@ public int doFinal(byte[] out, int outOff) { buffer[i >>> 2] |= (m_buf[i] & 0xFF) << ((i & 3) << 3); } - if (m_bufPos < RATE_BYTES) + if (m_bufPos < IV_SIZE) { if (!forEncryption) { @@ -430,26 +154,26 @@ public int doFinal(byte[] out, int outOff) } for (int i = 0; i < RATE_WORDS / 2; ++i) { - int j = i + RATE_WORDS /2; + int j = i + RATE_WORDS / 2; int s_i = state[i]; int s_j = state[j]; if (forEncryption) { - state[i] = s_j ^ buffer[i] ^ state[RATE_WORDS + i]; + state[i] = s_j ^ buffer[i] ^ state[RATE_WORDS + i]; state[j] = s_i ^ s_j ^ buffer[j] ^ state[RATE_WORDS + (j & CAP_MASK)]; } else { state[i] = s_i ^ s_j ^ buffer[i] ^ state[RATE_WORDS + i]; - state[j] = s_i ^ buffer[j] ^ state[RATE_WORDS + (j & CAP_MASK)]; + state[j] = s_i ^ buffer[j] ^ state[RATE_WORDS + (j & CAP_MASK)]; } buffer[i] ^= s_i; buffer[j] ^= s_j; } for (int i = 0; i < m_bufPos; ++i) { - out[outOff++] = (byte)(buffer[i >>> 2] >>> ((i & 3) << 3)); + output[outOff++] = (byte)(buffer[i >>> 2] >>> ((i & 3) << 3)); } // execute SPARKLE with big number of steps sparkle_opt(state, SPARKLE_STEPS_BIG); @@ -459,142 +183,11 @@ public int doFinal(byte[] out, int outOff) { state[RATE_WORDS + i] ^= k[i]; } - tag = new byte[TAG_BYTES]; - Pack.intToLittleEndian(state, RATE_WORDS, TAG_WORDS, tag, 0); - if (forEncryption) - { - System.arraycopy(tag, 0, out, outOff, TAG_BYTES); - } - else - { - if (!Arrays.constantTimeAreEqual(TAG_BYTES, tag, 0, m_buf, m_bufPos)) - { - throw new InvalidCipherTextException(algorithmName + " mac does not match"); - } - } - reset(!forEncryption); - return resultLength; - } - - public byte[] getMac() - { - return tag; - } - - public int getUpdateOutputSize(int len) - { - // The -1 is to account for the lazy processing of a full buffer - int total = Math.max(0, len) - 1; - - switch (m_state) - { - case DecInit: - case DecAad: - total = Math.max(0, total - TAG_BYTES); - break; - case DecData: - case DecFinal: - total = Math.max(0, total + m_bufPos - TAG_BYTES); - break; - case EncData: - case EncFinal: - total = Math.max(0, total + m_bufPos); - break; - default: - break; - } - - return total - total % RATE_BYTES; - } - - public int getOutputSize(int len) - { - int total = Math.max(0, len); - - switch (m_state) - { - case DecInit: - case DecAad: - return Math.max(0, total - TAG_BYTES); - case DecData: - case DecFinal: - return Math.max(0, total + m_bufPos - TAG_BYTES); - case EncData: - case EncFinal: - return total + m_bufPos + TAG_BYTES; - default: - return total + TAG_BYTES; - } - } - - public void reset() - { - reset(true); - } - - private void checkAAD() - { - switch (m_state) - { - case DecInit: - m_state = State.DecAad; - break; - case EncInit: - m_state = State.EncAad; - break; - case DecAad: - case EncAad: - break; - case EncFinal: - throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); - default: - throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); - } - } + Pack.intToLittleEndian(state, RATE_WORDS, TAG_WORDS, mac, 0); - private boolean checkData() - { - switch (m_state) - { - case DecInit: - case DecAad: - finishAAD(State.DecData); - return false; - case EncInit: - case EncAad: - finishAAD(State.EncData); - return true; - case DecData: - return false; - case EncData: - return true; - case EncFinal: - throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); - default: - throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); - } } - private void finishAAD(State nextState) - { - // State indicates whether we ever received AAD - switch (m_state) - { - case DecAad: - case EncAad: - { - processFinalAAD(); - break; - } - default: - break; - } - - m_bufPos = 0; - m_state = nextState; - } - - private void processBufferAAD(byte[] buffer, int bufOff) + protected void processBufferAAD(byte[] buffer, int bufOff) { for (int i = 0; i < RATE_WORDS / 2; ++i) { @@ -606,22 +199,15 @@ private void processBufferAAD(byte[] buffer, int bufOff) int d_i = Pack.littleEndianToInt(buffer, bufOff + (i * 4)); int d_j = Pack.littleEndianToInt(buffer, bufOff + (j * 4)); - state[i] = s_j ^ d_i ^ state[RATE_WORDS + i]; + state[i] = s_j ^ d_i ^ state[RATE_WORDS + i]; state[j] = s_i ^ s_j ^ d_j ^ state[RATE_WORDS + (j & CAP_MASK)]; } sparkle_opt(state, SPARKLE_STEPS_SLIM); } - private void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int outOff) + protected void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int outOff) { -// assert bufOff <= buffer.length - RATE_BYTES; - - if (outOff > output.length - RATE_BYTES) - { - throw new OutputLengthException("output buffer too short"); - } - for (int i = 0; i < RATE_WORDS / 2; ++i) { int j = i + (RATE_WORDS / 2); @@ -633,7 +219,7 @@ private void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int int d_j = Pack.littleEndianToInt(buffer, bufOff + (j * 4)); state[i] = s_i ^ s_j ^ d_i ^ state[RATE_WORDS + i]; - state[j] = s_i ^ d_j ^ state[RATE_WORDS + (j & CAP_MASK)]; + state[j] = s_i ^ d_j ^ state[RATE_WORDS + (j & CAP_MASK)]; Pack.intToLittleEndian(d_i ^ s_i, output, outOff + (i * 4)); Pack.intToLittleEndian(d_j ^ s_j, output, outOff + (j * 4)); @@ -644,15 +230,8 @@ private void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int encrypted = true; } - private void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int outOff) + protected void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int outOff) { -// assert bufOff <= buffer.length - RATE_BYTES; - - if (outOff > output.length - RATE_BYTES) - { - throw new OutputLengthException("output buffer too short"); - } - for (int i = 0; i < RATE_WORDS / 2; ++i) { int j = i + (RATE_WORDS / 2); @@ -663,7 +242,7 @@ private void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int int d_i = Pack.littleEndianToInt(buffer, bufOff + (i * 4)); int d_j = Pack.littleEndianToInt(buffer, bufOff + (j * 4)); - state[i] = s_j ^ d_i ^ state[RATE_WORDS + i]; + state[i] = s_j ^ d_i ^ state[RATE_WORDS + i]; state[j] = s_i ^ s_j ^ d_j ^ state[RATE_WORDS + (j & CAP_MASK)]; Pack.intToLittleEndian(d_i ^ s_i, output, outOff + (i * 4)); @@ -675,19 +254,16 @@ private void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int encrypted = true; } - private void processFinalAAD() + protected void processFinalAAD() { // addition of constant A0 or A1 to the state - if (m_bufPos < RATE_BYTES) + if (m_aadPos < BlockSize) { state[STATE_WORDS - 1] ^= _A0; // padding - m_buf[m_bufPos] = (byte)0x80; - while (++m_bufPos < RATE_BYTES) - { - m_buf[m_bufPos] = 0x00; - } + m_aad[m_aadPos++] = (byte)0x80; + Arrays.fill(m_aad, m_aadPos, BlockSize, (byte)0); } else { @@ -701,46 +277,20 @@ private void processFinalAAD() int s_i = state[i]; int s_j = state[j]; - int d_i = Pack.littleEndianToInt(m_buf, i * 4); - int d_j = Pack.littleEndianToInt(m_buf, j * 4); + int d_i = Pack.littleEndianToInt(m_aad, i * 4); + int d_j = Pack.littleEndianToInt(m_aad, j * 4); - state[i] = s_j ^ d_i ^ state[RATE_WORDS + i]; + state[i] = s_j ^ d_i ^ state[RATE_WORDS + i]; state[j] = s_i ^ s_j ^ d_j ^ state[RATE_WORDS + (j & CAP_MASK)]; } sparkle_opt(state, SPARKLE_STEPS_BIG); } - private void reset(boolean clearMac) - { - if (clearMac) - { - tag = null; - } - Arrays.clear(m_buf); - m_bufPos = 0; + protected void reset(boolean clearMac) + { encrypted = false; - - switch (m_state) - { - case DecInit: - case EncInit: - break; - case DecAad: - case DecData: - case DecFinal: - m_state = State.DecInit; - break; - case EncAad: - case EncData: - case EncFinal: - m_state = State.EncFinal; - return; - default: - throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); - } - // The Initialize function loads nonce and key into the state and executes the // SPARKLE permutation with the big number of steps. // load nonce into the rate-part of the state @@ -750,10 +300,7 @@ private void reset(boolean clearMac) sparkle_opt(state, SPARKLE_STEPS_BIG); - if (initialAssociatedText != null) - { - processAADBytes(initialAssociatedText, 0, initialAssociatedText.length); - } + super.reset(clearMac); } private static int ELL(int x) @@ -765,10 +312,17 @@ private static void sparkle_opt(int[] state, int steps) { switch (state.length) { - case 8: sparkle_opt8 (state, steps); break; - case 12: sparkle_opt12(state, steps); break; - case 16: sparkle_opt16(state, steps); break; - default: throw new IllegalStateException(); + case 8: + sparkle_opt8(state, steps); + break; + case 12: + sparkle_opt12(state, steps); + break; + case 16: + sparkle_opt16(state, steps); + break; + default: + throw new IllegalStateException(); } } @@ -1037,7 +591,7 @@ static void sparkle_opt12(int[] state, int steps) state[10] = s10; state[11] = s11; } - + public static void sparkle_opt12(SparkleDigest.Friend friend, int[] state, int steps) { if (null == friend) diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/XoodyakEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/XoodyakEngine.java index 41cc3bce50..b22e39eeea 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/XoodyakEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/XoodyakEngine.java @@ -1,320 +1,144 @@ package org.bouncycastle.crypto.engines; -import java.io.ByteArrayOutputStream; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.OutputLengthException; -import org.bouncycastle.crypto.constraints.DefaultServiceProperties; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.crypto.digests.XoodyakDigest; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Bytes; +import org.bouncycastle.util.Integers; import org.bouncycastle.util.Pack; /** - * Xoodyak v1, https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/xoodyak-spec-final.pdf + * Xoodyak v1, *

    - * Xoodyak with reference to C Reference Impl from: https://github.com/XKCP/XKCP + * Xoodyak with reference to C Reference Impl from: *

    */ public class XoodyakEngine - implements AEADCipher + extends AEADBaseEngine { - private boolean forEncryption; - private byte[] state; + private final byte[] state; private int phase; - private MODE mode; - private int Rabsorb; - private final int f_bPrime = 48; - private final int Rkout = 24; + private int mode; + private static final int f_bPrime_1 = 47; private byte[] K; private byte[] iv; - private final int PhaseDown = 1; - private final int PhaseUp = 2; - private final int NLANES = 12; - private final int NROWS = 3; - private final int NCOLUMS = 4; - private final int MAXROUNDS = 12; - private final int TAGLEN = 16; - final int Rkin = 44; - private byte[] tag; - private final int[] RC = {0x00000058, 0x00000038, 0x000003C0, 0x000000D0, 0x00000120, 0x00000014, 0x00000060, + private static final int PhaseUp = 2; + private static final int PhaseDown = 1; + private static final int[] RC = {0x00000058, 0x00000038, 0x000003C0, 0x000000D0, 0x00000120, 0x00000014, 0x00000060, 0x0000002C, 0x00000380, 0x000000F0, 0x000001A0, 0x00000012}; - private boolean aadFinished; private boolean encrypted; - private boolean initialised = false; - private final ByteArrayOutputStream aadData = new ByteArrayOutputStream(); - private final ByteArrayOutputStream message = new ByteArrayOutputStream(); + private byte aadcd; + private static final int ModeKeyed = 0; + private static final int ModeHash = 1; - enum MODE + public XoodyakEngine() { - ModeHash, - ModeKeyed + algorithmName = "Xoodyak AEAD"; + KEY_SIZE = IV_SIZE = MAC_SIZE = 16; + BlockSize = 24; + AADBufferSize = 44; + state = new byte[48]; + setInnerMembers(ProcessingBufferType.Immediate, AADOperatorType.Default, DataOperatorType.Counter); } @Override - public void init(boolean forEncryption, CipherParameters params) + protected void init(byte[] key, byte[] iv) throws IllegalArgumentException { - this.forEncryption = forEncryption; - if (!(params instanceof ParametersWithIV)) - { - throw new IllegalArgumentException("Xoodyak init parameters must include an IV"); - } - ParametersWithIV ivParams = (ParametersWithIV)params; - iv = ivParams.getIV(); - if (iv == null || iv.length != 16) - { - throw new IllegalArgumentException("Xoodyak requires exactly 16 bytes of IV"); - } - if (!(ivParams.getParameters() instanceof KeyParameter)) - { - throw new IllegalArgumentException("Xoodyak init parameters must include a key"); - } - KeyParameter key = (KeyParameter)ivParams.getParameters(); - K = key.getKey(); - if (K.length != 16) - { - throw new IllegalArgumentException("Xoodyak key must be 128 bits long"); - } - CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( - this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); - state = new byte[48]; - tag = new byte[TAGLEN]; - initialised = true; - reset(); + K = key; + this.iv = iv; } - @Override - public String getAlgorithmName() + protected void processBufferAAD(byte[] input, int inOff) { - return "Xoodyak AEAD"; + AbsorbAny(input, inOff, AADBufferSize, aadcd); + aadcd = 0; } - @Override - public void processAADByte(byte input) + protected void processFinalAAD() { - if (aadFinished) - { - throw new IllegalArgumentException("AAD cannot be added after reading a full block(" + getBlockSize() + - " bytes) of input for " + (forEncryption ? "encryption" : "decryption")); - } - aadData.write(input); + AbsorbAny(m_aad, 0, m_aadPos, aadcd); } @Override - public void processAADBytes(byte[] input, int inOff, int len) + protected void finishAAD(State nextState, boolean isDoFinal) { - if (aadFinished) - { - throw new IllegalArgumentException("AAD cannot be added after reading a full block(" + getBlockSize() + - " bytes) of input for " + (forEncryption ? "encryption" : "decryption")); - } - if ((inOff + len) > input.length) - { - throw new DataLengthException("input buffer too short"); - } - aadData.write(input, inOff, len); + finishAAD3(nextState, isDoFinal); } - @Override - public int processByte(byte input, byte[] output, int outOff) - throws DataLengthException + protected void processBufferEncrypt(byte[] input, int inOff, byte[] output, int outOff) { - return processBytes(new byte[]{input}, 0, 1, output, outOff); + up(mode, state, encrypted ? 0 : 0x80); /* Up without extract */ + /* Extract from Up and Add */ + Bytes.xor(BlockSize, state, input, inOff, output, outOff); + down(mode, state, input, inOff, BlockSize, 0x00); + phase = PhaseDown; + encrypted = true; } - private void processAAD() + protected void processBufferDecrypt(byte[] input, int inOff, byte[] output, int outOff) { - if (!aadFinished) - { - byte[] ad = aadData.toByteArray(); - AbsorbAny(ad, 0, ad.length, Rabsorb, 0x03); - aadFinished = true; - } + up(mode, state, encrypted ? 0 : 0x80); /* Up without extract */ + /* Extract from Up and Add */ + Bytes.xor(BlockSize, state, input, inOff, output, outOff); + down(mode, state, output, outOff, BlockSize, 0x00); + phase = PhaseDown; + encrypted = true; } @Override - public int processBytes(byte[] input, int inOff, int len, byte[] output, int outOff) - throws DataLengthException + protected void processFinalBlock(byte[] output, int outOff) { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - if (mode != MODE.ModeKeyed) + if (m_bufPos != 0 || !encrypted) { - throw new IllegalArgumentException("Xoodyak has not been initialised"); - } - if (inOff + len > input.length) - { - throw new DataLengthException("input buffer too short"); - } - message.write(input, inOff, len); - int blockLen = message.size() - (forEncryption ? 0 : TAGLEN); - if (blockLen >= getBlockSize()) - { - byte[] blocks = message.toByteArray(); - len = blockLen / getBlockSize() * getBlockSize(); - if (len + outOff > output.length) - { - throw new OutputLengthException("output buffer is too short"); - } - processAAD(); - encrypt(blocks, 0, len, output, outOff); - message.reset(); - message.write(blocks, len, blocks.length - len); - return len; - } - return 0; - } - - private int encrypt(byte[] input, int inOff, int len, byte[] output, int outOff) - { - int IOLen = len; - int splitLen; - byte[] P = new byte[Rkout]; - int Cu = encrypted ? 0 : 0x80; - while (IOLen != 0 || !encrypted) - { - splitLen = Math.min(IOLen, Rkout); /* use Rkout instead of Rsqueeze, this function is only called in keyed mode */ - if (forEncryption) - { - System.arraycopy(input, inOff, P, 0, splitLen); - } - Up(null, 0, Cu); /* Up without extract */ + up(mode, state, encrypted ? 0 : 0x80); /* Up without extract */ /* Extract from Up and Add */ - for (int i = 0; i < splitLen; i++) - { - output[outOff + i] = (byte)(input[inOff++] ^ state[i]); - } + Bytes.xor(m_bufPos, state, m_buf, 0, output, outOff); if (forEncryption) { - Down(P, 0, splitLen, 0x00); + down(mode, state, m_buf, 0, m_bufPos, 0x00); } else { - Down(output, outOff, splitLen, 0x00); + down(mode, state, output, outOff, m_bufPos, 0x00); } - Cu = 0x00; - outOff += splitLen; - IOLen -= splitLen; - encrypted = true; + phase = PhaseDown; } - return len; - } - - @Override - public int doFinal(byte[] output, int outOff) - throws IllegalStateException, InvalidCipherTextException - { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - byte[] blocks = message.toByteArray(); - int len = message.size(); - if ((forEncryption && len + TAGLEN + outOff > output.length) || (!forEncryption && len - TAGLEN + outOff > output.length)) - { - throw new OutputLengthException("output buffer too short"); - } - processAAD(); - int rv = 0; - if (forEncryption) - { - encrypt(blocks, 0, len, output, outOff); - outOff += len; - tag = new byte[TAGLEN]; - Up(tag, TAGLEN, 0x40); - System.arraycopy(tag, 0, output, outOff, TAGLEN); - rv = len + TAGLEN; - } - else - { - int inOff = len - TAGLEN; - rv = inOff; - encrypt(blocks, 0, inOff, output, outOff); - tag = new byte[TAGLEN]; - Up(tag, TAGLEN, 0x40); - for (int i = 0; i < TAGLEN; ++i) - { - if (tag[i] != blocks[inOff++]) - { - throw new IllegalArgumentException("Mac does not match"); - } - } - } - reset(false); - return rv; - } - - @Override - public byte[] getMac() - { - return tag; - } - - @Override - public int getUpdateOutputSize(int len) - { - return len; - } - - @Override - public int getOutputSize(int len) - { - return len + TAGLEN; - } - - @Override - public void reset() - { - if (!initialised) - { - throw new IllegalArgumentException("Need call init function before encryption/decryption"); - } - reset(true); + up(mode, state, 0x40); + System.arraycopy(state, 0, mac, 0, MAC_SIZE); + phase = PhaseUp; } - private void reset(boolean clearMac) + protected void reset(boolean clearMac) { - if (clearMac) - { - tag = null; - } + super.reset(clearMac); Arrays.fill(state, (byte)0); - aadFinished = false; encrypted = false; phase = PhaseUp; - message.reset(); - aadData.reset(); + aadcd = (byte)0x03; //Absorb key int KLen = K.length; int IDLen = iv.length; - byte[] KID = new byte[Rkin]; - mode = MODE.ModeKeyed; - Rabsorb = Rkin; + byte[] KID = new byte[AADBufferSize]; + mode = ModeKeyed; System.arraycopy(K, 0, KID, 0, KLen); System.arraycopy(iv, 0, KID, KLen, IDLen); KID[KLen + IDLen] = (byte)IDLen; - AbsorbAny(KID, 0, KLen + IDLen + 1, Rabsorb, 0x02); + AbsorbAny(KID, 0, KLen + IDLen + 1, 0x02); } - private void AbsorbAny(byte[] X, int Xoff, int XLen, int r, int Cd) + private void AbsorbAny(byte[] X, int Xoff, int XLen, int Cd) { int splitLen; + if (phase != PhaseUp) + { + up(mode, state, 0); + } do { - if (phase != PhaseUp) - { - Up(null, 0, 0); - } - splitLen = Math.min(XLen, r); - Down(X, Xoff, splitLen, Cd); + splitLen = Math.min(XLen, AADBufferSize); + down(mode, state, X, Xoff, splitLen, Cd); + phase = PhaseDown; Cd = 0; Xoff += splitLen; XLen -= splitLen; @@ -322,104 +146,138 @@ private void AbsorbAny(byte[] X, int Xoff, int XLen, int r, int Cd) while (XLen != 0); } - private void Up(byte[] Yi, int YiLen, int Cu) + public static void up(XoodyakDigest.Friend friend, int mode, byte[] state, int Cu) { - if (mode != MODE.ModeHash) - { - state[f_bPrime - 1] ^= Cu; - } - int[] a = new int[NLANES]; - Pack.littleEndianToInt(state, 0, a, 0, a.length); - int x, y; - int[] b = new int[NLANES]; - int[] p = new int[NCOLUMS]; - int[] e = new int[NCOLUMS]; - for (int i = 0; i < MAXROUNDS; ++i) - { - /* Theta: Column Parity Mixer */ - for (x = 0; x < NCOLUMS; ++x) - { - p[x] = a[index(x, 0)] ^ a[index(x, 1)] ^ a[index(x, 2)]; - } - for (x = 0; x < NCOLUMS; ++x) - { - y = p[(x + 3) & 3]; - e[x] = ROTL32(y, 5) ^ ROTL32(y, 14); - } - for (x = 0; x < NCOLUMS; ++x) - { - for (y = 0; y < NROWS; ++y) - { - a[index(x, y)] ^= e[x]; - } - } - /* Rho-west: plane shift */ - for (x = 0; x < NCOLUMS; ++x) - { - b[index(x, 0)] = a[index(x, 0)]; - b[index(x, 1)] = a[index(x + 3, 1)]; - b[index(x, 2)] = ROTL32(a[index(x, 2)], 11); - } - /* Iota: round ant */ - b[0] ^= RC[i]; - /* Chi: non linear layer */ - for (x = 0; x < NCOLUMS; ++x) - { - for (y = 0; y < NROWS; ++y) - { - a[index(x, y)] = b[index(x, y)] ^ (~b[index(x, y + 1)] & b[index(x, y + 2)]); - } - } - /* Rho-east: plane shift */ - for (x = 0; x < NCOLUMS; ++x) - { - b[index(x, 0)] = a[index(x, 0)]; - b[index(x, 1)] = ROTL32(a[index(x, 1)], 1); - b[index(x, 2)] = ROTL32(a[index(x + 2, 2)], 8); - } - System.arraycopy(b, 0, a, 0, NLANES); - } - Pack.intToLittleEndian(a, 0, a.length, state, 0); - phase = PhaseUp; - if (Yi != null) + if (null == friend) { - System.arraycopy(state, 0, Yi, 0, YiLen); + throw new NullPointerException("This method is only for use by XoodyakDigest"); } + up(mode, state, Cu); } - void Down(byte[] Xi, int XiOff, int XiLen, int Cd) + private static void up(int mode, byte[] state, int Cu) { - for (int i = 0; i < XiLen; i++) + if (mode != ModeHash) { - state[i] ^= Xi[XiOff++]; + state[f_bPrime_1] ^= Cu; } - state[XiLen] ^= 0x01; - state[f_bPrime - 1] ^= (mode == MODE.ModeHash) ? (Cd & 0x01) : Cd; - phase = PhaseDown; - } - private int index(int x, int y) - { - return (((y % NROWS) * NCOLUMS) + ((x) % NCOLUMS)); - } + int a0 = Pack.littleEndianToInt(state, 0); + int a1 = Pack.littleEndianToInt(state, 4); + int a2 = Pack.littleEndianToInt(state, 8); + int a3 = Pack.littleEndianToInt(state, 12); + int a4 = Pack.littleEndianToInt(state, 16); + int a5 = Pack.littleEndianToInt(state, 20); + int a6 = Pack.littleEndianToInt(state, 24); + int a7 = Pack.littleEndianToInt(state, 28); + int a8 = Pack.littleEndianToInt(state, 32); + int a9 = Pack.littleEndianToInt(state, 36); + int a10 = Pack.littleEndianToInt(state, 40); + int a11 = Pack.littleEndianToInt(state, 44); - private int ROTL32(int a, int offset) - { - return (a << (offset & 31)) ^ (a >>> ((32 - (offset)) & 31)); - } + for (int i = 0; i < 12; ++i) + { + /* Theta: Column Parity Mixer */ + int p0 = a0 ^ a4 ^ a8; + int p1 = a1 ^ a5 ^ a9; + int p2 = a2 ^ a6 ^ a10; + int p3 = a3 ^ a7 ^ a11; - public int getBlockSize() - { - return Rkout; + int e0 = Integers.rotateLeft(p3, 5) ^ Integers.rotateLeft(p3, 14); + int e1 = Integers.rotateLeft(p0, 5) ^ Integers.rotateLeft(p0, 14); + int e2 = Integers.rotateLeft(p1, 5) ^ Integers.rotateLeft(p1, 14); + int e3 = Integers.rotateLeft(p2, 5) ^ Integers.rotateLeft(p2, 14); + + a0 ^= e0; + a4 ^= e0; + a8 ^= e0; + + a1 ^= e1; + a5 ^= e1; + a9 ^= e1; + + a2 ^= e2; + a6 ^= e2; + a10 ^= e2; + + a3 ^= e3; + a7 ^= e3; + a11 ^= e3; + + /* Rho-west: plane shift */ + int b0 = a0; + int b1 = a1; + int b2 = a2; + int b3 = a3; + + int b4 = a7; + int b5 = a4; + int b6 = a5; + int b7 = a6; + + int b8 = Integers.rotateLeft(a8, 11); + int b9 = Integers.rotateLeft(a9, 11); + int b10 = Integers.rotateLeft(a10, 11); + int b11 = Integers.rotateLeft(a11, 11); + + /* Iota: round ant */ + b0 ^= RC[i]; + + /* Chi: non-linear layer */ + a0 = b0 ^ (~b4 & b8); + a1 = b1 ^ (~b5 & b9); + a2 = b2 ^ (~b6 & b10); + a3 = b3 ^ (~b7 & b11); + + a4 = b4 ^ (~b8 & b0); + a5 = b5 ^ (~b9 & b1); + a6 = b6 ^ (~b10 & b2); + a7 = b7 ^ (~b11 & b3); + + b8 ^= (~b0 & b4); + b9 ^= (~b1 & b5); + b10 ^= (~b2 & b6); + b11 ^= (~b3 & b7); + + /* Rho-east: plane shift */ + a4 = Integers.rotateLeft(a4, 1); + a5 = Integers.rotateLeft(a5, 1); + a6 = Integers.rotateLeft(a6, 1); + a7 = Integers.rotateLeft(a7, 1); + + a8 = Integers.rotateLeft(b10, 8); + a9 = Integers.rotateLeft(b11, 8); + a10 = Integers.rotateLeft(b8, 8); + a11 = Integers.rotateLeft(b9, 8); + } + + Pack.intToLittleEndian(a0, state, 0); + Pack.intToLittleEndian(a1, state, 4); + Pack.intToLittleEndian(a2, state, 8); + Pack.intToLittleEndian(a3, state, 12); + Pack.intToLittleEndian(a4, state, 16); + Pack.intToLittleEndian(a5, state, 20); + Pack.intToLittleEndian(a6, state, 24); + Pack.intToLittleEndian(a7, state, 28); + Pack.intToLittleEndian(a8, state, 32); + Pack.intToLittleEndian(a9, state, 36); + Pack.intToLittleEndian(a10, state, 40); + Pack.intToLittleEndian(a11, state, 44); } - public int getKeyBytesSize() + public static void down(XoodyakDigest.Friend friend, int mode, byte[] state, byte[] Xi, int XiOff, int XiLen, int Cd) { - return 16; + if (null == friend) + { + throw new NullPointerException("This method is only for use by XoodyakDigest"); + } + down(mode, state, Xi, XiOff, XiLen, Cd); } - public int getIVBytesSize() + private static void down(int mode, byte[] state, byte[] Xi, int XiOff, int XiLen, int Cd) { - return 16; + Bytes.xorTo(XiLen, Xi, XiOff, state); + state[XiLen] ^= 0x01; + state[f_bPrime_1] ^= (mode == ModeHash) ? (Cd & 0x01) : Cd; } } diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/package-info.java b/core/src/main/java/org/bouncycastle/crypto/engines/package-info.java new file mode 100644 index 0000000000..2ed7bfe4d2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/engines/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic cipher classes. + */ +package org.bouncycastle.crypto.engines; diff --git a/core/src/main/java/org/bouncycastle/crypto/examples/ECJPAKEExample.java b/core/src/main/java/org/bouncycastle/crypto/examples/ECJPAKEExample.java new file mode 100644 index 0000000000..a5006030b6 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/examples/ECJPAKEExample.java @@ -0,0 +1,227 @@ +package org.bouncycastle.crypto.examples; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.SavableDigest; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurve; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurves; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKEParticipant; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKERound1Payload; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKERound2Payload; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKERound3Payload; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; + +/** + * An example of a J-PAKE exchange. + *

    + *

    + * In this example, both Alice and Bob are on the same computer (in the same JVM, in fact). + * In reality, Alice and Bob would be in different locations, + * and would be sending their generated payloads to each other. + */ +public class ECJPAKEExample +{ + + public static void main(String args[]) + throws CryptoException + { + // -DM 48 System.out.print + /* + * Initialization + * + * Pick an appropriate elliptic curve to use throughout the exchange. + * Note that both participants must use the same group. + */ + ECJPAKECurve curve = ECJPAKECurves.NIST_P256; + +// ECCurve ecCurve = curve.getCurve(); + BigInteger a = curve.getA(); + BigInteger b = curve.getB(); + ECPoint g = curve.getG(); + BigInteger h = curve.getH(); + BigInteger n = curve.getN(); + BigInteger q = curve.getQ(); + + String alicePassword = "password"; + String bobPassword = "password"; + + System.out.println("********* Initialization **********"); + System.out.println("Public parameters for the elliptic curve over prime field:"); + System.out.println("Curve param a (" + a.bitLength() + " bits): " + a.toString(16)); + System.out.println("Curve param b (" + b.bitLength() + " bits): " + b.toString(16)); + System.out.println("Co-factor h (" + h.bitLength() + " bits): " + h.toString(16)); + System.out.println("Base point G (" + g.getEncoded(true).length + " bytes): " + new BigInteger(g.getEncoded(true)).toString(16)); + System.out.println("X coord of G (G not normalised) (" + g.getXCoord().toBigInteger().bitLength() + " bits): " + g.getXCoord().toBigInteger().toString(16)); + System.out.println("y coord of G (G not normalised) (" + g.getYCoord().toBigInteger().bitLength() + " bits): " + g.getYCoord().toBigInteger().toString(16)); + System.out.println("Order of the base point n (" + n.bitLength() + " bits): " + n.toString(16)); + System.out.println("Prime field q (" + q.bitLength() + " bits): " + q.toString(16)); + System.out.println(""); + + System.out.println("(Secret passwords used by Alice and Bob: " + + "\"" + alicePassword + "\" and \"" + bobPassword + "\")\n"); + + /* + * Both participants must use the same hashing algorithm. + */ + Digest digest = SHA256Digest.newInstance(); + SecureRandom random = new SecureRandom(); + + ECJPAKEParticipant alice = new ECJPAKEParticipant("alice", alicePassword.toCharArray(), curve, digest, random); + ECJPAKEParticipant bob = new ECJPAKEParticipant("bob", bobPassword.toCharArray(), curve, digest, random); + + /* + * Round 1 + * + * Alice and Bob each generate a round 1 payload, and send it to each other. + */ + + ECJPAKERound1Payload aliceRound1Payload = alice.createRound1PayloadToSend(); + ECJPAKERound1Payload bobRound1Payload = bob.createRound1PayloadToSend(); + + System.out.println("************ Round 1 **************"); + System.out.println("Alice sends to Bob: "); + System.out.println("g^{x1}=" + new BigInteger(aliceRound1Payload.getGx1().getEncoded(true)).toString(16)); + System.out.println("g^{x2}=" + new BigInteger(aliceRound1Payload.getGx2().getEncoded(true)).toString(16)); + System.out.println("KP{x1}: {V=" + new BigInteger(aliceRound1Payload.getKnowledgeProofForX1().getV().getEncoded(true)).toString(16) + "; r=" + aliceRound1Payload.getKnowledgeProofForX1().getr().toString(16) + "}"); + System.out.println("KP{x2}: {V=" + new BigInteger(aliceRound1Payload.getKnowledgeProofForX2().getV().getEncoded(true)).toString(16) + "; r=" + aliceRound1Payload.getKnowledgeProofForX2().getr().toString(16) + "}"); + System.out.println(""); + + System.out.println("Bob sends to Alice: "); + System.out.println("g^{x3}=" + new BigInteger(bobRound1Payload.getGx1().getEncoded(true)).toString(16)); + System.out.println("g^{x4}=" + new BigInteger(bobRound1Payload.getGx2().getEncoded(true)).toString(16)); + System.out.println("KP{x3}: {V=" + new BigInteger(bobRound1Payload.getKnowledgeProofForX1().getV().getEncoded(true)).toString(16) + "; r=" + bobRound1Payload.getKnowledgeProofForX1().getr().toString(16) + "}"); + System.out.println("KP{x4}: {V=" + new BigInteger(bobRound1Payload.getKnowledgeProofForX2().getV().getEncoded(true)).toString(16) + "; r=" + bobRound1Payload.getKnowledgeProofForX2().getr().toString(16) + "}"); + System.out.println(""); + + /* + * Each participant must then validate the received payload for round 1 + */ + + alice.validateRound1PayloadReceived(bobRound1Payload); + System.out.println("Alice checks g^{x4}!=1: OK"); + System.out.println("Alice checks KP{x3}: OK"); + System.out.println("Alice checks KP{x4}: OK"); + System.out.println(""); + + bob.validateRound1PayloadReceived(aliceRound1Payload); + System.out.println("Bob checks g^{x2}!=1: OK"); + System.out.println("Bob checks KP{x1},: OK"); + System.out.println("Bob checks KP{x2},: OK"); + System.out.println(""); + + /* + * Round 2 + * + * Alice and Bob each generate a round 2 payload, and send it to each other. + */ + + ECJPAKERound2Payload aliceRound2Payload = alice.createRound2PayloadToSend(); + ECJPAKERound2Payload bobRound2Payload = bob.createRound2PayloadToSend(); + + System.out.println("************ Round 2 **************"); + System.out.println("Alice sends to Bob: "); + System.out.println("A=" + new BigInteger(aliceRound2Payload.getA().getEncoded(true)).toString(16)); + System.out.println("KP{x2*s}: {V=" + new BigInteger(aliceRound2Payload.getKnowledgeProofForX2s().getV().getEncoded(true)).toString(16) + ", r=" + aliceRound2Payload.getKnowledgeProofForX2s().getr().toString(16) + "}"); + System.out.println(""); + + System.out.println("Bob sends to Alice"); + System.out.println("B=" + new BigInteger(bobRound2Payload.getA().getEncoded(true)).toString(16)); + System.out.println("KP{x4*s}: {V=" + new BigInteger(bobRound2Payload.getKnowledgeProofForX2s().getV().getEncoded(true)).toString(16) + ", r=" + bobRound2Payload.getKnowledgeProofForX2s().getr().toString(16) + "}"); + System.out.println(""); + + /* + * Each participant must then validate the received payload for round 2 + */ + + alice.validateRound2PayloadReceived(bobRound2Payload); + System.out.println("Alice checks KP{x4*s}: OK\n"); + + bob.validateRound2PayloadReceived(aliceRound2Payload); + System.out.println("Bob checks KP{x2*s}: OK\n"); + + /* + * After round 2, each participant computes the keying material. + */ + + BigInteger aliceKeyingMaterial = alice.calculateKeyingMaterial(); + BigInteger bobKeyingMaterial = bob.calculateKeyingMaterial(); + + System.out.println("********* After round 2 ***********"); + System.out.println("Alice computes key material \t K=" + aliceKeyingMaterial.toString(16)); + System.out.println("Bob computes key material \t K=" + bobKeyingMaterial.toString(16)); + System.out.println(); + + + /* + * You must derive a session key from the keying material applicable + * to whatever encryption algorithm you want to use. + */ + + BigInteger aliceKey = deriveSessionKey(aliceKeyingMaterial); + BigInteger bobKey = deriveSessionKey(bobKeyingMaterial); + + /* + * At this point, you can stop and use the session keys if you want. + * This is implicit key confirmation. + * + * If you want to explicitly confirm that the key material matches, + * you can continue on and perform round 3. + */ + + /* + * Round 3 + * + * Alice and Bob each generate a round 3 payload, and send it to each other. + */ + + ECJPAKERound3Payload aliceRound3Payload = alice.createRound3PayloadToSend(aliceKeyingMaterial); + ECJPAKERound3Payload bobRound3Payload = bob.createRound3PayloadToSend(bobKeyingMaterial); + + // -DM 11grad System.out.println + System.out.println("************ Round 3 **************"); + System.out.println("Alice sends to Bob: "); + System.out.println("MacTag=" + aliceRound3Payload.getMacTag().toString(16)); + System.out.println(""); + System.out.println("Bob sends to Alice: "); + System.out.println("MacTag=" + bobRound3Payload.getMacTag().toString(16)); + System.out.println(""); + + /* + * Each participant must then validate the received payload for round 3 + */ + + alice.validateRound3PayloadReceived(bobRound3Payload, aliceKeyingMaterial); + System.out.println("Alice checks MacTag: OK\n"); + + bob.validateRound3PayloadReceived(aliceRound3Payload, bobKeyingMaterial); + System.out.println("Bob checks MacTag: OK\n"); + + System.out.println(); + System.out.println("MacTags validated, therefore the keying material matches."); + } + + private static BigInteger deriveSessionKey(BigInteger keyingMaterial) + { + /* + * You should use a secure key derivation function (KDF) to derive the session key. + * + * For the purposes of this example, I'm just going to use a hash of the keying material. + */ + SavableDigest digest = SHA256Digest.newInstance(); + + byte[] keyByteArray = keyingMaterial.toByteArray(); + + byte[] output = new byte[digest.getDigestSize()]; + + digest.update(keyByteArray, 0, keyByteArray.length); + + digest.doFinal(output, 0); + + return new BigInteger(output); + } +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/examples/package-info.java b/core/src/main/java/org/bouncycastle/crypto/examples/package-info.java new file mode 100644 index 0000000000..fb7d512270 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/examples/package-info.java @@ -0,0 +1,4 @@ +/** + * Simple examples of light weight API usage. + */ +package org.bouncycastle.crypto.examples; diff --git a/core/src/main/java/org/bouncycastle/crypto/generators/Argon2BytesGenerator.java b/core/src/main/java/org/bouncycastle/crypto/generators/Argon2BytesGenerator.java index eade40ff68..2e113a7ab4 100755 --- a/core/src/main/java/org/bouncycastle/crypto/generators/Argon2BytesGenerator.java +++ b/core/src/main/java/org/bouncycastle/crypto/generators/Argon2BytesGenerator.java @@ -24,7 +24,7 @@ public class Argon2BytesGenerator /* Minimum and maximum number of lanes (degree of parallelism) */ private static final int MIN_PARALLELISM = 1; - private static final int MAX_PARALLELISM = 16777216; + private static final int MAX_PARALLELISM = (1 << 24) - 1; /* Minimum and maximum digest size in bytes */ private static final int MIN_OUTLEN = 4; @@ -52,26 +52,49 @@ public Argon2BytesGenerator() */ public void init(Argon2Parameters parameters) { - this.parameters = parameters; - - if (parameters.getLanes() < Argon2BytesGenerator.MIN_PARALLELISM) + if (parameters.getVersion() != Argon2Parameters.ARGON2_VERSION_10 && + parameters.getVersion() != Argon2Parameters.ARGON2_VERSION_13) { - throw new IllegalStateException("lanes must be greater than " + Argon2BytesGenerator.MIN_PARALLELISM); + throw new UnsupportedOperationException("unknown Argon2 version"); } - else if (parameters.getLanes() > Argon2BytesGenerator.MAX_PARALLELISM) + if (parameters.getType() != Argon2Parameters.ARGON2_d && + parameters.getType() != Argon2Parameters.ARGON2_i && + parameters.getType() != Argon2Parameters.ARGON2_id) + { + throw new UnsupportedOperationException("unknown Argon2 type"); + } + + if (parameters.getLanes() < MIN_PARALLELISM) { - throw new IllegalStateException("lanes must be less than " + Argon2BytesGenerator.MAX_PARALLELISM); + throw new IllegalStateException("lanes must be at least " + MIN_PARALLELISM); } - else if (parameters.getMemory() < 2 * parameters.getLanes()) + else if (parameters.getLanes() > MAX_PARALLELISM) { - throw new IllegalStateException("memory is less than: " + (2 * parameters.getLanes()) + " expected " + (2 * parameters.getLanes())); + throw new IllegalStateException("lanes must be at most " + MAX_PARALLELISM); } - else if (parameters.getIterations() < Argon2BytesGenerator.MIN_ITERATIONS) + else if (parameters.getIterations() < MIN_ITERATIONS) { - throw new IllegalStateException("iterations is less than: " + Argon2BytesGenerator.MIN_ITERATIONS); + throw new IllegalStateException("iterations is less than: " + MIN_ITERATIONS); } - doInit(parameters); + this.parameters = parameters; + + // 2. Align memory size + // Minimum memoryBlocks = 8L blocks, where L is the number of lanes + int memoryBlocks = Math.max(parameters.getMemory(), 2 * ARGON2_SYNC_POINTS * parameters.getLanes()); + + this.segmentLength = memoryBlocks / (ARGON2_SYNC_POINTS * parameters.getLanes()); + this.laneLength = segmentLength * ARGON2_SYNC_POINTS; + + // Ensure that all segments have equal length + memoryBlocks = parameters.getLanes() * laneLength; + + this.memory = new Block[memoryBlocks]; + + for (int i = 0; i < memory.length; i++) + { + memory[i] = new Block(); + } } public int generateBytes(char[] password, byte[] out) @@ -91,9 +114,9 @@ public int generateBytes(byte[] password, byte[] out) public int generateBytes(byte[] password, byte[] out, int outOff, int outLen) { - if (outLen < Argon2BytesGenerator.MIN_OUTLEN) + if (outLen < MIN_OUTLEN) { - throw new IllegalStateException("output length less than " + Argon2BytesGenerator.MIN_OUTLEN); + throw new IllegalStateException("output length less than " + MIN_OUTLEN); } byte[] tmpBlockBytes = new byte[ARGON2_BLOCK_SIZE]; @@ -124,36 +147,6 @@ private void reset() } } - private void doInit(Argon2Parameters parameters) - { - /* 2. Align memory size */ - /* Minimum memoryBlocks = 8L blocks, where L is the number of lanes */ - int memoryBlocks = parameters.getMemory(); - - if (memoryBlocks < 2 * Argon2BytesGenerator.ARGON2_SYNC_POINTS * parameters.getLanes()) - { - memoryBlocks = 2 * Argon2BytesGenerator.ARGON2_SYNC_POINTS * parameters.getLanes(); - } - - this.segmentLength = memoryBlocks / (parameters.getLanes() * Argon2BytesGenerator.ARGON2_SYNC_POINTS); - this.laneLength = segmentLength * Argon2BytesGenerator.ARGON2_SYNC_POINTS; - - /* Ensure that all segments have equal length */ - memoryBlocks = segmentLength * (parameters.getLanes() * Argon2BytesGenerator.ARGON2_SYNC_POINTS); - - initMemory(memoryBlocks); - } - - private void initMemory(int memoryBlocks) - { - this.memory = new Block[memoryBlocks]; - - for (int i = 0; i < memory.length; i++) - { - memory[i] = new Block(); - } - } - private void fillMemoryBlocks() { FillBlock filler = new FillBlock(); diff --git a/core/src/main/java/org/bouncycastle/crypto/generators/BCrypt.java b/core/src/main/java/org/bouncycastle/crypto/generators/BCrypt.java index f065056b8b..55f1bfcf51 100644 --- a/core/src/main/java/org/bouncycastle/crypto/generators/BCrypt.java +++ b/core/src/main/java/org/bouncycastle/crypto/generators/BCrypt.java @@ -616,10 +616,10 @@ public static byte[] passwordToByteArray(char[] password) /** * Calculates the bcrypt hash of an input - note for processing general passwords you want to - * make sure the password is terminated in a manner similar to what is done by passwordToByteArray(). + * make sure the password is terminated in a manner similar to what is done by {@link #passwordToByteArray(char[])}. *

    * This implements the raw bcrypt function as defined in the bcrypt specification, not - * the crypt encoded version implemented in OpenBSD. + * the crypt encoded version implemented in OpenBSD, see {@link OpenBSDBCrypt} for that. *

    * @param pwInput the password bytes (up to 72 bytes) to use for this invocation. * @param salt the 128 bit salt to use for this invocation. diff --git a/core/src/main/java/org/bouncycastle/crypto/generators/ECCSIKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/crypto/generators/ECCSIKeyPairGenerator.java new file mode 100644 index 0000000000..321c020abd --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/generators/ECCSIKeyPairGenerator.java @@ -0,0 +1,82 @@ +package org.bouncycastle.crypto.generators; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.CryptoServicePurpose; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.crypto.constraints.DefaultServiceProperties; +import org.bouncycastle.crypto.params.ECCSIKeyGenerationParameters; +import org.bouncycastle.crypto.params.ECCSIPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECCSIPublicKeyParameters; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.BigIntegers; + +/** + * A key pair generator for the ECCSI scheme (Elliptic Curve-based Certificateless Signatures + * for Identity-based Encryption) as defined in RFC 6507. + * + * @see + * RFC 6507: Elliptic Curve-Based Certificateless Signatures for Identity-based Encryption (ECCSI) + * + */ + +public class ECCSIKeyPairGenerator + implements AsymmetricCipherKeyPairGenerator +{ + private BigInteger q; + private ECPoint G; + private Digest digest; + private ECCSIKeyGenerationParameters parameters; + + /** + * Initializes the key pair generator with the specified parameters. + * + * @param parameters an instance of {@link ECCSIKeyGenerationParameters} which encapsulates the elliptic + * curve domain parameters, the digest algorithm, and an associated identifier. + */ + @Override + public void init(KeyGenerationParameters parameters) + { + this.parameters = (ECCSIKeyGenerationParameters)parameters; + this.q = this.parameters.getQ(); + this.G = this.parameters.getG(); + this.digest = this.parameters.getDigest(); + + CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties("ECCSI", this.parameters.getN(), null, CryptoServicePurpose.KEYGEN)); + } + + @Override + public AsymmetricCipherKeyPair generateKeyPair() + { + SecureRandom random = parameters.getRandom(); + this.digest.reset(); + byte[] id = parameters.getId(); + ECPoint kpak = parameters.getKPAK(); + // 1) Choose v, a random (ephemeral) non-zero element of F_q; + BigInteger v = BigIntegers.createRandomBigInteger(256, random).mod(q); + // 2) Compute PVT = [v]G + ECPoint pvt = G.multiply(v).normalize(); + + // 3) Compute a hash value HS = hash( G || KPAK || ID || PVT ), an N-octet integer; + byte[] tmp = G.getEncoded(false); + digest.update(tmp, 0, tmp.length); + tmp = kpak.getEncoded(false); + digest.update(tmp, 0, tmp.length); + digest.update(id, 0, id.length); + tmp = pvt.getEncoded(false); + digest.update(tmp, 0, tmp.length); + tmp = new byte[digest.getDigestSize()]; + digest.doFinal(tmp, 0); + BigInteger HS = new BigInteger(1, tmp).mod(q); + + // 4) Compute SSK = ( KSAK + HS * v ) modulo q; + BigInteger ssk = parameters.computeSSK(HS.multiply(v)); + ECCSIPublicKeyParameters pub = new ECCSIPublicKeyParameters(pvt); + return new AsymmetricCipherKeyPair(new ECCSIPublicKeyParameters(pvt), new ECCSIPrivateKeyParameters(ssk, pub)); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java b/core/src/main/java/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java index 3667835551..da0a93c3f5 100644 --- a/core/src/main/java/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java +++ b/core/src/main/java/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java @@ -12,7 +12,10 @@ * Password hashing scheme BCrypt, * designed by Niels Provos and David Mazières, using the * String format and the Base64 encoding - * of the reference implementation on OpenBSD + * of the reference implementation on OpenBSD. + *

    + * Passwords are encoded using UTF-8 when provided as char[]. Encoded passwords longer than + * 72 bytes are truncated and all remaining bytes are ignored. */ public class OpenBSDBCrypt { diff --git a/core/src/main/java/org/bouncycastle/crypto/generators/package-info.java b/core/src/main/java/org/bouncycastle/crypto/generators/package-info.java new file mode 100644 index 0000000000..6168dee299 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/generators/package-info.java @@ -0,0 +1,4 @@ +/** + * Generators for keys, key pairs and password based encryption algorithms. + */ +package org.bouncycastle.crypto.generators; diff --git a/core/src/main/java/org/bouncycastle/crypto/hpke/AEAD.java b/core/src/main/java/org/bouncycastle/crypto/hpke/AEAD.java index e4e840bec1..a6d93cab1b 100644 --- a/core/src/main/java/org/bouncycastle/crypto/hpke/AEAD.java +++ b/core/src/main/java/org/bouncycastle/crypto/hpke/AEAD.java @@ -9,11 +9,11 @@ import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Bytes; import org.bouncycastle.util.Pack; public class AEAD { - private final short aeadId; private final byte[] key; private final byte[] baseNonce; @@ -32,7 +32,7 @@ public AEAD(short aeadId, byte[] key, byte[] baseNonce) { case HPKE.aead_AES_GCM128: case HPKE.aead_AES_GCM256: - cipher = new GCMBlockCipher(new AESEngine()); + cipher = GCMBlockCipher.newInstance(AESEngine.newInstance()); break; case HPKE.aead_CHACHA20_POLY1305: cipher = new ChaCha20Poly1305(); @@ -42,106 +42,73 @@ public AEAD(short aeadId, byte[] key, byte[] baseNonce) } } + // used by Sender + public byte[] seal(byte[] aad, byte[] pt) + throws InvalidCipherTextException + { + return process(true, aad, pt, 0, pt.length); + } // used by Sender public byte[] seal(byte[] aad, byte[] pt, int ptOffset, int ptLength) throws InvalidCipherTextException { - if (ptOffset < 0 || ptOffset > pt.length) - { - throw new IndexOutOfBoundsException("Invalid offset"); - } - if (ptOffset + ptLength > pt.length) - { - throw new IndexOutOfBoundsException("Invalid length"); - } - - CipherParameters params; - switch (aeadId) - { - case HPKE.aead_AES_GCM128: - case HPKE.aead_AES_GCM256: - case HPKE.aead_CHACHA20_POLY1305: - params = new ParametersWithIV(new KeyParameter(key), ComputeNonce()); - break; - case HPKE.aead_EXPORT_ONLY: - default: - throw new IllegalStateException("Export only mode, cannot be used to seal/open"); - } - cipher.init(true, params); - cipher.processAADBytes(aad, 0, aad.length); - byte[] ct = new byte[cipher.getOutputSize(ptLength)]; - int len = cipher.processBytes(pt, ptOffset, ptLength, ct, 0); - cipher.doFinal(ct, len); + Arrays.validateSegment(pt, ptOffset, ptLength); - seq++; - return ct; + return process(true, aad, pt, ptOffset, ptLength); } - // used by Sender - public byte[] seal(byte[] aad, byte[] pt) + // used by Receiver + public byte[] open(byte[] aad, byte[] ct) throws InvalidCipherTextException { - return this.seal(aad, pt, 0, pt.length); + return process(false, aad, ct, 0, ct.length); } // used by Receiver public byte[] open(byte[] aad, byte[] ct, int ctOffset, int ctLength) throws InvalidCipherTextException { - if (ctOffset < 0 || ctOffset > ct.length) - { - throw new IndexOutOfBoundsException("Invalid offset"); - } - if (ctOffset + ctLength > ct.length) - { - throw new IndexOutOfBoundsException("Invalid length"); - } + Arrays.validateSegment(ct, ctOffset, ctLength); + + return process(false, aad, ct, ctOffset, ctLength); + } + + private byte[] computeNonce() + { + byte[] seq_bytes = Pack.longToBigEndian(seq++); + byte[] nonce = Arrays.clone(baseNonce); + Bytes.xorTo(8, seq_bytes, 0, nonce, nonce.length - 8); + return nonce; + } + private byte[] process(boolean forEncryption, byte[] aad, byte[] buf, int off, int len) + throws InvalidCipherTextException + { CipherParameters params; switch (aeadId) { case HPKE.aead_AES_GCM128: case HPKE.aead_AES_GCM256: case HPKE.aead_CHACHA20_POLY1305: - params = new ParametersWithIV(new KeyParameter(key), ComputeNonce()); + params = new ParametersWithIV(new KeyParameter(key), computeNonce()); break; case HPKE.aead_EXPORT_ONLY: default: throw new IllegalStateException("Export only mode, cannot be used to seal/open"); } - cipher.init(false, params); + cipher.init(forEncryption, params); cipher.processAADBytes(aad, 0, aad.length); - byte[] pt = new byte[cipher.getOutputSize(ctLength)]; - int len = cipher.processBytes(ct, ctOffset, ctLength, pt, 0); - len += cipher.doFinal(pt, len); - - seq++; - return pt; - } - - // used by Receiver - public byte[] open(byte[] aad, byte[] ct) - throws InvalidCipherTextException - { - return this.open(aad, ct, 0, ct.length); - } - - private byte[] ComputeNonce() - { - byte[] seq_bytes = Pack.longToBigEndian(seq); - int Nn = baseNonce.length; - byte[] nonce = Arrays.clone(baseNonce); - //xor - for (int i = 0; i < 8; i++) + byte[] output = new byte[cipher.getOutputSize(len)]; + int pos = cipher.processBytes(buf, off, len, output, 0); + pos += cipher.doFinal(output, pos); + if (pos != output.length) { - nonce[Nn - 8 + i] ^= seq_bytes[i]; + // Existing AEAD modes should return exact value for getOutputSize. + throw new IllegalStateException(); } - return nonce; + return output; } - - } - diff --git a/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java b/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java index a17bfcd235..2eb175b6a3 100644 --- a/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java +++ b/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java @@ -5,9 +5,13 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.BasicAgreement; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.RawAgreement; +import org.bouncycastle.crypto.agreement.BasicRawAgreement; import org.bouncycastle.crypto.agreement.ECDHCBasicAgreement; -import org.bouncycastle.crypto.agreement.XDHBasicAgreement; +import org.bouncycastle.crypto.agreement.X25519Agreement; +import org.bouncycastle.crypto.agreement.X448Agreement; +import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; import org.bouncycastle.crypto.generators.X448KeyPairGenerator; @@ -22,24 +26,22 @@ import org.bouncycastle.crypto.params.X448KeyGenerationParameters; import org.bouncycastle.crypto.params.X448PrivateKeyParameters; import org.bouncycastle.crypto.params.X448PublicKeyParameters; -import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.FixedPointCombMultiplier; import org.bouncycastle.math.ec.WNafUtil; -import org.bouncycastle.math.ec.custom.sec.SecP256R1Curve; -import org.bouncycastle.math.ec.custom.sec.SecP384R1Curve; -import org.bouncycastle.math.ec.custom.sec.SecP521R1Curve; +import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Pack; import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Hex; - class DHKEM + extends KEM { private AsymmetricCipherKeyPairGenerator kpGen; - private BasicAgreement agreement; + private RawAgreement rawAgreement; // kem ids private final short kemId; @@ -48,99 +50,75 @@ class DHKEM private byte bitmask; private int Nsk; private int Nsecret; + private int Nenc; ECDomainParameters domainParams; protected DHKEM(short kemid) { this.kemId = kemid; - ECCurve curve; + switch (kemid) { case HPKE.kem_P256_SHA256: this.hkdf = new HKDF(HPKE.kdf_HKDF_SHA256); - curve = new SecP256R1Curve(); - domainParams = new ECDomainParameters( - curve, - curve.createPoint( - new BigInteger(1, Hex.decode("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296")), - new BigInteger(1, Hex.decode("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")) - ), - curve.getOrder(), - curve.getCofactor(), - Hex.decode("c49d360886e704936a6678e1139d26b7819f7e90") - ); - this.agreement = new ECDHCBasicAgreement(); + domainParams = getDomainParameters("P-256"); + rawAgreement = new BasicRawAgreement(new ECDHCBasicAgreement()); bitmask = (byte)0xff; Nsk = 32; Nsecret = 32; + Nenc = 65; this.kpGen = new ECKeyPairGenerator(); - this.kpGen.init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); + this.kpGen.init(new ECKeyGenerationParameters(domainParams, getSecureRandom())); break; case HPKE.kem_P384_SHA348: this.hkdf = new HKDF(HPKE.kdf_HKDF_SHA384); - curve = new SecP384R1Curve(); - domainParams = new ECDomainParameters( - curve, - curve.createPoint( - new BigInteger(1, Hex.decode("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7")), - new BigInteger(1, Hex.decode("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")) - ), - curve.getOrder(), - curve.getCofactor(), - Hex.decode("a335926aa319a27a1d00896a6773a4827acdac73") - ); - this.agreement = new ECDHCBasicAgreement(); + domainParams = getDomainParameters("P-384"); + rawAgreement = new BasicRawAgreement(new ECDHCBasicAgreement()); bitmask = (byte)0xff; Nsk = 48; Nsecret = 48; + Nenc = 97; this.kpGen = new ECKeyPairGenerator(); - this.kpGen.init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); + this.kpGen.init(new ECKeyGenerationParameters(domainParams, getSecureRandom())); break; case HPKE.kem_P521_SHA512: this.hkdf = new HKDF(HPKE.kdf_HKDF_SHA512); - - curve = new SecP521R1Curve(); - domainParams = new ECDomainParameters( - curve, - curve.createPoint( - new BigInteger("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", 16), - new BigInteger("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", 16) - ), - curve.getOrder(), - curve.getCofactor(), - Hex.decode("d09e8800291cb85396cc6717393284aaa0da64ba") - ); - this.agreement = new ECDHCBasicAgreement(); + domainParams = getDomainParameters("P-521"); + rawAgreement = new BasicRawAgreement(new ECDHCBasicAgreement()); bitmask = 0x01; Nsk = 66; Nsecret = 64; + Nenc = 133; this.kpGen = new ECKeyPairGenerator(); - this.kpGen.init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); + this.kpGen.init(new ECKeyGenerationParameters(domainParams, getSecureRandom())); break; case HPKE.kem_X25519_SHA256: this.hkdf = new HKDF(HPKE.kdf_HKDF_SHA256); - this.agreement = new XDHBasicAgreement(); + rawAgreement = new X25519Agreement(); Nsecret = 32; Nsk = 32; + Nenc = 32; + this.kpGen = new X25519KeyPairGenerator(); - this.kpGen.init(new X25519KeyGenerationParameters(new SecureRandom())); + this.kpGen.init(new X25519KeyGenerationParameters(getSecureRandom())); break; case HPKE.kem_X448_SHA512: this.hkdf = new HKDF(HPKE.kdf_HKDF_SHA512); - this.agreement = new XDHBasicAgreement(); + rawAgreement = new X448Agreement(); Nsecret = 64; Nsk = 56; + Nenc = 56; this.kpGen = new X448KeyPairGenerator(); - this.kpGen.init(new X448KeyGenerationParameters(new SecureRandom())); + this.kpGen.init(new X448KeyGenerationParameters(getSecureRandom())); break; default: @@ -150,12 +128,15 @@ protected DHKEM(short kemid) public byte[] SerializePublicKey(AsymmetricKeyParameter key) { - switch (kemId) { case HPKE.kem_P256_SHA256: case HPKE.kem_P384_SHA348: case HPKE.kem_P521_SHA512: + /* + * RFC 9180 7.1.1. For P-256, P-384, and P-521, the SerializePublicKey() function of the KEM performs + * the uncompressed Elliptic-Curve-Point-to-Octet-String conversion according to [SECG]. + */ return ((ECPublicKeyParameters)key).getQ().getEncoded(false); case HPKE.kem_X448_SHA512: return ((X448PublicKeyParameters)key).getEncoded(); @@ -165,6 +146,7 @@ public byte[] SerializePublicKey(AsymmetricKeyParameter key) throw new IllegalStateException("invalid kem id"); } } + public byte[] SerializePrivateKey(AsymmetricKeyParameter key) { switch (kemId) @@ -172,36 +154,90 @@ public byte[] SerializePrivateKey(AsymmetricKeyParameter key) case HPKE.kem_P256_SHA256: case HPKE.kem_P384_SHA348: case HPKE.kem_P521_SHA512: - return formatBigIntegerBytes(((ECPrivateKeyParameters)key).getD().toByteArray(), Nsk); + { + /* + * RFC 9180 7.1.2. For P-256, P-384, and P-521, the SerializePrivateKey() function of the KEM + * performs the Field-Element-to-Octet-String conversion according to [SECG]. + */ + return BigIntegers.asUnsignedByteArray(Nsk, ((ECPrivateKeyParameters)key).getD()); + } case HPKE.kem_X448_SHA512: - return ((X448PrivateKeyParameters)key).getEncoded(); + { + /* + * RFC 9180 7.1.2. For [..] X448 [..]. The SerializePrivateKey() function MUST clamp its output + * [..]. + * + * NOTE: Our X448 implementation clamps generated keys, but de-serialized keys are preserved as is + * (clamping applied only during usage). + */ + byte[] encoded = ((X448PrivateKeyParameters)key).getEncoded(); + X448.clampPrivateKey(encoded); + return encoded; + } case HPKE.kem_X25519_SHA256: - return ((X25519PrivateKeyParameters)key).getEncoded(); + { + /* + * RFC 9180 7.1.2. For X25519 [..]. The SerializePrivateKey() function MUST clamp its output [..]. + * + * NOTE: Our X25519 implementation clamps generated keys, but de-serialized keys are preserved as + * is (clamping applied only during usage). + */ + byte[] encoded = ((X25519PrivateKeyParameters)key).getEncoded(); + X25519.clampPrivateKey(encoded); + return encoded; + } default: throw new IllegalStateException("invalid kem id"); } } - public AsymmetricKeyParameter DeserializePublicKey(byte[] encoded) + public AsymmetricKeyParameter DeserializePublicKey(byte[] pkEncoded) { + if (pkEncoded == null) + { + throw new NullPointerException("'pkEncoded' cannot be null"); + } + if (pkEncoded.length != Nenc) + { + throw new IllegalArgumentException("'pkEncoded' has invalid length"); + } + switch (kemId) { - case HPKE.kem_P256_SHA256: - case HPKE.kem_P384_SHA348: - case HPKE.kem_P521_SHA512: - ECPoint G = domainParams.getCurve().decodePoint(encoded); - return new ECPublicKeyParameters(G, domainParams); - case HPKE.kem_X448_SHA512: - return new X448PublicKeyParameters(encoded); - case HPKE.kem_X25519_SHA256: - return new X25519PublicKeyParameters(encoded); - default: - throw new IllegalStateException("invalid kem id"); + case HPKE.kem_P256_SHA256: + case HPKE.kem_P384_SHA348: + case HPKE.kem_P521_SHA512: + /* + * RFC 9180 7.1.1. For P-256, P-384, and P-521 [..]. DeserializePublicKey() performs the + * uncompressed Octet-String-to-Elliptic-Curve-Point conversion. + */ + if (pkEncoded[0] != 0x04) // "0x04" is the marker for an uncompressed encoding + { + throw new IllegalArgumentException("'pkEncoded' has invalid format"); + } + + ECPoint G = domainParams.getCurve().decodePoint(pkEncoded); + return new ECPublicKeyParameters(G, domainParams); + case HPKE.kem_X448_SHA512: + return new X448PublicKeyParameters(pkEncoded); + case HPKE.kem_X25519_SHA256: + return new X25519PublicKeyParameters(pkEncoded); + default: + throw new IllegalStateException("invalid kem id"); } } public AsymmetricCipherKeyPair DeserializePrivateKey(byte[] skEncoded, byte[] pkEncoded) { + if (skEncoded == null) + { + throw new NullPointerException("'skEncoded' cannot be null"); + } + if (skEncoded.length != Nsk) + { + throw new IllegalArgumentException("'skEncoded' has invalid length"); + } + AsymmetricKeyParameter pubParam = null; if (pkEncoded != null) @@ -211,38 +247,47 @@ public AsymmetricCipherKeyPair DeserializePrivateKey(byte[] skEncoded, byte[] pk switch (kemId) { - case HPKE.kem_P256_SHA256: - case HPKE.kem_P384_SHA348: - case HPKE.kem_P521_SHA512: - BigInteger d = new BigInteger(1, skEncoded); - ECPrivateKeyParameters ec = new ECPrivateKeyParameters(d, domainParams); - - if (pubParam == null) - { - ECPoint Q = new FixedPointCombMultiplier().multiply(domainParams.getG(), ((ECPrivateKeyParameters)ec).getD()); - pubParam = new ECPublicKeyParameters(Q, domainParams); - } - return new AsymmetricCipherKeyPair(pubParam, ec); - case HPKE.kem_X448_SHA512: - X448PrivateKeyParameters x448 = new X448PrivateKeyParameters(skEncoded); - if (pubParam == null) - { - pubParam = x448.generatePublicKey(); - } - return new AsymmetricCipherKeyPair(pubParam, x448); - case HPKE.kem_X25519_SHA256: - X25519PrivateKeyParameters x25519 = new X25519PrivateKeyParameters(skEncoded); - if (pubParam == null) - { - pubParam = x25519.generatePublicKey(); - } - return new AsymmetricCipherKeyPair(pubParam, x25519); - default: - throw new IllegalStateException("invalid kem id"); + case HPKE.kem_P256_SHA256: + case HPKE.kem_P384_SHA348: + case HPKE.kem_P521_SHA512: + /* + * RFC 9180 7.1.2. For P-256, P-384, and P-521 [..]. DeserializePrivateKey() performs the Octet- + * String-to-Field-Element conversion according to [SECG]. + */ + BigInteger d = new BigInteger(1, skEncoded); + ECPrivateKeyParameters ec = new ECPrivateKeyParameters(d, domainParams); + + if (pubParam == null) + { + ECPoint Q = new FixedPointCombMultiplier().multiply(domainParams.getG(), ((ECPrivateKeyParameters)ec).getD()); + pubParam = new ECPublicKeyParameters(Q, domainParams); + } + return new AsymmetricCipherKeyPair(pubParam, ec); + case HPKE.kem_X448_SHA512: + X448PrivateKeyParameters x448 = new X448PrivateKeyParameters(skEncoded); + if (pubParam == null) + { + pubParam = x448.generatePublicKey(); + } + return new AsymmetricCipherKeyPair(pubParam, x448); + case HPKE.kem_X25519_SHA256: + X25519PrivateKeyParameters x25519 = new X25519PrivateKeyParameters(skEncoded); + if (pubParam == null) + { + pubParam = x25519.generatePublicKey(); + } + return new AsymmetricCipherKeyPair(pubParam, x25519); + default: + throw new IllegalStateException("invalid kem id"); } } - private boolean ValidateSk(BigInteger d) + int getEncryptionSize() + { + return Nenc; + } + + private boolean validateSk(BigInteger d) { BigInteger n = domainParams.getN(); int nBitLength = n.bitLength(); @@ -278,44 +323,41 @@ public AsymmetricCipherKeyPair DeriveKeyPair(byte[] ikm) case HPKE.kem_P256_SHA256: case HPKE.kem_P384_SHA348: case HPKE.kem_P521_SHA512: + { byte[] dkp_prk = hkdf.LabeledExtract(null, suiteID, "dkp_prk", ikm); - int counter = 0; byte[] counterArray = new byte[1]; - while (true) + for (int counter = 0; counter < 256; ++counter) { - if (counter > 255) - { - throw new IllegalStateException("DeriveKeyPairError"); - } counterArray[0] = (byte)counter; byte[] bytes = hkdf.LabeledExpand(dkp_prk, suiteID, "candidate", counterArray, Nsk); bytes[0] = (byte)(bytes[0] & bitmask); - // generating keypair BigInteger d = new BigInteger(1, bytes); - if (ValidateSk(d)) + if (validateSk(d)) { ECPoint Q = new FixedPointCombMultiplier().multiply(domainParams.getG(), d); ECPrivateKeyParameters sk = new ECPrivateKeyParameters(d, domainParams); ECPublicKeyParameters pk = new ECPublicKeyParameters(Q, domainParams); return new AsymmetricCipherKeyPair(pk, sk); } - - counter++; } + throw new IllegalStateException("DeriveKeyPairError"); + } case HPKE.kem_X448_SHA512: - dkp_prk = hkdf.LabeledExtract(null, suiteID, "dkp_prk", ikm); + { + byte[] dkp_prk = hkdf.LabeledExtract(null, suiteID, "dkp_prk", ikm); byte[] x448sk = hkdf.LabeledExpand(dkp_prk, suiteID, "sk", null, Nsk); X448PrivateKeyParameters x448params = new X448PrivateKeyParameters(x448sk); return new AsymmetricCipherKeyPair(x448params.generatePublicKey(), x448params); - + } case HPKE.kem_X25519_SHA256: - dkp_prk = hkdf.LabeledExtract(null, suiteID, "dkp_prk", ikm); + { + byte[] dkp_prk = hkdf.LabeledExtract(null, suiteID, "dkp_prk", ikm); byte[] skBytes = hkdf.LabeledExpand(dkp_prk, suiteID, "sk", null, Nsk); X25519PrivateKeyParameters sk = new X25519PrivateKeyParameters(skBytes); - return new AsymmetricCipherKeyPair(sk.generatePublicKey(), sk); + } default: throw new IllegalStateException("invalid kem id"); } @@ -330,11 +372,8 @@ protected byte[][] Encap(AsymmetricKeyParameter pkR, AsymmetricCipherKeyPair kpE { byte[][] output = new byte[2][]; - //DH - agreement.init(kpE.getPrivate()); - - byte[] temp = agreement.calculateAgreement(pkR).toByteArray(); - byte[] secret = formatBigIntegerBytes(temp, agreement.getFieldSize()); + // DH + byte[] secret = calculateRawAgreement(rawAgreement, kpE.getPrivate(), pkR); byte[] enc = SerializePublicKey(kpE.getPublic()); byte[] pkRm = SerializePublicKey(pkR); @@ -351,17 +390,13 @@ protected byte[] Decap(byte[] enc, AsymmetricCipherKeyPair kpR) { AsymmetricKeyParameter pkE = DeserializePublicKey(enc); - //DH - agreement.init(kpR.getPrivate()); - - byte[] temp = agreement.calculateAgreement(pkE).toByteArray(); // add leading zeros - byte[] secret = formatBigIntegerBytes(temp, agreement.getFieldSize()); + // DH + byte[] secret = calculateRawAgreement(rawAgreement, kpR.getPrivate(), pkE); byte[] pkRm = SerializePublicKey(kpR.getPublic()); byte[] KEMContext = Arrays.concatenate(enc, pkRm); - byte[] sharedSecret = ExtractAndExpand(secret, KEMContext); - return sharedSecret; + return ExtractAndExpand(secret, KEMContext); } protected byte[][] AuthEncap(AsymmetricKeyParameter pkR, AsymmetricCipherKeyPair kpS) @@ -370,18 +405,23 @@ protected byte[][] AuthEncap(AsymmetricKeyParameter pkR, AsymmetricCipherKeyPair AsymmetricCipherKeyPair kpE = kpGen.generateKeyPair(); // todo: can be replaced with deriveKeyPair(random) - // DH(skE, pkR) - agreement.init(kpE.getPrivate()); - byte[] temp = agreement.calculateAgreement(pkR).toByteArray(); - byte[] secret1 = formatBigIntegerBytes(temp, agreement.getFieldSize()); + rawAgreement.init(kpE.getPrivate()); + int agreementSize = rawAgreement.getAgreementSize(); + + byte[] secret = new byte[agreementSize * 2]; + + rawAgreement.calculateAgreement(pkR, secret, 0); // DH(skS, pkR) - agreement.init(kpS.getPrivate()); - temp = agreement.calculateAgreement(pkR).toByteArray(); - byte[] secret2 = formatBigIntegerBytes(temp, agreement.getFieldSize()); + rawAgreement.init(kpS.getPrivate()); + if (agreementSize != rawAgreement.getAgreementSize()) + { + throw new IllegalStateException(); + } + + rawAgreement.calculateAgreement(pkR, secret, agreementSize); - byte[] secret = Arrays.concatenate(secret1, secret2); byte[] enc = SerializePublicKey(kpE.getPublic()); byte[] pkRm = SerializePublicKey(pkR); @@ -399,25 +439,22 @@ protected byte[] AuthDecap(byte[] enc, AsymmetricCipherKeyPair kpR, AsymmetricKe { AsymmetricKeyParameter pkE = DeserializePublicKey(enc); - // DH(skR, pkE) - agreement.init(kpR.getPrivate()); + rawAgreement.init(kpR.getPrivate()); - byte[] temp = agreement.calculateAgreement(pkE).toByteArray(); // add leading zeros - byte[] secret1 = formatBigIntegerBytes(temp, agreement.getFieldSize()); + int agreementSize = rawAgreement.getAgreementSize(); + byte[] secret = new byte[agreementSize * 2]; - // DH(skR, pkS) - agreement.init(kpR.getPrivate()); - temp = agreement.calculateAgreement(pkS).toByteArray(); - byte[] secret2 = formatBigIntegerBytes(temp, agreement.getFieldSize()); + // DH(skR, pkE) + rawAgreement.calculateAgreement(pkE, secret, 0); - byte[] secret = Arrays.concatenate(secret1, secret2); + // DH(skR, pkS) + rawAgreement.calculateAgreement(pkS, secret, agreementSize); byte[] pkRm = SerializePublicKey(kpR.getPublic()); byte[] pkSm = SerializePublicKey(pkS); byte[] KEMContext = Arrays.concatenate(enc, pkRm, pkSm); - byte[] sharedSecret = ExtractAndExpand(secret, KEMContext); - return sharedSecret; + return ExtractAndExpand(secret, KEMContext); } private byte[] ExtractAndExpand(byte[] dh, byte[] kemContext) @@ -426,21 +463,25 @@ private byte[] ExtractAndExpand(byte[] dh, byte[] kemContext) byte[] eae_prk = hkdf.LabeledExtract(null, suiteID, "eae_prk", dh); - byte[] sharedSecret = hkdf.LabeledExpand(eae_prk, suiteID, "shared_secret", kemContext, Nsecret); - return sharedSecret; + return hkdf.LabeledExpand(eae_prk, suiteID, "shared_secret", kemContext, Nsecret); } - private byte[] formatBigIntegerBytes(byte[] bigIntBytes, int outputSize) + private static byte[] calculateRawAgreement(RawAgreement rawAgreement, AsymmetricKeyParameter privateKey, + AsymmetricKeyParameter publicKey) { - byte[] output = new byte[outputSize]; - if (bigIntBytes.length <= outputSize) - { - System.arraycopy(bigIntBytes, 0, output, outputSize - bigIntBytes.length, bigIntBytes.length); - } - else - { - System.arraycopy(bigIntBytes, bigIntBytes.length - outputSize, output, 0, outputSize); - } - return output; + rawAgreement.init(privateKey); + byte[] z = new byte[rawAgreement.getAgreementSize()]; + rawAgreement.calculateAgreement(publicKey, z, 0); + return z; + } + + private static ECDomainParameters getDomainParameters(String curveName) + { + return new ECDomainParameters(CustomNamedCurves.getByName(curveName)); + } + + private static SecureRandom getSecureRandom() + { + return CryptoServicesRegistrar.getSecureRandom(); } } diff --git a/core/src/main/java/org/bouncycastle/crypto/hpke/HKDF.java b/core/src/main/java/org/bouncycastle/crypto/hpke/HKDF.java index a9e0ef8d37..f69cc8e398 100644 --- a/core/src/main/java/org/bouncycastle/crypto/hpke/HKDF.java +++ b/core/src/main/java/org/bouncycastle/crypto/hpke/HKDF.java @@ -8,10 +8,11 @@ import org.bouncycastle.crypto.params.HKDFParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; +import org.bouncycastle.util.Strings; class HKDF { - private final static String versionLabel = "HPKE-v1"; + private final static byte[] VERSION_LABEL = getBytes("HPKE-v1"); private final HKDFBytesGenerator kdf; private final int hashLength; @@ -50,7 +51,7 @@ protected byte[] LabeledExtract(byte[] salt, byte[] suiteID, String label, byte[ salt = new byte[hashLength]; } - byte[] labeledIKM = Arrays.concatenate(versionLabel.getBytes(), suiteID, label.getBytes(), ikm); + byte[] labeledIKM = Arrays.concatenate(VERSION_LABEL, suiteID, getBytes(label), ikm); return kdf.extractPRK(salt, labeledIKM); } @@ -61,7 +62,9 @@ protected byte[] LabeledExpand(byte[] prk, byte[] suiteID, String label, byte[] { throw new IllegalArgumentException("Expand length cannot be larger than 2^16"); } - byte[] labeledInfo = Arrays.concatenate(Pack.shortToBigEndian((short)L), versionLabel.getBytes(), suiteID, label.getBytes()); + + byte[] labeledInfo = Arrays.concatenate(Pack.shortToBigEndian((short)L), VERSION_LABEL, suiteID, + getBytes(label)); kdf.init(HKDFParameters.skipExtractParameters(prk, Arrays.concatenate(labeledInfo, info))); @@ -97,4 +100,14 @@ protected byte[] Expand(byte[] prk, byte[] info, int L) return rv; } + + private static byte[] getBytes(String label) + { + /* + * RFC 9180 seems silent about this conversion, but all given labels are ASCII anyway. + * + * NOTE: String#getBytes not reliable because it depends on the platform's default charset. + */ + return Strings.toByteArray(label); + } } diff --git a/core/src/main/java/org/bouncycastle/crypto/hpke/HPKE.java b/core/src/main/java/org/bouncycastle/crypto/hpke/HPKE.java index 076e28f45f..6841f62dfc 100644 --- a/core/src/main/java/org/bouncycastle/crypto/hpke/HPKE.java +++ b/core/src/main/java/org/bouncycastle/crypto/hpke/HPKE.java @@ -40,8 +40,9 @@ public class HPKE private final short kemId; private final short kdfId; private final short aeadId; - private final DHKEM dhkem; + private final KEM kem; private final HKDF hkdf; + private final int encSize; short Nk; @@ -58,7 +59,7 @@ public HPKE(byte mode, short kemId, short kdfId, short aeadId) this.kdfId = kdfId; this.aeadId = aeadId; this.hkdf = new HKDF(kdfId); - this.dhkem = new DHKEM(kemId); + this.kem = new DHKEM(kemId); if (aeadId == aead_AES_GCM128) { Nk = 16; @@ -67,26 +68,35 @@ public HPKE(byte mode, short kemId, short kdfId, short aeadId) { Nk = 32; } + this.encSize = kem.getEncryptionSize(); } - public int getEncSize() + public HPKE(byte mode, short kemId, short kdfId, short aeadId, KEM kem, int encSize) { - switch (kemId) + this.mode = mode; + this.kemId = kemId; + this.kdfId = kdfId; + this.aeadId = aeadId; + this.hkdf = new HKDF(kdfId); + this.kem = kem; + + if (aeadId == aead_AES_GCM128) { - case HPKE.kem_P256_SHA256: - return 65; - case HPKE.kem_P384_SHA348: - return 97; - case HPKE.kem_P521_SHA512: - return 133; - case HPKE.kem_X25519_SHA256: - return 32; - case HPKE.kem_X448_SHA512: - return 56; - default: - throw new IllegalArgumentException("invalid kem id"); + Nk = 16; } + else + { + Nk = 32; + } + + this.encSize = encSize; } + + public int getEncSize() + { + return encSize; + } + public short getAeadId() { return aeadId; @@ -139,32 +149,32 @@ private HPKEContext keySchedule(byte mode, byte[] sharedSecret, byte[] info, byt public AsymmetricCipherKeyPair generatePrivateKey() { - return dhkem.GeneratePrivateKey(); + return kem.GeneratePrivateKey(); } public byte[] serializePublicKey(AsymmetricKeyParameter pk) { - return dhkem.SerializePublicKey(pk); + return kem.SerializePublicKey(pk); } public byte[] serializePrivateKey(AsymmetricKeyParameter sk) { - return dhkem.SerializePrivateKey(sk); + return kem.SerializePrivateKey(sk); } public AsymmetricKeyParameter deserializePublicKey(byte[] pkEncoded) { - return dhkem.DeserializePublicKey(pkEncoded); + return kem.DeserializePublicKey(pkEncoded); } public AsymmetricCipherKeyPair deserializePrivateKey(byte[] skEncoded, byte[] pkEncoded) { - return dhkem.DeserializePrivateKey(skEncoded, pkEncoded); + return kem.DeserializePrivateKey(skEncoded, pkEncoded); } public AsymmetricCipherKeyPair deriveKeyPair(byte[] ikm) { - return dhkem.DeriveKeyPair(ikm); + return kem.DeriveKeyPair(ikm); } public byte[][] sendExport(AsymmetricKeyParameter pkR, byte[] info, byte[] exporterContext, int L, @@ -273,7 +283,7 @@ public byte[] open(byte[] enc, AsymmetricCipherKeyPair skR, byte[] info, byte[] public HPKEContextWithEncapsulation setupBaseS(AsymmetricKeyParameter pkR, byte[] info) { - byte[][] output = dhkem.Encap(pkR); // sharedSecret, enc + byte[][] output = kem.Encap(pkR); // sharedSecret, enc HPKEContext ctx = keySchedule(mode_base, output[0], info, default_psk, default_psk_id); return new HPKEContextWithEncapsulation(ctx, output[1]); @@ -283,7 +293,7 @@ public HPKEContextWithEncapsulation setupBaseS(AsymmetricKeyParameter pkR, byte[ // This should only be used to validate test vectors. public HPKEContextWithEncapsulation setupBaseS(AsymmetricKeyParameter pkR, byte[] info, AsymmetricCipherKeyPair kpE) { - byte[][] output = dhkem.Encap(pkR, kpE); // sharedSecret, enc + byte[][] output = kem.Encap(pkR, kpE); // sharedSecret, enc HPKEContext ctx = keySchedule(mode_base, output[0], info, default_psk, default_psk_id); return new HPKEContextWithEncapsulation(ctx, output[1]); @@ -291,13 +301,13 @@ public HPKEContextWithEncapsulation setupBaseS(AsymmetricKeyParameter pkR, byte[ public HPKEContext setupBaseR(byte[] enc, AsymmetricCipherKeyPair skR, byte[] info) { - byte[] sharedSecret = dhkem.Decap(enc, skR); + byte[] sharedSecret = kem.Decap(enc, skR); return keySchedule(mode_base, sharedSecret, info, default_psk, default_psk_id); } public HPKEContextWithEncapsulation SetupPSKS(AsymmetricKeyParameter pkR, byte[] info, byte[] psk, byte[] psk_id) { - byte[][] output = dhkem.Encap(pkR); // sharedSecret, enc + byte[][] output = kem.Encap(pkR); // sharedSecret, enc HPKEContext ctx = keySchedule(mode_psk, output[0], info, psk, psk_id); @@ -306,13 +316,13 @@ public HPKEContextWithEncapsulation SetupPSKS(AsymmetricKeyParameter pkR, byte[] public HPKEContext setupPSKR(byte[] enc, AsymmetricCipherKeyPair skR, byte[] info, byte[] psk, byte[] psk_id) { - byte[] sharedSecret = dhkem.Decap(enc, skR); + byte[] sharedSecret = kem.Decap(enc, skR); return keySchedule(mode_psk, sharedSecret, info, psk, psk_id); } public HPKEContextWithEncapsulation setupAuthS(AsymmetricKeyParameter pkR, byte[] info, AsymmetricCipherKeyPair skS) { - byte[][] output = dhkem.AuthEncap(pkR, skS); + byte[][] output = kem.AuthEncap(pkR, skS); HPKEContext ctx = keySchedule(mode_auth, output[0], info, default_psk, default_psk_id); return new HPKEContextWithEncapsulation(ctx, output[1]); @@ -320,13 +330,13 @@ public HPKEContextWithEncapsulation setupAuthS(AsymmetricKeyParameter pkR, byte[ public HPKEContext setupAuthR(byte[] enc, AsymmetricCipherKeyPair skR, byte[] info, AsymmetricKeyParameter pkS) { - byte[] sharedSecret = dhkem.AuthDecap(enc, skR, pkS); + byte[] sharedSecret = kem.AuthDecap(enc, skR, pkS); return keySchedule(mode_auth, sharedSecret, info, default_psk, default_psk_id); } public HPKEContextWithEncapsulation setupAuthPSKS(AsymmetricKeyParameter pkR, byte[] info, byte[] psk, byte[] psk_id, AsymmetricCipherKeyPair skS) { - byte[][] output = dhkem.AuthEncap(pkR, skS); + byte[][] output = kem.AuthEncap(pkR, skS); HPKEContext ctx = keySchedule(mode_auth_psk, output[0], info, psk, psk_id); return new HPKEContextWithEncapsulation(ctx, output[1]); @@ -334,7 +344,7 @@ public HPKEContextWithEncapsulation setupAuthPSKS(AsymmetricKeyParameter pkR, by public HPKEContext setupAuthPSKR(byte[] enc, AsymmetricCipherKeyPair skR, byte[] info, byte[] psk, byte[] psk_id, AsymmetricKeyParameter pkS) { - byte[] sharedSecret = dhkem.AuthDecap(enc, skR, pkS); + byte[] sharedSecret = kem.AuthDecap(enc, skR, pkS); return keySchedule(mode_auth_psk, sharedSecret, info, psk, psk_id); } } diff --git a/core/src/main/java/org/bouncycastle/crypto/hpke/KEM.java b/core/src/main/java/org/bouncycastle/crypto/hpke/KEM.java new file mode 100644 index 0000000000..35bb58348f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/hpke/KEM.java @@ -0,0 +1,35 @@ +package org.bouncycastle.crypto.hpke; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; + + +/** + * base class for HPKE KEM + */ +public abstract class KEM +{ + // Key Generation + abstract AsymmetricCipherKeyPair GeneratePrivateKey(); + abstract AsymmetricCipherKeyPair DeriveKeyPair(byte[] ikm); + + // Encapsulates a shared secret for a given public key and returns the encapsulated key and shared secret. + abstract byte[][] Encap(AsymmetricKeyParameter recipientPublicKey); + abstract byte[][] Encap(AsymmetricKeyParameter pkR, AsymmetricCipherKeyPair kpE); + abstract byte[][] AuthEncap(AsymmetricKeyParameter pkR, AsymmetricCipherKeyPair kpS); + + // Decapsulates the given encapsulated key using the recipient's key pair and returns the shared secret. + abstract byte[] Decap(byte[] encapsulatedKey, AsymmetricCipherKeyPair recipientKeyPair); + abstract byte[] AuthDecap(byte[] enc, AsymmetricCipherKeyPair kpR, AsymmetricKeyParameter pkS); + + // Serialization + abstract byte[] SerializePublicKey(AsymmetricKeyParameter publicKey); + abstract byte[] SerializePrivateKey(AsymmetricKeyParameter key); + + // Deserialization + abstract AsymmetricKeyParameter DeserializePublicKey(byte[] encodedPublicKey); + abstract AsymmetricCipherKeyPair DeserializePrivateKey(byte[] skEncoded, byte[] pkEncoded); + + abstract int getEncryptionSize(); + +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/io/package-info.java b/core/src/main/java/org/bouncycastle/crypto/io/package-info.java new file mode 100644 index 0000000000..c3443e7bb2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/io/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for doing "enhanced" I/O with Digests and MACs. + */ +package org.bouncycastle.crypto.io; diff --git a/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMExtractor.java b/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMExtractor.java index 234cc4355f..578078d6c8 100755 --- a/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMExtractor.java +++ b/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMExtractor.java @@ -119,6 +119,6 @@ public byte[] extractSecret(byte[] encapsulation) public int getEncapsulationLength() { - return (decKey.getParameters().getCurve().getFieldSize() / 8) * 2 + 1; + return decKey.getParameters().getCurve().getAffinePointEncodingLength(false); } } diff --git a/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMGenerator.java b/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMGenerator.java index 1b356444ab..5aa57fef07 100755 --- a/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMGenerator.java +++ b/core/src/main/java/org/bouncycastle/crypto/kems/ECIESKEMGenerator.java @@ -100,9 +100,9 @@ private ECMultiplier createBasePointMultiplier() public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recipientKey) { - if (!(recipientKey instanceof ECKeyParameters)) + if (!(recipientKey instanceof ECPublicKeyParameters)) { - throw new IllegalArgumentException("EC key required"); + throw new IllegalArgumentException("EC public key required"); } ECPublicKeyParameters ecPubKey = (ECPublicKeyParameters)recipientKey; diff --git a/core/src/main/java/org/bouncycastle/crypto/kems/SAKKEKEMExtractor.java b/core/src/main/java/org/bouncycastle/crypto/kems/SAKKEKEMExtractor.java new file mode 100644 index 0000000000..8e2307e153 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/kems/SAKKEKEMExtractor.java @@ -0,0 +1,211 @@ +package org.bouncycastle.crypto.kems; + +import java.math.BigInteger; + +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.EncapsulatedSecretExtractor; +import org.bouncycastle.crypto.params.SAKKEPrivateKeyParameters; +import org.bouncycastle.crypto.params.SAKKEPublicKeyParameters; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; + +/** + * Implements the receiver side of the SAKKE (Sakai-Kasahara Key Encryption) protocol + * as defined in RFC 6508. This class extracts the shared secret value (SSV) from + * encapsulated data using the receiver's private key. + *

    + * The extraction process follows these steps (RFC 6508, Section 6.2.2): + *

      + *
    1. Parse encapsulated data into R_(b,S) and H
    2. + *
    3. Compute pairing result w = <R_(b,S), K_(b,S)>
    4. + *
    5. Recover SSV via SSV = H XOR HashToIntegerRange(w, 2^n)
    6. + *
    7. Validate R_(b,S) by recomputing it with derived parameters
    8. + *
    + *

    + * + * @see Sakai-Kasahara Key Encryption (SAKKE) + */ +public class SAKKEKEMExtractor + implements EncapsulatedSecretExtractor +{ + private final ECCurve curve; + private final BigInteger p; + private final BigInteger q; + private final ECPoint P; + private final ECPoint Z_S; + private final ECPoint K_bs; + private final int n; // Security parameter + private final BigInteger identifier; + private final Digest digest; + + /** + * Initializes the extractor with cryptographic parameters from the receiver's private key. + * + * @param privateKey The receiver's private key containing public parameters + * (curve, prime, generator, etc.) and the Receiver Secret Key (RSK). + * Must not be {@code null}. + */ + public SAKKEKEMExtractor(SAKKEPrivateKeyParameters privateKey) + { + SAKKEPublicKeyParameters publicKey = privateKey.getPublicParams(); + this.curve = publicKey.getCurve(); + this.q = publicKey.getQ(); + this.P = publicKey.getPoint(); + this.p = publicKey.getPrime(); + this.Z_S = publicKey.getZ(); + this.identifier = publicKey.getIdentifier(); + this.K_bs = P.multiply(this.identifier.add(privateKey.getMasterSecret()).modInverse(q)).normalize(); + this.n = publicKey.getN(); + + this.digest = publicKey.getDigest(); + } + + /** + * Extracts the shared secret value (SSV) from encapsulated data as per RFC 6508. + * + * @param encapsulation The encapsulated data containing: + *
      + *
    • R_(b,S): Elliptic curve point (uncompressed format, 257 bytes)
    • + *
    • H: Integer value (n/8 bytes)
    • + *
    + * @return The extracted SSV as a byte array. + * @throws IllegalStateException If: Validation of R_(b,S) fails + */ + @Override + public byte[] extractSecret(byte[] encapsulation) + { + // Step 1: Parse Encapsulated Data (R_bS, H) + ECPoint R_bS = curve.decodePoint(Arrays.copyOfRange(encapsulation, 0, 257)); + BigInteger H = BigIntegers.fromUnsignedByteArray(encapsulation, 257, 16); + + // Step 2: Compute w = using pairing + BigInteger w = computePairing(R_bS, K_bs, p, q); + + // Step 3: Compute SSV = H XOR HashToIntegerRange(w, 2^n) + BigInteger twoToN = BigInteger.ONE.shiftLeft(n); + BigInteger mask = SAKKEKEMSGenerator.hashToIntegerRange(w.toByteArray(), twoToN, digest); + BigInteger ssv = H.xor(mask).mod(p); + + // Step 4: Compute r = HashToIntegerRange(SSV || b) + BigInteger b = identifier; + BigInteger r = SAKKEKEMSGenerator.hashToIntegerRange(Arrays.concatenate(ssv.toByteArray(), b.toByteArray()), q, digest); + + // Step 5: Validate R_bS + ECPoint bP = P.multiply(b).normalize(); + ECPoint Test = bP.add(Z_S).multiply(r).normalize(); + if (!R_bS.equals(Test)) + { + throw new IllegalStateException("Validation of R_bS failed"); + } + + return BigIntegers.asUnsignedByteArray(n / 8, ssv); + } + + @Override + public int getEncapsulationLength() + { + return 273; //257 (length of ECPoint) + 16 (length of Hash) + } + + /** + * Computes the Tate-Lichtenbaum pairing <R, Q> for SAKKE validation. + * Follows the pairing algorithm described in RFC 6508, Section 3.2. + * + * @param R First pairing input (elliptic curve point) + * @param Q Second pairing input (elliptic curve point) + * @param p Prime field characteristic + * @param q Subgroup order + * @return Pairing result in PF_p[q], represented as a field element + */ + static BigInteger computePairing(ECPoint R, ECPoint Q, BigInteger p, BigInteger q) + { + // v = (1,0) in F_p^2 + BigInteger[] v = new BigInteger[]{BigInteger.ONE, BigInteger.ZERO}; + ECPoint C = R; + + BigInteger qMinusOne = q.subtract(BigInteger.ONE); + int numBits = qMinusOne.bitLength(); + BigInteger Qx = Q.getAffineXCoord().toBigInteger(); + BigInteger Qy = Q.getAffineYCoord().toBigInteger(); + BigInteger Rx = R.getAffineXCoord().toBigInteger(); + BigInteger Ry = R.getAffineYCoord().toBigInteger(); + BigInteger l, Cx, Cy; + final BigInteger three = BigInteger.valueOf(3); + final BigInteger two = BigInteger.valueOf(2); + + // Miller loop + for (int i = numBits - 2; i >= 0; i--) + { + Cx = C.getAffineXCoord().toBigInteger(); + Cy = C.getAffineYCoord().toBigInteger(); + + // Compute l = (3 * (Cx^2 - 1)) / (2 * Cy) mod p + l = three.multiply(Cx.multiply(Cx).subtract(BigInteger.ONE)) + .multiply(Cy.multiply(two).modInverse(p)).mod(p); + + // Compute v = v^2 * ( l*( Q_x + C_x ) + ( i*Q_y - C_y ) ) + v = fp2PointSquare(v[0], v[1], p); + v = fp2Multiply(v[0], v[1], l.multiply(Qx.add(Cx)).subtract(Cy), Qy, p); + + C = C.twice().normalize(); // C = [2]C + + if (qMinusOne.testBit(i)) + { + Cx = C.getAffineXCoord().toBigInteger(); + Cy = C.getAffineYCoord().toBigInteger(); + + // Compute l = (Cy - Ry) / (Cx - Rx) mod p + l = Cy.subtract(Ry).multiply(Cx.subtract(Rx).modInverse(p)).mod(p); + + // Compute v = v * ( l*( Q_x + C_x ) + ( i*Q_y - C_y ) ) + v = fp2Multiply(v[0], v[1], l.multiply(Qx.add(Cx)).subtract(Cy), Qy, p); + + C = C.add(R).normalize(); + } + } + + // Final exponentiation: t = v^c + v = fp2PointSquare(v[0], v[1], p); + v = fp2PointSquare(v[0], v[1], p); + return v[1].multiply(v[0].modInverse(p)).mod(p); + } + + /** + * Performs multiplication in F_p^2 field. + * + * @param x_real Real component of first operand + * @param x_imag Imaginary component of first operand + * @param y_real Real component of second operand + * @param y_imag Imaginary component of second operand + * @param p Prime field characteristic + * @return Result of multiplication in F_p^2 as [real, imaginary] array + */ + static BigInteger[] fp2Multiply(BigInteger x_real, BigInteger x_imag, BigInteger y_real, BigInteger y_imag, BigInteger p) + { + return new BigInteger[]{ + x_real.multiply(y_real).subtract(x_imag.multiply(y_imag)).mod(p), + x_real.multiply(y_imag).add(x_imag.multiply(y_real)).mod(p) + }; + } + + /** + * Computes squaring operation in F_p^2 field. + * + * @param currentX Real component of input + * @param currentY Imaginary component of input + * @param p Prime field characteristic + * @return Squared result in F_p^2 as [newX, newY] array + */ + static BigInteger[] fp2PointSquare(BigInteger currentX, BigInteger currentY, BigInteger p) + { + BigInteger xPlusY = currentX.add(currentY).mod(p); + BigInteger xMinusY = currentX.subtract(currentY).mod(p); + BigInteger newX = xPlusY.multiply(xMinusY).mod(p); + + // Compute newY = 2xy mod p + BigInteger newY = currentX.multiply(currentY).multiply(BigInteger.valueOf(2)).mod(p); + return new BigInteger[]{newX, newY}; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/kems/SAKKEKEMSGenerator.java b/core/src/main/java/org/bouncycastle/crypto/kems/SAKKEKEMSGenerator.java new file mode 100644 index 0000000000..2ab72dce8c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/kems/SAKKEKEMSGenerator.java @@ -0,0 +1,176 @@ +package org.bouncycastle.crypto.kems; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.EncapsulatedSecretGenerator; +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.SAKKEPublicKeyParameters; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; + +/** + * This class implements the SAKKE (Sakai-Kasahara Key Encryption) Key Encapsulation Mechanism + * as defined in RFC 6508. It generates an encapsulated shared secret value (SSV) using + * Identity-Based Encryption (IBE) for secure transmission from a Sender to a Receiver. + *

    + * The algorithm follows these steps (as per RFC 6508, Section 6.2.1): + *

      + *
    1. Generate a random SSV in the range [0, 2^n - 1].
    2. + *
    3. Compute r = HashToIntegerRange(SSV || b, q).
    4. + *
    5. Compute R_(b,S) = [r]([b]P + Z_S) on the elliptic curve.
    6. + *
    7. Compute H = SSV XOR HashToIntegerRange(g^r, 2^n).
    8. + *
    9. Encode the encapsulated data (R_(b,S), H).
    10. + *
    + *

    + * + * @see RFC 6508: Sakai-Kasahara Key Encryption (SAKKE) + */ +public class SAKKEKEMSGenerator + implements EncapsulatedSecretGenerator +{ + private final SecureRandom random; + + /** + * Constructs a SAKKEKEMSGenerator with the specified source of randomness. + * + * @param random a {@link SecureRandom} instance for generating cryptographically secure random values. + * Must not be {@code null}. + */ + public SAKKEKEMSGenerator(SecureRandom random) + { + this.random = random; + } + + /** + * Generates an encapsulated shared secret value (SSV) using the recipient's public key parameters + * as specified in RFC 6508, Section 6.2.1. + *

    + * This method performs the following operations: + *

      + *
    • Derives cryptographic parameters from the recipient's public key.
    • + *
    • Generates a random SSV and computes the encapsulation components (R_(b,S), H).
    • + *
    • Encodes the encapsulated data as specified in RFC 6508, Section 4.
    • + *
    + *

    + * + * @param recipientKey the recipient's public key parameters. Must be an instance of + * {@link SAKKEPublicKeyParameters}. Must not be {@code null}. + * @return a {@link SecretWithEncapsulation} containing the SSV and the encapsulated data. + */ + @Override + public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recipientKey) + { + // Extract public parameters from the recipient's key + SAKKEPublicKeyParameters keyParameters = (SAKKEPublicKeyParameters)recipientKey; + ECPoint Z = keyParameters.getZ(); + BigInteger b = keyParameters.getIdentifier(); + BigInteger p = keyParameters.getPrime(); + BigInteger q = keyParameters.getQ(); + BigInteger g = keyParameters.getG(); + int n = keyParameters.getN(); + ECCurve curve = keyParameters.getCurve(); + ECPoint P = keyParameters.getPoint(); + Digest digest = keyParameters.getDigest(); + + // 1. Generate random SSV in range [0, 2^n - 1] + BigInteger ssv = BigIntegers.createRandomBigInteger(n, random); + + // 2. Compute r = HashToIntegerRange(SSV || b, q) + BigInteger r = hashToIntegerRange(Arrays.concatenate(ssv.toByteArray(), b.toByteArray()), q, digest); + + + // 3. Compute R_(b,S) = [r]([b]P + Z_S) + ECPoint bP = P.multiply(b).normalize(); + ECPoint R_bS = bP.add(Z).multiply(r).normalize(); + + // 4. Compute H = SSV XOR HashToIntegerRange( g^r, 2^n ) + BigInteger pointX = BigInteger.ONE; + BigInteger pointY = g; + BigInteger[] v = new BigInteger[2]; + + // Initialize result with the original point + BigInteger currentX = BigInteger.ONE; + BigInteger currentY = g; + ECPoint current = curve.createPoint(currentX, currentY); + + int numBits = r.bitLength(); + BigInteger[] rlt; + // Process bits from MSB-1 down to 0 + for (int i = numBits - 2; i >= 0; i--) + { + // Square the current point + rlt = SAKKEKEMExtractor.fp2PointSquare(currentX, currentY, p); + current = current.timesPow2(2); + currentX = rlt[0]; + currentY = rlt[1]; + // Multiply if bit is set + if (r.testBit(i)) + { + rlt = SAKKEKEMExtractor.fp2Multiply(currentX, currentY, pointX, pointY, p); + + currentX = rlt[0]; + currentY = rlt[1]; + } + } + + v[0] = currentX; + v[1] = currentY; + BigInteger g_r = v[1].multiply(v[0].modInverse(p)).mod(p); + + BigInteger mask = hashToIntegerRange(g_r.toByteArray(), BigInteger.ONE.shiftLeft(n), digest); // 2^n + + BigInteger H = ssv.xor(mask); + // 5. Encode encapsulated data (R_bS, H) +// byte[] encapsulated = Arrays.concatenate(new byte[]{(byte)0x04}, +// BigIntegers.asUnsignedByteArray(n, R_bS.getXCoord().toBigInteger()), +// BigIntegers.asUnsignedByteArray(n, R_bS.getYCoord().toBigInteger()), +// BigIntegers.asUnsignedByteArray(16, H)); + byte[] encapsulated = Arrays.concatenate(R_bS.getEncoded(false), BigIntegers.asUnsignedByteArray(16, H)); + + return new SecretWithEncapsulationImpl( + BigIntegers.asUnsignedByteArray(n / 8, ssv), // Output SSV as key material + encapsulated + ); + } + + static BigInteger hashToIntegerRange(byte[] input, BigInteger q, Digest digest) + { + // RFC 6508 Section 5.1: Hashing to an Integer Range + byte[] hash = new byte[digest.getDigestSize()]; + + // Step 1: Compute A = hashfn(s) + digest.update(input, 0, input.length); + digest.doFinal(hash, 0); + byte[] A = Arrays.clone(hash); + + // Step 2: Initialize h_0 to all-zero bytes of hashlen size + byte[] h = new byte[digest.getDigestSize()]; + + // Step 3: Compute l = Ceiling(lg(n)/hashlen) + int l = q.bitLength() >> 8; + + BigInteger v = BigInteger.ZERO; + + // Step 4: Compute h_i and v_i + for (int i = 0; i <= l; i++) + { + // h_i = hashfn(h_{i-1}) + digest.update(h, 0, h.length); + digest.doFinal(h, 0); + // v_i = hashfn(h_i || A) + digest.update(h, 0, h.length); + digest.update(A, 0, A.length); + byte[] v_i = new byte[digest.getDigestSize()]; + digest.doFinal(v_i, 0); + // Append v_i to v' + v = v.shiftLeft(v_i.length * 8).add(new BigInteger(1, v_i)); + } + // Step 6: v = v' mod n + return v.mod(q); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/kems/package-info.java b/core/src/main/java/org/bouncycastle/crypto/kems/package-info.java new file mode 100644 index 0000000000..400d3465e7 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/kems/package-info.java @@ -0,0 +1,4 @@ +/** + * Key Encapsulation Mechanisms. + */ +package org.bouncycastle.crypto.kems; diff --git a/core/src/main/java/org/bouncycastle/crypto/macs/package-info.java b/core/src/main/java/org/bouncycastle/crypto/macs/package-info.java new file mode 100644 index 0000000000..d2286a0d20 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/macs/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for creating MACs and HMACs. + */ +package org.bouncycastle.crypto.macs; diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/CTSBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/CTSBlockCipher.java index af1fa46ded..0671ee4495 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/CTSBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/CTSBlockCipher.java @@ -6,6 +6,7 @@ import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.StreamBlockCipher; +import org.bouncycastle.util.Arrays; /** * A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to @@ -146,15 +147,19 @@ public int processBytes( if (len > gapLen) { System.arraycopy(in, inOff, buf, bufOff, gapLen); - + inOff += gapLen; + len -= gapLen; + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, length)) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } resultLen += cipher.processBlock(buf, 0, out, outOff); System.arraycopy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; - len -= gapLen; - inOff += gapLen; - while (len > blockSize) { System.arraycopy(in, inOff, buf, bufOff, blockSize); diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/ChaCha20Poly1305.java b/core/src/main/java/org/bouncycastle/crypto/modes/ChaCha20Poly1305.java index 2425dec220..49d43a2557 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/ChaCha20Poly1305.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/ChaCha20Poly1305.java @@ -307,6 +307,12 @@ public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) t { throw new IllegalArgumentException("'outOff' cannot be negative"); } + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, getUpdateOutputSize(len))) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } checkData(); diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/EAXBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/EAXBlockCipher.java index 6eb5ca4fb1..80d766a5d7 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/EAXBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/EAXBlockCipher.java @@ -224,6 +224,12 @@ public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) { throw new DataLengthException("Input buffer too short"); } + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, getUpdateOutputSize(len))) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } int resultLen = 0; diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/GCFBBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/GCFBBlockCipher.java index 0851d2e750..e1b4df2dd4 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/GCFBBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/GCFBBlockCipher.java @@ -25,14 +25,16 @@ public class GCFBBlockCipher private final CFBBlockCipher cfbEngine; + private ParametersWithIV initParams; + private KeyParameter key; - private long counter = 0; - private boolean forEncryption; + private long counter = 0; + private boolean forEncryption; public GCFBBlockCipher(BlockCipher engine) { super(engine); - + //TODO: Ensure the key size of the engine is 32 bits this.cfbEngine = new CFBBlockCipher(engine, engine.getBlockSize() * 8); } @@ -41,12 +43,15 @@ public void init(boolean forEncryption, CipherParameters params) { counter = 0; cfbEngine.init(forEncryption, params); + byte[] iv = null; this.forEncryption = forEncryption; if (params instanceof ParametersWithIV) { - params = ((ParametersWithIV)params).getParameters(); + ParametersWithIV ivParams = (ParametersWithIV)params; + params = ivParams.getParameters(); + iv = ivParams.getIV(); } if (params instanceof ParametersWithRandom) @@ -60,6 +65,23 @@ public void init(boolean forEncryption, CipherParameters params) } key = (KeyParameter)params; + + /* Pick up key/IV from parameters or most recent parameters */ + if (key == null && initParams != null) + { + key = (KeyParameter)initParams.getParameters(); + } + if (iv == null && initParams != null) + { + iv = initParams.getIV(); + } + else + { + iv = cfbEngine.getCurrentIV(); + } + + /* Save the initParameters */ + initParams = new ParametersWithIV(key, iv); } public String getAlgorithmName() @@ -83,18 +105,19 @@ public int processBlock(byte[] in, int inOff, byte[] out, int outOff) protected byte calculateByte(byte b) { - if (counter > 0 && counter % 1024 == 0) + if (counter > 0 && (counter & 1023) == 0) { - BlockCipher base = cfbEngine.getUnderlyingCipher(); + BlockCipher base = cfbEngine.getUnderlyingCipher(); base.init(false, key); byte[] nextKey = new byte[32]; + int blockSize = base.getBlockSize(); - base.processBlock(C, 0, nextKey, 0); - base.processBlock(C, 8, nextKey, 8); - base.processBlock(C, 16, nextKey, 16); - base.processBlock(C, 24, nextKey, 24); + for (int i = 0; i < nextKey.length; i += blockSize) + { + base.processBlock(C, i, nextKey, i); + } key = new KeyParameter(nextKey); @@ -115,6 +138,14 @@ protected byte calculateByte(byte b) public void reset() { counter = 0; - cfbEngine.reset(); + if (initParams != null) + { + key = (KeyParameter)initParams.getParameters(); + cfbEngine.init(forEncryption, initParams); + } + else + { + cfbEngine.reset(); + } } } diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/GCMBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/GCMBlockCipher.java index 017847ef8d..42c0c23528 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/GCMBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/GCMBlockCipher.java @@ -383,7 +383,12 @@ public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) { throw new DataLengthException("Input buffer too short"); } - + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, getUpdateOutputSize(len))) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } int resultLen = 0; if (forEncryption) diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/KXTSBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/KXTSBlockCipher.java index 2062fea183..62ece62b53 100755 --- a/core/src/main/java/org/bouncycastle/crypto/modes/KXTSBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/KXTSBlockCipher.java @@ -6,6 +6,7 @@ import org.bouncycastle.crypto.DefaultBufferedBlockCipher; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; /** @@ -123,16 +124,21 @@ public int processBytes(byte[] input, int inOff, int len, byte[] output, int out { throw new IllegalArgumentException("Partial blocks not supported"); } - + if (input == output && Arrays.segmentsOverlap(inOff, len, outOff, len)) + { + input = new byte[len]; + System.arraycopy(output, inOff, input, 0, len); + inOff = 0; + } for (int pos = 0; pos < len; pos += blockSize) { - processBlocks(input, inOff + pos, output, outOff + pos); + processBlock(input, inOff + pos, output, outOff + pos); } return len; } - private void processBlocks(byte[] input, int inOff, byte[] output, int outOff) + private void processBlock(byte[] input, int inOff, byte[] output, int outOff) { /* * A somewhat arbitrary limit of 2^32 - 1 blocks diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/NISTCTSBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/NISTCTSBlockCipher.java index e13c6ea9a5..66df8ddf0e 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/NISTCTSBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/NISTCTSBlockCipher.java @@ -9,6 +9,7 @@ import org.bouncycastle.crypto.DefaultBufferedBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.util.Arrays; /** * A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to @@ -155,15 +156,19 @@ public int processBytes( if (len > gapLen) { System.arraycopy(in, inOff, buf, bufOff, gapLen); - + inOff += gapLen; + len -= gapLen; + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, length)) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } resultLen += cipher.processBlock(buf, 0, out, outOff); System.arraycopy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; - len -= gapLen; - inOff += gapLen; - while (len > blockSize) { System.arraycopy(in, inOff, buf, bufOff, blockSize); diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/OCBBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/OCBBlockCipher.java index 93854eadc1..fd03272a4f 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/OCBBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/OCBBlockCipher.java @@ -333,7 +333,12 @@ public int processBytes(byte[] input, int inOff, int len, byte[] output, int out throw new DataLengthException("Input buffer too short"); } int resultLen = 0; - + if (input == output && Arrays.segmentsOverlap(inOff, len, outOff, getUpdateOutputSize(len))) + { + input = new byte[len]; + System.arraycopy(output, inOff, input, 0, len); + inOff = 0; + } for (int i = 0; i < len; ++i) { mainBlock[mainBlockPos] = input[inOff + i]; diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/OldCTSBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/OldCTSBlockCipher.java index 13ba147753..3b09bf3ab2 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/OldCTSBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/OldCTSBlockCipher.java @@ -5,6 +5,7 @@ import org.bouncycastle.crypto.DefaultBufferedBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.util.Arrays; /** * A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to @@ -149,15 +150,19 @@ public int processBytes( if (len > gapLen) { System.arraycopy(in, inOff, buf, bufOff, gapLen); - + inOff += gapLen; + len -= gapLen; + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, length)) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } resultLen += cipher.processBlock(buf, 0, out, outOff); System.arraycopy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; - len -= gapLen; - inOff += gapLen; - while (len > blockSize) { System.arraycopy(in, inOff, buf, bufOff, blockSize); diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/SICBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/modes/SICBlockCipher.java index 8b20136356..95f386b9a5 100644 --- a/core/src/main/java/org/bouncycastle/crypto/modes/SICBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/modes/SICBlockCipher.java @@ -241,10 +241,8 @@ private void incrementCounterAt(int pos) private void incrementCounter(int offSet) { byte old = counter[counter.length - 1]; - - counter[counter.length - 1] += offSet; - - if (old != 0 && counter[counter.length - 1] < old) + counter[counter.length - 1] += (byte) offSet; + if ((old & 0xff) + offSet > 255) { incrementCounterAt(1); } diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/gcm/package-info.java b/core/src/main/java/org/bouncycastle/crypto/modes/gcm/package-info.java new file mode 100644 index 0000000000..edca99e2b3 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/modes/gcm/package-info.java @@ -0,0 +1,4 @@ +/** + * GCM mode support classes. + */ +package org.bouncycastle.crypto.modes.gcm; diff --git a/core/src/main/java/org/bouncycastle/crypto/modes/package-info.java b/core/src/main/java/org/bouncycastle/crypto/modes/package-info.java new file mode 100644 index 0000000000..384510e819 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/modes/package-info.java @@ -0,0 +1,4 @@ +/** + * Modes for symmetric ciphers. + */ +package org.bouncycastle.crypto.modes; diff --git a/core/src/main/java/org/bouncycastle/crypto/package-info.java b/core/src/main/java/org/bouncycastle/crypto/package-info.java new file mode 100644 index 0000000000..73d7c3c6a3 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/package-info.java @@ -0,0 +1,4 @@ +/** + * Base classes for the lightweight API. + */ +package org.bouncycastle.crypto; diff --git a/core/src/main/java/org/bouncycastle/crypto/paddings/PaddedBufferedBlockCipher.java b/core/src/main/java/org/bouncycastle/crypto/paddings/PaddedBufferedBlockCipher.java index 28ec78bff9..9250a649cf 100644 --- a/core/src/main/java/org/bouncycastle/crypto/paddings/PaddedBufferedBlockCipher.java +++ b/core/src/main/java/org/bouncycastle/crypto/paddings/PaddedBufferedBlockCipher.java @@ -7,6 +7,7 @@ import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.util.Arrays; /** * A wrapper class that allows block ciphers to be used to process data in @@ -202,12 +203,18 @@ public int processBytes( if (len > gapLen) { System.arraycopy(in, inOff, buf, bufOff, gapLen); + inOff += gapLen; + len -= gapLen; + if (in == out && Arrays.segmentsOverlap(inOff, len, outOff, length)) + { + in = new byte[len]; + System.arraycopy(out, inOff, in, 0, len); + inOff = 0; + } resultLen += cipher.processBlock(buf, 0, out, outOff); bufOff = 0; - len -= gapLen; - inOff += gapLen; while (len > buf.length) { diff --git a/core/src/main/java/org/bouncycastle/crypto/paddings/package-info.java b/core/src/main/java/org/bouncycastle/crypto/paddings/package-info.java new file mode 100644 index 0000000000..b07d70815e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/paddings/package-info.java @@ -0,0 +1,4 @@ +/** + * Paddings for symmetric ciphers. + */ +package org.bouncycastle.crypto.paddings; diff --git a/core/src/main/java/org/bouncycastle/crypto/params/ECCSIKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/crypto/params/ECCSIKeyGenerationParameters.java new file mode 100644 index 0000000000..4df70d28bd --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/ECCSIKeyGenerationParameters.java @@ -0,0 +1,159 @@ +package org.bouncycastle.crypto.params; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; + +/** + * Parameters for ECCSI key generation. + * + *

    + * This class encapsulates the parameters required for ECCSI (Elliptic Curve + * Certificateless Signatures for Identity-based encryption) key generation. + * It holds the elliptic curve domain parameters and computes the key pair + * components used in ECCSI. + *

    + * + *

    + * The secret component {@code ksak} is generated randomly and reduced modulo + * {@code q}, while {@code kpak} is derived from {@code ksak} by multiplying the + * generator point. + *

    + */ +public class ECCSIKeyGenerationParameters + extends KeyGenerationParameters +{ + /** + * The order of the elliptic curve. + */ + private final BigInteger q; + + /** + * The generator (base point) of the elliptic curve. + */ + private final ECPoint G; + + /** + * The digest algorithm used in key generation. + */ + private final Digest digest; + + /** + * The identifier (e.g. user identity) used in key generation. + */ + private final byte[] id; + + /** + * The secret key component (ksak) used in ECCSI, generated randomly. + */ + private final BigInteger ksak; + + /** + * The public key component (kpak), computed as G * ksak. + */ + private final ECPoint kpak; + + /** + * The bit length used for key generation (typically the bit length of the curve's parameter A). + */ + private final int n; + + /** + * Constructs an instance of {@code ECCSIKeyGenerationParameters} with the specified + * source of randomness, elliptic curve parameters, digest algorithm, and identifier. + * + * @param random the source of randomness. + * @param params the elliptic curve parameters (in X9.62 format) providing the curve, order, and generator. + * @param digest the digest algorithm to be used. + * @param id the identifier associated with the key generation (e.g. a user or device ID). + */ + public ECCSIKeyGenerationParameters(SecureRandom random, X9ECParameters params, Digest digest, byte[] id) + { + super(random, params.getCurve().getA().bitLength()); + this.q = params.getCurve().getOrder(); + this.G = params.getG(); + this.digest = digest; + this.id = Arrays.clone(id); + this.n = params.getCurve().getA().bitLength(); + this.ksak = BigIntegers.createRandomBigInteger(n, random).mod(q); + this.kpak = G.multiply(ksak).normalize(); + } + + /** + * Returns a copy of the identifier used in these parameters. + * + * @return a byte array containing the identifier. + */ + public byte[] getId() + { + return Arrays.clone(id); + } + + /** + * Returns the public key component (kpak) corresponding to the secret key. + * + * @return the public key point. + */ + public ECPoint getKPAK() + { + return kpak; + } + + /** + * Computes the session secret key (SSK) by adding the provided value to the secret key component + * and reducing modulo the curve order. + * + * @param hs_v a BigInteger value (typically derived from a hash) to be added to the secret. + * @return the computed session secret key. + */ + public BigInteger computeSSK(BigInteger hs_v) + { + return ksak.add(hs_v).mod(q); + } + + /** + * Returns the order of the elliptic curve. + * + * @return the curve order. + */ + public BigInteger getQ() + { + return q; + } + + /** + * Returns the generator (base point) of the elliptic curve. + * + * @return the generator point. + */ + public ECPoint getG() + { + return G; + } + + /** + * Returns the digest algorithm used for key generation. + * + * @return the digest. + */ + public Digest getDigest() + { + return digest; + } + + /** + * Returns the bit length used in key generation. + * + * @return the bit length. + */ + public int getN() + { + return n; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/params/ECCSIPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/crypto/params/ECCSIPrivateKeyParameters.java new file mode 100644 index 0000000000..bc37f5f839 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/ECCSIPrivateKeyParameters.java @@ -0,0 +1,72 @@ +package org.bouncycastle.crypto.params; + +import java.math.BigInteger; + +/** + * Represents the private key parameters for the Elliptic Curve-based Certificateless + * Signature Infrastructure (ECCSI) scheme as defined in RFC 6507. + * + *

    + * This class encapsulates the secret signing key (SSK) used in ECCSI. The SSK is generated by + * the Key Management Service (KMS) and is a random integer modulo the order of the elliptic curve. + * It is paired with the corresponding public key parameters, represented by an instance of + * {@link ECCSIPublicKeyParameters}, to form the complete key material required for generating + * and verifying ECCSI signatures without the use of traditional certificates. + *

    + * + *

    + * Per RFC 6507 Section 5.1: + *

      + *
    • The SSK is generated as a random value in the appropriate range.
    • + *
    • It is used in conjunction with the public validation token (PVT) to perform signature + * operations.
    • + *
    • The combination of the SSK and the public key parameters enables certificateless + * signature generation and verification.
    • + *
    + *

    + * + * @see ECCSIPublicKeyParameters + * @see + * RFC 6507: Elliptic Curve-Based Certificateless Signatures for Identity-Based Encryption (ECCSI) + * + */ +public class ECCSIPrivateKeyParameters + extends AsymmetricKeyParameter +{ + private final BigInteger ssk; + private final ECCSIPublicKeyParameters pub; + + /** + * Constructs {@code ECCSIPrivateKeyParameters} with the specified secret signing key + * and associated public key parameters. + * + * @param ssk the secret signing key (SSK) as a BigInteger. + * @param pub the corresponding public key parameters, which encapsulate the public validation token. + */ + public ECCSIPrivateKeyParameters(BigInteger ssk, ECCSIPublicKeyParameters pub) + { + super(true); + this.ssk = ssk; + this.pub = pub; + } + + /** + * Returns the public key parameters associated with this private key. + * + * @return the {@link ECCSIPublicKeyParameters} containing the public validation token (PVT). + */ + public ECCSIPublicKeyParameters getPublicKeyParameters() + { + return pub; + } + + /** + * Returns the secret signing key (SSK) used in ECCSI. + * + * @return the SSK as a BigInteger. + */ + public BigInteger getSSK() + { + return ssk; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/params/ECCSIPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/crypto/params/ECCSIPublicKeyParameters.java new file mode 100644 index 0000000000..15269a0b46 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/ECCSIPublicKeyParameters.java @@ -0,0 +1,50 @@ +package org.bouncycastle.crypto.params; + +import org.bouncycastle.math.ec.ECPoint; + +/** + * Represents the public key parameters for the Elliptic Curve-based Certificateless + * Signature Infrastructure (ECCSI) scheme as defined in RFC 6507. + *

    + * This class encapsulates the Public Validation Token (PVT) required for verifying + * ECCSI signatures. The PVT is cryptographically bound to a user's identity and + * generated by the Key Management Service (KMS) as part of the key material. + * + *

    Per RFC 6507 Section 5.1: + *

      + *
    • The PVT is derived from the user's identity and KMS secret material
    • + *
    • Used during signature verification to validate the signer's identity
    • + *
    • Does not require certificates for authentication
    • + *
    + * + * @see RFC 6507: Elliptic Curve-Based Certificateless + * * Signatures for Identity-Based Encryption (ECCSI) + */ + +public class ECCSIPublicKeyParameters + extends AsymmetricKeyParameter +{ + private final ECPoint pvt; + + /** + * Constructs {@code ECCSIPublicKeyParameters} with the provided Public Validation Token (PVT). + */ + public ECCSIPublicKeyParameters(ECPoint pvt) + { + super(false); + this.pvt = pvt; + } + + /** + * Returns the Public Validation Token (PVT) for signature verification. + *

    + * The PVT is used in conjunction with the KMS Public Authentication Key (KPAK) + * to verify signatures per RFC 6507 Section 5.2.2. + * + * @return The PVT as an elliptic curve point in uncompressed format + */ + public final ECPoint getPVT() + { + return pvt; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/params/ECNamedDomainParameters.java b/core/src/main/java/org/bouncycastle/crypto/params/ECNamedDomainParameters.java index 1394884846..a36f1d8e13 100644 --- a/core/src/main/java/org/bouncycastle/crypto/params/ECNamedDomainParameters.java +++ b/core/src/main/java/org/bouncycastle/crypto/params/ECNamedDomainParameters.java @@ -3,7 +3,9 @@ import java.math.BigInteger; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.math.ec.ECConstants; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; @@ -11,6 +13,16 @@ public class ECNamedDomainParameters extends ECDomainParameters { + public static ECNamedDomainParameters lookup(ASN1ObjectIdentifier name) + { + X9ECParameters x9 = CustomNamedCurves.getByOID(name); + if (x9 == null) + { + x9 = ECNamedCurveTable.getByOID(name); + } + return new ECNamedDomainParameters(name, x9); + } + private ASN1ObjectIdentifier name; public ECNamedDomainParameters(ASN1ObjectIdentifier name, ECCurve curve, ECPoint G, BigInteger n) diff --git a/core/src/main/java/org/bouncycastle/crypto/params/ParametersWithContext.java b/core/src/main/java/org/bouncycastle/crypto/params/ParametersWithContext.java new file mode 100644 index 0000000000..0f6a3c8524 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/ParametersWithContext.java @@ -0,0 +1,49 @@ +package org.bouncycastle.crypto.params; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.util.Arrays; + +public class ParametersWithContext + implements CipherParameters +{ + private CipherParameters parameters; + private byte[] context; + + public ParametersWithContext( + CipherParameters parameters, + byte[] context) + { + if (context == null) + { + throw new NullPointerException("'context' cannot be null"); + } + + this.parameters = parameters; + this.context = Arrays.clone(context); + } + + public void copyContextTo(byte[] buf, int off, int len) + { + if (context.length != len) + { + throw new IllegalArgumentException("len"); + } + + System.arraycopy(context, 0, buf, off, len); + } + + public byte[] getContext() + { + return Arrays.clone(context); + } + + public int getContextLength() + { + return context.length; + } + + public CipherParameters getParameters() + { + return parameters; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/params/SAKKEPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/crypto/params/SAKKEPrivateKeyParameters.java new file mode 100644 index 0000000000..9e3be92c3f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/SAKKEPrivateKeyParameters.java @@ -0,0 +1,91 @@ +package org.bouncycastle.crypto.params; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.BigIntegers; + +/** + * Represents a private key for the Sakai-Kasahara Key Encryption (SAKKE) scheme, as defined in RFC 6508. + * + *

    SAKKE is an identity-based public key encryption scheme designed for one-pass key establishment. + * It is used in MIKEY-SAKKE for secure communication key distribution.

    + * + *

    This class generates and manages a SAKKE private key, which consists of a randomly generated + * scalar {@code z}. The corresponding public key is computed as {@code Z = [z]P}, where {@code P} + * is a publicly known generator point on the elliptic curve.

    + * + *

    The private key is used to derive the master secret in the key exchange process.

    + * + * @see RFC 6508: Sakai-Kasahara Key Encryption (SAKKE) + */ +public class SAKKEPrivateKeyParameters + extends AsymmetricKeyParameter +{ + private static final BigInteger qMinOne = SAKKEPublicKeyParameters.q.subtract(BigInteger.ONE); + /** + * The associated public key parameters. + */ + private final SAKKEPublicKeyParameters publicParams; + /** + * The private key scalar (master secret). + */ + private final BigInteger z; // KMS Public Key: Z = [z]P + + /** + * Constructs a SAKKE private key with a given private value and associated public parameters. + * + * @param z The private key scalar. + * @param publicParams The associated public key parameters. + */ + public SAKKEPrivateKeyParameters(BigInteger z, SAKKEPublicKeyParameters publicParams) + { + super(true); + this.z = z; + this.publicParams = publicParams; + ECPoint computed_Z = publicParams.getPoint().multiply(z).normalize(); + if (!computed_Z.equals(publicParams.getZ())) + { + throw new IllegalStateException("public key and private key of SAKKE do not match"); + } + } + + /** + * Generates a random SAKKE private key and its corresponding public key. + * + *

    The private key scalar {@code z} is chosen randomly in the range [2, q-1], + * where {@code q} is the order of the subgroup. The public key is computed as + * {@code Z = [z]P}, where {@code P} is the public generator.

    + * + * @param random A cryptographic random number generator. + */ + public SAKKEPrivateKeyParameters(SecureRandom random) + { + super(true); + this.z = BigIntegers.createRandomInRange(BigIntegers.TWO, qMinOne, random); + BigInteger identifier = BigIntegers.createRandomInRange(BigIntegers.TWO, qMinOne, random); + this.publicParams = new SAKKEPublicKeyParameters(identifier, + SAKKEPublicKeyParameters.P.multiply(z).normalize()); + } + + /** + * Retrieves the public key parameters associated with this private key. + * + * @return The corresponding SAKKE public key parameters. + */ + public SAKKEPublicKeyParameters getPublicParams() + { + return publicParams; + } + + /** + * Retrieves the private key scalar (master secret). + * + * @return The private key scalar {@code z}. + */ + public BigInteger getMasterSecret() + { + return z; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/params/SAKKEPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/crypto/params/SAKKEPublicKeyParameters.java new file mode 100644 index 0000000000..5dc57b95d1 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/SAKKEPublicKeyParameters.java @@ -0,0 +1,200 @@ +package org.bouncycastle.crypto.params; + +import java.math.BigInteger; + +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.encoders.Hex; + +/** + * Represents the public parameters for the SAKKE (Sakai-Kasahara Key Encryption) scheme + * as defined in RFC 6508. This class encapsulates the cryptographic domain parameters + * and public key components required for SAKKE operations. + *

    + * Contains the following public parameters (RFC 6508, Section 2.3): + *

      + *
    • Prime modulus {@code p} defining the field F_p
    • + *
    • Subgroup order {@code q} (divides p+1)
    • + *
    • Base point {@code P} on the elliptic curve E(F_p)
    • + *
    • Pairing result {@code g = }
    • + *
    • KMS Public Key {@code Z_S = [z_S]P}
    • + *
    • Security parameter {@code n} (SSV bit length)
    • + *
    • User Identifier
    • + *
    • Elliptic curve parameters (a = -3, b = 0)
    • + *
    + *

    + *

    + * The predefined parameters in this implementation correspond to the 128-bit security + * level example from RFC 6509 Appendix A. + *

    + * + * @see RFC 6508: Sakai-Kasahara Key Encryption + * @see RFC 6509: MIKEY-SAKKE + */ +public class SAKKEPublicKeyParameters + extends AsymmetricKeyParameter +{ + /** + * Prime modulus p defining the finite field F_p (RFC 6508, Section 2.1). + * Value from RFC 6509 Appendix A. + */ + static final BigInteger p = new BigInteger( + "997ABB1F0A563FDA65C61198DAD0657A416C0CE19CB48261BE9AE358B3E01A2E" + + "F40AAB27E2FC0F1B228730D531A59CB0E791B39FF7C88A19356D27F4A666A6D0" + + "E26C6487326B4CD4512AC5CD65681CE1B6AFF4A831852A82A7CF3C521C3C09AA" + + "9F94D6AF56971F1FFCE3E82389857DB080C5DF10AC7ACE87666D807AFEA85FEB", 16 + ); + + /** + * Subgroup order q (divides p+1) (RFC 6508, Section 2.1). + * Value from RFC 6509 Appendix A. + */ + static final BigInteger q = new BigInteger( + "265EAEC7C2958FF69971846636B4195E905B0338672D20986FA6B8D62CF8068B" + + "BD02AAC9F8BF03C6C8A1CC354C69672C39E46CE7FDF222864D5B49FD2999A9B4" + + "389B1921CC9AD335144AB173595A07386DABFD2A0C614AA0A9F3CF14870F026A" + + "A7E535ABD5A5C7C7FF38FA08E2615F6C203177C42B1EB3A1D99B601EBFAA17FB", 16 + ); + + private static final BigInteger Px = new BigInteger( + "53FC09EE332C29AD0A7990053ED9B52A2B1A2FD60AEC69C698B2F204B6FF7CBF" + + "B5EDB6C0F6CE2308AB10DB9030B09E1043D5F22CDB9DFA55718BD9E7406CE890" + + "9760AF765DD5BCCB337C86548B72F2E1A702C3397A60DE74A7C1514DBA66910D" + + "D5CFB4CC80728D87EE9163A5B63F73EC80EC46C4967E0979880DC8ABEAE63895", 16 + ); + + + private static final BigInteger Py = new BigInteger( + "0A8249063F6009F1F9F1F0533634A135D3E82016029906963D778D821E141178" + + "F5EA69F4654EC2B9E7F7F5E5F0DE55F66B598CCF9A140B2E416CFF0CA9E032B9" + + "70DAE117AD547C6CCAD696B5B7652FE0AC6F1E80164AA989492D979FC5A4D5F2" + + "13515AD7E9CB99A980BDAD5AD5BB4636ADB9B5706A67DCDE75573FD71BEF16D7", 16 + ); + + /** + * Pairing result g = computed using the Tate-Lichtenbaum pairing + * (RFC 6508, Section 3.2). Value from RFC 6509 Appendix A. + */ + private static final BigInteger g = new BigInteger(1, Hex.decode("66FC2A43 2B6EA392 148F1586 7D623068\n" + + " C6A87BD1 FB94C41E 27FABE65 8E015A87\n" + + " 371E9474 4C96FEDA 449AE956 3F8BC446\n" + + " CBFDA85D 5D00EF57 7072DA8F 541721BE\n" + + " EE0FAED1 828EAB90 B99DFB01 38C78433\n" + + " 55DF0460 B4A9FD74 B4F1A32B CAFA1FFA\n" + + " D682C033 A7942BCC E3720F20 B9B7B040\n" + + " 3C8CAE87 B7A0042A CDE0FAB3 6461EA46")); + + /** + * The elliptic curve E: y² = x³ - 3x over F_p (RFC 6508, Section 3.1). + * Uses parameters from RFC 6509 Appendix A. + */ + private static final ECCurve.Fp curve = new ECCurve.Fp( + p, // Prime p + BigInteger.valueOf(-3).mod(p), // a = -3 + BigInteger.ZERO, // , + g, // Order of the subgroup (from RFC 6509) + BigInteger.ONE // Cofactor = 1 + ); + + /** + * Base point P on the elliptic curve E(F_p) (RFC 6508, Section 3.1). + * Coordinates from RFC 6509 Appendix A. + */ + static final ECPoint P = curve.createPoint(Px, Py); + /** KMS Public Key Z_S = [z_S]P (RFC 6508, Section 2.2) */ + private final ECPoint Z; + /** User's Identifier (RFC 6508, Section 2.2) */ + private final BigInteger identifier; // User's identity + /** Security parameter: SSV bit length (n = 128 bits) */ + private static final int n = 128; // SSV bit length + /** Hash function (SHA-256) used in SAKKE operations */ + private final Digest digest = new SHA256Digest(); + /** + * Constructs SAKKE public key parameters with the specified identifier and KMS Public Key. + * + * @param identifier The user's identifier as defined in RFC 6508, Section 2.2. + * Must be a valid integer in [2, q-1]. + * @param Z The KMS Public Key Z_S = [z_S]P (RFC 6508, Section 2.2). + * Must be a valid point on the curve E(F_p). + */ + public SAKKEPublicKeyParameters(BigInteger identifier, ECPoint Z) + { + super(false); + this.identifier = identifier; + this.Z = Z; + } + + /** + * @return The user's identifier (RFC 6508, Section 2.2) + */ + public BigInteger getIdentifier() + { + return identifier; + } + + /** + * @return The KMS Public Key Z_S = [z_S]P (RFC 6508, Section 2.2) + */ + public ECPoint getZ() + { + return Z; + } + + /** + * @return The elliptic curve E(F_p) with parameters from RFC 6509 Appendix A + */ + public ECCurve getCurve() + { + return curve; + } + + /** + * @return The base point P on E(F_p) (RFC 6508, Section 3.1) + */ + public ECPoint getPoint() + { + return P; + } + + /** + * @return Prime modulus p defining the field F_p (RFC 6508, Section 2.1) + */ + public BigInteger getPrime() + { + return p; + } + + /** + * @return Subgroup order q (divides p+1) (RFC 6508, Section 2.1) + */ + public BigInteger getQ() + { + return q; + } + + /** + * @return Security parameter n (SSV bit length = 128 bits) + */ + public int getN() + { + return n; + } + + /** + * @return The hash function (SHA-256) used in SAKKE operations + */ + public Digest getDigest() + { + return digest; + } + + /** + * @return The pairing result g = (RFC 6508, Section 3.2) + */ + public BigInteger getG() + { + return g; + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/params/package-info.java b/core/src/main/java/org/bouncycastle/crypto/params/package-info.java new file mode 100644 index 0000000000..04fc776863 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/params/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for parameter objects for ciphers and generators. + */ +package org.bouncycastle.crypto.params; diff --git a/core/src/main/java/org/bouncycastle/crypto/parsers/ECIESPublicKeyParser.java b/core/src/main/java/org/bouncycastle/crypto/parsers/ECIESPublicKeyParser.java index b6b6e857dc..8e58ce6a2f 100644 --- a/core/src/main/java/org/bouncycastle/crypto/parsers/ECIESPublicKeyParser.java +++ b/core/src/main/java/org/bouncycastle/crypto/parsers/ECIESPublicKeyParser.java @@ -1,5 +1,6 @@ package org.bouncycastle.crypto.parsers; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -7,6 +8,7 @@ import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; +import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.io.Streams; public class ECIESPublicKeyParser @@ -22,10 +24,14 @@ public ECIESPublicKeyParser(ECDomainParameters ecParams) public AsymmetricKeyParameter readKey(InputStream stream) throws IOException { - byte[] V; - int first = stream.read(); + int first = stream.read(); + if (first < 0) + { + throw new EOFException(); + } // Decode the public ephemeral key + boolean compressed; switch (first) { case 0x00: // infinity @@ -33,22 +39,30 @@ public AsymmetricKeyParameter readKey(InputStream stream) case 0x02: // compressed case 0x03: // Byte length calculated as in ECPoint.getEncoded(); - V = new byte[1 + (ecParams.getCurve().getFieldSize()+7)/8]; + compressed = true; break; case 0x04: // uncompressed or case 0x06: // hybrid case 0x07: // Byte length calculated as in ECPoint.getEncoded(); - V = new byte[1 + 2*((ecParams.getCurve().getFieldSize()+7)/8)]; + compressed = false; break; default: throw new IOException("Sender's public key has invalid point encoding 0x" + Integer.toString(first, 16)); } + ECCurve curve = ecParams.getCurve(); + int encodingLength = curve.getAffinePointEncodingLength(compressed); + byte[] V = new byte[encodingLength]; V[0] = (byte)first; - Streams.readFully(stream, V, 1, V.length - 1); - return new ECPublicKeyParameters(ecParams.getCurve().decodePoint(V), ecParams); + int readLength = encodingLength - 1; + if (Streams.readFully(stream, V, 1, readLength) != readLength) + { + throw new EOFException(); + } + + return new ECPublicKeyParameters(curve.decodePoint(V), ecParams); } } diff --git a/core/src/main/java/org/bouncycastle/crypto/parsers/package-info.java b/core/src/main/java/org/bouncycastle/crypto/parsers/package-info.java new file mode 100644 index 0000000000..a885308816 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/parsers/package-info.java @@ -0,0 +1,4 @@ +/** + * Helper classes for parsing "on the wire" public keys. + */ +package org.bouncycastle.crypto.parsers; diff --git a/core/src/main/java/org/bouncycastle/crypto/prng/drbg/DualECSP800DRBG.java b/core/src/main/java/org/bouncycastle/crypto/prng/drbg/DualECSP800DRBG.java index 83fa545e58..2d3aaba7d9 100644 --- a/core/src/main/java/org/bouncycastle/crypto/prng/drbg/DualECSP800DRBG.java +++ b/core/src/main/java/org/bouncycastle/crypto/prng/drbg/DualECSP800DRBG.java @@ -2,8 +2,8 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.crypto.prng.EntropySource; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECMultiplier; @@ -36,23 +36,18 @@ public class DualECSP800DRBG private static final BigInteger p521_Qx = new BigInteger("1b9fa3e518d683c6b65763694ac8efbaec6fab44f2276171a42726507dd08add4c3b3f4c1ebc5b1222ddba077f722943b24c3edfa0f85fe24d0c8c01591f0be6f63", 16); private static final BigInteger p521_Qy = new BigInteger("1f3bdba585295d9a1110d1df1f9430ef8442c5018976ff3437ef91b81dc0b8132c8d5c39c32d0e004a3092b7d327c0e7a4d26d2c7b69b58f9066652911e457779de", 16); - private static final DualECPoints[] nistPoints; - - static + private static final DualECPoints[] nistPoints = new DualECPoints[] { - nistPoints = new DualECPoints[3]; - - ECCurve.Fp curve = (ECCurve.Fp)NISTNamedCurves.getByNameLazy("P-256").getCurve(); - - nistPoints[0] = new DualECPoints(128, curve.createPoint(p256_Px, p256_Py), curve.createPoint(p256_Qx, p256_Qy), 1); - - curve = (ECCurve.Fp)NISTNamedCurves.getByNameLazy("P-384").getCurve(); - - nistPoints[1] = new DualECPoints(192, curve.createPoint(p384_Px, p384_Py), curve.createPoint(p384_Qx, p384_Qy), 1); + createDualECPoints("P-256", 128, p256_Px, p256_Py, p256_Qx, p256_Qy, 1), + createDualECPoints("P-384", 192, p384_Px, p384_Py, p384_Qx, p384_Qy, 1), + createDualECPoints("P-521", 256, p521_Px, p521_Py, p521_Qx, p521_Qy, 1), + }; - curve = (ECCurve.Fp)NISTNamedCurves.getByNameLazy("P-521").getCurve(); - - nistPoints[2] = new DualECPoints(256, curve.createPoint(p521_Px, p521_Py), curve.createPoint(p521_Qx, p521_Qy), 1); + private static DualECPoints createDualECPoints(String curveName, int securityStrength, BigInteger Px, + BigInteger Py, BigInteger Qx, BigInteger Qy, int cofactor) + { + ECCurve.AbstractFp c = (ECCurve.AbstractFp)CustomNamedCurves.getByNameLazy(curveName).getCurve(); + return new DualECPoints(securityStrength, c.createPoint(Px, Py), c.createPoint(Qx, Qy), cofactor); } @@ -67,7 +62,6 @@ public class DualECSP800DRBG private int _securityStrength; private int _seedlen; private int _outlen; - private ECCurve.Fp _curve; private ECPoint _P; private ECPoint _Q; private byte[] _s; @@ -210,11 +204,9 @@ public int generate(byte[] output, byte[] additionalInput, boolean predictionRes { s = getScalarMultipleXCoord(_P, s); - //System.err.println("S: " + new String(Hex.encode(_s))); - byte[] r = getScalarMultipleXCoord(_Q, s).toByteArray(); - if (r.length > _outlen) + if (r.length >= _outlen) { System.arraycopy(r, r.length - _outlen, output, outOffset, _outlen); } @@ -223,7 +215,6 @@ public int generate(byte[] output, byte[] additionalInput, boolean predictionRes System.arraycopy(r, 0, output, outOffset + (_outlen - r.length), r.length); } - //System.err.println("R: " + new String(Hex.encode(r))); outOffset += _outlen; _reseedCounter++; @@ -237,13 +228,17 @@ public int generate(byte[] output, byte[] additionalInput, boolean predictionRes int required = output.length - outOffset; - if (r.length > _outlen) + if (r.length >= _outlen) { System.arraycopy(r, r.length - _outlen, output, outOffset, required); } else { - System.arraycopy(r, 0, output, outOffset + (_outlen - r.length), required); + int outPos = _outlen - r.length; + if (outPos < required) + { + System.arraycopy(r, 0, output, outOffset + outPos, required - outPos); + } } _reseedCounter++; diff --git a/core/src/main/java/org/bouncycastle/crypto/prng/drbg/package-info.java b/core/src/main/java/org/bouncycastle/crypto/prng/drbg/package-info.java new file mode 100644 index 0000000000..b920674db3 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/prng/drbg/package-info.java @@ -0,0 +1,4 @@ +/** + * SP800-90A deterministic random bit generators, can be used stand alone or in conjunction with SP800SecureRandomBuilder class. + */ +package org.bouncycastle.crypto.prng.drbg; diff --git a/core/src/main/java/org/bouncycastle/crypto/prng/package-info.java b/core/src/main/java/org/bouncycastle/crypto/prng/package-info.java new file mode 100644 index 0000000000..27a1118e71 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/prng/package-info.java @@ -0,0 +1,4 @@ +/** + * Lightweight psuedo-random number generators and SecureRandom builders. + */ +package org.bouncycastle.crypto.prng; diff --git a/core/src/main/java/org/bouncycastle/crypto/signers/ECCSISigner.java b/core/src/main/java/org/bouncycastle/crypto/signers/ECCSISigner.java new file mode 100644 index 0000000000..bec1461a8a --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/signers/ECCSISigner.java @@ -0,0 +1,235 @@ +package org.bouncycastle.crypto.signers; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.params.ECCSIPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECCSIPublicKeyParameters; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; + +/** + * Implementation of Elliptic Curve-based Certificateless Signatures for Identity-Based Encryption (ECCSI) + * as defined in RFC 6507. + * + * @see RFC 6507: Elliptic Curve-Based Certificateless + * Signatures for Identity-Based Encryption (ECCSI) + */ +public class ECCSISigner + implements Signer +{ + private final BigInteger q; + private final ECPoint G; + private final Digest digest; + private BigInteger j; + private BigInteger r; + private ECPoint Y; + private final ECPoint kpak; + private final byte[] id; + private CipherParameters param; + private ByteArrayOutputStream stream; + private boolean forSigning; + private final int N; + + /** + * Constructs an ECCSI signer/verifier with KMS Public Authentication Key and user identity. + * + * @param kpak KMS Public Authentication Key (KPAK) from RFC 6507 Section 2 + * @param id User identity byte array formatted + */ + public ECCSISigner(ECPoint kpak, X9ECParameters params, Digest digest, byte[] id) + { + this.kpak = kpak; + this.id = id; + this.q = params.getCurve().getOrder(); + this.G = params.getG(); + this.digest = digest; + this.digest.reset(); + this.N = (params.getCurve().getOrder().bitLength() + 7) >> 3; + } + + /** + * Initializes the signer for either signature generation or verification. + * + * @param forSigning true for signing, false for verification + * @param param Key parameters: + * - For signing: {@code ParametersWithRandom} containing {@code ECCSIPrivateKeyParameters} + * - For verification: {@code ECCSIPublicKeyParameters} + * @throws IllegalArgumentException if invalid parameters are provided + */ + @Override + public void init(boolean forSigning, CipherParameters param) + { + this.forSigning = forSigning; + this.param = param; + reset(); + } + + @Override + public void update(byte b) + { + if (forSigning) + { + digest.update(b); + } + else + { + stream.write(b); + } + } + + @Override + public void update(byte[] in, int off, int len) + { + if (forSigning) + { + digest.update(in, off, len); + } + else + { + stream.write(in, off, len); + } + } + + /** + * Generates an ECCSI signature according to RFC 6507 Section 5.2.1. + * + * @return Signature structure containing: + * - r (N bytes) + * - s (N bytes) + * - PVT (Public Validation Token) + * @throws CryptoException if cryptographic operations fail + * @throws DataLengthException if input data is invalid + * @throws IllegalArgumentException if invalid SSK or j parameter is detected + */ + @Override + public byte[] generateSignature() + throws CryptoException, DataLengthException + { + byte[] heBytes = new byte[digest.getDigestSize()]; + digest.doFinal(heBytes, 0); + + //Compute s' = ( (( HE + r * SSK )^-1) * j ) modulo q + ECCSIPrivateKeyParameters params = (ECCSIPrivateKeyParameters)(((ParametersWithRandom)param).getParameters()); + BigInteger ssk = params.getSSK(); + BigInteger denominator = new BigInteger(1, heBytes).add(r.multiply(ssk)).mod(q); + if (denominator.equals(BigInteger.ZERO)) + { + throw new IllegalArgumentException("Invalid j, retry"); + } + + BigInteger sPrime = denominator.modInverse(q).multiply(j).mod(q); + + return Arrays.concatenate(BigIntegers.asUnsignedByteArray(this.N, r), BigIntegers.asUnsignedByteArray(this.N, sPrime), + params.getPublicKeyParameters().getPVT().getEncoded(false)); + } + + /** + * Verifies an ECCSI signature according to RFC 6507 Section 5.2.2. + * + * @param signature Signature to verify (r || s || PVT) + * @return true if signature is valid, false otherwise + * @throws IllegalArgumentException if signature format is invalid + */ + @Override + public boolean verifySignature(byte[] signature) + { + byte[] bytes = Arrays.copyOf(signature, this.N); + BigInteger s = new BigInteger(1, Arrays.copyOfRange(signature, this.N, this.N << 1)); + r = new BigInteger(1, bytes).mod(q); + digest.update(bytes, 0, this.N); + bytes = stream.toByteArray(); + digest.update(bytes, 0, bytes.length); + bytes = new byte[digest.getDigestSize()]; + digest.doFinal(bytes, 0); + + BigInteger HE = new BigInteger(1, bytes).mod(q); + + // Compute J = s*(HE*G + r*Y) + ECPoint HE_G = G.multiply(HE).normalize(); + ECPoint rY = Y.multiply(r).normalize(); + ECPoint sum = HE_G.add(rY).normalize(); + ECPoint J = sum.multiply(s).normalize(); + + BigInteger rComputed = J.getAffineXCoord().toBigInteger(); + + return rComputed.mod(q).equals(r.mod(q)); + } + + /** + * Resets the signer/verifier state and performs initial computations: + * - For signing: Validates KPAK consistency (RFC 6507 Section 5.1.2) + * - For verification: Computes Y = HS·PVT + KPAK + * + * Also computes HS = hash(G || KPAK || ID || PVT) as per RFC 6507 Section 5.1.1 + */ + @Override + public void reset() + { + digest.reset(); + CipherParameters param = this.param; + SecureRandom random = null; + if (param instanceof ParametersWithRandom) + { + random = ((ParametersWithRandom)param).getRandom(); + param = ((ParametersWithRandom)param).getParameters(); + } + ECPoint kpak_computed = null; + ECPoint pvt; + if (forSigning) + { + ECCSIPrivateKeyParameters parameters = (ECCSIPrivateKeyParameters)param; + pvt = parameters.getPublicKeyParameters().getPVT(); + j = BigIntegers.createRandomBigInteger(q.bitLength(), random); + ECPoint J = G.multiply(j).normalize(); + r = J.getAffineXCoord().toBigInteger().mod(q); + + kpak_computed = G.multiply(parameters.getSSK()); + } + else + { + ECCSIPublicKeyParameters parameters = (ECCSIPublicKeyParameters)param; + pvt = parameters.getPVT(); + stream = new ByteArrayOutputStream(); + } + + // compute HS + byte[] tmp = G.getEncoded(false); + digest.update(tmp, 0, tmp.length); + tmp = kpak.getEncoded(false); + digest.update(tmp, 0, tmp.length); + digest.update(id, 0, id.length); + tmp = pvt.getEncoded(false); + digest.update(tmp, 0, tmp.length); + tmp = new byte[digest.getDigestSize()]; + digest.doFinal(tmp, 0); + BigInteger HS = new BigInteger(1, tmp).mod(q); + + //HE = hash( HS || r || M ); + digest.update(tmp, 0, tmp.length); + if (forSigning) + { + kpak_computed = kpak_computed.subtract(pvt.multiply(HS)).normalize(); + if (!kpak_computed.equals(kpak)) + { + throw new IllegalArgumentException("Invalid KPAK"); + } + byte[] rBytes = BigIntegers.asUnsignedByteArray(this.N, r); + digest.update(rBytes, 0, rBytes.length); + } + else + { + // Compute Y = HS*PVT + KPAK + Y = pvt.multiply(HS).add(kpak).normalize(); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/signers/package-info.java b/core/src/main/java/org/bouncycastle/crypto/signers/package-info.java new file mode 100644 index 0000000000..98d36e6c48 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/signers/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic signers. + */ +package org.bouncycastle.crypto.signers; diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/Polynomial.java b/core/src/main/java/org/bouncycastle/crypto/threshold/Polynomial.java new file mode 100644 index 0000000000..7ebcd68c7c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/Polynomial.java @@ -0,0 +1,287 @@ +package org.bouncycastle.crypto.threshold; + +abstract class Polynomial +{ + public static Polynomial newInstance(ShamirSecretSplitter.Algorithm algorithm, ShamirSecretSplitter.Mode mode) + { + if (mode == ShamirSecretSplitter.Mode.Native) + { + return new PolynomialNative(algorithm); + } + else + { + return new PolynomialTable(algorithm); + } + } + + protected abstract byte gfMul(int x, int y); + + protected abstract byte gfDiv(int x, int y); + + protected byte gfPow(int n, byte k) + { + int result = 1; + for (int i = 0; i < 8; i++) + { + if ((k & (1 << i)) != 0) + { + result = gfMul(result & 0xff, n & 0xff); + } + n = gfMul(n & 0xff, n & 0xff); + } + return (byte)result; + } + + public byte[] gfVecMul(byte[] xs, byte[][] yss) + { + byte[] result = new byte[yss[0].length]; + int sum; + for (int j = 0; j < yss[0].length; j++) + { + sum = 0; + for (int k = 0; k < xs.length; k++) + { + sum ^= gfMul(xs[k] & 0xff, yss[k][j] & 0xff); + } + result[j] = (byte)sum; + } + return result; + } +} + +class PolynomialTable + extends Polynomial +{ + private final byte[] LOG; + private final byte[] EXP; + private static final byte[] AES_LOG = { + (byte)0x00, (byte)0xff, (byte)0x19, (byte)0x01, (byte)0x32, (byte)0x02, (byte)0x1a, (byte)0xc6, + (byte)0x4b, (byte)0xc7, (byte)0x1b, (byte)0x68, (byte)0x33, (byte)0xee, (byte)0xdf, (byte)0x03, + (byte)0x64, (byte)0x04, (byte)0xe0, (byte)0x0e, (byte)0x34, (byte)0x8d, (byte)0x81, (byte)0xef, + (byte)0x4c, (byte)0x71, (byte)0x08, (byte)0xc8, (byte)0xf8, (byte)0x69, (byte)0x1c, (byte)0xc1, + (byte)0x7d, (byte)0xc2, (byte)0x1d, (byte)0xb5, (byte)0xf9, (byte)0xb9, (byte)0x27, (byte)0x6a, + (byte)0x4d, (byte)0xe4, (byte)0xa6, (byte)0x72, (byte)0x9a, (byte)0xc9, (byte)0x09, (byte)0x78, + (byte)0x65, (byte)0x2f, (byte)0x8a, (byte)0x05, (byte)0x21, (byte)0x0f, (byte)0xe1, (byte)0x24, + (byte)0x12, (byte)0xf0, (byte)0x82, (byte)0x45, (byte)0x35, (byte)0x93, (byte)0xda, (byte)0x8e, + (byte)0x96, (byte)0x8f, (byte)0xdb, (byte)0xbd, (byte)0x36, (byte)0xd0, (byte)0xce, (byte)0x94, + (byte)0x13, (byte)0x5c, (byte)0xd2, (byte)0xf1, (byte)0x40, (byte)0x46, (byte)0x83, (byte)0x38, + (byte)0x66, (byte)0xdd, (byte)0xfd, (byte)0x30, (byte)0xbf, (byte)0x06, (byte)0x8b, (byte)0x62, + (byte)0xb3, (byte)0x25, (byte)0xe2, (byte)0x98, (byte)0x22, (byte)0x88, (byte)0x91, (byte)0x10, + (byte)0x7e, (byte)0x6e, (byte)0x48, (byte)0xc3, (byte)0xa3, (byte)0xb6, (byte)0x1e, (byte)0x42, + (byte)0x3a, (byte)0x6b, (byte)0x28, (byte)0x54, (byte)0xfa, (byte)0x85, (byte)0x3d, (byte)0xba, + (byte)0x2b, (byte)0x79, (byte)0x0a, (byte)0x15, (byte)0x9b, (byte)0x9f, (byte)0x5e, (byte)0xca, + (byte)0x4e, (byte)0xd4, (byte)0xac, (byte)0xe5, (byte)0xf3, (byte)0x73, (byte)0xa7, (byte)0x57, + (byte)0xaf, (byte)0x58, (byte)0xa8, (byte)0x50, (byte)0xf4, (byte)0xea, (byte)0xd6, (byte)0x74, + (byte)0x4f, (byte)0xae, (byte)0xe9, (byte)0xd5, (byte)0xe7, (byte)0xe6, (byte)0xad, (byte)0xe8, + (byte)0x2c, (byte)0xd7, (byte)0x75, (byte)0x7a, (byte)0xeb, (byte)0x16, (byte)0x0b, (byte)0xf5, + (byte)0x59, (byte)0xcb, (byte)0x5f, (byte)0xb0, (byte)0x9c, (byte)0xa9, (byte)0x51, (byte)0xa0, + (byte)0x7f, (byte)0x0c, (byte)0xf6, (byte)0x6f, (byte)0x17, (byte)0xc4, (byte)0x49, (byte)0xec, + (byte)0xd8, (byte)0x43, (byte)0x1f, (byte)0x2d, (byte)0xa4, (byte)0x76, (byte)0x7b, (byte)0xb7, + (byte)0xcc, (byte)0xbb, (byte)0x3e, (byte)0x5a, (byte)0xfb, (byte)0x60, (byte)0xb1, (byte)0x86, + (byte)0x3b, (byte)0x52, (byte)0xa1, (byte)0x6c, (byte)0xaa, (byte)0x55, (byte)0x29, (byte)0x9d, + (byte)0x97, (byte)0xb2, (byte)0x87, (byte)0x90, (byte)0x61, (byte)0xbe, (byte)0xdc, (byte)0xfc, + (byte)0xbc, (byte)0x95, (byte)0xcf, (byte)0xcd, (byte)0x37, (byte)0x3f, (byte)0x5b, (byte)0xd1, + (byte)0x53, (byte)0x39, (byte)0x84, (byte)0x3c, (byte)0x41, (byte)0xa2, (byte)0x6d, (byte)0x47, + (byte)0x14, (byte)0x2a, (byte)0x9e, (byte)0x5d, (byte)0x56, (byte)0xf2, (byte)0xd3, (byte)0xab, + (byte)0x44, (byte)0x11, (byte)0x92, (byte)0xd9, (byte)0x23, (byte)0x20, (byte)0x2e, (byte)0x89, + (byte)0xb4, (byte)0x7c, (byte)0xb8, (byte)0x26, (byte)0x77, (byte)0x99, (byte)0xe3, (byte)0xa5, + (byte)0x67, (byte)0x4a, (byte)0xed, (byte)0xde, (byte)0xc5, (byte)0x31, (byte)0xfe, (byte)0x18, + (byte)0x0d, (byte)0x63, (byte)0x8c, (byte)0x80, (byte)0xc0, (byte)0xf7, (byte)0x70, (byte)0x07 + }; + /* given a j, (byte)return alpha^j, (byte)where alpha = mimimum primitive element (x + 1 = 3) */ + private static final byte[] AES_EXP = { + (byte)0x01, (byte)0x03, (byte)0x05, (byte)0x0f, (byte)0x11, (byte)0x33, (byte)0x55, (byte)0xff, + (byte)0x1a, (byte)0x2e, (byte)0x72, (byte)0x96, (byte)0xa1, (byte)0xf8, (byte)0x13, (byte)0x35, + (byte)0x5f, (byte)0xe1, (byte)0x38, (byte)0x48, (byte)0xd8, (byte)0x73, (byte)0x95, (byte)0xa4, + (byte)0xf7, (byte)0x02, (byte)0x06, (byte)0x0a, (byte)0x1e, (byte)0x22, (byte)0x66, (byte)0xaa, + (byte)0xe5, (byte)0x34, (byte)0x5c, (byte)0xe4, (byte)0x37, (byte)0x59, (byte)0xeb, (byte)0x26, + (byte)0x6a, (byte)0xbe, (byte)0xd9, (byte)0x70, (byte)0x90, (byte)0xab, (byte)0xe6, (byte)0x31, + (byte)0x53, (byte)0xf5, (byte)0x04, (byte)0x0c, (byte)0x14, (byte)0x3c, (byte)0x44, (byte)0xcc, + (byte)0x4f, (byte)0xd1, (byte)0x68, (byte)0xb8, (byte)0xd3, (byte)0x6e, (byte)0xb2, (byte)0xcd, + (byte)0x4c, (byte)0xd4, (byte)0x67, (byte)0xa9, (byte)0xe0, (byte)0x3b, (byte)0x4d, (byte)0xd7, + (byte)0x62, (byte)0xa6, (byte)0xf1, (byte)0x08, (byte)0x18, (byte)0x28, (byte)0x78, (byte)0x88, + (byte)0x83, (byte)0x9e, (byte)0xb9, (byte)0xd0, (byte)0x6b, (byte)0xbd, (byte)0xdc, (byte)0x7f, + (byte)0x81, (byte)0x98, (byte)0xb3, (byte)0xce, (byte)0x49, (byte)0xdb, (byte)0x76, (byte)0x9a, + (byte)0xb5, (byte)0xc4, (byte)0x57, (byte)0xf9, (byte)0x10, (byte)0x30, (byte)0x50, (byte)0xf0, + (byte)0x0b, (byte)0x1d, (byte)0x27, (byte)0x69, (byte)0xbb, (byte)0xd6, (byte)0x61, (byte)0xa3, + (byte)0xfe, (byte)0x19, (byte)0x2b, (byte)0x7d, (byte)0x87, (byte)0x92, (byte)0xad, (byte)0xec, + (byte)0x2f, (byte)0x71, (byte)0x93, (byte)0xae, (byte)0xe9, (byte)0x20, (byte)0x60, (byte)0xa0, + (byte)0xfb, (byte)0x16, (byte)0x3a, (byte)0x4e, (byte)0xd2, (byte)0x6d, (byte)0xb7, (byte)0xc2, + (byte)0x5d, (byte)0xe7, (byte)0x32, (byte)0x56, (byte)0xfa, (byte)0x15, (byte)0x3f, (byte)0x41, + (byte)0xc3, (byte)0x5e, (byte)0xe2, (byte)0x3d, (byte)0x47, (byte)0xc9, (byte)0x40, (byte)0xc0, + (byte)0x5b, (byte)0xed, (byte)0x2c, (byte)0x74, (byte)0x9c, (byte)0xbf, (byte)0xda, (byte)0x75, + (byte)0x9f, (byte)0xba, (byte)0xd5, (byte)0x64, (byte)0xac, (byte)0xef, (byte)0x2a, (byte)0x7e, + (byte)0x82, (byte)0x9d, (byte)0xbc, (byte)0xdf, (byte)0x7a, (byte)0x8e, (byte)0x89, (byte)0x80, + (byte)0x9b, (byte)0xb6, (byte)0xc1, (byte)0x58, (byte)0xe8, (byte)0x23, (byte)0x65, (byte)0xaf, + (byte)0xea, (byte)0x25, (byte)0x6f, (byte)0xb1, (byte)0xc8, (byte)0x43, (byte)0xc5, (byte)0x54, + (byte)0xfc, (byte)0x1f, (byte)0x21, (byte)0x63, (byte)0xa5, (byte)0xf4, (byte)0x07, (byte)0x09, + (byte)0x1b, (byte)0x2d, (byte)0x77, (byte)0x99, (byte)0xb0, (byte)0xcb, (byte)0x46, (byte)0xca, + (byte)0x45, (byte)0xcf, (byte)0x4a, (byte)0xde, (byte)0x79, (byte)0x8b, (byte)0x86, (byte)0x91, + (byte)0xa8, (byte)0xe3, (byte)0x3e, (byte)0x42, (byte)0xc6, (byte)0x51, (byte)0xf3, (byte)0x0e, + (byte)0x12, (byte)0x36, (byte)0x5a, (byte)0xee, (byte)0x29, (byte)0x7b, (byte)0x8d, (byte)0x8c, + (byte)0x8f, (byte)0x8a, (byte)0x85, (byte)0x94, (byte)0xa7, (byte)0xf2, (byte)0x0d, (byte)0x17, + (byte)0x39, (byte)0x4b, (byte)0xdd, (byte)0x7c, (byte)0x84, (byte)0x97, (byte)0xa2, (byte)0xfd, + (byte)0x1c, (byte)0x24, (byte)0x6c, (byte)0xb4, (byte)0xc7, (byte)0x52, (byte)0xf6, (byte)0x01 + }; + + /* given an alpha^j, (byte)where alpha = mimimum primitive element (x + 1 = 3), (byte)return j */ + private static final byte[] RSA_LOG = { + (byte)0xff, (byte)0x00, (byte)0x01, (byte)0x19, (byte)0x02, (byte)0x32, (byte)0x1a, (byte)0xc6, + (byte)0x03, (byte)0xdf, (byte)0x33, (byte)0xee, (byte)0x1b, (byte)0x68, (byte)0xc7, (byte)0x4b, + (byte)0x04, (byte)0x64, (byte)0xe0, (byte)0x0e, (byte)0x34, (byte)0x8d, (byte)0xef, (byte)0x81, + (byte)0x1c, (byte)0xc1, (byte)0x69, (byte)0xf8, (byte)0xc8, (byte)0x08, (byte)0x4c, (byte)0x71, + (byte)0x05, (byte)0x8a, (byte)0x65, (byte)0x2f, (byte)0xe1, (byte)0x24, (byte)0x0f, (byte)0x21, + (byte)0x35, (byte)0x93, (byte)0x8e, (byte)0xda, (byte)0xf0, (byte)0x12, (byte)0x82, (byte)0x45, + (byte)0x1d, (byte)0xb5, (byte)0xc2, (byte)0x7d, (byte)0x6a, (byte)0x27, (byte)0xf9, (byte)0xb9, + (byte)0xc9, (byte)0x9a, (byte)0x09, (byte)0x78, (byte)0x4d, (byte)0xe4, (byte)0x72, (byte)0xa6, + (byte)0x06, (byte)0xbf, (byte)0x8b, (byte)0x62, (byte)0x66, (byte)0xdd, (byte)0x30, (byte)0xfd, + (byte)0xe2, (byte)0x98, (byte)0x25, (byte)0xb3, (byte)0x10, (byte)0x91, (byte)0x22, (byte)0x88, + (byte)0x36, (byte)0xd0, (byte)0x94, (byte)0xce, (byte)0x8f, (byte)0x96, (byte)0xdb, (byte)0xbd, + (byte)0xf1, (byte)0xd2, (byte)0x13, (byte)0x5c, (byte)0x83, (byte)0x38, (byte)0x46, (byte)0x40, + (byte)0x1e, (byte)0x42, (byte)0xb6, (byte)0xa3, (byte)0xc3, (byte)0x48, (byte)0x7e, (byte)0x6e, + (byte)0x6b, (byte)0x3a, (byte)0x28, (byte)0x54, (byte)0xfa, (byte)0x85, (byte)0xba, (byte)0x3d, + (byte)0xca, (byte)0x5e, (byte)0x9b, (byte)0x9f, (byte)0x0a, (byte)0x15, (byte)0x79, (byte)0x2b, + (byte)0x4e, (byte)0xd4, (byte)0xe5, (byte)0xac, (byte)0x73, (byte)0xf3, (byte)0xa7, (byte)0x57, + (byte)0x07, (byte)0x70, (byte)0xc0, (byte)0xf7, (byte)0x8c, (byte)0x80, (byte)0x63, (byte)0x0d, + (byte)0x67, (byte)0x4a, (byte)0xde, (byte)0xed, (byte)0x31, (byte)0xc5, (byte)0xfe, (byte)0x18, + (byte)0xe3, (byte)0xa5, (byte)0x99, (byte)0x77, (byte)0x26, (byte)0xb8, (byte)0xb4, (byte)0x7c, + (byte)0x11, (byte)0x44, (byte)0x92, (byte)0xd9, (byte)0x23, (byte)0x20, (byte)0x89, (byte)0x2e, + (byte)0x37, (byte)0x3f, (byte)0xd1, (byte)0x5b, (byte)0x95, (byte)0xbc, (byte)0xcf, (byte)0xcd, + (byte)0x90, (byte)0x87, (byte)0x97, (byte)0xb2, (byte)0xdc, (byte)0xfc, (byte)0xbe, (byte)0x61, + (byte)0xf2, (byte)0x56, (byte)0xd3, (byte)0xab, (byte)0x14, (byte)0x2a, (byte)0x5d, (byte)0x9e, + (byte)0x84, (byte)0x3c, (byte)0x39, (byte)0x53, (byte)0x47, (byte)0x6d, (byte)0x41, (byte)0xa2, + (byte)0x1f, (byte)0x2d, (byte)0x43, (byte)0xd8, (byte)0xb7, (byte)0x7b, (byte)0xa4, (byte)0x76, + (byte)0xc4, (byte)0x17, (byte)0x49, (byte)0xec, (byte)0x7f, (byte)0x0c, (byte)0x6f, (byte)0xf6, + (byte)0x6c, (byte)0xa1, (byte)0x3b, (byte)0x52, (byte)0x29, (byte)0x9d, (byte)0x55, (byte)0xaa, + (byte)0xfb, (byte)0x60, (byte)0x86, (byte)0xb1, (byte)0xbb, (byte)0xcc, (byte)0x3e, (byte)0x5a, + (byte)0xcb, (byte)0x59, (byte)0x5f, (byte)0xb0, (byte)0x9c, (byte)0xa9, (byte)0xa0, (byte)0x51, + (byte)0x0b, (byte)0xf5, (byte)0x16, (byte)0xeb, (byte)0x7a, (byte)0x75, (byte)0x2c, (byte)0xd7, + (byte)0x4f, (byte)0xae, (byte)0xd5, (byte)0xe9, (byte)0xe6, (byte)0xe7, (byte)0xad, (byte)0xe8, + (byte)0x74, (byte)0xd6, (byte)0xf4, (byte)0xea, (byte)0xa8, (byte)0x50, (byte)0x58, (byte)0xaf + }; + /* given a j, (byte)return alpha^j, (byte)where alpha = mimimum primitive element (x + 1 = 3) */ + private static final byte[] RSA_EXP = { + (byte)0x01, (byte)0x02, (byte)0x04, (byte)0x08, (byte)0x10, (byte)0x20, (byte)0x40, (byte)0x80, + (byte)0x1d, (byte)0x3a, (byte)0x74, (byte)0xe8, (byte)0xcd, (byte)0x87, (byte)0x13, (byte)0x26, + (byte)0x4c, (byte)0x98, (byte)0x2d, (byte)0x5a, (byte)0xb4, (byte)0x75, (byte)0xea, (byte)0xc9, + (byte)0x8f, (byte)0x03, (byte)0x06, (byte)0x0c, (byte)0x18, (byte)0x30, (byte)0x60, (byte)0xc0, + (byte)0x9d, (byte)0x27, (byte)0x4e, (byte)0x9c, (byte)0x25, (byte)0x4a, (byte)0x94, (byte)0x35, + (byte)0x6a, (byte)0xd4, (byte)0xb5, (byte)0x77, (byte)0xee, (byte)0xc1, (byte)0x9f, (byte)0x23, + (byte)0x46, (byte)0x8c, (byte)0x05, (byte)0x0a, (byte)0x14, (byte)0x28, (byte)0x50, (byte)0xa0, + (byte)0x5d, (byte)0xba, (byte)0x69, (byte)0xd2, (byte)0xb9, (byte)0x6f, (byte)0xde, (byte)0xa1, + (byte)0x5f, (byte)0xbe, (byte)0x61, (byte)0xc2, (byte)0x99, (byte)0x2f, (byte)0x5e, (byte)0xbc, + (byte)0x65, (byte)0xca, (byte)0x89, (byte)0x0f, (byte)0x1e, (byte)0x3c, (byte)0x78, (byte)0xf0, + (byte)0xfd, (byte)0xe7, (byte)0xd3, (byte)0xbb, (byte)0x6b, (byte)0xd6, (byte)0xb1, (byte)0x7f, + (byte)0xfe, (byte)0xe1, (byte)0xdf, (byte)0xa3, (byte)0x5b, (byte)0xb6, (byte)0x71, (byte)0xe2, + (byte)0xd9, (byte)0xaf, (byte)0x43, (byte)0x86, (byte)0x11, (byte)0x22, (byte)0x44, (byte)0x88, + (byte)0x0d, (byte)0x1a, (byte)0x34, (byte)0x68, (byte)0xd0, (byte)0xbd, (byte)0x67, (byte)0xce, + (byte)0x81, (byte)0x1f, (byte)0x3e, (byte)0x7c, (byte)0xf8, (byte)0xed, (byte)0xc7, (byte)0x93, + (byte)0x3b, (byte)0x76, (byte)0xec, (byte)0xc5, (byte)0x97, (byte)0x33, (byte)0x66, (byte)0xcc, + (byte)0x85, (byte)0x17, (byte)0x2e, (byte)0x5c, (byte)0xb8, (byte)0x6d, (byte)0xda, (byte)0xa9, + (byte)0x4f, (byte)0x9e, (byte)0x21, (byte)0x42, (byte)0x84, (byte)0x15, (byte)0x2a, (byte)0x54, + (byte)0xa8, (byte)0x4d, (byte)0x9a, (byte)0x29, (byte)0x52, (byte)0xa4, (byte)0x55, (byte)0xaa, + (byte)0x49, (byte)0x92, (byte)0x39, (byte)0x72, (byte)0xe4, (byte)0xd5, (byte)0xb7, (byte)0x73, + (byte)0xe6, (byte)0xd1, (byte)0xbf, (byte)0x63, (byte)0xc6, (byte)0x91, (byte)0x3f, (byte)0x7e, + (byte)0xfc, (byte)0xe5, (byte)0xd7, (byte)0xb3, (byte)0x7b, (byte)0xf6, (byte)0xf1, (byte)0xff, + (byte)0xe3, (byte)0xdb, (byte)0xab, (byte)0x4b, (byte)0x96, (byte)0x31, (byte)0x62, (byte)0xc4, + (byte)0x95, (byte)0x37, (byte)0x6e, (byte)0xdc, (byte)0xa5, (byte)0x57, (byte)0xae, (byte)0x41, + (byte)0x82, (byte)0x19, (byte)0x32, (byte)0x64, (byte)0xc8, (byte)0x8d, (byte)0x07, (byte)0x0e, + (byte)0x1c, (byte)0x38, (byte)0x70, (byte)0xe0, (byte)0xdd, (byte)0xa7, (byte)0x53, (byte)0xa6, + (byte)0x51, (byte)0xa2, (byte)0x59, (byte)0xb2, (byte)0x79, (byte)0xf2, (byte)0xf9, (byte)0xef, + (byte)0xc3, (byte)0x9b, (byte)0x2b, (byte)0x56, (byte)0xac, (byte)0x45, (byte)0x8a, (byte)0x09, + (byte)0x12, (byte)0x24, (byte)0x48, (byte)0x90, (byte)0x3d, (byte)0x7a, (byte)0xf4, (byte)0xf5, + (byte)0xf7, (byte)0xf3, (byte)0xfb, (byte)0xeb, (byte)0xcb, (byte)0x8b, (byte)0x0b, (byte)0x16, + (byte)0x2c, (byte)0x58, (byte)0xb0, (byte)0x7d, (byte)0xfa, (byte)0xe9, (byte)0xcf, (byte)0x83, + (byte)0x1b, (byte)0x36, (byte)0x6c, (byte)0xd8, (byte)0xad, (byte)0x47, (byte)0x8e, (byte)0x01 + }; + + public PolynomialTable(ShamirSecretSplitter.Algorithm algorithm) + { + switch (algorithm) + { + case AES: + LOG = AES_LOG; + EXP = AES_EXP; + break; + case RSA: + LOG = RSA_LOG; + EXP = RSA_EXP; + break; + default: + throw new IllegalArgumentException("The algorithm is not correct"); + } + } + + protected byte gfMul(int x, int y) + { + if (x == 0 || y == 0) + { + return 0; + } + return (byte)(EXP[((LOG[x] & 0xff) + (LOG[y] & 0xff)) % 255] & 0xff); + } + + protected byte gfDiv(int x, int y) + { + if (x == 0) + { + return 0; + } + return EXP[((LOG[x] & 0xff) - (LOG[y] & 0xff) + 255) % 255]; + } +} + +class PolynomialNative + extends Polynomial +{ + private final int IRREDUCIBLE; + + public PolynomialNative(ShamirSecretSplitter.Algorithm algorithm) + { + switch (algorithm) + { + case AES: + IRREDUCIBLE = 0x11B; + break; + case RSA: + IRREDUCIBLE = 0x11D; + break; + default: + throw new IllegalArgumentException("The algorithm is not correct"); + } + } + + protected byte gfMul(int x, int y) + { + //pmult + int result = 0; + while (y > 0) + { + if ((y & 1) != 0) + { // If the lowest bit of y is 1 + result ^= x; // XOR x into the result + } + x <<= 1; // Shift x left (multiply by 2 in GF) + if ((x & 0x100) != 0) + { // If x is larger than 8 bits, reduce + x ^= IRREDUCIBLE; // XOR with the irreducible polynomial + } + y >>= 1; // Shift y right + } + //mod + while (result >= (1 << 8)) + { + if ((result & (1 << 8)) != 0) + { + result ^= IRREDUCIBLE; + } + result <<= 1; + } + return (byte) (result & 0xFF); + } + + protected byte gfDiv(int x, int y) + { + return gfMul(x, gfPow((byte)y, (byte)254) & 0xff); + } +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/SecretShare.java b/core/src/main/java/org/bouncycastle/crypto/threshold/SecretShare.java new file mode 100644 index 0000000000..5e9a53937d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/SecretShare.java @@ -0,0 +1,8 @@ +package org.bouncycastle.crypto.threshold; + +import org.bouncycastle.util.Encodable; + +public interface SecretShare + extends Encodable +{ +} diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/SecretSplitter.java b/core/src/main/java/org/bouncycastle/crypto/threshold/SecretSplitter.java new file mode 100644 index 0000000000..95741257e4 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/SecretSplitter.java @@ -0,0 +1,36 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; + +/** + * Secret sharing (also called secret splitting) refers to methods for distributing a secret among a group. + * In this process, no individual holds any intelligible information about the secret. + * However, when a sufficient number of individuals combine their 'shares', the secret can be reconstructed. + */ +public interface SecretSplitter +{ + /** + * Creates secret shares. The secret will be divided into shares, where the secret has a length of L bytes. + * @param m A threshold number of shares + * @param n Total number of shares + * @return An array of {@code byte[][]} representing the generated secret shares for m users with l bytes each. + */ + SplitSecret split(int m, int n); + + /** + * Creates secret shares from a given secret share. The secret will be divided into shares, where the secret has a length of L bytes. + * @param m A threshold number of shares + * @param n Total number of shares + * @return An array of {@code byte[][]} representing the generated secret shares for m users with l bytes each. + */ + SplitSecret splitAround(SecretShare s, int m, int n) + throws IOException; + + /** + * Creates secret shares from a given secret. The secret will be divided into shares, where the secret has a length of L bytes. + * @param m A threshold number of shares + * @param n Total number of shares + * @return An array of {@code byte[][]} representing the generated secret shares for m users with l bytes each. + */ + SplitSecret resplit(byte[] secret, int m, int n); +} diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSecretSplitter.java b/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSecretSplitter.java new file mode 100644 index 0000000000..788186d218 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSecretSplitter.java @@ -0,0 +1,133 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.util.Arrays; + + +public class ShamirSecretSplitter + implements SecretSplitter +{ + public enum Algorithm + { + AES, + RSA + } + + public enum Mode + { + Native, + Table + } + + private final Polynomial poly; + /** + * Length of the secret + */ + protected int l; + + protected SecureRandom random; + + public ShamirSecretSplitter(Algorithm algorithm, Mode mode, int l, SecureRandom random) + { + if (l < 0 || l > 65534) + { + throw new IllegalArgumentException("Invalid input: l ranges from 0 to 65534 (2^16-2) bytes."); + } + + poly = Polynomial.newInstance(algorithm, mode); + this.l = l; + this.random = random; + } + + + public ShamirSplitSecret split(int m, int n) + { + byte[][] p = initP(m, n); + byte[][] sr = new byte[m][l]; + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[l]; + int i; + for (i = 0; i < m; i++) + { + random.nextBytes(sr[i]); + } + for (i = 0; i < p.length; i++) + { + secretShares[i] = new ShamirSplitSecretShare(poly.gfVecMul(p[i], sr), i + 1); + } + return new ShamirSplitSecret(poly, secretShares); + } + + @Override + public ShamirSplitSecret splitAround(SecretShare s, int m, int n) + throws IOException + { + byte[][] p = initP(m, n); + byte[][] sr = new byte[m][l]; + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[l]; + byte[] ss0 = s.getEncoded(); + secretShares[0] = new ShamirSplitSecretShare(ss0, 1); + int i, j; + byte tmp; + for (i = 0; i < m; i++) + { + random.nextBytes(sr[i]); + } + for (i = 0; i < l; i++) + { + tmp = sr[1][i]; + for (j = 2; j < m; j++) + { + tmp ^= sr[j][i]; + } + sr[0][i] = (byte)(tmp ^ ss0[i]); + } + for (i = 1; i < p.length; i++) + { + secretShares[i] = new ShamirSplitSecretShare(poly.gfVecMul(p[i], sr), i + 1); + } + + return new ShamirSplitSecret(poly, secretShares); + } + + @Override + public ShamirSplitSecret resplit(byte[] secret, int m, int n) + { + byte[][] p = initP(m, n); + byte[][] sr = new byte[m][l]; + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[l]; + sr[0] = Arrays.clone(secret); + int i; + for (i = 1; i < m; i++) + { + random.nextBytes(sr[i]); + } + for (i = 0; i < p.length; i++) + { + secretShares[i] = new ShamirSplitSecretShare(poly.gfVecMul(p[i], sr), i + 1); + } + return new ShamirSplitSecret(poly, secretShares); + } + + private byte[][] initP(int m, int n) + { + if (m < 1 || m > 255) + { + throw new IllegalArgumentException("Invalid input: m must be less than 256 and positive."); + } + if (n < m || n > 255) + { + throw new IllegalArgumentException("Invalid input: n must be less than 256 and greater than or equal to n."); + } + byte[][] p = new byte[n][m]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + p[i][j] = poly.gfPow((byte)(i + 1), (byte)j); + } + } + return p; + } +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSplitSecret.java b/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSplitSecret.java new file mode 100644 index 0000000000..59b2a7a66d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSplitSecret.java @@ -0,0 +1,91 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; + +public class ShamirSplitSecret + implements SplitSecret +{ + private final ShamirSplitSecretShare[] secretShares; + private final Polynomial poly; + + public ShamirSplitSecret(ShamirSecretSplitter.Algorithm algorithm, ShamirSecretSplitter.Mode mode, ShamirSplitSecretShare[] secretShares) + { + this.secretShares = secretShares; + this.poly = Polynomial.newInstance(algorithm, mode); + } + + ShamirSplitSecret(Polynomial poly, ShamirSplitSecretShare[] secretShares) + { + this.secretShares = secretShares; + this.poly = poly; + } + + public ShamirSplitSecretShare[] getSecretShares() + { + return secretShares; + } + + public ShamirSplitSecret multiple(int mul) + throws IOException + { + byte[] ss; + for (int i = 0; i < secretShares.length; ++i) + { + ss = secretShares[i].getEncoded(); + for (int j = 0; j < ss.length; ++j) + { + ss[j] = poly.gfMul(ss[j] & 0xFF, mul); + } + secretShares[i] = new ShamirSplitSecretShare(ss, i + 1); + } + return this; + } + + public ShamirSplitSecret divide(int div) + throws IOException + { + byte[] ss; + for (int i = 0; i < secretShares.length; ++i) + { + ss = secretShares[i].getEncoded(); + for (int j = 0; j < ss.length; ++j) + { + ss[j] = poly.gfDiv(ss[j] & 0xFF, div); + } + secretShares[i] = new ShamirSplitSecretShare(ss, i + 1); + } + return this; + } + + @Override + public byte[] getSecret() + throws IOException + { + int n = secretShares.length; + byte[] r = new byte[n]; + byte tmp; + byte[] products = new byte[n - 1]; + byte[][] splits = new byte[n][secretShares[0].getEncoded().length]; + for (int i = 0; i < n; i++) + { + splits[i] = secretShares[i].getEncoded(); + tmp = 0; + for (int j = 0; j < n; j++) + { + if (j != i) + { + products[tmp++] = poly.gfDiv(secretShares[j].r, secretShares[i].r ^ secretShares[j].r); + } + } + + tmp = 1; + for (int prdI = 0; prdI != products.length; prdI++) + { + tmp = poly.gfMul(tmp & 0xff, products[prdI] & 0xff); + } + r[i] = tmp; + } + + return poly.gfVecMul(r, splits); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSplitSecretShare.java b/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSplitSecretShare.java new file mode 100644 index 0000000000..c3d31836c7 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/ShamirSplitSecretShare.java @@ -0,0 +1,31 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; + +import org.bouncycastle.util.Arrays; + +public class ShamirSplitSecretShare + implements SecretShare +{ + private final byte[] secretShare; + final int r; // index of secretShare + + public ShamirSplitSecretShare(byte[] secretShare, int r) + { + this.secretShare = Arrays.clone(secretShare); + this.r = r; + } + + public ShamirSplitSecretShare(byte[] secretShare) + { + this.secretShare = Arrays.clone(secretShare); + this.r = 1; + } + + @Override + public byte[] getEncoded() + throws IOException + { + return Arrays.clone(secretShare); + } +} diff --git a/core/src/main/java/org/bouncycastle/crypto/threshold/SplitSecret.java b/core/src/main/java/org/bouncycastle/crypto/threshold/SplitSecret.java new file mode 100644 index 0000000000..cc9aa8a1e8 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/threshold/SplitSecret.java @@ -0,0 +1,16 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; + +public interface SplitSecret +{ + SecretShare[] getSecretShares(); + + /** + * Recombines secret shares to reconstruct the original secret. + * + * @return A byte array containing the reconstructed secret. + */ + byte[] getSecret() + throws IOException; +} diff --git a/core/src/main/java/org/bouncycastle/crypto/util/CipherFactory.java b/core/src/main/java/org/bouncycastle/crypto/util/CipherFactory.java index 04e53d2d36..a8e9b2f82a 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/CipherFactory.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/CipherFactory.java @@ -2,6 +2,7 @@ import java.io.OutputStream; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; @@ -65,6 +66,24 @@ public class CipherFactory 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd }; + private static int getRC2EffectiveKeyBits(RC2CBCParameter rc2CbcParameter) + { + ASN1Integer version = rc2CbcParameter.getRC2ParameterVersionData(); + if (version == null) + { + return 32; + } + + int encoding = version.intPositiveValueExact(); + if (encoding >= 256) + { + return encoding; + } + + // TODO Why an entire table when RFC 8018 B.2.3. says only 160, 120, 58, 256+ are defined? + return rc2Ekb[encoding] & 0xFFFF; + } + /** * Create a content cipher for encrypting bulk data. * @@ -144,9 +163,12 @@ else if (encAlg.equals(AlgorithmIdentifierFactory.CAST5_CBC)) } else if (encAlg.equals(PKCSObjectIdentifiers.RC2_CBC)) { - RC2CBCParameter cbcParams = RC2CBCParameter.getInstance(sParams); + RC2CBCParameter rc2CBCParameter = RC2CBCParameter.getInstance(sParams); + RC2Parameters rc2Parameters = new RC2Parameters( + ((KeyParameter)encKey).getKey(), + getRC2EffectiveKeyBits(rc2CBCParameter)); - cipher.init(forEncryption, new ParametersWithIV(new RC2Parameters(((KeyParameter)encKey).getKey(), rc2Ekb[cbcParams.getRC2ParameterVersion().intValue()]), cbcParams.getIV())); + cipher.init(forEncryption, new ParametersWithIV(rc2Parameters, rc2CBCParameter.getIV())); } else { diff --git a/core/src/main/java/org/bouncycastle/crypto/util/DigestFactory.java b/core/src/main/java/org/bouncycastle/crypto/util/DigestFactory.java index 685be1b1c0..be9248055f 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/DigestFactory.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/DigestFactory.java @@ -40,7 +40,7 @@ public Digest createClone(Digest original) { public Digest createClone(Digest original) { - return new MD5Digest((MD5Digest)original); + return new SHA1Digest((SHA1Digest)original); } }); cloneMap.put(createSHA224().getAlgorithmName(), new Cloner() diff --git a/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPrivateKeyUtil.java b/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPrivateKeyUtil.java index 58d1b7fe2d..b33a1a7036 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPrivateKeyUtil.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPrivateKeyUtil.java @@ -13,12 +13,13 @@ import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSAPrivateKey; import org.bouncycastle.asn1.sec.ECPrivateKey; -import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECNamedDomainParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; @@ -199,13 +200,24 @@ else if (sequence.size() == 4) && sequence.getObjectAt(2) instanceof ASN1TaggedObject) { ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(sequence); - ASN1ObjectIdentifier curveOID = ASN1ObjectIdentifier.getInstance(ecPrivateKey.getParametersObject()); - X9ECParameters x9Params = ECNamedCurveTable.getByOID(curveOID); - result = new ECPrivateKeyParameters( - ecPrivateKey.getKey(), - new ECNamedDomainParameters( - curveOID, - x9Params)); + + X962Parameters parameters = X962Parameters.getInstance( + ecPrivateKey.getParametersObject().toASN1Primitive()); + ECDomainParameters domainParams; + if (parameters.isNamedCurve()) + { + ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(parameters.getParameters()); + domainParams = ECNamedDomainParameters.lookup(oid); + } + else + { + X9ECParameters x9 = X9ECParameters.getInstance(parameters.getParameters()); + domainParams = new ECDomainParameters(x9); + } + + BigInteger d = ecPrivateKey.getKey(); + + result = new ECPrivateKeyParameters(d, domainParams); } } } diff --git a/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPublicKeyUtil.java b/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPublicKeyUtil.java index cf643fa262..7a1ac0f490 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPublicKeyUtil.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/OpenSSHPublicKeyUtil.java @@ -30,6 +30,9 @@ private OpenSSHPublicKeyUtil() private static final String ED_25519 = "ssh-ed25519"; private static final String DSS = "ssh-dss"; + private static final String FIDO2_EC_P256 = "sk-ecdsa-sha2-nistp256@openssh.com"; + private static final String FIDO_ED_25519 = "sk-ssh-ed25519@openssh.com"; + /** * Parse a public key. *

    @@ -167,6 +170,29 @@ else if (magic.startsWith(ECDSA)) curve.decodePoint(pointRaw), new ECNamedDomainParameters(oid, x9ECParameters)); } + else if (magic.equals(FIDO2_EC_P256)) + { + String curveName = buffer.readString(); + + ASN1ObjectIdentifier oid = SSHNamedCurves.getByName(curveName); + X9ECParameters x9ECParameters = SSHNamedCurves.getParameters(oid); + + if (x9ECParameters == null) + { + throw new IllegalStateException("unable to find curve for " + magic + " using curve name " + curveName); + } + + ECCurve curve = x9ECParameters.getCurve(); + + byte[] pointRaw = buffer.readBlock(); + + // TODO: at the moment we have no use for this, but it's there. + String application = buffer.readString(); + + result = new ECPublicKeyParameters( + curve.decodePoint(pointRaw), + new ECNamedDomainParameters(oid, x9ECParameters)); + } else if (ED_25519.equals(magic)) { byte[] pubKeyBytes = buffer.readBlock(); @@ -177,6 +203,19 @@ else if (ED_25519.equals(magic)) result = new Ed25519PublicKeyParameters(pubKeyBytes, 0); } + else if (FIDO2_EC_P256.equals(magic)) + { + byte[] pubKeyBytes = buffer.readBlock(); + if (pubKeyBytes.length != Ed25519PublicKeyParameters.KEY_SIZE) + { + throw new IllegalStateException("public key value of wrong length"); + } + + // TODO: at the moment we have no use for this, but it's there. + String application = buffer.readString(); + + result = new Ed25519PublicKeyParameters(pubKeyBytes, 0); + } if (result == null) { diff --git a/core/src/main/java/org/bouncycastle/crypto/util/PrivateKeyFactory.java b/core/src/main/java/org/bouncycastle/crypto/util/PrivateKeyFactory.java index edc436365d..8e94bc92c4 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/PrivateKeyFactory.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/PrivateKeyFactory.java @@ -26,7 +26,6 @@ import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; @@ -155,33 +154,24 @@ else if (algOID.equals(X9ObjectIdentifiers.id_dsa)) } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) { - X962Parameters params = X962Parameters.getInstance(algId.getParameters()); + ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(keyInfo.parsePrivateKey()); - X9ECParameters x9; - ECDomainParameters dParams; - - if (params.isNamedCurve()) + X962Parameters parameters = X962Parameters.getInstance(algId.getParameters().toASN1Primitive()); + ECDomainParameters domainParams; + if (parameters.isNamedCurve()) { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)params.getParameters(); - - x9 = CustomNamedCurves.getByOID(oid); - if (x9 == null) - { - x9 = ECNamedCurveTable.getByOID(oid); - } - dParams = new ECNamedDomainParameters(oid, x9); + ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(parameters.getParameters()); + domainParams = ECNamedDomainParameters.lookup(oid); } else { - x9 = X9ECParameters.getInstance(params.getParameters()); - dParams = new ECDomainParameters( - x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed()); + X9ECParameters x9 = X9ECParameters.getInstance(parameters.getParameters()); + domainParams = new ECDomainParameters(x9); } - ECPrivateKey ec = ECPrivateKey.getInstance(keyInfo.parsePrivateKey()); - BigInteger d = ec.getKey(); + BigInteger d = ecPrivateKey.getKey(); - return new ECPrivateKeyParameters(d, dParams); + return new ECPrivateKeyParameters(d, domainParams); } else if (algOID.equals(EdECObjectIdentifiers.id_X25519)) { diff --git a/core/src/main/java/org/bouncycastle/crypto/util/PublicKeyFactory.java b/core/src/main/java/org/bouncycastle/crypto/util/PublicKeyFactory.java index a8c7055e48..0a5a1189a4 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/PublicKeyFactory.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/PublicKeyFactory.java @@ -32,14 +32,12 @@ import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.DHPublicKey; import org.bouncycastle.asn1.x9.DomainParameters; -import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.ValidationParams; import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ECPoint; import org.bouncycastle.asn1.x9.X9IntegerConverter; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; @@ -291,13 +289,7 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje if (params.isNamedCurve()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)params.getParameters(); - - X9ECParameters x9 = CustomNamedCurves.getByOID(oid); - if (x9 == null) - { - x9 = ECNamedCurveTable.getByOID(oid); - } - dParams = new ECNamedDomainParameters(oid, x9); + dParams = ECNamedDomainParameters.lookup(oid); } else if (params.isImplicitlyCA()) { diff --git a/core/src/main/java/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java b/core/src/main/java/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java index 3ade492281..a7208d0b19 100644 --- a/core/src/main/java/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java +++ b/core/src/main/java/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java @@ -35,12 +35,17 @@ import org.bouncycastle.crypto.params.X448PublicKeyParameters; import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.internal.asn1.rosstandart.RosstandartObjectIdentifiers; +import org.bouncycastle.pqc.crypto.lms.Composer; +import org.bouncycastle.pqc.crypto.lms.HSSPublicKeyParameters; +import org.bouncycastle.pqc.crypto.lms.LMSPublicKeyParameters; +import org.bouncycastle.util.Arrays; /** * Factory to create ASN.1 subject public key info objects from lightweight public keys. */ public class SubjectPublicKeyInfoFactory { + private static final byte tag_OctetString = (byte)0x04; private static Set cryptoProOids = new HashSet(5); static @@ -192,6 +197,20 @@ else if (publicKey instanceof Ed25519PublicKeyParameters) return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), key.getEncoded()); } + else if (publicKey instanceof HSSPublicKeyParameters) + { + HSSPublicKeyParameters params = (HSSPublicKeyParameters)publicKey; + byte[] encoding = Composer.compose().u32str(params.getL()).bytes(params.getLMSPublicKey()).build(); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); + return new SubjectPublicKeyInfo(algorithmIdentifier, Arrays.concatenate(new byte[]{tag_OctetString, (byte)encoding.length}, encoding)); + } + else if (publicKey instanceof LMSPublicKeyParameters) + { + LMSPublicKeyParameters params = (LMSPublicKeyParameters)publicKey; + byte[] encoding = Composer.compose().u32str(1).bytes(params).build(); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); + return new SubjectPublicKeyInfo(algorithmIdentifier, Arrays.concatenate(new byte[]{tag_OctetString, (byte)encoding.length}, encoding)); + } else { throw new IOException("key parameters not recognized"); diff --git a/core/src/main/java/org/bouncycastle/crypto/util/package-info.java b/core/src/main/java/org/bouncycastle/crypto/util/package-info.java new file mode 100644 index 0000000000..9070f49b00 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/crypto/util/package-info.java @@ -0,0 +1,4 @@ +/** + * Some general utility/conversion classes. + */ +package org.bouncycastle.crypto.util; diff --git a/core/src/main/java/org/bouncycastle/internal/asn1/iana/IANAObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/internal/asn1/iana/IANAObjectIdentifiers.java index 97a97d0680..2b586baf63 100644 --- a/core/src/main/java/org/bouncycastle/internal/asn1/iana/IANAObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/internal/asn1/iana/IANAObjectIdentifiers.java @@ -37,8 +37,8 @@ public interface IANAObjectIdentifiers /** IANA security nametypes; 1.3.6.1.5.6 */ static final ASN1ObjectIdentifier security_nametypes = security.branch("6"); - /** PKIX base OID: 1.3.6.1.5.6.6 */ - static final ASN1ObjectIdentifier pkix = security_mechanisms.branch("6"); + /** PKIX base OID: 1.3.6.1.5.5.7 */ + static final ASN1ObjectIdentifier pkix = security_mechanisms.branch("7"); /** IPSEC base OID: 1.3.6.1.5.5.8 */ diff --git a/core/src/main/java/org/bouncycastle/internal/asn1/kisa/KISAObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/internal/asn1/kisa/KISAObjectIdentifiers.java index 89ac25559c..978d19b04f 100644 --- a/core/src/main/java/org/bouncycastle/internal/asn1/kisa/KISAObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/internal/asn1/kisa/KISAObjectIdentifiers.java @@ -14,18 +14,23 @@ */ public interface KISAObjectIdentifiers { - /** RFC 4010, 4269: id-seedCBC; OID 1.2.410.200004.1.4 */ + /** + * RFC 4010, 4269: id-seedCBC; OID 1.2.410.200004.1.4 + */ static final ASN1ObjectIdentifier id_seedCBC = new ASN1ObjectIdentifier("1.2.410.200004.1.4"); - /** RFC 4269: id-seedMAC; OID 1.2.410.200004.1.7 */ + /** + * RFC 4269: id-seedMAC; OID 1.2.410.200004.1.7 + */ static final ASN1ObjectIdentifier id_seedMAC = new ASN1ObjectIdentifier("1.2.410.200004.1.7"); - /** RFC 4269: pbeWithSHA1AndSEED-CBC; OID 1.2.410.200004.1.15 */ + /** + * RFC 4269: pbeWithSHA1AndSEED-CBC; OID 1.2.410.200004.1.15 + */ static final ASN1ObjectIdentifier pbeWithSHA1AndSEED_CBC = new ASN1ObjectIdentifier("1.2.410.200004.1.15"); - /** RFC 4010: id-npki-app-cmsSeed-wrap; OID 1.2.410.200004.7.1.1.1 */ + /** + * RFC 4010: id-npki-app-cmsSeed-wrap; OID 1.2.410.200004.7.1.1.1 + */ static final ASN1ObjectIdentifier id_npki_app_cmsSeed_wrap = new ASN1ObjectIdentifier("1.2.410.200004.7.1.1.1"); - - /** RFC 4010: SeedEncryptionAlgorithmInCMS; OID 1.2.840.113549.1.9.16.0.24 */ - static final ASN1ObjectIdentifier id_mod_cms_seed = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.0.24"); } diff --git a/core/src/main/java/org/bouncycastle/internal/asn1/misc/CAST5CBCParameters.java b/core/src/main/java/org/bouncycastle/internal/asn1/misc/CAST5CBCParameters.java index 78c4066245..6f89a98b39 100644 --- a/core/src/main/java/org/bouncycastle/internal/asn1/misc/CAST5CBCParameters.java +++ b/core/src/main/java/org/bouncycastle/internal/asn1/misc/CAST5CBCParameters.java @@ -1,6 +1,5 @@ package org.bouncycastle.internal.asn1.misc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; @@ -69,11 +68,6 @@ public int getKeyLength() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(iv); - v.add(keyLength); - - return new DERSequence(v); + return new DERSequence(iv, keyLength); } } diff --git a/core/src/main/java/org/bouncycastle/internal/asn1/misc/MiscObjectIdentifiers.java b/core/src/main/java/org/bouncycastle/internal/asn1/misc/MiscObjectIdentifiers.java index 0ff100ec7b..f96201e8d4 100644 --- a/core/src/main/java/org/bouncycastle/internal/asn1/misc/MiscObjectIdentifiers.java +++ b/core/src/main/java/org/bouncycastle/internal/asn1/misc/MiscObjectIdentifiers.java @@ -169,25 +169,34 @@ public interface MiscObjectIdentifiers // Composite signature related OIDs. Based https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html // The current OIDs are EXPERIMENTAL and are going to change. ASN1ObjectIdentifier id_composite_signatures = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1"); - ASN1ObjectIdentifier id_MLDSA44_RSA2048_PSS_SHA256 = id_composite_signatures.branch("1"); - ASN1ObjectIdentifier id_MLDSA44_RSA2048_PKCS15_SHA256 = id_composite_signatures.branch("2"); - ASN1ObjectIdentifier id_MLDSA44_Ed25519_SHA512 = id_composite_signatures.branch("3"); - ASN1ObjectIdentifier id_MLDSA44_ECDSA_P256_SHA256 = id_composite_signatures.branch("4"); - ASN1ObjectIdentifier id_MLDSA44_ECDSA_brainpoolP256r1_SHA256 = id_composite_signatures.branch("5"); - ASN1ObjectIdentifier id_MLDSA65_RSA3072_PSS_SHA512 = id_composite_signatures.branch("6"); - ASN1ObjectIdentifier id_MLDSA65_RSA3072_PKCS15_SHA512 = id_composite_signatures.branch("7"); - ASN1ObjectIdentifier id_MLDSA65_ECDSA_P256_SHA512 = id_composite_signatures.branch("8"); - ASN1ObjectIdentifier id_MLDSA65_ECDSA_brainpoolP256r1_SHA512 = id_composite_signatures.branch("9"); - ASN1ObjectIdentifier id_MLDSA65_Ed25519_SHA512 = id_composite_signatures.branch("10"); - ASN1ObjectIdentifier id_MLDSA87_ECDSA_P384_SHA512 = id_composite_signatures.branch("11"); - ASN1ObjectIdentifier id_MLDSA87_ECDSA_brainpoolP384r1_SHA512 = id_composite_signatures.branch("12"); - ASN1ObjectIdentifier id_MLDSA87_Ed448_SHA512 = id_composite_signatures.branch("13"); - - // Falcon-based composites below were removed from the IETF draft in version 13 and are expected to be included in a later/separate standard. - // Most likely due to the fact that the Falcon (FN-DSA) NIST standard is going to be released after the Dilithium (ML-DSA) standard. - // However, we still leave their implementation for experimental usage. - ASN1ObjectIdentifier id_Falcon512_ECDSA_P256_SHA256 = id_composite_signatures.branch("14"); - ASN1ObjectIdentifier id_Falcon512_ECDSA_brainpoolP256r1_SHA256 = id_composite_signatures.branch("15"); - ASN1ObjectIdentifier id_Falcon512_Ed25519_SHA512 = id_composite_signatures.branch("16"); + ASN1ObjectIdentifier id_MLDSA44_RSA2048_PSS_SHA256 = id_composite_signatures.branch("21"); + ASN1ObjectIdentifier id_MLDSA44_RSA2048_PKCS15_SHA256 = id_composite_signatures.branch("22"); + ASN1ObjectIdentifier id_MLDSA44_Ed25519_SHA512 = id_composite_signatures.branch("23"); + ASN1ObjectIdentifier id_MLDSA44_ECDSA_P256_SHA256 = id_composite_signatures.branch("24"); + ASN1ObjectIdentifier id_MLDSA65_RSA3072_PSS_SHA256 = id_composite_signatures.branch("26"); + ASN1ObjectIdentifier id_MLDSA65_RSA3072_PKCS15_SHA256 = id_composite_signatures.branch("27"); + ASN1ObjectIdentifier id_MLDSA65_RSA4096_PSS_SHA384 = id_composite_signatures.branch("34"); + ASN1ObjectIdentifier id_MLDSA65_RSA4096_PKCS15_SHA384 = id_composite_signatures.branch("35"); + ASN1ObjectIdentifier id_MLDSA65_ECDSA_P384_SHA384 = id_composite_signatures.branch("28"); + ASN1ObjectIdentifier id_MLDSA65_ECDSA_brainpoolP256r1_SHA256 = id_composite_signatures.branch("29"); + ASN1ObjectIdentifier id_MLDSA65_Ed25519_SHA512 = id_composite_signatures.branch("30"); + ASN1ObjectIdentifier id_MLDSA87_ECDSA_P384_SHA384 = id_composite_signatures.branch("31"); + ASN1ObjectIdentifier id_MLDSA87_ECDSA_brainpoolP384r1_SHA384 = id_composite_signatures.branch("32"); + ASN1ObjectIdentifier id_MLDSA87_Ed448_SHA512 = id_composite_signatures.branch("33"); + + ASN1ObjectIdentifier id_HashMLDSA44_RSA2048_PSS_SHA256 = id_composite_signatures.branch("40"); + ASN1ObjectIdentifier id_HashMLDSA44_RSA2048_PKCS15_SHA256 = id_composite_signatures.branch("41"); + ASN1ObjectIdentifier id_HashMLDSA44_Ed25519_SHA512 = id_composite_signatures.branch("42"); + ASN1ObjectIdentifier id_HashMLDSA44_ECDSA_P256_SHA256 = id_composite_signatures.branch("43"); + ASN1ObjectIdentifier id_HashMLDSA65_RSA3072_PSS_SHA512 = id_composite_signatures.branch("44"); + ASN1ObjectIdentifier id_HashMLDSA65_RSA3072_PKCS15_SHA512 = id_composite_signatures.branch("45"); + ASN1ObjectIdentifier id_HashMLDSA65_RSA4096_PSS_SHA512 = id_composite_signatures.branch("46"); + ASN1ObjectIdentifier id_HashMLDSA65_RSA4096_PKCS15_SHA512 = id_composite_signatures.branch("47"); + ASN1ObjectIdentifier id_HashMLDSA65_ECDSA_P384_SHA512 = id_composite_signatures.branch("48"); + ASN1ObjectIdentifier id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512 = id_composite_signatures.branch("49"); + ASN1ObjectIdentifier id_HashMLDSA65_Ed25519_SHA512 = id_composite_signatures.branch("50"); + ASN1ObjectIdentifier id_HashMLDSA87_ECDSA_P384_SHA512 = id_composite_signatures.branch("51"); + ASN1ObjectIdentifier id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512 = id_composite_signatures.branch("52"); + ASN1ObjectIdentifier id_HashMLDSA87_Ed448_SHA512 = id_composite_signatures.branch("53"); // COMPOSITE SIGNATURES END } diff --git a/core/src/main/java/org/bouncycastle/internal/asn1/oiw/ElGamalParameter.java b/core/src/main/java/org/bouncycastle/internal/asn1/oiw/ElGamalParameter.java index d281f78269..b1f022b09f 100644 --- a/core/src/main/java/org/bouncycastle/internal/asn1/oiw/ElGamalParameter.java +++ b/core/src/main/java/org/bouncycastle/internal/asn1/oiw/ElGamalParameter.java @@ -3,7 +3,6 @@ import java.math.BigInteger; import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -58,11 +57,6 @@ public BigInteger getG() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(p); - v.add(g); - - return new DERSequence(v); + return new DERSequence(p, g); } } diff --git a/core/src/main/java/org/bouncycastle/math/ec/ECCurve.java b/core/src/main/java/org/bouncycastle/math/ec/ECCurve.java index ce879c4159..de75cb24ff 100644 --- a/core/src/main/java/org/bouncycastle/math/ec/ECCurve.java +++ b/core/src/main/java/org/bouncycastle/math/ec/ECCurve.java @@ -123,6 +123,19 @@ public synchronized Config configure() return new Config(this.coord, this.endomorphism, this.multiplier); } + public int getFieldElementEncodingLength() + { + return (getFieldSize() + 7) / 8; + } + + public int getAffinePointEncodingLength(boolean compressed) + { + int fieldLength = getFieldElementEncodingLength(); + return compressed + ? 1 + fieldLength + : 1 + fieldLength * 2; + } + public ECPoint validatePoint(BigInteger x, BigInteger y) { ECPoint p = createPoint(x, y); @@ -379,7 +392,7 @@ public ECMultiplier getMultiplier() public ECPoint decodePoint(byte[] encoded) { ECPoint p = null; - int expectedLength = (getFieldSize() + 7) / 8; + int expectedLength = getFieldElementEncodingLength(); byte type = encoded[0]; switch (type) @@ -463,25 +476,15 @@ public ECPoint decodePoint(byte[] encoded) */ public ECLookupTable createCacheSafeLookupTable(final ECPoint[] points, int off, final int len) { - final int FE_BYTES = (getFieldSize() + 7) >>> 3; - + final int FE_BYTES = getFieldElementEncodingLength(); final byte[] table = new byte[len * FE_BYTES * 2]; + int pos = 0; + for (int i = 0; i < len; ++i) { - int pos = 0; - for (int i = 0; i < len; ++i) - { - ECPoint p = points[off + i]; - byte[] px = p.getRawXCoord().toBigInteger().toByteArray(); - byte[] py = p.getRawYCoord().toBigInteger().toByteArray(); - - int pxStart = px.length > FE_BYTES ? 1 : 0, pxLen = px.length - pxStart; - int pyStart = py.length > FE_BYTES ? 1 : 0, pyLen = py.length - pyStart; - - System.arraycopy(px, pxStart, table, pos + FE_BYTES - pxLen, pxLen); pos += FE_BYTES; - System.arraycopy(py, pyStart, table, pos + FE_BYTES - pyLen, pyLen); pos += FE_BYTES; - } + ECPoint p = points[off + i]; + p.getRawXCoord().encodeTo(table, pos); pos += FE_BYTES; + p.getRawYCoord().encodeTo(table, pos); pos += FE_BYTES; } - return new AbstractECLookupTable() { public int getSize() @@ -593,9 +596,14 @@ protected AbstractFp(BigInteger q) super(FiniteFields.getPrimeField(q)); } + public BigInteger getQ() + { + return getField().getCharacteristic(); + } + public boolean isValidFieldElement(BigInteger x) { - return x != null && x.signum() >= 0 && x.compareTo(this.getField().getCharacteristic()) < 0; + return x != null && x.signum() >= 0 && x.compareTo(getQ()) < 0; } public ECFieldElement randomFieldElement(SecureRandom r) @@ -604,7 +612,7 @@ public ECFieldElement randomFieldElement(SecureRandom r) * NOTE: BigInteger comparisons in the rejection sampling are not constant-time, so we * use the product of two independent elements to mitigate side-channels. */ - BigInteger p = getField().getCharacteristic(); + BigInteger p = getQ(); ECFieldElement fe1 = fromBigInteger(implRandomFieldElement(r, p)); ECFieldElement fe2 = fromBigInteger(implRandomFieldElement(r, p)); return fe1.multiply(fe2); @@ -616,7 +624,7 @@ public ECFieldElement randomFieldElementMult(SecureRandom r) * NOTE: BigInteger comparisons in the rejection sampling are not constant-time, so we * use the product of two independent elements to mitigate side-channels. */ - BigInteger p = getField().getCharacteristic(); + BigInteger p = getQ(); ECFieldElement fe1 = fromBigInteger(implRandomFieldElementMult(r, p)); ECFieldElement fe2 = fromBigInteger(implRandomFieldElementMult(r, p)); return fe1.multiply(fe2); @@ -699,12 +707,11 @@ public Fp(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger if (isInternal) { - this.q = q; knownQs.add(q); } else if (knownQs.contains(q) || validatedQs.contains(q)) { - this.q = q; + // No need to validate } else { @@ -724,10 +731,9 @@ else if (knownQs.contains(q) || validatedQs.contains(q)) } validatedQs.add(q); - - this.q = q; } + this.q = q; this.r = ECFieldElement.Fp.calculateResidue(q); this.infinity = new ECPoint.Fp(this, null, null); diff --git a/core/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java b/core/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java index ef2221265f..c47204ffc0 100644 --- a/core/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java +++ b/core/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java @@ -85,7 +85,17 @@ public String toString() public byte[] getEncoded() { - return BigIntegers.asUnsignedByteArray((getFieldSize() + 7) / 8, toBigInteger()); + return BigIntegers.asUnsignedByteArray(getEncodedLength(), toBigInteger()); + } + + public int getEncodedLength() + { + return (getFieldSize() + 7) / 8; + } + + public void encodeTo(byte[] buf, int off) + { + BigIntegers.asUnsignedByteArray(toBigInteger(), buf, off, getEncodedLength()); } public static abstract class AbstractFp extends ECFieldElement diff --git a/core/src/main/java/org/bouncycastle/math/ec/ECPoint.java b/core/src/main/java/org/bouncycastle/math/ec/ECPoint.java index cc4f63a437..44349f5a4e 100644 --- a/core/src/main/java/org/bouncycastle/math/ec/ECPoint.java +++ b/core/src/main/java/org/bouncycastle/math/ec/ECPoint.java @@ -501,11 +501,51 @@ public byte[] getEncoded(boolean compressed) byte[] Y = normed.getYCoord().getEncoded(); - byte[] PO = new byte[X.length + Y.length + 1]; - PO[0] = 0x04; - System.arraycopy(X, 0, PO, 1, X.length); - System.arraycopy(Y, 0, PO, X.length + 1, Y.length); - return PO; + { + byte[] PO = new byte[X.length + Y.length + 1]; + PO[0] = 0x04; + System.arraycopy(X, 0, PO, 1, X.length); + System.arraycopy(Y, 0, PO, X.length + 1, Y.length); + return PO; + } + } + + public int getEncodedLength(boolean compressed) + { + if (isInfinity()) + { + return 1; + } + + if (compressed) + { + return 1 + getXCoord().getEncodedLength(); + } + + return 1 + getXCoord().getEncodedLength() + getYCoord().getEncodedLength(); + } + + public void encodeTo(boolean compressed, byte[] buf, int off) + { + if (isInfinity()) + { + buf[off] = 0x00; + return; + } + + ECPoint normed = normalize(); + ECFieldElement X = normed.getXCoord(), Y = normed.getYCoord(); + + if (compressed) + { + buf[off] = (byte)(normed.getCompressionYTilde() ? 0x03 : 0x02); + X.encodeTo(buf, off + 1); + return; + } + + buf[off] = 0x04; + X.encodeTo(buf, off + 1); + Y.encodeTo(buf, off + 1 + X.getEncodedLength()); } protected abstract boolean getCompressionYTilde(); diff --git a/core/src/main/java/org/bouncycastle/math/ec/custom/djb/package-info.java b/core/src/main/java/org/bouncycastle/math/ec/custom/djb/package-info.java new file mode 100644 index 0000000000..c8ae54be2f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/math/ec/custom/djb/package-info.java @@ -0,0 +1,6 @@ +/** + * Experimental implementation of curve25519. Note that the curve implementation is in the short-Weierstrass form, + * which is not the recommended (nor most suitable) approach. In particular, the input/output conventions are not + * compliant with standard implementations, and point conversions would be needed to interoperate. + */ +package org.bouncycastle.math.ec.custom.djb; diff --git a/core/src/main/java/org/bouncycastle/math/ec/custom/gm/package-info.java b/core/src/main/java/org/bouncycastle/math/ec/custom/gm/package-info.java new file mode 100644 index 0000000000..930d328efa --- /dev/null +++ b/core/src/main/java/org/bouncycastle/math/ec/custom/gm/package-info.java @@ -0,0 +1,4 @@ +/** + * Custom implementation of SM2 EC curve, SM2-P256V1. + */ +package org.bouncycastle.math.ec.custom.gm; diff --git a/core/src/main/java/org/bouncycastle/math/ec/custom/sec/package-info.java b/core/src/main/java/org/bouncycastle/math/ec/custom/sec/package-info.java new file mode 100644 index 0000000000..829ad9d47f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/math/ec/custom/sec/package-info.java @@ -0,0 +1,5 @@ +/** + * Custom implementations of (most of) the curves over Fp from the SEC specification. Uses the new "raw" math classes + * in place of BigInteger, and includes customized modular reductions taking advantage of the special forms of the primes. + */ +package org.bouncycastle.math.ec.custom.sec; diff --git a/core/src/main/java/org/bouncycastle/math/ec/package-info.java b/core/src/main/java/org/bouncycastle/math/ec/package-info.java new file mode 100644 index 0000000000..711abae69a --- /dev/null +++ b/core/src/main/java/org/bouncycastle/math/ec/package-info.java @@ -0,0 +1,4 @@ +/** + * Math support for Elliptic Curve. + */ +package org.bouncycastle.math.ec; diff --git a/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X25519.java b/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X25519.java index 02fdefed0f..3a752d3324 100644 --- a/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X25519.java +++ b/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X25519.java @@ -30,6 +30,18 @@ public static boolean calculateAgreement(byte[] k, int kOff, byte[] u, int uOff, return !Arrays.areAllZeroes(r, rOff, POINT_SIZE); } + public static void clampPrivateKey(byte[] k) + { + if (k.length != SCALAR_SIZE) + { + throw new IllegalArgumentException("k"); + } + + k[0] &= 0xF8; + k[SCALAR_SIZE - 1] &= 0x7F; + k[SCALAR_SIZE - 1] |= 0x40; + } + private static int decode32(byte[] bs, int off) { int n = bs[off] & 0xFF; @@ -60,9 +72,7 @@ public static void generatePrivateKey(SecureRandom random, byte[] k) random.nextBytes(k); - k[0] &= 0xF8; - k[SCALAR_SIZE - 1] &= 0x7F; - k[SCALAR_SIZE - 1] |= 0x40; + clampPrivateKey(k); } public static void generatePublicKey(byte[] k, int kOff, byte[] r, int rOff) diff --git a/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X448.java b/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X448.java index 3954ba110c..ecfbc8c4f1 100644 --- a/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X448.java +++ b/core/src/main/java/org/bouncycastle/math/ec/rfc7748/X448.java @@ -31,6 +31,17 @@ public static boolean calculateAgreement(byte[] k, int kOff, byte[] u, int uOff, return !Arrays.areAllZeroes(r, rOff, POINT_SIZE); } + public static void clampPrivateKey(byte[] k) + { + if (k.length != SCALAR_SIZE) + { + throw new IllegalArgumentException("k"); + } + + k[0] &= 0xFC; + k[SCALAR_SIZE - 1] |= 0x80; + } + private static int decode32(byte[] bs, int off) { int n = bs[ off] & 0xFF; @@ -60,8 +71,7 @@ public static void generatePrivateKey(SecureRandom random, byte[] k) random.nextBytes(k); - k[0] &= 0xFC; - k[SCALAR_SIZE - 1] |= 0x80; + clampPrivateKey(k); } public static void generatePublicKey(byte[] k, int kOff, byte[] r, int rOff) diff --git a/core/src/main/java/org/bouncycastle/math/package-info.java b/core/src/main/java/org/bouncycastle/math/package-info.java new file mode 100644 index 0000000000..0eb4ecd275 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/math/package-info.java @@ -0,0 +1,4 @@ +/** + * The Bouncy Castle math package. + */ +package org.bouncycastle.math; diff --git a/core/src/main/java/org/bouncycastle/math/raw/package-info.java b/core/src/main/java/org/bouncycastle/math/raw/package-info.java new file mode 100644 index 0000000000..533f9e4023 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/math/raw/package-info.java @@ -0,0 +1,4 @@ +/** + * Math support for raw multi-precision calculations. + */ +package org.bouncycastle.math.raw; diff --git a/core/src/main/java/org/bouncycastle/pqc/asn1/KyberPrivateKey.java b/core/src/main/java/org/bouncycastle/pqc/asn1/KyberPrivateKey.java deleted file mode 100644 index b5f4bc4445..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/asn1/KyberPrivateKey.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.bouncycastle.pqc.asn1; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Object; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.util.Arrays; - -/** - * - * Crystal Kyber Private Key Format. - * See https://www.ietf.org/archive/id/draft-uni-qsckeys-kyber-00.html for details. - *

    - *        KyberPrivateKey ::= SEQUENCE {
    - *        version     INTEGER {v0(0)}   -- version (round 3)
    - *        s           OCTET STRING,     -- EMPTY
    - *        hpk         OCTET STRING      -- EMPTY
    - *        nonce       OCTET STRING,     -- d
    - *        publicKey   [0] IMPLICIT KyberPublicKey OPTIONAL,
    - *                                      -- see next section
    - *        }
    - *    
    - */ -public class KyberPrivateKey - extends ASN1Object -{ - private int version; - private byte[] s; - private KyberPublicKey publicKey; - private byte[] hpk; - private byte[] nonce; - - public KyberPrivateKey(int version, byte[] s, byte[] hpk, byte[] nonce, KyberPublicKey publicKey) - { - this.version = version; - this.s = s; - this.publicKey = publicKey; - this.hpk = hpk; - this.nonce = nonce; - } - - public KyberPrivateKey(int version, byte[] s, byte[] hpk, byte[] nonce) - { - this(version, s, hpk, nonce, null); - } - - public int getVersion() - { - return version; - } - - public byte[] getS() - { - return Arrays.clone(s); - } - - public KyberPublicKey getPublicKey() - { - return publicKey; - } - - public byte[] getHpk() - { - return Arrays.clone(hpk); - } - - public byte[] getNonce() - { - return Arrays.clone(nonce); - } - - private KyberPrivateKey(ASN1Sequence seq) - { - version = ASN1Integer.getInstance(seq.getObjectAt(0)).intValueExact(); - if (version != 0) - { - throw new IllegalArgumentException("unrecognized version"); - } - - s = Arrays.clone(ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets()); - - int skipPubKey = 1; - if (seq.size() == 5) - { - skipPubKey = 0; - publicKey = KyberPublicKey.getInstance(seq.getObjectAt(2)); - } - - hpk = Arrays.clone(ASN1OctetString.getInstance(seq.getObjectAt(3 - skipPubKey)).getOctets()); - - nonce = Arrays.clone(ASN1OctetString.getInstance(seq.getObjectAt(4 - skipPubKey)).getOctets()); - } - - public ASN1Primitive toASN1Primitive() - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new ASN1Integer(version)); - v.add(new DEROctetString(s)); - // todo optional publickey - if(publicKey != null) - { - v.add(new KyberPublicKey(publicKey.getT(), publicKey.getRho())); - } - v.add(new DEROctetString(hpk)); - v.add(new DEROctetString(nonce)); - - return new DERSequence(v); - } - - public static KyberPrivateKey getInstance(Object o) - { - if (o instanceof KyberPrivateKey) - { - return (KyberPrivateKey)o; - } - else if (o != null) - { - return new KyberPrivateKey(ASN1Sequence.getInstance(o)); - } - - return null; - } - -} diff --git a/core/src/main/java/org/bouncycastle/pqc/asn1/KyberPublicKey.java b/core/src/main/java/org/bouncycastle/pqc/asn1/KyberPublicKey.java deleted file mode 100644 index ac67bd5aa2..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/asn1/KyberPublicKey.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bouncycastle.pqc.asn1; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Object; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.util.Arrays; - -/** - * - * Crystal Kyber Public Key Format. - * See https://www.ietf.org/archive/id/draft-uni-qsckeys-kyber-00.html for details. - *
    - *        KyberPublicKey ::= SEQUENCE {
    - *         t           OCTET STRING,
    - *         rho         OCTET STRING
    -*     }
    - *    
    - */ -public class KyberPublicKey - extends ASN1Object - -{ - private byte[] t; - private byte[] rho; - - public KyberPublicKey(byte[] t, byte[] rho) - { - this.t = t; - this.rho = rho; - } - - /** - * @deprecated use getInstance() - */ - public KyberPublicKey(ASN1Sequence seq) - { - t = Arrays.clone(ASN1OctetString.getInstance(seq.getObjectAt(0)).getOctets()); - rho = Arrays.clone(ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets()); - } - - public byte[] getT() - { - return Arrays.clone(t); - } - - public byte[] getRho() - { - return Arrays.clone(rho); - } - - - - public ASN1Primitive toASN1Primitive() - { - ASN1EncodableVector v = new ASN1EncodableVector(); - v.add(new DEROctetString(t)); - v.add(new DEROctetString(rho)); - return new DERSequence(v); - } - public static KyberPublicKey getInstance(Object o) - { - if (o instanceof KyberPublicKey) - { - return (KyberPublicKey) o; - } - else if (o != null) - { - return new KyberPublicKey(ASN1Sequence.getInstance(o)); - } - - return null; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/asn1/RainbowPrivateKey.java b/core/src/main/java/org/bouncycastle/pqc/asn1/RainbowPrivateKey.java deleted file mode 100644 index e194699be1..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/asn1/RainbowPrivateKey.java +++ /dev/null @@ -1,349 +0,0 @@ -package org.bouncycastle.pqc.asn1; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Object; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.pqc.legacy.crypto.rainbow.Layer; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.RainbowUtil; - -/** - * Return the key data to encode in the PrivateKeyInfo structure. - *

    - * The ASN.1 definition of the key structure is - *

    - *   RainbowPrivateKey ::= SEQUENCE {
    - *         CHOICE
    - *         {
    - *         oid        OBJECT IDENTIFIER         -- OID identifying the algorithm
    - *         version    INTEGER                    -- 0
    - *         }
    - *     A1inv      SEQUENCE OF OCTET STRING  -- inversed matrix of L1
    - *     b1         OCTET STRING              -- translation vector of L1
    - *     A2inv      SEQUENCE OF OCTET STRING  -- inversed matrix of L2
    - *     b2         OCTET STRING              -- translation vector of L2
    - *     vi         OCTET STRING              -- num of elmts in each Set S
    - *     layers     SEQUENCE OF Layer         -- layers of F
    - *   }
    - *
    - *   Layer             ::= SEQUENCE OF Poly
    - *
    - *   Poly              ::= SEQUENCE {
    - *     alpha      SEQUENCE OF OCTET STRING
    - *     beta       SEQUENCE OF OCTET STRING
    - *     gamma      OCTET STRING
    - *     eta        INTEGER
    - *   }
    - * 
    - */ -public class RainbowPrivateKey - extends ASN1Object -{ - private ASN1Integer version; - private ASN1ObjectIdentifier oid; - - private byte[][] invA1; - private byte[] b1; - private byte[][] invA2; - private byte[] b2; - private byte[] vi; - private Layer[] layers; - - private RainbowPrivateKey(ASN1Sequence seq) - { - // or version - if (seq.getObjectAt(0) instanceof ASN1Integer) - { - version = ASN1Integer.getInstance(seq.getObjectAt(0)); - } - else - { - oid = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0)); - } - - // - ASN1Sequence asnA1 = (ASN1Sequence)seq.getObjectAt(1); - invA1 = new byte[asnA1.size()][]; - for (int i = 0; i < asnA1.size(); i++) - { - invA1[i] = ((ASN1OctetString)asnA1.getObjectAt(i)).getOctets(); - } - - // - ASN1Sequence asnb1 = (ASN1Sequence)seq.getObjectAt(2); - b1 = ((ASN1OctetString)asnb1.getObjectAt(0)).getOctets(); - - // - ASN1Sequence asnA2 = (ASN1Sequence)seq.getObjectAt(3); - invA2 = new byte[asnA2.size()][]; - for (int j = 0; j < asnA2.size(); j++) - { - invA2[j] = ((ASN1OctetString)asnA2.getObjectAt(j)).getOctets(); - } - - // - ASN1Sequence asnb2 = (ASN1Sequence)seq.getObjectAt(4); - b2 = ((ASN1OctetString)asnb2.getObjectAt(0)).getOctets(); - - // - ASN1Sequence asnvi = (ASN1Sequence)seq.getObjectAt(5); - vi = ((ASN1OctetString)asnvi.getObjectAt(0)).getOctets(); - - // - ASN1Sequence asnLayers = (ASN1Sequence)seq.getObjectAt(6); - - byte[][][][] alphas = new byte[asnLayers.size()][][][]; - byte[][][][] betas = new byte[asnLayers.size()][][][]; - byte[][][] gammas = new byte[asnLayers.size()][][]; - byte[][] etas = new byte[asnLayers.size()][]; - // a layer: - for (int l = 0; l < asnLayers.size(); l++) - { - ASN1Sequence asnLayer = (ASN1Sequence)asnLayers.getObjectAt(l); - - // alphas (num of alpha-2d-array = oi) - ASN1Sequence alphas3d = (ASN1Sequence)asnLayer.getObjectAt(0); - alphas[l] = new byte[alphas3d.size()][][]; - for (int m = 0; m < alphas3d.size(); m++) - { - ASN1Sequence alphas2d = (ASN1Sequence)alphas3d.getObjectAt(m); - alphas[l][m] = new byte[alphas2d.size()][]; - for (int n = 0; n < alphas2d.size(); n++) - { - alphas[l][m][n] = ((ASN1OctetString)alphas2d.getObjectAt(n)).getOctets(); - } - } - - // betas .... - ASN1Sequence betas3d = (ASN1Sequence)asnLayer.getObjectAt(1); - betas[l] = new byte[betas3d.size()][][]; - for (int mb = 0; mb < betas3d.size(); mb++) - { - ASN1Sequence betas2d = (ASN1Sequence)betas3d.getObjectAt(mb); - betas[l][mb] = new byte[betas2d.size()][]; - for (int nb = 0; nb < betas2d.size(); nb++) - { - betas[l][mb][nb] = ((ASN1OctetString)betas2d.getObjectAt(nb)).getOctets(); - } - } - - // gammas ... - ASN1Sequence gammas2d = (ASN1Sequence)asnLayer.getObjectAt(2); - gammas[l] = new byte[gammas2d.size()][]; - for (int mg = 0; mg < gammas2d.size(); mg++) - { - gammas[l][mg] = ((ASN1OctetString)gammas2d.getObjectAt(mg)).getOctets(); - } - - // eta ... - etas[l] = ((ASN1OctetString)asnLayer.getObjectAt(3)).getOctets(); - } - - int numOfLayers = vi.length - 1; - this.layers = new Layer[numOfLayers]; - for (int i = 0; i < numOfLayers; i++) - { - Layer l = new Layer(vi[i], vi[i + 1], RainbowUtil.convertArray(alphas[i]), - RainbowUtil.convertArray(betas[i]), RainbowUtil.convertArray(gammas[i]), RainbowUtil.convertArray(etas[i])); - this.layers[i] = l; - - } - } - - public RainbowPrivateKey(short[][] invA1, short[] b1, short[][] invA2, - short[] b2, int[] vi, Layer[] layers) - { - this.version = new ASN1Integer(1); - this.invA1 = RainbowUtil.convertArray(invA1); - this.b1 = RainbowUtil.convertArray(b1); - this.invA2 = RainbowUtil.convertArray(invA2); - this.b2 = RainbowUtil.convertArray(b2); - this.vi = RainbowUtil.convertIntArray(vi); - this.layers = layers; - } - - public static RainbowPrivateKey getInstance(Object o) - { - if (o instanceof RainbowPrivateKey) - { - return (RainbowPrivateKey)o; - } - else if (o != null) - { - return new RainbowPrivateKey(ASN1Sequence.getInstance(o)); - } - - return null; - } - - public ASN1Integer getVersion() - { - return version; - } - - /** - * Getter for the inverse matrix of A1. - * - * @return the A1inv inverse - */ - public short[][] getInvA1() - { - return RainbowUtil.convertArray(invA1); - } - - /** - * Getter for the translation part of the private quadratic map L1. - * - * @return b1 the translation part of L1 - */ - public short[] getB1() - { - return RainbowUtil.convertArray(b1); - } - - /** - * Getter for the translation part of the private quadratic map L2. - * - * @return b2 the translation part of L2 - */ - public short[] getB2() - { - return RainbowUtil.convertArray(b2); - } - - /** - * Getter for the inverse matrix of A2 - * - * @return the A2inv - */ - public short[][] getInvA2() - { - return RainbowUtil.convertArray(invA2); - } - - /** - * Returns the layers contained in the private key - * - * @return layers - */ - public Layer[] getLayers() - { - return this.layers; - } - - /** - * Returns the array of vi-s - * - * @return the vi - */ - public int[] getVi() - { - return RainbowUtil.convertArraytoInt(vi); - } - - public ASN1Primitive toASN1Primitive() - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - // encode or version - if (version != null) - { - v.add(version); - } - else - { - v.add(oid); - } - - // encode - ASN1EncodableVector asnA1 = new ASN1EncodableVector(); - for (int i = 0; i < invA1.length; i++) - { - asnA1.add(new DEROctetString(invA1[i])); - } - v.add(new DERSequence(asnA1)); - - // encode - ASN1EncodableVector asnb1 = new ASN1EncodableVector(); - asnb1.add(new DEROctetString(b1)); - v.add(new DERSequence(asnb1)); - - // encode - ASN1EncodableVector asnA2 = new ASN1EncodableVector(); - for (int i = 0; i < invA2.length; i++) - { - asnA2.add(new DEROctetString(invA2[i])); - } - v.add(new DERSequence(asnA2)); - - // encode - ASN1EncodableVector asnb2 = new ASN1EncodableVector(); - asnb2.add(new DEROctetString(b2)); - v.add(new DERSequence(asnb2)); - - // encode - ASN1EncodableVector asnvi = new ASN1EncodableVector(); - asnvi.add(new DEROctetString(vi)); - v.add(new DERSequence(asnvi)); - - // encode - ASN1EncodableVector asnLayers = new ASN1EncodableVector(); - // a layer: - for (int l = 0; l < layers.length; l++) - { - ASN1EncodableVector aLayer = new ASN1EncodableVector(); - - // alphas (num of alpha-2d-array = oi) - byte[][][] alphas = RainbowUtil.convertArray(layers[l].getCoeffAlpha()); - ASN1EncodableVector alphas3d = new ASN1EncodableVector(); - for (int i = 0; i < alphas.length; i++) - { - ASN1EncodableVector alphas2d = new ASN1EncodableVector(); - for (int j = 0; j < alphas[i].length; j++) - { - alphas2d.add(new DEROctetString(alphas[i][j])); - } - alphas3d.add(new DERSequence(alphas2d)); - } - aLayer.add(new DERSequence(alphas3d)); - - // betas .... - byte[][][] betas = RainbowUtil.convertArray(layers[l].getCoeffBeta()); - ASN1EncodableVector betas3d = new ASN1EncodableVector(); - for (int i = 0; i < betas.length; i++) - { - ASN1EncodableVector betas2d = new ASN1EncodableVector(); - for (int j = 0; j < betas[i].length; j++) - { - betas2d.add(new DEROctetString(betas[i][j])); - } - betas3d.add(new DERSequence(betas2d)); - } - aLayer.add(new DERSequence(betas3d)); - - // gammas ... - byte[][] gammas = RainbowUtil.convertArray(layers[l].getCoeffGamma()); - ASN1EncodableVector asnG = new ASN1EncodableVector(); - for (int i = 0; i < gammas.length; i++) - { - asnG.add(new DEROctetString(gammas[i])); - } - aLayer.add(new DERSequence(asnG)); - - // eta - aLayer.add(new DEROctetString(RainbowUtil.convertArray(layers[l].getCoeffEta()))); - - // now, layer built up. add it! - asnLayers.add(new DERSequence(aLayer)); - } - - v.add(new DERSequence(asnLayers)); - - return new DERSequence(v); - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/asn1/RainbowPublicKey.java b/core/src/main/java/org/bouncycastle/pqc/asn1/RainbowPublicKey.java deleted file mode 100644 index 0e36f91f23..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/asn1/RainbowPublicKey.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.bouncycastle.pqc.asn1; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Object; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.RainbowUtil; - -/** - * This class implements an ASN.1 encoded Rainbow public key. The ASN.1 definition - * of this structure is: - *
    - *       RainbowPublicKey ::= SEQUENCE {
    - *         CHOICE
    - *         {
    - *         oid        OBJECT IDENTIFIER         -- OID identifying the algorithm
    - *         version    INTEGER                    -- 0
    - *         }
    - *         docLength        Integer               -- length of the code
    - *         coeffquadratic   SEQUENCE OF OCTET STRING -- quadratic (mixed) coefficients
    - *         coeffsingular    SEQUENCE OF OCTET STRING -- singular coefficients
    - *         coeffscalar    SEQUENCE OF OCTET STRING -- scalar coefficients
    - *       }
    - * 
    - */ -public class RainbowPublicKey - extends ASN1Object -{ - private ASN1Integer version; - private ASN1ObjectIdentifier oid; - private ASN1Integer docLength; - private byte[][] coeffQuadratic; - private byte[][] coeffSingular; - private byte[] coeffScalar; - - private RainbowPublicKey(ASN1Sequence seq) - { - // or version - if (seq.getObjectAt(0) instanceof ASN1Integer) - { - version = ASN1Integer.getInstance(seq.getObjectAt(0)); - } - else - { - oid = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0)); - } - - docLength = ASN1Integer.getInstance(seq.getObjectAt(1)); - - ASN1Sequence asnCoeffQuad = ASN1Sequence.getInstance(seq.getObjectAt(2)); - coeffQuadratic = new byte[asnCoeffQuad.size()][]; - for (int quadSize = 0; quadSize < asnCoeffQuad.size(); quadSize++) - { - coeffQuadratic[quadSize] = ASN1OctetString.getInstance(asnCoeffQuad.getObjectAt(quadSize)).getOctets(); - } - - ASN1Sequence asnCoeffSing = (ASN1Sequence)seq.getObjectAt(3); - coeffSingular = new byte[asnCoeffSing.size()][]; - for (int singSize = 0; singSize < asnCoeffSing.size(); singSize++) - { - coeffSingular[singSize] = ASN1OctetString.getInstance(asnCoeffSing.getObjectAt(singSize)).getOctets(); - } - - ASN1Sequence asnCoeffScalar = (ASN1Sequence)seq.getObjectAt(4); - coeffScalar = ASN1OctetString.getInstance(asnCoeffScalar.getObjectAt(0)).getOctets(); - } - - public RainbowPublicKey(int docLength, short[][] coeffQuadratic, short[][] coeffSingular, short[] coeffScalar) - { - this.version = new ASN1Integer(0); - this.docLength = new ASN1Integer(docLength); - this.coeffQuadratic = RainbowUtil.convertArray(coeffQuadratic); - this.coeffSingular = RainbowUtil.convertArray(coeffSingular); - this.coeffScalar = RainbowUtil.convertArray(coeffScalar); - } - - public static RainbowPublicKey getInstance(Object o) - { - if (o instanceof RainbowPublicKey) - { - return (RainbowPublicKey)o; - } - else if (o != null) - { - return new RainbowPublicKey(ASN1Sequence.getInstance(o)); - } - - return null; - } - - public ASN1Integer getVersion() - { - return version; - } - - /** - * @return the docLength - */ - public int getDocLength() - { - return this.docLength.intValueExact(); - } - - /** - * @return the coeffquadratic - */ - public short[][] getCoeffQuadratic() - { - return RainbowUtil.convertArray(coeffQuadratic); - } - - /** - * @return the coeffsingular - */ - public short[][] getCoeffSingular() - { - return RainbowUtil.convertArray(coeffSingular); - } - - /** - * @return the coeffscalar - */ - public short[] getCoeffScalar() - { - return RainbowUtil.convertArray(coeffScalar); - } - - public ASN1Primitive toASN1Primitive() - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - // encode or version - if (version != null) - { - v.add(version); - } - else - { - v.add(oid); - } - - // encode - v.add(docLength); - - // encode - ASN1EncodableVector asnCoeffQuad = new ASN1EncodableVector(); - for (int i = 0; i < coeffQuadratic.length; i++) - { - asnCoeffQuad.add(new DEROctetString(coeffQuadratic[i])); - } - v.add(new DERSequence(asnCoeffQuad)); - - // encode - ASN1EncodableVector asnCoeffSing = new ASN1EncodableVector(); - for (int i = 0; i < coeffSingular.length; i++) - { - asnCoeffSing.add(new DEROctetString(coeffSingular[i])); - } - v.add(new DERSequence(asnCoeffSing)); - - // encode - ASN1EncodableVector asnCoeffScalar = new ASN1EncodableVector(); - asnCoeffScalar.add(new DEROctetString(coeffScalar)); - v.add(new DERSequence(asnCoeffScalar)); - - - return new DERSequence(v); - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/asn1/package-info.java b/core/src/main/java/org/bouncycastle/pqc/asn1/package-info.java new file mode 100644 index 0000000000..9c5f053c82 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/asn1/package-info.java @@ -0,0 +1,4 @@ +/** + * ASN.1 Support classes for PQC algorithms. + */ +package org.bouncycastle.pqc.asn1; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/DigestUtils.java b/core/src/main/java/org/bouncycastle/pqc/crypto/DigestUtils.java new file mode 100644 index 0000000000..247b32512e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/DigestUtils.java @@ -0,0 +1,48 @@ +package org.bouncycastle.pqc.crypto; + +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; + +public class DigestUtils +{ + + /** + * Retrieve oid of hash/XOF function used to calculate pre-hash signatures + * for pre-hash versions of slh-dsa and ml-dsa + */ + static final Map digestOids = new HashMap(); + + static + { + digestOids.put("SHA-1", X509ObjectIdentifiers.id_SHA1); + digestOids.put("SHA-224", NISTObjectIdentifiers.id_sha224); + digestOids.put("SHA-256", NISTObjectIdentifiers.id_sha256); + digestOids.put("SHA-384", NISTObjectIdentifiers.id_sha384); + digestOids.put("SHA-512", NISTObjectIdentifiers.id_sha512); + digestOids.put("SHA-512/224", NISTObjectIdentifiers.id_sha512_224); + digestOids.put("SHA-512/256", NISTObjectIdentifiers.id_sha512_256); + + digestOids.put("SHA3-224", NISTObjectIdentifiers.id_sha3_224); + digestOids.put("SHA3-256", NISTObjectIdentifiers.id_sha3_256); + digestOids.put("SHA3-384", NISTObjectIdentifiers.id_sha3_384); + digestOids.put("SHA3-512", NISTObjectIdentifiers.id_sha3_512); + + digestOids.put("SHAKE128", NISTObjectIdentifiers.id_shake128); + digestOids.put("SHAKE256", NISTObjectIdentifiers.id_shake256); + } + + + public static ASN1ObjectIdentifier getDigestOid(String digestName) + { + if (digestOids.containsKey(digestName)) + { + return (ASN1ObjectIdentifier)digestOids.get(digestName); + } + + throw new IllegalArgumentException("unrecognised digest algorithm: " + digestName); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumEngine.java index 99ee009f50..76103b4373 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumEngine.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumEngine.java @@ -9,7 +9,6 @@ class DilithiumEngine { private final SecureRandom random; - private final SHAKEDigest shake128Digest = new SHAKEDigest(128); private final SHAKEDigest shake256Digest = new SHAKEDigest(256); public final static int DilithiumN = 256; @@ -151,11 +150,6 @@ SHAKEDigest getShake256Digest() return this.shake256Digest; } - SHAKEDigest getShake128Digest() - { - return this.shake128Digest; - } - DilithiumEngine(int mode, SecureRandom random, boolean usingAes) { this.DilithiumMode = mode; @@ -222,7 +216,8 @@ SHAKEDigest getShake128Digest() this.CryptoPublicKeyBytes = SeedBytes + this.DilithiumK * DilithiumPolyT1PackedBytes; this.CryptoSecretKeyBytes = ( - 3 * SeedBytes + 2 * SeedBytes + + TrBytes + DilithiumL * this.DilithiumPolyEtaPackedBytes + DilithiumK * this.DilithiumPolyEtaPackedBytes + DilithiumK * DilithiumPolyT0PackedBytes @@ -243,24 +238,28 @@ else if (this.DilithiumGamma1 == (1 << 19)) } } - public byte[][] generateKeyPair() + //Internal functions are deterministic. No randomness is sampled inside them + public byte[][] generateKeyPairInternal(byte[] seed) { - byte[] seedBuf = new byte[SeedBytes]; byte[] buf = new byte[2 * SeedBytes + CrhBytes]; byte[] tr = new byte[TrBytes]; byte[] rho = new byte[SeedBytes], - rhoPrime = new byte[CrhBytes], - key = new byte[SeedBytes]; + rhoPrime = new byte[CrhBytes], + key = new byte[SeedBytes]; PolyVecMatrix aMatrix = new PolyVecMatrix(this); PolyVecL s1 = new PolyVecL(this), s1hat; PolyVecK s2 = new PolyVecK(this), t1 = new PolyVecK(this), t0 = new PolyVecK(this); - random.nextBytes(seedBuf); - shake256Digest.update(seedBuf, 0, SeedBytes); + + shake256Digest.update(seed, 0, SeedBytes); + + //Domain separation + shake256Digest.update((byte)DilithiumK); + shake256Digest.update((byte)DilithiumL); shake256Digest.doFinal(buf, 0, 2 * SeedBytes + CrhBytes); // System.out.print("buf = "); @@ -314,11 +313,11 @@ public byte[][] generateKeyPair() shake256Digest.doFinal(tr, 0, TrBytes); byte[][] sk = Packing.packSecretKey(rho, tr, key, t0, s1, s2, this); - + return new byte[][]{ sk[0], sk[1], sk[2], sk[3], sk[4], sk[5], encT1}; } - public byte[] signSignature(byte[] msg, int msglen, byte[] rho, byte[] key, byte[] tr, byte[] t0Enc, byte[] s1Enc, byte[] s2Enc) + public byte[] signSignatureInternal(byte[] msg, int msglen, byte[] rho, byte[] key, byte[] tr, byte[] t0Enc, byte[] s1Enc, byte[] s2Enc, byte[] rnd) { int n; byte[] outSig = new byte[CryptoBytes + msglen]; @@ -335,11 +334,7 @@ public byte[] signSignature(byte[] msg, int msglen, byte[] rho, byte[] key, byte this.shake256Digest.update(msg, 0, msglen); this.shake256Digest.doFinal(mu, 0, CrhBytes); - byte[] rnd = new byte[RndBytes]; - if (random != null) - { - random.nextBytes(rnd); - } + byte[] keyMu = Arrays.copyOf(key, SeedBytes + RndBytes + CrhBytes); System.arraycopy(rnd, 0, keyMu, SeedBytes, RndBytes); @@ -379,7 +374,7 @@ public byte[] signSignature(byte[] msg, int msglen, byte[] rho, byte[] key, byte shake256Digest.update(outSig, 0, DilithiumK * DilithiumPolyW1PackedBytes); shake256Digest.doFinal(outSig, 0, DilithiumCTilde); - cp.challenge(Arrays.copyOfRange(outSig, 0, SeedBytes)); // uses only the first SeedBytes bytes of sig + cp.challenge(Arrays.copyOfRange(outSig, 0, DilithiumCTilde)); // uses only the first DilithiumCTilde bytes of sig cp.polyNtt(); // Compute z, reject if it reveals secret @@ -423,17 +418,12 @@ public byte[] signSignature(byte[] msg, int msglen, byte[] rho, byte[] key, byte return null; } - public byte[] sign(byte[] msg, int mlen, byte[] rho, byte[] key, byte[] tr, byte[] t0, byte[] s1, byte[] s2) - { - return signSignature(msg, mlen, rho, key, tr, t0, s1, s2); - } - - public boolean signVerify(byte[] sig, int siglen, byte[] msg, int msglen, byte[] rho, byte[] encT1) + public boolean signVerifyInternal(byte[] sig, int siglen, byte[] msg, int msglen, byte[] rho, byte[] encT1) { byte[] buf, - mu = new byte[CrhBytes], - c, - c2 = new byte[DilithiumCTilde]; + mu = new byte[CrhBytes], + c, + c2 = new byte[DilithiumCTilde]; Poly cp = new Poly(this); PolyVecMatrix aMatrix = new PolyVecMatrix(this); PolyVecL z = new PolyVecL(this); @@ -483,7 +473,7 @@ public boolean signVerify(byte[] sig, int siglen, byte[] msg, int msglen, byte[] // Helper.printByteArray(mu); // Matrix-vector multiplication; compute Az - c2^dt1 - cp.challenge(Arrays.copyOfRange(c, 0, SeedBytes)); // use only first SeedBytes of c. + cp.challenge(Arrays.copyOfRange(c, 0, DilithiumCTilde)); // use only first DilithiumCTilde of c. // System.out.println("cp = "); // System.out.println(cp.toString()); @@ -536,18 +526,53 @@ public boolean signVerify(byte[] sig, int siglen, byte[] msg, int msglen, byte[] // Helper.printByteArray(c2); - for (int i = 0; i < DilithiumCTilde; ++i) + return Arrays.constantTimeAreEqual(c, c2); + } + + + + public byte[][] generateKeyPair() + { + byte[] seedBuf = new byte[SeedBytes]; + random.nextBytes(seedBuf); + return generateKeyPairInternal(seedBuf); + + } + + public byte[] signSignature(byte[] msg, int msglen, byte[] rho, byte[] key, byte[] tr, byte[] t0Enc, byte[] s1Enc, byte[] s2Enc) + { + byte[] rnd = new byte[RndBytes]; + if (random != null) { - if (c[i] != c2[i]) - { - return false; - } + random.nextBytes(rnd); } - return true; + return signSignatureInternal(msg, msglen, rho, key, tr, t0Enc, s1Enc, s2Enc, rnd); + } + + public byte[] sign(byte[] msg, int mlen, byte[] rho, byte[] key, byte[] tr, byte[] t0, byte[] s1, byte[] s2) + { + return signSignature(msg, mlen, rho, key, tr, t0, s1, s2); + } + + public boolean signVerify(byte[] sig, int siglen, byte[] msg, int msglen, byte[] rho, byte[] encT1) + { + //TODO: add domain separation + // M' <- BytesToBits( IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || ctx ) || M + return signVerifyInternal(sig, siglen, msg, msglen, rho, encT1); } public boolean signOpen(byte[] msg, byte[] signedMsg, int signedMsglen, byte[] rho, byte[] t1) { + //TODO: add domain separation + // M' <- BytesToBits( IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || ctx ) || M return signVerify(signedMsg, signedMsglen, msg, msg.length, rho, t1); } + + // HashML-DSA + //TODO: Generate a "pre-hash" ML-DSA signature +// public byte[] hashSign(byte[] sk, byte[] message, byte[] ctx, Digest ph) {} + //TODO: Verify a pre-hash HashML-DSA signature +// public boolean hashVerify(byte[] pk, byte[] message, byte[] sig) {} + + } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumKeyPairGenerator.java index a32e187e23..25bb5f1219 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumKeyPairGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumKeyPairGenerator.java @@ -44,4 +44,17 @@ public AsymmetricCipherKeyPair generateKeyPair() { return genKeyPair(); } + public AsymmetricCipherKeyPair internalGenerateKeyPair(byte[] seed) + { + DilithiumEngine engine = dilithiumParams.getEngine(random); + + byte[][] keyPair = engine.generateKeyPairInternal(seed); + // System.out.println("pk gen = "); + // Helper.printByteArray(keyPair[0]); + + DilithiumPublicKeyParameters pubKey = new DilithiumPublicKeyParameters(dilithiumParams, keyPair[0], keyPair[6]); + DilithiumPrivateKeyParameters privKey = new DilithiumPrivateKeyParameters(dilithiumParams, keyPair[0], keyPair[1], keyPair[2], keyPair[3], keyPair[4], keyPair[5], keyPair[6]); + + return new AsymmetricCipherKeyPair(pubKey, privKey); + } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumSigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumSigner.java index 859916207f..a37eaafa75 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumSigner.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/DilithiumSigner.java @@ -45,6 +45,12 @@ public byte[] generateSignature(byte[] message) return engine.sign(message, message.length, privKey.rho, privKey.k, privKey.tr, privKey.t0, privKey.s1, privKey.s2); } + public byte[] internalGenerateSignature(byte[] message, byte[] random) + { + DilithiumEngine engine = privKey.getParameters().getEngine(this.random); + + return engine.signSignatureInternal(message, message.length, privKey.rho, privKey.k, privKey.tr, privKey.t0, privKey.s1, privKey.s2, random); + } public boolean verifySignature(byte[] message, byte[] signature) { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Packing.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Packing.java index 7f63350efb..ce6847ff14 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Packing.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Packing.java @@ -22,7 +22,7 @@ static PolyVecK unpackPublicKey(PolyVecK t1, byte[] publicKey, DilithiumEngine e for (i = 0; i < engine.getDilithiumK(); ++i) { - t1.getVectorIndex(i).polyt1Unpack(Arrays.copyOfRange(publicKey, i * DilithiumEngine.DilithiumPolyT1PackedBytes, DilithiumEngine.SeedBytes + (i + 1) * DilithiumEngine.DilithiumPolyT1PackedBytes)); + t1.getVectorIndex(i).polyt1Unpack(Arrays.copyOfRange(publicKey, i * DilithiumEngine.DilithiumPolyT1PackedBytes, (i + 1) * DilithiumEngine.DilithiumPolyT1PackedBytes)); } return t1; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Poly.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Poly.java index 3b1042fb87..62d6a753ce 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Poly.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/dilithium/Poly.java @@ -580,7 +580,7 @@ public void challenge(byte[] seed) byte[] buf = new byte[symmetric.stream256BlockBytes]; SHAKEDigest shake256Digest = new SHAKEDigest(256); - shake256Digest.update(seed, 0, DilithiumEngine.SeedBytes); + shake256Digest.update(seed, 0, engine.getDilithiumCTilde()); shake256Digest.doOutput(buf, 0, symmetric.stream256BlockBytes); signs = (long)0; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKEMExtractor.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKEMExtractor.java deleted file mode 100644 index 46aaf279da..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKEMExtractor.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import org.bouncycastle.crypto.EncapsulatedSecretExtractor; -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; - -public class KyberKEMExtractor - implements EncapsulatedSecretExtractor -{ - private KyberEngine engine; - - private KyberPrivateKeyParameters key; - - public KyberKEMExtractor(KyberPrivateKeyParameters privParams) - { - this.key = privParams; - initCipher(privParams); - } - - private void initCipher(AsymmetricKeyParameter recipientKey) - { - KyberPrivateKeyParameters key = (KyberPrivateKeyParameters)recipientKey; - engine = key.getParameters().getEngine(); - } - - @Override - public byte[] extractSecret(byte[] encapsulation) - { - // Decryption - byte[] sharedSecret = engine.kemDecrypt(encapsulation, key.getEncoded()); - return sharedSecret; - } - - public int getEncapsulationLength() - { - return engine.getCryptoCipherTextBytes(); - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKEMGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKEMGenerator.java deleted file mode 100644 index a10d2a3ffc..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKEMGenerator.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.EncapsulatedSecretGenerator; -import org.bouncycastle.crypto.SecretWithEncapsulation; -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; -import org.bouncycastle.pqc.crypto.util.SecretWithEncapsulationImpl; - -public class KyberKEMGenerator - implements EncapsulatedSecretGenerator -{ - // the source of randomness - private final SecureRandom sr; - - public KyberKEMGenerator(SecureRandom random) - { - this.sr = random; - } - - public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recipientKey) - { - KyberPublicKeyParameters key = (KyberPublicKeyParameters)recipientKey; - KyberEngine engine = key.getParameters().getEngine(); - engine.init(sr); - byte[][] kemEncrypt = engine.kemEncrypt(key.getEncoded()); - return new SecretWithEncapsulationImpl(kemEncrypt[0], kemEncrypt[1]); - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyGenerationParameters.java deleted file mode 100644 index 897bb69655..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyGenerationParameters.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.KeyGenerationParameters; - -public class KyberKeyGenerationParameters - extends KeyGenerationParameters -{ - private final KyberParameters params; - - public KyberKeyGenerationParameters( - SecureRandom random, - KyberParameters kyberParameters) - { - super(random, 256); - this.params = kyberParameters; - } - - public KyberParameters getParameters() - { - return params; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyPairGenerator.java deleted file mode 100644 index 96ab334d20..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyPairGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.KeyGenerationParameters; - -public class KyberKeyPairGenerator - implements AsymmetricCipherKeyPairGenerator -{ - private KyberParameters kyberParams; - - private SecureRandom random; - - private void initialize( - KeyGenerationParameters param) - { - this.kyberParams = ((KyberKeyGenerationParameters)param).getParameters(); - this.random = param.getRandom(); - - } - - private AsymmetricCipherKeyPair genKeyPair() - { - KyberEngine engine = kyberParams.getEngine(); - - engine.init(random); - - byte[][] keyPair = engine.generateKemKeyPair(); - - KyberPublicKeyParameters pubKey = new KyberPublicKeyParameters(kyberParams, keyPair[0], keyPair[1]); - KyberPrivateKeyParameters privKey = new KyberPrivateKeyParameters(kyberParams, keyPair[2], keyPair[3], keyPair[4], keyPair[0], keyPair[1]); - - return new AsymmetricCipherKeyPair(pubKey, privKey); - } - - public void init(KeyGenerationParameters param) - { - this.initialize(param); - } - - public AsymmetricCipherKeyPair generateKeyPair() - { - return genKeyPair(); - } - -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberParameters.java deleted file mode 100644 index 53cc23faf6..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberParameters.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import org.bouncycastle.pqc.crypto.KEMParameters; - -public class KyberParameters - implements KEMParameters -{ - public static final KyberParameters kyber512 = new KyberParameters("kyber512", 2, 256, false); - public static final KyberParameters kyber768 = new KyberParameters("kyber768", 3, 256, false); - public static final KyberParameters kyber1024 = new KyberParameters("kyber1024", 4, 256, false); - - private final String name; - private final int k; - private final int sessionKeySize; - - /** - * @deprecated - * obsolete to be removed - */ - private final boolean usingAes; - - private KyberParameters(String name, int k, int sessionKeySize, boolean usingAes) - { - this.name = name; - this.k = k; - this.sessionKeySize = sessionKeySize; - this.usingAes = usingAes; - } - - public String getName() - { - return name; - } - - KyberEngine getEngine() - { - return new KyberEngine(k, usingAes); - } - - public int getSessionKeySize() - { - return sessionKeySize; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberPrivateKeyParameters.java deleted file mode 100644 index afdd303658..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberPrivateKeyParameters.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import org.bouncycastle.util.Arrays; - -public class KyberPrivateKeyParameters - extends KyberKeyParameters -{ - final byte[] s; - final byte[] hpk; - final byte[] nonce; - final byte[] t; - final byte[] rho; - - public KyberPrivateKeyParameters(KyberParameters params, byte[] s, byte[] hpk, byte[] nonce, byte[] t, byte[] rho) - { - super(true, params); - - this.s = Arrays.clone(s); - this.hpk = Arrays.clone(hpk); - this.nonce = Arrays.clone(nonce); - this.t = Arrays.clone(t); - this.rho = Arrays.clone(rho); - } - - public KyberPrivateKeyParameters(KyberParameters params, byte[] encoding) - { - super(true, params); - - KyberEngine eng = params.getEngine(); - int index = 0; - this.s = Arrays.copyOfRange(encoding, 0, eng.getKyberIndCpaSecretKeyBytes()); index += eng.getKyberIndCpaSecretKeyBytes(); - this.t = Arrays.copyOfRange(encoding, index, index + eng.getKyberIndCpaPublicKeyBytes() - KyberEngine.KyberSymBytes); index += eng.getKyberIndCpaPublicKeyBytes() - KyberEngine.KyberSymBytes; - this.rho = Arrays.copyOfRange(encoding, index, index + 32); index += 32; - this.hpk = Arrays.copyOfRange(encoding, index, index + 32); index += 32; - this.nonce = Arrays.copyOfRange(encoding, index, index + KyberEngine.KyberSymBytes); - } - - public byte[] getEncoded() - { - return Arrays.concatenate(new byte[][]{ s, t, rho, hpk, nonce }); - } - - public byte[] getHPK() - { - return Arrays.clone(hpk); - } - - public byte[] getNonce() - { - return Arrays.clone(nonce); - } - - /** @deprecated Use {@link #getEncoded()} instead. */ - public byte[] getPrivateKey() - { - return getEncoded(); - } - - public byte[] getPublicKey() - { - return KyberPublicKeyParameters.getEncoded(t, rho); - } - - public KyberPublicKeyParameters getPublicKeyParameters() - { - return new KyberPublicKeyParameters(getParameters(), t, rho); - } - - public byte[] getRho() - { - return Arrays.clone(rho); - } - - public byte[] getS() - { - return Arrays.clone(s); - } - - public byte[] getT() - { - return Arrays.clone(t); - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Symmetric.java b/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Symmetric.java deleted file mode 100644 index ed666a58cb..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Symmetric.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import org.bouncycastle.crypto.ExtendedDigest; -import org.bouncycastle.crypto.StreamCipher; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.digests.SHA3Digest; -import org.bouncycastle.crypto.digests.SHA512Digest; -import org.bouncycastle.crypto.digests.SHAKEDigest; -import org.bouncycastle.crypto.engines.AESEngine; -import org.bouncycastle.crypto.modes.SICBlockCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; - -abstract class Symmetric -{ - - final int xofBlockBytes; - - abstract void hash_h(byte[] out, byte[] in, int outOffset); - - abstract void hash_g(byte[] out, byte[] in); - - abstract void xofAbsorb(byte[] seed, byte x, byte y); - - abstract void xofSqueezeBlocks(byte[] out, int outOffset, int outLen); - - abstract void prf(byte[] out, byte[] key, byte nonce); - - abstract void kdf(byte[] out, byte[] in); - - Symmetric(int blockBytes) - { - this.xofBlockBytes = blockBytes; - } - - - static class ShakeSymmetric - extends Symmetric - { - private final SHAKEDigest xof; - private final SHA3Digest sha3Digest512; - private final SHA3Digest sha3Digest256; - private final SHAKEDigest shakeDigest; - - ShakeSymmetric() - { - super(168); - this.xof = new SHAKEDigest(128); - this.shakeDigest = new SHAKEDigest(256); - this.sha3Digest256 = new SHA3Digest(256); - this.sha3Digest512 = new SHA3Digest(512); - } - - @Override - void hash_h(byte[] out, byte[] in, int outOffset) - { - sha3Digest256.update(in, 0, in.length); - sha3Digest256.doFinal(out, outOffset); - } - - @Override - void hash_g(byte[] out, byte[] in) - { - sha3Digest512.update(in, 0, in.length); - sha3Digest512.doFinal(out, 0); - } - - @Override - void xofAbsorb(byte[] seed, byte a, byte b) - { - xof.reset(); - byte[] buf = new byte[seed.length + 2]; - System.arraycopy(seed, 0, buf, 0, seed.length); - buf[seed.length] = a; - buf[seed.length + 1] = b; - xof.update(buf, 0, seed.length + 2); - } - - @Override - void xofSqueezeBlocks(byte[] out, int outOffset, int outLen) - { - xof.doOutput(out, outOffset, outLen); - } - - @Override - void prf(byte[] out, byte[] seed, byte nonce) - { - byte[] extSeed = new byte[seed.length + 1]; - System.arraycopy(seed, 0, extSeed, 0, seed.length); - extSeed[seed.length] = nonce; - shakeDigest.update(extSeed, 0, extSeed.length); - shakeDigest.doFinal(out, 0, out.length); - } - - @Override - void kdf(byte[] out, byte[] in) - { - shakeDigest.update(in, 0, in.length); - shakeDigest.doFinal(out, 0, out.length); - } - } - - /** - * @deprecated - * obsolete to be removed - */ - @Deprecated - static class AesSymmetric - extends Symmetric - { - private final SHA256Digest sha256Digest; - private final SHA512Digest sha512Digest; - private final StreamCipher cipher; - - AesSymmetric() - { - super(64); - this.sha256Digest = new SHA256Digest(); - this.sha512Digest = new SHA512Digest(); - this.cipher = SICBlockCipher.newInstance(AESEngine.newInstance()); - } - - private void doDigest(ExtendedDigest digest, byte[] out, byte[] in, int outOffset) - { - digest.update(in, 0, in.length); - digest.doFinal(out, outOffset); - } - - private void aes128(byte[] out, int offset, int size) - { - byte[] buf = new byte[size]; // TODO: there might be a more efficient way of doing this... - cipher.processBytes(buf, 0, size, out, offset); - } - - @Override - void hash_h(byte[] out, byte[] in, int outOffset) - { - doDigest(sha256Digest, out, in, outOffset); - } - - @Override - void hash_g(byte[] out, byte[] in) - { - doDigest(sha512Digest, out, in, 0); - } - - @Override - void xofAbsorb(byte[] key, byte x, byte y) - { - byte[] expnonce = new byte[12]; - expnonce[0] = x; - expnonce[1] = y; - - ParametersWithIV kp = new ParametersWithIV(new KeyParameter(key, 0, 32), expnonce); - cipher.init(true, kp); - } - - @Override - void xofSqueezeBlocks(byte[] out, int outOffset, int outLen) - { - aes128(out, outOffset, outLen); - } - - @Override - void prf(byte[] out, byte[] key, byte nonce) - { - byte[] expnonce = new byte[12]; - expnonce[0] = nonce; - - ParametersWithIV kp = new ParametersWithIV(new KeyParameter(key, 0, 32), expnonce); - cipher.init(true, kp); - aes128(out, 0, out.length); - } - - @Override - void kdf(byte[] out, byte[] in) - { - byte[] buf = new byte[32]; - doDigest(sha256Digest, buf, in, 0); - System.arraycopy(buf, 0, out, 0, out.length); - } - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/ComplexNumberWrapper.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/ComplexNumberWrapper.java deleted file mode 100644 index f3a9345381..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/ComplexNumberWrapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.bouncycastle.pqc.crypto.falcon; - -class ComplexNumberWrapper -{ - FalconFPR re; - FalconFPR im; - - ComplexNumberWrapper(FalconFPR re, FalconFPR im) - { - this.re = re; - this.im = im; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FPREngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FPREngine.java index f90b25f456..37906426d1 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FPREngine.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FPREngine.java @@ -2,1144 +2,1136 @@ class FPREngine { - private static final FalconFPR[] inv_sigma; - private static final FalconFPR[] sigma_min; - private static final FalconFPR[] gm_tab; - private static final FalconFPR[] p2_tab; +// static final double[] inv_sigma; +// static final double[] sigma_min; +// static final double[] gm_tab; +// static final double[] p2_tab; static { - inv_sigma = new FalconFPR[]{ - new FalconFPR(0.0), /* unused */ - new FalconFPR(0.0069054793295940891952143765991630516), - new FalconFPR(0.0068102267767177975961393730687908629), - new FalconFPR(0.0067188101910722710707826117910434131), - new FalconFPR(0.0065883354370073665545865037227681924), - new FalconFPR(0.0064651781207602900738053897763485516), - new FalconFPR(0.0063486788828078995327741182928037856), - new FalconFPR(0.0062382586529084374473367528433697537), - new FalconFPR(0.0061334065020930261548984001431770281), - new FalconFPR(0.0060336696681577241031668062510953022), - new FalconFPR(0.0059386453095331159950250124336477482) + fpr_inv_sigma = new double[]{ + 0.0, /* unused */ + 0.0069054793295940891952143765991630516, + 0.0068102267767177975961393730687908629, + 0.0067188101910722710707826117910434131, + 0.0065883354370073665545865037227681924, + 0.0064651781207602900738053897763485516, + 0.0063486788828078995327741182928037856, + 0.0062382586529084374473367528433697537, + 0.0061334065020930261548984001431770281, + 0.0060336696681577241031668062510953022, + 0.0059386453095331159950250124336477482 }; - sigma_min = new FalconFPR[]{ - new FalconFPR(0.0), /* unused */ - new FalconFPR(1.1165085072329102588881898380334015), - new FalconFPR(1.1321247692325272405718031785357108), - new FalconFPR(1.1475285353733668684571123112513188), - new FalconFPR(1.1702540788534828939713084716509250), - new FalconFPR(1.1925466358390344011122170489094133), - new FalconFPR(1.2144300507766139921088487776957699), - new FalconFPR(1.2359260567719808790104525941706723), - new FalconFPR(1.2570545284063214162779743112075080), - new FalconFPR(1.2778336969128335860256340575729042), - new FalconFPR(1.2982803343442918539708792538826807) + fpr_sigma_min = new double[]{ + 0.0, /* unused */ + 1.1165085072329102588881898380334015, + 1.1321247692325272405718031785357108, + 1.1475285353733668684571123112513188, + 1.1702540788534828939713084716509250, + 1.1925466358390344011122170489094133, + 1.2144300507766139921088487776957699, + 1.2359260567719808790104525941706723, + 1.2570545284063214162779743112075080, + 1.2778336969128335860256340575729042, + 1.2982803343442918539708792538826807 }; - gm_tab = new FalconFPR[]{ - new FalconFPR(0), new FalconFPR(0), /* unused */ - new FalconFPR(-0.000000000000000000000000000), new FalconFPR(1.000000000000000000000000000), - new FalconFPR(0.707106781186547524400844362), new FalconFPR(0.707106781186547524400844362), - new FalconFPR(-0.707106781186547524400844362), new FalconFPR(0.707106781186547524400844362), - new FalconFPR(0.923879532511286756128183189), new FalconFPR(0.382683432365089771728459984), - new FalconFPR(-0.382683432365089771728459984), new FalconFPR(0.923879532511286756128183189), - new FalconFPR(0.382683432365089771728459984), new FalconFPR(0.923879532511286756128183189), - new FalconFPR(-0.923879532511286756128183189), new FalconFPR(0.382683432365089771728459984), - new FalconFPR(0.980785280403230449126182236), new FalconFPR(0.195090322016128267848284868), - new FalconFPR(-0.195090322016128267848284868), new FalconFPR(0.980785280403230449126182236), - new FalconFPR(0.555570233019602224742830814), new FalconFPR(0.831469612302545237078788378), - new FalconFPR(-0.831469612302545237078788378), new FalconFPR(0.555570233019602224742830814), - new FalconFPR(0.831469612302545237078788378), new FalconFPR(0.555570233019602224742830814), - new FalconFPR(-0.555570233019602224742830814), new FalconFPR(0.831469612302545237078788378), - new FalconFPR(0.195090322016128267848284868), new FalconFPR(0.980785280403230449126182236), - new FalconFPR(-0.980785280403230449126182236), new FalconFPR(0.195090322016128267848284868), - new FalconFPR(0.995184726672196886244836953), new FalconFPR(0.098017140329560601994195564), - new FalconFPR(-0.098017140329560601994195564), new FalconFPR(0.995184726672196886244836953), - new FalconFPR(0.634393284163645498215171613), new FalconFPR(0.773010453362736960810906610), - new FalconFPR(-0.773010453362736960810906610), new FalconFPR(0.634393284163645498215171613), - new FalconFPR(0.881921264348355029712756864), new FalconFPR(0.471396736825997648556387626), - new FalconFPR(-0.471396736825997648556387626), new FalconFPR(0.881921264348355029712756864), - new FalconFPR(0.290284677254462367636192376), new FalconFPR(0.956940335732208864935797887), - new FalconFPR(-0.956940335732208864935797887), new FalconFPR(0.290284677254462367636192376), - new FalconFPR(0.956940335732208864935797887), new FalconFPR(0.290284677254462367636192376), - new FalconFPR(-0.290284677254462367636192376), new FalconFPR(0.956940335732208864935797887), - new FalconFPR(0.471396736825997648556387626), new FalconFPR(0.881921264348355029712756864), - new FalconFPR(-0.881921264348355029712756864), new FalconFPR(0.471396736825997648556387626), - new FalconFPR(0.773010453362736960810906610), new FalconFPR(0.634393284163645498215171613), - new FalconFPR(-0.634393284163645498215171613), new FalconFPR(0.773010453362736960810906610), - new FalconFPR(0.098017140329560601994195564), new FalconFPR(0.995184726672196886244836953), - new FalconFPR(-0.995184726672196886244836953), new FalconFPR(0.098017140329560601994195564), - new FalconFPR(0.998795456205172392714771605), new FalconFPR(0.049067674327418014254954977), - new FalconFPR(-0.049067674327418014254954977), new FalconFPR(0.998795456205172392714771605), - new FalconFPR(0.671558954847018400625376850), new FalconFPR(0.740951125354959091175616897), - new FalconFPR(-0.740951125354959091175616897), new FalconFPR(0.671558954847018400625376850), - new FalconFPR(0.903989293123443331586200297), new FalconFPR(0.427555093430282094320966857), - new FalconFPR(-0.427555093430282094320966857), new FalconFPR(0.903989293123443331586200297), - new FalconFPR(0.336889853392220050689253213), new FalconFPR(0.941544065183020778412509403), - new FalconFPR(-0.941544065183020778412509403), new FalconFPR(0.336889853392220050689253213), - new FalconFPR(0.970031253194543992603984207), new FalconFPR(0.242980179903263889948274162), - new FalconFPR(-0.242980179903263889948274162), new FalconFPR(0.970031253194543992603984207), - new FalconFPR(0.514102744193221726593693839), new FalconFPR(0.857728610000272069902269984), - new FalconFPR(-0.857728610000272069902269984), new FalconFPR(0.514102744193221726593693839), - new FalconFPR(0.803207531480644909806676513), new FalconFPR(0.595699304492433343467036529), - new FalconFPR(-0.595699304492433343467036529), new FalconFPR(0.803207531480644909806676513), - new FalconFPR(0.146730474455361751658850130), new FalconFPR(0.989176509964780973451673738), - new FalconFPR(-0.989176509964780973451673738), new FalconFPR(0.146730474455361751658850130), - new FalconFPR(0.989176509964780973451673738), new FalconFPR(0.146730474455361751658850130), - new FalconFPR(-0.146730474455361751658850130), new FalconFPR(0.989176509964780973451673738), - new FalconFPR(0.595699304492433343467036529), new FalconFPR(0.803207531480644909806676513), - new FalconFPR(-0.803207531480644909806676513), new FalconFPR(0.595699304492433343467036529), - new FalconFPR(0.857728610000272069902269984), new FalconFPR(0.514102744193221726593693839), - new FalconFPR(-0.514102744193221726593693839), new FalconFPR(0.857728610000272069902269984), - new FalconFPR(0.242980179903263889948274162), new FalconFPR(0.970031253194543992603984207), - new FalconFPR(-0.970031253194543992603984207), new FalconFPR(0.242980179903263889948274162), - new FalconFPR(0.941544065183020778412509403), new FalconFPR(0.336889853392220050689253213), - new FalconFPR(-0.336889853392220050689253213), new FalconFPR(0.941544065183020778412509403), - new FalconFPR(0.427555093430282094320966857), new FalconFPR(0.903989293123443331586200297), - new FalconFPR(-0.903989293123443331586200297), new FalconFPR(0.427555093430282094320966857), - new FalconFPR(0.740951125354959091175616897), new FalconFPR(0.671558954847018400625376850), - new FalconFPR(-0.671558954847018400625376850), new FalconFPR(0.740951125354959091175616897), - new FalconFPR(0.049067674327418014254954977), new FalconFPR(0.998795456205172392714771605), - new FalconFPR(-0.998795456205172392714771605), new FalconFPR(0.049067674327418014254954977), - new FalconFPR(0.999698818696204220115765650), new FalconFPR(0.024541228522912288031734529), - new FalconFPR(-0.024541228522912288031734529), new FalconFPR(0.999698818696204220115765650), - new FalconFPR(0.689540544737066924616730630), new FalconFPR(0.724247082951466920941069243), - new FalconFPR(-0.724247082951466920941069243), new FalconFPR(0.689540544737066924616730630), - new FalconFPR(0.914209755703530654635014829), new FalconFPR(0.405241314004989870908481306), - new FalconFPR(-0.405241314004989870908481306), new FalconFPR(0.914209755703530654635014829), - new FalconFPR(0.359895036534988148775104572), new FalconFPR(0.932992798834738887711660256), - new FalconFPR(-0.932992798834738887711660256), new FalconFPR(0.359895036534988148775104572), - new FalconFPR(0.975702130038528544460395766), new FalconFPR(0.219101240156869797227737547), - new FalconFPR(-0.219101240156869797227737547), new FalconFPR(0.975702130038528544460395766), - new FalconFPR(0.534997619887097210663076905), new FalconFPR(0.844853565249707073259571205), - new FalconFPR(-0.844853565249707073259571205), new FalconFPR(0.534997619887097210663076905), - new FalconFPR(0.817584813151583696504920884), new FalconFPR(0.575808191417845300745972454), - new FalconFPR(-0.575808191417845300745972454), new FalconFPR(0.817584813151583696504920884), - new FalconFPR(0.170961888760301226363642357), new FalconFPR(0.985277642388941244774018433), - new FalconFPR(-0.985277642388941244774018433), new FalconFPR(0.170961888760301226363642357), - new FalconFPR(0.992479534598709998156767252), new FalconFPR(0.122410675199216198498704474), - new FalconFPR(-0.122410675199216198498704474), new FalconFPR(0.992479534598709998156767252), - new FalconFPR(0.615231590580626845484913563), new FalconFPR(0.788346427626606262009164705), - new FalconFPR(-0.788346427626606262009164705), new FalconFPR(0.615231590580626845484913563), - new FalconFPR(0.870086991108711418652292404), new FalconFPR(0.492898192229784036873026689), - new FalconFPR(-0.492898192229784036873026689), new FalconFPR(0.870086991108711418652292404), - new FalconFPR(0.266712757474898386325286515), new FalconFPR(0.963776065795439866686464356), - new FalconFPR(-0.963776065795439866686464356), new FalconFPR(0.266712757474898386325286515), - new FalconFPR(0.949528180593036667195936074), new FalconFPR(0.313681740398891476656478846), - new FalconFPR(-0.313681740398891476656478846), new FalconFPR(0.949528180593036667195936074), - new FalconFPR(0.449611329654606600046294579), new FalconFPR(0.893224301195515320342416447), - new FalconFPR(-0.893224301195515320342416447), new FalconFPR(0.449611329654606600046294579), - new FalconFPR(0.757208846506484547575464054), new FalconFPR(0.653172842953776764084203014), - new FalconFPR(-0.653172842953776764084203014), new FalconFPR(0.757208846506484547575464054), - new FalconFPR(0.073564563599667423529465622), new FalconFPR(0.997290456678690216135597140), - new FalconFPR(-0.997290456678690216135597140), new FalconFPR(0.073564563599667423529465622), - new FalconFPR(0.997290456678690216135597140), new FalconFPR(0.073564563599667423529465622), - new FalconFPR(-0.073564563599667423529465622), new FalconFPR(0.997290456678690216135597140), - new FalconFPR(0.653172842953776764084203014), new FalconFPR(0.757208846506484547575464054), - new FalconFPR(-0.757208846506484547575464054), new FalconFPR(0.653172842953776764084203014), - new FalconFPR(0.893224301195515320342416447), new FalconFPR(0.449611329654606600046294579), - new FalconFPR(-0.449611329654606600046294579), new FalconFPR(0.893224301195515320342416447), - new FalconFPR(0.313681740398891476656478846), new FalconFPR(0.949528180593036667195936074), - new FalconFPR(-0.949528180593036667195936074), new FalconFPR(0.313681740398891476656478846), - new FalconFPR(0.963776065795439866686464356), new FalconFPR(0.266712757474898386325286515), - new FalconFPR(-0.266712757474898386325286515), new FalconFPR(0.963776065795439866686464356), - new FalconFPR(0.492898192229784036873026689), new FalconFPR(0.870086991108711418652292404), - new FalconFPR(-0.870086991108711418652292404), new FalconFPR(0.492898192229784036873026689), - new FalconFPR(0.788346427626606262009164705), new FalconFPR(0.615231590580626845484913563), - new FalconFPR(-0.615231590580626845484913563), new FalconFPR(0.788346427626606262009164705), - new FalconFPR(0.122410675199216198498704474), new FalconFPR(0.992479534598709998156767252), - new FalconFPR(-0.992479534598709998156767252), new FalconFPR(0.122410675199216198498704474), - new FalconFPR(0.985277642388941244774018433), new FalconFPR(0.170961888760301226363642357), - new FalconFPR(-0.170961888760301226363642357), new FalconFPR(0.985277642388941244774018433), - new FalconFPR(0.575808191417845300745972454), new FalconFPR(0.817584813151583696504920884), - new FalconFPR(-0.817584813151583696504920884), new FalconFPR(0.575808191417845300745972454), - new FalconFPR(0.844853565249707073259571205), new FalconFPR(0.534997619887097210663076905), - new FalconFPR(-0.534997619887097210663076905), new FalconFPR(0.844853565249707073259571205), - new FalconFPR(0.219101240156869797227737547), new FalconFPR(0.975702130038528544460395766), - new FalconFPR(-0.975702130038528544460395766), new FalconFPR(0.219101240156869797227737547), - new FalconFPR(0.932992798834738887711660256), new FalconFPR(0.359895036534988148775104572), - new FalconFPR(-0.359895036534988148775104572), new FalconFPR(0.932992798834738887711660256), - new FalconFPR(0.405241314004989870908481306), new FalconFPR(0.914209755703530654635014829), - new FalconFPR(-0.914209755703530654635014829), new FalconFPR(0.405241314004989870908481306), - new FalconFPR(0.724247082951466920941069243), new FalconFPR(0.689540544737066924616730630), - new FalconFPR(-0.689540544737066924616730630), new FalconFPR(0.724247082951466920941069243), - new FalconFPR(0.024541228522912288031734529), new FalconFPR(0.999698818696204220115765650), - new FalconFPR(-0.999698818696204220115765650), new FalconFPR(0.024541228522912288031734529), - new FalconFPR(0.999924701839144540921646491), new FalconFPR(0.012271538285719926079408262), - new FalconFPR(-0.012271538285719926079408262), new FalconFPR(0.999924701839144540921646491), - new FalconFPR(0.698376249408972853554813503), new FalconFPR(0.715730825283818654125532623), - new FalconFPR(-0.715730825283818654125532623), new FalconFPR(0.698376249408972853554813503), - new FalconFPR(0.919113851690057743908477789), new FalconFPR(0.393992040061048108596188661), - new FalconFPR(-0.393992040061048108596188661), new FalconFPR(0.919113851690057743908477789), - new FalconFPR(0.371317193951837543411934967), new FalconFPR(0.928506080473215565937167396), - new FalconFPR(-0.928506080473215565937167396), new FalconFPR(0.371317193951837543411934967), - new FalconFPR(0.978317370719627633106240097), new FalconFPR(0.207111376192218549708116020), - new FalconFPR(-0.207111376192218549708116020), new FalconFPR(0.978317370719627633106240097), - new FalconFPR(0.545324988422046422313987347), new FalconFPR(0.838224705554838043186996856), - new FalconFPR(-0.838224705554838043186996856), new FalconFPR(0.545324988422046422313987347), - new FalconFPR(0.824589302785025264474803737), new FalconFPR(0.565731810783613197389765011), - new FalconFPR(-0.565731810783613197389765011), new FalconFPR(0.824589302785025264474803737), - new FalconFPR(0.183039887955140958516532578), new FalconFPR(0.983105487431216327180301155), - new FalconFPR(-0.983105487431216327180301155), new FalconFPR(0.183039887955140958516532578), - new FalconFPR(0.993906970002356041546922813), new FalconFPR(0.110222207293883058807899140), - new FalconFPR(-0.110222207293883058807899140), new FalconFPR(0.993906970002356041546922813), - new FalconFPR(0.624859488142386377084072816), new FalconFPR(0.780737228572094478301588484), - new FalconFPR(-0.780737228572094478301588484), new FalconFPR(0.624859488142386377084072816), - new FalconFPR(0.876070094195406607095844268), new FalconFPR(0.482183772079122748517344481), - new FalconFPR(-0.482183772079122748517344481), new FalconFPR(0.876070094195406607095844268), - new FalconFPR(0.278519689385053105207848526), new FalconFPR(0.960430519415565811199035138), - new FalconFPR(-0.960430519415565811199035138), new FalconFPR(0.278519689385053105207848526), - new FalconFPR(0.953306040354193836916740383), new FalconFPR(0.302005949319228067003463232), - new FalconFPR(-0.302005949319228067003463232), new FalconFPR(0.953306040354193836916740383), - new FalconFPR(0.460538710958240023633181487), new FalconFPR(0.887639620402853947760181617), - new FalconFPR(-0.887639620402853947760181617), new FalconFPR(0.460538710958240023633181487), - new FalconFPR(0.765167265622458925888815999), new FalconFPR(0.643831542889791465068086063), - new FalconFPR(-0.643831542889791465068086063), new FalconFPR(0.765167265622458925888815999), - new FalconFPR(0.085797312344439890461556332), new FalconFPR(0.996312612182778012627226190), - new FalconFPR(-0.996312612182778012627226190), new FalconFPR(0.085797312344439890461556332), - new FalconFPR(0.998118112900149207125155861), new FalconFPR(0.061320736302208577782614593), - new FalconFPR(-0.061320736302208577782614593), new FalconFPR(0.998118112900149207125155861), - new FalconFPR(0.662415777590171761113069817), new FalconFPR(0.749136394523459325469203257), - new FalconFPR(-0.749136394523459325469203257), new FalconFPR(0.662415777590171761113069817), - new FalconFPR(0.898674465693953843041976744), new FalconFPR(0.438616238538527637647025738), - new FalconFPR(-0.438616238538527637647025738), new FalconFPR(0.898674465693953843041976744), - new FalconFPR(0.325310292162262934135954708), new FalconFPR(0.945607325380521325730945387), - new FalconFPR(-0.945607325380521325730945387), new FalconFPR(0.325310292162262934135954708), - new FalconFPR(0.966976471044852109087220226), new FalconFPR(0.254865659604514571553980779), - new FalconFPR(-0.254865659604514571553980779), new FalconFPR(0.966976471044852109087220226), - new FalconFPR(0.503538383725717558691867071), new FalconFPR(0.863972856121586737918147054), - new FalconFPR(-0.863972856121586737918147054), new FalconFPR(0.503538383725717558691867071), - new FalconFPR(0.795836904608883536262791915), new FalconFPR(0.605511041404325513920626941), - new FalconFPR(-0.605511041404325513920626941), new FalconFPR(0.795836904608883536262791915), - new FalconFPR(0.134580708507126186316358409), new FalconFPR(0.990902635427780025108237011), - new FalconFPR(-0.990902635427780025108237011), new FalconFPR(0.134580708507126186316358409), - new FalconFPR(0.987301418157858382399815802), new FalconFPR(0.158858143333861441684385360), - new FalconFPR(-0.158858143333861441684385360), new FalconFPR(0.987301418157858382399815802), - new FalconFPR(0.585797857456438860328080838), new FalconFPR(0.810457198252594791726703434), - new FalconFPR(-0.810457198252594791726703434), new FalconFPR(0.585797857456438860328080838), - new FalconFPR(0.851355193105265142261290312), new FalconFPR(0.524589682678468906215098464), - new FalconFPR(-0.524589682678468906215098464), new FalconFPR(0.851355193105265142261290312), - new FalconFPR(0.231058108280671119643236018), new FalconFPR(0.972939952205560145467720114), - new FalconFPR(-0.972939952205560145467720114), new FalconFPR(0.231058108280671119643236018), - new FalconFPR(0.937339011912574923201899593), new FalconFPR(0.348418680249434568419308588), - new FalconFPR(-0.348418680249434568419308588), new FalconFPR(0.937339011912574923201899593), - new FalconFPR(0.416429560097637182562598911), new FalconFPR(0.909167983090522376563884788), - new FalconFPR(-0.909167983090522376563884788), new FalconFPR(0.416429560097637182562598911), - new FalconFPR(0.732654271672412834615546649), new FalconFPR(0.680600997795453050594430464), - new FalconFPR(-0.680600997795453050594430464), new FalconFPR(0.732654271672412834615546649), - new FalconFPR(0.036807222941358832324332691), new FalconFPR(0.999322384588349500896221011), - new FalconFPR(-0.999322384588349500896221011), new FalconFPR(0.036807222941358832324332691), - new FalconFPR(0.999322384588349500896221011), new FalconFPR(0.036807222941358832324332691), - new FalconFPR(-0.036807222941358832324332691), new FalconFPR(0.999322384588349500896221011), - new FalconFPR(0.680600997795453050594430464), new FalconFPR(0.732654271672412834615546649), - new FalconFPR(-0.732654271672412834615546649), new FalconFPR(0.680600997795453050594430464), - new FalconFPR(0.909167983090522376563884788), new FalconFPR(0.416429560097637182562598911), - new FalconFPR(-0.416429560097637182562598911), new FalconFPR(0.909167983090522376563884788), - new FalconFPR(0.348418680249434568419308588), new FalconFPR(0.937339011912574923201899593), - new FalconFPR(-0.937339011912574923201899593), new FalconFPR(0.348418680249434568419308588), - new FalconFPR(0.972939952205560145467720114), new FalconFPR(0.231058108280671119643236018), - new FalconFPR(-0.231058108280671119643236018), new FalconFPR(0.972939952205560145467720114), - new FalconFPR(0.524589682678468906215098464), new FalconFPR(0.851355193105265142261290312), - new FalconFPR(-0.851355193105265142261290312), new FalconFPR(0.524589682678468906215098464), - new FalconFPR(0.810457198252594791726703434), new FalconFPR(0.585797857456438860328080838), - new FalconFPR(-0.585797857456438860328080838), new FalconFPR(0.810457198252594791726703434), - new FalconFPR(0.158858143333861441684385360), new FalconFPR(0.987301418157858382399815802), - new FalconFPR(-0.987301418157858382399815802), new FalconFPR(0.158858143333861441684385360), - new FalconFPR(0.990902635427780025108237011), new FalconFPR(0.134580708507126186316358409), - new FalconFPR(-0.134580708507126186316358409), new FalconFPR(0.990902635427780025108237011), - new FalconFPR(0.605511041404325513920626941), new FalconFPR(0.795836904608883536262791915), - new FalconFPR(-0.795836904608883536262791915), new FalconFPR(0.605511041404325513920626941), - new FalconFPR(0.863972856121586737918147054), new FalconFPR(0.503538383725717558691867071), - new FalconFPR(-0.503538383725717558691867071), new FalconFPR(0.863972856121586737918147054), - new FalconFPR(0.254865659604514571553980779), new FalconFPR(0.966976471044852109087220226), - new FalconFPR(-0.966976471044852109087220226), new FalconFPR(0.254865659604514571553980779), - new FalconFPR(0.945607325380521325730945387), new FalconFPR(0.325310292162262934135954708), - new FalconFPR(-0.325310292162262934135954708), new FalconFPR(0.945607325380521325730945387), - new FalconFPR(0.438616238538527637647025738), new FalconFPR(0.898674465693953843041976744), - new FalconFPR(-0.898674465693953843041976744), new FalconFPR(0.438616238538527637647025738), - new FalconFPR(0.749136394523459325469203257), new FalconFPR(0.662415777590171761113069817), - new FalconFPR(-0.662415777590171761113069817), new FalconFPR(0.749136394523459325469203257), - new FalconFPR(0.061320736302208577782614593), new FalconFPR(0.998118112900149207125155861), - new FalconFPR(-0.998118112900149207125155861), new FalconFPR(0.061320736302208577782614593), - new FalconFPR(0.996312612182778012627226190), new FalconFPR(0.085797312344439890461556332), - new FalconFPR(-0.085797312344439890461556332), new FalconFPR(0.996312612182778012627226190), - new FalconFPR(0.643831542889791465068086063), new FalconFPR(0.765167265622458925888815999), - new FalconFPR(-0.765167265622458925888815999), new FalconFPR(0.643831542889791465068086063), - new FalconFPR(0.887639620402853947760181617), new FalconFPR(0.460538710958240023633181487), - new FalconFPR(-0.460538710958240023633181487), new FalconFPR(0.887639620402853947760181617), - new FalconFPR(0.302005949319228067003463232), new FalconFPR(0.953306040354193836916740383), - new FalconFPR(-0.953306040354193836916740383), new FalconFPR(0.302005949319228067003463232), - new FalconFPR(0.960430519415565811199035138), new FalconFPR(0.278519689385053105207848526), - new FalconFPR(-0.278519689385053105207848526), new FalconFPR(0.960430519415565811199035138), - new FalconFPR(0.482183772079122748517344481), new FalconFPR(0.876070094195406607095844268), - new FalconFPR(-0.876070094195406607095844268), new FalconFPR(0.482183772079122748517344481), - new FalconFPR(0.780737228572094478301588484), new FalconFPR(0.624859488142386377084072816), - new FalconFPR(-0.624859488142386377084072816), new FalconFPR(0.780737228572094478301588484), - new FalconFPR(0.110222207293883058807899140), new FalconFPR(0.993906970002356041546922813), - new FalconFPR(-0.993906970002356041546922813), new FalconFPR(0.110222207293883058807899140), - new FalconFPR(0.983105487431216327180301155), new FalconFPR(0.183039887955140958516532578), - new FalconFPR(-0.183039887955140958516532578), new FalconFPR(0.983105487431216327180301155), - new FalconFPR(0.565731810783613197389765011), new FalconFPR(0.824589302785025264474803737), - new FalconFPR(-0.824589302785025264474803737), new FalconFPR(0.565731810783613197389765011), - new FalconFPR(0.838224705554838043186996856), new FalconFPR(0.545324988422046422313987347), - new FalconFPR(-0.545324988422046422313987347), new FalconFPR(0.838224705554838043186996856), - new FalconFPR(0.207111376192218549708116020), new FalconFPR(0.978317370719627633106240097), - new FalconFPR(-0.978317370719627633106240097), new FalconFPR(0.207111376192218549708116020), - new FalconFPR(0.928506080473215565937167396), new FalconFPR(0.371317193951837543411934967), - new FalconFPR(-0.371317193951837543411934967), new FalconFPR(0.928506080473215565937167396), - new FalconFPR(0.393992040061048108596188661), new FalconFPR(0.919113851690057743908477789), - new FalconFPR(-0.919113851690057743908477789), new FalconFPR(0.393992040061048108596188661), - new FalconFPR(0.715730825283818654125532623), new FalconFPR(0.698376249408972853554813503), - new FalconFPR(-0.698376249408972853554813503), new FalconFPR(0.715730825283818654125532623), - new FalconFPR(0.012271538285719926079408262), new FalconFPR(0.999924701839144540921646491), - new FalconFPR(-0.999924701839144540921646491), new FalconFPR(0.012271538285719926079408262), - new FalconFPR(0.999981175282601142656990438), new FalconFPR(0.006135884649154475359640235), - new FalconFPR(-0.006135884649154475359640235), new FalconFPR(0.999981175282601142656990438), - new FalconFPR(0.702754744457225302452914421), new FalconFPR(0.711432195745216441522130290), - new FalconFPR(-0.711432195745216441522130290), new FalconFPR(0.702754744457225302452914421), - new FalconFPR(0.921514039342041943465396332), new FalconFPR(0.388345046698826291624993541), - new FalconFPR(-0.388345046698826291624993541), new FalconFPR(0.921514039342041943465396332), - new FalconFPR(0.377007410216418256726567823), new FalconFPR(0.926210242138311341974793388), - new FalconFPR(-0.926210242138311341974793388), new FalconFPR(0.377007410216418256726567823), - new FalconFPR(0.979569765685440534439326110), new FalconFPR(0.201104634842091911558443546), - new FalconFPR(-0.201104634842091911558443546), new FalconFPR(0.979569765685440534439326110), - new FalconFPR(0.550457972936604802977289893), new FalconFPR(0.834862874986380056304401383), - new FalconFPR(-0.834862874986380056304401383), new FalconFPR(0.550457972936604802977289893), - new FalconFPR(0.828045045257755752067527592), new FalconFPR(0.560661576197336023839710223), - new FalconFPR(-0.560661576197336023839710223), new FalconFPR(0.828045045257755752067527592), - new FalconFPR(0.189068664149806212754997837), new FalconFPR(0.981963869109555264072848154), - new FalconFPR(-0.981963869109555264072848154), new FalconFPR(0.189068664149806212754997837), - new FalconFPR(0.994564570734255452119106243), new FalconFPR(0.104121633872054579120943880), - new FalconFPR(-0.104121633872054579120943880), new FalconFPR(0.994564570734255452119106243), - new FalconFPR(0.629638238914927025372981341), new FalconFPR(0.776888465673232450040827983), - new FalconFPR(-0.776888465673232450040827983), new FalconFPR(0.629638238914927025372981341), - new FalconFPR(0.879012226428633477831323711), new FalconFPR(0.476799230063322133342158117), - new FalconFPR(-0.476799230063322133342158117), new FalconFPR(0.879012226428633477831323711), - new FalconFPR(0.284407537211271843618310615), new FalconFPR(0.958703474895871555374645792), - new FalconFPR(-0.958703474895871555374645792), new FalconFPR(0.284407537211271843618310615), - new FalconFPR(0.955141168305770721498157712), new FalconFPR(0.296150888243623824121786128), - new FalconFPR(-0.296150888243623824121786128), new FalconFPR(0.955141168305770721498157712), - new FalconFPR(0.465976495767966177902756065), new FalconFPR(0.884797098430937780104007041), - new FalconFPR(-0.884797098430937780104007041), new FalconFPR(0.465976495767966177902756065), - new FalconFPR(0.769103337645579639346626069), new FalconFPR(0.639124444863775743801488193), - new FalconFPR(-0.639124444863775743801488193), new FalconFPR(0.769103337645579639346626069), - new FalconFPR(0.091908956497132728624990979), new FalconFPR(0.995767414467659793982495643), - new FalconFPR(-0.995767414467659793982495643), new FalconFPR(0.091908956497132728624990979), - new FalconFPR(0.998475580573294752208559038), new FalconFPR(0.055195244349689939809447526), - new FalconFPR(-0.055195244349689939809447526), new FalconFPR(0.998475580573294752208559038), - new FalconFPR(0.666999922303637506650154222), new FalconFPR(0.745057785441465962407907310), - new FalconFPR(-0.745057785441465962407907310), new FalconFPR(0.666999922303637506650154222), - new FalconFPR(0.901348847046022014570746093), new FalconFPR(0.433093818853151968484222638), - new FalconFPR(-0.433093818853151968484222638), new FalconFPR(0.901348847046022014570746093), - new FalconFPR(0.331106305759876401737190737), new FalconFPR(0.943593458161960361495301445), - new FalconFPR(-0.943593458161960361495301445), new FalconFPR(0.331106305759876401737190737), - new FalconFPR(0.968522094274417316221088329), new FalconFPR(0.248927605745720168110682816), - new FalconFPR(-0.248927605745720168110682816), new FalconFPR(0.968522094274417316221088329), - new FalconFPR(0.508830142543107036931749324), new FalconFPR(0.860866938637767279344583877), - new FalconFPR(-0.860866938637767279344583877), new FalconFPR(0.508830142543107036931749324), - new FalconFPR(0.799537269107905033500246232), new FalconFPR(0.600616479383868926653875896), - new FalconFPR(-0.600616479383868926653875896), new FalconFPR(0.799537269107905033500246232), - new FalconFPR(0.140658239332849230714788846), new FalconFPR(0.990058210262297105505906464), - new FalconFPR(-0.990058210262297105505906464), new FalconFPR(0.140658239332849230714788846), - new FalconFPR(0.988257567730749491404792538), new FalconFPR(0.152797185258443427720336613), - new FalconFPR(-0.152797185258443427720336613), new FalconFPR(0.988257567730749491404792538), - new FalconFPR(0.590759701858874228423887908), new FalconFPR(0.806847553543799272206514313), - new FalconFPR(-0.806847553543799272206514313), new FalconFPR(0.590759701858874228423887908), - new FalconFPR(0.854557988365400520767862276), new FalconFPR(0.519355990165589587361829932), - new FalconFPR(-0.519355990165589587361829932), new FalconFPR(0.854557988365400520767862276), - new FalconFPR(0.237023605994367206867735915), new FalconFPR(0.971503890986251775537099622), - new FalconFPR(-0.971503890986251775537099622), new FalconFPR(0.237023605994367206867735915), - new FalconFPR(0.939459223602189911962669246), new FalconFPR(0.342660717311994397592781983), - new FalconFPR(-0.342660717311994397592781983), new FalconFPR(0.939459223602189911962669246), - new FalconFPR(0.422000270799799685941287941), new FalconFPR(0.906595704514915365332960588), - new FalconFPR(-0.906595704514915365332960588), new FalconFPR(0.422000270799799685941287941), - new FalconFPR(0.736816568877369875090132520), new FalconFPR(0.676092703575315960360419228), - new FalconFPR(-0.676092703575315960360419228), new FalconFPR(0.736816568877369875090132520), - new FalconFPR(0.042938256934940823077124540), new FalconFPR(0.999077727752645382888781997), - new FalconFPR(-0.999077727752645382888781997), new FalconFPR(0.042938256934940823077124540), - new FalconFPR(0.999529417501093163079703322), new FalconFPR(0.030674803176636625934021028), - new FalconFPR(-0.030674803176636625934021028), new FalconFPR(0.999529417501093163079703322), - new FalconFPR(0.685083667772700381362052545), new FalconFPR(0.728464390448225196492035438), - new FalconFPR(-0.728464390448225196492035438), new FalconFPR(0.685083667772700381362052545), - new FalconFPR(0.911706032005429851404397325), new FalconFPR(0.410843171057903942183466675), - new FalconFPR(-0.410843171057903942183466675), new FalconFPR(0.911706032005429851404397325), - new FalconFPR(0.354163525420490382357395796), new FalconFPR(0.935183509938947577642207480), - new FalconFPR(-0.935183509938947577642207480), new FalconFPR(0.354163525420490382357395796), - new FalconFPR(0.974339382785575860518721668), new FalconFPR(0.225083911359792835991642120), - new FalconFPR(-0.225083911359792835991642120), new FalconFPR(0.974339382785575860518721668), - new FalconFPR(0.529803624686294668216054671), new FalconFPR(0.848120344803297251279133563), - new FalconFPR(-0.848120344803297251279133563), new FalconFPR(0.529803624686294668216054671), - new FalconFPR(0.814036329705948361654516690), new FalconFPR(0.580813958095764545075595272), - new FalconFPR(-0.580813958095764545075595272), new FalconFPR(0.814036329705948361654516690), - new FalconFPR(0.164913120489969921418189113), new FalconFPR(0.986308097244598647863297524), - new FalconFPR(-0.986308097244598647863297524), new FalconFPR(0.164913120489969921418189113), - new FalconFPR(0.991709753669099522860049931), new FalconFPR(0.128498110793793172624415589), - new FalconFPR(-0.128498110793793172624415589), new FalconFPR(0.991709753669099522860049931), - new FalconFPR(0.610382806276309452716352152), new FalconFPR(0.792106577300212351782342879), - new FalconFPR(-0.792106577300212351782342879), new FalconFPR(0.610382806276309452716352152), - new FalconFPR(0.867046245515692651480195629), new FalconFPR(0.498227666972781852410983869), - new FalconFPR(-0.498227666972781852410983869), new FalconFPR(0.867046245515692651480195629), - new FalconFPR(0.260794117915275518280186509), new FalconFPR(0.965394441697689374550843858), - new FalconFPR(-0.965394441697689374550843858), new FalconFPR(0.260794117915275518280186509), - new FalconFPR(0.947585591017741134653387321), new FalconFPR(0.319502030816015677901518272), - new FalconFPR(-0.319502030816015677901518272), new FalconFPR(0.947585591017741134653387321), - new FalconFPR(0.444122144570429231642069418), new FalconFPR(0.895966249756185155914560282), - new FalconFPR(-0.895966249756185155914560282), new FalconFPR(0.444122144570429231642069418), - new FalconFPR(0.753186799043612482483430486), new FalconFPR(0.657806693297078656931182264), - new FalconFPR(-0.657806693297078656931182264), new FalconFPR(0.753186799043612482483430486), - new FalconFPR(0.067443919563664057897972422), new FalconFPR(0.997723066644191609848546728), - new FalconFPR(-0.997723066644191609848546728), new FalconFPR(0.067443919563664057897972422), - new FalconFPR(0.996820299291165714972629398), new FalconFPR(0.079682437971430121147120656), - new FalconFPR(-0.079682437971430121147120656), new FalconFPR(0.996820299291165714972629398), - new FalconFPR(0.648514401022112445084560551), new FalconFPR(0.761202385484261814029709836), - new FalconFPR(-0.761202385484261814029709836), new FalconFPR(0.648514401022112445084560551), - new FalconFPR(0.890448723244757889952150560), new FalconFPR(0.455083587126343823535869268), - new FalconFPR(-0.455083587126343823535869268), new FalconFPR(0.890448723244757889952150560), - new FalconFPR(0.307849640041534893682063646), new FalconFPR(0.951435020969008369549175569), - new FalconFPR(-0.951435020969008369549175569), new FalconFPR(0.307849640041534893682063646), - new FalconFPR(0.962121404269041595429604316), new FalconFPR(0.272621355449948984493347477), - new FalconFPR(-0.272621355449948984493347477), new FalconFPR(0.962121404269041595429604316), - new FalconFPR(0.487550160148435954641485027), new FalconFPR(0.873094978418290098636085973), - new FalconFPR(-0.873094978418290098636085973), new FalconFPR(0.487550160148435954641485027), - new FalconFPR(0.784556597155575233023892575), new FalconFPR(0.620057211763289178646268191), - new FalconFPR(-0.620057211763289178646268191), new FalconFPR(0.784556597155575233023892575), - new FalconFPR(0.116318630911904767252544319), new FalconFPR(0.993211949234794533104601012), - new FalconFPR(-0.993211949234794533104601012), new FalconFPR(0.116318630911904767252544319), - new FalconFPR(0.984210092386929073193874387), new FalconFPR(0.177004220412148756196839844), - new FalconFPR(-0.177004220412148756196839844), new FalconFPR(0.984210092386929073193874387), - new FalconFPR(0.570780745886967280232652864), new FalconFPR(0.821102514991104679060430820), - new FalconFPR(-0.821102514991104679060430820), new FalconFPR(0.570780745886967280232652864), - new FalconFPR(0.841554977436898409603499520), new FalconFPR(0.540171472729892881297845480), - new FalconFPR(-0.540171472729892881297845480), new FalconFPR(0.841554977436898409603499520), - new FalconFPR(0.213110319916091373967757518), new FalconFPR(0.977028142657754351485866211), - new FalconFPR(-0.977028142657754351485866211), new FalconFPR(0.213110319916091373967757518), - new FalconFPR(0.930766961078983731944872340), new FalconFPR(0.365612997804773870011745909), - new FalconFPR(-0.365612997804773870011745909), new FalconFPR(0.930766961078983731944872340), - new FalconFPR(0.399624199845646828544117031), new FalconFPR(0.916679059921042663116457013), - new FalconFPR(-0.916679059921042663116457013), new FalconFPR(0.399624199845646828544117031), - new FalconFPR(0.720002507961381629076682999), new FalconFPR(0.693971460889654009003734389), - new FalconFPR(-0.693971460889654009003734389), new FalconFPR(0.720002507961381629076682999), - new FalconFPR(0.018406729905804820927366313), new FalconFPR(0.999830581795823422015722275), - new FalconFPR(-0.999830581795823422015722275), new FalconFPR(0.018406729905804820927366313), - new FalconFPR(0.999830581795823422015722275), new FalconFPR(0.018406729905804820927366313), - new FalconFPR(-0.018406729905804820927366313), new FalconFPR(0.999830581795823422015722275), - new FalconFPR(0.693971460889654009003734389), new FalconFPR(0.720002507961381629076682999), - new FalconFPR(-0.720002507961381629076682999), new FalconFPR(0.693971460889654009003734389), - new FalconFPR(0.916679059921042663116457013), new FalconFPR(0.399624199845646828544117031), - new FalconFPR(-0.399624199845646828544117031), new FalconFPR(0.916679059921042663116457013), - new FalconFPR(0.365612997804773870011745909), new FalconFPR(0.930766961078983731944872340), - new FalconFPR(-0.930766961078983731944872340), new FalconFPR(0.365612997804773870011745909), - new FalconFPR(0.977028142657754351485866211), new FalconFPR(0.213110319916091373967757518), - new FalconFPR(-0.213110319916091373967757518), new FalconFPR(0.977028142657754351485866211), - new FalconFPR(0.540171472729892881297845480), new FalconFPR(0.841554977436898409603499520), - new FalconFPR(-0.841554977436898409603499520), new FalconFPR(0.540171472729892881297845480), - new FalconFPR(0.821102514991104679060430820), new FalconFPR(0.570780745886967280232652864), - new FalconFPR(-0.570780745886967280232652864), new FalconFPR(0.821102514991104679060430820), - new FalconFPR(0.177004220412148756196839844), new FalconFPR(0.984210092386929073193874387), - new FalconFPR(-0.984210092386929073193874387), new FalconFPR(0.177004220412148756196839844), - new FalconFPR(0.993211949234794533104601012), new FalconFPR(0.116318630911904767252544319), - new FalconFPR(-0.116318630911904767252544319), new FalconFPR(0.993211949234794533104601012), - new FalconFPR(0.620057211763289178646268191), new FalconFPR(0.784556597155575233023892575), - new FalconFPR(-0.784556597155575233023892575), new FalconFPR(0.620057211763289178646268191), - new FalconFPR(0.873094978418290098636085973), new FalconFPR(0.487550160148435954641485027), - new FalconFPR(-0.487550160148435954641485027), new FalconFPR(0.873094978418290098636085973), - new FalconFPR(0.272621355449948984493347477), new FalconFPR(0.962121404269041595429604316), - new FalconFPR(-0.962121404269041595429604316), new FalconFPR(0.272621355449948984493347477), - new FalconFPR(0.951435020969008369549175569), new FalconFPR(0.307849640041534893682063646), - new FalconFPR(-0.307849640041534893682063646), new FalconFPR(0.951435020969008369549175569), - new FalconFPR(0.455083587126343823535869268), new FalconFPR(0.890448723244757889952150560), - new FalconFPR(-0.890448723244757889952150560), new FalconFPR(0.455083587126343823535869268), - new FalconFPR(0.761202385484261814029709836), new FalconFPR(0.648514401022112445084560551), - new FalconFPR(-0.648514401022112445084560551), new FalconFPR(0.761202385484261814029709836), - new FalconFPR(0.079682437971430121147120656), new FalconFPR(0.996820299291165714972629398), - new FalconFPR(-0.996820299291165714972629398), new FalconFPR(0.079682437971430121147120656), - new FalconFPR(0.997723066644191609848546728), new FalconFPR(0.067443919563664057897972422), - new FalconFPR(-0.067443919563664057897972422), new FalconFPR(0.997723066644191609848546728), - new FalconFPR(0.657806693297078656931182264), new FalconFPR(0.753186799043612482483430486), - new FalconFPR(-0.753186799043612482483430486), new FalconFPR(0.657806693297078656931182264), - new FalconFPR(0.895966249756185155914560282), new FalconFPR(0.444122144570429231642069418), - new FalconFPR(-0.444122144570429231642069418), new FalconFPR(0.895966249756185155914560282), - new FalconFPR(0.319502030816015677901518272), new FalconFPR(0.947585591017741134653387321), - new FalconFPR(-0.947585591017741134653387321), new FalconFPR(0.319502030816015677901518272), - new FalconFPR(0.965394441697689374550843858), new FalconFPR(0.260794117915275518280186509), - new FalconFPR(-0.260794117915275518280186509), new FalconFPR(0.965394441697689374550843858), - new FalconFPR(0.498227666972781852410983869), new FalconFPR(0.867046245515692651480195629), - new FalconFPR(-0.867046245515692651480195629), new FalconFPR(0.498227666972781852410983869), - new FalconFPR(0.792106577300212351782342879), new FalconFPR(0.610382806276309452716352152), - new FalconFPR(-0.610382806276309452716352152), new FalconFPR(0.792106577300212351782342879), - new FalconFPR(0.128498110793793172624415589), new FalconFPR(0.991709753669099522860049931), - new FalconFPR(-0.991709753669099522860049931), new FalconFPR(0.128498110793793172624415589), - new FalconFPR(0.986308097244598647863297524), new FalconFPR(0.164913120489969921418189113), - new FalconFPR(-0.164913120489969921418189113), new FalconFPR(0.986308097244598647863297524), - new FalconFPR(0.580813958095764545075595272), new FalconFPR(0.814036329705948361654516690), - new FalconFPR(-0.814036329705948361654516690), new FalconFPR(0.580813958095764545075595272), - new FalconFPR(0.848120344803297251279133563), new FalconFPR(0.529803624686294668216054671), - new FalconFPR(-0.529803624686294668216054671), new FalconFPR(0.848120344803297251279133563), - new FalconFPR(0.225083911359792835991642120), new FalconFPR(0.974339382785575860518721668), - new FalconFPR(-0.974339382785575860518721668), new FalconFPR(0.225083911359792835991642120), - new FalconFPR(0.935183509938947577642207480), new FalconFPR(0.354163525420490382357395796), - new FalconFPR(-0.354163525420490382357395796), new FalconFPR(0.935183509938947577642207480), - new FalconFPR(0.410843171057903942183466675), new FalconFPR(0.911706032005429851404397325), - new FalconFPR(-0.911706032005429851404397325), new FalconFPR(0.410843171057903942183466675), - new FalconFPR(0.728464390448225196492035438), new FalconFPR(0.685083667772700381362052545), - new FalconFPR(-0.685083667772700381362052545), new FalconFPR(0.728464390448225196492035438), - new FalconFPR(0.030674803176636625934021028), new FalconFPR(0.999529417501093163079703322), - new FalconFPR(-0.999529417501093163079703322), new FalconFPR(0.030674803176636625934021028), - new FalconFPR(0.999077727752645382888781997), new FalconFPR(0.042938256934940823077124540), - new FalconFPR(-0.042938256934940823077124540), new FalconFPR(0.999077727752645382888781997), - new FalconFPR(0.676092703575315960360419228), new FalconFPR(0.736816568877369875090132520), - new FalconFPR(-0.736816568877369875090132520), new FalconFPR(0.676092703575315960360419228), - new FalconFPR(0.906595704514915365332960588), new FalconFPR(0.422000270799799685941287941), - new FalconFPR(-0.422000270799799685941287941), new FalconFPR(0.906595704514915365332960588), - new FalconFPR(0.342660717311994397592781983), new FalconFPR(0.939459223602189911962669246), - new FalconFPR(-0.939459223602189911962669246), new FalconFPR(0.342660717311994397592781983), - new FalconFPR(0.971503890986251775537099622), new FalconFPR(0.237023605994367206867735915), - new FalconFPR(-0.237023605994367206867735915), new FalconFPR(0.971503890986251775537099622), - new FalconFPR(0.519355990165589587361829932), new FalconFPR(0.854557988365400520767862276), - new FalconFPR(-0.854557988365400520767862276), new FalconFPR(0.519355990165589587361829932), - new FalconFPR(0.806847553543799272206514313), new FalconFPR(0.590759701858874228423887908), - new FalconFPR(-0.590759701858874228423887908), new FalconFPR(0.806847553543799272206514313), - new FalconFPR(0.152797185258443427720336613), new FalconFPR(0.988257567730749491404792538), - new FalconFPR(-0.988257567730749491404792538), new FalconFPR(0.152797185258443427720336613), - new FalconFPR(0.990058210262297105505906464), new FalconFPR(0.140658239332849230714788846), - new FalconFPR(-0.140658239332849230714788846), new FalconFPR(0.990058210262297105505906464), - new FalconFPR(0.600616479383868926653875896), new FalconFPR(0.799537269107905033500246232), - new FalconFPR(-0.799537269107905033500246232), new FalconFPR(0.600616479383868926653875896), - new FalconFPR(0.860866938637767279344583877), new FalconFPR(0.508830142543107036931749324), - new FalconFPR(-0.508830142543107036931749324), new FalconFPR(0.860866938637767279344583877), - new FalconFPR(0.248927605745720168110682816), new FalconFPR(0.968522094274417316221088329), - new FalconFPR(-0.968522094274417316221088329), new FalconFPR(0.248927605745720168110682816), - new FalconFPR(0.943593458161960361495301445), new FalconFPR(0.331106305759876401737190737), - new FalconFPR(-0.331106305759876401737190737), new FalconFPR(0.943593458161960361495301445), - new FalconFPR(0.433093818853151968484222638), new FalconFPR(0.901348847046022014570746093), - new FalconFPR(-0.901348847046022014570746093), new FalconFPR(0.433093818853151968484222638), - new FalconFPR(0.745057785441465962407907310), new FalconFPR(0.666999922303637506650154222), - new FalconFPR(-0.666999922303637506650154222), new FalconFPR(0.745057785441465962407907310), - new FalconFPR(0.055195244349689939809447526), new FalconFPR(0.998475580573294752208559038), - new FalconFPR(-0.998475580573294752208559038), new FalconFPR(0.055195244349689939809447526), - new FalconFPR(0.995767414467659793982495643), new FalconFPR(0.091908956497132728624990979), - new FalconFPR(-0.091908956497132728624990979), new FalconFPR(0.995767414467659793982495643), - new FalconFPR(0.639124444863775743801488193), new FalconFPR(0.769103337645579639346626069), - new FalconFPR(-0.769103337645579639346626069), new FalconFPR(0.639124444863775743801488193), - new FalconFPR(0.884797098430937780104007041), new FalconFPR(0.465976495767966177902756065), - new FalconFPR(-0.465976495767966177902756065), new FalconFPR(0.884797098430937780104007041), - new FalconFPR(0.296150888243623824121786128), new FalconFPR(0.955141168305770721498157712), - new FalconFPR(-0.955141168305770721498157712), new FalconFPR(0.296150888243623824121786128), - new FalconFPR(0.958703474895871555374645792), new FalconFPR(0.284407537211271843618310615), - new FalconFPR(-0.284407537211271843618310615), new FalconFPR(0.958703474895871555374645792), - new FalconFPR(0.476799230063322133342158117), new FalconFPR(0.879012226428633477831323711), - new FalconFPR(-0.879012226428633477831323711), new FalconFPR(0.476799230063322133342158117), - new FalconFPR(0.776888465673232450040827983), new FalconFPR(0.629638238914927025372981341), - new FalconFPR(-0.629638238914927025372981341), new FalconFPR(0.776888465673232450040827983), - new FalconFPR(0.104121633872054579120943880), new FalconFPR(0.994564570734255452119106243), - new FalconFPR(-0.994564570734255452119106243), new FalconFPR(0.104121633872054579120943880), - new FalconFPR(0.981963869109555264072848154), new FalconFPR(0.189068664149806212754997837), - new FalconFPR(-0.189068664149806212754997837), new FalconFPR(0.981963869109555264072848154), - new FalconFPR(0.560661576197336023839710223), new FalconFPR(0.828045045257755752067527592), - new FalconFPR(-0.828045045257755752067527592), new FalconFPR(0.560661576197336023839710223), - new FalconFPR(0.834862874986380056304401383), new FalconFPR(0.550457972936604802977289893), - new FalconFPR(-0.550457972936604802977289893), new FalconFPR(0.834862874986380056304401383), - new FalconFPR(0.201104634842091911558443546), new FalconFPR(0.979569765685440534439326110), - new FalconFPR(-0.979569765685440534439326110), new FalconFPR(0.201104634842091911558443546), - new FalconFPR(0.926210242138311341974793388), new FalconFPR(0.377007410216418256726567823), - new FalconFPR(-0.377007410216418256726567823), new FalconFPR(0.926210242138311341974793388), - new FalconFPR(0.388345046698826291624993541), new FalconFPR(0.921514039342041943465396332), - new FalconFPR(-0.921514039342041943465396332), new FalconFPR(0.388345046698826291624993541), - new FalconFPR(0.711432195745216441522130290), new FalconFPR(0.702754744457225302452914421), - new FalconFPR(-0.702754744457225302452914421), new FalconFPR(0.711432195745216441522130290), - new FalconFPR(0.006135884649154475359640235), new FalconFPR(0.999981175282601142656990438), - new FalconFPR(-0.999981175282601142656990438), new FalconFPR(0.006135884649154475359640235), - new FalconFPR(0.999995293809576171511580126), new FalconFPR(0.003067956762965976270145365), - new FalconFPR(-0.003067956762965976270145365), new FalconFPR(0.999995293809576171511580126), - new FalconFPR(0.704934080375904908852523758), new FalconFPR(0.709272826438865651316533772), - new FalconFPR(-0.709272826438865651316533772), new FalconFPR(0.704934080375904908852523758), - new FalconFPR(0.922701128333878570437264227), new FalconFPR(0.385516053843918864075607949), - new FalconFPR(-0.385516053843918864075607949), new FalconFPR(0.922701128333878570437264227), - new FalconFPR(0.379847208924051170576281147), new FalconFPR(0.925049240782677590302371869), - new FalconFPR(-0.925049240782677590302371869), new FalconFPR(0.379847208924051170576281147), - new FalconFPR(0.980182135968117392690210009), new FalconFPR(0.198098410717953586179324918), - new FalconFPR(-0.198098410717953586179324918), new FalconFPR(0.980182135968117392690210009), - new FalconFPR(0.553016705580027531764226988), new FalconFPR(0.833170164701913186439915922), - new FalconFPR(-0.833170164701913186439915922), new FalconFPR(0.553016705580027531764226988), - new FalconFPR(0.829761233794523042469023765), new FalconFPR(0.558118531220556115693702964), - new FalconFPR(-0.558118531220556115693702964), new FalconFPR(0.829761233794523042469023765), - new FalconFPR(0.192080397049892441679288205), new FalconFPR(0.981379193313754574318224190), - new FalconFPR(-0.981379193313754574318224190), new FalconFPR(0.192080397049892441679288205), - new FalconFPR(0.994879330794805620591166107), new FalconFPR(0.101069862754827824987887585), - new FalconFPR(-0.101069862754827824987887585), new FalconFPR(0.994879330794805620591166107), - new FalconFPR(0.632018735939809021909403706), new FalconFPR(0.774953106594873878359129282), - new FalconFPR(-0.774953106594873878359129282), new FalconFPR(0.632018735939809021909403706), - new FalconFPR(0.880470889052160770806542929), new FalconFPR(0.474100214650550014398580015), - new FalconFPR(-0.474100214650550014398580015), new FalconFPR(0.880470889052160770806542929), - new FalconFPR(0.287347459544729526477331841), new FalconFPR(0.957826413027532890321037029), - new FalconFPR(-0.957826413027532890321037029), new FalconFPR(0.287347459544729526477331841), - new FalconFPR(0.956045251349996443270479823), new FalconFPR(0.293219162694258650606608599), - new FalconFPR(-0.293219162694258650606608599), new FalconFPR(0.956045251349996443270479823), - new FalconFPR(0.468688822035827933697617870), new FalconFPR(0.883363338665731594736308015), - new FalconFPR(-0.883363338665731594736308015), new FalconFPR(0.468688822035827933697617870), - new FalconFPR(0.771060524261813773200605759), new FalconFPR(0.636761861236284230413943435), - new FalconFPR(-0.636761861236284230413943435), new FalconFPR(0.771060524261813773200605759), - new FalconFPR(0.094963495329638998938034312), new FalconFPR(0.995480755491926941769171600), - new FalconFPR(-0.995480755491926941769171600), new FalconFPR(0.094963495329638998938034312), - new FalconFPR(0.998640218180265222418199049), new FalconFPR(0.052131704680283321236358216), - new FalconFPR(-0.052131704680283321236358216), new FalconFPR(0.998640218180265222418199049), - new FalconFPR(0.669282588346636065720696366), new FalconFPR(0.743007952135121693517362293), - new FalconFPR(-0.743007952135121693517362293), new FalconFPR(0.669282588346636065720696366), - new FalconFPR(0.902673318237258806751502391), new FalconFPR(0.430326481340082633908199031), - new FalconFPR(-0.430326481340082633908199031), new FalconFPR(0.902673318237258806751502391), - new FalconFPR(0.333999651442009404650865481), new FalconFPR(0.942573197601446879280758735), - new FalconFPR(-0.942573197601446879280758735), new FalconFPR(0.333999651442009404650865481), - new FalconFPR(0.969281235356548486048290738), new FalconFPR(0.245955050335794611599924709), - new FalconFPR(-0.245955050335794611599924709), new FalconFPR(0.969281235356548486048290738), - new FalconFPR(0.511468850437970399504391001), new FalconFPR(0.859301818357008404783582139), - new FalconFPR(-0.859301818357008404783582139), new FalconFPR(0.511468850437970399504391001), - new FalconFPR(0.801376171723140219430247777), new FalconFPR(0.598160706996342311724958652), - new FalconFPR(-0.598160706996342311724958652), new FalconFPR(0.801376171723140219430247777), - new FalconFPR(0.143695033150294454819773349), new FalconFPR(0.989622017463200834623694454), - new FalconFPR(-0.989622017463200834623694454), new FalconFPR(0.143695033150294454819773349), - new FalconFPR(0.988721691960323767604516485), new FalconFPR(0.149764534677321517229695737), - new FalconFPR(-0.149764534677321517229695737), new FalconFPR(0.988721691960323767604516485), - new FalconFPR(0.593232295039799808047809426), new FalconFPR(0.805031331142963597922659282), - new FalconFPR(-0.805031331142963597922659282), new FalconFPR(0.593232295039799808047809426), - new FalconFPR(0.856147328375194481019630732), new FalconFPR(0.516731799017649881508753876), - new FalconFPR(-0.516731799017649881508753876), new FalconFPR(0.856147328375194481019630732), - new FalconFPR(0.240003022448741486568922365), new FalconFPR(0.970772140728950302138169611), - new FalconFPR(-0.970772140728950302138169611), new FalconFPR(0.240003022448741486568922365), - new FalconFPR(0.940506070593268323787291309), new FalconFPR(0.339776884406826857828825803), - new FalconFPR(-0.339776884406826857828825803), new FalconFPR(0.940506070593268323787291309), - new FalconFPR(0.424779681209108833357226189), new FalconFPR(0.905296759318118774354048329), - new FalconFPR(-0.905296759318118774354048329), new FalconFPR(0.424779681209108833357226189), - new FalconFPR(0.738887324460615147933116508), new FalconFPR(0.673829000378756060917568372), - new FalconFPR(-0.673829000378756060917568372), new FalconFPR(0.738887324460615147933116508), - new FalconFPR(0.046003182130914628814301788), new FalconFPR(0.998941293186856850633930266), - new FalconFPR(-0.998941293186856850633930266), new FalconFPR(0.046003182130914628814301788), - new FalconFPR(0.999618822495178597116830637), new FalconFPR(0.027608145778965741612354872), - new FalconFPR(-0.027608145778965741612354872), new FalconFPR(0.999618822495178597116830637), - new FalconFPR(0.687315340891759108199186948), new FalconFPR(0.726359155084345976817494315), - new FalconFPR(-0.726359155084345976817494315), new FalconFPR(0.687315340891759108199186948), - new FalconFPR(0.912962190428398164628018233), new FalconFPR(0.408044162864978680820747499), - new FalconFPR(-0.408044162864978680820747499), new FalconFPR(0.912962190428398164628018233), - new FalconFPR(0.357030961233430032614954036), new FalconFPR(0.934092550404258914729877883), - new FalconFPR(-0.934092550404258914729877883), new FalconFPR(0.357030961233430032614954036), - new FalconFPR(0.975025345066994146844913468), new FalconFPR(0.222093620973203534094094721), - new FalconFPR(-0.222093620973203534094094721), new FalconFPR(0.975025345066994146844913468), - new FalconFPR(0.532403127877197971442805218), new FalconFPR(0.846490938774052078300544488), - new FalconFPR(-0.846490938774052078300544488), new FalconFPR(0.532403127877197971442805218), - new FalconFPR(0.815814410806733789010772660), new FalconFPR(0.578313796411655563342245019), - new FalconFPR(-0.578313796411655563342245019), new FalconFPR(0.815814410806733789010772660), - new FalconFPR(0.167938294974731178054745536), new FalconFPR(0.985797509167567424700995000), - new FalconFPR(-0.985797509167567424700995000), new FalconFPR(0.167938294974731178054745536), - new FalconFPR(0.992099313142191757112085445), new FalconFPR(0.125454983411546238542336453), - new FalconFPR(-0.125454983411546238542336453), new FalconFPR(0.992099313142191757112085445), - new FalconFPR(0.612810082429409703935211936), new FalconFPR(0.790230221437310055030217152), - new FalconFPR(-0.790230221437310055030217152), new FalconFPR(0.612810082429409703935211936), - new FalconFPR(0.868570705971340895340449876), new FalconFPR(0.495565261825772531150266670), - new FalconFPR(-0.495565261825772531150266670), new FalconFPR(0.868570705971340895340449876), - new FalconFPR(0.263754678974831383611349322), new FalconFPR(0.964589793289812723836432159), - new FalconFPR(-0.964589793289812723836432159), new FalconFPR(0.263754678974831383611349322), - new FalconFPR(0.948561349915730288158494826), new FalconFPR(0.316593375556165867243047035), - new FalconFPR(-0.316593375556165867243047035), new FalconFPR(0.948561349915730288158494826), - new FalconFPR(0.446868840162374195353044389), new FalconFPR(0.894599485631382678433072126), - new FalconFPR(-0.894599485631382678433072126), new FalconFPR(0.446868840162374195353044389), - new FalconFPR(0.755201376896536527598710756), new FalconFPR(0.655492852999615385312679701), - new FalconFPR(-0.655492852999615385312679701), new FalconFPR(0.755201376896536527598710756), - new FalconFPR(0.070504573389613863027351471), new FalconFPR(0.997511456140303459699448390), - new FalconFPR(-0.997511456140303459699448390), new FalconFPR(0.070504573389613863027351471), - new FalconFPR(0.997060070339482978987989949), new FalconFPR(0.076623861392031492278332463), - new FalconFPR(-0.076623861392031492278332463), new FalconFPR(0.997060070339482978987989949), - new FalconFPR(0.650846684996380915068975573), new FalconFPR(0.759209188978388033485525443), - new FalconFPR(-0.759209188978388033485525443), new FalconFPR(0.650846684996380915068975573), - new FalconFPR(0.891840709392342727796478697), new FalconFPR(0.452349587233770874133026703), - new FalconFPR(-0.452349587233770874133026703), new FalconFPR(0.891840709392342727796478697), - new FalconFPR(0.310767152749611495835997250), new FalconFPR(0.950486073949481721759926101), - new FalconFPR(-0.950486073949481721759926101), new FalconFPR(0.310767152749611495835997250), - new FalconFPR(0.962953266873683886347921481), new FalconFPR(0.269668325572915106525464462), - new FalconFPR(-0.269668325572915106525464462), new FalconFPR(0.962953266873683886347921481), - new FalconFPR(0.490226483288291154229598449), new FalconFPR(0.871595086655951034842481435), - new FalconFPR(-0.871595086655951034842481435), new FalconFPR(0.490226483288291154229598449), - new FalconFPR(0.786455213599085757522319464), new FalconFPR(0.617647307937803932403979402), - new FalconFPR(-0.617647307937803932403979402), new FalconFPR(0.786455213599085757522319464), - new FalconFPR(0.119365214810991364593637790), new FalconFPR(0.992850414459865090793563344), - new FalconFPR(-0.992850414459865090793563344), new FalconFPR(0.119365214810991364593637790), - new FalconFPR(0.984748501801904218556553176), new FalconFPR(0.173983873387463827950700807), - new FalconFPR(-0.173983873387463827950700807), new FalconFPR(0.984748501801904218556553176), - new FalconFPR(0.573297166698042212820171239), new FalconFPR(0.819347520076796960824689637), - new FalconFPR(-0.819347520076796960824689637), new FalconFPR(0.573297166698042212820171239), - new FalconFPR(0.843208239641845437161743865), new FalconFPR(0.537587076295645482502214932), - new FalconFPR(-0.537587076295645482502214932), new FalconFPR(0.843208239641845437161743865), - new FalconFPR(0.216106797076219509948385131), new FalconFPR(0.976369731330021149312732194), - new FalconFPR(-0.976369731330021149312732194), new FalconFPR(0.216106797076219509948385131), - new FalconFPR(0.931884265581668106718557199), new FalconFPR(0.362755724367397216204854462), - new FalconFPR(-0.362755724367397216204854462), new FalconFPR(0.931884265581668106718557199), - new FalconFPR(0.402434650859418441082533934), new FalconFPR(0.915448716088267819566431292), - new FalconFPR(-0.915448716088267819566431292), new FalconFPR(0.402434650859418441082533934), - new FalconFPR(0.722128193929215321243607198), new FalconFPR(0.691759258364157774906734132), - new FalconFPR(-0.691759258364157774906734132), new FalconFPR(0.722128193929215321243607198), - new FalconFPR(0.021474080275469507418374898), new FalconFPR(0.999769405351215321657617036), - new FalconFPR(-0.999769405351215321657617036), new FalconFPR(0.021474080275469507418374898), - new FalconFPR(0.999882347454212525633049627), new FalconFPR(0.015339206284988101044151868), - new FalconFPR(-0.015339206284988101044151868), new FalconFPR(0.999882347454212525633049627), - new FalconFPR(0.696177131491462944788582591), new FalconFPR(0.717870045055731736211325329), - new FalconFPR(-0.717870045055731736211325329), new FalconFPR(0.696177131491462944788582591), - new FalconFPR(0.917900775621390457642276297), new FalconFPR(0.396809987416710328595290911), - new FalconFPR(-0.396809987416710328595290911), new FalconFPR(0.917900775621390457642276297), - new FalconFPR(0.368466829953372331712746222), new FalconFPR(0.929640895843181265457918066), - new FalconFPR(-0.929640895843181265457918066), new FalconFPR(0.368466829953372331712746222), - new FalconFPR(0.977677357824509979943404762), new FalconFPR(0.210111836880469621717489972), - new FalconFPR(-0.210111836880469621717489972), new FalconFPR(0.977677357824509979943404762), - new FalconFPR(0.542750784864515906586768661), new FalconFPR(0.839893794195999504583383987), - new FalconFPR(-0.839893794195999504583383987), new FalconFPR(0.542750784864515906586768661), - new FalconFPR(0.822849781375826332046780034), new FalconFPR(0.568258952670131549790548489), - new FalconFPR(-0.568258952670131549790548489), new FalconFPR(0.822849781375826332046780034), - new FalconFPR(0.180022901405699522679906590), new FalconFPR(0.983662419211730274396237776), - new FalconFPR(-0.983662419211730274396237776), new FalconFPR(0.180022901405699522679906590), - new FalconFPR(0.993564135520595333782021697), new FalconFPR(0.113270952177564349018228733), - new FalconFPR(-0.113270952177564349018228733), new FalconFPR(0.993564135520595333782021697), - new FalconFPR(0.622461279374149972519166721), new FalconFPR(0.782650596166575738458949301), - new FalconFPR(-0.782650596166575738458949301), new FalconFPR(0.622461279374149972519166721), - new FalconFPR(0.874586652278176112634431897), new FalconFPR(0.484869248000791101822951699), - new FalconFPR(-0.484869248000791101822951699), new FalconFPR(0.874586652278176112634431897), - new FalconFPR(0.275571819310958163076425168), new FalconFPR(0.961280485811320641748659653), - new FalconFPR(-0.961280485811320641748659653), new FalconFPR(0.275571819310958163076425168), - new FalconFPR(0.952375012719765858529893608), new FalconFPR(0.304929229735402406490728633), - new FalconFPR(-0.304929229735402406490728633), new FalconFPR(0.952375012719765858529893608), - new FalconFPR(0.457813303598877221904961155), new FalconFPR(0.889048355854664562540777729), - new FalconFPR(-0.889048355854664562540777729), new FalconFPR(0.457813303598877221904961155), - new FalconFPR(0.763188417263381271704838297), new FalconFPR(0.646176012983316364832802220), - new FalconFPR(-0.646176012983316364832802220), new FalconFPR(0.763188417263381271704838297), - new FalconFPR(0.082740264549375693111987083), new FalconFPR(0.996571145790554847093566910), - new FalconFPR(-0.996571145790554847093566910), new FalconFPR(0.082740264549375693111987083), - new FalconFPR(0.997925286198596012623025462), new FalconFPR(0.064382630929857460819324537), - new FalconFPR(-0.064382630929857460819324537), new FalconFPR(0.997925286198596012623025462), - new FalconFPR(0.660114342067420478559490747), new FalconFPR(0.751165131909686411205819422), - new FalconFPR(-0.751165131909686411205819422), new FalconFPR(0.660114342067420478559490747), - new FalconFPR(0.897324580705418281231391836), new FalconFPR(0.441371268731716692879988968), - new FalconFPR(-0.441371268731716692879988968), new FalconFPR(0.897324580705418281231391836), - new FalconFPR(0.322407678801069848384807478), new FalconFPR(0.946600913083283570044599823), - new FalconFPR(-0.946600913083283570044599823), new FalconFPR(0.322407678801069848384807478), - new FalconFPR(0.966190003445412555433832961), new FalconFPR(0.257831102162159005614471295), - new FalconFPR(-0.257831102162159005614471295), new FalconFPR(0.966190003445412555433832961), - new FalconFPR(0.500885382611240786241285004), new FalconFPR(0.865513624090569082825488358), - new FalconFPR(-0.865513624090569082825488358), new FalconFPR(0.500885382611240786241285004), - new FalconFPR(0.793975477554337164895083757), new FalconFPR(0.607949784967773667243642671), - new FalconFPR(-0.607949784967773667243642671), new FalconFPR(0.793975477554337164895083757), - new FalconFPR(0.131540028702883111103387493), new FalconFPR(0.991310859846115418957349799), - new FalconFPR(-0.991310859846115418957349799), new FalconFPR(0.131540028702883111103387493), - new FalconFPR(0.986809401814185476970235952), new FalconFPR(0.161886393780111837641387995), - new FalconFPR(-0.161886393780111837641387995), new FalconFPR(0.986809401814185476970235952), - new FalconFPR(0.583308652937698294392830961), new FalconFPR(0.812250586585203913049744181), - new FalconFPR(-0.812250586585203913049744181), new FalconFPR(0.583308652937698294392830961), - new FalconFPR(0.849741768000852489471268395), new FalconFPR(0.527199134781901348464274575), - new FalconFPR(-0.527199134781901348464274575), new FalconFPR(0.849741768000852489471268395), - new FalconFPR(0.228072083170885739254457379), new FalconFPR(0.973644249650811925318383912), - new FalconFPR(-0.973644249650811925318383912), new FalconFPR(0.228072083170885739254457379), - new FalconFPR(0.936265667170278246576310996), new FalconFPR(0.351292756085567125601307623), - new FalconFPR(-0.351292756085567125601307623), new FalconFPR(0.936265667170278246576310996), - new FalconFPR(0.413638312238434547471944324), new FalconFPR(0.910441292258067196934095369), - new FalconFPR(-0.910441292258067196934095369), new FalconFPR(0.413638312238434547471944324), - new FalconFPR(0.730562769227827561177758850), new FalconFPR(0.682845546385248068164596123), - new FalconFPR(-0.682845546385248068164596123), new FalconFPR(0.730562769227827561177758850), - new FalconFPR(0.033741171851377584833716112), new FalconFPR(0.999430604555461772019008327), - new FalconFPR(-0.999430604555461772019008327), new FalconFPR(0.033741171851377584833716112), - new FalconFPR(0.999204758618363895492950001), new FalconFPR(0.039872927587739811128578738), - new FalconFPR(-0.039872927587739811128578738), new FalconFPR(0.999204758618363895492950001), - new FalconFPR(0.678350043129861486873655042), new FalconFPR(0.734738878095963464563223604), - new FalconFPR(-0.734738878095963464563223604), new FalconFPR(0.678350043129861486873655042), - new FalconFPR(0.907886116487666212038681480), new FalconFPR(0.419216888363223956433010020), - new FalconFPR(-0.419216888363223956433010020), new FalconFPR(0.907886116487666212038681480), - new FalconFPR(0.345541324963989065539191723), new FalconFPR(0.938403534063108112192420774), - new FalconFPR(-0.938403534063108112192420774), new FalconFPR(0.345541324963989065539191723), - new FalconFPR(0.972226497078936305708321144), new FalconFPR(0.234041958583543423191242045), - new FalconFPR(-0.234041958583543423191242045), new FalconFPR(0.972226497078936305708321144), - new FalconFPR(0.521975292937154342694258318), new FalconFPR(0.852960604930363657746588082), - new FalconFPR(-0.852960604930363657746588082), new FalconFPR(0.521975292937154342694258318), - new FalconFPR(0.808656181588174991946968128), new FalconFPR(0.588281548222645304786439813), - new FalconFPR(-0.588281548222645304786439813), new FalconFPR(0.808656181588174991946968128), - new FalconFPR(0.155828397654265235743101486), new FalconFPR(0.987784141644572154230969032), - new FalconFPR(-0.987784141644572154230969032), new FalconFPR(0.155828397654265235743101486), - new FalconFPR(0.990485084256457037998682243), new FalconFPR(0.137620121586486044948441663), - new FalconFPR(-0.137620121586486044948441663), new FalconFPR(0.990485084256457037998682243), - new FalconFPR(0.603066598540348201693430617), new FalconFPR(0.797690840943391108362662755), - new FalconFPR(-0.797690840943391108362662755), new FalconFPR(0.603066598540348201693430617), - new FalconFPR(0.862423956111040538690933878), new FalconFPR(0.506186645345155291048942344), - new FalconFPR(-0.506186645345155291048942344), new FalconFPR(0.862423956111040538690933878), - new FalconFPR(0.251897818154216950498106628), new FalconFPR(0.967753837093475465243391912), - new FalconFPR(-0.967753837093475465243391912), new FalconFPR(0.251897818154216950498106628), - new FalconFPR(0.944604837261480265659265493), new FalconFPR(0.328209843579092526107916817), - new FalconFPR(-0.328209843579092526107916817), new FalconFPR(0.944604837261480265659265493), - new FalconFPR(0.435857079922255491032544080), new FalconFPR(0.900015892016160228714535267), - new FalconFPR(-0.900015892016160228714535267), new FalconFPR(0.435857079922255491032544080), - new FalconFPR(0.747100605980180144323078847), new FalconFPR(0.664710978203344868130324985), - new FalconFPR(-0.664710978203344868130324985), new FalconFPR(0.747100605980180144323078847), - new FalconFPR(0.058258264500435759613979782), new FalconFPR(0.998301544933892840738782163), - new FalconFPR(-0.998301544933892840738782163), new FalconFPR(0.058258264500435759613979782), - new FalconFPR(0.996044700901251989887944810), new FalconFPR(0.088853552582524596561586535), - new FalconFPR(-0.088853552582524596561586535), new FalconFPR(0.996044700901251989887944810), - new FalconFPR(0.641481012808583151988739898), new FalconFPR(0.767138911935820381181694573), - new FalconFPR(-0.767138911935820381181694573), new FalconFPR(0.641481012808583151988739898), - new FalconFPR(0.886222530148880631647990821), new FalconFPR(0.463259783551860197390719637), - new FalconFPR(-0.463259783551860197390719637), new FalconFPR(0.886222530148880631647990821), - new FalconFPR(0.299079826308040476750336973), new FalconFPR(0.954228095109105629780430732), - new FalconFPR(-0.954228095109105629780430732), new FalconFPR(0.299079826308040476750336973), - new FalconFPR(0.959571513081984528335528181), new FalconFPR(0.281464937925757984095231007), - new FalconFPR(-0.281464937925757984095231007), new FalconFPR(0.959571513081984528335528181), - new FalconFPR(0.479493757660153026679839798), new FalconFPR(0.877545290207261291668470750), - new FalconFPR(-0.877545290207261291668470750), new FalconFPR(0.479493757660153026679839798), - new FalconFPR(0.778816512381475953374724325), new FalconFPR(0.627251815495144113509622565), - new FalconFPR(-0.627251815495144113509622565), new FalconFPR(0.778816512381475953374724325), - new FalconFPR(0.107172424956808849175529148), new FalconFPR(0.994240449453187946358413442), - new FalconFPR(-0.994240449453187946358413442), new FalconFPR(0.107172424956808849175529148), - new FalconFPR(0.982539302287441255907040396), new FalconFPR(0.186055151663446648105438304), - new FalconFPR(-0.186055151663446648105438304), new FalconFPR(0.982539302287441255907040396), - new FalconFPR(0.563199344013834115007363772), new FalconFPR(0.826321062845663480311195452), - new FalconFPR(-0.826321062845663480311195452), new FalconFPR(0.563199344013834115007363772), - new FalconFPR(0.836547727223511984524285790), new FalconFPR(0.547894059173100165608820571), - new FalconFPR(-0.547894059173100165608820571), new FalconFPR(0.836547727223511984524285790), - new FalconFPR(0.204108966092816874181696950), new FalconFPR(0.978948175319062194715480124), - new FalconFPR(-0.978948175319062194715480124), new FalconFPR(0.204108966092816874181696950), - new FalconFPR(0.927362525650401087274536959), new FalconFPR(0.374164062971457997104393020), - new FalconFPR(-0.374164062971457997104393020), new FalconFPR(0.927362525650401087274536959), - new FalconFPR(0.391170384302253888687512949), new FalconFPR(0.920318276709110566440076541), - new FalconFPR(-0.920318276709110566440076541), new FalconFPR(0.391170384302253888687512949), - new FalconFPR(0.713584868780793592903125099), new FalconFPR(0.700568793943248366792866380), - new FalconFPR(-0.700568793943248366792866380), new FalconFPR(0.713584868780793592903125099), - new FalconFPR(0.009203754782059819315102378), new FalconFPR(0.999957644551963866333120920), - new FalconFPR(-0.999957644551963866333120920), new FalconFPR(0.009203754782059819315102378), - new FalconFPR(0.999957644551963866333120920), new FalconFPR(0.009203754782059819315102378), - new FalconFPR(-0.009203754782059819315102378), new FalconFPR(0.999957644551963866333120920), - new FalconFPR(0.700568793943248366792866380), new FalconFPR(0.713584868780793592903125099), - new FalconFPR(-0.713584868780793592903125099), new FalconFPR(0.700568793943248366792866380), - new FalconFPR(0.920318276709110566440076541), new FalconFPR(0.391170384302253888687512949), - new FalconFPR(-0.391170384302253888687512949), new FalconFPR(0.920318276709110566440076541), - new FalconFPR(0.374164062971457997104393020), new FalconFPR(0.927362525650401087274536959), - new FalconFPR(-0.927362525650401087274536959), new FalconFPR(0.374164062971457997104393020), - new FalconFPR(0.978948175319062194715480124), new FalconFPR(0.204108966092816874181696950), - new FalconFPR(-0.204108966092816874181696950), new FalconFPR(0.978948175319062194715480124), - new FalconFPR(0.547894059173100165608820571), new FalconFPR(0.836547727223511984524285790), - new FalconFPR(-0.836547727223511984524285790), new FalconFPR(0.547894059173100165608820571), - new FalconFPR(0.826321062845663480311195452), new FalconFPR(0.563199344013834115007363772), - new FalconFPR(-0.563199344013834115007363772), new FalconFPR(0.826321062845663480311195452), - new FalconFPR(0.186055151663446648105438304), new FalconFPR(0.982539302287441255907040396), - new FalconFPR(-0.982539302287441255907040396), new FalconFPR(0.186055151663446648105438304), - new FalconFPR(0.994240449453187946358413442), new FalconFPR(0.107172424956808849175529148), - new FalconFPR(-0.107172424956808849175529148), new FalconFPR(0.994240449453187946358413442), - new FalconFPR(0.627251815495144113509622565), new FalconFPR(0.778816512381475953374724325), - new FalconFPR(-0.778816512381475953374724325), new FalconFPR(0.627251815495144113509622565), - new FalconFPR(0.877545290207261291668470750), new FalconFPR(0.479493757660153026679839798), - new FalconFPR(-0.479493757660153026679839798), new FalconFPR(0.877545290207261291668470750), - new FalconFPR(0.281464937925757984095231007), new FalconFPR(0.959571513081984528335528181), - new FalconFPR(-0.959571513081984528335528181), new FalconFPR(0.281464937925757984095231007), - new FalconFPR(0.954228095109105629780430732), new FalconFPR(0.299079826308040476750336973), - new FalconFPR(-0.299079826308040476750336973), new FalconFPR(0.954228095109105629780430732), - new FalconFPR(0.463259783551860197390719637), new FalconFPR(0.886222530148880631647990821), - new FalconFPR(-0.886222530148880631647990821), new FalconFPR(0.463259783551860197390719637), - new FalconFPR(0.767138911935820381181694573), new FalconFPR(0.641481012808583151988739898), - new FalconFPR(-0.641481012808583151988739898), new FalconFPR(0.767138911935820381181694573), - new FalconFPR(0.088853552582524596561586535), new FalconFPR(0.996044700901251989887944810), - new FalconFPR(-0.996044700901251989887944810), new FalconFPR(0.088853552582524596561586535), - new FalconFPR(0.998301544933892840738782163), new FalconFPR(0.058258264500435759613979782), - new FalconFPR(-0.058258264500435759613979782), new FalconFPR(0.998301544933892840738782163), - new FalconFPR(0.664710978203344868130324985), new FalconFPR(0.747100605980180144323078847), - new FalconFPR(-0.747100605980180144323078847), new FalconFPR(0.664710978203344868130324985), - new FalconFPR(0.900015892016160228714535267), new FalconFPR(0.435857079922255491032544080), - new FalconFPR(-0.435857079922255491032544080), new FalconFPR(0.900015892016160228714535267), - new FalconFPR(0.328209843579092526107916817), new FalconFPR(0.944604837261480265659265493), - new FalconFPR(-0.944604837261480265659265493), new FalconFPR(0.328209843579092526107916817), - new FalconFPR(0.967753837093475465243391912), new FalconFPR(0.251897818154216950498106628), - new FalconFPR(-0.251897818154216950498106628), new FalconFPR(0.967753837093475465243391912), - new FalconFPR(0.506186645345155291048942344), new FalconFPR(0.862423956111040538690933878), - new FalconFPR(-0.862423956111040538690933878), new FalconFPR(0.506186645345155291048942344), - new FalconFPR(0.797690840943391108362662755), new FalconFPR(0.603066598540348201693430617), - new FalconFPR(-0.603066598540348201693430617), new FalconFPR(0.797690840943391108362662755), - new FalconFPR(0.137620121586486044948441663), new FalconFPR(0.990485084256457037998682243), - new FalconFPR(-0.990485084256457037998682243), new FalconFPR(0.137620121586486044948441663), - new FalconFPR(0.987784141644572154230969032), new FalconFPR(0.155828397654265235743101486), - new FalconFPR(-0.155828397654265235743101486), new FalconFPR(0.987784141644572154230969032), - new FalconFPR(0.588281548222645304786439813), new FalconFPR(0.808656181588174991946968128), - new FalconFPR(-0.808656181588174991946968128), new FalconFPR(0.588281548222645304786439813), - new FalconFPR(0.852960604930363657746588082), new FalconFPR(0.521975292937154342694258318), - new FalconFPR(-0.521975292937154342694258318), new FalconFPR(0.852960604930363657746588082), - new FalconFPR(0.234041958583543423191242045), new FalconFPR(0.972226497078936305708321144), - new FalconFPR(-0.972226497078936305708321144), new FalconFPR(0.234041958583543423191242045), - new FalconFPR(0.938403534063108112192420774), new FalconFPR(0.345541324963989065539191723), - new FalconFPR(-0.345541324963989065539191723), new FalconFPR(0.938403534063108112192420774), - new FalconFPR(0.419216888363223956433010020), new FalconFPR(0.907886116487666212038681480), - new FalconFPR(-0.907886116487666212038681480), new FalconFPR(0.419216888363223956433010020), - new FalconFPR(0.734738878095963464563223604), new FalconFPR(0.678350043129861486873655042), - new FalconFPR(-0.678350043129861486873655042), new FalconFPR(0.734738878095963464563223604), - new FalconFPR(0.039872927587739811128578738), new FalconFPR(0.999204758618363895492950001), - new FalconFPR(-0.999204758618363895492950001), new FalconFPR(0.039872927587739811128578738), - new FalconFPR(0.999430604555461772019008327), new FalconFPR(0.033741171851377584833716112), - new FalconFPR(-0.033741171851377584833716112), new FalconFPR(0.999430604555461772019008327), - new FalconFPR(0.682845546385248068164596123), new FalconFPR(0.730562769227827561177758850), - new FalconFPR(-0.730562769227827561177758850), new FalconFPR(0.682845546385248068164596123), - new FalconFPR(0.910441292258067196934095369), new FalconFPR(0.413638312238434547471944324), - new FalconFPR(-0.413638312238434547471944324), new FalconFPR(0.910441292258067196934095369), - new FalconFPR(0.351292756085567125601307623), new FalconFPR(0.936265667170278246576310996), - new FalconFPR(-0.936265667170278246576310996), new FalconFPR(0.351292756085567125601307623), - new FalconFPR(0.973644249650811925318383912), new FalconFPR(0.228072083170885739254457379), - new FalconFPR(-0.228072083170885739254457379), new FalconFPR(0.973644249650811925318383912), - new FalconFPR(0.527199134781901348464274575), new FalconFPR(0.849741768000852489471268395), - new FalconFPR(-0.849741768000852489471268395), new FalconFPR(0.527199134781901348464274575), - new FalconFPR(0.812250586585203913049744181), new FalconFPR(0.583308652937698294392830961), - new FalconFPR(-0.583308652937698294392830961), new FalconFPR(0.812250586585203913049744181), - new FalconFPR(0.161886393780111837641387995), new FalconFPR(0.986809401814185476970235952), - new FalconFPR(-0.986809401814185476970235952), new FalconFPR(0.161886393780111837641387995), - new FalconFPR(0.991310859846115418957349799), new FalconFPR(0.131540028702883111103387493), - new FalconFPR(-0.131540028702883111103387493), new FalconFPR(0.991310859846115418957349799), - new FalconFPR(0.607949784967773667243642671), new FalconFPR(0.793975477554337164895083757), - new FalconFPR(-0.793975477554337164895083757), new FalconFPR(0.607949784967773667243642671), - new FalconFPR(0.865513624090569082825488358), new FalconFPR(0.500885382611240786241285004), - new FalconFPR(-0.500885382611240786241285004), new FalconFPR(0.865513624090569082825488358), - new FalconFPR(0.257831102162159005614471295), new FalconFPR(0.966190003445412555433832961), - new FalconFPR(-0.966190003445412555433832961), new FalconFPR(0.257831102162159005614471295), - new FalconFPR(0.946600913083283570044599823), new FalconFPR(0.322407678801069848384807478), - new FalconFPR(-0.322407678801069848384807478), new FalconFPR(0.946600913083283570044599823), - new FalconFPR(0.441371268731716692879988968), new FalconFPR(0.897324580705418281231391836), - new FalconFPR(-0.897324580705418281231391836), new FalconFPR(0.441371268731716692879988968), - new FalconFPR(0.751165131909686411205819422), new FalconFPR(0.660114342067420478559490747), - new FalconFPR(-0.660114342067420478559490747), new FalconFPR(0.751165131909686411205819422), - new FalconFPR(0.064382630929857460819324537), new FalconFPR(0.997925286198596012623025462), - new FalconFPR(-0.997925286198596012623025462), new FalconFPR(0.064382630929857460819324537), - new FalconFPR(0.996571145790554847093566910), new FalconFPR(0.082740264549375693111987083), - new FalconFPR(-0.082740264549375693111987083), new FalconFPR(0.996571145790554847093566910), - new FalconFPR(0.646176012983316364832802220), new FalconFPR(0.763188417263381271704838297), - new FalconFPR(-0.763188417263381271704838297), new FalconFPR(0.646176012983316364832802220), - new FalconFPR(0.889048355854664562540777729), new FalconFPR(0.457813303598877221904961155), - new FalconFPR(-0.457813303598877221904961155), new FalconFPR(0.889048355854664562540777729), - new FalconFPR(0.304929229735402406490728633), new FalconFPR(0.952375012719765858529893608), - new FalconFPR(-0.952375012719765858529893608), new FalconFPR(0.304929229735402406490728633), - new FalconFPR(0.961280485811320641748659653), new FalconFPR(0.275571819310958163076425168), - new FalconFPR(-0.275571819310958163076425168), new FalconFPR(0.961280485811320641748659653), - new FalconFPR(0.484869248000791101822951699), new FalconFPR(0.874586652278176112634431897), - new FalconFPR(-0.874586652278176112634431897), new FalconFPR(0.484869248000791101822951699), - new FalconFPR(0.782650596166575738458949301), new FalconFPR(0.622461279374149972519166721), - new FalconFPR(-0.622461279374149972519166721), new FalconFPR(0.782650596166575738458949301), - new FalconFPR(0.113270952177564349018228733), new FalconFPR(0.993564135520595333782021697), - new FalconFPR(-0.993564135520595333782021697), new FalconFPR(0.113270952177564349018228733), - new FalconFPR(0.983662419211730274396237776), new FalconFPR(0.180022901405699522679906590), - new FalconFPR(-0.180022901405699522679906590), new FalconFPR(0.983662419211730274396237776), - new FalconFPR(0.568258952670131549790548489), new FalconFPR(0.822849781375826332046780034), - new FalconFPR(-0.822849781375826332046780034), new FalconFPR(0.568258952670131549790548489), - new FalconFPR(0.839893794195999504583383987), new FalconFPR(0.542750784864515906586768661), - new FalconFPR(-0.542750784864515906586768661), new FalconFPR(0.839893794195999504583383987), - new FalconFPR(0.210111836880469621717489972), new FalconFPR(0.977677357824509979943404762), - new FalconFPR(-0.977677357824509979943404762), new FalconFPR(0.210111836880469621717489972), - new FalconFPR(0.929640895843181265457918066), new FalconFPR(0.368466829953372331712746222), - new FalconFPR(-0.368466829953372331712746222), new FalconFPR(0.929640895843181265457918066), - new FalconFPR(0.396809987416710328595290911), new FalconFPR(0.917900775621390457642276297), - new FalconFPR(-0.917900775621390457642276297), new FalconFPR(0.396809987416710328595290911), - new FalconFPR(0.717870045055731736211325329), new FalconFPR(0.696177131491462944788582591), - new FalconFPR(-0.696177131491462944788582591), new FalconFPR(0.717870045055731736211325329), - new FalconFPR(0.015339206284988101044151868), new FalconFPR(0.999882347454212525633049627), - new FalconFPR(-0.999882347454212525633049627), new FalconFPR(0.015339206284988101044151868), - new FalconFPR(0.999769405351215321657617036), new FalconFPR(0.021474080275469507418374898), - new FalconFPR(-0.021474080275469507418374898), new FalconFPR(0.999769405351215321657617036), - new FalconFPR(0.691759258364157774906734132), new FalconFPR(0.722128193929215321243607198), - new FalconFPR(-0.722128193929215321243607198), new FalconFPR(0.691759258364157774906734132), - new FalconFPR(0.915448716088267819566431292), new FalconFPR(0.402434650859418441082533934), - new FalconFPR(-0.402434650859418441082533934), new FalconFPR(0.915448716088267819566431292), - new FalconFPR(0.362755724367397216204854462), new FalconFPR(0.931884265581668106718557199), - new FalconFPR(-0.931884265581668106718557199), new FalconFPR(0.362755724367397216204854462), - new FalconFPR(0.976369731330021149312732194), new FalconFPR(0.216106797076219509948385131), - new FalconFPR(-0.216106797076219509948385131), new FalconFPR(0.976369731330021149312732194), - new FalconFPR(0.537587076295645482502214932), new FalconFPR(0.843208239641845437161743865), - new FalconFPR(-0.843208239641845437161743865), new FalconFPR(0.537587076295645482502214932), - new FalconFPR(0.819347520076796960824689637), new FalconFPR(0.573297166698042212820171239), - new FalconFPR(-0.573297166698042212820171239), new FalconFPR(0.819347520076796960824689637), - new FalconFPR(0.173983873387463827950700807), new FalconFPR(0.984748501801904218556553176), - new FalconFPR(-0.984748501801904218556553176), new FalconFPR(0.173983873387463827950700807), - new FalconFPR(0.992850414459865090793563344), new FalconFPR(0.119365214810991364593637790), - new FalconFPR(-0.119365214810991364593637790), new FalconFPR(0.992850414459865090793563344), - new FalconFPR(0.617647307937803932403979402), new FalconFPR(0.786455213599085757522319464), - new FalconFPR(-0.786455213599085757522319464), new FalconFPR(0.617647307937803932403979402), - new FalconFPR(0.871595086655951034842481435), new FalconFPR(0.490226483288291154229598449), - new FalconFPR(-0.490226483288291154229598449), new FalconFPR(0.871595086655951034842481435), - new FalconFPR(0.269668325572915106525464462), new FalconFPR(0.962953266873683886347921481), - new FalconFPR(-0.962953266873683886347921481), new FalconFPR(0.269668325572915106525464462), - new FalconFPR(0.950486073949481721759926101), new FalconFPR(0.310767152749611495835997250), - new FalconFPR(-0.310767152749611495835997250), new FalconFPR(0.950486073949481721759926101), - new FalconFPR(0.452349587233770874133026703), new FalconFPR(0.891840709392342727796478697), - new FalconFPR(-0.891840709392342727796478697), new FalconFPR(0.452349587233770874133026703), - new FalconFPR(0.759209188978388033485525443), new FalconFPR(0.650846684996380915068975573), - new FalconFPR(-0.650846684996380915068975573), new FalconFPR(0.759209188978388033485525443), - new FalconFPR(0.076623861392031492278332463), new FalconFPR(0.997060070339482978987989949), - new FalconFPR(-0.997060070339482978987989949), new FalconFPR(0.076623861392031492278332463), - new FalconFPR(0.997511456140303459699448390), new FalconFPR(0.070504573389613863027351471), - new FalconFPR(-0.070504573389613863027351471), new FalconFPR(0.997511456140303459699448390), - new FalconFPR(0.655492852999615385312679701), new FalconFPR(0.755201376896536527598710756), - new FalconFPR(-0.755201376896536527598710756), new FalconFPR(0.655492852999615385312679701), - new FalconFPR(0.894599485631382678433072126), new FalconFPR(0.446868840162374195353044389), - new FalconFPR(-0.446868840162374195353044389), new FalconFPR(0.894599485631382678433072126), - new FalconFPR(0.316593375556165867243047035), new FalconFPR(0.948561349915730288158494826), - new FalconFPR(-0.948561349915730288158494826), new FalconFPR(0.316593375556165867243047035), - new FalconFPR(0.964589793289812723836432159), new FalconFPR(0.263754678974831383611349322), - new FalconFPR(-0.263754678974831383611349322), new FalconFPR(0.964589793289812723836432159), - new FalconFPR(0.495565261825772531150266670), new FalconFPR(0.868570705971340895340449876), - new FalconFPR(-0.868570705971340895340449876), new FalconFPR(0.495565261825772531150266670), - new FalconFPR(0.790230221437310055030217152), new FalconFPR(0.612810082429409703935211936), - new FalconFPR(-0.612810082429409703935211936), new FalconFPR(0.790230221437310055030217152), - new FalconFPR(0.125454983411546238542336453), new FalconFPR(0.992099313142191757112085445), - new FalconFPR(-0.992099313142191757112085445), new FalconFPR(0.125454983411546238542336453), - new FalconFPR(0.985797509167567424700995000), new FalconFPR(0.167938294974731178054745536), - new FalconFPR(-0.167938294974731178054745536), new FalconFPR(0.985797509167567424700995000), - new FalconFPR(0.578313796411655563342245019), new FalconFPR(0.815814410806733789010772660), - new FalconFPR(-0.815814410806733789010772660), new FalconFPR(0.578313796411655563342245019), - new FalconFPR(0.846490938774052078300544488), new FalconFPR(0.532403127877197971442805218), - new FalconFPR(-0.532403127877197971442805218), new FalconFPR(0.846490938774052078300544488), - new FalconFPR(0.222093620973203534094094721), new FalconFPR(0.975025345066994146844913468), - new FalconFPR(-0.975025345066994146844913468), new FalconFPR(0.222093620973203534094094721), - new FalconFPR(0.934092550404258914729877883), new FalconFPR(0.357030961233430032614954036), - new FalconFPR(-0.357030961233430032614954036), new FalconFPR(0.934092550404258914729877883), - new FalconFPR(0.408044162864978680820747499), new FalconFPR(0.912962190428398164628018233), - new FalconFPR(-0.912962190428398164628018233), new FalconFPR(0.408044162864978680820747499), - new FalconFPR(0.726359155084345976817494315), new FalconFPR(0.687315340891759108199186948), - new FalconFPR(-0.687315340891759108199186948), new FalconFPR(0.726359155084345976817494315), - new FalconFPR(0.027608145778965741612354872), new FalconFPR(0.999618822495178597116830637), - new FalconFPR(-0.999618822495178597116830637), new FalconFPR(0.027608145778965741612354872), - new FalconFPR(0.998941293186856850633930266), new FalconFPR(0.046003182130914628814301788), - new FalconFPR(-0.046003182130914628814301788), new FalconFPR(0.998941293186856850633930266), - new FalconFPR(0.673829000378756060917568372), new FalconFPR(0.738887324460615147933116508), - new FalconFPR(-0.738887324460615147933116508), new FalconFPR(0.673829000378756060917568372), - new FalconFPR(0.905296759318118774354048329), new FalconFPR(0.424779681209108833357226189), - new FalconFPR(-0.424779681209108833357226189), new FalconFPR(0.905296759318118774354048329), - new FalconFPR(0.339776884406826857828825803), new FalconFPR(0.940506070593268323787291309), - new FalconFPR(-0.940506070593268323787291309), new FalconFPR(0.339776884406826857828825803), - new FalconFPR(0.970772140728950302138169611), new FalconFPR(0.240003022448741486568922365), - new FalconFPR(-0.240003022448741486568922365), new FalconFPR(0.970772140728950302138169611), - new FalconFPR(0.516731799017649881508753876), new FalconFPR(0.856147328375194481019630732), - new FalconFPR(-0.856147328375194481019630732), new FalconFPR(0.516731799017649881508753876), - new FalconFPR(0.805031331142963597922659282), new FalconFPR(0.593232295039799808047809426), - new FalconFPR(-0.593232295039799808047809426), new FalconFPR(0.805031331142963597922659282), - new FalconFPR(0.149764534677321517229695737), new FalconFPR(0.988721691960323767604516485), - new FalconFPR(-0.988721691960323767604516485), new FalconFPR(0.149764534677321517229695737), - new FalconFPR(0.989622017463200834623694454), new FalconFPR(0.143695033150294454819773349), - new FalconFPR(-0.143695033150294454819773349), new FalconFPR(0.989622017463200834623694454), - new FalconFPR(0.598160706996342311724958652), new FalconFPR(0.801376171723140219430247777), - new FalconFPR(-0.801376171723140219430247777), new FalconFPR(0.598160706996342311724958652), - new FalconFPR(0.859301818357008404783582139), new FalconFPR(0.511468850437970399504391001), - new FalconFPR(-0.511468850437970399504391001), new FalconFPR(0.859301818357008404783582139), - new FalconFPR(0.245955050335794611599924709), new FalconFPR(0.969281235356548486048290738), - new FalconFPR(-0.969281235356548486048290738), new FalconFPR(0.245955050335794611599924709), - new FalconFPR(0.942573197601446879280758735), new FalconFPR(0.333999651442009404650865481), - new FalconFPR(-0.333999651442009404650865481), new FalconFPR(0.942573197601446879280758735), - new FalconFPR(0.430326481340082633908199031), new FalconFPR(0.902673318237258806751502391), - new FalconFPR(-0.902673318237258806751502391), new FalconFPR(0.430326481340082633908199031), - new FalconFPR(0.743007952135121693517362293), new FalconFPR(0.669282588346636065720696366), - new FalconFPR(-0.669282588346636065720696366), new FalconFPR(0.743007952135121693517362293), - new FalconFPR(0.052131704680283321236358216), new FalconFPR(0.998640218180265222418199049), - new FalconFPR(-0.998640218180265222418199049), new FalconFPR(0.052131704680283321236358216), - new FalconFPR(0.995480755491926941769171600), new FalconFPR(0.094963495329638998938034312), - new FalconFPR(-0.094963495329638998938034312), new FalconFPR(0.995480755491926941769171600), - new FalconFPR(0.636761861236284230413943435), new FalconFPR(0.771060524261813773200605759), - new FalconFPR(-0.771060524261813773200605759), new FalconFPR(0.636761861236284230413943435), - new FalconFPR(0.883363338665731594736308015), new FalconFPR(0.468688822035827933697617870), - new FalconFPR(-0.468688822035827933697617870), new FalconFPR(0.883363338665731594736308015), - new FalconFPR(0.293219162694258650606608599), new FalconFPR(0.956045251349996443270479823), - new FalconFPR(-0.956045251349996443270479823), new FalconFPR(0.293219162694258650606608599), - new FalconFPR(0.957826413027532890321037029), new FalconFPR(0.287347459544729526477331841), - new FalconFPR(-0.287347459544729526477331841), new FalconFPR(0.957826413027532890321037029), - new FalconFPR(0.474100214650550014398580015), new FalconFPR(0.880470889052160770806542929), - new FalconFPR(-0.880470889052160770806542929), new FalconFPR(0.474100214650550014398580015), - new FalconFPR(0.774953106594873878359129282), new FalconFPR(0.632018735939809021909403706), - new FalconFPR(-0.632018735939809021909403706), new FalconFPR(0.774953106594873878359129282), - new FalconFPR(0.101069862754827824987887585), new FalconFPR(0.994879330794805620591166107), - new FalconFPR(-0.994879330794805620591166107), new FalconFPR(0.101069862754827824987887585), - new FalconFPR(0.981379193313754574318224190), new FalconFPR(0.192080397049892441679288205), - new FalconFPR(-0.192080397049892441679288205), new FalconFPR(0.981379193313754574318224190), - new FalconFPR(0.558118531220556115693702964), new FalconFPR(0.829761233794523042469023765), - new FalconFPR(-0.829761233794523042469023765), new FalconFPR(0.558118531220556115693702964), - new FalconFPR(0.833170164701913186439915922), new FalconFPR(0.553016705580027531764226988), - new FalconFPR(-0.553016705580027531764226988), new FalconFPR(0.833170164701913186439915922), - new FalconFPR(0.198098410717953586179324918), new FalconFPR(0.980182135968117392690210009), - new FalconFPR(-0.980182135968117392690210009), new FalconFPR(0.198098410717953586179324918), - new FalconFPR(0.925049240782677590302371869), new FalconFPR(0.379847208924051170576281147), - new FalconFPR(-0.379847208924051170576281147), new FalconFPR(0.925049240782677590302371869), - new FalconFPR(0.385516053843918864075607949), new FalconFPR(0.922701128333878570437264227), - new FalconFPR(-0.922701128333878570437264227), new FalconFPR(0.385516053843918864075607949), - new FalconFPR(0.709272826438865651316533772), new FalconFPR(0.704934080375904908852523758), - new FalconFPR(-0.704934080375904908852523758), new FalconFPR(0.709272826438865651316533772), - new FalconFPR(0.003067956762965976270145365), new FalconFPR(0.999995293809576171511580126), - new FalconFPR(-0.999995293809576171511580126), new FalconFPR(0.003067956762965976270145365) + fpr_gm_tab = new double[]{ + 0, 0, /* unused */ + -0.000000000000000000000000000, 1.000000000000000000000000000, + 0.707106781186547524400844362, 0.707106781186547524400844362, + -0.707106781186547524400844362, 0.707106781186547524400844362, + 0.923879532511286756128183189, 0.382683432365089771728459984, + -0.382683432365089771728459984, 0.923879532511286756128183189, + 0.382683432365089771728459984, 0.923879532511286756128183189, + -0.923879532511286756128183189, 0.382683432365089771728459984, + 0.980785280403230449126182236, 0.195090322016128267848284868, + -0.195090322016128267848284868, 0.980785280403230449126182236, + 0.555570233019602224742830814, 0.831469612302545237078788378, + -0.831469612302545237078788378, 0.555570233019602224742830814, + 0.831469612302545237078788378, 0.555570233019602224742830814, + -0.555570233019602224742830814, 0.831469612302545237078788378, + 0.195090322016128267848284868, 0.980785280403230449126182236, + -0.980785280403230449126182236, 0.195090322016128267848284868, + 0.995184726672196886244836953, 0.098017140329560601994195564, + -0.098017140329560601994195564, 0.995184726672196886244836953, + 0.634393284163645498215171613, 0.773010453362736960810906610, + -0.773010453362736960810906610, 0.634393284163645498215171613, + 0.881921264348355029712756864, 0.471396736825997648556387626, + -0.471396736825997648556387626, 0.881921264348355029712756864, + 0.290284677254462367636192376, 0.956940335732208864935797887, + -0.956940335732208864935797887, 0.290284677254462367636192376, + 0.956940335732208864935797887, 0.290284677254462367636192376, + -0.290284677254462367636192376, 0.956940335732208864935797887, + 0.471396736825997648556387626, 0.881921264348355029712756864, + -0.881921264348355029712756864, 0.471396736825997648556387626, + 0.773010453362736960810906610, 0.634393284163645498215171613, + -0.634393284163645498215171613, 0.773010453362736960810906610, + 0.098017140329560601994195564, 0.995184726672196886244836953, + -0.995184726672196886244836953, 0.098017140329560601994195564, + 0.998795456205172392714771605, 0.049067674327418014254954977, + -0.049067674327418014254954977, 0.998795456205172392714771605, + 0.671558954847018400625376850, 0.740951125354959091175616897, + -0.740951125354959091175616897, 0.671558954847018400625376850, + 0.903989293123443331586200297, 0.427555093430282094320966857, + -0.427555093430282094320966857, 0.903989293123443331586200297, + 0.336889853392220050689253213, 0.941544065183020778412509403, + -0.941544065183020778412509403, 0.336889853392220050689253213, + 0.970031253194543992603984207, 0.242980179903263889948274162, + -0.242980179903263889948274162, 0.970031253194543992603984207, + 0.514102744193221726593693839, 0.857728610000272069902269984, + -0.857728610000272069902269984, 0.514102744193221726593693839, + 0.803207531480644909806676513, 0.595699304492433343467036529, + -0.595699304492433343467036529, 0.803207531480644909806676513, + 0.146730474455361751658850130, 0.989176509964780973451673738, + -0.989176509964780973451673738, 0.146730474455361751658850130, + 0.989176509964780973451673738, 0.146730474455361751658850130, + -0.146730474455361751658850130, 0.989176509964780973451673738, + 0.595699304492433343467036529, 0.803207531480644909806676513, + -0.803207531480644909806676513, 0.595699304492433343467036529, + 0.857728610000272069902269984, 0.514102744193221726593693839, + -0.514102744193221726593693839, 0.857728610000272069902269984, + 0.242980179903263889948274162, 0.970031253194543992603984207, + -0.970031253194543992603984207, 0.242980179903263889948274162, + 0.941544065183020778412509403, 0.336889853392220050689253213, + -0.336889853392220050689253213, 0.941544065183020778412509403, + 0.427555093430282094320966857, 0.903989293123443331586200297, + -0.903989293123443331586200297, 0.427555093430282094320966857, + 0.740951125354959091175616897, 0.671558954847018400625376850, + -0.671558954847018400625376850, 0.740951125354959091175616897, + 0.049067674327418014254954977, 0.998795456205172392714771605, + -0.998795456205172392714771605, 0.049067674327418014254954977, + 0.999698818696204220115765650, 0.024541228522912288031734529, + -0.024541228522912288031734529, 0.999698818696204220115765650, + 0.689540544737066924616730630, 0.724247082951466920941069243, + -0.724247082951466920941069243, 0.689540544737066924616730630, + 0.914209755703530654635014829, 0.405241314004989870908481306, + -0.405241314004989870908481306, 0.914209755703530654635014829, + 0.359895036534988148775104572, 0.932992798834738887711660256, + -0.932992798834738887711660256, 0.359895036534988148775104572, + 0.975702130038528544460395766, 0.219101240156869797227737547, + -0.219101240156869797227737547, 0.975702130038528544460395766, + 0.534997619887097210663076905, 0.844853565249707073259571205, + -0.844853565249707073259571205, 0.534997619887097210663076905, + 0.817584813151583696504920884, 0.575808191417845300745972454, + -0.575808191417845300745972454, 0.817584813151583696504920884, + 0.170961888760301226363642357, 0.985277642388941244774018433, + -0.985277642388941244774018433, 0.170961888760301226363642357, + 0.992479534598709998156767252, 0.122410675199216198498704474, + -0.122410675199216198498704474, 0.992479534598709998156767252, + 0.615231590580626845484913563, 0.788346427626606262009164705, + -0.788346427626606262009164705, 0.615231590580626845484913563, + 0.870086991108711418652292404, 0.492898192229784036873026689, + -0.492898192229784036873026689, 0.870086991108711418652292404, + 0.266712757474898386325286515, 0.963776065795439866686464356, + -0.963776065795439866686464356, 0.266712757474898386325286515, + 0.949528180593036667195936074, 0.313681740398891476656478846, + -0.313681740398891476656478846, 0.949528180593036667195936074, + 0.449611329654606600046294579, 0.893224301195515320342416447, + -0.893224301195515320342416447, 0.449611329654606600046294579, + 0.757208846506484547575464054, 0.653172842953776764084203014, + -0.653172842953776764084203014, 0.757208846506484547575464054, + 0.073564563599667423529465622, 0.997290456678690216135597140, + -0.997290456678690216135597140, 0.073564563599667423529465622, + 0.997290456678690216135597140, 0.073564563599667423529465622, + -0.073564563599667423529465622, 0.997290456678690216135597140, + 0.653172842953776764084203014, 0.757208846506484547575464054, + -0.757208846506484547575464054, 0.653172842953776764084203014, + 0.893224301195515320342416447, 0.449611329654606600046294579, + -0.449611329654606600046294579, 0.893224301195515320342416447, + 0.313681740398891476656478846, 0.949528180593036667195936074, + -0.949528180593036667195936074, 0.313681740398891476656478846, + 0.963776065795439866686464356, 0.266712757474898386325286515, + -0.266712757474898386325286515, 0.963776065795439866686464356, + 0.492898192229784036873026689, 0.870086991108711418652292404, + -0.870086991108711418652292404, 0.492898192229784036873026689, + 0.788346427626606262009164705, 0.615231590580626845484913563, + -0.615231590580626845484913563, 0.788346427626606262009164705, + 0.122410675199216198498704474, 0.992479534598709998156767252, + -0.992479534598709998156767252, 0.122410675199216198498704474, + 0.985277642388941244774018433, 0.170961888760301226363642357, + -0.170961888760301226363642357, 0.985277642388941244774018433, + 0.575808191417845300745972454, 0.817584813151583696504920884, + -0.817584813151583696504920884, 0.575808191417845300745972454, + 0.844853565249707073259571205, 0.534997619887097210663076905, + -0.534997619887097210663076905, 0.844853565249707073259571205, + 0.219101240156869797227737547, 0.975702130038528544460395766, + -0.975702130038528544460395766, 0.219101240156869797227737547, + 0.932992798834738887711660256, 0.359895036534988148775104572, + -0.359895036534988148775104572, 0.932992798834738887711660256, + 0.405241314004989870908481306, 0.914209755703530654635014829, + -0.914209755703530654635014829, 0.405241314004989870908481306, + 0.724247082951466920941069243, 0.689540544737066924616730630, + -0.689540544737066924616730630, 0.724247082951466920941069243, + 0.024541228522912288031734529, 0.999698818696204220115765650, + -0.999698818696204220115765650, 0.024541228522912288031734529, + 0.999924701839144540921646491, 0.012271538285719926079408262, + -0.012271538285719926079408262, 0.999924701839144540921646491, + 0.698376249408972853554813503, 0.715730825283818654125532623, + -0.715730825283818654125532623, 0.698376249408972853554813503, + 0.919113851690057743908477789, 0.393992040061048108596188661, + -0.393992040061048108596188661, 0.919113851690057743908477789, + 0.371317193951837543411934967, 0.928506080473215565937167396, + -0.928506080473215565937167396, 0.371317193951837543411934967, + 0.978317370719627633106240097, 0.207111376192218549708116020, + -0.207111376192218549708116020, 0.978317370719627633106240097, + 0.545324988422046422313987347, 0.838224705554838043186996856, + -0.838224705554838043186996856, 0.545324988422046422313987347, + 0.824589302785025264474803737, 0.565731810783613197389765011, + -0.565731810783613197389765011, 0.824589302785025264474803737, + 0.183039887955140958516532578, 0.983105487431216327180301155, + -0.983105487431216327180301155, 0.183039887955140958516532578, + 0.993906970002356041546922813, 0.110222207293883058807899140, + -0.110222207293883058807899140, 0.993906970002356041546922813, + 0.624859488142386377084072816, 0.780737228572094478301588484, + -0.780737228572094478301588484, 0.624859488142386377084072816, + 0.876070094195406607095844268, 0.482183772079122748517344481, + -0.482183772079122748517344481, 0.876070094195406607095844268, + 0.278519689385053105207848526, 0.960430519415565811199035138, + -0.960430519415565811199035138, 0.278519689385053105207848526, + 0.953306040354193836916740383, 0.302005949319228067003463232, + -0.302005949319228067003463232, 0.953306040354193836916740383, + 0.460538710958240023633181487, 0.887639620402853947760181617, + -0.887639620402853947760181617, 0.460538710958240023633181487, + 0.765167265622458925888815999, 0.643831542889791465068086063, + -0.643831542889791465068086063, 0.765167265622458925888815999, + 0.085797312344439890461556332, 0.996312612182778012627226190, + -0.996312612182778012627226190, 0.085797312344439890461556332, + 0.998118112900149207125155861, 0.061320736302208577782614593, + -0.061320736302208577782614593, 0.998118112900149207125155861, + 0.662415777590171761113069817, 0.749136394523459325469203257, + -0.749136394523459325469203257, 0.662415777590171761113069817, + 0.898674465693953843041976744, 0.438616238538527637647025738, + -0.438616238538527637647025738, 0.898674465693953843041976744, + 0.325310292162262934135954708, 0.945607325380521325730945387, + -0.945607325380521325730945387, 0.325310292162262934135954708, + 0.966976471044852109087220226, 0.254865659604514571553980779, + -0.254865659604514571553980779, 0.966976471044852109087220226, + 0.503538383725717558691867071, 0.863972856121586737918147054, + -0.863972856121586737918147054, 0.503538383725717558691867071, + 0.795836904608883536262791915, 0.605511041404325513920626941, + -0.605511041404325513920626941, 0.795836904608883536262791915, + 0.134580708507126186316358409, 0.990902635427780025108237011, + -0.990902635427780025108237011, 0.134580708507126186316358409, + 0.987301418157858382399815802, 0.158858143333861441684385360, + -0.158858143333861441684385360, 0.987301418157858382399815802, + 0.585797857456438860328080838, 0.810457198252594791726703434, + -0.810457198252594791726703434, 0.585797857456438860328080838, + 0.851355193105265142261290312, 0.524589682678468906215098464, + -0.524589682678468906215098464, 0.851355193105265142261290312, + 0.231058108280671119643236018, 0.972939952205560145467720114, + -0.972939952205560145467720114, 0.231058108280671119643236018, + 0.937339011912574923201899593, 0.348418680249434568419308588, + -0.348418680249434568419308588, 0.937339011912574923201899593, + 0.416429560097637182562598911, 0.909167983090522376563884788, + -0.909167983090522376563884788, 0.416429560097637182562598911, + 0.732654271672412834615546649, 0.680600997795453050594430464, + -0.680600997795453050594430464, 0.732654271672412834615546649, + 0.036807222941358832324332691, 0.999322384588349500896221011, + -0.999322384588349500896221011, 0.036807222941358832324332691, + 0.999322384588349500896221011, 0.036807222941358832324332691, + -0.036807222941358832324332691, 0.999322384588349500896221011, + 0.680600997795453050594430464, 0.732654271672412834615546649, + -0.732654271672412834615546649, 0.680600997795453050594430464, + 0.909167983090522376563884788, 0.416429560097637182562598911, + -0.416429560097637182562598911, 0.909167983090522376563884788, + 0.348418680249434568419308588, 0.937339011912574923201899593, + -0.937339011912574923201899593, 0.348418680249434568419308588, + 0.972939952205560145467720114, 0.231058108280671119643236018, + -0.231058108280671119643236018, 0.972939952205560145467720114, + 0.524589682678468906215098464, 0.851355193105265142261290312, + -0.851355193105265142261290312, 0.524589682678468906215098464, + 0.810457198252594791726703434, 0.585797857456438860328080838, + -0.585797857456438860328080838, 0.810457198252594791726703434, + 0.158858143333861441684385360, 0.987301418157858382399815802, + -0.987301418157858382399815802, 0.158858143333861441684385360, + 0.990902635427780025108237011, 0.134580708507126186316358409, + -0.134580708507126186316358409, 0.990902635427780025108237011, + 0.605511041404325513920626941, 0.795836904608883536262791915, + -0.795836904608883536262791915, 0.605511041404325513920626941, + 0.863972856121586737918147054, 0.503538383725717558691867071, + -0.503538383725717558691867071, 0.863972856121586737918147054, + 0.254865659604514571553980779, 0.966976471044852109087220226, + -0.966976471044852109087220226, 0.254865659604514571553980779, + 0.945607325380521325730945387, 0.325310292162262934135954708, + -0.325310292162262934135954708, 0.945607325380521325730945387, + 0.438616238538527637647025738, 0.898674465693953843041976744, + -0.898674465693953843041976744, 0.438616238538527637647025738, + 0.749136394523459325469203257, 0.662415777590171761113069817, + -0.662415777590171761113069817, 0.749136394523459325469203257, + 0.061320736302208577782614593, 0.998118112900149207125155861, + -0.998118112900149207125155861, 0.061320736302208577782614593, + 0.996312612182778012627226190, 0.085797312344439890461556332, + -0.085797312344439890461556332, 0.996312612182778012627226190, + 0.643831542889791465068086063, 0.765167265622458925888815999, + -0.765167265622458925888815999, 0.643831542889791465068086063, + 0.887639620402853947760181617, 0.460538710958240023633181487, + -0.460538710958240023633181487, 0.887639620402853947760181617, + 0.302005949319228067003463232, 0.953306040354193836916740383, + -0.953306040354193836916740383, 0.302005949319228067003463232, + 0.960430519415565811199035138, 0.278519689385053105207848526, + -0.278519689385053105207848526, 0.960430519415565811199035138, + 0.482183772079122748517344481, 0.876070094195406607095844268, + -0.876070094195406607095844268, 0.482183772079122748517344481, + 0.780737228572094478301588484, 0.624859488142386377084072816, + -0.624859488142386377084072816, 0.780737228572094478301588484, + 0.110222207293883058807899140, 0.993906970002356041546922813, + -0.993906970002356041546922813, 0.110222207293883058807899140, + 0.983105487431216327180301155, 0.183039887955140958516532578, + -0.183039887955140958516532578, 0.983105487431216327180301155, + 0.565731810783613197389765011, 0.824589302785025264474803737, + -0.824589302785025264474803737, 0.565731810783613197389765011, + 0.838224705554838043186996856, 0.545324988422046422313987347, + -0.545324988422046422313987347, 0.838224705554838043186996856, + 0.207111376192218549708116020, 0.978317370719627633106240097, + -0.978317370719627633106240097, 0.207111376192218549708116020, + 0.928506080473215565937167396, 0.371317193951837543411934967, + -0.371317193951837543411934967, 0.928506080473215565937167396, + 0.393992040061048108596188661, 0.919113851690057743908477789, + -0.919113851690057743908477789, 0.393992040061048108596188661, + 0.715730825283818654125532623, 0.698376249408972853554813503, + -0.698376249408972853554813503, 0.715730825283818654125532623, + 0.012271538285719926079408262, 0.999924701839144540921646491, + -0.999924701839144540921646491, 0.012271538285719926079408262, + 0.999981175282601142656990438, 0.006135884649154475359640235, + -0.006135884649154475359640235, 0.999981175282601142656990438, + 0.702754744457225302452914421, 0.711432195745216441522130290, + -0.711432195745216441522130290, 0.702754744457225302452914421, + 0.921514039342041943465396332, 0.388345046698826291624993541, + -0.388345046698826291624993541, 0.921514039342041943465396332, + 0.377007410216418256726567823, 0.926210242138311341974793388, + -0.926210242138311341974793388, 0.377007410216418256726567823, + 0.979569765685440534439326110, 0.201104634842091911558443546, + -0.201104634842091911558443546, 0.979569765685440534439326110, + 0.550457972936604802977289893, 0.834862874986380056304401383, + -0.834862874986380056304401383, 0.550457972936604802977289893, + 0.828045045257755752067527592, 0.560661576197336023839710223, + -0.560661576197336023839710223, 0.828045045257755752067527592, + 0.189068664149806212754997837, 0.981963869109555264072848154, + -0.981963869109555264072848154, 0.189068664149806212754997837, + 0.994564570734255452119106243, 0.104121633872054579120943880, + -0.104121633872054579120943880, 0.994564570734255452119106243, + 0.629638238914927025372981341, 0.776888465673232450040827983, + -0.776888465673232450040827983, 0.629638238914927025372981341, + 0.879012226428633477831323711, 0.476799230063322133342158117, + -0.476799230063322133342158117, 0.879012226428633477831323711, + 0.284407537211271843618310615, 0.958703474895871555374645792, + -0.958703474895871555374645792, 0.284407537211271843618310615, + 0.955141168305770721498157712, 0.296150888243623824121786128, + -0.296150888243623824121786128, 0.955141168305770721498157712, + 0.465976495767966177902756065, 0.884797098430937780104007041, + -0.884797098430937780104007041, 0.465976495767966177902756065, + 0.769103337645579639346626069, 0.639124444863775743801488193, + -0.639124444863775743801488193, 0.769103337645579639346626069, + 0.091908956497132728624990979, 0.995767414467659793982495643, + -0.995767414467659793982495643, 0.091908956497132728624990979, + 0.998475580573294752208559038, 0.055195244349689939809447526, + -0.055195244349689939809447526, 0.998475580573294752208559038, + 0.666999922303637506650154222, 0.745057785441465962407907310, + -0.745057785441465962407907310, 0.666999922303637506650154222, + 0.901348847046022014570746093, 0.433093818853151968484222638, + -0.433093818853151968484222638, 0.901348847046022014570746093, + 0.331106305759876401737190737, 0.943593458161960361495301445, + -0.943593458161960361495301445, 0.331106305759876401737190737, + 0.968522094274417316221088329, 0.248927605745720168110682816, + -0.248927605745720168110682816, 0.968522094274417316221088329, + 0.508830142543107036931749324, 0.860866938637767279344583877, + -0.860866938637767279344583877, 0.508830142543107036931749324, + 0.799537269107905033500246232, 0.600616479383868926653875896, + -0.600616479383868926653875896, 0.799537269107905033500246232, + 0.140658239332849230714788846, 0.990058210262297105505906464, + -0.990058210262297105505906464, 0.140658239332849230714788846, + 0.988257567730749491404792538, 0.152797185258443427720336613, + -0.152797185258443427720336613, 0.988257567730749491404792538, + 0.590759701858874228423887908, 0.806847553543799272206514313, + -0.806847553543799272206514313, 0.590759701858874228423887908, + 0.854557988365400520767862276, 0.519355990165589587361829932, + -0.519355990165589587361829932, 0.854557988365400520767862276, + 0.237023605994367206867735915, 0.971503890986251775537099622, + -0.971503890986251775537099622, 0.237023605994367206867735915, + 0.939459223602189911962669246, 0.342660717311994397592781983, + -0.342660717311994397592781983, 0.939459223602189911962669246, + 0.422000270799799685941287941, 0.906595704514915365332960588, + -0.906595704514915365332960588, 0.422000270799799685941287941, + 0.736816568877369875090132520, 0.676092703575315960360419228, + -0.676092703575315960360419228, 0.736816568877369875090132520, + 0.042938256934940823077124540, 0.999077727752645382888781997, + -0.999077727752645382888781997, 0.042938256934940823077124540, + 0.999529417501093163079703322, 0.030674803176636625934021028, + -0.030674803176636625934021028, 0.999529417501093163079703322, + 0.685083667772700381362052545, 0.728464390448225196492035438, + -0.728464390448225196492035438, 0.685083667772700381362052545, + 0.911706032005429851404397325, 0.410843171057903942183466675, + -0.410843171057903942183466675, 0.911706032005429851404397325, + 0.354163525420490382357395796, 0.935183509938947577642207480, + -0.935183509938947577642207480, 0.354163525420490382357395796, + 0.974339382785575860518721668, 0.225083911359792835991642120, + -0.225083911359792835991642120, 0.974339382785575860518721668, + 0.529803624686294668216054671, 0.848120344803297251279133563, + -0.848120344803297251279133563, 0.529803624686294668216054671, + 0.814036329705948361654516690, 0.580813958095764545075595272, + -0.580813958095764545075595272, 0.814036329705948361654516690, + 0.164913120489969921418189113, 0.986308097244598647863297524, + -0.986308097244598647863297524, 0.164913120489969921418189113, + 0.991709753669099522860049931, 0.128498110793793172624415589, + -0.128498110793793172624415589, 0.991709753669099522860049931, + 0.610382806276309452716352152, 0.792106577300212351782342879, + -0.792106577300212351782342879, 0.610382806276309452716352152, + 0.867046245515692651480195629, 0.498227666972781852410983869, + -0.498227666972781852410983869, 0.867046245515692651480195629, + 0.260794117915275518280186509, 0.965394441697689374550843858, + -0.965394441697689374550843858, 0.260794117915275518280186509, + 0.947585591017741134653387321, 0.319502030816015677901518272, + -0.319502030816015677901518272, 0.947585591017741134653387321, + 0.444122144570429231642069418, 0.895966249756185155914560282, + -0.895966249756185155914560282, 0.444122144570429231642069418, + 0.753186799043612482483430486, 0.657806693297078656931182264, + -0.657806693297078656931182264, 0.753186799043612482483430486, + 0.067443919563664057897972422, 0.997723066644191609848546728, + -0.997723066644191609848546728, 0.067443919563664057897972422, + 0.996820299291165714972629398, 0.079682437971430121147120656, + -0.079682437971430121147120656, 0.996820299291165714972629398, + 0.648514401022112445084560551, 0.761202385484261814029709836, + -0.761202385484261814029709836, 0.648514401022112445084560551, + 0.890448723244757889952150560, 0.455083587126343823535869268, + -0.455083587126343823535869268, 0.890448723244757889952150560, + 0.307849640041534893682063646, 0.951435020969008369549175569, + -0.951435020969008369549175569, 0.307849640041534893682063646, + 0.962121404269041595429604316, 0.272621355449948984493347477, + -0.272621355449948984493347477, 0.962121404269041595429604316, + 0.487550160148435954641485027, 0.873094978418290098636085973, + -0.873094978418290098636085973, 0.487550160148435954641485027, + 0.784556597155575233023892575, 0.620057211763289178646268191, + -0.620057211763289178646268191, 0.784556597155575233023892575, + 0.116318630911904767252544319, 0.993211949234794533104601012, + -0.993211949234794533104601012, 0.116318630911904767252544319, + 0.984210092386929073193874387, 0.177004220412148756196839844, + -0.177004220412148756196839844, 0.984210092386929073193874387, + 0.570780745886967280232652864, 0.821102514991104679060430820, + -0.821102514991104679060430820, 0.570780745886967280232652864, + 0.841554977436898409603499520, 0.540171472729892881297845480, + -0.540171472729892881297845480, 0.841554977436898409603499520, + 0.213110319916091373967757518, 0.977028142657754351485866211, + -0.977028142657754351485866211, 0.213110319916091373967757518, + 0.930766961078983731944872340, 0.365612997804773870011745909, + -0.365612997804773870011745909, 0.930766961078983731944872340, + 0.399624199845646828544117031, 0.916679059921042663116457013, + -0.916679059921042663116457013, 0.399624199845646828544117031, + 0.720002507961381629076682999, 0.693971460889654009003734389, + -0.693971460889654009003734389, 0.720002507961381629076682999, + 0.018406729905804820927366313, 0.999830581795823422015722275, + -0.999830581795823422015722275, 0.018406729905804820927366313, + 0.999830581795823422015722275, 0.018406729905804820927366313, + -0.018406729905804820927366313, 0.999830581795823422015722275, + 0.693971460889654009003734389, 0.720002507961381629076682999, + -0.720002507961381629076682999, 0.693971460889654009003734389, + 0.916679059921042663116457013, 0.399624199845646828544117031, + -0.399624199845646828544117031, 0.916679059921042663116457013, + 0.365612997804773870011745909, 0.930766961078983731944872340, + -0.930766961078983731944872340, 0.365612997804773870011745909, + 0.977028142657754351485866211, 0.213110319916091373967757518, + -0.213110319916091373967757518, 0.977028142657754351485866211, + 0.540171472729892881297845480, 0.841554977436898409603499520, + -0.841554977436898409603499520, 0.540171472729892881297845480, + 0.821102514991104679060430820, 0.570780745886967280232652864, + -0.570780745886967280232652864, 0.821102514991104679060430820, + 0.177004220412148756196839844, 0.984210092386929073193874387, + -0.984210092386929073193874387, 0.177004220412148756196839844, + 0.993211949234794533104601012, 0.116318630911904767252544319, + -0.116318630911904767252544319, 0.993211949234794533104601012, + 0.620057211763289178646268191, 0.784556597155575233023892575, + -0.784556597155575233023892575, 0.620057211763289178646268191, + 0.873094978418290098636085973, 0.487550160148435954641485027, + -0.487550160148435954641485027, 0.873094978418290098636085973, + 0.272621355449948984493347477, 0.962121404269041595429604316, + -0.962121404269041595429604316, 0.272621355449948984493347477, + 0.951435020969008369549175569, 0.307849640041534893682063646, + -0.307849640041534893682063646, 0.951435020969008369549175569, + 0.455083587126343823535869268, 0.890448723244757889952150560, + -0.890448723244757889952150560, 0.455083587126343823535869268, + 0.761202385484261814029709836, 0.648514401022112445084560551, + -0.648514401022112445084560551, 0.761202385484261814029709836, + 0.079682437971430121147120656, 0.996820299291165714972629398, + -0.996820299291165714972629398, 0.079682437971430121147120656, + 0.997723066644191609848546728, 0.067443919563664057897972422, + -0.067443919563664057897972422, 0.997723066644191609848546728, + 0.657806693297078656931182264, 0.753186799043612482483430486, + -0.753186799043612482483430486, 0.657806693297078656931182264, + 0.895966249756185155914560282, 0.444122144570429231642069418, + -0.444122144570429231642069418, 0.895966249756185155914560282, + 0.319502030816015677901518272, 0.947585591017741134653387321, + -0.947585591017741134653387321, 0.319502030816015677901518272, + 0.965394441697689374550843858, 0.260794117915275518280186509, + -0.260794117915275518280186509, 0.965394441697689374550843858, + 0.498227666972781852410983869, 0.867046245515692651480195629, + -0.867046245515692651480195629, 0.498227666972781852410983869, + 0.792106577300212351782342879, 0.610382806276309452716352152, + -0.610382806276309452716352152, 0.792106577300212351782342879, + 0.128498110793793172624415589, 0.991709753669099522860049931, + -0.991709753669099522860049931, 0.128498110793793172624415589, + 0.986308097244598647863297524, 0.164913120489969921418189113, + -0.164913120489969921418189113, 0.986308097244598647863297524, + 0.580813958095764545075595272, 0.814036329705948361654516690, + -0.814036329705948361654516690, 0.580813958095764545075595272, + 0.848120344803297251279133563, 0.529803624686294668216054671, + -0.529803624686294668216054671, 0.848120344803297251279133563, + 0.225083911359792835991642120, 0.974339382785575860518721668, + -0.974339382785575860518721668, 0.225083911359792835991642120, + 0.935183509938947577642207480, 0.354163525420490382357395796, + -0.354163525420490382357395796, 0.935183509938947577642207480, + 0.410843171057903942183466675, 0.911706032005429851404397325, + -0.911706032005429851404397325, 0.410843171057903942183466675, + 0.728464390448225196492035438, 0.685083667772700381362052545, + -0.685083667772700381362052545, 0.728464390448225196492035438, + 0.030674803176636625934021028, 0.999529417501093163079703322, + -0.999529417501093163079703322, 0.030674803176636625934021028, + 0.999077727752645382888781997, 0.042938256934940823077124540, + -0.042938256934940823077124540, 0.999077727752645382888781997, + 0.676092703575315960360419228, 0.736816568877369875090132520, + -0.736816568877369875090132520, 0.676092703575315960360419228, + 0.906595704514915365332960588, 0.422000270799799685941287941, + -0.422000270799799685941287941, 0.906595704514915365332960588, + 0.342660717311994397592781983, 0.939459223602189911962669246, + -0.939459223602189911962669246, 0.342660717311994397592781983, + 0.971503890986251775537099622, 0.237023605994367206867735915, + -0.237023605994367206867735915, 0.971503890986251775537099622, + 0.519355990165589587361829932, 0.854557988365400520767862276, + -0.854557988365400520767862276, 0.519355990165589587361829932, + 0.806847553543799272206514313, 0.590759701858874228423887908, + -0.590759701858874228423887908, 0.806847553543799272206514313, + 0.152797185258443427720336613, 0.988257567730749491404792538, + -0.988257567730749491404792538, 0.152797185258443427720336613, + 0.990058210262297105505906464, 0.140658239332849230714788846, + -0.140658239332849230714788846, 0.990058210262297105505906464, + 0.600616479383868926653875896, 0.799537269107905033500246232, + -0.799537269107905033500246232, 0.600616479383868926653875896, + 0.860866938637767279344583877, 0.508830142543107036931749324, + -0.508830142543107036931749324, 0.860866938637767279344583877, + 0.248927605745720168110682816, 0.968522094274417316221088329, + -0.968522094274417316221088329, 0.248927605745720168110682816, + 0.943593458161960361495301445, 0.331106305759876401737190737, + -0.331106305759876401737190737, 0.943593458161960361495301445, + 0.433093818853151968484222638, 0.901348847046022014570746093, + -0.901348847046022014570746093, 0.433093818853151968484222638, + 0.745057785441465962407907310, 0.666999922303637506650154222, + -0.666999922303637506650154222, 0.745057785441465962407907310, + 0.055195244349689939809447526, 0.998475580573294752208559038, + -0.998475580573294752208559038, 0.055195244349689939809447526, + 0.995767414467659793982495643, 0.091908956497132728624990979, + -0.091908956497132728624990979, 0.995767414467659793982495643, + 0.639124444863775743801488193, 0.769103337645579639346626069, + -0.769103337645579639346626069, 0.639124444863775743801488193, + 0.884797098430937780104007041, 0.465976495767966177902756065, + -0.465976495767966177902756065, 0.884797098430937780104007041, + 0.296150888243623824121786128, 0.955141168305770721498157712, + -0.955141168305770721498157712, 0.296150888243623824121786128, + 0.958703474895871555374645792, 0.284407537211271843618310615, + -0.284407537211271843618310615, 0.958703474895871555374645792, + 0.476799230063322133342158117, 0.879012226428633477831323711, + -0.879012226428633477831323711, 0.476799230063322133342158117, + 0.776888465673232450040827983, 0.629638238914927025372981341, + -0.629638238914927025372981341, 0.776888465673232450040827983, + 0.104121633872054579120943880, 0.994564570734255452119106243, + -0.994564570734255452119106243, 0.104121633872054579120943880, + 0.981963869109555264072848154, 0.189068664149806212754997837, + -0.189068664149806212754997837, 0.981963869109555264072848154, + 0.560661576197336023839710223, 0.828045045257755752067527592, + -0.828045045257755752067527592, 0.560661576197336023839710223, + 0.834862874986380056304401383, 0.550457972936604802977289893, + -0.550457972936604802977289893, 0.834862874986380056304401383, + 0.201104634842091911558443546, 0.979569765685440534439326110, + -0.979569765685440534439326110, 0.201104634842091911558443546, + 0.926210242138311341974793388, 0.377007410216418256726567823, + -0.377007410216418256726567823, 0.926210242138311341974793388, + 0.388345046698826291624993541, 0.921514039342041943465396332, + -0.921514039342041943465396332, 0.388345046698826291624993541, + 0.711432195745216441522130290, 0.702754744457225302452914421, + -0.702754744457225302452914421, 0.711432195745216441522130290, + 0.006135884649154475359640235, 0.999981175282601142656990438, + -0.999981175282601142656990438, 0.006135884649154475359640235, + 0.999995293809576171511580126, 0.003067956762965976270145365, + -0.003067956762965976270145365, 0.999995293809576171511580126, + 0.704934080375904908852523758, 0.709272826438865651316533772, + -0.709272826438865651316533772, 0.704934080375904908852523758, + 0.922701128333878570437264227, 0.385516053843918864075607949, + -0.385516053843918864075607949, 0.922701128333878570437264227, + 0.379847208924051170576281147, 0.925049240782677590302371869, + -0.925049240782677590302371869, 0.379847208924051170576281147, + 0.980182135968117392690210009, 0.198098410717953586179324918, + -0.198098410717953586179324918, 0.980182135968117392690210009, + 0.553016705580027531764226988, 0.833170164701913186439915922, + -0.833170164701913186439915922, 0.553016705580027531764226988, + 0.829761233794523042469023765, 0.558118531220556115693702964, + -0.558118531220556115693702964, 0.829761233794523042469023765, + 0.192080397049892441679288205, 0.981379193313754574318224190, + -0.981379193313754574318224190, 0.192080397049892441679288205, + 0.994879330794805620591166107, 0.101069862754827824987887585, + -0.101069862754827824987887585, 0.994879330794805620591166107, + 0.632018735939809021909403706, 0.774953106594873878359129282, + -0.774953106594873878359129282, 0.632018735939809021909403706, + 0.880470889052160770806542929, 0.474100214650550014398580015, + -0.474100214650550014398580015, 0.880470889052160770806542929, + 0.287347459544729526477331841, 0.957826413027532890321037029, + -0.957826413027532890321037029, 0.287347459544729526477331841, + 0.956045251349996443270479823, 0.293219162694258650606608599, + -0.293219162694258650606608599, 0.956045251349996443270479823, + 0.468688822035827933697617870, 0.883363338665731594736308015, + -0.883363338665731594736308015, 0.468688822035827933697617870, + 0.771060524261813773200605759, 0.636761861236284230413943435, + -0.636761861236284230413943435, 0.771060524261813773200605759, + 0.094963495329638998938034312, 0.995480755491926941769171600, + -0.995480755491926941769171600, 0.094963495329638998938034312, + 0.998640218180265222418199049, 0.052131704680283321236358216, + -0.052131704680283321236358216, 0.998640218180265222418199049, + 0.669282588346636065720696366, 0.743007952135121693517362293, + -0.743007952135121693517362293, 0.669282588346636065720696366, + 0.902673318237258806751502391, 0.430326481340082633908199031, + -0.430326481340082633908199031, 0.902673318237258806751502391, + 0.333999651442009404650865481, 0.942573197601446879280758735, + -0.942573197601446879280758735, 0.333999651442009404650865481, + 0.969281235356548486048290738, 0.245955050335794611599924709, + -0.245955050335794611599924709, 0.969281235356548486048290738, + 0.511468850437970399504391001, 0.859301818357008404783582139, + -0.859301818357008404783582139, 0.511468850437970399504391001, + 0.801376171723140219430247777, 0.598160706996342311724958652, + -0.598160706996342311724958652, 0.801376171723140219430247777, + 0.143695033150294454819773349, 0.989622017463200834623694454, + -0.989622017463200834623694454, 0.143695033150294454819773349, + 0.988721691960323767604516485, 0.149764534677321517229695737, + -0.149764534677321517229695737, 0.988721691960323767604516485, + 0.593232295039799808047809426, 0.805031331142963597922659282, + -0.805031331142963597922659282, 0.593232295039799808047809426, + 0.856147328375194481019630732, 0.516731799017649881508753876, + -0.516731799017649881508753876, 0.856147328375194481019630732, + 0.240003022448741486568922365, 0.970772140728950302138169611, + -0.970772140728950302138169611, 0.240003022448741486568922365, + 0.940506070593268323787291309, 0.339776884406826857828825803, + -0.339776884406826857828825803, 0.940506070593268323787291309, + 0.424779681209108833357226189, 0.905296759318118774354048329, + -0.905296759318118774354048329, 0.424779681209108833357226189, + 0.738887324460615147933116508, 0.673829000378756060917568372, + -0.673829000378756060917568372, 0.738887324460615147933116508, + 0.046003182130914628814301788, 0.998941293186856850633930266, + -0.998941293186856850633930266, 0.046003182130914628814301788, + 0.999618822495178597116830637, 0.027608145778965741612354872, + -0.027608145778965741612354872, 0.999618822495178597116830637, + 0.687315340891759108199186948, 0.726359155084345976817494315, + -0.726359155084345976817494315, 0.687315340891759108199186948, + 0.912962190428398164628018233, 0.408044162864978680820747499, + -0.408044162864978680820747499, 0.912962190428398164628018233, + 0.357030961233430032614954036, 0.934092550404258914729877883, + -0.934092550404258914729877883, 0.357030961233430032614954036, + 0.975025345066994146844913468, 0.222093620973203534094094721, + -0.222093620973203534094094721, 0.975025345066994146844913468, + 0.532403127877197971442805218, 0.846490938774052078300544488, + -0.846490938774052078300544488, 0.532403127877197971442805218, + 0.815814410806733789010772660, 0.578313796411655563342245019, + -0.578313796411655563342245019, 0.815814410806733789010772660, + 0.167938294974731178054745536, 0.985797509167567424700995000, + -0.985797509167567424700995000, 0.167938294974731178054745536, + 0.992099313142191757112085445, 0.125454983411546238542336453, + -0.125454983411546238542336453, 0.992099313142191757112085445, + 0.612810082429409703935211936, 0.790230221437310055030217152, + -0.790230221437310055030217152, 0.612810082429409703935211936, + 0.868570705971340895340449876, 0.495565261825772531150266670, + -0.495565261825772531150266670, 0.868570705971340895340449876, + 0.263754678974831383611349322, 0.964589793289812723836432159, + -0.964589793289812723836432159, 0.263754678974831383611349322, + 0.948561349915730288158494826, 0.316593375556165867243047035, + -0.316593375556165867243047035, 0.948561349915730288158494826, + 0.446868840162374195353044389, 0.894599485631382678433072126, + -0.894599485631382678433072126, 0.446868840162374195353044389, + 0.755201376896536527598710756, 0.655492852999615385312679701, + -0.655492852999615385312679701, 0.755201376896536527598710756, + 0.070504573389613863027351471, 0.997511456140303459699448390, + -0.997511456140303459699448390, 0.070504573389613863027351471, + 0.997060070339482978987989949, 0.076623861392031492278332463, + -0.076623861392031492278332463, 0.997060070339482978987989949, + 0.650846684996380915068975573, 0.759209188978388033485525443, + -0.759209188978388033485525443, 0.650846684996380915068975573, + 0.891840709392342727796478697, 0.452349587233770874133026703, + -0.452349587233770874133026703, 0.891840709392342727796478697, + 0.310767152749611495835997250, 0.950486073949481721759926101, + -0.950486073949481721759926101, 0.310767152749611495835997250, + 0.962953266873683886347921481, 0.269668325572915106525464462, + -0.269668325572915106525464462, 0.962953266873683886347921481, + 0.490226483288291154229598449, 0.871595086655951034842481435, + -0.871595086655951034842481435, 0.490226483288291154229598449, + 0.786455213599085757522319464, 0.617647307937803932403979402, + -0.617647307937803932403979402, 0.786455213599085757522319464, + 0.119365214810991364593637790, 0.992850414459865090793563344, + -0.992850414459865090793563344, 0.119365214810991364593637790, + 0.984748501801904218556553176, 0.173983873387463827950700807, + -0.173983873387463827950700807, 0.984748501801904218556553176, + 0.573297166698042212820171239, 0.819347520076796960824689637, + -0.819347520076796960824689637, 0.573297166698042212820171239, + 0.843208239641845437161743865, 0.537587076295645482502214932, + -0.537587076295645482502214932, 0.843208239641845437161743865, + 0.216106797076219509948385131, 0.976369731330021149312732194, + -0.976369731330021149312732194, 0.216106797076219509948385131, + 0.931884265581668106718557199, 0.362755724367397216204854462, + -0.362755724367397216204854462, 0.931884265581668106718557199, + 0.402434650859418441082533934, 0.915448716088267819566431292, + -0.915448716088267819566431292, 0.402434650859418441082533934, + 0.722128193929215321243607198, 0.691759258364157774906734132, + -0.691759258364157774906734132, 0.722128193929215321243607198, + 0.021474080275469507418374898, 0.999769405351215321657617036, + -0.999769405351215321657617036, 0.021474080275469507418374898, + 0.999882347454212525633049627, 0.015339206284988101044151868, + -0.015339206284988101044151868, 0.999882347454212525633049627, + 0.696177131491462944788582591, 0.717870045055731736211325329, + -0.717870045055731736211325329, 0.696177131491462944788582591, + 0.917900775621390457642276297, 0.396809987416710328595290911, + -0.396809987416710328595290911, 0.917900775621390457642276297, + 0.368466829953372331712746222, 0.929640895843181265457918066, + -0.929640895843181265457918066, 0.368466829953372331712746222, + 0.977677357824509979943404762, 0.210111836880469621717489972, + -0.210111836880469621717489972, 0.977677357824509979943404762, + 0.542750784864515906586768661, 0.839893794195999504583383987, + -0.839893794195999504583383987, 0.542750784864515906586768661, + 0.822849781375826332046780034, 0.568258952670131549790548489, + -0.568258952670131549790548489, 0.822849781375826332046780034, + 0.180022901405699522679906590, 0.983662419211730274396237776, + -0.983662419211730274396237776, 0.180022901405699522679906590, + 0.993564135520595333782021697, 0.113270952177564349018228733, + -0.113270952177564349018228733, 0.993564135520595333782021697, + 0.622461279374149972519166721, 0.782650596166575738458949301, + -0.782650596166575738458949301, 0.622461279374149972519166721, + 0.874586652278176112634431897, 0.484869248000791101822951699, + -0.484869248000791101822951699, 0.874586652278176112634431897, + 0.275571819310958163076425168, 0.961280485811320641748659653, + -0.961280485811320641748659653, 0.275571819310958163076425168, + 0.952375012719765858529893608, 0.304929229735402406490728633, + -0.304929229735402406490728633, 0.952375012719765858529893608, + 0.457813303598877221904961155, 0.889048355854664562540777729, + -0.889048355854664562540777729, 0.457813303598877221904961155, + 0.763188417263381271704838297, 0.646176012983316364832802220, + -0.646176012983316364832802220, 0.763188417263381271704838297, + 0.082740264549375693111987083, 0.996571145790554847093566910, + -0.996571145790554847093566910, 0.082740264549375693111987083, + 0.997925286198596012623025462, 0.064382630929857460819324537, + -0.064382630929857460819324537, 0.997925286198596012623025462, + 0.660114342067420478559490747, 0.751165131909686411205819422, + -0.751165131909686411205819422, 0.660114342067420478559490747, + 0.897324580705418281231391836, 0.441371268731716692879988968, + -0.441371268731716692879988968, 0.897324580705418281231391836, + 0.322407678801069848384807478, 0.946600913083283570044599823, + -0.946600913083283570044599823, 0.322407678801069848384807478, + 0.966190003445412555433832961, 0.257831102162159005614471295, + -0.257831102162159005614471295, 0.966190003445412555433832961, + 0.500885382611240786241285004, 0.865513624090569082825488358, + -0.865513624090569082825488358, 0.500885382611240786241285004, + 0.793975477554337164895083757, 0.607949784967773667243642671, + -0.607949784967773667243642671, 0.793975477554337164895083757, + 0.131540028702883111103387493, 0.991310859846115418957349799, + -0.991310859846115418957349799, 0.131540028702883111103387493, + 0.986809401814185476970235952, 0.161886393780111837641387995, + -0.161886393780111837641387995, 0.986809401814185476970235952, + 0.583308652937698294392830961, 0.812250586585203913049744181, + -0.812250586585203913049744181, 0.583308652937698294392830961, + 0.849741768000852489471268395, 0.527199134781901348464274575, + -0.527199134781901348464274575, 0.849741768000852489471268395, + 0.228072083170885739254457379, 0.973644249650811925318383912, + -0.973644249650811925318383912, 0.228072083170885739254457379, + 0.936265667170278246576310996, 0.351292756085567125601307623, + -0.351292756085567125601307623, 0.936265667170278246576310996, + 0.413638312238434547471944324, 0.910441292258067196934095369, + -0.910441292258067196934095369, 0.413638312238434547471944324, + 0.730562769227827561177758850, 0.682845546385248068164596123, + -0.682845546385248068164596123, 0.730562769227827561177758850, + 0.033741171851377584833716112, 0.999430604555461772019008327, + -0.999430604555461772019008327, 0.033741171851377584833716112, + 0.999204758618363895492950001, 0.039872927587739811128578738, + -0.039872927587739811128578738, 0.999204758618363895492950001, + 0.678350043129861486873655042, 0.734738878095963464563223604, + -0.734738878095963464563223604, 0.678350043129861486873655042, + 0.907886116487666212038681480, 0.419216888363223956433010020, + -0.419216888363223956433010020, 0.907886116487666212038681480, + 0.345541324963989065539191723, 0.938403534063108112192420774, + -0.938403534063108112192420774, 0.345541324963989065539191723, + 0.972226497078936305708321144, 0.234041958583543423191242045, + -0.234041958583543423191242045, 0.972226497078936305708321144, + 0.521975292937154342694258318, 0.852960604930363657746588082, + -0.852960604930363657746588082, 0.521975292937154342694258318, + 0.808656181588174991946968128, 0.588281548222645304786439813, + -0.588281548222645304786439813, 0.808656181588174991946968128, + 0.155828397654265235743101486, 0.987784141644572154230969032, + -0.987784141644572154230969032, 0.155828397654265235743101486, + 0.990485084256457037998682243, 0.137620121586486044948441663, + -0.137620121586486044948441663, 0.990485084256457037998682243, + 0.603066598540348201693430617, 0.797690840943391108362662755, + -0.797690840943391108362662755, 0.603066598540348201693430617, + 0.862423956111040538690933878, 0.506186645345155291048942344, + -0.506186645345155291048942344, 0.862423956111040538690933878, + 0.251897818154216950498106628, 0.967753837093475465243391912, + -0.967753837093475465243391912, 0.251897818154216950498106628, + 0.944604837261480265659265493, 0.328209843579092526107916817, + -0.328209843579092526107916817, 0.944604837261480265659265493, + 0.435857079922255491032544080, 0.900015892016160228714535267, + -0.900015892016160228714535267, 0.435857079922255491032544080, + 0.747100605980180144323078847, 0.664710978203344868130324985, + -0.664710978203344868130324985, 0.747100605980180144323078847, + 0.058258264500435759613979782, 0.998301544933892840738782163, + -0.998301544933892840738782163, 0.058258264500435759613979782, + 0.996044700901251989887944810, 0.088853552582524596561586535, + -0.088853552582524596561586535, 0.996044700901251989887944810, + 0.641481012808583151988739898, 0.767138911935820381181694573, + -0.767138911935820381181694573, 0.641481012808583151988739898, + 0.886222530148880631647990821, 0.463259783551860197390719637, + -0.463259783551860197390719637, 0.886222530148880631647990821, + 0.299079826308040476750336973, 0.954228095109105629780430732, + -0.954228095109105629780430732, 0.299079826308040476750336973, + 0.959571513081984528335528181, 0.281464937925757984095231007, + -0.281464937925757984095231007, 0.959571513081984528335528181, + 0.479493757660153026679839798, 0.877545290207261291668470750, + -0.877545290207261291668470750, 0.479493757660153026679839798, + 0.778816512381475953374724325, 0.627251815495144113509622565, + -0.627251815495144113509622565, 0.778816512381475953374724325, + 0.107172424956808849175529148, 0.994240449453187946358413442, + -0.994240449453187946358413442, 0.107172424956808849175529148, + 0.982539302287441255907040396, 0.186055151663446648105438304, + -0.186055151663446648105438304, 0.982539302287441255907040396, + 0.563199344013834115007363772, 0.826321062845663480311195452, + -0.826321062845663480311195452, 0.563199344013834115007363772, + 0.836547727223511984524285790, 0.547894059173100165608820571, + -0.547894059173100165608820571, 0.836547727223511984524285790, + 0.204108966092816874181696950, 0.978948175319062194715480124, + -0.978948175319062194715480124, 0.204108966092816874181696950, + 0.927362525650401087274536959, 0.374164062971457997104393020, + -0.374164062971457997104393020, 0.927362525650401087274536959, + 0.391170384302253888687512949, 0.920318276709110566440076541, + -0.920318276709110566440076541, 0.391170384302253888687512949, + 0.713584868780793592903125099, 0.700568793943248366792866380, + -0.700568793943248366792866380, 0.713584868780793592903125099, + 0.009203754782059819315102378, 0.999957644551963866333120920, + -0.999957644551963866333120920, 0.009203754782059819315102378, + 0.999957644551963866333120920, 0.009203754782059819315102378, + -0.009203754782059819315102378, 0.999957644551963866333120920, + 0.700568793943248366792866380, 0.713584868780793592903125099, + -0.713584868780793592903125099, 0.700568793943248366792866380, + 0.920318276709110566440076541, 0.391170384302253888687512949, + -0.391170384302253888687512949, 0.920318276709110566440076541, + 0.374164062971457997104393020, 0.927362525650401087274536959, + -0.927362525650401087274536959, 0.374164062971457997104393020, + 0.978948175319062194715480124, 0.204108966092816874181696950, + -0.204108966092816874181696950, 0.978948175319062194715480124, + 0.547894059173100165608820571, 0.836547727223511984524285790, + -0.836547727223511984524285790, 0.547894059173100165608820571, + 0.826321062845663480311195452, 0.563199344013834115007363772, + -0.563199344013834115007363772, 0.826321062845663480311195452, + 0.186055151663446648105438304, 0.982539302287441255907040396, + -0.982539302287441255907040396, 0.186055151663446648105438304, + 0.994240449453187946358413442, 0.107172424956808849175529148, + -0.107172424956808849175529148, 0.994240449453187946358413442, + 0.627251815495144113509622565, 0.778816512381475953374724325, + -0.778816512381475953374724325, 0.627251815495144113509622565, + 0.877545290207261291668470750, 0.479493757660153026679839798, + -0.479493757660153026679839798, 0.877545290207261291668470750, + 0.281464937925757984095231007, 0.959571513081984528335528181, + -0.959571513081984528335528181, 0.281464937925757984095231007, + 0.954228095109105629780430732, 0.299079826308040476750336973, + -0.299079826308040476750336973, 0.954228095109105629780430732, + 0.463259783551860197390719637, 0.886222530148880631647990821, + -0.886222530148880631647990821, 0.463259783551860197390719637, + 0.767138911935820381181694573, 0.641481012808583151988739898, + -0.641481012808583151988739898, 0.767138911935820381181694573, + 0.088853552582524596561586535, 0.996044700901251989887944810, + -0.996044700901251989887944810, 0.088853552582524596561586535, + 0.998301544933892840738782163, 0.058258264500435759613979782, + -0.058258264500435759613979782, 0.998301544933892840738782163, + 0.664710978203344868130324985, 0.747100605980180144323078847, + -0.747100605980180144323078847, 0.664710978203344868130324985, + 0.900015892016160228714535267, 0.435857079922255491032544080, + -0.435857079922255491032544080, 0.900015892016160228714535267, + 0.328209843579092526107916817, 0.944604837261480265659265493, + -0.944604837261480265659265493, 0.328209843579092526107916817, + 0.967753837093475465243391912, 0.251897818154216950498106628, + -0.251897818154216950498106628, 0.967753837093475465243391912, + 0.506186645345155291048942344, 0.862423956111040538690933878, + -0.862423956111040538690933878, 0.506186645345155291048942344, + 0.797690840943391108362662755, 0.603066598540348201693430617, + -0.603066598540348201693430617, 0.797690840943391108362662755, + 0.137620121586486044948441663, 0.990485084256457037998682243, + -0.990485084256457037998682243, 0.137620121586486044948441663, + 0.987784141644572154230969032, 0.155828397654265235743101486, + -0.155828397654265235743101486, 0.987784141644572154230969032, + 0.588281548222645304786439813, 0.808656181588174991946968128, + -0.808656181588174991946968128, 0.588281548222645304786439813, + 0.852960604930363657746588082, 0.521975292937154342694258318, + -0.521975292937154342694258318, 0.852960604930363657746588082, + 0.234041958583543423191242045, 0.972226497078936305708321144, + -0.972226497078936305708321144, 0.234041958583543423191242045, + 0.938403534063108112192420774, 0.345541324963989065539191723, + -0.345541324963989065539191723, 0.938403534063108112192420774, + 0.419216888363223956433010020, 0.907886116487666212038681480, + -0.907886116487666212038681480, 0.419216888363223956433010020, + 0.734738878095963464563223604, 0.678350043129861486873655042, + -0.678350043129861486873655042, 0.734738878095963464563223604, + 0.039872927587739811128578738, 0.999204758618363895492950001, + -0.999204758618363895492950001, 0.039872927587739811128578738, + 0.999430604555461772019008327, 0.033741171851377584833716112, + -0.033741171851377584833716112, 0.999430604555461772019008327, + 0.682845546385248068164596123, 0.730562769227827561177758850, + -0.730562769227827561177758850, 0.682845546385248068164596123, + 0.910441292258067196934095369, 0.413638312238434547471944324, + -0.413638312238434547471944324, 0.910441292258067196934095369, + 0.351292756085567125601307623, 0.936265667170278246576310996, + -0.936265667170278246576310996, 0.351292756085567125601307623, + 0.973644249650811925318383912, 0.228072083170885739254457379, + -0.228072083170885739254457379, 0.973644249650811925318383912, + 0.527199134781901348464274575, 0.849741768000852489471268395, + -0.849741768000852489471268395, 0.527199134781901348464274575, + 0.812250586585203913049744181, 0.583308652937698294392830961, + -0.583308652937698294392830961, 0.812250586585203913049744181, + 0.161886393780111837641387995, 0.986809401814185476970235952, + -0.986809401814185476970235952, 0.161886393780111837641387995, + 0.991310859846115418957349799, 0.131540028702883111103387493, + -0.131540028702883111103387493, 0.991310859846115418957349799, + 0.607949784967773667243642671, 0.793975477554337164895083757, + -0.793975477554337164895083757, 0.607949784967773667243642671, + 0.865513624090569082825488358, 0.500885382611240786241285004, + -0.500885382611240786241285004, 0.865513624090569082825488358, + 0.257831102162159005614471295, 0.966190003445412555433832961, + -0.966190003445412555433832961, 0.257831102162159005614471295, + 0.946600913083283570044599823, 0.322407678801069848384807478, + -0.322407678801069848384807478, 0.946600913083283570044599823, + 0.441371268731716692879988968, 0.897324580705418281231391836, + -0.897324580705418281231391836, 0.441371268731716692879988968, + 0.751165131909686411205819422, 0.660114342067420478559490747, + -0.660114342067420478559490747, 0.751165131909686411205819422, + 0.064382630929857460819324537, 0.997925286198596012623025462, + -0.997925286198596012623025462, 0.064382630929857460819324537, + 0.996571145790554847093566910, 0.082740264549375693111987083, + -0.082740264549375693111987083, 0.996571145790554847093566910, + 0.646176012983316364832802220, 0.763188417263381271704838297, + -0.763188417263381271704838297, 0.646176012983316364832802220, + 0.889048355854664562540777729, 0.457813303598877221904961155, + -0.457813303598877221904961155, 0.889048355854664562540777729, + 0.304929229735402406490728633, 0.952375012719765858529893608, + -0.952375012719765858529893608, 0.304929229735402406490728633, + 0.961280485811320641748659653, 0.275571819310958163076425168, + -0.275571819310958163076425168, 0.961280485811320641748659653, + 0.484869248000791101822951699, 0.874586652278176112634431897, + -0.874586652278176112634431897, 0.484869248000791101822951699, + 0.782650596166575738458949301, 0.622461279374149972519166721, + -0.622461279374149972519166721, 0.782650596166575738458949301, + 0.113270952177564349018228733, 0.993564135520595333782021697, + -0.993564135520595333782021697, 0.113270952177564349018228733, + 0.983662419211730274396237776, 0.180022901405699522679906590, + -0.180022901405699522679906590, 0.983662419211730274396237776, + 0.568258952670131549790548489, 0.822849781375826332046780034, + -0.822849781375826332046780034, 0.568258952670131549790548489, + 0.839893794195999504583383987, 0.542750784864515906586768661, + -0.542750784864515906586768661, 0.839893794195999504583383987, + 0.210111836880469621717489972, 0.977677357824509979943404762, + -0.977677357824509979943404762, 0.210111836880469621717489972, + 0.929640895843181265457918066, 0.368466829953372331712746222, + -0.368466829953372331712746222, 0.929640895843181265457918066, + 0.396809987416710328595290911, 0.917900775621390457642276297, + -0.917900775621390457642276297, 0.396809987416710328595290911, + 0.717870045055731736211325329, 0.696177131491462944788582591, + -0.696177131491462944788582591, 0.717870045055731736211325329, + 0.015339206284988101044151868, 0.999882347454212525633049627, + -0.999882347454212525633049627, 0.015339206284988101044151868, + 0.999769405351215321657617036, 0.021474080275469507418374898, + -0.021474080275469507418374898, 0.999769405351215321657617036, + 0.691759258364157774906734132, 0.722128193929215321243607198, + -0.722128193929215321243607198, 0.691759258364157774906734132, + 0.915448716088267819566431292, 0.402434650859418441082533934, + -0.402434650859418441082533934, 0.915448716088267819566431292, + 0.362755724367397216204854462, 0.931884265581668106718557199, + -0.931884265581668106718557199, 0.362755724367397216204854462, + 0.976369731330021149312732194, 0.216106797076219509948385131, + -0.216106797076219509948385131, 0.976369731330021149312732194, + 0.537587076295645482502214932, 0.843208239641845437161743865, + -0.843208239641845437161743865, 0.537587076295645482502214932, + 0.819347520076796960824689637, 0.573297166698042212820171239, + -0.573297166698042212820171239, 0.819347520076796960824689637, + 0.173983873387463827950700807, 0.984748501801904218556553176, + -0.984748501801904218556553176, 0.173983873387463827950700807, + 0.992850414459865090793563344, 0.119365214810991364593637790, + -0.119365214810991364593637790, 0.992850414459865090793563344, + 0.617647307937803932403979402, 0.786455213599085757522319464, + -0.786455213599085757522319464, 0.617647307937803932403979402, + 0.871595086655951034842481435, 0.490226483288291154229598449, + -0.490226483288291154229598449, 0.871595086655951034842481435, + 0.269668325572915106525464462, 0.962953266873683886347921481, + -0.962953266873683886347921481, 0.269668325572915106525464462, + 0.950486073949481721759926101, 0.310767152749611495835997250, + -0.310767152749611495835997250, 0.950486073949481721759926101, + 0.452349587233770874133026703, 0.891840709392342727796478697, + -0.891840709392342727796478697, 0.452349587233770874133026703, + 0.759209188978388033485525443, 0.650846684996380915068975573, + -0.650846684996380915068975573, 0.759209188978388033485525443, + 0.076623861392031492278332463, 0.997060070339482978987989949, + -0.997060070339482978987989949, 0.076623861392031492278332463, + 0.997511456140303459699448390, 0.070504573389613863027351471, + -0.070504573389613863027351471, 0.997511456140303459699448390, + 0.655492852999615385312679701, 0.755201376896536527598710756, + -0.755201376896536527598710756, 0.655492852999615385312679701, + 0.894599485631382678433072126, 0.446868840162374195353044389, + -0.446868840162374195353044389, 0.894599485631382678433072126, + 0.316593375556165867243047035, 0.948561349915730288158494826, + -0.948561349915730288158494826, 0.316593375556165867243047035, + 0.964589793289812723836432159, 0.263754678974831383611349322, + -0.263754678974831383611349322, 0.964589793289812723836432159, + 0.495565261825772531150266670, 0.868570705971340895340449876, + -0.868570705971340895340449876, 0.495565261825772531150266670, + 0.790230221437310055030217152, 0.612810082429409703935211936, + -0.612810082429409703935211936, 0.790230221437310055030217152, + 0.125454983411546238542336453, 0.992099313142191757112085445, + -0.992099313142191757112085445, 0.125454983411546238542336453, + 0.985797509167567424700995000, 0.167938294974731178054745536, + -0.167938294974731178054745536, 0.985797509167567424700995000, + 0.578313796411655563342245019, 0.815814410806733789010772660, + -0.815814410806733789010772660, 0.578313796411655563342245019, + 0.846490938774052078300544488, 0.532403127877197971442805218, + -0.532403127877197971442805218, 0.846490938774052078300544488, + 0.222093620973203534094094721, 0.975025345066994146844913468, + -0.975025345066994146844913468, 0.222093620973203534094094721, + 0.934092550404258914729877883, 0.357030961233430032614954036, + -0.357030961233430032614954036, 0.934092550404258914729877883, + 0.408044162864978680820747499, 0.912962190428398164628018233, + -0.912962190428398164628018233, 0.408044162864978680820747499, + 0.726359155084345976817494315, 0.687315340891759108199186948, + -0.687315340891759108199186948, 0.726359155084345976817494315, + 0.027608145778965741612354872, 0.999618822495178597116830637, + -0.999618822495178597116830637, 0.027608145778965741612354872, + 0.998941293186856850633930266, 0.046003182130914628814301788, + -0.046003182130914628814301788, 0.998941293186856850633930266, + 0.673829000378756060917568372, 0.738887324460615147933116508, + -0.738887324460615147933116508, 0.673829000378756060917568372, + 0.905296759318118774354048329, 0.424779681209108833357226189, + -0.424779681209108833357226189, 0.905296759318118774354048329, + 0.339776884406826857828825803, 0.940506070593268323787291309, + -0.940506070593268323787291309, 0.339776884406826857828825803, + 0.970772140728950302138169611, 0.240003022448741486568922365, + -0.240003022448741486568922365, 0.970772140728950302138169611, + 0.516731799017649881508753876, 0.856147328375194481019630732, + -0.856147328375194481019630732, 0.516731799017649881508753876, + 0.805031331142963597922659282, 0.593232295039799808047809426, + -0.593232295039799808047809426, 0.805031331142963597922659282, + 0.149764534677321517229695737, 0.988721691960323767604516485, + -0.988721691960323767604516485, 0.149764534677321517229695737, + 0.989622017463200834623694454, 0.143695033150294454819773349, + -0.143695033150294454819773349, 0.989622017463200834623694454, + 0.598160706996342311724958652, 0.801376171723140219430247777, + -0.801376171723140219430247777, 0.598160706996342311724958652, + 0.859301818357008404783582139, 0.511468850437970399504391001, + -0.511468850437970399504391001, 0.859301818357008404783582139, + 0.245955050335794611599924709, 0.969281235356548486048290738, + -0.969281235356548486048290738, 0.245955050335794611599924709, + 0.942573197601446879280758735, 0.333999651442009404650865481, + -0.333999651442009404650865481, 0.942573197601446879280758735, + 0.430326481340082633908199031, 0.902673318237258806751502391, + -0.902673318237258806751502391, 0.430326481340082633908199031, + 0.743007952135121693517362293, 0.669282588346636065720696366, + -0.669282588346636065720696366, 0.743007952135121693517362293, + 0.052131704680283321236358216, 0.998640218180265222418199049, + -0.998640218180265222418199049, 0.052131704680283321236358216, + 0.995480755491926941769171600, 0.094963495329638998938034312, + -0.094963495329638998938034312, 0.995480755491926941769171600, + 0.636761861236284230413943435, 0.771060524261813773200605759, + -0.771060524261813773200605759, 0.636761861236284230413943435, + 0.883363338665731594736308015, 0.468688822035827933697617870, + -0.468688822035827933697617870, 0.883363338665731594736308015, + 0.293219162694258650606608599, 0.956045251349996443270479823, + -0.956045251349996443270479823, 0.293219162694258650606608599, + 0.957826413027532890321037029, 0.287347459544729526477331841, + -0.287347459544729526477331841, 0.957826413027532890321037029, + 0.474100214650550014398580015, 0.880470889052160770806542929, + -0.880470889052160770806542929, 0.474100214650550014398580015, + 0.774953106594873878359129282, 0.632018735939809021909403706, + -0.632018735939809021909403706, 0.774953106594873878359129282, + 0.101069862754827824987887585, 0.994879330794805620591166107, + -0.994879330794805620591166107, 0.101069862754827824987887585, + 0.981379193313754574318224190, 0.192080397049892441679288205, + -0.192080397049892441679288205, 0.981379193313754574318224190, + 0.558118531220556115693702964, 0.829761233794523042469023765, + -0.829761233794523042469023765, 0.558118531220556115693702964, + 0.833170164701913186439915922, 0.553016705580027531764226988, + -0.553016705580027531764226988, 0.833170164701913186439915922, + 0.198098410717953586179324918, 0.980182135968117392690210009, + -0.980182135968117392690210009, 0.198098410717953586179324918, + 0.925049240782677590302371869, 0.379847208924051170576281147, + -0.379847208924051170576281147, 0.925049240782677590302371869, + 0.385516053843918864075607949, 0.922701128333878570437264227, + -0.922701128333878570437264227, 0.385516053843918864075607949, + 0.709272826438865651316533772, 0.704934080375904908852523758, + -0.704934080375904908852523758, 0.709272826438865651316533772, + 0.003067956762965976270145365, 0.999995293809576171511580126, + -0.999995293809576171511580126, 0.003067956762965976270145365 }; - p2_tab = new FalconFPR[]{ - new FalconFPR(2.00000000000), - new FalconFPR(1.00000000000), - new FalconFPR(0.50000000000), - new FalconFPR(0.25000000000), - new FalconFPR(0.12500000000), - new FalconFPR(0.06250000000), - new FalconFPR(0.03125000000), - new FalconFPR(0.01562500000), - new FalconFPR(0.00781250000), - new FalconFPR(0.00390625000), - new FalconFPR(0.00195312500) + fpr_p2_tab = new double[]{ + 2.00000000000, + 1.00000000000, + 0.50000000000, + 0.25000000000, + 0.12500000000, + 0.06250000000, + 0.03125000000, + 0.01562500000, + 0.00781250000, + 0.00390625000, + 0.00195312500 }; } FPREngine() { - this.fpr_q = new FalconFPR(12289.0); - this.fpr_inverse_of_q = new FalconFPR(1.0 / 12289.0); - this.fpr_inv_2sqrsigma0 = new FalconFPR(0.150865048875372721532312163019); - this.fpr_inv_sigma = inv_sigma; - this.fpr_sigma_min = sigma_min; - this.fpr_log2 = new FalconFPR(0.69314718055994530941723212146); - this.fpr_inv_log2 = new FalconFPR(1.4426950408889634073599246810); - this.fpr_bnorm_max = new FalconFPR(16822.4121); - this.fpr_zero = new FalconFPR(0.0); - this.fpr_one = new FalconFPR(1.0); - this.fpr_two = new FalconFPR(2.0); - this.fpr_onehalf = new FalconFPR(0.5); - this.fpr_invsqrt2 = new FalconFPR(0.707106781186547524400844362105); - this.fpr_invsqrt8 = new FalconFPR(0.353553390593273762200422181052); - this.fpr_ptwo31 = new FalconFPR(2147483648.0); - this.fpr_ptwo31m1 = new FalconFPR(2147483647.0); - this.fpr_mtwo31m1 = new FalconFPR(-2147483647.0); - this.fpr_ptwo63m1 = new FalconFPR(9223372036854775807.0); - this.fpr_mtwo63m1 = new FalconFPR(-9223372036854775807.0); - this.fpr_ptwo63 = new FalconFPR(9223372036854775808.0); - this.fpr_gm_tab = gm_tab; - this.fpr_p2_tab = p2_tab; + //this.fpr_inverse_of_q = 1.0 / 12289.0; + //this.fpr_inv_2sqrsigma0 = 0.150865048875372721532312163019; + //this.fpr_inv_sigma = inv_sigma; + //this.fpr_sigma_min = sigma_min; + //this.fpr_log2 = 0.69314718055994530941723212146; + //this.fpr_inv_log2 = 1.4426950408889634073599246810; + //this.fpr_bnorm_max = 16822.4121; +// this.fpr_zero = 0.0; +// this.fpr_one = 1.0; +// this.fpr_two = 2.0; + //this.fpr_onehalf = 0.5; +// this.fpr_invsqrt2 = 0.707106781186547524400844362105; +// this.fpr_invsqrt8 = 0.353553390593273762200422181052; +// this.fpr_ptwo31 = 2147483648.0; +// this.fpr_ptwo31m1 = 2147483647.0; +// this.fpr_mtwo31m1 = -2147483647.0; +// this.fpr_ptwo63m1 = 9223372036854775807.0; +// this.fpr_mtwo63m1 = -9223372036854775807.0; +// this.fpr_ptwo63 = 9223372036854775808.0; + //this.fpr_gm_tab = gm_tab; + //this.fpr_p2_tab = p2_tab; } - FalconFPR FPR(double v) - { - FalconFPR x = new FalconFPR(v); - return x; - } - - FalconFPR fpr_of(long i) - { - return FPR((double)i); - } +// static double fpr_of(long i) +// { +// return (double)i; +// } - final FalconFPR fpr_q; - final FalconFPR fpr_inverse_of_q; - final FalconFPR fpr_inv_2sqrsigma0; - final FalconFPR[] fpr_inv_sigma; - final FalconFPR[] fpr_sigma_min; - final FalconFPR fpr_log2; - final FalconFPR fpr_inv_log2; - final FalconFPR fpr_bnorm_max; - final FalconFPR fpr_zero; - final FalconFPR fpr_one; - final FalconFPR fpr_two; - final FalconFPR fpr_onehalf; - final FalconFPR fpr_invsqrt2; - final FalconFPR fpr_invsqrt8; - final FalconFPR fpr_ptwo31; - final FalconFPR fpr_ptwo31m1; - final FalconFPR fpr_mtwo31m1; - final FalconFPR fpr_ptwo63m1; - final FalconFPR fpr_mtwo63m1; - final FalconFPR fpr_ptwo63; - final FalconFPR[] fpr_gm_tab; - final FalconFPR[] fpr_p2_tab; + static final double fpr_q = 12289.0; + static final double fpr_inverse_of_q = 1.0 / 12289.0; + static final double fpr_inv_2sqrsigma0 = 0.150865048875372721532312163019; + static final double[] fpr_inv_sigma; + static final double[] fpr_sigma_min; + static final double fpr_log2 = 0.69314718055994530941723212146; + static final double fpr_inv_log2 = 1.4426950408889634073599246810; + static final double fpr_bnorm_max = 16822.4121; + static final double fpr_zero = 0.0; + static final double fpr_one = 1.0; + static final double fpr_two = 2.0; + static final double fpr_onehalf = 0.5; +// static final double fpr_invsqrt2 = 0.707106781186547524400844362105; +// static final double fpr_invsqrt8 = 0.353553390593273762200422181052; + static final double fpr_ptwo31 = 2147483648.0; + static final double fpr_ptwo31m1 = 2147483647.0; + static final double fpr_mtwo31m1 = -2147483647.0; + static final double fpr_ptwo63m1 = 9223372036854775807.0; + static final double fpr_mtwo63m1 = -9223372036854775807.0; + static final double fpr_ptwo63 = 9223372036854775808.0; + static final double[] fpr_gm_tab; + static final double[] fpr_p2_tab; - long - fpr_rint(FalconFPR x) + static long fpr_rint(double x) { /* * We do not want to use llrint() since it might be not @@ -1158,10 +1150,10 @@ FalconFPR fpr_of(long i) long sx, tx, rp, rn, m; int ub; - sx = (long)(x.v - 1.0); - tx = (long)x.v; - rp = (long)(x.v + 4503599627370496.0) - 4503599627370496l; - rn = (long)(x.v - 4503599627370496.0) + 4503599627370496l; + sx = (long)(x - 1.0); + tx = (long)x; + rp = (long)(x + 4503599627370496.0) - 4503599627370496L; + rn = (long)(x - 4503599627370496.0) + 4503599627370496L; /* * If tx >= 2^52 or tx < -2^52, then result is tx. @@ -1198,7 +1190,7 @@ FalconFPR fpr_of(long i) return tx | rn | rp; } - long fpr_floor(FalconFPR x) + static long fpr_floor(double x) { long r; @@ -1212,85 +1204,82 @@ long fpr_floor(FalconFPR x) * if it is false on a given arch, then chances are that the FPU * itself is not constant-time, making the point moot). */ - r = (long)x.v; - return r - (x.v < (double)r ? 1 : 0); + r = (long)x; + return r - (x < (double)r ? 1 : 0); } - long - fpr_trunc(FalconFPR x) - { - return (long)x.v; - } +// long +// fpr_trunc(double x) +// { +// return (long)x; +// } - FalconFPR - fpr_add(FalconFPR x, FalconFPR y) - { - return FPR(x.v + y.v); - } +// static double fpr_add(double x, double y) +// { +// return x + y; +// } - FalconFPR - fpr_sub(FalconFPR x, FalconFPR y) - { - return FPR(x.v - y.v); - } +// static double fpr_sub(double x, double y) +// { +// return x - y; +// } - FalconFPR - fpr_neg(FalconFPR x) - { - return FPR(-x.v); - } +// static double fpr_neg(double x) +// { +// return -x; +// } - FalconFPR - fpr_half(FalconFPR x) - { - return FPR(x.v * 0.5); - } +// static double +// fpr_half(double x) +// { +// return x * 0.5; +// } - FalconFPR - fpr_double(FalconFPR x) - { - return FPR(x.v + x.v); - } +// double +// fpr_double(double x) +// { +// return x + x; +// } - FalconFPR - fpr_mul(FalconFPR x, FalconFPR y) - { - return FPR(x.v * y.v); - } +// static double +// fpr_mul(double x, double y) +// { +// return x * y; +// } - FalconFPR - fpr_sqr(FalconFPR x) - { - return FPR(x.v * x.v); - } +// static double +// fpr_sqr(double x) +// { +// return x * x; +// } - FalconFPR - fpr_inv(FalconFPR x) - { - return FPR(1.0 / x.v); - } +// static double +// fpr_inv(double x) +// { +// return 1.0 / x; +// } - FalconFPR - fpr_div(FalconFPR x, FalconFPR y) - { - return FPR(x.v / y.v); - } +// double +// fpr_div(double x, double y) +// { +// return FPR(x / y); +// } - FalconFPR - fpr_sqrt(FalconFPR x) - { - return FPR(Math.sqrt(x.v)); - } +// static double +// fpr_sqrt(double x) +// { +// return Math.sqrt(x); +// } - boolean - fpr_lt(FalconFPR x, FalconFPR y) - { - return x.v < y.v; - } +// static boolean +// fpr_lt(double x, double y) +// { +// return x < y; +// } - long - fpr_expm_p63(FalconFPR x, FalconFPR ccs) + static long + fpr_expm_p63(double x, double ccs) { /* * Polynomial approximation of exp(-x) is taken from FACCT: @@ -1311,7 +1300,7 @@ long fpr_floor(FalconFPR x) double d, y; - d = x.v; + d = x; y = 0.000000002073772366009083061987; y = 0.000000025299506379442070029551 - y * d; y = 0.000000275607356160477811864927 - y * d; @@ -1325,7 +1314,7 @@ long fpr_floor(FalconFPR x) y = 0.500000000000019206858326015208 - y * d; y = 0.999999999999994892974086724280 - y * d; y = 1.000000000000000000000000000000 - y * d; - y *= ccs.v; - return (long)(y * fpr_ptwo63.v); + y *= ccs; + return (long)(y * fpr_ptwo63); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCodec.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCodec.java index 1452ccb849..271473d744 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCodec.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCodec.java @@ -2,15 +2,10 @@ class FalconCodec { - - FalconCodec() - { - } - /* see inner.h */ - int modq_encode( - byte[] srcout, int out, int max_out_len, - short[] srcx, int x, int logn) + static int modq_encode( + byte[] srcout, int max_out_len, + short[] srcx, int logn) { int n, out_len, u; int buf; @@ -20,7 +15,7 @@ int modq_encode( n = 1 << logn; for (u = 0; u < n; u++) { - if ((srcx[x + u] & 0x0000ffff) >= 12289) + if ((srcx[u] & 0x0000ffff) >= 12289) { return 0; } @@ -34,12 +29,12 @@ int modq_encode( { return 0; } - buf = out; + buf = 1; acc = 0; acc_len = 0; for (u = 0; u < n; u++) { - acc = (acc << 14) | (srcx[x + u] & 0xffff); + acc = (acc << 14) | (srcx[u] & 0xffff); acc_len += 14; while (acc_len >= 8) { @@ -55,9 +50,9 @@ int modq_encode( } /* see inner.h */ - int modq_decode( - short[] srcx, int x, int logn, - byte[] srcin, int in, int max_in_len) + static int modq_decode( + short[] srcx, int logn, + byte[] srcin, int max_in_len) { int n, in_len, u; int buf; @@ -70,7 +65,7 @@ int modq_decode( { return 0; } - buf = in; + buf = 0; acc = 0; acc_len = 0; u = 0; @@ -88,7 +83,7 @@ int modq_decode( { return 0; } - srcx[x + u] = (short)w; + srcx[u] = (short)w; u++; } } @@ -100,116 +95,116 @@ int modq_decode( } /* see inner.h */ - int trim_i16_encode( - byte[] srcout, int out, int max_out_len, - short[] srcx, int x, int logn, int bits) - { - int n, u, out_len; - int minv, maxv; - int buf; - int acc, mask; - int acc_len; - - n = 1 << logn; - maxv = (1 << (bits - 1)) - 1; - minv = -maxv; - for (u = 0; u < n; u++) - { - if (srcx[x + u] < minv || srcx[x + u] > maxv) - { - return 0; - } - } - out_len = ((n * bits) + 7) >> 3; - if (srcout == null) - { - return out_len; - } - if (out_len > max_out_len) - { - return 0; - } - buf = out; - acc = 0; - acc_len = 0; - mask = (1 << bits) - 1; - for (u = 0; u < n; u++) - { - acc = (acc << bits) | ((srcx[x + u] & 0xfff) & mask); - acc_len += bits; - while (acc_len >= 8) - { - acc_len -= 8; - srcout[buf++] = (byte)(acc >> acc_len); - } - } - if (acc_len > 0) - { - srcout[buf++] = (byte)(acc << (8 - acc_len)); - } - return out_len; - } +// int trim_i16_encode( +// byte[] srcout, int out, int max_out_len, +// short[] srcx, int x, int logn, int bits) +// { +// int n, u, out_len; +// int minv, maxv; +// int buf; +// int acc, mask; +// int acc_len; +// +// n = 1 << logn; +// maxv = (1 << (bits - 1)) - 1; +// minv = -maxv; +// for (u = 0; u < n; u++) +// { +// if (srcx[x + u] < minv || srcx[x + u] > maxv) +// { +// return 0; +// } +// } +// out_len = ((n * bits) + 7) >> 3; +// if (srcout == null) +// { +// return out_len; +// } +// if (out_len > max_out_len) +// { +// return 0; +// } +// buf = out; +// acc = 0; +// acc_len = 0; +// mask = (1 << bits) - 1; +// for (u = 0; u < n; u++) +// { +// acc = (acc << bits) | ((srcx[x + u] & 0xfff) & mask); +// acc_len += bits; +// while (acc_len >= 8) +// { +// acc_len -= 8; +// srcout[buf++] = (byte)(acc >> acc_len); +// } +// } +// if (acc_len > 0) +// { +// srcout[buf++] = (byte)(acc << (8 - acc_len)); +// } +// return out_len; +// } /* see inner.h */ - int trim_i16_decode( - short[] srcx, int x, int logn, int bits, - byte[] srcin, int in, int max_in_len) - { - int n, in_len; - int buf; - int u; - int acc, mask1, mask2; - int acc_len; - - n = 1 << logn; - in_len = ((n * bits) + 7) >> 3; - if (in_len > max_in_len) - { - return 0; - } - buf = in; - u = 0; - acc = 0; - acc_len = 0; - mask1 = (1 << bits) - 1; - mask2 = 1 << (bits - 1); - while (u < n) - { - acc = (acc << 8) | (srcin[buf++] & 0xff); - acc_len += 8; - while (acc_len >= bits && u < n) - { - int w; - - acc_len -= bits; - w = (acc >>> acc_len) & mask1; - w |= -(w & mask2); - if (w == -mask2) - { - /* - * The -2^(bits-1) value is forbidden. - */ - return 0; - } - w |= -(w & mask2); - srcx[x + u] = (short)w; - u++; - } - } - if ((acc & ((1 << acc_len) - 1)) != 0) - { - /* - * Extra bits in the last byte must be zero. - */ - return 0; - } - return in_len; - } +// int trim_i16_decode( +// short[] srcx, int x, int logn, int bits, +// byte[] srcin, int in, int max_in_len) +// { +// int n, in_len; +// int buf; +// int u; +// int acc, mask1, mask2; +// int acc_len; +// +// n = 1 << logn; +// in_len = ((n * bits) + 7) >> 3; +// if (in_len > max_in_len) +// { +// return 0; +// } +// buf = in; +// u = 0; +// acc = 0; +// acc_len = 0; +// mask1 = (1 << bits) - 1; +// mask2 = 1 << (bits - 1); +// while (u < n) +// { +// acc = (acc << 8) | (srcin[buf++] & 0xff); +// acc_len += 8; +// while (acc_len >= bits && u < n) +// { +// int w; +// +// acc_len -= bits; +// w = (acc >>> acc_len) & mask1; +// w |= -(w & mask2); +// if (w == -mask2) +// { +// /* +// * The -2^(bits-1) value is forbidden. +// */ +// return 0; +// } +// w |= -(w & mask2); +// srcx[x + u] = (short)w; +// u++; +// } +// } +// if ((acc & ((1 << acc_len) - 1)) != 0) +// { +// /* +// * Extra bits in the last byte must be zero. +// */ +// return 0; +// } +// return in_len; +// } /* see inner.h */ - int trim_i8_encode( + static int trim_i8_encode( byte[] srcout, int out, int max_out_len, - byte[] srcx, int x, int logn, int bits) + byte[] srcx, int logn, int bits) { int n, u, out_len; int minv, maxv; @@ -222,7 +217,7 @@ int trim_i8_encode( minv = -maxv; for (u = 0; u < n; u++) { - if (srcx[x + u] < minv || srcx[x + u] > maxv) + if (srcx[u] < minv || srcx[u] > maxv) { return 0; } @@ -242,7 +237,7 @@ int trim_i8_encode( mask = (1 << bits) - 1; for (u = 0; u < n; u++) { - acc = (acc << bits) | ((srcx[x + u] & 0xffff) & mask); + acc = (acc << bits) | ((srcx[u] & 0xffff) & mask); acc_len += bits; while (acc_len >= 8) { @@ -252,14 +247,14 @@ int trim_i8_encode( } if (acc_len > 0) { - srcout[buf++] = (byte)(acc << (8 - acc_len)); + srcout[buf] = (byte)(acc << (8 - acc_len)); } return out_len; } /* see inner.h */ - int trim_i8_decode( - byte[] srcx, int x, int logn, int bits, + static int trim_i8_decode( + byte[] srcx, int logn, int bits, byte[] srcin, int in, int max_in_len) { int n, in_len; @@ -298,7 +293,7 @@ int trim_i8_decode( */ return 0; } - srcx[x + u] = (byte)w; + srcx[u] = (byte)w; u++; } } @@ -313,9 +308,9 @@ int trim_i8_decode( } /* see inner.h */ - int comp_encode( - byte[] srcout, int out, int max_out_len, - short[] srcx, int x, int logn) + static int comp_encode( + byte[] srcout, int max_out_len, + short[] srcx, int logn) { int buf; int n, u, v; @@ -323,14 +318,14 @@ int comp_encode( int acc_len; n = 1 << logn; - buf = out; + buf = 0; /* * Make sure that all values are within the -2047..+2047 range. */ for (u = 0; u < n; u++) { - if (srcx[x + u] < -2047 || srcx[x + u] > +2047) + if (srcx[u] < -2047 || srcx[u] > 2047) { return 0; } @@ -349,7 +344,7 @@ int comp_encode( * sign bit. */ acc <<= 1; - t = srcx[x + u]; + t = srcx[u]; if (t < 0) { t = -t; @@ -419,9 +414,9 @@ int comp_encode( } /* see inner.h */ - int comp_decode( - short[] srcx, int x, int logn, - byte[] srcin, int in, int max_in_len) + static int comp_decode( + short[] srcx, int logn, + byte[] srcin, int max_in_len) { int buf; int n, u, v; @@ -429,7 +424,7 @@ int comp_decode( int acc_len; n = 1 << logn; - buf = in; + buf = 0; acc = 0; acc_len = 0; v = 0; @@ -486,7 +481,7 @@ int comp_decode( return 0; } - srcx[x + u] = (short)(s != 0 ? -m : m); + srcx[u] = (short)(s != 0 ? -m : m); } /* @@ -532,7 +527,7 @@ int comp_decode( * of max_fg_bits[] and max_FG_bits[] shall be greater than 8. */ - final byte[] max_fg_bits = { + static final byte[] max_fg_bits = { 0, /* unused */ 8, 8, @@ -546,7 +541,7 @@ int comp_decode( 5 }; - final byte[] max_FG_bits = { + static final byte[] max_FG_bits = { 0, /* unused */ 8, 8, @@ -588,18 +583,18 @@ int comp_decode( * in -2047..2047, i.e. 12 bits. */ - final byte[] max_sig_bits = { - 0, /* unused */ - 10, - 11, - 11, - 12, - 12, - 12, - 12, - 12, - 12, - 12 - }; +// final byte[] max_sig_bits = { +// 0, /* unused */ +// 10, +// 11, +// 11, +// 12, +// 12, +// 12, +// 12, +// 12, +// 12, +// 12 +// }; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCommon.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCommon.java index a4f266a8df..2a5c19ab42 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCommon.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconCommon.java @@ -1,13 +1,12 @@ package org.bouncycastle.pqc.crypto.falcon; +import org.bouncycastle.crypto.digests.SHAKEDigest; + class FalconCommon { - FalconCommon() - { - } /* see inner.h */ - void hash_to_point_vartime(SHAKE256 sc, short[] srcx, int x, int logn) + static void hash_to_point_vartime(SHAKEDigest sc, short[] srcx, int logn) { /* * This is the straightforward per-the-spec implementation. It @@ -20,251 +19,253 @@ void hash_to_point_vartime(SHAKE256 sc, short[] srcx, int x, int logn) * plaintexts). */ int n; - + int x = 0; n = 1 << logn; + byte[] buf = new byte[2]; while (n > 0) { - byte[] buf = new byte[2]; + int w; // unsigned // inner_shake256_extract(sc, (void *)buf, sizeof buf); - sc.inner_shake256_extract(buf, 0, 2); + sc.doOutput(buf, 0, 2); w = ((buf[0] & 0xff) << 8) | (buf[1] & 0xff); if (w < 61445) { - while (w >= 12289) - { - w -= 12289; - } +// while (w >= 12289) +// { +// w -= 12289; +// } + w %= 12289; srcx[x++] = (short)w; n--; } } } - void hash_to_point_ct( - SHAKE256 sc, - short[] srcx, int x, int logn, short[] srctmp, int tmp) - { - /* - * Each 16-bit sample is a value in 0..65535. The value is - * kept if it falls in 0..61444 (because 61445 = 5*12289) - * and rejected otherwise; thus, each sample has probability - * about 0.93758 of being selected. - * - * We want to oversample enough to be sure that we will - * have enough values with probability at least 1 - 2^(-256). - * Depending on degree N, this leads to the following - * required oversampling: - * - * logn n oversampling - * 1 2 65 - * 2 4 67 - * 3 8 71 - * 4 16 77 - * 5 32 86 - * 6 64 100 - * 7 128 122 - * 8 256 154 - * 9 512 205 - * 10 1024 287 - * - * If logn >= 7, then the provided temporary buffer is large - * enough. Otherwise, we use a stack buffer of 63 entries - * (i.e. 126 bytes) for the values that do not fit in tmp[]. - */ - - short overtab[] = { - 0, /* unused */ - 65, - 67, - 71, - 77, - 86, - 100, - 122, - 154, - 205, - 287 - }; - - int n, n2, u, m, p, over; - int tt1; - short[] tt2 = new short[63]; - - /* - * We first generate m 16-bit value. Values 0..n-1 go to x[]. - * Values n..2*n-1 go to tt1[]. Values 2*n and later go to tt2[]. - * We also reduce modulo q the values; rejected values are set - * to 0xFFFF. - */ - n = 1 << logn; - n2 = n << 1; - over = overtab[logn]; - m = n + over; - tt1 = tmp; - for (u = 0; u < m; u++) - { - byte[] buf = new byte[2]; - int w, wr; - - sc.inner_shake256_extract(buf, 0, buf.length); - w = ((buf[0] & 0xff) << 8) | (buf[1] & 0xff); - wr = w - (24578 & (((w - 24578) >>> 31) - 1)); - wr = wr - (24578 & (((wr - 24578) >>> 31) - 1)); - wr = wr - (12289 & (((wr - 12289) >>> 31) - 1)); - wr |= ((w - 61445) >>> 31) - 1; - if (u < n) - { - srcx[x + u] = (short)wr; - } - else if (u < n2) - { - srctmp[tt1 + u - n] = (short)wr; - } - else - { - tt2[u - n2] = (short)wr; - } - } - - /* - * Now we must "squeeze out" the invalid values. We do this in - * a logarithmic sequence of passes; each pass computes where a - * value should go, and moves it down by 'p' slots if necessary, - * where 'p' uses an increasing powers-of-two scale. It can be - * shown that in all cases where the loop decides that a value - * has to be moved down by p slots, the destination slot is - * "free" (i.e. contains an invalid value). - */ - for (p = 1; p <= over; p <<= 1) - { - int v; - - /* - * In the loop below: - * - * - v contains the index of the final destination of - * the value; it is recomputed dynamically based on - * whether values are valid or not. - * - * - u is the index of the value we consider ("source"); - * its address is s. - * - * - The loop may swap the value with the one at index - * u-p. The address of the swap destination is d. - */ - v = 0; - for (u = 0; u < m; u++) - { - int s, d; - int sp, dp; - int j, sv, dv, mk; - - if (u < n) - { - sp = 1; - s = x + u; - sv = srcx[s]; - } - else if (u < n2) - { - sp = 2; - s = tt1 + u - n; - sv = srctmp[s]; - } - else - { - sp = 3; - s = u - n2; - sv = tt2[s]; - } - - /* - * The value in sv should ultimately go to - * address v, i.e. jump back by u-v slots. - */ - j = u - v; - - /* - * We increment v for the next iteration, but - * only if the source value is valid. The mask - * 'mk' is -1 if the value is valid, 0 otherwise, - * so we _subtract_ mk. - */ - mk = (sv >>> 15) - 1; - v -= mk; - - /* - * In this loop we consider jumps by p slots; if - * u < p then there is nothing more to do. - */ - if (u < p) - { - continue; - } - - /* - * Destination for the swap: value at address u-p. - */ - if ((u - p) < n) - { - dp = 1; - d = x + u - p; - dv = srcx[d]; - } - else if ((u - p) < n2) - { - dp = 2; - d = tt1 + (u - p) - n; - dv = srctmp[d]; - } - else - { - dp = 3; - d = (u - p) - n2; - dv = tt2[d]; - } - - /* - * The swap should be performed only if the source - * is valid AND the jump j has its 'p' bit set. - */ - mk &= -(((j & p) + 0x1FF) >> 9); - if (sp == 1) - { - srcx[s] = (short)(sv ^ (mk & (sv ^ dv))); - } - else if (sp == 2) - { - srctmp[s] = (short)(sv ^ (mk & (sv ^ dv))); - } - else - { - tt2[s] = (short)(sv ^ (mk & (sv ^ dv))); - } - if (dp == 1) - { - srcx[d] = (short)(dv ^ (mk & (sv ^ dv))); - } - else if (dp == 2) - { - srctmp[d] = (short)(dv ^ (mk & (sv ^ dv))); - } - else - { - tt2[d] = (short)(dv ^ (mk & (sv ^ dv))); - } - } - } - } +// void hash_to_point_ct( +// SHAKE256 sc, +// short[] srcx, int x, int logn, short[] srctmp, int tmp) +// { +// /* +// * Each 16-bit sample is a value in 0..65535. The value is +// * kept if it falls in 0..61444 (because 61445 = 5*12289) +// * and rejected otherwise; thus, each sample has probability +// * about 0.93758 of being selected. +// * +// * We want to oversample enough to be sure that we will +// * have enough values with probability at least 1 - 2^(-256). +// * Depending on degree N, this leads to the following +// * required oversampling: +// * +// * logn n oversampling +// * 1 2 65 +// * 2 4 67 +// * 3 8 71 +// * 4 16 77 +// * 5 32 86 +// * 6 64 100 +// * 7 128 122 +// * 8 256 154 +// * 9 512 205 +// * 10 1024 287 +// * +// * If logn >= 7, then the provided temporary buffer is large +// * enough. Otherwise, we use a stack buffer of 63 entries +// * (i.e. 126 bytes) for the values that do not fit in tmp[]. +// */ +// +// short overtab[] = { +// 0, /* unused */ +// 65, +// 67, +// 71, +// 77, +// 86, +// 100, +// 122, +// 154, +// 205, +// 287 +// }; +// +// int n, n2, u, m, p, over; +// int tt1; +// short[] tt2 = new short[63]; +// +// /* +// * We first generate m 16-bit value. Values 0..n-1 go to x[]. +// * Values n..2*n-1 go to tt1[]. Values 2*n and later go to tt2[]. +// * We also reduce modulo q the values; rejected values are set +// * to 0xFFFF. +// */ +// n = 1 << logn; +// n2 = n << 1; +// over = overtab[logn]; +// m = n + over; +// tt1 = tmp; +// for (u = 0; u < m; u++) +// { +// byte[] buf = new byte[2]; +// int w, wr; +// +// sc.inner_shake256_extract(buf, 0, buf.length); +// w = ((buf[0] & 0xff) << 8) | (buf[1] & 0xff); +// wr = w - (24578 & (((w - 24578) >>> 31) - 1)); +// wr = wr - (24578 & (((wr - 24578) >>> 31) - 1)); +// wr = wr - (12289 & (((wr - 12289) >>> 31) - 1)); +// wr |= ((w - 61445) >>> 31) - 1; +// if (u < n) +// { +// srcx[x + u] = (short)wr; +// } +// else if (u < n2) +// { +// srctmp[tt1 + u - n] = (short)wr; +// } +// else +// { +// tt2[u - n2] = (short)wr; +// } +// } +// +// /* +// * Now we must "squeeze out" the invalid values. We do this in +// * a logarithmic sequence of passes; each pass computes where a +// * value should go, and moves it down by 'p' slots if necessary, +// * where 'p' uses an increasing powers-of-two scale. It can be +// * shown that in all cases where the loop decides that a value +// * has to be moved down by p slots, the destination slot is +// * "free" (i.e. contains an invalid value). +// */ +// for (p = 1; p <= over; p <<= 1) +// { +// int v; +// +// /* +// * In the loop below: +// * +// * - v contains the index of the final destination of +// * the value; it is recomputed dynamically based on +// * whether values are valid or not. +// * +// * - u is the index of the value we consider ("source"); +// * its address is s. +// * +// * - The loop may swap the value with the one at index +// * u-p. The address of the swap destination is d. +// */ +// v = 0; +// for (u = 0; u < m; u++) +// { +// int s, d; +// int sp, dp; +// int j, sv, dv, mk; +// +// if (u < n) +// { +// sp = 1; +// s = x + u; +// sv = srcx[s]; +// } +// else if (u < n2) +// { +// sp = 2; +// s = tt1 + u - n; +// sv = srctmp[s]; +// } +// else +// { +// sp = 3; +// s = u - n2; +// sv = tt2[s]; +// } +// +// /* +// * The value in sv should ultimately go to +// * address v, i.e. jump back by u-v slots. +// */ +// j = u - v; +// +// /* +// * We increment v for the next iteration, but +// * only if the source value is valid. The mask +// * 'mk' is -1 if the value is valid, 0 otherwise, +// * so we _subtract_ mk. +// */ +// mk = (sv >>> 15) - 1; +// v -= mk; +// +// /* +// * In this loop we consider jumps by p slots; if +// * u < p then there is nothing more to do. +// */ +// if (u < p) +// { +// continue; +// } +// +// /* +// * Destination for the swap: value at address u-p. +// */ +// if ((u - p) < n) +// { +// dp = 1; +// d = x + u - p; +// dv = srcx[d]; +// } +// else if ((u - p) < n2) +// { +// dp = 2; +// d = tt1 + (u - p) - n; +// dv = srctmp[d]; +// } +// else +// { +// dp = 3; +// d = (u - p) - n2; +// dv = tt2[d]; +// } +// +// /* +// * The swap should be performed only if the source +// * is valid AND the jump j has its 'p' bit set. +// */ +// mk &= -(((j & p) + 0x1FF) >> 9); +// if (sp == 1) +// { +// srcx[s] = (short)(sv ^ (mk & (sv ^ dv))); +// } +// else if (sp == 2) +// { +// srctmp[s] = (short)(sv ^ (mk & (sv ^ dv))); +// } +// else +// { +// tt2[s] = (short)(sv ^ (mk & (sv ^ dv))); +// } +// if (dp == 1) +// { +// srcx[d] = (short)(dv ^ (mk & (sv ^ dv))); +// } +// else if (dp == 2) +// { +// srctmp[d] = (short)(dv ^ (mk & (sv ^ dv))); +// } +// else +// { +// tt2[d] = (short)(dv ^ (mk & (sv ^ dv))); +// } +// } +// } +// } /* * Acceptance bound for the (squared) l2-norm of the signature depends * on the degree. This array is indexed by logn (1 to 10). These bounds * are _inclusive_ (they are equal to floor(beta^2)). */ - static final int l2bound[] = { + static final int[] l2bound = { 0, /* unused */ 101498, 208714, @@ -279,8 +280,7 @@ else if (dp == 2) }; /* see inner.h */ - int is_short( - short[] srcs1, int s1, short[] srcs2, int s2, int logn) + static int is_short(short[] srcs1, int s1, short[] srcs2, int logn) { /* * We use the l2-norm. Code below uses only 32-bit operations to @@ -300,7 +300,7 @@ int is_short( z = srcs1[s1 + u]; s += (z * z); ng |= s; - z = srcs2[s2 + u]; + z = srcs2[u]; s += (z * z); ng |= s; } @@ -310,8 +310,7 @@ int is_short( } /* see inner.h */ - int is_short_half( - int sqn, short[] srcs2, int s2, int logn) + static int is_short_half(int sqn, short[] srcs2, int logn) { int n, u; int ng; @@ -322,7 +321,7 @@ int is_short_half( { int z; - z = srcs2[s2 + u]; + z = srcs2[u]; sqn += (z * z); ng |= sqn; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconConversions.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconConversions.java deleted file mode 100644 index 873236ae08..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconConversions.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bouncycastle.pqc.crypto.falcon; - -class FalconConversions -{ - - FalconConversions() - { - } - - byte[] int_to_bytes(int x) - { - byte[] res = new byte[4]; - res[0] = (byte)(x >>> 0); - res[1] = (byte)(x >>> 8); - res[2] = (byte)(x >>> 16); - res[3] = (byte)(x >>> 24); - return res; - } - - int bytes_to_int(byte[] src, int pos) - { - int acc = 0; - acc = toUnsignedInt(src[pos + 0]) << 0 | - toUnsignedInt(src[pos + 1]) << 8 | - toUnsignedInt(src[pos + 2]) << 16 | - toUnsignedInt(src[pos + 3]) << 24; - return acc; - } - - int[] bytes_to_int_array(byte[] src, int pos, int num) - { - int[] res = new int[num]; - for (int i = 0; i < num; i++) - { - res[i] = bytes_to_int(src, pos + (4 * i)); - } - return res; - } - - byte[] long_to_bytes(long x) - { - byte[] res = new byte[8]; - res[0] = (byte)(x >>> 0); - res[1] = (byte)(x >>> 8); - res[2] = (byte)(x >>> 16); - res[3] = (byte)(x >>> 24); - res[4] = (byte)(x >>> 32); - res[5] = (byte)(x >>> 40); - res[6] = (byte)(x >>> 48); - res[7] = (byte)(x >>> 56); - return res; - } - - long bytes_to_long(byte[] src, int pos) - { - long acc = 0; - acc = toUnsignedLong(src[pos + 0]) << 0 | - toUnsignedLong(src[pos + 1]) << 8 | - toUnsignedLong(src[pos + 2]) << 16 | - toUnsignedLong(src[pos + 3]) << 24 | - toUnsignedLong(src[pos + 4]) << 32 | - toUnsignedLong(src[pos + 5]) << 40 | - toUnsignedLong(src[pos + 6]) << 48 | - toUnsignedLong(src[pos + 7]) << 56; - return acc; - } - - private int toUnsignedInt(byte b) - { - return b & 0xff; - } - - private long toUnsignedLong(byte b) - { - return b & 0xffL; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFFT.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFFT.java index bbd72a54f0..adb338947a 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFFT.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFFT.java @@ -2,95 +2,58 @@ class FalconFFT { - FPREngine fpr; - - FalconFFT() - { - fpr = new FPREngine(); - } +// FalconFFT() +// { +// } // complex number functions - ComplexNumberWrapper FPC_ADD(FalconFPR a_re, FalconFPR a_im, FalconFPR b_re, FalconFPR b_im) - { - FalconFPR fpct_re, fpct_im; - fpct_re = fpr.fpr_add(a_re, b_re); - fpct_im = fpr.fpr_add(a_im, b_im); - return new ComplexNumberWrapper(fpct_re, fpct_im); - } - - ComplexNumberWrapper FPC_SUB(FalconFPR a_re, FalconFPR a_im, FalconFPR b_re, FalconFPR b_im) - { - FalconFPR fpct_re, fpct_im; - fpct_re = fpr.fpr_sub(a_re, b_re); - fpct_im = fpr.fpr_sub(a_im, b_im); - return new ComplexNumberWrapper(fpct_re, fpct_im); - } - - ComplexNumberWrapper FPC_MUL(FalconFPR a_re, FalconFPR a_im, FalconFPR b_re, FalconFPR b_im) - { - FalconFPR fpct_a_re, fpct_a_im; - FalconFPR fpct_b_re, fpct_b_im; - FalconFPR fpct_d_re, fpct_d_im; - fpct_a_re = (a_re); - fpct_a_im = (a_im); - fpct_b_re = (b_re); - fpct_b_im = (b_im); - fpct_d_re = fpr.fpr_sub( - fpr.fpr_mul(fpct_a_re, fpct_b_re), - fpr.fpr_mul(fpct_a_im, fpct_b_im)); - fpct_d_im = fpr.fpr_add( - fpr.fpr_mul(fpct_a_re, fpct_b_im), - fpr.fpr_mul(fpct_a_im, fpct_b_re)); - return new ComplexNumberWrapper(fpct_d_re, fpct_d_im); - } - - ComplexNumberWrapper FPC_SQR(FalconFPR a_re, FalconFPR a_im) - { - FalconFPR fpct_a_re, fpct_a_im; - FalconFPR fpct_d_re, fpct_d_im; - fpct_a_re = (a_re); - fpct_a_im = (a_im); - fpct_d_re = fpr.fpr_sub(fpr.fpr_sqr(fpct_a_re), fpr.fpr_sqr(fpct_a_im)); - fpct_d_im = fpr.fpr_double(fpr.fpr_mul(fpct_a_re, fpct_a_im)); - return new ComplexNumberWrapper(fpct_d_re, fpct_d_im); - } - - ComplexNumberWrapper FPC_INV(FalconFPR a_re, FalconFPR a_im) - { - FalconFPR fpct_a_re, fpct_a_im; - FalconFPR fpct_d_re, fpct_d_im; - FalconFPR fpct_m; - fpct_a_re = (a_re); - fpct_a_im = (a_im); - fpct_m = fpr.fpr_add(fpr.fpr_sqr(fpct_a_re), fpr.fpr_sqr(fpct_a_im)); - fpct_m = fpr.fpr_inv(fpct_m); - fpct_d_re = fpr.fpr_mul(fpct_a_re, fpct_m); - fpct_d_im = fpr.fpr_mul(fpr.fpr_neg(fpct_a_im), fpct_m); - return new ComplexNumberWrapper(fpct_d_re, fpct_d_im); - } - - ComplexNumberWrapper FPC_DIV(FalconFPR a_re, FalconFPR a_im, FalconFPR b_re, FalconFPR b_im) - { - FalconFPR fpct_a_re, fpct_a_im; - FalconFPR fpct_b_re, fpct_b_im; - FalconFPR fpct_d_re, fpct_d_im; - FalconFPR fpct_m; - fpct_a_re = (a_re); - fpct_a_im = (a_im); - fpct_b_re = (b_re); - fpct_b_im = (b_im); - fpct_m = fpr.fpr_add(fpr.fpr_sqr(fpct_b_re), fpr.fpr_sqr(fpct_b_im)); - fpct_m = fpr.fpr_inv(fpct_m); - fpct_b_re = fpr.fpr_mul(fpct_b_re, fpct_m); - fpct_b_im = fpr.fpr_mul(fpr.fpr_neg(fpct_b_im), fpct_m); - fpct_d_re = fpr.fpr_sub( - fpr.fpr_mul(fpct_a_re, fpct_b_re), - fpr.fpr_mul(fpct_a_im, fpct_b_im)); - fpct_d_im = fpr.fpr_add( - fpr.fpr_mul(fpct_a_re, fpct_b_im), - fpr.fpr_mul(fpct_a_im, fpct_b_re)); - return new ComplexNumberWrapper(fpct_d_re, fpct_d_im); - } +// static ComplexNumberWrapper FPC_ADD(double a_re, double a_im, double b_re, double b_im) +// { +// return new ComplexNumberWrapper(a_re + b_re, a_im + b_im); +// } +// +// static ComplexNumberWrapper FPC_SUB(double a_re, double a_im, double b_re, double b_im) +// { +// return new ComplexNumberWrapper(a_re - b_re, a_im - b_im); +// } + +// static ComplexNumberWrapper FPC_MUL(double a_re, double a_im, double b_re, double b_im) +// { +// return new ComplexNumberWrapper(a_re * b_re - a_im * b_im, a_re * b_im + a_im * b_re); +// } + +// ComplexNumberWrapper FPC_SQR(double a_re, double a_im) +// { +// double fpct_a_re, fpct_a_im; +// double fpct_d_re, fpct_d_im; +// fpct_a_re = (a_re); +// fpct_a_im = (a_im); +// fpct_d_re = FPREngine.fpr_sub(FPREngine.fpr_sqr(fpct_a_re), FPREngine.fpr_sqr(fpct_a_im)); +// fpct_d_im = FPREngine.fpr_double(FPREngine.fpr_mul(fpct_a_re, fpct_a_im)); +// return new ComplexNumberWrapper(fpct_d_re, fpct_d_im); +// } + +// ComplexNumberWrapper FPC_INV(double a_re, double a_im) +// { +// double fpct_a_re, fpct_a_im; +// double fpct_d_re, fpct_d_im; +// double fpct_m; +// fpct_a_re = (a_re); +// fpct_a_im = (a_im); +// fpct_m = FPREngine.fpr_add(FPREngine.fpr_sqr(fpct_a_re), FPREngine.fpr_sqr(fpct_a_im)); +// fpct_m = FPREngine.fpr_inv(fpct_m); +// fpct_d_re = FPREngine.fpr_mul(fpct_a_re, fpct_m); +// fpct_d_im = FPREngine.fpr_mul(FPREngine.fpr_neg(fpct_a_im), fpct_m); +// return new ComplexNumberWrapper(fpct_d_re, fpct_d_im); +// } + +// static ComplexNumberWrapper FPC_DIV(double a_re, double a_im, double b_re, double b_im) +// { +// double fpct_m = 1.0 / (b_re * b_re + b_im * b_im); +// b_re = b_re * fpct_m; +// b_im = -b_im * fpct_m; +// return new ComplexNumberWrapper(a_re * b_re - a_im * b_im, a_re * b_im + a_im * b_re); +// } /* * Let w = exp(i*pi/N); w is a primitive 2N-th root of 1. We define the @@ -117,7 +80,7 @@ ComplexNumberWrapper FPC_DIV(FalconFPR a_re, FalconFPR a_im, FalconFPR b_re, Fal */ /* see inner.h */ - void FFT(FalconFPR[] srcf, int f, int logn) + static void FFT(double[] srcf, int f, int logn) { /* * FFT algorithm in bit-reversal order uses the following @@ -165,41 +128,33 @@ void FFT(FalconFPR[] srcf, int f, int logn) n = 1 << logn; hn = n >> 1; t = hn; + int ht, hm, i1, j1; + int j2, fj, fjhn, fjht, fjhthn; + double s_re, s_im; + double x_re, x_im, y_re, y_im, a_re, a_im; for (u = 1, m = 2; u < logn; u++, m <<= 1) { - int ht, hm, i1, j1; - ht = t >> 1; hm = m >> 1; for (i1 = 0, j1 = 0; i1 < hm; i1++, j1 += t) { - int j, j2; - - j2 = j1 + ht; - FalconFPR s_re, s_im; - - s_re = fpr.fpr_gm_tab[((m + i1) << 1) + 0]; - s_im = fpr.fpr_gm_tab[((m + i1) << 1) + 1]; - for (j = j1; j < j2; j++) + j2 = j1 + ht + f; + fj = ((m + i1) << 1); + s_re = FPREngine.fpr_gm_tab[fj]; + s_im = FPREngine.fpr_gm_tab[fj + 1]; + for (fj = f + j1, fjhn = fj + hn, fjht = fj + ht, fjhthn = fjht + hn; fj < j2; + fj++, fjhn++, fjht++, fjhthn++) { - FalconFPR x_re, x_im, y_re, y_im; - ComplexNumberWrapper res; - - x_re = srcf[f + j]; - x_im = srcf[f + j + hn]; - y_re = srcf[f + j + ht]; - y_im = srcf[f + j + ht + hn]; - res = FPC_MUL(y_re, y_im, s_re, s_im); - y_re = res.re; - y_im = res.im; - - res = FPC_ADD(x_re, x_im, y_re, y_im); - srcf[f + j] = res.re; - srcf[f + j + hn] = res.im; - - res = FPC_SUB(x_re, x_im, y_re, y_im); - srcf[f + j + ht] = res.re; - srcf[f + j + ht + hn] = res.im; + x_re = srcf[fj]; + x_im = srcf[fjhn]; + a_re = srcf[fjht]; + a_im = srcf[fjhthn]; + y_re = a_re * s_re - a_im * s_im; + y_im = a_re * s_im + a_im * s_re; + srcf[fj] = x_re + y_re; + srcf[fjhn] = x_im + y_im; + srcf[fjht] = x_re - y_re; + srcf[fjhthn] = x_im - y_im; } } t = ht; @@ -207,7 +162,7 @@ void FFT(FalconFPR[] srcf, int f, int logn) } /* see inner.h */ - void iFFT(FalconFPR[] srcf, int f, int logn) + static void iFFT(double[] srcf, int f, int logn) { /* * Inverse FFT algorithm in bit-reversal order uses the following @@ -252,46 +207,37 @@ void iFFT(FalconFPR[] srcf, int f, int logn) * division into a division by N/2, not N. */ int u, n, hn, t, m; - + int dt, hm, i1, j1; + int j2, fj, fjhn, fjt, fjthn; + double s_re, s_im; + double x_re, x_im, y_re, y_im; n = 1 << logn; t = 1; m = n; hn = n >> 1; for (u = logn; u > 1; u--) { - int hm, dt, i1, j1; - hm = m >> 1; dt = t << 1; for (i1 = 0, j1 = 0; j1 < hn; i1++, j1 += dt) { - int j, j2; - - j2 = j1 + t; - FalconFPR s_re, s_im; - - s_re = fpr.fpr_gm_tab[((hm + i1) << 1) + 0]; - s_im = fpr.fpr_neg(fpr.fpr_gm_tab[((hm + i1) << 1) + 1]); - for (j = j1; j < j2; j++) + j2 = j1 + t + f; + fj = (hm + i1) << 1; + s_re = FPREngine.fpr_gm_tab[fj]; + s_im = -FPREngine.fpr_gm_tab[fj + 1]; + for (fj = f + j1, fjhn = fj + hn, fjt = fj + t, fjthn = fjt + hn; fj < j2; + fj++, fjhn++, fjt++, fjthn++) { - FalconFPR x_re, x_im, y_re, y_im; - ComplexNumberWrapper res; - - x_re = srcf[f + j]; - x_im = srcf[f + j + hn]; - y_re = srcf[f + j + t]; - y_im = srcf[f + j + t + hn]; - res = FPC_ADD(x_re, x_im, y_re, y_im); - srcf[f + j] = res.re; - srcf[f + j + hn] = res.im; - - res = FPC_SUB(x_re, x_im, y_re, y_im); - x_re = res.re; - x_im = res.im; - - res = FPC_MUL(x_re, x_im, s_re, s_im); - srcf[f + j + t] = res.re; - srcf[f + j + t + hn] = res.im; + x_re = srcf[fj]; + x_im = srcf[fjhn]; + y_re = srcf[fjt]; + y_im = srcf[fjthn]; + srcf[fj] = x_re + y_re; + srcf[fjhn] = x_im + y_im; + x_re -= y_re; + x_im -= y_im; + srcf[fjt] = x_re * s_re - x_im * s_im; + srcf[fjthn] = x_re * s_im + x_im * s_re; } } t = dt; @@ -304,114 +250,108 @@ void iFFT(FalconFPR[] srcf, int f, int logn) */ if (logn > 0) { - FalconFPR ni; + double ni; - ni = fpr.fpr_p2_tab[logn]; + ni = FPREngine.fpr_p2_tab[logn]; for (u = 0; u < n; u++) { - srcf[f + u] = fpr.fpr_mul(srcf[f + u], ni); + srcf[f + u] = srcf[f + u] * ni; } } } /* see inner.h */ - void poly_add( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_add( + double[] srca, int a, double[] srcb, int b, int logn) { int n, u; n = 1 << logn; for (u = 0; u < n; u++) { - srca[a + u] = fpr.fpr_add(srca[a + u], srcb[b + u]); + srca[a + u] += srcb[b + u]; } } /* see inner.h */ - void poly_sub( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_sub( + double[] srca, int a, double[] srcb, int b, int logn) { int n, u; n = 1 << logn; for (u = 0; u < n; u++) { - srca[a + u] = fpr.fpr_sub(srca[a + u], srcb[b + u]); + srca[a + u] -= srcb[b + u]; } } /* see inner.h */ - void poly_neg(FalconFPR[] srca, int a, int logn) + static void poly_neg(double[] srca, int a, int logn) { int n, u; n = 1 << logn; for (u = 0; u < n; u++) { - srca[a + u] = fpr.fpr_neg(srca[a + u]); + srca[a + u] = -srca[a + u]; } } /* see inner.h */ - void poly_adj_fft(FalconFPR[] srca, int a, int logn) + static void poly_adj_fft(double[] srca, int a, int logn) { int n, u; n = 1 << logn; for (u = (n >> 1); u < n; u++) { - srca[a + u] = fpr.fpr_neg(srca[a + u]); + srca[a + u] = -srca[a + u]; } } /* see inner.h */ - void poly_mul_fft( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_mul_fft( + double[] srca, int a, double[] srcb, int b, int logn) { int n, hn, u; n = 1 << logn; hn = n >> 1; - for (u = 0; u < hn; u++) + double a_re, a_im, b_re, b_im; + int au, auhn, bu; + for (u = 0, au = a, auhn = a + hn, bu = b; u < hn; u++, au++, bu++, auhn++) { - FalconFPR a_re, a_im, b_re, b_im; - ComplexNumberWrapper res; - - a_re = srca[a + u]; - a_im = srca[a + u + hn]; - b_re = srcb[b + u]; - b_im = srcb[b + u + hn]; - res = FPC_MUL(a_re, a_im, b_re, b_im); - srca[a + u] = res.re; - srca[a + u + hn] = res.im; + a_re = srca[au]; + a_im = srca[auhn]; + b_re = srcb[bu]; + b_im = srcb[bu + hn]; + srca[au] = a_re * b_re - a_im * b_im; + srca[auhn] = a_re * b_im + a_im * b_re; } } /* see inner.h */ - void poly_muladj_fft( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_muladj_fft( + double[] srca, int a, double[] srcb, int b, int logn) { - int n, hn, u; - + int n, hn, u, au; + double a_re, a_im, b_re, b_im; n = 1 << logn; hn = n >> 1; - for (u = 0; u < hn; u++) + for (u = 0, au = a; u < hn; u++, au++) { - FalconFPR a_re, a_im, b_re, b_im; - ComplexNumberWrapper res; - - a_re = srca[a + u]; - a_im = srca[a + u + hn]; + a_re = srca[au]; + a_im = srca[au + hn]; b_re = srcb[b + u]; - b_im = fpr.fpr_neg(srcb[b + u + hn]); - res = FPC_MUL(a_re, a_im, b_re, b_im); - srca[a + u] = res.re; - srca[a + u + hn] = res.im; + b_im = srcb[b + u + hn]; + srca[au] = a_re * b_re + a_im * b_im; + srca[au + hn] = a_im * b_re - a_re * b_im; } } /* see inner.h */ - void poly_mulselfadj_fft(FalconFPR[] srca, int a, int logn) + static void poly_mulselfadj_fft(double[] srca, int a, int logn) { /* * Since each coefficient is multiplied with its own conjugate, @@ -423,113 +363,108 @@ void poly_mulselfadj_fft(FalconFPR[] srca, int a, int logn) hn = n >> 1; for (u = 0; u < hn; u++) { - FalconFPR a_re, a_im; - ComplexNumberWrapper res; + double a_re, a_im; + //ComplexNumberWrapper res; a_re = srca[a + u]; a_im = srca[a + u + hn]; - srca[a + u] = fpr.fpr_add(fpr.fpr_sqr(a_re), fpr.fpr_sqr(a_im)); - srca[a + u + hn] = fpr.fpr_zero; + srca[a + u] = a_re * a_re + a_im * a_im; + srca[a + u + hn] = FPREngine.fpr_zero; } } /* see inner.h */ - void poly_mulconst(FalconFPR[] srca, int a, FalconFPR x, int logn) + static void poly_mulconst(double[] srca, int a, double x, int logn) { int n, u; n = 1 << logn; for (u = 0; u < n; u++) { - srca[a + u] = fpr.fpr_mul(srca[a + u], x); + srca[a + u] = srca[a + u] * x; } } /* see inner.h */ - void poly_div_fft( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) - { - int n, hn, u; - - n = 1 << logn; - hn = n >> 1; - for (u = 0; u < hn; u++) - { - FalconFPR a_re, a_im, b_re, b_im; - ComplexNumberWrapper res; - - a_re = srca[a + u]; - a_im = srca[a + u + hn]; - b_re = srcb[b + u]; - b_im = srcb[b + u + hn]; - res = FPC_DIV(a_re, a_im, b_re, b_im); - srca[a + u] = res.re; - srca[a + u + hn] = res.im; - } - } +// void poly_div_fft( +// double[] srca, int a, double[] srcb, int b, int logn) +// { +// int n, hn, u; +// +// n = 1 << logn; +// hn = n >> 1; +// for (u = 0; u < hn; u++) +// { +// double a_re, a_im, b_re, b_im; +// ComplexNumberWrapper res; +// +// a_re = srca[a + u]; +// a_im = srca[a + u + hn]; +// b_re = srcb[b + u]; +// b_im = srcb[b + u + hn]; +// res = FPC_DIV(a_re, a_im, b_re, b_im); +// srca[a + u] = res.re; +// srca[a + u + hn] = res.im; +// } +// } /* see inner.h */ - void poly_invnorm2_fft(FalconFPR[] srcd, int d, - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_invnorm2_fft(double[] srcd, int d, + double[] srca, int a, double[] srcb, int b, int logn) { int n, hn, u; - + double a_re, a_im; + double b_re, b_im; n = 1 << logn; hn = n >> 1; for (u = 0; u < hn; u++) { - FalconFPR a_re, a_im; - FalconFPR b_re, b_im; + a_re = srca[a + u]; a_im = srca[a + u + hn]; b_re = srcb[b + u]; b_im = srcb[b + u + hn]; - srcd[d + u] = fpr.fpr_inv(fpr.fpr_add( - fpr.fpr_add(fpr.fpr_sqr(a_re), fpr.fpr_sqr(a_im)), - fpr.fpr_add(fpr.fpr_sqr(b_re), fpr.fpr_sqr(b_im)))); + srcd[d + u] = 1.0 / (a_re * a_re + a_im * a_im + + b_re * b_re + b_im * b_im); } } /* see inner.h */ - void poly_add_muladj_fft(FalconFPR[] srcd, int d, - FalconFPR[] srcF, int F, FalconFPR[] srcG, int G, - FalconFPR[] srcf, int f, FalconFPR[] srcg, int g, int logn) + static void poly_add_muladj_fft(double[] srcd, + double[] srcF, double[] srcG, + double[] srcf, double[] srcg, int logn) { int n, hn, u; - + double F_re, F_im, G_re, G_im; + double f_re, f_im, g_re, g_im; + double a_re, a_im, b_re, b_im; n = 1 << logn; hn = n >> 1; for (u = 0; u < hn; u++) { - FalconFPR F_re, F_im, G_re, G_im; - FalconFPR f_re, f_im, g_re, g_im; - FalconFPR a_re, a_im, b_re, b_im; - ComplexNumberWrapper res; - - F_re = srcF[F + u]; - F_im = srcF[F + u + hn]; - G_re = srcG[G + u]; - G_im = srcG[G + u + hn]; - f_re = srcf[f + u]; - f_im = srcf[f + u + hn]; - g_re = srcg[g + u]; - g_im = srcg[g + u + hn]; - - res = FPC_MUL(F_re, F_im, f_re, fpr.fpr_neg(f_im)); - a_re = res.re; - a_im = res.im; - res = FPC_MUL(G_re, G_im, g_re, fpr.fpr_neg(g_im)); - b_re = res.re; - b_im = res.im; - srcd[d + u] = fpr.fpr_add(a_re, b_re); - srcd[d + u + hn] = fpr.fpr_add(a_im, b_im); + int uhn = u + hn; + F_re = srcF[u]; + F_im = srcF[uhn]; + G_re = srcG[u]; + G_im = srcG[uhn]; + f_re = srcf[u]; + f_im = srcf[uhn]; + g_re = srcg[u]; + g_im = srcg[uhn]; + + a_re = F_re * f_re + F_im * f_im; + a_im = F_im * f_re - F_re * f_im; + b_re = G_re * g_re + G_im * g_im; + b_im = G_im * g_re - G_re * g_im; + srcd[u] = a_re + b_re; + srcd[uhn] = a_im + b_im; } } /* see inner.h */ - void poly_mul_autoadj_fft( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_mul_autoadj_fft( + double[] srca, int a, double[] srcb, int b, int logn) { int n, hn, u; @@ -537,14 +472,14 @@ void poly_mul_autoadj_fft( hn = n >> 1; for (u = 0; u < hn; u++) { - srca[a + u] = fpr.fpr_mul(srca[a + u], srcb[b + u]); - srca[a + u + hn] = fpr.fpr_mul(srca[a + u + hn], srcb[b + u]); + srca[a + u] *= srcb[b + u]; + srca[a + u + hn] *= srcb[b + u]; } } /* see inner.h */ - void poly_div_autoadj_fft( - FalconFPR[] srca, int a, FalconFPR[] srcb, int b, int logn) + static void poly_div_autoadj_fft( + double[] srca, int a, double[] srcb, int b, int logn) { int n, hn, u; @@ -552,89 +487,85 @@ void poly_div_autoadj_fft( hn = n >> 1; for (u = 0; u < hn; u++) { - FalconFPR ib; - - ib = fpr.fpr_inv(srcb[b + u]); - srca[a + u] = fpr.fpr_mul(srca[a + u], ib); - srca[a + u + hn] = fpr.fpr_mul(srca[a + u + hn], ib); + double ib = 1.0 / srcb[b + u]; + srca[a + u] *= ib; + srca[a + u + hn] *= ib; } } /* see inner.h */ - void poly_LDL_fft( - FalconFPR[] srcg00, int g00, - FalconFPR[] srcg01, int g01, FalconFPR[] srcg11, int g11, int logn) + static void poly_LDL_fft( + double[] srcg00, int g00, + double[] srcg01, int g01, double[] srcg11, int g11, int logn) { - int n, hn, u; - + int n, hn, u, uhn, g01u, g01uhn; + double g00_re, g00_im, g01_re, g01_im, g11_re, g11_im; n = 1 << logn; hn = n >> 1; - for (u = 0; u < hn; u++) + for (u = 0, uhn = hn, g01u = g01, g01uhn = g01 + hn; + u < hn; u++, uhn++, g01u++, g01uhn++) { - FalconFPR g00_re, g00_im, g01_re, g01_im, g11_re, g11_im; - FalconFPR mu_re, mu_im; - ComplexNumberWrapper res; - g00_re = srcg00[g00 + u]; - g00_im = srcg00[g00 + u + hn]; - g01_re = srcg01[g01 + u]; - g01_im = srcg01[g01 + u + hn]; - g11_re = srcg11[g11 + u]; - g11_im = srcg11[g11 + u + hn]; - res = FPC_DIV(g01_re, g01_im, g00_re, g00_im); - mu_re = res.re; - mu_im = res.im; - res = FPC_MUL(mu_re, mu_im, g01_re, fpr.fpr_neg(g01_im)); - g01_re = res.re; - g01_im = res.im; - res = FPC_SUB(g11_re, g11_im, g01_re, g01_im); - srcg11[g11 + u] = res.re; - srcg11[g11 + u + hn] = res.im; - srcg01[g01 + u] = mu_re; - srcg01[g01 + u + hn] = fpr.fpr_neg(mu_im); + g00_im = srcg00[g00 + uhn]; + g01_re = srcg01[g01u]; + g01_im = srcg01[g01uhn]; + + g11_im = 1.0 / (g00_re * g00_re + g00_im * g00_im); + g11_re = g00_re * g11_im; + g11_im *= -g00_im; + g00_re = g01_re * g11_re - g01_im * g11_im; + g00_im = g01_re * g11_im + g01_im * g11_re; + g11_re = g01_re; + g11_im = g01_im; + g01_re = g00_re * g11_re + g00_im * g11_im; + g01_im = g00_re * -g11_im + g00_im * g11_re; + srcg11[g11 + u] -= g01_re; + srcg11[g11 + uhn] -= g01_im; + srcg01[g01u] = g00_re; + srcg01[g01uhn] = -g00_im; } } /* see inner.h */ - void poly_LDLmv_fft( - FalconFPR[] srcd11, int d11, FalconFPR[] srcl10, int l10, - FalconFPR[] srcg00, int g00, FalconFPR[] srcg01, int g01, - FalconFPR[] srcg11, int g11, int logn) - { - int n, hn, u; - - n = 1 << logn; - hn = n >> 1; - for (u = 0; u < hn; u++) - { - FalconFPR g00_re, g00_im, g01_re, g01_im, g11_re, g11_im; - FalconFPR mu_re, mu_im; - ComplexNumberWrapper res; - - g00_re = srcg00[g00 + u]; - g00_im = srcg00[g00 + u + hn]; - g01_re = srcg01[g01 + u]; - g01_im = srcg01[g01 + u + hn]; - g11_re = srcg11[g11 + u]; - g11_im = srcg11[g11 + u + hn]; - res = FPC_DIV(g01_re, g01_im, g00_re, g00_im); - mu_re = res.re; - mu_im = res.im; - res = FPC_MUL(mu_re, mu_im, g01_re, fpr.fpr_neg(g01_im)); - g01_re = res.re; - g01_im = res.im; - res = FPC_SUB(g11_re, g11_im, g01_re, g01_im); - srcd11[d11 + u] = res.re; - srcd11[d11 + u + hn] = res.im; - srcl10[l10 + u] = mu_re; - srcl10[l10 + u + hn] = fpr.fpr_neg(mu_im); - } - } +// void poly_LDLmv_fft( +// double[] srcd11, int d11, double[] srcl10, int l10, +// double[] srcg00, int g00, double[] srcg01, int g01, +// double[] srcg11, int g11, int logn) +// { +// int n, hn, u; +// +// n = 1 << logn; +// hn = n >> 1; +// for (u = 0; u < hn; u++) +// { +// double g00_re, g00_im, g01_re, g01_im, g11_re, g11_im; +// double mu_re, mu_im; +// ComplexNumberWrapper res; +// +// g00_re = srcg00[g00 + u]; +// g00_im = srcg00[g00 + u + hn]; +// g01_re = srcg01[g01 + u]; +// g01_im = srcg01[g01 + u + hn]; +// g11_re = srcg11[g11 + u]; +// g11_im = srcg11[g11 + u + hn]; +// res = FPC_DIV(g01_re, g01_im, g00_re, g00_im); +// mu_re = res.re; +// mu_im = res.im; +// res = FPC_MUL(mu_re, mu_im, g01_re, FPREngine.fpr_neg(g01_im)); +// g01_re = res.re; +// g01_im = res.im; +// res = FPC_SUB(g11_re, g11_im, g01_re, g01_im); +// srcd11[d11 + u] = res.re; +// srcd11[d11 + u + hn] = res.im; +// srcl10[l10 + u] = mu_re; +// srcl10[l10 + u + hn] = FPREngine.fpr_neg(mu_im); +// } +// } /* see inner.h */ - void poly_split_fft( - FalconFPR[] srcf0, int f0, FalconFPR[] srcf1, int f1, - FalconFPR[] srcf, int f, int logn) + static void poly_split_fft( + double[] srcf0, int f0, double[] srcf1, int f1, + double[] srcf, int f, int logn) { /* * The FFT representation we use is in bit-reversed order @@ -643,57 +574,52 @@ void poly_split_fft( * indexes with regards to the Falcon specification. */ int n, hn, qn, u; - + double a_re, a_im, b_re, b_im; + double t_re, t_im; n = 1 << logn; hn = n >> 1; qn = hn >> 1; - + int idx; /* * We process complex values by pairs. For logn = 1, there is only * one complex value (the other one is the implicit conjugate), * so we add the two lines below because the loop will be * skipped. */ - srcf0[f0 + 0] = srcf[f + 0]; - srcf1[f1 + 0] = srcf[f + hn]; + srcf0[f0] = srcf[f]; + srcf1[f1] = srcf[f + hn]; for (u = 0; u < qn; u++) { - FalconFPR a_re, a_im, b_re, b_im; - FalconFPR t_re, t_im; - ComplexNumberWrapper res; - - a_re = srcf[f + (u << 1) + 0]; - a_im = srcf[f + (u << 1) + 0 + hn]; - b_re = srcf[f + (u << 1) + 1]; - b_im = srcf[f + (u << 1) + 1 + hn]; - - res = FPC_ADD(a_re, a_im, b_re, b_im); - t_re = res.re; - t_im = res.im; - srcf0[f0 + u] = fpr.fpr_half(t_re); - srcf0[f0 + u + qn] = fpr.fpr_half(t_im); - - res = FPC_SUB(a_re, a_im, b_re, b_im); - t_re = res.re; - t_im = res.im; - res = FPC_MUL(t_re, t_im, - fpr.fpr_gm_tab[((u + hn) << 1) + 0], - fpr.fpr_neg(fpr.fpr_gm_tab[((u + hn) << 1) + 1])); - t_re = res.re; - t_im = res.im; - srcf1[f1 + u] = fpr.fpr_half(t_re); - srcf1[f1 + u + qn] = fpr.fpr_half(t_im); + idx = f + (u << 1); + a_re = srcf[idx]; + a_im = srcf[idx++ + hn]; + b_re = srcf[idx]; + b_im = srcf[idx + hn]; + + srcf0[f0 + u] = (a_re + b_re) * 0.5; + srcf0[f0 + u + qn] = (a_im + b_im) * 0.5; + + t_re = a_re - b_re; + t_im = a_im - b_im; + + idx = ((u + hn) << 1); + b_re = FPREngine.fpr_gm_tab[idx]; + b_im = -FPREngine.fpr_gm_tab[idx + 1]; + idx = f1 + u; + srcf1[idx] = (t_re * b_re - t_im * b_im) * 0.5; + srcf1[idx + qn] = (t_re * b_im + t_im * b_re) * 0.5; } } /* see inner.h */ - void poly_merge_fft( - FalconFPR[] srcf, int f, - FalconFPR[] srcf0, int f0, FalconFPR[] srcf1, int f1, int logn) + static void poly_merge_fft( + double[] srcf, int f, + double[] srcf0, int f0, double[] srcf1, int f1, int logn) { - int n, hn, qn, u; - + int n, hn, qn, u, idx; + double a_re, a_im, b_re, b_im; + double t_re, t_im; n = 1 << logn; hn = n >> 1; qn = hn >> 1; @@ -701,32 +627,30 @@ void poly_merge_fft( /* * An extra copy to handle the special case logn = 1. */ - srcf[f + 0] = srcf0[f0 + 0]; - srcf[f + hn] = srcf1[f1 + 0]; + srcf[f] = srcf0[f0]; + srcf[f + hn] = srcf1[f1]; for (u = 0; u < qn; u++) { - FalconFPR a_re, a_im, b_re, b_im; - FalconFPR t_re, t_im; - ComplexNumberWrapper res; - - a_re = srcf0[f0 + u]; - a_im = srcf0[f0 + u + qn]; - res = FPC_MUL(srcf1[f1 + u], srcf1[f1 + u + qn], - fpr.fpr_gm_tab[((u + hn) << 1) + 0], - fpr.fpr_gm_tab[((u + hn) << 1) + 1]); - b_re = res.re; - b_im = res.im; - res = FPC_ADD(a_re, a_im, b_re, b_im); - t_re = res.re; - t_im = res.im; - srcf[f + (u << 1) + 0] = t_re; - srcf[f + (u << 1) + 0 + hn] = t_im; - res = FPC_SUB(a_re, a_im, b_re, b_im); - t_re = res.re; - t_im = res.im; - srcf[f + (u << 1) + 1] = t_re; - srcf[f + (u << 1) + 1 + hn] = t_im; + idx = f1 + u; + a_re = srcf1[idx]; + a_im = srcf1[idx + qn]; + idx = ((u + hn) << 1); + t_re = FPREngine.fpr_gm_tab[idx]; + t_im = FPREngine.fpr_gm_tab[idx + 1]; + b_re = a_re * t_re - a_im * t_im; + b_im = a_re * t_im + a_im * t_re; + + idx = f0 + u; + a_re = srcf0[idx]; + a_im = srcf0[idx + qn]; + + idx = f + (u << 1); + srcf[idx] = a_re + b_re; + srcf[idx++ + hn] = a_im + b_im; + + srcf[idx] = a_re - b_re; + srcf[idx + hn] = a_im - b_im; } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFPR.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFPR.java deleted file mode 100644 index ec1f90343a..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconFPR.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bouncycastle.pqc.crypto.falcon; - -class FalconFPR -{ - double v; - - FalconFPR(double v) - { - this.v = v; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyGen.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyGen.java index 2932bc8c27..d1b26add7b 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyGen.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyGen.java @@ -1,20 +1,23 @@ package org.bouncycastle.pqc.crypto.falcon; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.util.Pack; + class FalconKeyGen { - FPREngine fpr; - FalconSmallPrimeList primes; - FalconFFT fft; - FalconCodec codec; - FalconVrfy vrfy; + // FPREngine fpr; + //FalconSmallPrimeList primes; + //FalconFFT fft; +// FalconCodec codec; +// FalconVrfy vrfy; FalconKeyGen() { - this.fpr = new FPREngine(); - this.primes = new FalconSmallPrimeList(); - this.fft = new FalconFFT(); - this.codec = new FalconCodec(); - this.vrfy = new FalconVrfy(); +// this.fpr = new FPREngine(); + //this.primes = new FalconSmallPrimeList(); + //this.fft = new FalconFFT(); +// this.codec = new FalconCodec(); +// this.vrfy = new FalconVrfy(); } private static int mkn(int logn) @@ -26,11 +29,9 @@ private static int mkn(int logn) * Reduce a small signed integer modulo a small prime. The source * value x MUST be such that -p < x < p. */ - int modp_set(int x, int p) + private static int modp_set(int x, int p) { - int w; - - w = x; + int w = x; w += p & -(w >>> 31); return w; } @@ -38,7 +39,7 @@ int modp_set(int x, int p) /* * Normalize a modular integer around 0. */ - int modp_norm(int x, int p) + private static int modp_norm(int x, int p) { return (x - (p & (((x - ((p + 1) >>> 1)) >>> 31) - 1))); } @@ -47,11 +48,9 @@ int modp_norm(int x, int p) * Compute -1/p mod 2^31. This works for all odd integers p that fit * on 31 bits. */ - int modp_ninv31(int p) + private static int modp_ninv31(int p) { - int y; - - y = 2 - p; + int y = 2 - p; y *= 2 - p * y; y *= 2 - p * y; y *= 2 - p * y; @@ -62,7 +61,7 @@ int modp_ninv31(int p) /* * Compute R = 2^31 mod p. */ - int modp_R(int p) + private static int modp_R(int p) { /* * Since 2^30 < p < 2^31, we know that 2^31 mod p is simply @@ -74,11 +73,9 @@ int modp_R(int p) /* * Addition modulo p. */ - int modp_add(int a, int b, int p) + private static int modp_add(int a, int b, int p) { - int d; - - d = a + b - p; + int d = a + b - p; d += p & -(d >>> 31); return d; } @@ -86,11 +83,9 @@ int modp_add(int a, int b, int p) /* * Subtraction modulo p. */ - int modp_sub(int a, int b, int p) + private static int modp_sub(int a, int b, int p) { - int d; - - d = a - b; + int d = a - b; d += p & -(d >>> 31); return d; } @@ -99,13 +94,13 @@ int modp_sub(int a, int b, int p) * Montgomery multiplication modulo p. The 'p0i' value is -1/p mod 2^31. * It is required that p is an odd integer. */ - int modp_montymul(int a, int b, int p, int p0i) + private static int modp_montymul(int a, int b, int p, int p0i) { long z, w; int d; z = toUnsignedLong(a) * toUnsignedLong(b); - w = ((z * p0i) & toUnsignedLong(0x7FFFFFFF)) * p; + w = ((z * p0i) & 0x7FFFFFFFL) * p; d = (int)((z + w) >>> 31) - p; d += p & -(d >>> 31); return d; @@ -114,7 +109,7 @@ int modp_montymul(int a, int b, int p, int p0i) /* * Compute R2 = 2^62 mod p. */ - int modp_R2(int p, int p0i) + private static int modp_R2(int p, int p0i) { int z; @@ -147,7 +142,7 @@ int modp_R2(int p, int p0i) * p must be prime such that 2^30 < p < 2^31; p0i must be equal to * -1/p mod 2^31; R2 must be equal to 2^62 mod p. */ - int modp_Rx(int x, int p, int p0i, int R2) + private static int modp_Rx(int x, int p, int p0i, int R2) { int i; int r, z; @@ -181,7 +176,7 @@ int modp_Rx(int x, int p, int p0i, int R2) * p0i -1/p mod 2^31 * R 2^31 mod R */ - int modp_div(int a, int b, int p, int p0i, int R) + private static int modp_div(int a, int b, int p, int p0i, int R) { int z, e; int i; @@ -215,7 +210,7 @@ int modp_div(int a, int b, int p, int p0i, int R) /* * Bit-reversal index table. */ - private short REV10[] = { + private static final short[] REV10 = { 0, 512, 256, 768, 128, 640, 384, 896, 64, 576, 320, 832, 192, 704, 448, 960, 32, 544, 288, 800, 160, 672, 416, 928, 96, 608, 352, 864, 224, 736, 480, 992, 16, 528, 272, 784, @@ -317,8 +312,8 @@ int modp_div(int a, int b, int p, int p0i, int R) * * p must be a prime such that p = 1 mod 2048. */ - void modp_mkgm2(int[] srcgm, int gm, int[] srcigm, int igm, int logn, - int g, int p, int p0i) + private static void modp_mkgm2(int[] srcgm, int gm, int[] srcigm, int igm, int logn, + int g, int p, int p0i) { int u, n; int k; @@ -356,8 +351,8 @@ void modp_mkgm2(int[] srcgm, int gm, int[] srcigm, int igm, int logn, * Compute the NTT over a polynomial (binary case). Polynomial elements * are a[0], a[stride], a[2 * stride]... */ - void modp_NTT2_ext(int[] srca, int a, int stride, int[] srcgm, int gm, int logn, - int p, int p0i) + private static void modp_NTT2_ext(int[] srca, int a, int stride, int[] srcgm, int gm, int logn, + int p, int p0i) { int t, m, n; @@ -398,8 +393,8 @@ void modp_NTT2_ext(int[] srca, int a, int stride, int[] srcgm, int gm, int logn, /* * Compute the inverse NTT over a polynomial (binary case). */ - void modp_iNTT2_ext(int[] srca, int a, int stride, int[] srcigm, int igm, int logn, - int p, int p0i) + private static void modp_iNTT2_ext(int[] srca, int a, int stride, int[] srcigm, int igm, int logn, + int p, int p0i) { int t, m, n, k; int ni; @@ -435,7 +430,6 @@ void modp_iNTT2_ext(int[] srca, int a, int stride, int[] srcigm, int igm, int lo srca[r1] = modp_add(x, y, p); srca[r2] = modp_montymul( modp_sub(x, y, p), s, p, p0i); - ; } } t = dt; @@ -458,13 +452,13 @@ void modp_iNTT2_ext(int[] srca, int a, int stride, int[] srcigm, int igm, int lo * are consecutive in RAM. */ // #define modp_NTT2(a, gm, logn, p, p0i) modp_NTT2_ext(a, 1, gm, logn, p, p0i) - void modp_NTT2(int[] srca, int a, int[] srcgm, int gm, int logn, int p, int p0i) + private static void modp_NTT2(int[] srca, int a, int[] srcgm, int gm, int logn, int p, int p0i) { modp_NTT2_ext(srca, a, 1, srcgm, gm, logn, p, p0i); } // #define modp_iNTT2(a, igm, logn, p, p0i) modp_iNTT2_ext(a, 1, igm, logn, p, p0i) - void modp_iNTT2(int[] srca, int a, int[] srcigm, int igm, int logn, int p, int p0i) + private static void modp_iNTT2(int[] srca, int a, int[] srcigm, int igm, int logn, int p, int p0i) { modp_iNTT2_ext(srca, a, 1, srcigm, igm, logn, p, p0i); } @@ -483,8 +477,8 @@ void modp_iNTT2(int[] srca, int a, int[] srcigm, int igm, int logn, int p, int p * This function applies only to the binary case; it is invoked from * solve_NTRU_binary_depth1(). */ - void modp_poly_rec_res(int[] srcf, int f, int logn, - int p, int p0i, int R2) + private static void modp_poly_rec_res(int[] srcf, int f, int logn, + int p, int p0i, int R2) { int hn, u; @@ -493,7 +487,7 @@ void modp_poly_rec_res(int[] srcf, int f, int logn, { int w0, w1; - w0 = srcf[f + (u << 1) + 0]; + w0 = srcf[f + (u << 1)]; w1 = srcf[f + (u << 1) + 1]; srcf[f + u] = modp_montymul(modp_montymul(w0, w1, p, p0i), R2, p, p0i); } @@ -540,32 +534,30 @@ void modp_poly_rec_res(int[] srcf, int f, int logn, * ctl = 0, the value a[] is unmodified, but all memory accesses are * still performed, and the carry is computed and returned. */ - int zint_sub(int[] srca, int a, int[] srcb, int b, int len, - int ctl) + private static void zint_sub(int[] srca, int a, int[] srcb, int b, int len, + int ctl) { int u; int cc, m; - + int aw, w, au; cc = 0; m = -ctl; for (u = 0; u < len; u++) { - int aw, w; - - aw = srca[a + u]; + au = a + u; + aw = srca[au]; w = aw - srcb[b + u] - cc; cc = w >>> 31; aw ^= ((w & 0x7FFFFFFF) ^ aw) & m; - srca[a + u] = aw; + srca[au] = aw; } - return cc; } /* * Mutiply the provided big integer m with a small value x. * This function assumes that x < 2^31. The carry word is returned. */ - int zint_mul_small(int[] srcm, int m, int mlen, int x) + private static int zint_mul_small(int[] srcm, int m, int mlen, int x) { int u; int cc; @@ -591,20 +583,17 @@ int zint_mul_small(int[] srcm, int m, int mlen, int x) * p0i = -(1/p) mod 2^31 * R2 = 2^62 mod p */ - int zint_mod_small_unsigned(int[] srcd, int d, int dlen, - int p, int p0i, int R2) + private static int zint_mod_small_unsigned(int[] srcd, int d, int dlen, + int p, int p0i, int R2) { - int x; - int u; - /* * Algorithm: we inject words one by one, starting with the high * word. Each step is: * - multiply x by 2^31 * - add new word */ - x = 0; - u = dlen; + int x = 0; + int u = dlen; while (u-- > 0) { int w; @@ -621,8 +610,8 @@ int zint_mod_small_unsigned(int[] srcd, int d, int dlen, * Similar to zint_mod_small_unsigned(), except that d may be signed. * Extra parameter is Rx = 2^(31*dlen) mod p. */ - int zint_mod_small_signed(int[] srcd, int d, int dlen, - int p, int p0i, int R2, int Rx) + private static int zint_mod_small_signed(int[] srcd, int d, int dlen, + int p, int p0i, int R2, int Rx) { int z; @@ -640,8 +629,8 @@ int zint_mod_small_signed(int[] srcd, int d, int dlen, * has length 'len+1' words. 's' must fit on 31 bits. x[] and y[] must * not overlap. */ - void zint_add_mul_small(int[] srcx, int x, - int[] srcy, int y, int len, int s) + private static void zint_add_mul_small(int[] srcx, int x, + int[] srcy, int y, int len, int s) { int u; int cc; @@ -666,7 +655,7 @@ void zint_add_mul_small(int[] srcx, int x, * with x - p (signed encoding with two's complement); otherwise, x is * untouched. The two integers x and p are encoded over the same length. */ - void zint_norm_zero(int[] srcx, int x, int[] srcp, int p, int len) + private static void zint_norm_zero(int[] srcx, int x, int[] srcp, int p, int len) { int u; int r, bb; @@ -727,14 +716,14 @@ void zint_norm_zero(int[] srcx, int x, int[] srcp, int p, int len) * normalized to the -m/2..m/2 interval (where m is the product of all * small prime moduli); two's complement is used for negative values. */ - void zint_rebuild_CRT(int[] srcxx, int xx, int xlen, int xstride, - int num, FalconSmallPrime[] primes, int normalize_signed, - int[] srctmp, int tmp) + private static void zint_rebuild_CRT(int[] srcxx, int xx, int xlen, int xstride, + int num, int normalize_signed, + int[] srctmp, int tmp) { int u; int x; - srctmp[tmp + 0] = primes[0].p; + srctmp[tmp] = FalconSmallPrimeList.PRIMES[0].p; for (u = 1; u < xlen; u++) { /* @@ -749,8 +738,8 @@ void zint_rebuild_CRT(int[] srcxx, int xx, int xlen, int xstride, int p, p0i, s, R2; int v; - p = primes[u].p; - s = primes[u].s; + p = FalconSmallPrimeList.PRIMES[u].p; + s = FalconSmallPrimeList.PRIMES[u].s; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); @@ -794,7 +783,7 @@ void zint_rebuild_CRT(int[] srcxx, int xx, int xlen, int xstride, * Negate a big integer conditionally: value a is replaced with -a if * and only if ctl = 1. Control value ctl must be 0 or 1. */ - void zint_negate(int[] srca, int a, int len, int ctl) + private static void zint_negate(int[] srca, int a, int len, int ctl) { int u; int cc, m; @@ -831,8 +820,8 @@ void zint_negate(int[] srca, int a, int len, int ctl) * * Coefficients xa, xb, ya and yb may use the full signed 32-bit range. */ - int zint_co_reduce(int[] srca, int a, int[] srcb, int b, int len, - long xa, long xb, long ya, long yb) + private static int zint_co_reduce(int[] srca, int a, int[] srcb, int b, int len, + long xa, long xb, long ya, long yb) { int u; long cca, ccb; @@ -879,7 +868,7 @@ int zint_co_reduce(int[] srca, int a, int[] srcb, int b, int len, * * Modulus m must be odd. */ - void zint_finish_mod(int[] srca, int a, int len, int[] srcm, int m, int neg) + private static void zint_finish_mod(int[] srca, int a, int len, int[] srcm, int m, int neg) { int u; int cc, xm, ym; @@ -923,8 +912,8 @@ void zint_finish_mod(int[] srca, int a, int len, int[] srcm, int m, int neg) * Replace a with (a*xa+b*xb)/(2^31) mod m, and b with * (a*ya+b*yb)/(2^31) mod m. Modulus m must be odd; m0i = -1/m[0] mod 2^31. */ - void zint_co_reduce_mod(int[] srca, int a, int[] srcb, int b, int[] srcm, int m, int len, - int m0i, long xa, long xb, long ya, long yb) + private static void zint_co_reduce_mod(int[] srca, int a, int[] srcb, int b, int[] srcm, int m, int len, + int m0i, long xa, long xb, long ya, long yb) { int u; long cca, ccb; @@ -935,8 +924,8 @@ void zint_co_reduce_mod(int[] srca, int a, int[] srcb, int b, int[] srcm, int m, */ cca = 0; ccb = 0; - fa = ((srca[a + 0] * (int)xa + srcb[b + 0] * (int)xb) * m0i) & 0x7FFFFFFF; - fb = ((srca[a + 0] * (int)ya + srcb[b + 0] * (int)yb) * m0i) & 0x7FFFFFFF; + fa = ((srca[a] * (int)xa + srcb[b] * (int)xb) * m0i) & 0x7FFFFFFF; + fb = ((srca[a] * (int)ya + srcb[b] * (int)yb) * m0i) & 0x7FFFFFFF; for (u = 0; u < len; u++) { int wa, wb; @@ -984,9 +973,9 @@ void zint_co_reduce_mod(int[] srca, int a, int[] srcb, int b, int[] srcm, int m, * extra values of that length. Arrays u, v and tmp may not overlap with * each other, or with either x or y. */ - int zint_bezout(int[] srcu, int u, int[] srcv, int v, - int[] srcx, int x, int[] srcy, int y, - int len, int[] srctmp, int tmp) + private static int zint_bezout(int[] srcu, int u, int[] srcv, int v, + int[] srcx, int x, int[] srcy, int y, + int len, int[] srctmp, int tmp) { /* * Algorithm is an extended binary GCD. We maintain 6 values @@ -1121,8 +1110,8 @@ int zint_bezout(int[] srcu, int u, int[] srcv, int v, /* * We'll need the Montgomery reduction coefficients. */ - x0i = modp_ninv31(srcx[x + 0]); - y0i = modp_ninv31(srcy[y + 0]); + x0i = modp_ninv31(srcx[x]); + y0i = modp_ninv31(srcy[y]); /* * Initialize a, b, u0, u1, v0 and v1. @@ -1135,10 +1124,10 @@ int zint_bezout(int[] srcu, int u, int[] srcv, int v, // memcpy(b, y, len * sizeof *y); System.arraycopy(srcy, y, srctmp, b, len); // u0[0] = 1; - srcu[u0 + 0] = 1; + srcu[u0] = 1; // memset(u0 + 1, 0, (len - 1) * sizeof *u0); // memset(v0, 0, len * sizeof *v0); - srcv[v0 + 0] = 0; + srcv[v0] = 0; for (int i = 1; i < len; i++) { srcu[u0 + i] = 0; @@ -1149,7 +1138,7 @@ int zint_bezout(int[] srcu, int u, int[] srcv, int v, // memcpy(v1, x, len * sizeof *v1); System.arraycopy(srcx, x, srctmp, v1, len); // v1[0] --; - srctmp[v1 + 0]--; + srctmp[v1]--; /* * Each input operand may be as large as 31*len bits, and we * reduce the total length by at least 30 bits at each iteration. @@ -1204,8 +1193,8 @@ int zint_bezout(int[] srcu, int u, int[] srcv, int v, b0 &= ~c1; a_hi = (toUnsignedLong(a0) << 31) + toUnsignedLong(a1); b_hi = (toUnsignedLong(b0) << 31) + toUnsignedLong(b1); - a_lo = srctmp[a + 0]; - b_lo = srctmp[b + 0]; + a_lo = srctmp[a]; + b_lo = srctmp[b]; /* * Compute reduction factors: @@ -1306,12 +1295,12 @@ int zint_bezout(int[] srcu, int u, int[] srcv, int v, * is indeed 1. We also check that the two operands x and y * are odd. */ - rc = srctmp[a + 0] ^ 1; + rc = srctmp[a] ^ 1; for (j = 1; j < len; j++) { rc |= srctmp[a + j]; } - return ((1 - ((rc | -rc) >>> 31)) & srcx[x + 0] & srcy[y + 0]); + return ((1 - ((rc | -rc) >>> 31)) & srcx[x] & srcy[y]); } /* @@ -1325,9 +1314,9 @@ int zint_bezout(int[] srcu, int u, int[] srcv, int v, * x[] and y[] are both signed integers, using two's complement for * negative values. */ - void zint_add_scaled_mul_small(int[] srcx, int x, int xlen, - int[] srcy, int y, int ylen, int k, - int sch, int scl) + private static void zint_add_scaled_mul_small(int[] srcx, int x, int xlen, + int[] srcy, int y, int ylen, int k, + int sch, int scl) { int u; int ysign, tw; @@ -1387,8 +1376,8 @@ void zint_add_scaled_mul_small(int[] srcx, int x, int xlen, * x[] and y[] are both signed integers, using two's complement for * negative values. */ - void zint_sub_scaled(int[] srcx, int x, int xlen, - int[] srcy, int y, int ylen, int sch, int scl) + private static void zint_sub_scaled(int[] srcx, int x, int xlen, + int[] srcy, int y, int ylen, int sch, int scl) { int u; int ysign, tw; @@ -1424,11 +1413,11 @@ void zint_sub_scaled(int[] srcx, int x, int xlen, /* * Convert a one-word signed big integer into a signed value. */ - int zint_one_to_plain(int[] srcx, int x) + private static int zint_one_to_plain(int[] srcx, int x) { int w; - w = srcx[x + 0]; + w = srcx[x]; w |= (w & 0x40000000) << 1; return w; } @@ -1446,8 +1435,8 @@ int zint_one_to_plain(int[] srcx, int x) * they should be "trimmed" by pointing not to the lowest word of each, * but upper. */ - void poly_big_to_fp(FalconFPR[] srcd, int d, int[] srcf, int f, int flen, int fstride, - int logn) + private static void poly_big_to_fp(double[] srcd, int[] srcf, int f, int flen, int fstride, + int logn) { int n, u; @@ -1456,7 +1445,7 @@ void poly_big_to_fp(FalconFPR[] srcd, int d, int[] srcf, int f, int flen, int fs { for (u = 0; u < n; u++) { - srcd[d + u] = fpr.fpr_zero; + srcd[u] = FPREngine.fpr_zero; } return; } @@ -1464,7 +1453,7 @@ void poly_big_to_fp(FalconFPR[] srcd, int d, int[] srcf, int f, int flen, int fs { int v; int neg, cc, xm; - FalconFPR x, fsc; + double x, fsc; /* * Get sign of the integer; if it is negative, then we @@ -1474,19 +1463,17 @@ void poly_big_to_fp(FalconFPR[] srcd, int d, int[] srcf, int f, int flen, int fs neg = -(srcf[f + flen - 1] >>> 30); xm = neg >>> 1; cc = neg & 1; - x = fpr.fpr_zero; - fsc = fpr.fpr_one; - for (v = 0; v < flen; v++, fsc = fpr.fpr_mul(fsc, fpr.fpr_ptwo31)) + x = FPREngine.fpr_zero; + fsc = FPREngine.fpr_one; + for (v = 0; v < flen; v++, fsc *= FPREngine.fpr_ptwo31) { - int w; - - w = (srcf[f + v] ^ xm) + cc; + int w = (srcf[f + v] ^ xm) + cc; cc = w >>> 31; w &= 0x7FFFFFFF; w -= (w << 1) & neg; - x = fpr.fpr_add(x, fpr.fpr_mul(fpr.fpr_of(w), fsc)); + x += w * fsc; } - srcd[d + u] = x; + srcd[u] = x; } } @@ -1500,7 +1487,7 @@ void poly_big_to_fp(FalconFPR[] srcd, int d, int[] srcf, int f, int flen, int fs * any failure, the NTRU-solving process will be deemed to have failed * and the (f,g) polynomials will be discarded. */ - int poly_big_to_small(byte[] srcd, int d, int[] srcs, int s, int lim, int logn) + private static int poly_big_to_small(byte[] srcd, int d, int[] srcs, int s, int lim, int logn) { int n, u; @@ -1529,9 +1516,9 @@ int poly_big_to_small(byte[] srcd, int d, int[] srcs, int s, int lim, int logn) * which is efficient in space (no extra buffer needed) but slow at * high degree. */ - void poly_sub_scaled(int[] srcF, int F, int Flen, int Fstride, - int[] srcf, int f, int flen, int fstride, - int[] srck, int k, int sch, int scl, int logn) + private static void poly_sub_scaled(int[] srcF, int F, int Flen, int Fstride, + int[] srcf, int f, int flen, int fstride, + int[] srck, int sch, int scl, int logn) { int n, u; @@ -1543,7 +1530,7 @@ void poly_sub_scaled(int[] srcF, int F, int Flen, int Fstride, int x; int y; - kf = -srck[k + u]; + kf = -srck[u]; x = F + u * Fstride; y = f; for (v = 0; v < n; v++) @@ -1570,15 +1557,15 @@ void poly_sub_scaled(int[] srcF, int F, int Flen, int Fstride, * assumes that the degree is large, and integers relatively small. * The value sc is provided as sch = sc / 31 and scl = sc % 31. */ - void poly_sub_scaled_ntt(int[] srcF, int F, int Flen, int Fstride, - int[] srcf, int f, int flen, int fstride, - int[] srck, int k, int sch, int scl, int logn, - int[] srctmp, int tmp) + private static void poly_sub_scaled_ntt(int[] srcF, int F, int Flen, int Fstride, + int[] srcf, int f, int flen, int fstride, + int[] srck, int sch, int scl, int logn, + int[] srctmp, int tmp) { int gm, igm, fk, t1, x; int y; int n, u, tlen; - FalconSmallPrime[] primes; +// FalconSmallPrime[] primes; n = mkn(logn); tlen = flen + 1; @@ -1587,7 +1574,7 @@ void poly_sub_scaled_ntt(int[] srcF, int F, int Flen, int Fstride, fk = igm + mkn(logn); t1 = fk + n * tlen; - primes = this.primes.PRIMES; +// primes = this.primes.PRIMES; /* * Compute k*f in fk[], in RNS notation. @@ -1597,15 +1584,15 @@ void poly_sub_scaled_ntt(int[] srcF, int F, int Flen, int Fstride, int p, p0i, R2, Rx; int v; - p = primes[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); Rx = modp_Rx(flen, p, p0i, R2); - modp_mkgm2(srctmp, gm, srctmp, igm, logn, primes[u].g, p, p0i); + modp_mkgm2(srctmp, gm, srctmp, igm, logn, FalconSmallPrimeList.PRIMES[u].g, p, p0i); for (v = 0; v < n; v++) { - srctmp[t1 + v] = modp_set(srck[k + v], p); + srctmp[t1 + v] = modp_set(srck[v], p); } modp_NTT2(srctmp, t1, srctmp, gm, logn, p, p0i); for (v = 0, y = f, x = fk + u; @@ -1625,7 +1612,7 @@ void poly_sub_scaled_ntt(int[] srcF, int F, int Flen, int Fstride, /* * Rebuild k*f. */ - zint_rebuild_CRT(srctmp, fk, tlen, tlen, n, primes, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, fk, tlen, tlen, n, 1, srctmp, t1); /* * Subtract k*f, scaled, from F. @@ -1644,7 +1631,7 @@ void poly_sub_scaled_ntt(int[] srcF, int F, int Flen, int Fstride, * the same values will be obtained over different platforms, in case * a known seed is used. */ - long get_rng_u64(SHAKE256 rng) + private static long get_rng_u64(SHAKEDigest rng) { /* * We enforce little-endian representation. @@ -1652,15 +1639,16 @@ long get_rng_u64(SHAKE256 rng) byte[] tmp = new byte[8]; - rng.inner_shake256_extract(tmp, 0, tmp.length); - return (tmp[0] & 0xffL) - | ((tmp[1] & 0xffL) << 8) - | ((tmp[2] & 0xffL) << 16) - | ((tmp[3] & 0xffL) << 24) - | ((tmp[4] & 0xffL) << 32) - | ((tmp[5] & 0xffL) << 40) - | ((tmp[6] & 0xffL) << 48) - | ((tmp[7] & 0xffL) << 56); + rng.doOutput(tmp, 0, tmp.length); + return Pack.littleEndianToLong(tmp, 0); +// return (tmp[0] & 0xffL) +// | ((tmp[1] & 0xffL) << 8) +// | ((tmp[2] & 0xffL) << 16) +// | ((tmp[3] & 0xffL) << 24) +// | ((tmp[4] & 0xffL) << 32) +// | ((tmp[5] & 0xffL) << 40) +// | ((tmp[6] & 0xffL) << 48) +// | ((tmp[7] & 0xffL) << 56); } @@ -1672,16 +1660,16 @@ long get_rng_u64(SHAKE256 rng) * For k > 0, element k is P(x >= k+1 | x > 0). * Probabilities are scaled up by 2^63. */ - final long[] gauss_1024_12289 = { - 1283868770400643928l, 6416574995475331444l, 4078260278032692663l, - 2353523259288686585l, 1227179971273316331l, 575931623374121527l, - 242543240509105209l, 91437049221049666l, 30799446349977173l, - 9255276791179340l, 2478152334826140l, 590642893610164l, - 125206034929641l, 23590435911403l, 3948334035941l, - 586753615614l, 77391054539l, 9056793210l, - 940121950l, 86539696l, 7062824l, - 510971l, 32764l, 1862l, - 94l, 4l, 0l + private static final long[] gauss_1024_12289 = { + 1283868770400643928L, 6416574995475331444L, 4078260278032692663L, + 2353523259288686585L, 1227179971273316331L, 575931623374121527L, + 242543240509105209L, 91437049221049666L, 30799446349977173L, + 9255276791179340L, 2478152334826140L, 590642893610164L, + 125206034929641L, 23590435911403L, 3948334035941L, + 586753615614L, 77391054539L, 9056793210L, + 940121950L, 86539696L, 7062824L, + 510971L, 32764L, 1862L, + 94L, 4L, 0L }; /* @@ -1694,7 +1682,7 @@ long get_rng_u64(SHAKE256 rng) * sigma*sqrt(2), then we can just generate more values and add them * together for lower dimensions. */ - int mkgauss(SHAKE256 rng, int logn) + private static int mkgauss(SHAKEDigest rng, int logn) { int u, g; int val; @@ -1728,7 +1716,7 @@ int mkgauss(SHAKE256 rng, int logn) */ r = get_rng_u64(rng); neg = (int)(r >>> 63); - r &= ~(1l << 63); + r &= ~(1L << 63); f = (int)((r - gauss_1024_12289[0]) >>> 63); /* @@ -1739,7 +1727,7 @@ int mkgauss(SHAKE256 rng, int logn) */ v = 0; r = get_rng_u64(rng); - r &= ~(1l << 63); + r &= ~(1L << 63); for (k = 1; k < gauss_1024_12289.length; k++) { int t; @@ -1819,11 +1807,11 @@ int mkgauss(SHAKE256 rng, int logn) * accordingly. */ - final int[] MAX_BL_SMALL = { + private static final int[] MAX_BL_SMALL = { 1, 1, 2, 2, 4, 7, 14, 27, 53, 106, 209 }; - final int[] MAX_BL_LARGE = { + private static final int[] MAX_BL_LARGE = { 2, 2, 5, 7, 12, 21, 40, 78, 157, 308 }; @@ -1832,7 +1820,7 @@ int mkgauss(SHAKE256 rng, int logn) * coefficients of (f,g), depending on depth. These values are used * to compute bounds for Babai's reduction. */ - final int[] bitlength_avg = { + private static final int[] bitlength_avg = { 4, 11, 24, @@ -1845,7 +1833,7 @@ int mkgauss(SHAKE256 rng, int logn) 3138, 6308 }; - final int[] bitlength_std = { + private static final int[] bitlength_std = { 0, 1, 1, @@ -1863,13 +1851,13 @@ int mkgauss(SHAKE256 rng, int logn) * Minimal recursion depth at which we rebuild intermediate values * when reconstructing f and g. */ - final int DEPTH_INT_FG = 4; + private static final int DEPTH_INT_FG = 4; /* * Compute squared norm of a short vector. Returned value is saturated to * 2^32-1 if it is not lower than 2^31. */ - int poly_small_sqnorm(byte[] srcf, int f, int logn) + private static int poly_small_sqnorm(byte[] srcf, int logn) { int n, u; int s, ng; @@ -1881,7 +1869,7 @@ int poly_small_sqnorm(byte[] srcf, int f, int logn) { int z; - z = srcf[f + u]; + z = srcf[u]; s += (z * z); ng |= s; } @@ -1891,14 +1879,14 @@ int poly_small_sqnorm(byte[] srcf, int f, int logn) /* * Convert a small vector to floating point. */ - void poly_small_to_fp(FalconFPR[] srcx, int x, byte[] srcf, int f, int logn) + private static void poly_small_to_fp(double[] srcx, int x, byte[] srcf, int logn) { int n, u; n = mkn(logn); for (u = 0; u < n; u++) { - srcx[x + u] = fpr.fpr_of(srcf[f + u]); + srcx[x + u] = srcf[u]; } } @@ -1910,19 +1898,19 @@ void poly_small_to_fp(FalconFPR[] srcx, int x, byte[] srcf, int f, int logn) * * Values are in RNS; input and/or output may also be in NTT. */ - void make_fg_step(int[] srcdata, int data, int logn, int depth, - int in_ntt, int out_ntt) + private static void make_fg_step(int[] srcdata, int data, int logn, int depth, + int in_ntt, int out_ntt) { int n, hn, u; int slen, tlen; int fd, gd, fs, gs, gm, igm, t1; - FalconSmallPrime[] primes; + //FalconSmallPrime[] primes; n = 1 << logn; hn = n >> 1; slen = MAX_BL_SMALL[depth]; tlen = MAX_BL_SMALL[depth + 1]; - primes = this.primes.PRIMES; + //primes = FalconSmallPrimeList.PRIMES; /* * Prepare room for the result. @@ -1947,10 +1935,10 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, int v; int x; - p = primes[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); - modp_mkgm2(srcdata, gm, srcdata, igm, logn, primes[u].g, p, p0i); + modp_mkgm2(srcdata, gm, srcdata, igm, logn, FalconSmallPrimeList.PRIMES[u].g, p, p0i); for (v = 0, x = fs + u; v < n; v++, x += slen) { @@ -1964,7 +1952,7 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, { int w0, w1; - w0 = srcdata[t1 + (v << 1) + 0]; + w0 = srcdata[t1 + (v << 1)]; w1 = srcdata[t1 + (v << 1) + 1]; srcdata[x] = modp_montymul( modp_montymul(w0, w1, p, p0i), R2, p, p0i); @@ -1986,7 +1974,7 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, { int w0, w1; - w0 = srcdata[t1 + (v << 1) + 0]; + w0 = srcdata[t1 + (v << 1)]; w1 = srcdata[t1 + (v << 1) + 1]; srcdata[x] = modp_montymul( modp_montymul(w0, w1, p, p0i), R2, p, p0i); @@ -2007,8 +1995,8 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, * Since the fs and gs words have been de-NTTized, we can use the * CRT to rebuild the values. */ - zint_rebuild_CRT(srcdata, fs, slen, slen, n, primes, 1, srcdata, gm); - zint_rebuild_CRT(srcdata, gs, slen, slen, n, primes, 1, srcdata, gm); + zint_rebuild_CRT(srcdata, fs, slen, slen, n, 1, srcdata, gm); + zint_rebuild_CRT(srcdata, gs, slen, slen, n, 1, srcdata, gm); /* * Remaining words: use modular reductions to extract the values. @@ -2019,11 +2007,11 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, int v; int x; - p = primes[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); Rx = modp_Rx(slen, p, p0i, R2); - modp_mkgm2(srcdata, gm, srcdata, igm, logn, primes[u].g, p, p0i); + modp_mkgm2(srcdata, gm, srcdata, igm, logn, FalconSmallPrimeList.PRIMES[u].g, p, p0i); for (v = 0, x = fs; v < n; v++, x += slen) { srcdata[t1 + v] = zint_mod_small_signed(srcdata, x, slen, p, p0i, R2, Rx); @@ -2033,7 +2021,7 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, { int w0, w1; - w0 = srcdata[t1 + (v << 1) + 0]; + w0 = srcdata[t1 + (v << 1)]; w1 = srcdata[t1 + (v << 1) + 1]; srcdata[x] = modp_montymul( modp_montymul(w0, w1, p, p0i), R2, p, p0i); @@ -2047,7 +2035,7 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, { int w0, w1; - w0 = srcdata[t1 + (v << 1) + 0]; + w0 = srcdata[t1 + (v << 1)]; w1 = srcdata[t1 + (v << 1) + 1]; srcdata[x] = modp_montymul( modp_montymul(w0, w1, p, p0i), R2, p, p0i); @@ -2069,23 +2057,23 @@ void make_fg_step(int[] srcdata, int data, int logn, int depth, * Space use in data[]: enough room for any two successive values (f', g', * f and g). */ - void make_fg(int[] srcdata, int data, byte[] srcf, int f, byte[] srcg, int g, - int logn, int depth, int out_ntt) + private static void make_fg(int[] srcdata, int data, byte[] srcf, byte[] srcg, + int logn, int depth, int out_ntt) { int n, u; int ft, gt, p0; int d; - FalconSmallPrime[] primes; + n = mkn(logn); ft = data; gt = ft + n; - primes = this.primes.PRIMES; - p0 = primes[0].p; + + p0 = FalconSmallPrimeList.PRIMES[0].p; for (u = 0; u < n; u++) { - srcdata[ft + u] = modp_set(srcf[f + u], p0); - srcdata[gt + u] = modp_set(srcg[g + u], p0); + srcdata[ft + u] = modp_set(srcf[u], p0); + srcdata[gt + u] = modp_set(srcg[u], p0); } if (depth == 0 && out_ntt != 0) @@ -2093,11 +2081,11 @@ void make_fg(int[] srcdata, int data, byte[] srcf, int f, byte[] srcg, int g, int gm, igm; int p, p0i; - p = primes[0].p; + p = FalconSmallPrimeList.PRIMES[0].p; p0i = modp_ninv31(p); gm = gt + n; igm = gm + n; - modp_mkgm2(srcdata, gm, srcdata, igm, logn, primes[0].g, p, p0i); + modp_mkgm2(srcdata, gm, srcdata, igm, logn, FalconSmallPrimeList.PRIMES[0].g, p, p0i); modp_NTT2(srcdata, ft, srcdata, gm, logn, p, p0i); modp_NTT2(srcdata, gt, srcdata, gm, logn, p, p0i); return; @@ -2117,30 +2105,30 @@ void make_fg(int[] srcdata, int data, byte[] srcf, int f, byte[] srcg, int g, * * Returned value: 1 on success, 0 on error. */ - int solve_NTRU_deepest(int logn_top, - byte[] srcf, int f, byte[] srcg, int g, int[] srctmp, int tmp) + private static int solve_NTRU_deepest(int logn_top, + byte[] srcf, byte[] srcg, int[] srctmp) { int len; int Fp, Gp, fp, gp, t1, q; - FalconSmallPrime[] primes; + //FalconSmallPrime[] primes; len = MAX_BL_SMALL[logn_top]; - primes = this.primes.PRIMES; + //primes = this.primes.PRIMES; - Fp = tmp; + Fp = 0; Gp = Fp + len; fp = Gp + len; gp = fp + len; t1 = gp + len; - make_fg(srctmp, fp, srcf, f, srcg, g, logn_top, logn_top, 0); + make_fg(srctmp, fp, srcf, srcg, logn_top, logn_top, 0); /* * We use the CRT to rebuild the resultants as big integers. * There are two such big integers. The resultants are always * nonnegative. */ - zint_rebuild_CRT(srctmp, fp, len, len, 2, primes, 0, srctmp, t1); + zint_rebuild_CRT(srctmp, fp, len, len, 2, 0, srctmp, t1); /* * Apply the binary GCD. The zint_bezout() function works only @@ -2179,8 +2167,8 @@ int solve_NTRU_deepest(int logn_top, * * Returned value: 1 on success, 0 on error. */ - int solve_NTRU_intermediate(int logn_top, - byte[] srcf, int f, byte[] srcg, int g, int depth, int[] srctmp, int tmp) + private static int solve_NTRU_intermediate(int logn_top, + byte[] srcf, byte[] srcg, int depth, int[] srctmp) { /* * In this function, 'logn' is the log2 of the degree for @@ -2192,11 +2180,11 @@ int solve_NTRU_intermediate(int logn_top, int logn; int n, hn, slen, dlen, llen, rlen, FGlen, u; int Fd, Gd, Ft, Gt, ft, gt, t1; - FalconFPR[] rt1, rt2, rt3, rt4, rt5; + double[] rt1, rt2, rt3, rt4, rt5; int scale_fg, minbl_fg, maxbl_fg, maxbl_FG, scale_k; int x, y; int[] k; - FalconSmallPrime[] primes; + //FalconSmallPrime[] primes; logn = logn_top - depth; n = 1 << logn; @@ -2217,12 +2205,12 @@ int solve_NTRU_intermediate(int logn_top, slen = MAX_BL_SMALL[depth]; dlen = MAX_BL_SMALL[depth + 1]; llen = MAX_BL_LARGE[depth]; - primes = this.primes.PRIMES; + //primes = this.primes.PRIMES; /* * Fd and Gd are the F and G from the deeper level. */ - Fd = tmp; + Fd = 0; Gd = Fd + dlen * hn; /* @@ -2230,28 +2218,30 @@ int solve_NTRU_intermediate(int logn_top, * and g in RNS + NTT representation. */ ft = Gd + dlen * hn; - make_fg(srctmp, ft, srcf, f, srcg, g, logn_top, depth, 1); + make_fg(srctmp, ft, srcf, srcg, logn_top, depth, 1); /* * Move the newly computed f and g to make room for our candidate * F and G (unreduced). */ - Ft = tmp; + Ft = 0; Gt = Ft + n * llen; t1 = Gt + n * llen; // memmove(t1, ft, 2 * n * slen * sizeof *ft); - System.arraycopy(srctmp, ft, srctmp, t1, 2 * n * slen); + int tmp = n * slen; + System.arraycopy(srctmp, ft, srctmp, t1, tmp + tmp); ft = t1; - gt = ft + slen * n; - t1 = gt + slen * n; + gt = ft + tmp; + t1 = gt + tmp; /* * Move Fd and Gd _after_ f and g. */ // memmove(t1, Fd, 2 * hn * dlen * sizeof *Fd); - System.arraycopy(srctmp, Fd, srctmp, t1, 2 * hn * dlen); + tmp = hn * dlen; + System.arraycopy(srctmp, Fd, srctmp, t1, tmp + tmp); Fd = t1; - Gd = Fd + hn * dlen; + Gd = Fd + tmp; /* * We reduce Fd and Gd modulo all the small primes we will need, @@ -2263,7 +2253,7 @@ int solve_NTRU_intermediate(int logn_top, int v; int xs, ys, xd, yd; - p = primes[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); Rx = modp_Rx(dlen, p, p0i, R2); @@ -2292,7 +2282,7 @@ int solve_NTRU_intermediate(int logn_top, /* * All computations are done modulo p. */ - p = primes[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); @@ -2302,8 +2292,8 @@ int solve_NTRU_intermediate(int logn_top, */ if (u == slen) { - zint_rebuild_CRT(srctmp, ft, slen, slen, n, primes, 1, srctmp, t1); - zint_rebuild_CRT(srctmp, gt, slen, slen, n, primes, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, ft, slen, slen, n, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, gt, slen, slen, n, 1, srctmp, t1); } gm = t1; @@ -2311,7 +2301,7 @@ int solve_NTRU_intermediate(int logn_top, fx = igm + n; gx = fx + n; - modp_mkgm2(srctmp, gm, srctmp, igm, logn, primes[u].g, p, p0i); + modp_mkgm2(srctmp, gm, srctmp, igm, logn, FalconSmallPrimeList.PRIMES[u].g, p, p0i); if (u < slen) { @@ -2393,15 +2383,15 @@ int solve_NTRU_intermediate(int logn_top, int ftA, ftB, gtA, gtB; int mFp, mGp; - ftA = srctmp[fx + (v << 1) + 0]; + ftA = srctmp[fx + (v << 1)]; ftB = srctmp[fx + (v << 1) + 1]; - gtA = srctmp[gx + (v << 1) + 0]; + gtA = srctmp[gx + (v << 1)]; gtB = srctmp[gx + (v << 1) + 1]; mFp = modp_montymul(srctmp[Fp + v], R2, p, p0i); mGp = modp_montymul(srctmp[Gp + v], R2, p, p0i); - srctmp[x + 0] = modp_montymul(gtB, mFp, p, p0i); + srctmp[x] = modp_montymul(gtB, mFp, p, p0i); srctmp[x + llen] = modp_montymul(gtA, mFp, p, p0i); - srctmp[y + 0] = modp_montymul(ftB, mGp, p, p0i); + srctmp[y] = modp_montymul(ftB, mGp, p, p0i); srctmp[y + llen] = modp_montymul(ftA, mGp, p, p0i); } modp_iNTT2_ext(srctmp, Ft + u, llen, srctmp, igm, logn, p, p0i); @@ -2411,8 +2401,8 @@ int solve_NTRU_intermediate(int logn_top, /* * Rebuild F and G with the CRT. */ - zint_rebuild_CRT(srctmp, Ft, llen, llen, n, primes, 1, srctmp, t1); - zint_rebuild_CRT(srctmp, Gt, llen, llen, n, primes, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, Ft, llen, llen, n, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, Gt, llen, llen, n, 1, srctmp, t1); /* * At that point, Ft, Gt, ft and gt are consecutive in RAM (in that @@ -2477,11 +2467,11 @@ int solve_NTRU_intermediate(int logn_top, * We ensure that the base is at a properly aligned offset (the * source array tmp[] is supposed to be already aligned). */ - rt1 = new FalconFPR[n]; - rt2 = new FalconFPR[n]; - rt3 = new FalconFPR[n]; - rt4 = new FalconFPR[n]; - rt5 = new FalconFPR[n >> 1]; + rt1 = new double[n]; + rt2 = new double[n]; + rt3 = new double[n]; + rt4 = new double[n]; + rt5 = new double[n >> 1]; k = new int[n]; /* @@ -2494,9 +2484,9 @@ int solve_NTRU_intermediate(int logn_top, * computed so that average maximum length will fall in the * middle or the upper half of these top 10 words. */ - rlen = (slen > 10) ? 10 : slen; - poly_big_to_fp(rt3, 0, srctmp, ft + slen - rlen, rlen, slen, logn); - poly_big_to_fp(rt4, 0, srctmp, gt + slen - rlen, rlen, slen, logn); + rlen = Math.min(slen, 10); + poly_big_to_fp(rt3, srctmp, ft + slen - rlen, rlen, slen, logn); + poly_big_to_fp(rt4, srctmp, gt + slen - rlen, rlen, slen, logn); /* * Values in rt3 and rt4 are downscaled by 2^(scale_fg). @@ -2516,11 +2506,11 @@ int solve_NTRU_intermediate(int logn_top, * Compute 1/(f*adj(f)+g*adj(g)) in rt5. We also keep adj(f) * and adj(g) in rt3 and rt4, respectively. */ - fft.FFT(rt3, 0, logn); - fft.FFT(rt4, 0, logn); - fft.poly_invnorm2_fft(rt5, 0, rt3, 0, rt4, 0, logn); - fft.poly_adj_fft(rt3, 0, logn); - fft.poly_adj_fft(rt4, 0, logn); + FalconFFT.FFT(rt3, 0, logn); + FalconFFT.FFT(rt4, 0, logn); + FalconFFT.poly_invnorm2_fft(rt5, 0, rt3, 0, rt4, 0, logn); + FalconFFT.poly_adj_fft(rt3, 0, logn); + FalconFFT.poly_adj_fft(rt4, 0, logn); /* * Reduce F and G repeatedly. @@ -2563,27 +2553,27 @@ int solve_NTRU_intermediate(int logn_top, { int scale_FG, dc, new_maxbl_FG; int scl, sch; - FalconFPR pdc, pt; + double pdc, pt; /* * Convert current F and G into floating-point. We apply * scaling if the current length is more than 10 words. */ - rlen = (FGlen > 10) ? 10 : FGlen; - scale_FG = 31 * (int)(FGlen - rlen); - poly_big_to_fp(rt1, 0, srctmp, Ft + FGlen - rlen, rlen, llen, logn); - poly_big_to_fp(rt2, 0, srctmp, Gt + FGlen - rlen, rlen, llen, logn); + rlen = Math.min(FGlen, 10); + scale_FG = 31 * (FGlen - rlen); + poly_big_to_fp(rt1, srctmp, Ft + FGlen - rlen, rlen, llen, logn); + poly_big_to_fp(rt2, srctmp, Gt + FGlen - rlen, rlen, llen, logn); /* * Compute (F*adj(f)+G*adj(g))/(f*adj(f)+g*adj(g)) in rt2. */ - fft.FFT(rt1, 0, logn); - fft.FFT(rt2, 0, logn); - fft.poly_mul_fft(rt1, 0, rt3, 0, logn); - fft.poly_mul_fft(rt2, 0, rt4, 0, logn); - fft.poly_add(rt2, 0, rt1, 0, logn); - fft.poly_mul_autoadj_fft(rt2, 0, rt5, 0, logn); - fft.iFFT(rt2, 0, logn); + FalconFFT.FFT(rt1, 0, logn); + FalconFFT.FFT(rt2, 0, logn); + FalconFFT.poly_mul_fft(rt1, 0, rt3, 0, logn); + FalconFFT.poly_mul_fft(rt2, 0, rt4, 0, logn); + FalconFFT.poly_add(rt2, 0, rt1, 0, logn); + FalconFFT.poly_mul_autoadj_fft(rt2, 0, rt5, 0, logn); + FalconFFT.iFFT(rt2, 0, logn); /* * (f,g) are scaled by 'scale_fg', meaning that the @@ -2611,28 +2601,26 @@ int solve_NTRU_intermediate(int logn_top, if (dc < 0) { dc = -dc; - pt = fpr.fpr_two; + pt = FPREngine.fpr_two; } else { - pt = fpr.fpr_onehalf; + pt = FPREngine.fpr_onehalf; } - pdc = fpr.fpr_one; + pdc = FPREngine.fpr_one; while (dc != 0) { if ((dc & 1) != 0) { - pdc = fpr.fpr_mul(pdc, pt); + pdc = pdc * pt; } dc >>= 1; - pt = fpr.fpr_sqr(pt); + pt *= pt; } for (u = 0; u < n; u++) { - FalconFPR xv; - - xv = fpr.fpr_mul(rt2[u], pdc); + double xv = rt2[u] * pdc; /* * Sometimes the values can be out-of-bounds if @@ -2643,12 +2631,12 @@ int solve_NTRU_intermediate(int logn_top, * failure here implies that we discard the current * secret key (f,g). */ - if (!fpr.fpr_lt(fpr.fpr_mtwo31m1, xv) - || !fpr.fpr_lt(xv, fpr.fpr_ptwo31m1)) + if (FPREngine.fpr_mtwo31m1 >= xv + || xv >= FPREngine.fpr_ptwo31m1) { return 0; } - k[u] = (int)fpr.fpr_rint(xv); + k[u] = (int)FPREngine.fpr_rint(xv); } /* @@ -2663,16 +2651,16 @@ int solve_NTRU_intermediate(int logn_top, if (depth <= DEPTH_INT_FG) { poly_sub_scaled_ntt(srctmp, Ft, FGlen, llen, srctmp, ft, slen, slen, - k, 0, sch, scl, logn, srctmp, t1); + k, sch, scl, logn, srctmp, t1); poly_sub_scaled_ntt(srctmp, Gt, FGlen, llen, srctmp, gt, slen, slen, - k, 0, sch, scl, logn, srctmp, t1); + k, sch, scl, logn, srctmp, t1); } else { poly_sub_scaled(srctmp, Ft, FGlen, llen, srctmp, ft, slen, slen, - k, 0, sch, scl, logn); + k, sch, scl, logn); poly_sub_scaled(srctmp, Gt, FGlen, llen, srctmp, gt, slen, slen, - k, 0, sch, scl, logn); + k, sch, scl, logn); } /* @@ -2735,7 +2723,7 @@ int solve_NTRU_intermediate(int logn_top, * Compress encoding of all values to 'slen' words (this is the * expected output format). */ - for (u = 0, x = tmp, y = tmp; + for (u = 0, x = 0, y = 0; u < (n << 1); u++, x += slen, y += llen) { // memmove(x, y, slen * sizeof *y); @@ -2750,8 +2738,8 @@ int solve_NTRU_intermediate(int logn_top, * * Returned value: 1 on success, 0 on error. */ - int solve_NTRU_binary_depth1(int logn_top, - byte[] srcf, int f, byte[] srcg, int g, int[] srctmp, int tmp) + private static int solve_NTRU_binary_depth1(int logn_top, + byte[] srcf, byte[] srcg, int[] srctmp) { /* * The first half of this function is a copy of the corresponding @@ -2764,7 +2752,7 @@ int solve_NTRU_binary_depth1(int logn_top, int depth, logn; int n_top, n, hn, slen, dlen, llen, u; int Fd, Gd, Ft, Gt, ft, gt, t1; - FalconFPR[] rt1, rt2, rt3, rt4, rt5, rt6; + double[] rt1, rt2, rt3, rt4, rt5, rt6; int x, y; depth = 1; @@ -2806,7 +2794,7 @@ int solve_NTRU_binary_depth1(int logn_top, * Fd and Gd are the F and G from the deeper level. Ft and Gt * are the destination arrays for the unreduced F and G. */ - Fd = tmp; + Fd = 0; Gd = Fd + dlen * hn; Ft = Gd + dlen * hn; Gt = Ft + llen * n; @@ -2821,7 +2809,7 @@ int solve_NTRU_binary_depth1(int logn_top, int v; int xs, ys, xd, yd; - p = this.primes.PRIMES[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); Rx = modp_Rx(dlen, p, p0i, R2); @@ -2838,8 +2826,8 @@ int solve_NTRU_binary_depth1(int logn_top, * Now Fd and Gd are not needed anymore; we can squeeze them out. */ // memmove(tmp, Ft, llen * n * sizeof(uint32_t)); - System.arraycopy(srctmp, Ft, srctmp, tmp, llen * n); - Ft = tmp; + System.arraycopy(srctmp, Ft, srctmp, 0, llen * n); + Ft = 0; // memmove(Ft + llen * n, Gt, llen * n * sizeof(uint32_t)); System.arraycopy(srctmp, Gt, srctmp, Ft + llen * n, llen * n); Gt = Ft + llen * n; @@ -2861,7 +2849,7 @@ int solve_NTRU_binary_depth1(int logn_top, /* * All computations are done modulo p. */ - p = this.primes.PRIMES[u].p; + p = FalconSmallPrimeList.PRIMES[u].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); @@ -2877,15 +2865,15 @@ int solve_NTRU_binary_depth1(int logn_top, igm = gm + n_top; fx = igm + n; gx = fx + n_top; - modp_mkgm2(srctmp, gm, srctmp, igm, logn_top, this.primes.PRIMES[u].g, p, p0i); + modp_mkgm2(srctmp, gm, srctmp, igm, logn_top, FalconSmallPrimeList.PRIMES[u].g, p, p0i); /* * Set ft and gt to f and g modulo p, respectively. */ for (v = 0; v < n_top; v++) { - srctmp[fx + v] = modp_set(srcf[f + v], p); - srctmp[gx + v] = modp_set(srcg[g + v], p); + srctmp[fx + v] = modp_set(srcf[v], p); + srctmp[gx + v] = modp_set(srcg[v], p); } /* @@ -2903,18 +2891,18 @@ int solve_NTRU_binary_depth1(int logn_top, * From that point onward, we only need tables for * degree n, so we can save some space. */ - if (depth > 0) - { /* always true */ +// if (depth > 0) +// { /* always true */ // memmove(gm + n, igm, n * sizeof *igm); - System.arraycopy(srctmp, igm, srctmp, gm + n, n); - igm = gm + n; + System.arraycopy(srctmp, igm, srctmp, gm + n, n); + igm = gm + n; // memmove(igm + n, fx, n * sizeof *ft); - System.arraycopy(srctmp, fx, srctmp, igm + n, n); - fx = igm + n; + System.arraycopy(srctmp, fx, srctmp, igm + n, n); + fx = igm + n; // memmove(fx + n, gx, n * sizeof *gt); - System.arraycopy(srctmp, gx, srctmp, fx + n, n); - gx = fx + n; - } + System.arraycopy(srctmp, gx, srctmp, fx + n, n); + gx = fx + n; +// } /* * Get F' and G' modulo p and in NTT representation @@ -2975,15 +2963,15 @@ int solve_NTRU_binary_depth1(int logn_top, int ftA, ftB, gtA, gtB; int mFp, mGp; - ftA = srctmp[fx + (v << 1) + 0]; + ftA = srctmp[fx + (v << 1)]; ftB = srctmp[fx + (v << 1) + 1]; - gtA = srctmp[gx + (v << 1) + 0]; + gtA = srctmp[gx + (v << 1)]; gtB = srctmp[gx + (v << 1) + 1]; mFp = modp_montymul(srctmp[Fp + v], R2, p, p0i); mGp = modp_montymul(srctmp[Gp + v], R2, p, p0i); - srctmp[x + 0] = modp_montymul(gtB, mFp, p, p0i); + srctmp[x] = modp_montymul(gtB, mFp, p, p0i); srctmp[x + llen] = modp_montymul(gtA, mFp, p, p0i); - srctmp[y + 0] = modp_montymul(ftB, mGp, p, p0i); + srctmp[y] = modp_montymul(ftB, mGp, p, p0i); srctmp[y + llen] = modp_montymul(ftA, mGp, p, p0i); } modp_iNTT2_ext(srctmp, Ft + u, llen, srctmp, igm, logn, p, p0i); @@ -3010,8 +2998,8 @@ int solve_NTRU_binary_depth1(int logn_top, * and G are consecutive, and thus can be rebuilt in a single * loop; similarly, the elements of f and g are consecutive. */ - zint_rebuild_CRT(srctmp, Ft, llen, llen, n << 1, this.primes.PRIMES, 1, srctmp, t1); - zint_rebuild_CRT(srctmp, ft, slen, slen, n << 1, this.primes.PRIMES, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, Ft, llen, llen, n << 1, 1, srctmp, t1); + zint_rebuild_CRT(srctmp, ft, slen, slen, n << 1, 1, srctmp, t1); /* * Here starts the Babai reduction, specialized for depth = 1. @@ -3025,31 +3013,31 @@ int solve_NTRU_binary_depth1(int logn_top, * Convert F and G into floating point (rt1 and rt2). */ // rt1 = align_fpr(tmp, gt + slen * n); - rt1 = new FalconFPR[n]; - rt2 = new FalconFPR[n]; - poly_big_to_fp(rt1, 0, srctmp, Ft, llen, llen, logn); - poly_big_to_fp(rt2, 0, srctmp, Gt, llen, llen, logn); + rt1 = new double[n]; + rt2 = new double[n]; + poly_big_to_fp(rt1, srctmp, Ft, llen, llen, logn); + poly_big_to_fp(rt2, srctmp, Gt, llen, llen, logn); /* * Integer representation of F and G is no longer needed, we * can remove it. */ // memmove(tmp, ft, 2 * slen * n * sizeof *ft); - System.arraycopy(srctmp, ft, srctmp, tmp, 2 * slen * n); - ft = tmp; + System.arraycopy(srctmp, ft, srctmp, 0, 2 * slen * n); + ft = 0; gt = ft + slen * n; // rt3 = align_fpr(tmp, gt + slen * n); // memmove(rt3, rt1, 2 * n * sizeof *rt1); // rt1 = rt3; // rt2 = rt1 + n; - rt3 = new FalconFPR[n]; - rt4 = new FalconFPR[n]; + rt3 = new double[n]; + rt4 = new double[n]; /* * Convert f and g into floating point (rt3 and rt4). */ - poly_big_to_fp(rt3, 0, srctmp, ft, slen, slen, logn); - poly_big_to_fp(rt4, 0, srctmp, gt, slen, slen, logn); + poly_big_to_fp(rt3, srctmp, ft, slen, slen, logn); + poly_big_to_fp(rt4, srctmp, gt, slen, slen, logn); /* * Remove unneeded ft and gt. - not required as we have rt_ in separate array @@ -3068,10 +3056,10 @@ int solve_NTRU_binary_depth1(int logn_top, * rt4 = g * in that order in RAM. We convert all of them to FFT. */ - fft.FFT(rt1, 0, logn); - fft.FFT(rt2, 0, logn); - fft.FFT(rt3, 0, logn); - fft.FFT(rt4, 0, logn); + FalconFFT.FFT(rt1, 0, logn); + FalconFFT.FFT(rt2, 0, logn); + FalconFFT.FFT(rt3, 0, logn); + FalconFFT.FFT(rt4, 0, logn); /* * Compute: @@ -3079,16 +3067,16 @@ int solve_NTRU_binary_depth1(int logn_top, * rt6 = 1 / (f*adj(f) + g*adj(g)) * (Note that rt6 is half-length.) */ - rt5 = new FalconFPR[n]; - rt6 = new FalconFPR[n >> 1]; - fft.poly_add_muladj_fft(rt5, 0, rt1, 0, rt2, 0, rt3, 0, rt4, 0, logn); - fft.poly_invnorm2_fft(rt6, 0, rt3, 0, rt4, 0, logn); + rt5 = new double[n]; + rt6 = new double[n >> 1]; + FalconFFT.poly_add_muladj_fft(rt5, rt1, rt2, rt3, rt4, logn); + FalconFFT.poly_invnorm2_fft(rt6, 0, rt3, 0, rt4, 0, logn); /* * Compute: * rt5 = (F*adj(f)+G*adj(g)) / (f*adj(f)+g*adj(g)) */ - fft.poly_mul_autoadj_fft(rt5, 0, rt6, 0, logn); + FalconFFT.poly_mul_autoadj_fft(rt5, 0, rt6, 0, logn); /* * Compute k as the rounded version of rt5. Check that none of @@ -3097,34 +3085,35 @@ int solve_NTRU_binary_depth1(int logn_top, * note that any out-of-bounds value here implies a failure and * (f,g) will be discarded, so we can make a simple test. */ - fft.iFFT(rt5, 0, logn); + FalconFFT.iFFT(rt5, 0, logn); for (u = 0; u < n; u++) { - FalconFPR z; + double z; z = rt5[u]; - if (!fpr.fpr_lt(z, fpr.fpr_ptwo63m1) || !fpr.fpr_lt(fpr.fpr_mtwo63m1, z)) +// if (!FPREngine.fpr_lt(z, FPREngine.fpr_ptwo63m1) || !FPREngine.fpr_lt(FPREngine.fpr_mtwo63m1, z)) + if (z >= FPREngine.fpr_ptwo63m1 || FPREngine.fpr_mtwo63m1 >= z) { return 0; } - rt5[u] = fpr.fpr_of(fpr.fpr_rint(z)); + rt5[u] = FPREngine.fpr_rint(z); } - fft.FFT(rt5, 0, logn); + FalconFFT.FFT(rt5, 0, logn); /* * Subtract k*f from F, and k*g from G. */ - fft.poly_mul_fft(rt3, 0, rt5, 0, logn); - fft.poly_mul_fft(rt4, 0, rt5, 0, logn); - fft.poly_sub(rt1, 0, rt3, 0, logn); - fft.poly_sub(rt2, 0, rt4, 0, logn); - fft.iFFT(rt1, 0, logn); - fft.iFFT(rt2, 0, logn); + FalconFFT.poly_mul_fft(rt3, 0, rt5, 0, logn); + FalconFFT.poly_mul_fft(rt4, 0, rt5, 0, logn); + FalconFFT.poly_sub(rt1, 0, rt3, 0, logn); + FalconFFT.poly_sub(rt2, 0, rt4, 0, logn); + FalconFFT.iFFT(rt1, 0, logn); + FalconFFT.iFFT(rt2, 0, logn); /* * Convert back F and G to integers, and return. */ - Ft = tmp; + //Ft = 0; Gt = Ft + n; // rt3 = align_fpr(tmp, Gt + n); // memmove(rt3, rt1, 2 * n * sizeof *rt1); @@ -3132,8 +3121,8 @@ int solve_NTRU_binary_depth1(int logn_top, // rt2 = rt1 + n; for (u = 0; u < n; u++) { - srctmp[Ft + u] = (int)fpr.fpr_rint(rt1[u]); - srctmp[Gt + u] = (int)fpr.fpr_rint(rt2[u]); + srctmp[Ft + u] = (int)FPREngine.fpr_rint(rt1[u]); + srctmp[Gt + u] = (int)FPREngine.fpr_rint(rt2[u]); } return 1; @@ -3145,8 +3134,8 @@ int solve_NTRU_binary_depth1(int logn_top, * * Returned value: 1 on success, 0 on error. */ - int solve_NTRU_binary_depth0(int logn, - byte[] srcf, int f, byte[] srcg, int g, int[] srctmp, int tmp) + private static int solve_NTRU_binary_depth0(int logn, + byte[] srcf, byte[] srcg, int[] srctmp) { int n, hn, u; int p, p0i, R2; @@ -3172,18 +3161,18 @@ int solve_NTRU_binary_depth0(int logn, * Everything should fit in 31-bit integers, hence we can just use * the first small prime p = 2147473409. */ - p = this.primes.PRIMES[0].p; + p = FalconSmallPrimeList.PRIMES[0].p; p0i = modp_ninv31(p); R2 = modp_R2(p, p0i); - Fp = tmp; + Fp = 0; Gp = Fp + hn; ft = Gp + hn; gt = ft + n; gm = gt + n; igm = gm + n; - modp_mkgm2(srctmp, gm, srctmp, igm, logn, this.primes.PRIMES[0].g, p, p0i); + modp_mkgm2(srctmp, gm, srctmp, igm, logn, FalconSmallPrimeList.PRIMES[0].g, p, p0i); /* * Convert F' anf G' in NTT representation. @@ -3201,8 +3190,8 @@ int solve_NTRU_binary_depth0(int logn, */ for (u = 0; u < n; u++) { - srctmp[ft + u] = modp_set(srcf[f + u], p); - srctmp[gt + u] = modp_set(srcg[g + u], p); + srctmp[ft + u] = modp_set(srcf[u], p); + srctmp[gt + u] = modp_set(srcg[u], p); } modp_NTT2(srctmp, ft, srctmp, gm, logn, p, p0i); modp_NTT2(srctmp, gt, srctmp, gm, logn, p, p0i); @@ -3215,15 +3204,15 @@ int solve_NTRU_binary_depth0(int logn, int ftA, ftB, gtA, gtB; int mFp, mGp; - ftA = srctmp[ft + u + 0]; + ftA = srctmp[ft + u]; ftB = srctmp[ft + u + 1]; - gtA = srctmp[gt + u + 0]; + gtA = srctmp[gt + u]; gtB = srctmp[gt + u + 1]; mFp = modp_montymul(srctmp[Fp + (u >> 1)], R2, p, p0i); mGp = modp_montymul(srctmp[Gp + (u >> 1)], R2, p, p0i); - srctmp[ft + u + 0] = modp_montymul(gtB, mFp, p, p0i); + srctmp[ft + u] = modp_montymul(gtB, mFp, p, p0i); srctmp[ft + u + 1] = modp_montymul(gtA, mFp, p, p0i); - srctmp[gt + u + 0] = modp_montymul(ftB, mGp, p, p0i); + srctmp[gt + u] = modp_montymul(ftB, mGp, p, p0i); srctmp[gt + u + 1] = modp_montymul(ftA, mGp, p, p0i); } modp_iNTT2(srctmp, ft, srctmp, igm, logn, p, p0i); @@ -3251,7 +3240,7 @@ int solve_NTRU_binary_depth0(int logn, * Compute the NTT tables in t1 and t2. We do not keep t2 * (we'll recompute it later on). */ - modp_mkgm2(srctmp, t1, srctmp, t2, logn, this.primes.PRIMES[0].g, p, p0i); + modp_mkgm2(srctmp, t1, srctmp, t2, logn, FalconSmallPrimeList.PRIMES[0].g, p, p0i); /* * Convert F and G to NTT. @@ -3263,11 +3252,11 @@ int solve_NTRU_binary_depth0(int logn, * Load f and adj(f) in t4 and t5, and convert them to NTT * representation. */ - srctmp[t4 + 0] = srctmp[t5 + 0] = modp_set(srcf[f + 0], p); + srctmp[t4] = srctmp[t5] = modp_set(srcf[0], p); for (u = 1; u < n; u++) { - srctmp[t4 + u] = modp_set(srcf[f + u], p); - srctmp[t5 + n - u] = modp_set(-srcf[f + u], p); + srctmp[t4 + u] = modp_set(srcf[u], p); + srctmp[t5 + n - u] = modp_set(-srcf[u], p); } modp_NTT2(srctmp, t4, srctmp, t1, logn, p, p0i); modp_NTT2(srctmp, t5, srctmp, t1, logn, p, p0i); @@ -3288,11 +3277,11 @@ int solve_NTRU_binary_depth0(int logn, * Load g and adj(g) in t4 and t5, and convert them to NTT * representation. */ - srctmp[t4 + 0] = srctmp[t5 + 0] = modp_set(srcg[g + 0], p); + srctmp[t4] = srctmp[t5] = modp_set(srcg[0], p); for (u = 1; u < n; u++) { - srctmp[t4 + u] = modp_set(srcg[g + u], p); - srctmp[t5 + n - u] = modp_set(-srcg[g + u], p); + srctmp[t4 + u] = modp_set(srcg[u], p); + srctmp[t5 + n - u] = modp_set(-srcg[u], p); } modp_NTT2(srctmp, t4, srctmp, t1, logn, p, p0i); modp_NTT2(srctmp, t5, srctmp, t1, logn, p, p0i); @@ -3317,7 +3306,7 @@ int solve_NTRU_binary_depth0(int logn, * move them to t1 and t2. We first need to recompute the * inverse table for NTT. */ - modp_mkgm2(srctmp, t1, srctmp, t4, logn, this.primes.PRIMES[0].g, p, p0i); + modp_mkgm2(srctmp, t1, srctmp, t4, logn, FalconSmallPrimeList.PRIMES[0].g, p, p0i); modp_iNTT2(srctmp, t2, srctmp, t4, logn, p, p0i); modp_iNTT2(srctmp, t3, srctmp, t4, logn, p, p0i); // TODO fix binary_depth0 -> t1 value is wrong for (u = 0; u < n; u++) @@ -3344,17 +3333,16 @@ int solve_NTRU_binary_depth0(int logn, * representation are actually real, so we can truncate off * the imaginary parts. */ - FalconFPR[] - tmp2 = new FalconFPR[3 * n]; + double[] tmp2 = new double[3 * n]; // rt3 = align_fpr(tmp, t3); rt1 = 0; rt2 = rt1 + n; rt3 = rt2 + n; for (u = 0; u < n; u++) { - tmp2[rt3 + u] = fpr.fpr_of(srctmp[t2 + u]); + tmp2[rt3 + u] = srctmp[t2 + u]; } - fft.FFT(tmp2, rt3, logn); + FalconFFT.FFT(tmp2, rt3, logn); // rt2 = align_fpr(tmp, t2); // memmove(rt2, rt3, hn * sizeof *rt3); System.arraycopy(tmp2, rt3, tmp2, rt2, hn); @@ -3365,19 +3353,19 @@ int solve_NTRU_binary_depth0(int logn, rt3 = rt2 + hn; for (u = 0; u < n; u++) { - tmp2[rt3 + u] = fpr.fpr_of(srctmp[t1 + u]); + tmp2[rt3 + u] = srctmp[t1 + u]; } - fft.FFT(tmp2, rt3, logn); + FalconFFT.FFT(tmp2, rt3, logn); /* * Compute (F*adj(f)+G*adj(g))/(f*adj(f)+g*adj(g)) and get * its rounded normal representation in t1. */ - fft.poly_div_autoadj_fft(tmp2, rt3, tmp2, rt2, logn); - fft.iFFT(tmp2, rt3, logn); + FalconFFT.poly_div_autoadj_fft(tmp2, rt3, tmp2, rt2, logn); + FalconFFT.iFFT(tmp2, rt3, logn); for (u = 0; u < n; u++) { - srctmp[t1 + u] = modp_set((int)fpr.fpr_rint(tmp2[rt3 + u]), p); + srctmp[t1 + u] = modp_set((int)FPREngine.fpr_rint(tmp2[rt3 + u]), p); } /* @@ -3393,11 +3381,11 @@ int solve_NTRU_binary_depth0(int logn, t3 = t2 + n; t4 = t3 + n; t5 = t4 + n; - modp_mkgm2(srctmp, t2, srctmp, t3, logn, this.primes.PRIMES[0].g, p, p0i); + modp_mkgm2(srctmp, t2, srctmp, t3, logn, FalconSmallPrimeList.PRIMES[0].g, p, p0i); for (u = 0; u < n; u++) { - srctmp[t4 + u] = modp_set(srcf[f + u], p); - srctmp[t5 + u] = modp_set(srcg[g + u], p); + srctmp[t4 + u] = modp_set(srcf[u], p); + srctmp[t5 + u] = modp_set(srcg[u], p); } modp_NTT2(srctmp, t1, srctmp, t2, logn, p, p0i); modp_NTT2(srctmp, t4, srctmp, t2, logn, p, p0i); @@ -3429,17 +3417,16 @@ int solve_NTRU_binary_depth0(int logn, * If any of the coefficients of F and G exceeds lim (in absolute value), * then 0 is returned. */ - int solve_NTRU(int logn, byte[] srcF, int F, byte[] srcG, int G, - byte[] srcf, int f, byte[] srcg, int g, int lim, int[] srctmp, int tmp) + private static int solve_NTRU(int logn, byte[] srcF, //byte[] srcG, + byte[] srcf, byte[] srcg, int lim, int[] srctmp) { int n, u; int ft, gt, Ft, Gt, gm; int p, p0i, r; - FalconSmallPrime[] primes; - + int G = 0; n = mkn(logn); - if (solve_NTRU_deepest(logn, srcf, f, srcg, g, srctmp, tmp) == 0) + if (solve_NTRU_deepest(logn, srcf, srcg, srctmp) == 0) { return 0; } @@ -3456,7 +3443,7 @@ int solve_NTRU(int logn, byte[] srcF, int F, byte[] srcG, int G, depth = logn; while (depth-- > 0) { - if (solve_NTRU_intermediate(logn, srcf, f, srcg, g, depth, srctmp, tmp) == 0) + if (solve_NTRU_intermediate(logn, srcf, srcg, depth, srctmp) == 0) { return 0; } @@ -3464,21 +3451,19 @@ int solve_NTRU(int logn, byte[] srcF, int F, byte[] srcG, int G, } else { - int depth; - - depth = logn; + int depth = logn; while (depth-- > 2) { - if (solve_NTRU_intermediate(logn, srcf, f, srcg, g, depth, srctmp, tmp) == 0) + if (solve_NTRU_intermediate(logn, srcf, srcg, depth, srctmp) == 0) { return 0; } } - if (solve_NTRU_binary_depth1(logn, srcf, f, srcg, g, srctmp, tmp) == 0) + if (solve_NTRU_binary_depth1(logn, srcf, srcg, srctmp) == 0) { return 0; } - if (solve_NTRU_binary_depth0(logn, srcf, f, srcg, g, srctmp, tmp) == 0) + if (solve_NTRU_binary_depth0(logn, srcf, srcg, srctmp) == 0) { return 0; } @@ -3487,18 +3472,19 @@ int solve_NTRU(int logn, byte[] srcF, int F, byte[] srcG, int G, /* * If no buffer has been provided for G, use a temporary one. */ - if (srcG == null) - { - G = 0; - srcG = new byte[n]; - } +// if (srcG == null) +// { +// G = 0; +// srcG = new byte[n]; +// } + byte[] srcG = new byte[n]; /* * Final F and G are in fk->tmp, one word per coefficient * (signed value over 31 bits). */ - if (poly_big_to_small(srcF, F, srctmp, tmp, lim, logn) == 0 - || poly_big_to_small(srcG, G, srctmp, tmp + n, lim, logn) == 0) + if (poly_big_to_small(srcF, 0, srctmp, 0, lim, logn) == 0 + || poly_big_to_small(srcG, G, srctmp, n, lim, logn) == 0) { return 0; } @@ -3511,25 +3497,24 @@ int solve_NTRU(int logn, byte[] srcF, int F, byte[] srcG, int G, * We put Gt[] first in tmp[], and process it first, so that it does * not overlap with G[] in case we allocated it ourselves. */ - Gt = tmp; + Gt = 0; ft = Gt + n; gt = ft + n; Ft = gt + n; gm = Ft + n; - primes = this.primes.PRIMES; - p = primes[0].p; + p = FalconSmallPrimeList.PRIMES[0].p; p0i = modp_ninv31(p); - modp_mkgm2(srctmp, gm, srctmp, tmp, logn, primes[0].g, p, p0i); + modp_mkgm2(srctmp, gm, srctmp, 0, logn, FalconSmallPrimeList.PRIMES[0].g, p, p0i); for (u = 0; u < n; u++) { srctmp[Gt + u] = modp_set(srcG[G + u], p); } for (u = 0; u < n; u++) { - srctmp[ft + u] = modp_set(srcf[f + u], p); - srctmp[gt + u] = modp_set(srcg[g + u], p); - srctmp[Ft + u] = modp_set(srcF[F + u], p); + srctmp[ft + u] = modp_set(srcf[u], p); + srctmp[gt + u] = modp_set(srcg[u], p); + srctmp[Ft + u] = modp_set(srcF[u], p); } modp_NTT2(srctmp, ft, srctmp, gm, logn, p, p0i); modp_NTT2(srctmp, gt, srctmp, gm, logn, p, p0i); @@ -3555,7 +3540,7 @@ int solve_NTRU(int logn, byte[] srcF, int F, byte[] srcG, int G, * Generate a random polynomial with a Gaussian distribution. This function * also makes sure that the resultant of the polynomial with phi is odd. */ - void poly_small_mkgauss(SHAKE256 rng, byte[] srcf, int f, int logn) + private static void poly_small_mkgauss(SHAKEDigest rng, byte[] srcf, int logn) { int n, u; int mod2; @@ -3597,16 +3582,16 @@ void poly_small_mkgauss(SHAKE256 rng, byte[] srcf, int f, int logn) { mod2 ^= (s & 1); } - srcf[f + u] = (byte)s; + srcf[u] = (byte)s; break; } } } /* see falcon.h */ - void keygen(SHAKE256 rng, - byte[] srcf, int f, byte[] srcg, int g, byte[] srcF, int F, byte[] srcG, int G, short[] srch, int h, - int logn) + static void keygen(SHAKEDigest rc, + byte[] srcf, byte[] srcg, byte[] srcF, short[] srch, + int logn) { /* * Algorithm is the following: @@ -3629,14 +3614,14 @@ void keygen(SHAKE256 rng, */ int n, u; int[] itmp; - byte[] btmp; + //byte[] btmp; short[] stmp; - FalconFPR[] ftmp; + double[] ftmp; int h2, tmp2; - SHAKE256 rc; + //SHAKE256 rc; n = mkn(logn); - rc = rng; + //rc = rng; /* * We need to generate f and g randomly, until we find values @@ -3659,9 +3644,9 @@ void keygen(SHAKE256 rng, */ for (; ; ) { - ftmp = new FalconFPR[3 * n]; + ftmp = new double[3 * n]; int rt1, rt2, rt3; - FalconFPR bnorm; + double bnorm; int normf, normg, norm; int lim; @@ -3671,8 +3656,8 @@ void keygen(SHAKE256 rng, * (i.e. the resultant of the polynomial with phi * will be odd). */ - poly_small_mkgauss(rc, srcf, f, logn); - poly_small_mkgauss(rc, srcg, g, logn); + poly_small_mkgauss(rc, srcf, logn); + poly_small_mkgauss(rc, srcg, logn); /* * Verify that all coefficients are within the bounds @@ -3680,15 +3665,15 @@ void keygen(SHAKE256 rng, * overwhelming probability; this guarantees that the * key will be encodable with FALCON_COMP_TRIM. */ - lim = 1 << (codec.max_fg_bits[logn] - 1); + lim = 1 << (FalconCodec.max_fg_bits[logn] - 1); for (u = 0; u < n; u++) { /* * We can use non-CT tests since on any failure * we will discard f and g. */ - if (srcf[f + u] >= lim || srcf[f + u] <= -lim - || srcg[g + u] >= lim || srcg[g + u] <= -lim) + if (srcf[u] >= lim || srcf[u] <= -lim + || srcg[u] >= lim || srcg[u] <= -lim) { lim = -1; break; @@ -3706,8 +3691,8 @@ void keygen(SHAKE256 rng, * Since f and g are integral, the squared norm * of (g,-f) is an integer. */ - normf = poly_small_sqnorm(srcf, f, logn); - normg = poly_small_sqnorm(srcg, g, logn); + normf = poly_small_sqnorm(srcf, logn); + normg = poly_small_sqnorm(srcg, logn); norm = (normf + normg) | -((normf | normg) >>> 31); if ((norm & 0xffffffffL) >= 16823L) { @@ -3720,26 +3705,26 @@ void keygen(SHAKE256 rng, rt1 = 0; rt2 = rt1 + n; rt3 = rt2 + n; - poly_small_to_fp(ftmp, rt1, srcf, f, logn); - poly_small_to_fp(ftmp, rt2, srcg, g, logn); - fft.FFT(ftmp, rt1, logn); - fft.FFT(ftmp, rt2, logn); - fft.poly_invnorm2_fft(ftmp, rt3, ftmp, rt1, ftmp, rt2, logn); - fft.poly_adj_fft(ftmp, rt1, logn); - fft.poly_adj_fft(ftmp, rt2, logn); - fft.poly_mulconst(ftmp, rt1, fpr.fpr_q, logn); - fft.poly_mulconst(ftmp, rt2, fpr.fpr_q, logn); - fft.poly_mul_autoadj_fft(ftmp, rt1, ftmp, rt3, logn); - fft.poly_mul_autoadj_fft(ftmp, rt2, ftmp, rt3, logn); - fft.iFFT(ftmp, rt1, logn); - fft.iFFT(ftmp, rt2, logn); - bnorm = fpr.fpr_zero; + poly_small_to_fp(ftmp, rt1, srcf, logn); + poly_small_to_fp(ftmp, rt2, srcg, logn); + FalconFFT.FFT(ftmp, rt1, logn); + FalconFFT.FFT(ftmp, rt2, logn); + FalconFFT.poly_invnorm2_fft(ftmp, rt3, ftmp, rt1, ftmp, rt2, logn); + FalconFFT.poly_adj_fft(ftmp, rt1, logn); + FalconFFT.poly_adj_fft(ftmp, rt2, logn); + FalconFFT.poly_mulconst(ftmp, rt1, FPREngine.fpr_q, logn); + FalconFFT.poly_mulconst(ftmp, rt2, FPREngine.fpr_q, logn); + FalconFFT.poly_mul_autoadj_fft(ftmp, rt1, ftmp, rt3, logn); + FalconFFT.poly_mul_autoadj_fft(ftmp, rt2, ftmp, rt3, logn); + FalconFFT.iFFT(ftmp, rt1, logn); + FalconFFT.iFFT(ftmp, rt2, logn); + bnorm = FPREngine.fpr_zero; for (u = 0; u < n; u++) { - bnorm = fpr.fpr_add(bnorm, fpr.fpr_sqr(ftmp[rt1 + u])); - bnorm = fpr.fpr_add(bnorm, fpr.fpr_sqr(ftmp[rt2 + u])); + bnorm += ftmp[rt1 + u] * ftmp[rt1 + u] + ftmp[rt2 + u] * ftmp[rt2 + u]; } - if (!fpr.fpr_lt(bnorm, fpr.fpr_bnorm_max)) + //if (!FPREngine.fpr_lt(bnorm, FPREngine.fpr_bnorm_max)) + if (bnorm >= FPREngine.fpr_bnorm_max) { continue; } @@ -3757,10 +3742,10 @@ void keygen(SHAKE256 rng, } else { - h2 = h; + h2 = 0; tmp2 = 0; } - if (vrfy.compute_public(srch, h2, srcf, f, srcg, g, logn, stmp, tmp2) == 0) + if (FalconVrfy.compute_public(srch, h2, srcf, srcg, logn, stmp, tmp2) == 0) { continue; } @@ -3769,8 +3754,8 @@ void keygen(SHAKE256 rng, * Solve the NTRU equation to get F and G. */ itmp = logn > 2 ? new int[28 * n] : new int[28 * n * 3]; - lim = (1 << (codec.max_FG_bits[logn] - 1)) - 1; - if (solve_NTRU(logn, srcF, F, srcG, G, srcf, f, srcg, g, lim, itmp, 0) == 0) + lim = (1 << (FalconCodec.max_FG_bits[logn] - 1)) - 1; + if (solve_NTRU(logn, srcF, srcf, srcg, lim, itmp) == 0) { continue; } @@ -3782,7 +3767,7 @@ void keygen(SHAKE256 rng, } } - private long toUnsignedLong(int x) + private static long toUnsignedLong(int x) { return x & 0xffffffffL; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyPairGenerator.java index fcd94de366..1f2d6e02c7 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyPairGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconKeyPairGenerator.java @@ -11,10 +11,7 @@ public class FalconKeyPairGenerator { private FalconKeyGenerationParameters params; - private SecureRandom random; private FalconNIST nist; - private int logn; - private int noncelen; private int pk_size; private int sk_size; @@ -22,11 +19,11 @@ public class FalconKeyPairGenerator public void init(KeyGenerationParameters param) { this.params = (FalconKeyGenerationParameters)param; - this.random = param.getRandom(); - this.logn = ((FalconKeyGenerationParameters)param).getParameters().getLogN(); - this.noncelen = ((FalconKeyGenerationParameters)param).getParameters().getNonceLength(); + SecureRandom random = param.getRandom(); + int logn = ((FalconKeyGenerationParameters)param).getParameters().getLogN(); + int noncelen = ((FalconKeyGenerationParameters)param).getParameters().getNonceLength(); this.nist = new FalconNIST(logn, noncelen, random); - int n = 1 << this.logn; + int n = 1 << logn; int sk_coeff_size = 8; if (n == 1024) { @@ -49,8 +46,8 @@ public AsymmetricCipherKeyPair generateKeyPair() byte[] pk, sk; pk = new byte[pk_size]; sk = new byte[sk_size]; - byte[][] keyData = nist.crypto_sign_keypair(pk, 0, sk, 0); - FalconParameters p = ((FalconKeyGenerationParameters)this.params).getParameters(); + byte[][] keyData = nist.crypto_sign_keypair(pk, sk); + FalconParameters p = this.params.getParameters(); FalconPrivateKeyParameters privk = new FalconPrivateKeyParameters(p, keyData[1], keyData[2], keyData[3], keyData[0]); FalconPublicKeyParameters pubk = new FalconPublicKeyParameters(p, keyData[0]); return new AsymmetricCipherKeyPair(pubk, privk); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconNIST.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconNIST.java index a70ebb07dd..b3c47c5c81 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconNIST.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconNIST.java @@ -1,26 +1,25 @@ package org.bouncycastle.pqc.crypto.falcon; - import java.security.SecureRandom; +import org.bouncycastle.crypto.digests.SHAKEDigest; import org.bouncycastle.util.Arrays; class FalconNIST { + final int NONCELEN; + final int LOGN; + private final int N; + private final SecureRandom rand; + private final int CRYPTO_SECRETKEYBYTES; + private final int CRYPTO_PUBLICKEYBYTES; + final int CRYPTO_BYTES; - int NONCELEN; - int LOGN; - private int N; - private SecureRandom rand; - private int CRYPTO_SECRETKEYBYTES; - private int CRYPTO_PUBLICKEYBYTES; - int CRYPTO_BYTES; - - private FalconCodec codec; +// private FalconCodec codec; FalconNIST(int logn, int noncelen, SecureRandom random) { - codec = new FalconCodec(); +// codec = new FalconCodec(); this.rand = random; this.LOGN = logn; this.NONCELEN = noncelen; @@ -48,7 +47,7 @@ else if (logn == 7 || logn == 6) } } - byte[][] crypto_sign_keypair(byte[] srcpk, int pk, byte[] srcsk, int sk) + byte[][] crypto_sign_keypair(byte[] srcpk, byte[] srcsk) { // TODO: clean up required byte[] f = new byte[N], @@ -56,9 +55,10 @@ byte[][] crypto_sign_keypair(byte[] srcpk, int pk, byte[] srcsk, int sk) F = new byte[N]; short[] h = new short[N]; byte[] seed = new byte[48]; - SHAKE256 rng = new SHAKE256(); + //SHAKE256 rng = new SHAKE256(); + SHAKEDigest rng = new SHAKEDigest(256); int u, v; - FalconKeyGen keygen = new FalconKeyGen(); +// FalconKeyGen keygen = new FalconKeyGen(); // savcw = set_fpu_cw(2); @@ -70,12 +70,12 @@ byte[][] crypto_sign_keypair(byte[] srcpk, int pk, byte[] srcsk, int sk) // inner_shake256_init(&rng); // inner_shake256_inject(&rng, seed, sizeof seed); // inner_shake256_flip(&rng); - rng.inner_shake256_init(); - rng.inner_shake256_inject(seed, 0, seed.length); - rng.i_shake256_flip(); + //rng.inner_shake256_init(); + rng.update(seed, 0, seed.length); + //rng.i_shake256_flip(); // Zf(keygen)(&rng, f, g, F, NULL, h, 10, tmp.b); - keygen.keygen(rng, f, 0, g, 0, F, 0, null, 0, h, 0, LOGN); + FalconKeyGen.keygen(rng, f, g, F, h, LOGN); // set_fpu_cw(savcw); @@ -83,32 +83,32 @@ byte[][] crypto_sign_keypair(byte[] srcpk, int pk, byte[] srcsk, int sk) /* * Encode private key. */ - srcsk[sk + 0] = (byte)(0x50 + LOGN); // old python header + srcsk[0] = (byte)(0x50 + LOGN); // old python header u = 1; - v = codec.trim_i8_encode(srcsk, sk + u, CRYPTO_SECRETKEYBYTES - u, - f, 0, LOGN, codec.max_fg_bits[LOGN]); + v = FalconCodec.trim_i8_encode(srcsk, u, CRYPTO_SECRETKEYBYTES - u, + f, LOGN, FalconCodec.max_fg_bits[LOGN]); if (v == 0) { throw new IllegalStateException("f encode failed"); } - byte[] fEnc = Arrays.copyOfRange(srcsk, sk + u, u + v); + byte[] fEnc = Arrays.copyOfRange(srcsk, u, u + v); u += v; - v = codec.trim_i8_encode(srcsk, sk + u, CRYPTO_SECRETKEYBYTES - u, - g, 0, LOGN, codec.max_fg_bits[LOGN]); + v = FalconCodec.trim_i8_encode(srcsk, u, CRYPTO_SECRETKEYBYTES - u, + g, LOGN, FalconCodec.max_fg_bits[LOGN]); if (v == 0) { throw new IllegalStateException("g encode failed"); } - byte[] gEnc = Arrays.copyOfRange(srcsk, sk + u, u + v); + byte[] gEnc = Arrays.copyOfRange(srcsk, u, u + v); u += v; - v = codec.trim_i8_encode(srcsk, sk + u, CRYPTO_SECRETKEYBYTES - u, - F, 0, LOGN, codec.max_FG_bits[LOGN]); + v = FalconCodec.trim_i8_encode(srcsk, u, CRYPTO_SECRETKEYBYTES - u, + F, LOGN, FalconCodec.max_FG_bits[LOGN]); if (v == 0) { throw new IllegalStateException("F encode failed"); } - byte[] FEnc = Arrays.copyOfRange(srcsk, sk + u, u + v); + byte[] FEnc = Arrays.copyOfRange(srcsk, u, u + v); u += v; if (u != CRYPTO_SECRETKEYBYTES) { @@ -118,24 +118,24 @@ byte[][] crypto_sign_keypair(byte[] srcpk, int pk, byte[] srcsk, int sk) /* * Encode public key. */ - srcpk[pk + 0] = (byte)(0x00 + LOGN); - v = codec.modq_encode(srcpk, pk + 1, CRYPTO_PUBLICKEYBYTES - 1, h, 0, LOGN); + srcpk[0] = (byte)(LOGN); + v = FalconCodec.modq_encode(srcpk, CRYPTO_PUBLICKEYBYTES - 1, h, LOGN); if (v != CRYPTO_PUBLICKEYBYTES - 1) { throw new IllegalStateException("public key encoding failed"); } - return new byte[][] { Arrays.copyOfRange(srcpk, 1, srcpk.length), fEnc, gEnc, FEnc }; + return new byte[][]{Arrays.copyOfRange(srcpk, 1, srcpk.length), fEnc, gEnc, FEnc}; } - byte[] crypto_sign(boolean attached, byte[] srcsm, - byte[] srcm, int m, int mlen, - byte[] srcsk, int sk) + byte[] crypto_sign(byte[] srcsm, + byte[] srcm, int mlen, + byte[] srcsk) { byte[] f = new byte[N], - g = new byte[N], - F = new byte[N], - G = new byte[N]; + g = new byte[N], + F = new byte[N], + G = new byte[N]; short[] sig = new short[N]; short[] hm = new short[N]; @@ -144,11 +144,11 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, nonce = new byte[NONCELEN]; - SHAKE256 sc = new SHAKE256(); + SHAKEDigest sc = new SHAKEDigest(256); int u, v, sig_len; FalconSign sign = new FalconSign(); - FalconVrfy vrfy = new FalconVrfy(); - FalconCommon common = new FalconCommon(); + //FalconVrfy vrfy = new FalconVrfy(); +// FalconCommon common = new FalconCommon(); /* * Decode the private key. @@ -158,22 +158,22 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, // throw new IllegalArgumentException("private key header incorrect"); // } u = 0; - v = codec.trim_i8_decode(f, 0, LOGN, codec.max_fg_bits[LOGN], - srcsk, sk + u, CRYPTO_SECRETKEYBYTES - u); + v = FalconCodec.trim_i8_decode(f, LOGN, FalconCodec.max_fg_bits[LOGN], + srcsk, 0, CRYPTO_SECRETKEYBYTES - u); if (v == 0) { throw new IllegalStateException("f decode failed"); } u += v; - v = codec.trim_i8_decode(g, 0, LOGN, codec.max_fg_bits[LOGN], - srcsk, sk + u, CRYPTO_SECRETKEYBYTES - u); + v = FalconCodec.trim_i8_decode(g, LOGN, FalconCodec.max_fg_bits[LOGN], + srcsk, u, CRYPTO_SECRETKEYBYTES - u); if (v == 0) { throw new IllegalStateException("g decode failed"); } u += v; - v = codec.trim_i8_decode(F, 0, LOGN, codec.max_FG_bits[LOGN], - srcsk, sk + u, CRYPTO_SECRETKEYBYTES - u); + v = FalconCodec.trim_i8_decode(F, LOGN, FalconCodec.max_FG_bits[LOGN], + srcsk, u, CRYPTO_SECRETKEYBYTES - u); if (v == 0) { throw new IllegalArgumentException("F decode failed"); @@ -184,7 +184,7 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, throw new IllegalStateException("full key not used"); } - if (!vrfy.complete_private(G, 0, f, 0, g, 0, F, 0, LOGN, new short[2 * N], 0)) + if (!FalconVrfy.complete_private(G, f, g, F, LOGN, new short[2 * N])) { throw new IllegalStateException("complete_private failed"); } @@ -202,12 +202,12 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, // inner_shake256_inject(&sc, nonce, sizeof nonce); // inner_shake256_inject(&sc, m, mlen); // inner_shake256_flip(&sc); - sc.inner_shake256_init(); - sc.inner_shake256_inject(nonce, 0, NONCELEN); - sc.inner_shake256_inject(srcm, m, mlen); - sc.i_shake256_flip(); + //sc.inner_shake256_init(); + sc.update(nonce, 0, NONCELEN); + sc.update(srcm, 0, mlen); + //sc.i_shake256_flip(); // Zf(hash_to_point_vartime)(&sc, r.hm, 10); - common.hash_to_point_vartime(sc, hm, 0, LOGN); // TODO check if this needs to be ct + FalconCommon.hash_to_point_vartime(sc, hm, LOGN); // TODO check if this needs to be ct // System.out.println(String.format("%x %x %x %x %x %x %x %x", hm[0], hm[1], hm[2], hm[3], hm[4], hm[5], hm[6], hm[7])); /* @@ -218,9 +218,10 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, // inner_shake256_init(&sc); // inner_shake256_inject(&sc, seed, sizeof seed); // inner_shake256_flip(&sc); - sc.inner_shake256_init(); - sc.inner_shake256_inject(seed, 0, seed.length); - sc.i_shake256_flip(); + sc.reset(); + //sc.inner_shake256_init(); + sc.update(seed, 0, seed.length); + //sc.i_shake256_flip(); // savcw = set_fpu_cw(2); @@ -228,35 +229,35 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, * Compute the signature. */ // Zf(sign_dyn)(r.sig, &sc, f, g, F, G, r.hm, 10, tmp.b); - sign.sign_dyn(sig, 0, sc, f, 0, g, 0, F, 0, G, 0, hm, 0, LOGN, new FalconFPR[10 * N], 0); + sign.sign_dyn(sig, sc, f, g, F, G, hm, LOGN, new double[10 * N]); // set_fpu_cw(savcw); byte[] esig = new byte[CRYPTO_BYTES - 2 - NONCELEN]; - if (attached) - { - /* - * Encode the signature. Format is: - * signature header 1 bytes - * nonce 40 bytes - * signature slen bytes - */ - esig[0] = (byte)(0x20 + LOGN); - sig_len = codec.comp_encode(esig, 1, esig.length - 1, sig, 0, LOGN); - if (sig_len == 0) - { - throw new IllegalStateException("signature failed to generate"); - } - sig_len++; - } - else +// if (attached) +// { +// /* +// * Encode the signature. Format is: +// * signature header 1 bytes +// * nonce 40 bytes +// * signature slen bytes +// */ +// esig[0] = (byte)(0x20 + LOGN); +// sig_len = FalconCodec.comp_encode(esig, 1, esig.length - 1, sig, LOGN); +// if (sig_len == 0) +// { +// throw new IllegalStateException("signature failed to generate"); +// } +// sig_len++; +// } +// else +// { + sig_len = FalconCodec.comp_encode(esig, esig.length, sig, LOGN); + if (sig_len == 0) { - sig_len = codec.comp_encode(esig, 0, esig.length, sig, 0, LOGN); - if (sig_len == 0) - { - throw new IllegalStateException("signature failed to generate"); - } + throw new IllegalStateException("signature failed to generate"); } +// } // header srcsm[0] = (byte)(0x30 + LOGN); @@ -269,16 +270,17 @@ byte[] crypto_sign(boolean attached, byte[] srcsm, return Arrays.copyOfRange(srcsm, 0, 1 + NONCELEN + sig_len); } - int crypto_sign_open(boolean attached, byte[] sig_encoded, byte[] nonce, byte[] msg, - byte[] srcpk, int pk) + int crypto_sign_open(byte[] sig_encoded, byte[] nonce, byte[] msg, + byte[] srcpk) { short[] h = new short[N], hm = new short[N]; short[] sig = new short[N]; - SHAKE256 sc = new SHAKE256(); + //SHAKE256 sc = new SHAKE256(); + SHAKEDigest sc = new SHAKEDigest(256); int sig_len, msg_len; - FalconVrfy vrfy = new FalconVrfy(); - FalconCommon common = new FalconCommon(); + //FalconVrfy vrfy = new FalconVrfy(); +// FalconCommon common = new FalconCommon(); /* * Decode public key. @@ -287,12 +289,12 @@ int crypto_sign_open(boolean attached, byte[] sig_encoded, byte[] nonce, byte[] // { // return -1; // } - if (codec.modq_decode(h, 0, LOGN, srcpk, pk, CRYPTO_PUBLICKEYBYTES - 1) + if (FalconCodec.modq_decode(h, LOGN, srcpk, CRYPTO_PUBLICKEYBYTES - 1) != CRYPTO_PUBLICKEYBYTES - 1) { return -1; } - vrfy.to_ntt_monty(h, 0, LOGN); + FalconVrfy.to_ntt_monty(h, LOGN); /* * Find nonce, signature, message length. @@ -313,40 +315,40 @@ int crypto_sign_open(boolean attached, byte[] sig_encoded, byte[] nonce, byte[] * Decode signature. */ // Check only required for attached signatures - see 3.11.3 and 3.11.6 in the spec - if (attached) - { - if (sig_len < 1 || sig_encoded[0] != (byte)(0x20 + LOGN)) - { - return -1; - } - if (codec.comp_decode(sig, 0, LOGN, - sig_encoded, 1, sig_len - 1) != sig_len - 1) - { - return -1; - } - } - else +// if (attached) +// { +// if (sig_len < 1 || sig_encoded[0] != (byte)(0x20 + LOGN)) +// { +// return -1; +// } +// if (FalconCodec.comp_decode(sig, LOGN, +// sig_encoded, 1, sig_len - 1) != sig_len - 1) +// { +// return -1; +// } +// } +// else +// { + if (sig_len < 1 || FalconCodec.comp_decode(sig, LOGN, + sig_encoded, sig_len) != sig_len) { - if (sig_len < 1 || codec.comp_decode(sig, 0, LOGN, - sig_encoded, 0, sig_len) != sig_len) - { - return -1; - } + return -1; } +// } /* * Hash nonce + message into a vector. */ - sc.inner_shake256_init(); - sc.inner_shake256_inject(nonce, 0, NONCELEN); - sc.inner_shake256_inject(msg, 0, msg_len); - sc.i_shake256_flip(); - common.hash_to_point_vartime(sc, hm, 0, LOGN); // TODO check if this needs to become ct + //sc.inner_shake256_init(); + sc.update(nonce, 0, NONCELEN); + sc.update(msg, 0, msg_len); + //sc.i_shake256_flip(); + FalconCommon.hash_to_point_vartime(sc, hm, LOGN); // TODO check if this needs to become ct /* * Verify signature. */ - if (vrfy.verify_raw(hm, 0, sig, 0, h, 0, LOGN, new short[N], 0) == 0) + if (FalconVrfy.verify_raw(hm, sig, h, LOGN, new short[N]) == 0) { return -1; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconPublicKeyParameters.java index 31f58be5a2..756341c56b 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconPublicKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconPublicKeyParameters.java @@ -5,7 +5,7 @@ public class FalconPublicKeyParameters extends FalconKeyParameters { - private byte[] H; + private final byte[] H; public FalconPublicKeyParameters(FalconParameters parameters, byte[] H) { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconRNG.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconRNG.java index bb191b0933..21e9e99baf 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconRNG.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconRNG.java @@ -1,57 +1,63 @@ package org.bouncycastle.pqc.crypto.falcon; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.util.Pack; + class FalconRNG { byte[] bd; - long bdummy_u64; + // long bdummy_u64; int ptr; byte[] sd; - long sdummy_u64; - int type; +// long sdummy_u64; +// int type; - FalconConversions convertor; + //FalconConversions convertor; FalconRNG() { this.bd = new byte[512]; - this.bdummy_u64 = 0; +// this.bdummy_u64 = 0; this.ptr = 0; this.sd = new byte[256]; - this.sdummy_u64 = 0; - this.type = 0; - this.convertor = new FalconConversions(); +// this.sdummy_u64 = 0; +// this.type = 0; + //this.convertor = new FalconConversions(); } - void prng_init(SHAKE256 src) + void prng_init(SHAKEDigest src) { /* * To ensure reproducibility for a given seed, we * must enforce little-endian interpretation of * the state words. */ - byte[] tmp = new byte[56]; - long th, tl; - int i; - - src.inner_shake256_extract(tmp, 0, 56); - for (i = 0; i < 14; i++) - { - int w; - - w = (tmp[(i << 2) + 0] & 0xff) - | ((tmp[(i << 2) + 1] & 0xff) << 8) - | ((tmp[(i << 2) + 2] & 0xff) << 16) - | ((tmp[(i << 2) + 3] & 0xff) << 24); +// byte[] tmp = new byte[56]; +// long th, tl; +// int i; - System.arraycopy(convertor.int_to_bytes(w), 0, this.sd, i << 2, 4); - } - - tl = (convertor.bytes_to_int(this.sd, 48) & 0xffffffffL); + src.doOutput(this.sd, 0, 56); +// System.arraycopy(tmp, 0, this.sd, 0, 56); +// for (i = 0; i < 14; i++) +// { +// int w = (tmp[(i << 2)] & 0xff) +// | ((tmp[(i << 2) + 1] & 0xff) << 8) +// | ((tmp[(i << 2) + 2] & 0xff) << 16) +// | ((tmp[(i << 2) + 3] & 0xff) << 24); +// +// +// System.arraycopy(Pack.intToLittleEndian(w), 0, this.sd, i << 2, 4); +// } - th = (convertor.bytes_to_int(this.sd, 52) & 0xffffffffL); + //tl = (convertor.bytes_to_int(this.sd, 48) & 0xffffffffL); +// tl = Pack.littleEndianToInt(this.sd, 48) & 0xffffffffL; +// +// //th = (convertor.bytes_to_int(this.sd, 52) & 0xffffffffL); +// th = Pack.littleEndianToInt(this.sd, 52) & 0xffffffffL; +// Pack.longToLittleEndian(tl + (th << 32), this.sd, 48); - System.arraycopy(convertor.long_to_bytes(tl + (th << 32)), 0, this.sd, 48, 8); + //System.arraycopy(convertor.long_to_bytes(tl + (th << 32)), 0, this.sd, 48, 8); this.prng_refill(); } @@ -84,17 +90,19 @@ void prng_refill() * converted to little endian (if used on a big-endian machine). */ // cc = *(uint64_t *)(p->state.d + 48); - cc = convertor.bytes_to_long(this.sd, 48); + cc = Pack.littleEndianToLong(this.sd, 48); + //cc = convertor.bytes_to_long(this.sd, 48); + int[] state = new int[16]; for (u = 0; u < 8; u++) { - int[] state = new int[16]; int v; int i; // memcpy(&state[0], CW, sizeof CW); System.arraycopy(CW, 0, state, 0, CW.length); // memcpy(&state[4], p->state.d, 48); - System.arraycopy(convertor.bytes_to_int_array(this.sd, 0, 12), 0, state, 4, 12); + Pack.littleEndianToInt(this.sd, 0, state, 4, 12); + //System.arraycopy(convertor.bytes_to_int_array(this.sd, 0, 12), 0, state, 4, 12); state[14] ^= (int)cc; state[15] ^= (int)(cc >>> 32); for (i = 0; i < 10; i++) @@ -117,14 +125,17 @@ void prng_refill() { // state[v] += ((uint32_t *)p->state.d)[v - 4]; // we multiply the -4 by 4 to account for 4 bytes per int - state[v] += convertor.bytes_to_int(sd, (4 * v) - 16); + //state[v] += convertor.bytes_to_int(sd, (4 * v) - 16); + state[v] += Pack.littleEndianToInt(sd, (4 * v) - 16); } // state[14] += ((uint32_t *)p->state.d)[10] // ^ (uint32_t)cc; - state[14] += convertor.bytes_to_int(sd, 40) ^ ((int)cc); + //state[14] += convertor.bytes_to_int(sd, 40) ^ ((int)cc); + state[14] += Pack.littleEndianToInt(sd, 40) ^ ((int)cc); // state[15] += ((uint32_t *)p->state.d)[11] // ^ (uint32_t)(cc >> 32); - state[15] += convertor.bytes_to_int(sd, 44) ^ ((int)(cc >>> 32)); + //state[15] += convertor.bytes_to_int(sd, 44) ^ ((int)(cc >>> 32)); + state[15] += Pack.littleEndianToInt(sd, 44) ^ ((int)(cc >>> 32)); cc++; /* @@ -141,49 +152,47 @@ void prng_refill() // (uint8_t)(state[v] >> 16); // p->buf.d[(u << 2) + (v << 5) + 3] = // (uint8_t)(state[v] >> 24); - bd[(u << 2) + (v << 5) + 0] = - (byte)state[v]; - bd[(u << 2) + (v << 5) + 1] = - (byte)(state[v] >>> 8); - bd[(u << 2) + (v << 5) + 2] = - (byte)(state[v] >>> 16); - bd[(u << 2) + (v << 5) + 3] = - (byte)(state[v] >>> 24); + Pack.intToLittleEndian(state[v], bd, (u << 2) + (v << 5)); +// bd[index] = (byte)state[v]; +// bd[index + 1] = (byte)(state[v] >>> 8); +// bd[index + 2] = (byte)(state[v] >>> 16); +// bd[index + 3] = (byte)(state[v] >>> 24); } } // *(uint64_t *)(p->state.d + 48) = cc; - System.arraycopy(convertor.long_to_bytes(cc), 0, sd, 48, 8); + //System.arraycopy(convertor.long_to_bytes(cc), 0, sd, 48, 8); + Pack.longToLittleEndian(cc, this.sd, 48); this.ptr = 0; } /* see inner.h */ - void prng_get_bytes(byte[] srcdst, int dst, int len) - { - int buf; - - buf = dst; - while (len > 0) - { - int clen; - - clen = (bd.length) - ptr; - if (clen > len) - { - clen = len; - } -// memcpy(buf, p->buf.d, clen); - System.arraycopy(bd, 0, srcdst, buf, clen); - buf += clen; - len -= clen; - ptr += clen; - if (ptr == bd.length) - { - this.prng_refill(); - } - } - } +// void prng_get_bytes(byte[] srcdst, int dst, int len) +// { +// int buf; +// +// buf = dst; +// while (len > 0) +// { +// int clen; +// +// clen = (bd.length) - ptr; +// if (clen > len) +// { +// clen = len; +// } +//// memcpy(buf, p->buf.d, clen); +// System.arraycopy(bd, 0, srcdst, buf, clen); +// buf += clen; +// len -= clen; +// ptr += clen; +// if (ptr == bd.length) +// { +// this.prng_refill(); +// } +// } +// } private void QROUND(int a, int b, int c, int d, int[] state) { @@ -223,14 +232,15 @@ long prng_get_u64() * On systems that use little-endian encoding and allow * unaligned accesses, we can simply read the data where it is. */ - return (this.bd[u + 0] & 0xffL) - | ((this.bd[u + 1] & 0xffL) << 8) - | ((this.bd[u + 2] & 0xffL) << 16) - | ((this.bd[u + 3] & 0xffL) << 24) - | ((this.bd[u + 4] & 0xffL) << 32) - | ((this.bd[u + 5] & 0xffL) << 40) - | ((this.bd[u + 6] & 0xffL) << 48) - | ((this.bd[u + 7] & 0xffL) << 56); + return Pack.littleEndianToLong(this.bd, u); +// return (this.bd[u] & 0xffL) +// | ((this.bd[u + 1] & 0xffL) << 8) +// | ((this.bd[u + 2] & 0xffL) << 16) +// | ((this.bd[u + 3] & 0xffL) << 24) +// | ((this.bd[u + 4] & 0xffL) << 32) +// | ((this.bd[u + 5] & 0xffL) << 40) +// | ((this.bd[u + 6] & 0xffL) << 48) +// | ((this.bd[u + 7] & 0xffL) << 56); } byte prng_get_u8() diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSign.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSign.java index ff25fb7ed8..f8ef315cf4 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSign.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSign.java @@ -1,23 +1,25 @@ package org.bouncycastle.pqc.crypto.falcon; +import org.bouncycastle.crypto.digests.SHAKEDigest; + class FalconSign { - FPREngine fpr; - FalconFFT fft; - FalconCommon common; + //FPREngine fpr; + //FalconFFT fft; +// FalconCommon common; FalconSign() { - this.fpr = new FPREngine(); - this.fft = new FalconFFT(); - this.common = new FalconCommon(); + //this.fpr = new FPREngine(); + //this.fft = new FalconFFT(); +// this.common = new FalconCommon(); } - private static int MKN(int logn) - { - return 1 << logn; - } +// private static int MKN(int logn) +// { +// return 1 << logn; +// } /* * Binary case: @@ -29,19 +31,19 @@ private static int MKN(int logn) * Get the size of the LDL tree for an input with polynomials of size * 2^logn. The size is expressed in the number of elements. */ - int ffLDL_treesize(int logn) - { - /* - * For logn = 0 (polynomials are constant), the "tree" is a - * single element. Otherwise, the tree node has size 2^logn, and - * has two child trees for size logn-1 each. Thus, treesize s() - * must fulfill these two relations: - * - * s(0) = 1 - * s(logn) = (2^logn) + 2*s(logn-1) - */ - return (logn + 1) << logn; - } +// int ffLDL_treesize(int logn) +// { +// /* +// * For logn = 0 (polynomials are constant), the "tree" is a +// * single element. Otherwise, the tree node has size 2^logn, and +// * has two child trees for size logn-1 each. Thus, treesize s() +// * must fulfill these two relations: +// * +// * s(0) = 1 +// * s(logn) = (2^logn) + 2*s(logn-1) +// */ +// return (logn + 1) << logn; +// } /* * Inner function for ffLDL_fft(). It expects the matrix to be both @@ -50,45 +52,45 @@ int ffLDL_treesize(int logn) * * tmp[] must have room for at least one polynomial. */ - void ffLDL_fft_inner(FalconFPR[] srctree, int tree, - FalconFPR[] srcg0, int g0, FalconFPR[] srcg1, int g1, - int logn, FalconFPR[] srctmp, int tmp) - { - int n, hn; - - n = MKN(logn); - if (n == 1) - { - srctree[tree + 0] = srcg0[g0 + 0]; - return; - } - hn = n >> 1; - - /* - * The LDL decomposition yields L (which is written in the tree) - * and the diagonal of D. Since d00 = g0, we just write d11 - * into tmp. - */ - fft.poly_LDLmv_fft(srctmp, tmp, srctree, tree, srcg0, g0, srcg1, g1, srcg0, g0, logn); - - /* - * Split d00 (currently in g0) and d11 (currently in tmp). We - * reuse g0 and g1 as temporary storage spaces: - * d00 splits into g1, g1+hn - * d11 splits into g0, g0+hn - */ - fft.poly_split_fft(srcg1, g1, srcg1, g1 + hn, srcg0, g0, logn); - fft.poly_split_fft(srcg0, g0, srcg0, g0 + hn, srctmp, tmp, logn); - - /* - * Each split result is the first row of a new auto-adjoint - * quasicyclic matrix for the next recursive step. - */ - ffLDL_fft_inner(srctree, tree + n, - srcg1, g1, srcg1, g1 + hn, logn - 1, srctmp, tmp); - ffLDL_fft_inner(srctree, tree + n + ffLDL_treesize(logn - 1), - srcg0, g0, srcg0, g0 + hn, logn - 1, srctmp, tmp); - } +// void ffLDL_fft_inner(double[] srctree, int tree, +// double[] srcg0, int g0, double[] srcg1, int g1, +// int logn, double[] srctmp, int tmp) +// { +// int n, hn; +// +// n = MKN(logn); +// if (n == 1) +// { +// srctree[tree] = srcg0[g0]; +// return; +// } +// hn = n >> 1; +// +// /* +// * The LDL decomposition yields L (which is written in the tree) +// * and the diagonal of D. Since d00 = g0, we just write d11 +// * into tmp. +// */ +// fft.poly_LDLmv_fft(srctmp, tmp, srctree, tree, srcg0, g0, srcg1, g1, srcg0, g0, logn); +// +// /* +// * Split d00 (currently in g0) and d11 (currently in tmp). We +// * reuse g0 and g1 as temporary storage spaces: +// * d00 splits into g1, g1+hn +// * d11 splits into g0, g0+hn +// */ +// fft.poly_split_fft(srcg1, g1, srcg1, g1 + hn, srcg0, g0, logn); +// fft.poly_split_fft(srcg0, g0, srcg0, g0 + hn, srctmp, tmp, logn); +// +// /* +// * Each split result is the first row of a new auto-adjoint +// * quasicyclic matrix for the next recursive step. +// */ +// ffLDL_fft_inner(srctree, tree + n, +// srcg1, g1, srcg1, g1 + hn, logn - 1, srctmp, tmp); +// ffLDL_fft_inner(srctree, tree + n + ffLDL_treesize(logn - 1), +// srcg0, g0, srcg0, g0 + hn, logn - 1, srctmp, tmp); +// } /* * Compute the ffLDL tree of an auto-adjoint matrix G. The matrix @@ -101,66 +103,66 @@ void ffLDL_fft_inner(FalconFPR[] srctree, int tree, * arrays g00, g01 and g11. tmp[] should have room for at least three * polynomials of 2^logn elements each. */ - void ffLDL_fft(FalconFPR[] srctree, int tree, FalconFPR[] srcg00, int g00, - FalconFPR[] srcg01, int g01, FalconFPR[] srcg11, int g11, - int logn, FalconFPR[] srctmp, int tmp) - { - int n, hn; - int d00, d11; - - n = MKN(logn); - if (n == 1) - { - srctree[tree + 0] = srcg00[g00 + 0]; - return; - } - hn = n >> 1; - d00 = tmp; - d11 = tmp + n; - tmp += n << 1; - -// memcpy(d00, g00, n * sizeof *g00); - System.arraycopy(srcg00, g00, srctmp, d00, n); - fft.poly_LDLmv_fft(srctmp, d11, srctree, tree, srcg00, g00, srcg01, g01, srcg11, g11, logn); - - fft.poly_split_fft(srctmp, tmp, srctmp, tmp + hn, srctmp, d00, logn); - fft.poly_split_fft(srctmp, d00, srctmp, d00 + hn, srctmp, d11, logn); -// memcpy(d11, tmp, n * sizeof *tmp); - System.arraycopy(srctmp, tmp, srctmp, d11, n); - ffLDL_fft_inner(srctree, tree + n, - srctmp, d11, srctmp, d11 + hn, logn - 1, srctmp, tmp); - ffLDL_fft_inner(srctree, tree + n + ffLDL_treesize(logn - 1), - srctmp, d00, srctmp, d00 + hn, logn - 1, srctmp, tmp); - } +// void ffLDL_fft(double[] srctree, int tree, double[] srcg00, int g00, +// double[] srcg01, int g01, double[] srcg11, int g11, +// int logn, double[] srctmp, int tmp) +// { +// int n, hn; +// int d00, d11; +// +// n = MKN(logn); +// if (n == 1) +// { +// srctree[tree + 0] = srcg00[g00 + 0]; +// return; +// } +// hn = n >> 1; +// d00 = tmp; +// d11 = tmp + n; +// tmp += n << 1; +// +//// memcpy(d00, g00, n * sizeof *g00); +// System.arraycopy(srcg00, g00, srctmp, d00, n); +// fft.poly_LDLmv_fft(srctmp, d11, srctree, tree, srcg00, g00, srcg01, g01, srcg11, g11, logn); +// +// fft.poly_split_fft(srctmp, tmp, srctmp, tmp + hn, srctmp, d00, logn); +// fft.poly_split_fft(srctmp, d00, srctmp, d00 + hn, srctmp, d11, logn); +//// memcpy(d11, tmp, n * sizeof *tmp); +// System.arraycopy(srctmp, tmp, srctmp, d11, n); +// ffLDL_fft_inner(srctree, tree + n, +// srctmp, d11, srctmp, d11 + hn, logn - 1, srctmp, tmp); +// ffLDL_fft_inner(srctree, tree + n + ffLDL_treesize(logn - 1), +// srctmp, d00, srctmp, d00 + hn, logn - 1, srctmp, tmp); +// } /* * Normalize an ffLDL tree: each leaf of value x is replaced with * sigma / sqrt(x). */ - void ffLDL_binary_normalize(FalconFPR[] srctree, int tree, int orig_logn, int logn) - { - /* - * TODO: make an iterative version. - */ - int n; - - n = MKN(logn); - if (n == 1) - { - /* - * We actually store in the tree leaf the inverse of - * the value mandated by the specification: this - * saves a division both here and in the sampler. - */ - srctree[tree + 0] = fpr.fpr_mul(fpr.fpr_sqrt(srctree[tree + 0]), fpr.fpr_inv_sigma[orig_logn]); - } - else - { - ffLDL_binary_normalize(srctree, tree + n, orig_logn, logn - 1); - ffLDL_binary_normalize(srctree, tree + n + ffLDL_treesize(logn - 1), - orig_logn, logn - 1); - } - } +// void ffLDL_binary_normalize(double[] srctree, int tree, int orig_logn, int logn) +// { +// /* +// * TODO: make an iterative version. +// */ +// int n; +// +// n = MKN(logn); +// if (n == 1) +// { +// /* +// * We actually store in the tree leaf the inverse of +// * the value mandated by the specification: this +// * saves a division both here and in the sampler. +// */ +// srctree[tree + 0] = fpr.fpr_mul(fpr.fpr_sqrt(srctree[tree + 0]), fpr.fpr_inv_sigma[orig_logn]); +// } +// else +// { +// ffLDL_binary_normalize(srctree, tree + n, orig_logn, logn - 1); +// ffLDL_binary_normalize(srctree, tree + n + ffLDL_treesize(logn - 1), +// orig_logn, logn - 1); +// } +// } /* =================================================================== */ @@ -168,14 +170,14 @@ void ffLDL_binary_normalize(FalconFPR[] srctree, int tree, int orig_logn, int lo * Convert an integer polynomial (with small values) into the * representation with complex numbers. */ - void smallints_to_fpr(FalconFPR[] srcr, int r, byte[] srct, int t, int logn) + void smallints_to_fpr(double[] srcr, int r, byte[] srct, int logn) { int n, u; - n = MKN(logn); + n = 1 << logn; for (u = 0; u < n; u++) { - srcr[r + u] = fpr.fpr_of(srct[t + u]); // t is signed + srcr[r + u] = srct[u]; // t is signed } } @@ -185,124 +187,124 @@ void smallints_to_fpr(FalconFPR[] srcr, int r, byte[] srct, int t, int logn) * - The ffLDL tree */ - int skoff_b00(int logn) - { -// (void)logn; - return 0; - } - - int skoff_b01(int logn) - { - return MKN(logn); - } - - int skoff_b10(int logn) - { - return 2 * MKN(logn); - } - - int skoff_b11(int logn) - { - return 3 * MKN(logn); - } - - int skoff_tree(int logn) - { - return 4 * MKN(logn); - } +// int skoff_b00(int logn) +// { +//// (void)logn; +// return 0; +// } +// +// int skoff_b01(int logn) +// { +// return MKN(logn); +// } +// +// int skoff_b10(int logn) +// { +// return 2 * MKN(logn); +// } +// +// int skoff_b11(int logn) +// { +// return 3 * MKN(logn); +// } +// +// int skoff_tree(int logn) +// { +// return 4 * MKN(logn); +// } /* see inner.h */ - void expand_privkey(FalconFPR[] srcexpanded_key, int expanded_key, - byte[] srcf, int f, byte[] srcg, int g, - byte[] srcF, int F, byte[] srcG, int G, - int logn, FalconFPR[] srctmp, int tmp) - { - int n; - int rf, rg, rF, rG; - int b00, b01, b10, b11; - int g00, g01, g11, gxx; - int tree; - - n = MKN(logn); - b00 = expanded_key + skoff_b00(logn); - b01 = expanded_key + skoff_b01(logn); - b10 = expanded_key + skoff_b10(logn); - b11 = expanded_key + skoff_b11(logn); - tree = expanded_key + skoff_tree(logn); - - /* - * We load the private key elements directly into the B0 matrix, - * since B0 = [[g, -f], [G, -F]]. - */ - rf = b01; - rg = b00; - rF = b11; - rG = b10; - - smallints_to_fpr(srcexpanded_key, rf, srcf, f, logn); - smallints_to_fpr(srcexpanded_key, rg, srcg, g, logn); - smallints_to_fpr(srcexpanded_key, rF, srcF, F, logn); - smallints_to_fpr(srcexpanded_key, rG, srcG, G, logn); - - /* - * Compute the FFT for the key elements, and negate f and F. - */ - fft.FFT(srcexpanded_key, rf, logn); - fft.FFT(srcexpanded_key, rg, logn); - fft.FFT(srcexpanded_key, rF, logn); - fft.FFT(srcexpanded_key, rG, logn); - fft.poly_neg(srcexpanded_key, rf, logn); - fft.poly_neg(srcexpanded_key, rF, logn); - - /* - * The Gram matrix is G = B·B*. Formulas are: - * g00 = b00*adj(b00) + b01*adj(b01) - * g01 = b00*adj(b10) + b01*adj(b11) - * g10 = b10*adj(b00) + b11*adj(b01) - * g11 = b10*adj(b10) + b11*adj(b11) - * - * For historical reasons, this implementation uses - * g00, g01 and g11 (upper triangle). - */ - g00 = tmp; // the b__ are in srcexpanded_key and g__ are int srctmp - g01 = g00 + n; - g11 = g01 + n; - gxx = g11 + n; - -// memcpy(g00, b00, n * sizeof *b00); - System.arraycopy(srcexpanded_key, b00, srctmp, g00, n); - fft.poly_mulselfadj_fft(srctmp, g00, logn); -// memcpy(gxx, b01, n * sizeof *b01); - System.arraycopy(srcexpanded_key, b01, srctmp, gxx, n); - fft.poly_mulselfadj_fft(srctmp, gxx, logn); - fft.poly_add(srctmp, g00, srctmp, gxx, logn); - -// memcpy(g01, b00, n * sizeof *b00); - System.arraycopy(srcexpanded_key, b00, srctmp, g01, n); - fft.poly_muladj_fft(srctmp, g01, srcexpanded_key, b10, logn); -// memcpy(gxx, b01, n * sizeof *b01); - System.arraycopy(srcexpanded_key, b01, srctmp, gxx, n); - fft.poly_muladj_fft(srctmp, gxx, srcexpanded_key, b11, logn); - fft.poly_add(srctmp, g01, srctmp, gxx, logn); - -// memcpy(g11, b10, n * sizeof *b10); - System.arraycopy(srcexpanded_key, b10, srctmp, g11, n); - fft.poly_mulselfadj_fft(srctmp, g11, logn); -// memcpy(gxx, b11, n * sizeof *b11); - System.arraycopy(srcexpanded_key, b11, srctmp, gxx, n); - fft.poly_mulselfadj_fft(srctmp, gxx, logn); - fft.poly_add(srctmp, g11, srctmp, gxx, logn); - - /* - * Compute the Falcon tree. - */ - ffLDL_fft(srcexpanded_key, tree, srctmp, g00, srctmp, g01, srctmp, g11, logn, srctmp, gxx); - - /* - * Normalize tree. - */ - ffLDL_binary_normalize(srcexpanded_key, tree, logn, logn); - } +// void expand_privkey(double[] srcexpanded_key, int expanded_key, +// byte[] srcf, int f, byte[] srcg, int g, +// byte[] srcF, int F, byte[] srcG, int G, +// int logn, double[] srctmp, int tmp) +// { +// int n; +// int rf, rg, rF, rG; +// int b00, b01, b10, b11; +// int g00, g01, g11, gxx; +// int tree; +// +// n = MKN(logn); +// b00 = expanded_key + skoff_b00(logn); +// b01 = expanded_key + skoff_b01(logn); +// b10 = expanded_key + skoff_b10(logn); +// b11 = expanded_key + skoff_b11(logn); +// tree = expanded_key + skoff_tree(logn); +// +// /* +// * We load the private key elements directly into the B0 matrix, +// * since B0 = [[g, -f], [G, -F]]. +// */ +// rf = b01; +// rg = b00; +// rF = b11; +// rG = b10; +// +// smallints_to_fpr(srcexpanded_key, rf, srcf, f, logn); +// smallints_to_fpr(srcexpanded_key, rg, srcg, g, logn); +// smallints_to_fpr(srcexpanded_key, rF, srcF, F, logn); +// smallints_to_fpr(srcexpanded_key, rG, srcG, G, logn); +// +// /* +// * Compute the FFT for the key elements, and negate f and F. +// */ +// fft.FFT(srcexpanded_key, rf, logn); +// fft.FFT(srcexpanded_key, rg, logn); +// fft.FFT(srcexpanded_key, rF, logn); +// fft.FFT(srcexpanded_key, rG, logn); +// fft.poly_neg(srcexpanded_key, rf, logn); +// fft.poly_neg(srcexpanded_key, rF, logn); +// +// /* +// * The Gram matrix is G = B·B*. Formulas are: +// * g00 = b00*adj(b00) + b01*adj(b01) +// * g01 = b00*adj(b10) + b01*adj(b11) +// * g10 = b10*adj(b00) + b11*adj(b01) +// * g11 = b10*adj(b10) + b11*adj(b11) +// * +// * For historical reasons, this implementation uses +// * g00, g01 and g11 (upper triangle). +// */ +// g00 = tmp; // the b__ are in srcexpanded_key and g__ are int srctmp +// g01 = g00 + n; +// g11 = g01 + n; +// gxx = g11 + n; +// +//// memcpy(g00, b00, n * sizeof *b00); +// System.arraycopy(srcexpanded_key, b00, srctmp, g00, n); +// fft.poly_mulselfadj_fft(srctmp, g00, logn); +//// memcpy(gxx, b01, n * sizeof *b01); +// System.arraycopy(srcexpanded_key, b01, srctmp, gxx, n); +// fft.poly_mulselfadj_fft(srctmp, gxx, logn); +// fft.poly_add(srctmp, g00, srctmp, gxx, logn); +// +//// memcpy(g01, b00, n * sizeof *b00); +// System.arraycopy(srcexpanded_key, b00, srctmp, g01, n); +// fft.poly_muladj_fft(srctmp, g01, srcexpanded_key, b10, logn); +//// memcpy(gxx, b01, n * sizeof *b01); +// System.arraycopy(srcexpanded_key, b01, srctmp, gxx, n); +// fft.poly_muladj_fft(srctmp, gxx, srcexpanded_key, b11, logn); +// fft.poly_add(srctmp, g01, srctmp, gxx, logn); +// +//// memcpy(g11, b10, n * sizeof *b10); +// System.arraycopy(srcexpanded_key, b10, srctmp, g11, n); +// fft.poly_mulselfadj_fft(srctmp, g11, logn); +//// memcpy(gxx, b11, n * sizeof *b11); +// System.arraycopy(srcexpanded_key, b11, srctmp, gxx, n); +// fft.poly_mulselfadj_fft(srctmp, gxx, logn); +// fft.poly_add(srctmp, g11, srctmp, gxx, logn); +// +// /* +// * Compute the Falcon tree. +// */ +// ffLDL_fft(srcexpanded_key, tree, srctmp, g00, srctmp, g01, srctmp, g11, logn, srctmp, gxx); +// +// /* +// * Normalize tree. +// */ +// ffLDL_binary_normalize(srcexpanded_key, tree, logn, logn); +// } /* * Perform Fast Fourier Sampling for target vector t. The Gram matrix @@ -310,10 +312,10 @@ void expand_privkey(FalconFPR[] srcexpanded_key, int expanded_key, * is written over (t0,t1). The Gram matrix is modified as well. The * tmp[] buffer must have room for four polynomials. */ - void ffSampling_fft_dyntree(SamplerZ samp, SamplerCtx samp_ctx, - FalconFPR[] srct0, int t0, FalconFPR[] srct1, int t1, - FalconFPR[] srcg00, int g00, FalconFPR[] srcg01, int g01, FalconFPR[] srcg11, int g11, - int orig_logn, int logn, FalconFPR[] srctmp, int tmp) + void ffSampling_fft_dyntree(SamplerCtx samp_ctx, + double[] srct0, int t0, double[] srct1, int t1, + double[] srcg00, int g00, double[] srcg01, int g01, double[] srcg11, int g11, + int orig_logn, int logn, double[] srctmp, int tmp) { int n, hn; int z0, z1; @@ -325,12 +327,16 @@ void ffSampling_fft_dyntree(SamplerZ samp, SamplerCtx samp_ctx, */ if (logn == 0) { - FalconFPR leaf; - - leaf = srcg00[g00 + 0]; - leaf = fpr.fpr_mul(fpr.fpr_sqrt(leaf), fpr.fpr_inv_sigma[orig_logn]); - srct0[t0 + 0] = fpr.fpr_of(samp.sample(samp_ctx, srct0[t0 + 0], leaf)); - srct1[t1 + 0] = fpr.fpr_of(samp.sample(samp_ctx, srct1[t1 + 0], leaf)); + double leaf; + +// leaf = srcg00[g00 + 0]; +// leaf = fpr.fpr_mul(fpr.fpr_sqrt(leaf), fpr.fpr_inv_sigma[orig_logn]); +// srct0[t0 + 0] = fpr.fpr_of(samp.sample(samp_ctx, srct0[t0 + 0], leaf)); +// srct1[t1 + 0] = fpr.fpr_of(samp.sample(samp_ctx, srct1[t1 + 0], leaf)); + leaf = srcg00[g00]; + leaf = Math.sqrt(leaf) * FPREngine.fpr_inv_sigma[orig_logn]; + srct0[t0] = SamplerZ.sample(samp_ctx, srct0[t0], leaf); + srct1[t1] = SamplerZ.sample(samp_ctx, srct1[t1], leaf); return; } @@ -341,16 +347,16 @@ void ffSampling_fft_dyntree(SamplerZ samp, SamplerCtx samp_ctx, * Decompose G into LDL. We only need d00 (identical to g00), * d11, and l10; we do that in place. */ - fft.poly_LDL_fft(srcg00, g00, srcg01, g01, srcg11, g11, logn); + FalconFFT.poly_LDL_fft(srcg00, g00, srcg01, g01, srcg11, g11, logn); /* * Split d00 and d11 and expand them into half-size quasi-cyclic * Gram matrices. We also save l10 in tmp[]. */ - fft.poly_split_fft(srctmp, tmp, srctmp, tmp + hn, srcg00, g00, logn); + FalconFFT.poly_split_fft(srctmp, tmp, srctmp, tmp + hn, srcg00, g00, logn); // memcpy(g00, tmp, n * sizeof *tmp); System.arraycopy(srctmp, tmp, srcg00, g00, n); - fft.poly_split_fft(srctmp, tmp, srctmp, tmp + hn, srcg11, g11, logn); + FalconFFT.poly_split_fft(srctmp, tmp, srctmp, tmp + hn, srcg11, g11, logn); // memcpy(g11, tmp, n * sizeof *tmp); System.arraycopy(srctmp, tmp, srcg11, g11, n); // memcpy(tmp, g01, n * sizeof *g01); @@ -374,10 +380,10 @@ void ffSampling_fft_dyntree(SamplerZ samp, SamplerCtx samp_ctx, * back into tmp + 2*n. */ z1 = tmp + n; - fft.poly_split_fft(srctmp, z1, srctmp, z1 + hn, srct1, t1, logn); - ffSampling_fft_dyntree(samp, samp_ctx, srctmp, z1, srctmp, z1 + hn, + FalconFFT.poly_split_fft(srctmp, z1, srctmp, z1 + hn, srct1, t1, logn); + ffSampling_fft_dyntree(samp_ctx, srctmp, z1, srctmp, z1 + hn, srcg11, g11, srcg11, g11 + hn, srcg01, g01 + hn, orig_logn, logn - 1, srctmp, z1 + n); - fft.poly_merge_fft(srctmp, tmp + (n << 1), srctmp, z1, srctmp, z1 + hn, logn); + FalconFFT.poly_merge_fft(srctmp, tmp + (n << 1), srctmp, z1, srctmp, z1 + hn, logn); /* * Compute tb0 = t0 + (t1 - z1) * l10. @@ -388,250 +394,250 @@ void ffSampling_fft_dyntree(SamplerZ samp, SamplerCtx samp_ctx, */ // memcpy(z1, t1, n * sizeof *t1); System.arraycopy(srct1, t1, srctmp, z1, n); - fft.poly_sub(srctmp, z1, srctmp, tmp + (n << 1), logn); + FalconFFT.poly_sub(srctmp, z1, srctmp, tmp + (n << 1), logn); // memcpy(t1, tmp + (n << 1), n * sizeof *tmp); System.arraycopy(srctmp, tmp + (n << 1), srct1, t1, n); - fft.poly_mul_fft(srctmp, tmp, srctmp, z1, logn); - fft.poly_add(srct0, t0, srctmp, tmp, logn); + FalconFFT.poly_mul_fft(srctmp, tmp, srctmp, z1, logn); + FalconFFT.poly_add(srct0, t0, srctmp, tmp, logn); /* * Second recursive invocation, on the split tb0 (currently in t0) * and the left sub-tree. */ z0 = tmp; - fft.poly_split_fft(srctmp, z0, srctmp, z0 + hn, srct0, t0, logn); - ffSampling_fft_dyntree(samp, samp_ctx, srctmp, z0, srctmp, z0 + hn, + FalconFFT.poly_split_fft(srctmp, z0, srctmp, z0 + hn, srct0, t0, logn); + ffSampling_fft_dyntree(samp_ctx, srctmp, z0, srctmp, z0 + hn, srcg00, g00, srcg00, g00 + hn, srcg01, g01, orig_logn, logn - 1, srctmp, z0 + n); - fft.poly_merge_fft(srct0, t0, srctmp, z0, srctmp, z0 + hn, logn); + FalconFFT.poly_merge_fft(srct0, t0, srctmp, z0, srctmp, z0 + hn, logn); } /* * Perform Fast Fourier Sampling for target vector t and LDL tree T. * tmp[] must have size for at least two polynomials of size 2^logn. */ - void ffSampling_fft(SamplerZ samp, SamplerCtx samp_ctx, - FalconFPR[] srcz0, int z0, FalconFPR[] srcz1, int z1, - FalconFPR[] srctree, int tree, - FalconFPR[] srct0, int t0, FalconFPR[] srct1, int t1, int logn, - FalconFPR[] srctmp, int tmp) - { - int n, hn; - int tree0, tree1; - - /* - * When logn == 2, we inline the last two recursion levels. - */ - if (logn == 2) - { - FalconFPR x0, x1, y0, y1, w0, w1, w2, w3, sigma; - FalconFPR a_re, a_im, b_re, b_im, c_re, c_im; - - tree0 = tree + 4; - tree1 = tree + 8; - - /* - * We split t1 into w*, then do the recursive invocation, - * with output in w*. We finally merge back into z1. - */ - a_re = srct1[t1 + 0]; - a_im = srct1[t1 + 2]; - b_re = srct1[t1 + 1]; - b_im = srct1[t1 + 3]; - c_re = fpr.fpr_add(a_re, b_re); - c_im = fpr.fpr_add(a_im, b_im); - w0 = fpr.fpr_half(c_re); - w1 = fpr.fpr_half(c_im); - c_re = fpr.fpr_sub(a_re, b_re); - c_im = fpr.fpr_sub(a_im, b_im); - w2 = fpr.fpr_mul(fpr.fpr_add(c_re, c_im), fpr.fpr_invsqrt8); - w3 = fpr.fpr_mul(fpr.fpr_sub(c_im, c_re), fpr.fpr_invsqrt8); - - x0 = w2; - x1 = w3; - sigma = srctree[tree1 + 3]; - w2 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); - w3 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); - a_re = fpr.fpr_sub(x0, w2); - a_im = fpr.fpr_sub(x1, w3); - b_re = srctree[tree1 + 0]; - b_im = srctree[tree1 + 1]; - c_re = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); - c_im = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); - x0 = fpr.fpr_add(c_re, w0); - x1 = fpr.fpr_add(c_im, w1); - sigma = srctree[tree1 + 2]; - w0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); - w1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); - - a_re = w0; - a_im = w1; - b_re = w2; - b_im = w3; - c_re = fpr.fpr_mul(fpr.fpr_sub(b_re, b_im), fpr.fpr_invsqrt2); - c_im = fpr.fpr_mul(fpr.fpr_add(b_re, b_im), fpr.fpr_invsqrt2); - srcz1[z1 + 0] = w0 = fpr.fpr_add(a_re, c_re); - srcz1[z1 + 2] = w2 = fpr.fpr_add(a_im, c_im); - srcz1[z1 + 1] = w1 = fpr.fpr_sub(a_re, c_re); - srcz1[z1 + 3] = w3 = fpr.fpr_sub(a_im, c_im); - - /* - * Compute tb0 = t0 + (t1 - z1) * L. Value tb0 ends up in w*. - */ - w0 = fpr.fpr_sub(srct1[t1 + 0], w0); - w1 = fpr.fpr_sub(srct1[t1 + 1], w1); - w2 = fpr.fpr_sub(srct1[t1 + 2], w2); - w3 = fpr.fpr_sub(srct1[t1 + 3], w3); - - a_re = w0; - a_im = w2; - b_re = srctree[tree + 0]; - b_im = srctree[tree + 2]; - w0 = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); - w2 = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); - a_re = w1; - a_im = w3; - b_re = srctree[tree + 1]; - b_im = srctree[tree + 3]; - w1 = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); - w3 = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); - - w0 = fpr.fpr_add(w0, srct0[t0 + 0]); - w1 = fpr.fpr_add(w1, srct0[t0 + 1]); - w2 = fpr.fpr_add(w2, srct0[t0 + 2]); - w3 = fpr.fpr_add(w3, srct0[t0 + 3]); - - /* - * Second recursive invocation. - */ - a_re = w0; - a_im = w2; - b_re = w1; - b_im = w3; - c_re = fpr.fpr_add(a_re, b_re); - c_im = fpr.fpr_add(a_im, b_im); - w0 = fpr.fpr_half(c_re); - w1 = fpr.fpr_half(c_im); - c_re = fpr.fpr_sub(a_re, b_re); - c_im = fpr.fpr_sub(a_im, b_im); - w2 = fpr.fpr_mul(fpr.fpr_add(c_re, c_im), fpr.fpr_invsqrt8); - w3 = fpr.fpr_mul(fpr.fpr_sub(c_im, c_re), fpr.fpr_invsqrt8); - - x0 = w2; - x1 = w3; - sigma = srctree[tree0 + 3]; - w2 = y0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); - w3 = y1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); - a_re = fpr.fpr_sub(x0, y0); - a_im = fpr.fpr_sub(x1, y1); - b_re = srctree[tree0 + 0]; - b_im = srctree[tree0 + 1]; - c_re = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); - c_im = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); - x0 = fpr.fpr_add(c_re, w0); - x1 = fpr.fpr_add(c_im, w1); - sigma = srctree[tree0 + 2]; - w0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); - w1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); - - a_re = w0; - a_im = w1; - b_re = w2; - b_im = w3; - c_re = fpr.fpr_mul(fpr.fpr_sub(b_re, b_im), fpr.fpr_invsqrt2); - c_im = fpr.fpr_mul(fpr.fpr_add(b_re, b_im), fpr.fpr_invsqrt2); - srcz0[z0 + 0] = fpr.fpr_add(a_re, c_re); - srcz0[z0 + 2] = fpr.fpr_add(a_im, c_im); - srcz0[z0 + 1] = fpr.fpr_sub(a_re, c_re); - srcz0[z0 + 3] = fpr.fpr_sub(a_im, c_im); - - return; - } - - /* - * Case logn == 1 is reachable only when using Falcon-2 (the - * smallest size for which Falcon is mathematically defined, but - * of course way too insecure to be of any use). - */ - if (logn == 1) - { - FalconFPR x0, x1, y0, y1, sigma; - FalconFPR a_re, a_im, b_re, b_im, c_re, c_im; - - x0 = srct1[t1 + 0]; - x1 = srct1[t1 + 1]; - sigma = srctree[tree + 3]; - srcz1[z1 + 0] = y0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); - srcz1[z1 + 1] = y1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); - a_re = fpr.fpr_sub(x0, y0); - a_im = fpr.fpr_sub(x1, y1); - b_re = srctree[tree + 0]; - b_im = srctree[tree + 1]; - c_re = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); - c_im = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); - x0 = fpr.fpr_add(c_re, srct0[t0 + 0]); - x1 = fpr.fpr_add(c_im, srct0[t0 + 1]); - sigma = srctree[tree + 2]; - srcz0[z0 + 0] = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); - srcz0[z0 + 1] = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); - - return; - } - - /* - * Normal end of recursion is for logn == 0. Since the last - * steps of the recursions were inlined in the blocks above - * (when logn == 1 or 2), this case is not reachable, and is - * retained here only for documentation purposes. - - if (logn == 0) { - fpr x0, x1, sigma; - - x0 = t0[0]; - x1 = t1[0]; - sigma = tree[0]; - z0[0] = fpr_of(samp(samp_ctx, x0, sigma)); - z1[0] = fpr_of(samp(samp_ctx, x1, sigma)); - return; - } - - */ - - /* - * General recursive case (logn >= 3). - */ - - n = 1 << logn; - hn = n >> 1; - tree0 = tree + n; - tree1 = tree + n + ffLDL_treesize(logn - 1); - - /* - * We split t1 into z1 (reused as temporary storage), then do - * the recursive invocation, with output in tmp. We finally - * merge back into z1. - */ - fft.poly_split_fft(srcz1, z1, srcz1, z1 + hn, srct1, t1, logn); - ffSampling_fft(samp, samp_ctx, srctmp, tmp, srctmp, tmp + hn, - srctree, tree1, srcz1, z1, srcz1, z1 + hn, logn - 1, srctmp, tmp + n); - fft.poly_merge_fft(srcz1, z1, srctmp, tmp, srctmp, tmp + hn, logn); - - /* - * Compute tb0 = t0 + (t1 - z1) * L. Value tb0 ends up in tmp[]. - */ -// memcpy(tmp, t1, n * sizeof *t1); - System.arraycopy(srct1, t1, srctmp, tmp, n); - fft.poly_sub(srctmp, tmp, srcz1, z1, logn); - fft.poly_mul_fft(srctmp, tmp, srctree, tree, logn); - fft.poly_add(srctmp, tmp, srct0, t0, logn); - - /* - * Second recursive invocation. - */ - fft.poly_split_fft(srcz0, z0, srcz0, z0 + hn, srctmp, tmp, logn); - ffSampling_fft(samp, samp_ctx, srctmp, tmp, srctmp, tmp + hn, - srctree, tree0, srcz0, z0, srcz0, z0 + hn, logn - 1, srctmp, tmp + n); - fft.poly_merge_fft(srcz0, z0, srctmp, tmp, srctmp, tmp + hn, logn); - } +// void ffSampling_fft(SamplerZ samp, SamplerCtx samp_ctx, +// double[] srcz0, int z0, double[] srcz1, int z1, +// double[] srctree, int tree, +// double[] srct0, int t0, double[] srct1, int t1, int logn, +// double[] srctmp, int tmp) +// { +// int n, hn; +// int tree0, tree1; +// +// /* +// * When logn == 2, we inline the last two recursion levels. +// */ +// if (logn == 2) +// { +// double x0, x1, y0, y1, w0, w1, w2, w3, sigma; +// double a_re, a_im, b_re, b_im, c_re, c_im; +// +// tree0 = tree + 4; +// tree1 = tree + 8; +// +// /* +// * We split t1 into w*, then do the recursive invocation, +// * with output in w*. We finally merge back into z1. +// */ +// a_re = srct1[t1 + 0]; +// a_im = srct1[t1 + 2]; +// b_re = srct1[t1 + 1]; +// b_im = srct1[t1 + 3]; +// c_re = fpr.fpr_add(a_re, b_re); +// c_im = fpr.fpr_add(a_im, b_im); +// w0 = fpr.fpr_half(c_re); +// w1 = fpr.fpr_half(c_im); +// c_re = fpr.fpr_sub(a_re, b_re); +// c_im = fpr.fpr_sub(a_im, b_im); +// w2 = fpr.fpr_mul(fpr.fpr_add(c_re, c_im), fpr.fpr_invsqrt8); +// w3 = fpr.fpr_mul(fpr.fpr_sub(c_im, c_re), fpr.fpr_invsqrt8); +// +// x0 = w2; +// x1 = w3; +// sigma = srctree[tree1 + 3]; +// w2 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); +// w3 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); +// a_re = fpr.fpr_sub(x0, w2); +// a_im = fpr.fpr_sub(x1, w3); +// b_re = srctree[tree1 + 0]; +// b_im = srctree[tree1 + 1]; +// c_re = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); +// c_im = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); +// x0 = fpr.fpr_add(c_re, w0); +// x1 = fpr.fpr_add(c_im, w1); +// sigma = srctree[tree1 + 2]; +// w0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); +// w1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); +// +// a_re = w0; +// a_im = w1; +// b_re = w2; +// b_im = w3; +// c_re = fpr.fpr_mul(fpr.fpr_sub(b_re, b_im), fpr.fpr_invsqrt2); +// c_im = fpr.fpr_mul(fpr.fpr_add(b_re, b_im), fpr.fpr_invsqrt2); +// srcz1[z1 + 0] = w0 = fpr.fpr_add(a_re, c_re); +// srcz1[z1 + 2] = w2 = fpr.fpr_add(a_im, c_im); +// srcz1[z1 + 1] = w1 = fpr.fpr_sub(a_re, c_re); +// srcz1[z1 + 3] = w3 = fpr.fpr_sub(a_im, c_im); +// +// /* +// * Compute tb0 = t0 + (t1 - z1) * L. Value tb0 ends up in w*. +// */ +// w0 = fpr.fpr_sub(srct1[t1 + 0], w0); +// w1 = fpr.fpr_sub(srct1[t1 + 1], w1); +// w2 = fpr.fpr_sub(srct1[t1 + 2], w2); +// w3 = fpr.fpr_sub(srct1[t1 + 3], w3); +// +// a_re = w0; +// a_im = w2; +// b_re = srctree[tree + 0]; +// b_im = srctree[tree + 2]; +// w0 = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); +// w2 = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); +// a_re = w1; +// a_im = w3; +// b_re = srctree[tree + 1]; +// b_im = srctree[tree + 3]; +// w1 = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); +// w3 = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); +// +// w0 = fpr.fpr_add(w0, srct0[t0 + 0]); +// w1 = fpr.fpr_add(w1, srct0[t0 + 1]); +// w2 = fpr.fpr_add(w2, srct0[t0 + 2]); +// w3 = fpr.fpr_add(w3, srct0[t0 + 3]); +// +// /* +// * Second recursive invocation. +// */ +// a_re = w0; +// a_im = w2; +// b_re = w1; +// b_im = w3; +// c_re = fpr.fpr_add(a_re, b_re); +// c_im = fpr.fpr_add(a_im, b_im); +// w0 = fpr.fpr_half(c_re); +// w1 = fpr.fpr_half(c_im); +// c_re = fpr.fpr_sub(a_re, b_re); +// c_im = fpr.fpr_sub(a_im, b_im); +// w2 = fpr.fpr_mul(fpr.fpr_add(c_re, c_im), fpr.fpr_invsqrt8); +// w3 = fpr.fpr_mul(fpr.fpr_sub(c_im, c_re), fpr.fpr_invsqrt8); +// +// x0 = w2; +// x1 = w3; +// sigma = srctree[tree0 + 3]; +// w2 = y0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); +// w3 = y1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); +// a_re = fpr.fpr_sub(x0, y0); +// a_im = fpr.fpr_sub(x1, y1); +// b_re = srctree[tree0 + 0]; +// b_im = srctree[tree0 + 1]; +// c_re = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); +// c_im = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); +// x0 = fpr.fpr_add(c_re, w0); +// x1 = fpr.fpr_add(c_im, w1); +// sigma = srctree[tree0 + 2]; +// w0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); +// w1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); +// +// a_re = w0; +// a_im = w1; +// b_re = w2; +// b_im = w3; +// c_re = fpr.fpr_mul(fpr.fpr_sub(b_re, b_im), fpr.fpr_invsqrt2); +// c_im = fpr.fpr_mul(fpr.fpr_add(b_re, b_im), fpr.fpr_invsqrt2); +// srcz0[z0 + 0] = fpr.fpr_add(a_re, c_re); +// srcz0[z0 + 2] = fpr.fpr_add(a_im, c_im); +// srcz0[z0 + 1] = fpr.fpr_sub(a_re, c_re); +// srcz0[z0 + 3] = fpr.fpr_sub(a_im, c_im); +// +// return; +// } +// +// /* +// * Case logn == 1 is reachable only when using Falcon-2 (the +// * smallest size for which Falcon is mathematically defined, but +// * of course way too insecure to be of any use). +// */ +// if (logn == 1) +// { +// double x0, x1, y0, y1, sigma; +// double a_re, a_im, b_re, b_im, c_re, c_im; +// +// x0 = srct1[t1 + 0]; +// x1 = srct1[t1 + 1]; +// sigma = srctree[tree + 3]; +// srcz1[z1 + 0] = y0 = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); +// srcz1[z1 + 1] = y1 = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); +// a_re = fpr.fpr_sub(x0, y0); +// a_im = fpr.fpr_sub(x1, y1); +// b_re = srctree[tree + 0]; +// b_im = srctree[tree + 1]; +// c_re = fpr.fpr_sub(fpr.fpr_mul(a_re, b_re), fpr.fpr_mul(a_im, b_im)); +// c_im = fpr.fpr_add(fpr.fpr_mul(a_re, b_im), fpr.fpr_mul(a_im, b_re)); +// x0 = fpr.fpr_add(c_re, srct0[t0 + 0]); +// x1 = fpr.fpr_add(c_im, srct0[t0 + 1]); +// sigma = srctree[tree + 2]; +// srcz0[z0 + 0] = fpr.fpr_of(samp.sample(samp_ctx, x0, sigma)); +// srcz0[z0 + 1] = fpr.fpr_of(samp.sample(samp_ctx, x1, sigma)); +// +// return; +// } +// +// /* +// * Normal end of recursion is for logn == 0. Since the last +// * steps of the recursions were inlined in the blocks above +// * (when logn == 1 or 2), this case is not reachable, and is +// * retained here only for documentation purposes. +// +// if (logn == 0) { +// fpr x0, x1, sigma; +// +// x0 = t0[0]; +// x1 = t1[0]; +// sigma = tree[0]; +// z0[0] = fpr_of(samp(samp_ctx, x0, sigma)); +// z1[0] = fpr_of(samp(samp_ctx, x1, sigma)); +// return; +// } +// +// */ +// +// /* +// * General recursive case (logn >= 3). +// */ +// +// n = 1 << logn; +// hn = n >> 1; +// tree0 = tree + n; +// tree1 = tree + n + ffLDL_treesize(logn - 1); +// +// /* +// * We split t1 into z1 (reused as temporary storage), then do +// * the recursive invocation, with output in tmp. We finally +// * merge back into z1. +// */ +// fft.poly_split_fft(srcz1, z1, srcz1, z1 + hn, srct1, t1, logn); +// ffSampling_fft(samp, samp_ctx, srctmp, tmp, srctmp, tmp + hn, +// srctree, tree1, srcz1, z1, srcz1, z1 + hn, logn - 1, srctmp, tmp + n); +// fft.poly_merge_fft(srcz1, z1, srctmp, tmp, srctmp, tmp + hn, logn); +// +// /* +// * Compute tb0 = t0 + (t1 - z1) * L. Value tb0 ends up in tmp[]. +// */ +//// memcpy(tmp, t1, n * sizeof *t1); +// System.arraycopy(srct1, t1, srctmp, tmp, n); +// fft.poly_sub(srctmp, tmp, srcz1, z1, logn); +// fft.poly_mul_fft(srctmp, tmp, srctree, tree, logn); +// fft.poly_add(srctmp, tmp, srct0, t0, logn); +// +// /* +// * Second recursive invocation. +// */ +// fft.poly_split_fft(srcz0, z0, srcz0, z0 + hn, srctmp, tmp, logn); +// ffSampling_fft(samp, samp_ctx, srctmp, tmp, srctmp, tmp + hn, +// srctree, tree0, srcz0, z0, srcz0, z0 + hn, logn - 1, srctmp, tmp + n); +// fft.poly_merge_fft(srcz0, z0, srctmp, tmp, srctmp, tmp + hn, logn); +// } /* * Compute a signature: the signature contains two vectors, s1 and s2. @@ -643,123 +649,123 @@ void ffSampling_fft(SamplerZ samp, SamplerCtx samp_ctx, * * tmp[] must have room for at least six polynomials. */ - int do_sign_tree(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, - FalconFPR[] srcexpanded_key, int expanded_key, - short[] srchm, int hm, - int logn, FalconFPR[] srctmp, int tmp) - { - int n, u; - int t0, t1, tx, ty; - int b00, b01, b10, b11, tree; - FalconFPR ni; - int sqn, ng; - short[] s1tmp, s2tmp; - - n = MKN(logn); - t0 = tmp; - t1 = t0 + n; - b00 = expanded_key + skoff_b00(logn); - b01 = expanded_key + skoff_b01(logn); - b10 = expanded_key + skoff_b10(logn); - b11 = expanded_key + skoff_b11(logn); - tree = expanded_key + skoff_tree(logn); - - /* - * Set the target vector to [hm, 0] (hm is the hashed message). - */ - for (u = 0; u < n; u++) - { - srctmp[t0 + u] = fpr.fpr_of(srchm[hm + u]); - /* This is implicit. - t1[u] = fpr_zero; - */ - } - - /* - * Apply the lattice basis to obtain the real target - * vector (after normalization with regards to modulus). - */ - fft.FFT(srctmp, t0, logn); - ni = fpr.fpr_inverse_of_q; -// memcpy(t1, t0, n * sizeof *t0); - System.arraycopy(srctmp, t0, srctmp, t1, n); - fft.poly_mul_fft(srctmp, t1, srcexpanded_key, b01, logn); - fft.poly_mulconst(srctmp, t1, fpr.fpr_neg(ni), logn); - fft.poly_mul_fft(srctmp, t0, srcexpanded_key, b11, logn); - fft.poly_mulconst(srctmp, t0, ni, logn); - - tx = t1 + n; - ty = tx + n; - - /* - * Apply sampling. Output is written back in [tx, ty]. - */ - ffSampling_fft(samp, samp_ctx, srctmp, tx, srctmp, ty, srcexpanded_key, tree, - srctmp, t0, srctmp, t1, logn, srctmp, ty + n); - - /* - * Get the lattice point corresponding to that tiny vector. - */ -// memcpy(t0, tx, n * sizeof *tx); - System.arraycopy(srctmp, tx, srctmp, t0, n); -// memcpy(t1, ty, n * sizeof *ty); - System.arraycopy(srctmp, ty, srctmp, t1, n); - fft.poly_mul_fft(srctmp, tx, srcexpanded_key, b00, logn); - fft.poly_mul_fft(srctmp, ty, srcexpanded_key, b10, logn); - fft.poly_add(srctmp, tx, srctmp, ty, logn); -// memcpy(ty, t0, n * sizeof *t0); - System.arraycopy(srctmp, t0, srctmp, ty, n); - fft.poly_mul_fft(srctmp, ty, srcexpanded_key, b01, logn); - -// memcpy(t0, tx, n * sizeof *tx); - System.arraycopy(srctmp, tx, srctmp, t0, n); - fft.poly_mul_fft(srctmp, t1, srcexpanded_key, b11, logn); - fft.poly_add(srctmp, t1, srctmp, ty, logn); - - fft.iFFT(srctmp, t0, logn); - fft.iFFT(srctmp, t1, logn); - - /* - * Compute the signature. - */ - s1tmp = new short[n]; - sqn = 0; - ng = 0; - for (u = 0; u < n; u++) - { - int z; - // note: hm is unsigned - z = (srchm[hm + u] & 0xffff) - (int)fpr.fpr_rint(srctmp[t0 + u]); - sqn += (z * z); - ng |= sqn; - s1tmp[u] = (short)z; - } - sqn |= -(ng >>> 31); - - /* - * With "normal" degrees (e.g. 512 or 1024), it is very - * improbable that the computed vector is not short enough; - * however, it may happen in practice for the very reduced - * versions (e.g. degree 16 or below). In that case, the caller - * will loop, and we must not write anything into s2[] because - * s2[] may overlap with the hashed message hm[] and we need - * hm[] for the next iteration. - */ - s2tmp = new short[n]; - for (u = 0; u < n; u++) - { - s2tmp[u] = (short)-fpr.fpr_rint(srctmp[t1 + u]); - } - if (common.is_short_half(sqn, s2tmp, 0, logn) != 0) - { -// memcpy(s2, s2tmp, n * sizeof *s2); - System.arraycopy(s2tmp, 0, srcs2, s2, n); -// memcpy(tmp, s1tmp, n * sizeof *s1tmp); - System.arraycopy(s1tmp, 0, srctmp, tmp, n); - return 1; - } - return 0; - } +// int do_sign_tree(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, +// double[] srcexpanded_key, int expanded_key, +// short[] srchm, int hm, +// int logn, double[] srctmp, int tmp) +// { +// int n, u; +// int t0, t1, tx, ty; +// int b00, b01, b10, b11, tree; +// double ni; +// int sqn, ng; +// short[] s1tmp, s2tmp; +// +// n = MKN(logn); +// t0 = tmp; +// t1 = t0 + n; +// b00 = expanded_key + skoff_b00(logn); +// b01 = expanded_key + skoff_b01(logn); +// b10 = expanded_key + skoff_b10(logn); +// b11 = expanded_key + skoff_b11(logn); +// tree = expanded_key + skoff_tree(logn); +// +// /* +// * Set the target vector to [hm, 0] (hm is the hashed message). +// */ +// for (u = 0; u < n; u++) +// { +// srctmp[t0 + u] = fpr.fpr_of(srchm[hm + u]); +// /* This is implicit. +// t1[u] = fpr_zero; +// */ +// } +// +// /* +// * Apply the lattice basis to obtain the real target +// * vector (after normalization with regards to modulus). +// */ +// fft.FFT(srctmp, t0, logn); +// ni = fpr.fpr_inverse_of_q; +//// memcpy(t1, t0, n * sizeof *t0); +// System.arraycopy(srctmp, t0, srctmp, t1, n); +// fft.poly_mul_fft(srctmp, t1, srcexpanded_key, b01, logn); +// fft.poly_mulconst(srctmp, t1, fpr.fpr_neg(ni), logn); +// fft.poly_mul_fft(srctmp, t0, srcexpanded_key, b11, logn); +// fft.poly_mulconst(srctmp, t0, ni, logn); +// +// tx = t1 + n; +// ty = tx + n; +// +// /* +// * Apply sampling. Output is written back in [tx, ty]. +// */ +// ffSampling_fft(samp, samp_ctx, srctmp, tx, srctmp, ty, srcexpanded_key, tree, +// srctmp, t0, srctmp, t1, logn, srctmp, ty + n); +// +// /* +// * Get the lattice point corresponding to that tiny vector. +// */ +//// memcpy(t0, tx, n * sizeof *tx); +// System.arraycopy(srctmp, tx, srctmp, t0, n); +//// memcpy(t1, ty, n * sizeof *ty); +// System.arraycopy(srctmp, ty, srctmp, t1, n); +// fft.poly_mul_fft(srctmp, tx, srcexpanded_key, b00, logn); +// fft.poly_mul_fft(srctmp, ty, srcexpanded_key, b10, logn); +// fft.poly_add(srctmp, tx, srctmp, ty, logn); +//// memcpy(ty, t0, n * sizeof *t0); +// System.arraycopy(srctmp, t0, srctmp, ty, n); +// fft.poly_mul_fft(srctmp, ty, srcexpanded_key, b01, logn); +// +//// memcpy(t0, tx, n * sizeof *tx); +// System.arraycopy(srctmp, tx, srctmp, t0, n); +// fft.poly_mul_fft(srctmp, t1, srcexpanded_key, b11, logn); +// fft.poly_add(srctmp, t1, srctmp, ty, logn); +// +// fft.iFFT(srctmp, t0, logn); +// fft.iFFT(srctmp, t1, logn); +// +// /* +// * Compute the signature. +// */ +// s1tmp = new short[n]; +// sqn = 0; +// ng = 0; +// for (u = 0; u < n; u++) +// { +// int z; +// // note: hm is unsigned +// z = (srchm[hm + u] & 0xffff) - (int)fpr.fpr_rint(srctmp[t0 + u]); +// sqn += (z * z); +// ng |= sqn; +// s1tmp[u] = (short)z; +// } +// sqn |= -(ng >>> 31); +// +// /* +// * With "normal" degrees (e.g. 512 or 1024), it is very +// * improbable that the computed vector is not short enough; +// * however, it may happen in practice for the very reduced +// * versions (e.g. degree 16 or below). In that case, the caller +// * will loop, and we must not write anything into s2[] because +// * s2[] may overlap with the hashed message hm[] and we need +// * hm[] for the next iteration. +// */ +// s2tmp = new short[n]; +// for (u = 0; u < n; u++) +// { +// s2tmp[u] = (short)-fpr.fpr_rint(srctmp[t1 + u]); +// } +// if (common.is_short_half(sqn, s2tmp, logn) != 0) +// { +//// memcpy(s2, s2tmp, n * sizeof *s2); +// System.arraycopy(s2tmp, 0, srcs2, s2, n); +//// memcpy(tmp, s1tmp, n * sizeof *s1tmp); +// System.arraycopy(s1tmp, 0, srctmp, tmp, n); +// return 1; +// } +// return 0; +// } /* * Compute a signature: the signature contains two vectors, s1 and s2. @@ -770,19 +776,19 @@ int do_sign_tree(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, * * tmp[] must have room for at least nine polynomials. */ - int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, - byte[] srcf, int f, byte[] srcg, int g, - byte[] srcF, int F, byte[] srcG, int G, - short[] srchm, int hm, int logn, FalconFPR[] srctmp, int tmp) + int do_sign_dyn(SamplerCtx samp_ctx, short[] srcs2, + byte[] srcf, byte[] srcg, + byte[] srcF, byte[] srcG, + short[] srchm, int logn, double[] srctmp, int tmp) { int n, u; int t0, t1, tx, ty; int b00, b01, b10, b11, g00, g01, g11; - FalconFPR ni; + double ni; int sqn, ng; - short[] s1tmp, s2tmp; + short[] s2tmp; //s1tmp, - n = MKN(logn); + n = 1 << logn; /* * Lattice basis is B = [[g, -f], [G, -F]]. We convert it to FFT. @@ -791,16 +797,16 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, b01 = b00 + n; b10 = b01 + n; b11 = b10 + n; - smallints_to_fpr(srctmp, b01, srcf, f, logn); - smallints_to_fpr(srctmp, b00, srcg, g, logn); - smallints_to_fpr(srctmp, b11, srcF, F, logn); - smallints_to_fpr(srctmp, b10, srcG, G, logn); - fft.FFT(srctmp, b01, logn); - fft.FFT(srctmp, b00, logn); - fft.FFT(srctmp, b11, logn); - fft.FFT(srctmp, b10, logn); - fft.poly_neg(srctmp, b01, logn); - fft.poly_neg(srctmp, b11, logn); + smallints_to_fpr(srctmp, b01, srcf, logn); + smallints_to_fpr(srctmp, b00, srcg, logn); + smallints_to_fpr(srctmp, b11, srcF, logn); + smallints_to_fpr(srctmp, b10, srcG, logn); + FalconFFT.FFT(srctmp, b01, logn); + FalconFFT.FFT(srctmp, b00, logn); + FalconFFT.FFT(srctmp, b11, logn); + FalconFFT.FFT(srctmp, b10, logn); + FalconFFT.poly_neg(srctmp, b01, logn); + FalconFFT.poly_neg(srctmp, b11, logn); /* * Compute the Gram matrix G = B·B*. Formulas are: @@ -821,23 +827,23 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, // memcpy(t0, b01, n * sizeof *b01); System.arraycopy(srctmp, b01, srctmp, t0, n); - fft.poly_mulselfadj_fft(srctmp, t0, logn); // t0 <- b01*adj(b01) + FalconFFT.poly_mulselfadj_fft(srctmp, t0, logn); // t0 <- b01*adj(b01) // memcpy(t1, b00, n * sizeof *b00); System.arraycopy(srctmp, b00, srctmp, t1, n); - fft.poly_muladj_fft(srctmp, t1, srctmp, b10, logn); // t1 <- b00*adj(b10) - fft.poly_mulselfadj_fft(srctmp, b00, logn); // b00 <- b00*adj(b00) - fft.poly_add(srctmp, b00, srctmp, t0, logn); // b00 <- g00 + FalconFFT.poly_muladj_fft(srctmp, t1, srctmp, b10, logn); // t1 <- b00*adj(b10) + FalconFFT.poly_mulselfadj_fft(srctmp, b00, logn); // b00 <- b00*adj(b00) + FalconFFT.poly_add(srctmp, b00, srctmp, t0, logn); // b00 <- g00 // memcpy(t0, b01, n * sizeof *b01); System.arraycopy(srctmp, b01, srctmp, t0, n); - fft.poly_muladj_fft(srctmp, b01, srctmp, b11, logn); // b01 <- b01*adj(b11) - fft.poly_add(srctmp, b01, srctmp, t1, logn); // b01 <- g01 + FalconFFT.poly_muladj_fft(srctmp, b01, srctmp, b11, logn); // b01 <- b01*adj(b11) + FalconFFT.poly_add(srctmp, b01, srctmp, t1, logn); // b01 <- g01 - fft.poly_mulselfadj_fft(srctmp, b10, logn); // b10 <- b10*adj(b10) + FalconFFT.poly_mulselfadj_fft(srctmp, b10, logn); // b10 <- b10*adj(b10) // memcpy(t1, b11, n * sizeof *b11); System.arraycopy(srctmp, b11, srctmp, t1, n); - fft.poly_mulselfadj_fft(srctmp, t1, logn); // t1 <- b11*adj(b11) - fft.poly_add(srctmp, b10, srctmp, t1, logn); // b10 <- g11 + FalconFFT.poly_mulselfadj_fft(srctmp, t1, logn); // t1 <- b11*adj(b11) + FalconFFT.poly_add(srctmp, b10, srctmp, t1, logn); // b10 <- g11 /* * We rename variables to make things clearer. The three elements @@ -861,7 +867,7 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, */ for (u = 0; u < n; u++) { - srctmp[t0 + u] = fpr.fpr_of(srchm[hm + u]); + srctmp[t0 + u] = srchm[u]; /* This is implicit. t1[u] = fpr_zero; */ @@ -871,14 +877,14 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, * Apply the lattice basis to obtain the real target * vector (after normalization with regards to modulus). */ - fft.FFT(srctmp, t0, logn); - ni = fpr.fpr_inverse_of_q; + FalconFFT.FFT(srctmp, t0, logn); + ni = FPREngine.fpr_inverse_of_q; // memcpy(t1, t0, n * sizeof *t0); System.arraycopy(srctmp, t0, srctmp, t1, n); - fft.poly_mul_fft(srctmp, t1, srctmp, b01, logn); - fft.poly_mulconst(srctmp, t1, fpr.fpr_neg(ni), logn); - fft.poly_mul_fft(srctmp, t0, srctmp, b11, logn); - fft.poly_mulconst(srctmp, t0, ni, logn); + FalconFFT.poly_mul_fft(srctmp, t1, srctmp, b01, logn); + FalconFFT.poly_mulconst(srctmp, t1, -ni, logn); + FalconFFT.poly_mul_fft(srctmp, t0, srctmp, b11, logn); + FalconFFT.poly_mulconst(srctmp, t0, ni, logn); /* * b01 and b11 can be discarded, so we move back (t0,t1). @@ -893,7 +899,7 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, /* * Apply sampling; result is written over (t0,t1). */ - ffSampling_fft_dyntree(samp, samp_ctx, + ffSampling_fft_dyntree(samp_ctx, srctmp, t0, srctmp, t1, srctmp, g00, srctmp, g01, srctmp, g11, logn, logn, srctmp, t1 + n); @@ -905,7 +911,7 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, * We did not conserve the matrix basis, so we must recompute * it now. */ - b00 = tmp; + //b00 = tmp; b01 = b00 + n; b10 = b01 + n; b11 = b10 + n; @@ -913,16 +919,16 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, System.arraycopy(srctmp, t0, srctmp, b11 + n, n * 2); t0 = b11 + n; t1 = t0 + n; - smallints_to_fpr(srctmp, b01, srcf, f, logn); - smallints_to_fpr(srctmp, b00, srcg, g, logn); - smallints_to_fpr(srctmp, b11, srcF, F, logn); - smallints_to_fpr(srctmp, b10, srcG, G, logn); - fft.FFT(srctmp, b01, logn); - fft.FFT(srctmp, b00, logn); - fft.FFT(srctmp, b11, logn); - fft.FFT(srctmp, b10, logn); - fft.poly_neg(srctmp, b01, logn); - fft.poly_neg(srctmp, b11, logn); + smallints_to_fpr(srctmp, b01, srcf, logn); + smallints_to_fpr(srctmp, b00, srcg, logn); + smallints_to_fpr(srctmp, b11, srcF, logn); + smallints_to_fpr(srctmp, b10, srcG, logn); + FalconFFT.FFT(srctmp, b01, logn); + FalconFFT.FFT(srctmp, b00, logn); + FalconFFT.FFT(srctmp, b11, logn); + FalconFFT.FFT(srctmp, b10, logn); + FalconFFT.poly_neg(srctmp, b01, logn); + FalconFFT.poly_neg(srctmp, b11, logn); tx = t1 + n; ty = tx + n; @@ -933,31 +939,31 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, System.arraycopy(srctmp, t0, srctmp, tx, n); // memcpy(ty, t1, n * sizeof *t1); System.arraycopy(srctmp, t1, srctmp, ty, n); - fft.poly_mul_fft(srctmp, tx, srctmp, b00, logn); - fft.poly_mul_fft(srctmp, ty, srctmp, b10, logn); - fft.poly_add(srctmp, tx, srctmp, ty, logn); + FalconFFT.poly_mul_fft(srctmp, tx, srctmp, b00, logn); + FalconFFT.poly_mul_fft(srctmp, ty, srctmp, b10, logn); + FalconFFT.poly_add(srctmp, tx, srctmp, ty, logn); // memcpy(ty, t0, n * sizeof *t0); System.arraycopy(srctmp, t0, srctmp, ty, n); - fft.poly_mul_fft(srctmp, ty, srctmp, b01, logn); + FalconFFT.poly_mul_fft(srctmp, ty, srctmp, b01, logn); // memcpy(t0, tx, n * sizeof *tx); System.arraycopy(srctmp, tx, srctmp, t0, n); - fft.poly_mul_fft(srctmp, t1, srctmp, b11, logn); - fft.poly_add(srctmp, t1, srctmp, ty, logn); - fft.iFFT(srctmp, t0, logn); - fft.iFFT(srctmp, t1, logn); + FalconFFT.poly_mul_fft(srctmp, t1, srctmp, b11, logn); + FalconFFT.poly_add(srctmp, t1, srctmp, ty, logn); + FalconFFT.iFFT(srctmp, t0, logn); + FalconFFT.iFFT(srctmp, t1, logn); - s1tmp = new short[n]; + //s1tmp = new short[n]; sqn = 0; ng = 0; for (u = 0; u < n; u++) { int z; - z = (srchm[hm + u] & 0xffff) - (int)fpr.fpr_rint(srctmp[t0 + u]); + z = (srchm[u] & 0xffff) - (int)FPREngine.fpr_rint(srctmp[t0 + u]); sqn += (z * z); ng |= sqn; - s1tmp[u] = (short)z; + //s1tmp[u] = (short)z; } sqn |= -(ng >>> 31); @@ -973,12 +979,12 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, s2tmp = new short[n]; for (u = 0; u < n; u++) { - s2tmp[u] = (short)-fpr.fpr_rint(srctmp[t1 + u]); + s2tmp[u] = (short)-FPREngine.fpr_rint(srctmp[t1 + u]); } - if (common.is_short_half(sqn, s2tmp, 0, logn) != 0) + if (FalconCommon.is_short_half(sqn, s2tmp, logn) != 0) { // memcpy(s2, s2tmp, n * sizeof *s2); - System.arraycopy(s2tmp, 0, srcs2, s2, n); + System.arraycopy(s2tmp, 0, srcs2, 0, n); // memcpy(tmp, s1tmp, n * sizeof *s1tmp); // System.arraycopy(s1tmp, 0, srctmp, tmp, n); return 1; @@ -988,57 +994,57 @@ int do_sign_dyn(SamplerZ samp, SamplerCtx samp_ctx, short[] srcs2, int s2, /* see inner.h */ - void sign_tree(short[] srcsig, int sig, SHAKE256 rng, - FalconFPR[] srcexpanded_key, int expanded_key, - short[] srchm, int hm, int logn, FalconFPR[] srctmp, int tmp) - { - int ftmp; - - ftmp = tmp; - for (; ; ) - { - /* - * Signature produces short vectors s1 and s2. The - * signature is acceptable only if the aggregate vector - * s1,s2 is short; we must use the same bound as the - * verifier. - * - * If the signature is acceptable, then we return only s2 - * (the verifier recomputes s1 from s2, the hashed message, - * and the public key). - */ - SamplerCtx spc = new SamplerCtx(); - SamplerZ samp = new SamplerZ(); - SamplerCtx samp_ctx; - - /* - * Normal sampling. We use a fast PRNG seeded from our - * SHAKE context ('rng'). - */ - spc.sigma_min = fpr.fpr_sigma_min[logn]; - spc.p.prng_init(rng); - samp_ctx = spc; - - /* - * Do the actual signature. - */ - if (do_sign_tree(samp, samp_ctx, srcsig, sig, - srcexpanded_key, expanded_key, srchm, hm, logn, srctmp, ftmp) != 0) - { - break; - } - } - } +// void sign_tree(short[] srcsig, int sig, SHAKE256 rng, +// double[] srcexpanded_key, int expanded_key, +// short[] srchm, int hm, int logn, double[] srctmp, int tmp) +// { +// int ftmp; +// +// ftmp = tmp; +// for (; ; ) +// { +// /* +// * Signature produces short vectors s1 and s2. The +// * signature is acceptable only if the aggregate vector +// * s1,s2 is short; we must use the same bound as the +// * verifier. +// * +// * If the signature is acceptable, then we return only s2 +// * (the verifier recomputes s1 from s2, the hashed message, +// * and the public key). +// */ +// SamplerCtx spc = new SamplerCtx(); +// SamplerZ samp = new SamplerZ(); +// SamplerCtx samp_ctx; +// +// /* +// * Normal sampling. We use a fast PRNG seeded from our +// * SHAKE context ('rng'). +// */ +// spc.sigma_min = fpr.fpr_sigma_min[logn]; +// spc.p.prng_init(rng); +// samp_ctx = spc; +// +// /* +// * Do the actual signature. +// */ +// if (do_sign_tree(samp, samp_ctx, srcsig, sig, +// srcexpanded_key, expanded_key, srchm, hm, logn, srctmp, ftmp) != 0) +// { +// break; +// } +// } +// } /* see inner.h */ - void sign_dyn(short[] srcsig, int sig, SHAKE256 rng, - byte[] srcf, int f, byte[] srcg, int g, - byte[] srcF, int F, byte[] srcG, int G, - short[] srchm, int hm, int logn, FalconFPR[] srctmp, int tmp) + void sign_dyn(short[] srcsig, SHAKEDigest rng, + byte[] srcf, byte[] srcg, + byte[] srcF, byte[] srcG, + short[] srchm, int logn, double[] srctmp) { int ftmp; - ftmp = tmp; + ftmp = 0; for (; ; ) { /* @@ -1052,22 +1058,22 @@ void sign_dyn(short[] srcsig, int sig, SHAKE256 rng, * and the public key). */ SamplerCtx spc = new SamplerCtx(); - SamplerZ samp = new SamplerZ(); - SamplerCtx samp_ctx; +// SamplerZ samp = new SamplerZ(); +// SamplerCtx samp_ctx; /* * Normal sampling. We use a fast PRNG seeded from our * SHAKE context ('rng'). */ - spc.sigma_min = fpr.fpr_sigma_min[logn]; + spc.sigma_min = FPREngine.fpr_sigma_min[logn]; spc.p.prng_init(rng); - samp_ctx = spc; +// samp_ctx = spc; /* * Do the actual signature. */ - if (do_sign_dyn(samp, samp_ctx, srcsig, sig, - srcf, f, srcg, g, srcF, F, srcG, G, srchm, hm, logn, srctmp, ftmp) != 0) + if (do_sign_dyn(spc, srcsig, + srcf, srcg, srcF, srcG, srchm, logn, srctmp, ftmp) != 0) { break; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSigner.java index 43e567df1e..f5c9bd18c7 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSigner.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconSigner.java @@ -4,7 +4,6 @@ import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.pqc.crypto.MessageSigner; -import org.bouncycastle.util.encoders.Hex; public class FalconSigner implements MessageSigner @@ -47,7 +46,7 @@ public byte[] generateSignature(byte[] message) { byte[] sm = new byte[nist.CRYPTO_BYTES]; - return nist.crypto_sign(false, sm, message, 0, message.length, encodedkey, 0); + return nist.crypto_sign(sm, message, message.length, encodedkey); } public boolean verifySignature(byte[] message, byte[] signature) @@ -60,7 +59,6 @@ public boolean verifySignature(byte[] message, byte[] signature) byte[] sig = new byte[signature.length - nist.NONCELEN - 1]; System.arraycopy(signature, 1, nonce, 0, nist.NONCELEN); System.arraycopy(signature, nist.NONCELEN + 1, sig, 0, signature.length - nist.NONCELEN - 1); - boolean res = nist.crypto_sign_open(false, sig,nonce,message,encodedkey,0) == 0; - return res; + return nist.crypto_sign_open(sig,nonce,message,encodedkey) == 0; } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconVrfy.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconVrfy.java index 5478bdc2a5..636912ae46 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconVrfy.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/FalconVrfy.java @@ -3,11 +3,11 @@ class FalconVrfy { - FalconCommon common; +// FalconCommon common; FalconVrfy() { - this.common = new FalconCommon(); +// this.common = new FalconCommon(); } /* ===================================================================== */ /* @@ -25,10 +25,10 @@ class FalconVrfy // #define Q0I 12287 // #define R 4091 // #define R2 10952 - final int Q = 12289; - final int Q0I = 12287; - final int R = 4091; - final int R2 = 10952; + static final int Q = 12289; + static final int Q0I = 12287; + static final int R = 4091; + static final int R2 = 10952; /* * Table for NTT, binary case: @@ -36,7 +36,7 @@ class FalconVrfy * where g = 7 (it is a 2048-th primitive root of 1 modulo q) * and rev() is the bit-reversal function over 10 bits. */ - final short[] GMb = { + static final short[] GMb = { 4091, 7888, 11060, 11208, 6960, 4342, 6275, 9759, 1591, 6399, 9477, 5266, 586, 5825, 7538, 9710, 1134, 6407, 1711, 965, 7099, 7674, 3743, 6442, @@ -172,7 +172,7 @@ class FalconVrfy * iGMb[x] = R*((1/g)^rev(x)) mod q * Since g = 7, 1/g = 8778 mod 12289. */ - final short[] iGMb = { + static final short[] iGMb = { 4091, 4401, 1081, 1229, 2530, 6014, 7947, 5329, 2579, 4751, 6464, 11703, 7023, 2812, 5890, 10698, 3109, 2125, 1960, 10925, 10601, 10404, 4189, 1875, @@ -307,23 +307,23 @@ class FalconVrfy * Reduce a small signed integer modulo q. The source integer MUST * be between -q/2 and +q/2. */ - int mq_conv_small(int x) + static int mq_conv_small(int x) { /* * If x < 0, the cast to uint32_t will set the high bit to 1. * ^ in Java, integers already use 2s complement so high bit will be 1 if negative */ - int y; - - y = x; - y += Q & -(y >>> 31); - return y; +// int x; +// +// x = x; + x += Q & -(x >>> 31); + return x; } /* * Addition modulo q. Operands must be in the 0..q-1 range. */ - int mq_add(int x, int y) + static int mq_add(int x, int y) { /* * We compute x + y - q. If the result is negative, then the @@ -342,7 +342,7 @@ int mq_add(int x, int y) /* * Subtraction modulo q. Operands must be in the 0..q-1 range. */ - int mq_sub(int x, int y) + static int mq_sub(int x, int y) { /* * As in mq_add(), we use a conditional addition to ensure the @@ -358,7 +358,7 @@ int mq_sub(int x, int y) /* * Division by 2 modulo q. Operand must be in the 0..q-1 range. */ - int mq_rshift1(int x) + static int mq_rshift1(int x) { x += Q & -(x & 1); return (x >>> 1); @@ -369,7 +369,7 @@ int mq_rshift1(int x) * this function computes: x * y / R mod q * Operands must be in the 0..q-1 range. */ - int mq_montymul(int x, int y) + static int mq_montymul(int x, int y) { int z, w; @@ -404,7 +404,7 @@ int mq_montymul(int x, int y) /* * Montgomery squaring (computes (x^2)/R). */ - int mq_montysqr(int x) + static int mq_montysqr(int x) { return mq_montymul(x, x); } @@ -412,7 +412,7 @@ int mq_montysqr(int x) /* * Divide x by y modulo q = 12289. */ - int mq_div_12289(int x, int y) + static int mq_div_12289(int x, int y) { /* * We invert y by computing y^(q-2) mod q. @@ -477,7 +477,7 @@ int mq_div_12289(int x, int y) /* * Compute NTT on a ring element. */ - void mq_NTT(short[] srca, int a, int logn) + static void mq_NTT(short[] srca, int a, int logn) { int n, t, m; @@ -512,7 +512,7 @@ void mq_NTT(short[] srca, int a, int logn) /* * Compute the inverse NTT on a ring element, binary case. */ - void mq_iNTT(short[] srca, int a, int logn) + static void mq_iNTT(short[] srca, int a, int logn) { int n, t, m; int ni; @@ -571,7 +571,7 @@ void mq_iNTT(short[] srca, int a, int logn) /* * Convert a polynomial (mod q) to Montgomery representation. */ - void mq_poly_tomonty(short[] srcf, int f, int logn) + static void mq_poly_tomonty(short[] srcf, int f, int logn) { int u, n; @@ -586,7 +586,7 @@ void mq_poly_tomonty(short[] srcf, int f, int logn) * Multiply two polynomials together (NTT representation, and using * a Montgomery multiplication). Result f*g is written over f. */ - void mq_poly_montymul_ntt(short[] srcf, int f, short[] srcg, int g, int logn) + static void mq_poly_montymul_ntt(short[] srcf, int f, short[] srcg, int g, int logn) { int u, n; @@ -600,35 +600,35 @@ void mq_poly_montymul_ntt(short[] srcf, int f, short[] srcg, int g, int logn) /* * Subtract polynomial g from polynomial f. */ - void mq_poly_sub(short[] srcf, int f, short[] srcg, int g, int logn) + static void mq_poly_sub(short[] srcf, int f, short[] srcg, int logn) { int u, n; n = 1 << logn; for (u = 0; u < n; u++) { - srcf[f + u] = (short)mq_sub(srcf[f + u], srcg[g + u]); + srcf[f + u] = (short)mq_sub(srcf[f + u], srcg[u]); } } /* ===================================================================== */ /* see inner.h */ - void to_ntt_monty(short[] srch, int h, int logn) + static void to_ntt_monty(short[] srch, int logn) { - mq_NTT(srch, h, logn); - mq_poly_tomonty(srch, h, logn); + mq_NTT(srch, 0, logn); + mq_poly_tomonty(srch, 0, logn); } /* see inner.h */ - int verify_raw(short[] srcc0, int c0, short[] srcs2, int s2, - short[] srch, int h, int logn, short[] srctmp, int tmp) + static int verify_raw(short[] srcc0, short[] srcs2, + short[] srch, int logn, short[] srctmp) { int u, n; int tt; n = 1 << logn; - tt = tmp; + tt = 0; /* * Reduce s2 elements modulo q ([0..q-1] range). @@ -637,7 +637,7 @@ int verify_raw(short[] srcc0, int c0, short[] srcs2, int s2, { int w; - w = (int)srcs2[s2 + u]; // s2 is signed, so ( & 0xffff) is not needed + w = srcs2[u]; // s2 is signed, so ( & 0xffff) is not needed w += Q & -(w >>> 31); srctmp[tt + u] = (short)w; } @@ -646,9 +646,9 @@ int verify_raw(short[] srcc0, int c0, short[] srcs2, int s2, * Compute -s1 = s2*h - c0 mod phi mod q (in tt[]). */ mq_NTT(srctmp, tt, logn); - mq_poly_montymul_ntt(srctmp, tt, srch, h, logn); + mq_poly_montymul_ntt(srctmp, tt, srch, 0, logn); mq_iNTT(srctmp, tt, logn); - mq_poly_sub(srctmp, tt, srcc0, c0, logn); + mq_poly_sub(srctmp, tt, srcc0, logn); /* * Normalize -s1 elements into the [-q/2..q/2] range. @@ -666,12 +666,12 @@ int verify_raw(short[] srcc0, int c0, short[] srcs2, int s2, * Signature is valid if and only if the aggregate (-s1,s2) vector * is short enough. */ - return common.is_short(srctmp, tt, srcs2, s2, logn); + return FalconCommon.is_short(srctmp, tt, srcs2, logn); } /* see inner.h */ - int compute_public(short[] srch, int h, - byte[] srcf, int f, byte[] srcg, int g, int logn, short[] srctmp, int tmp) + static int compute_public(short[] srch, int h, + byte[] srcf, byte[] srcg, int logn, short[] srctmp, int tmp) { int u, n; int tt; @@ -680,8 +680,8 @@ int compute_public(short[] srch, int h, tt = tmp; for (u = 0; u < n; u++) { - srctmp[tt + u] = (short)mq_conv_small(srcf[f + u]); - srch[h + u] = (short)mq_conv_small(srcg[g + u]); + srctmp[tt + u] = (short)mq_conv_small(srcf[u]); + srch[h + u] = (short)mq_conv_small(srcg[u]); } mq_NTT(srch, h, logn); mq_NTT(srctmp, tt, logn); @@ -698,21 +698,21 @@ int compute_public(short[] srch, int h, } /* see inner.h */ - boolean complete_private(byte[] srcG, int G, - byte[] srcf, int f, byte[] srcg, int g, byte[] srcF, int F, - int logn, short[] srctmp, int tmp) + static boolean complete_private(byte[] srcG, + byte[] srcf, byte[] srcg, byte[] srcF, + int logn, short[] srctmp) { - boolean success = true; + int success = -1; int u, n; int t1, t2; n = 1 << logn; - t1 = tmp; + t1 = 0; t2 = t1 + n; for (u = 0; u < n; u++) { - srctmp[t1 + u] = (short)mq_conv_small(srcg[g + u]); - srctmp[t2 + u] = (short)mq_conv_small(srcF[F + u]); + srctmp[t1 + u] = (short)mq_conv_small(srcg[u]); + srctmp[t2 + u] = (short)mq_conv_small(srcF[u]); } mq_NTT(srctmp, t1, logn); mq_NTT(srctmp, t2, logn); @@ -720,140 +720,138 @@ boolean complete_private(byte[] srcG, int G, mq_poly_montymul_ntt(srctmp, t1, srctmp, t2, logn); for (u = 0; u < n; u++) { - srctmp[t2 + u] = (short)mq_conv_small(srcf[f + u]); + srctmp[t2 + u] = (short)mq_conv_small(srcf[u]); } mq_NTT(srctmp, t2, logn); for (u = 0; u < n; u++) { - success &= (srctmp[t2 + u] != 0); + int tmp2 = srctmp[t2 + u] & 0xffff; + success &= -tmp2; // check tmp2 != 0 srctmp[t1 + u] = (short)mq_div_12289(srctmp[t1 + u], srctmp[t2 + u]); } mq_iNTT(srctmp, t1, logn); for (u = 0; u < n; u++) { - int w; - int gi; - - w = (srctmp[t1 + u] & 0xffff); - w -= (Q & ~-((w - (Q >> 1)) >>> 31)); // w is unsigned - gi = w; // gi is signed - success &= !(gi < -127 || gi > +127); - srcG[G + u] = (byte)gi; + int w = srctmp[t1 + u] & 0xffff; + int gi = w - (Q & (((Q >> 1) - w) >> 31)); + success &= gi - 128; // check +gi < 128 + success &= -gi - 128; // check -gi < 128 + srcG[u] = (byte)gi; } - return success; + return success < 0; } /* see inner.h */ - int is_invertible(short[] srcs2, int s2, int logn, short[] srctmp, int tmp) - { - int u, n; - int tt; - int r; - - n = 1 << logn; - tt = tmp; - for (u = 0; u < n; u++) - { - int w; - - w = (int)srcs2[s2 + u]; // s2 is signed - w += Q & -(w >>> 31); - srctmp[tt + u] = (short)w; - } - mq_NTT(srctmp, tt, logn); - r = 0; - for (u = 0; u < n; u++) - { - r |= (srctmp[tt + u] & 0xffff) - 1; - } - return (1 - (r >>> 31)); - } +// int is_invertible(short[] srcs2, int s2, int logn, short[] srctmp, int tmp) +// { +// int u, n; +// int tt; +// int r; +// +// n = 1 << logn; +// tt = tmp; +// for (u = 0; u < n; u++) +// { +// int w; +// +// w = (int)srcs2[s2 + u]; // s2 is signed +// w += Q & -(w >>> 31); +// srctmp[tt + u] = (short)w; +// } +// mq_NTT(srctmp, tt, logn); +// r = 0; +// for (u = 0; u < n; u++) +// { +// r |= (srctmp[tt + u] & 0xffff) - 1; +// } +// return (1 - (r >>> 31)); +// } /* see inner.h */ - int verify_recover(short[] srch, int h, - short[] srcc0, int c0, short[] srcs1, int s1, short[] srcs2, int s2, - int logn, short[] srctmp, int tmp) - { - int u, n; - int tt; - int r; - - n = 1 << logn; - - /* - * Reduce elements of s1 and s2 modulo q; then write s2 into tt[] - * and c0 - s1 into h[]. - */ - tt = tmp; - for (u = 0; u < n; u++) - { - int w; - - w = (int)srcs2[s2 + u]; // s2 is signed - w += Q & -(w >> 31); - srctmp[tt + u] = (short)w; - - w = (int)srcs1[s1 + u]; // s2 is signed - w += Q & -(w >>> 31); - w = mq_sub((srcc0[c0 + u]), w & 0xffff); // c0 is unsigned - srch[h + u] = (short)w; - } - - /* - * Compute h = (c0 - s1) / s2. If one of the coefficients of s2 - * is zero (in NTT representation) then the operation fails. We - * keep that information into a flag so that we do not deviate - * from strict constant-time processing; if all coefficients of - * s2 are non-zero, then the high bit of r will be zero. - */ - mq_NTT(srctmp, tt, logn); - mq_NTT(srctmp, h, logn); - r = 0; - for (u = 0; u < n; u++) - { - r |= (srctmp[tt + u] & 0xffff) - 1; - srch[h + u] = (short)mq_div_12289((srch[h + u] & 0xffff), - (srctmp[tt + u]) & 0xffff); - } - mq_iNTT(srch, h, logn); - - /* - * Signature is acceptable if and only if it is short enough, - * and s2 was invertible mod phi mod q. The caller must still - * check that the rebuilt public key matches the expected - * value (e.g. through a hash). - */ - r = ~r & -common.is_short(srcs1, s1, srcs2, s2, logn); - return (int)(r >>> 31); - } +// int verify_recover(short[] srch, int h, +// short[] srcc0, int c0, short[] srcs1, int s1, short[] srcs2, int s2, +// int logn, short[] srctmp, int tmp) +// { +// int u, n; +// int tt; +// int r; +// +// n = 1 << logn; +// +// /* +// * Reduce elements of s1 and s2 modulo q; then write s2 into tt[] +// * and c0 - s1 into h[]. +// */ +// tt = tmp; +// for (u = 0; u < n; u++) +// { +// int w; +// +// w = (int)srcs2[s2 + u]; // s2 is signed +// w += Q & -(w >> 31); +// srctmp[tt + u] = (short)w; +// +// w = (int)srcs1[s1 + u]; // s2 is signed +// w += Q & -(w >>> 31); +// w = mq_sub((srcc0[c0 + u]), w & 0xffff); // c0 is unsigned +// srch[h + u] = (short)w; +// } +// +// /* +// * Compute h = (c0 - s1) / s2. If one of the coefficients of s2 +// * is zero (in NTT representation) then the operation fails. We +// * keep that information into a flag so that we do not deviate +// * from strict constant-time processing; if all coefficients of +// * s2 are non-zero, then the high bit of r will be zero. +// */ +// mq_NTT(srctmp, tt, logn); +// mq_NTT(srctmp, h, logn); +// r = 0; +// for (u = 0; u < n; u++) +// { +// r |= (srctmp[tt + u] & 0xffff) - 1; +// srch[h + u] = (short)mq_div_12289((srch[h + u] & 0xffff), +// (srctmp[tt + u]) & 0xffff); +// } +// mq_iNTT(srch, h, logn); +// +// /* +// * Signature is acceptable if and only if it is short enough, +// * and s2 was invertible mod phi mod q. The caller must still +// * check that the rebuilt public key matches the expected +// * value (e.g. through a hash). +// */ +// r = ~r & -FalconCommon.is_short(srcs1, s1, srcs2, s2, logn); +// return (int)(r >>> 31); +// } /* see inner.h */ - int count_nttzero(short[] srcsig, int sig, int logn, short[] srctmp, int tmp) - { - int s2; - int u, n; - int r; - - n = 1 << logn; - s2 = tmp; - for (u = 0; u < n; u++) - { - int w; - - w = (int)srcsig[sig + u]; // sig is signed - w += Q & -(w >>> 31); - srctmp[s2 + u] = (short)w; - } - mq_NTT(srctmp, s2, logn); - r = 0; - for (u = 0; u < n; u++) - { - int w; - - w = (srctmp[s2 + u] & 0xffff) - 1; // s2 is unsigned - r += (w >>> 31); - } - return (int)r; - } +// int count_nttzero(short[] srcsig, int sig, int logn, short[] srctmp, int tmp) +// { +// int s2; +// int u, n; +// int r; +// +// n = 1 << logn; +// s2 = tmp; +// for (u = 0; u < n; u++) +// { +// int w; +// +// w = (int)srcsig[sig + u]; // sig is signed +// w += Q & -(w >>> 31); +// srctmp[s2 + u] = (short)w; +// } +// mq_NTT(srctmp, s2, logn); +// r = 0; +// for (u = 0; u < n; u++) +// { +// int w; +// +// w = (srctmp[s2 + u] & 0xffff) - 1; // s2 is unsigned +// r += (w >>> 31); +// } +// return (int)r; +// } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SHAKE256.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SHAKE256.java deleted file mode 100644 index eae8ee6133..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SHAKE256.java +++ /dev/null @@ -1,562 +0,0 @@ -package org.bouncycastle.pqc.crypto.falcon; - -class SHAKE256 -{ - long[] A; - byte[] dbuf; - long dptr; - - SHAKE256() - { - this.A = new long[25]; - this.dbuf = new byte[200]; - this.dptr = 0; - } - - /* - * Round constants. - */ - private long RC[] = { - 0x0000000000000001l, 0x0000000000008082l, - 0x800000000000808Al, 0x8000000080008000l, - 0x000000000000808Bl, 0x0000000080000001l, - 0x8000000080008081l, 0x8000000000008009l, - 0x000000000000008Al, 0x0000000000000088l, - 0x0000000080008009l, 0x000000008000000Al, - 0x000000008000808Bl, 0x800000000000008Bl, - 0x8000000000008089l, 0x8000000000008003l, - 0x8000000000008002l, 0x8000000000000080l, - 0x000000000000800Al, 0x800000008000000Al, - 0x8000000080008081l, 0x8000000000008080l, - 0x0000000080000001l, 0x8000000080008008l - }; - - /* - * Process the provided state. - */ - void process_block(long[] A) - { - long t0, t1, t2, t3, t4; - long tt0, tt1, tt2, tt3; - long t, kt; - long c0, c1, c2, c3, c4, bnn; - int j; - - /* - * Invert some words (alternate internal representation, which - * saves some operations). - */ - A[1] = ~A[1]; - A[2] = ~A[2]; - A[8] = ~A[8]; - A[12] = ~A[12]; - A[17] = ~A[17]; - A[20] = ~A[20]; - - /* - * Compute the 24 rounds. This loop is partially unrolled (each - * iteration computes two rounds). - */ - for (j = 0; j < 24; j += 2) - { - - tt0 = A[1] ^ A[6]; - tt1 = A[11] ^ A[16]; - tt0 ^= A[21] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[4] ^ A[9]; - tt3 = A[14] ^ A[19]; - tt0 ^= A[24]; - tt2 ^= tt3; - t0 = tt0 ^ tt2; - - tt0 = A[2] ^ A[7]; - tt1 = A[12] ^ A[17]; - tt0 ^= A[22] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[0] ^ A[5]; - tt3 = A[10] ^ A[15]; - tt0 ^= A[20]; - tt2 ^= tt3; - t1 = tt0 ^ tt2; - - tt0 = A[3] ^ A[8]; - tt1 = A[13] ^ A[18]; - tt0 ^= A[23] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[1] ^ A[6]; - tt3 = A[11] ^ A[16]; - tt0 ^= A[21]; - tt2 ^= tt3; - t2 = tt0 ^ tt2; - - tt0 = A[4] ^ A[9]; - tt1 = A[14] ^ A[19]; - tt0 ^= A[24] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[2] ^ A[7]; - tt3 = A[12] ^ A[17]; - tt0 ^= A[22]; - tt2 ^= tt3; - t3 = tt0 ^ tt2; - - tt0 = A[0] ^ A[5]; - tt1 = A[10] ^ A[15]; - tt0 ^= A[20] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[3] ^ A[8]; - tt3 = A[13] ^ A[18]; - tt0 ^= A[23]; - tt2 ^= tt3; - t4 = tt0 ^ tt2; - - A[0] = A[0] ^ t0; - A[5] = A[5] ^ t0; - A[10] = A[10] ^ t0; - A[15] = A[15] ^ t0; - A[20] = A[20] ^ t0; - A[1] = A[1] ^ t1; - A[6] = A[6] ^ t1; - A[11] = A[11] ^ t1; - A[16] = A[16] ^ t1; - A[21] = A[21] ^ t1; - A[2] = A[2] ^ t2; - A[7] = A[7] ^ t2; - A[12] = A[12] ^ t2; - A[17] = A[17] ^ t2; - A[22] = A[22] ^ t2; - A[3] = A[3] ^ t3; - A[8] = A[8] ^ t3; - A[13] = A[13] ^ t3; - A[18] = A[18] ^ t3; - A[23] = A[23] ^ t3; - A[4] = A[4] ^ t4; - A[9] = A[9] ^ t4; - A[14] = A[14] ^ t4; - A[19] = A[19] ^ t4; - A[24] = A[24] ^ t4; - A[5] = (A[5] << 36) | (A[5] >>> (64 - 36)); - A[10] = (A[10] << 3) | (A[10] >>> (64 - 3)); - A[15] = (A[15] << 41) | (A[15] >>> (64 - 41)); - A[20] = (A[20] << 18) | (A[20] >>> (64 - 18)); - A[1] = (A[1] << 1) | (A[1] >>> (64 - 1)); - A[6] = (A[6] << 44) | (A[6] >>> (64 - 44)); - A[11] = (A[11] << 10) | (A[11] >>> (64 - 10)); - A[16] = (A[16] << 45) | (A[16] >>> (64 - 45)); - A[21] = (A[21] << 2) | (A[21] >>> (64 - 2)); - A[2] = (A[2] << 62) | (A[2] >>> (64 - 62)); - A[7] = (A[7] << 6) | (A[7] >>> (64 - 6)); - A[12] = (A[12] << 43) | (A[12] >>> (64 - 43)); - A[17] = (A[17] << 15) | (A[17] >>> (64 - 15)); - A[22] = (A[22] << 61) | (A[22] >>> (64 - 61)); - A[3] = (A[3] << 28) | (A[3] >>> (64 - 28)); - A[8] = (A[8] << 55) | (A[8] >>> (64 - 55)); - A[13] = (A[13] << 25) | (A[13] >>> (64 - 25)); - A[18] = (A[18] << 21) | (A[18] >>> (64 - 21)); - A[23] = (A[23] << 56) | (A[23] >>> (64 - 56)); - A[4] = (A[4] << 27) | (A[4] >>> (64 - 27)); - A[9] = (A[9] << 20) | (A[9] >>> (64 - 20)); - A[14] = (A[14] << 39) | (A[14] >>> (64 - 39)); - A[19] = (A[19] << 8) | (A[19] >>> (64 - 8)); - A[24] = (A[24] << 14) | (A[24] >>> (64 - 14)); - - bnn = ~A[12]; - kt = A[6] | A[12]; - c0 = A[0] ^ kt; - kt = bnn | A[18]; - c1 = A[6] ^ kt; - kt = A[18] & A[24]; - c2 = A[12] ^ kt; - kt = A[24] | A[0]; - c3 = A[18] ^ kt; - kt = A[0] & A[6]; - c4 = A[24] ^ kt; - A[0] = c0; - A[6] = c1; - A[12] = c2; - A[18] = c3; - A[24] = c4; - bnn = ~A[22]; - kt = A[9] | A[10]; - c0 = A[3] ^ kt; - kt = A[10] & A[16]; - c1 = A[9] ^ kt; - kt = A[16] | bnn; - c2 = A[10] ^ kt; - kt = A[22] | A[3]; - c3 = A[16] ^ kt; - kt = A[3] & A[9]; - c4 = A[22] ^ kt; - A[3] = c0; - A[9] = c1; - A[10] = c2; - A[16] = c3; - A[22] = c4; - bnn = ~A[19]; - kt = A[7] | A[13]; - c0 = A[1] ^ kt; - kt = A[13] & A[19]; - c1 = A[7] ^ kt; - kt = bnn & A[20]; - c2 = A[13] ^ kt; - kt = A[20] | A[1]; - c3 = bnn ^ kt; - kt = A[1] & A[7]; - c4 = A[20] ^ kt; - A[1] = c0; - A[7] = c1; - A[13] = c2; - A[19] = c3; - A[20] = c4; - bnn = ~A[17]; - kt = A[5] & A[11]; - c0 = A[4] ^ kt; - kt = A[11] | A[17]; - c1 = A[5] ^ kt; - kt = bnn | A[23]; - c2 = A[11] ^ kt; - kt = A[23] & A[4]; - c3 = bnn ^ kt; - kt = A[4] | A[5]; - c4 = A[23] ^ kt; - A[4] = c0; - A[5] = c1; - A[11] = c2; - A[17] = c3; - A[23] = c4; - bnn = ~A[8]; - kt = bnn & A[14]; - c0 = A[2] ^ kt; - kt = A[14] | A[15]; - c1 = bnn ^ kt; - kt = A[15] & A[21]; - c2 = A[14] ^ kt; - kt = A[21] | A[2]; - c3 = A[15] ^ kt; - kt = A[2] & A[8]; - c4 = A[21] ^ kt; - A[2] = c0; - A[8] = c1; - A[14] = c2; - A[15] = c3; - A[21] = c4; - A[0] = A[0] ^ RC[j + 0]; - - tt0 = A[6] ^ A[9]; - tt1 = A[7] ^ A[5]; - tt0 ^= A[8] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[24] ^ A[22]; - tt3 = A[20] ^ A[23]; - tt0 ^= A[21]; - tt2 ^= tt3; - t0 = tt0 ^ tt2; - - tt0 = A[12] ^ A[10]; - tt1 = A[13] ^ A[11]; - tt0 ^= A[14] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[0] ^ A[3]; - tt3 = A[1] ^ A[4]; - tt0 ^= A[2]; - tt2 ^= tt3; - t1 = tt0 ^ tt2; - - tt0 = A[18] ^ A[16]; - tt1 = A[19] ^ A[17]; - tt0 ^= A[15] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[6] ^ A[9]; - tt3 = A[7] ^ A[5]; - tt0 ^= A[8]; - tt2 ^= tt3; - t2 = tt0 ^ tt2; - - tt0 = A[24] ^ A[22]; - tt1 = A[20] ^ A[23]; - tt0 ^= A[21] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[12] ^ A[10]; - tt3 = A[13] ^ A[11]; - tt0 ^= A[14]; - tt2 ^= tt3; - t3 = tt0 ^ tt2; - - tt0 = A[0] ^ A[3]; - tt1 = A[1] ^ A[4]; - tt0 ^= A[2] ^ tt1; - tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[18] ^ A[16]; - tt3 = A[19] ^ A[17]; - tt0 ^= A[15]; - tt2 ^= tt3; - t4 = tt0 ^ tt2; - - A[0] = A[0] ^ t0; - A[3] = A[3] ^ t0; - A[1] = A[1] ^ t0; - A[4] = A[4] ^ t0; - A[2] = A[2] ^ t0; - A[6] = A[6] ^ t1; - A[9] = A[9] ^ t1; - A[7] = A[7] ^ t1; - A[5] = A[5] ^ t1; - A[8] = A[8] ^ t1; - A[12] = A[12] ^ t2; - A[10] = A[10] ^ t2; - A[13] = A[13] ^ t2; - A[11] = A[11] ^ t2; - A[14] = A[14] ^ t2; - A[18] = A[18] ^ t3; - A[16] = A[16] ^ t3; - A[19] = A[19] ^ t3; - A[17] = A[17] ^ t3; - A[15] = A[15] ^ t3; - A[24] = A[24] ^ t4; - A[22] = A[22] ^ t4; - A[20] = A[20] ^ t4; - A[23] = A[23] ^ t4; - A[21] = A[21] ^ t4; - A[3] = (A[3] << 36) | (A[3] >>> (64 - 36)); - A[1] = (A[1] << 3) | (A[1] >>> (64 - 3)); - A[4] = (A[4] << 41) | (A[4] >>> (64 - 41)); - A[2] = (A[2] << 18) | (A[2] >>> (64 - 18)); - A[6] = (A[6] << 1) | (A[6] >>> (64 - 1)); - A[9] = (A[9] << 44) | (A[9] >>> (64 - 44)); - A[7] = (A[7] << 10) | (A[7] >>> (64 - 10)); - A[5] = (A[5] << 45) | (A[5] >>> (64 - 45)); - A[8] = (A[8] << 2) | (A[8] >>> (64 - 2)); - A[12] = (A[12] << 62) | (A[12] >>> (64 - 62)); - A[10] = (A[10] << 6) | (A[10] >>> (64 - 6)); - A[13] = (A[13] << 43) | (A[13] >>> (64 - 43)); - A[11] = (A[11] << 15) | (A[11] >>> (64 - 15)); - A[14] = (A[14] << 61) | (A[14] >>> (64 - 61)); - A[18] = (A[18] << 28) | (A[18] >>> (64 - 28)); - A[16] = (A[16] << 55) | (A[16] >>> (64 - 55)); - A[19] = (A[19] << 25) | (A[19] >>> (64 - 25)); - A[17] = (A[17] << 21) | (A[17] >>> (64 - 21)); - A[15] = (A[15] << 56) | (A[15] >>> (64 - 56)); - A[24] = (A[24] << 27) | (A[24] >>> (64 - 27)); - A[22] = (A[22] << 20) | (A[22] >>> (64 - 20)); - A[20] = (A[20] << 39) | (A[20] >>> (64 - 39)); - A[23] = (A[23] << 8) | (A[23] >>> (64 - 8)); - A[21] = (A[21] << 14) | (A[21] >>> (64 - 14)); - - bnn = ~A[13]; - kt = A[9] | A[13]; - c0 = A[0] ^ kt; - kt = bnn | A[17]; - c1 = A[9] ^ kt; - kt = A[17] & A[21]; - c2 = A[13] ^ kt; - kt = A[21] | A[0]; - c3 = A[17] ^ kt; - kt = A[0] & A[9]; - c4 = A[21] ^ kt; - A[0] = c0; - A[9] = c1; - A[13] = c2; - A[17] = c3; - A[21] = c4; - bnn = ~A[14]; - kt = A[22] | A[1]; - c0 = A[18] ^ kt; - kt = A[1] & A[5]; - c1 = A[22] ^ kt; - kt = A[5] | bnn; - c2 = A[1] ^ kt; - kt = A[14] | A[18]; - c3 = A[5] ^ kt; - kt = A[18] & A[22]; - c4 = A[14] ^ kt; - A[18] = c0; - A[22] = c1; - A[1] = c2; - A[5] = c3; - A[14] = c4; - bnn = ~A[23]; - kt = A[10] | A[19]; - c0 = A[6] ^ kt; - kt = A[19] & A[23]; - c1 = A[10] ^ kt; - kt = bnn & A[2]; - c2 = A[19] ^ kt; - kt = A[2] | A[6]; - c3 = bnn ^ kt; - kt = A[6] & A[10]; - c4 = A[2] ^ kt; - A[6] = c0; - A[10] = c1; - A[19] = c2; - A[23] = c3; - A[2] = c4; - bnn = ~A[11]; - kt = A[3] & A[7]; - c0 = A[24] ^ kt; - kt = A[7] | A[11]; - c1 = A[3] ^ kt; - kt = bnn | A[15]; - c2 = A[7] ^ kt; - kt = A[15] & A[24]; - c3 = bnn ^ kt; - kt = A[24] | A[3]; - c4 = A[15] ^ kt; - A[24] = c0; - A[3] = c1; - A[7] = c2; - A[11] = c3; - A[15] = c4; - bnn = ~A[16]; - kt = bnn & A[20]; - c0 = A[12] ^ kt; - kt = A[20] | A[4]; - c1 = bnn ^ kt; - kt = A[4] & A[8]; - c2 = A[20] ^ kt; - kt = A[8] | A[12]; - c3 = A[4] ^ kt; - kt = A[12] & A[16]; - c4 = A[8] ^ kt; - A[12] = c0; - A[16] = c1; - A[20] = c2; - A[4] = c3; - A[8] = c4; - A[0] = A[0] ^ RC[j + 1]; - t = A[5]; - A[5] = A[18]; - A[18] = A[11]; - A[11] = A[10]; - A[10] = A[6]; - A[6] = A[22]; - A[22] = A[20]; - A[20] = A[12]; - A[12] = A[19]; - A[19] = A[15]; - A[15] = A[24]; - A[24] = A[8]; - A[8] = t; - t = A[1]; - A[1] = A[9]; - A[9] = A[14]; - A[14] = A[2]; - A[2] = A[13]; - A[13] = A[23]; - A[23] = A[4]; - A[4] = A[21]; - A[21] = A[16]; - A[16] = A[3]; - A[3] = A[17]; - A[17] = A[7]; - A[7] = t; - } - - /* - * Invert some words back to normal representation. - */ - A[1] = ~A[1]; - A[2] = ~A[2]; - A[8] = ~A[8]; - A[12] = ~A[12]; - A[17] = ~A[17]; - A[20] = ~A[20]; - } - - - /* see inner.h */ - void inner_shake256_init() - { - this.dptr = 0; - - /* - * Representation of an all-ones uint64_t is the same regardless - * of local endianness. - */ - for (int i = 0; i < this.A.length; i++) - { - this.A[i] = 0; - } - } - - /* see inner.h */ - void inner_shake256_inject(byte[] srcin, int in, int len) - { - long dptr; - - dptr = this.dptr; - while (len > 0) - { - long clen, u; - - clen = 136 - dptr; - if (clen > len) - { - clen = len; - } - for (u = 0; u < clen; u++) - { - long v; - - v = u + dptr; - this.A[(int)(v >> 3)] ^=(srcin[in + (int)u] & 0xffL) << ((v & 7) << 3); - } - dptr += clen; - in += clen; - len -= clen; - if (dptr == 136) - { - process_block(this.A); - dptr = 0; - } - } - this.dptr = dptr; - } - - /* see falcon.h */ - void i_shake256_flip() - { - /* - * We apply padding and pre-XOR the value into the state. We - * set dptr to the end of the buffer, so that first call to - * shake_extract() will process the block. - */ - int v; - - v = (int)this.dptr; - this.A[v >> 3] ^= (0x1FL) << ((v & 7) << 3); - this.A[16] ^= (0x80L) << 56; - this.dptr = 136; - } - - /* see falcon.h */ - void inner_shake256_extract(byte[] srcout, int out, int len) - { - int dptr; - int o = out; - - dptr = (int)this.dptr; - while (len > 0) - { - int clen; - - if (dptr == 136) - { - process_block(this.A); - dptr = 0; - } - clen = 136 - dptr; - if (clen > len) - { - clen = len; - } - len -= clen; - while (clen-- > 0) - { - srcout[o++] = (byte)(this.A[dptr >> 3] >>> ((dptr & 7) << 3)); - dptr++; - } - } - this.dptr = dptr; - } - -} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerCtx.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerCtx.java index 351878f0ba..104c258c4d 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerCtx.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerCtx.java @@ -3,12 +3,12 @@ class SamplerCtx { - FalconFPR sigma_min; + double sigma_min; FalconRNG p; SamplerCtx() { - this.sigma_min = new FalconFPR(0.0); + this.sigma_min = 0.0; this.p = new FalconRNG(); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerZ.java b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerZ.java index bde395f3fc..32e066ccd2 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerZ.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/falcon/SamplerZ.java @@ -3,14 +3,14 @@ class SamplerZ { - FPREngine fpr; + //FPREngine fpr; - SamplerZ() - { - this.fpr = new FPREngine(); - } +// SamplerZ() +// { +// //this.fpr = new FPREngine(); +// } - int sample(SamplerCtx ctx, FalconFPR mu, FalconFPR iSigma) + static int sample(SamplerCtx ctx, double mu, double iSigma) { return sampler(ctx, mu, iSigma); } @@ -19,7 +19,7 @@ int sample(SamplerCtx ctx, FalconFPR mu, FalconFPR iSigma) * Sample an integer value along a half-gaussian distribution centered * on zero and standard deviation 1.8205, with a precision of 72 bits. */ - int gaussian0_sampler(FalconRNG p) + static int gaussian0_sampler(FalconRNG p) { int[] dist = { @@ -68,11 +68,11 @@ int gaussian0_sampler(FalconRNG p) w0 = dist[u + 2]; w1 = dist[u + 1]; - w2 = dist[u + 0]; + w2 = dist[u]; cc = (v0 - w0) >>> 31; cc = (v1 - w1 - cc) >>> 31; cc = (v2 - w2 - cc) >>> 31; - z += (int)cc; + z += cc; } return z; @@ -81,10 +81,10 @@ int gaussian0_sampler(FalconRNG p) /* * Sample a bit with probability exp(-x) for some x >= 0. */ - int BerExp(FalconRNG p, FalconFPR x, FalconFPR ccs) + private static int BerExp(FalconRNG p, double x, double ccs) { int s, i; - FalconFPR r; + double r; int sw, w; long z; @@ -92,8 +92,8 @@ int BerExp(FalconRNG p, FalconFPR x, FalconFPR ccs) * Reduce x modulo log(2): x = s*log(2) + r, with s an integer, * and 0 <= r < log(2). Since x >= 0, we can use fpr_trunc(). */ - s = (int)fpr.fpr_trunc(fpr.fpr_mul(x, fpr.fpr_inv_log2)); - r = fpr.fpr_sub(x, fpr.fpr_mul(fpr.fpr_of(s), fpr.fpr_log2)); + s = (int)(x * FPREngine.fpr_inv_log2);//(int)fpr.fpr_trunc(fpr.fpr_mul(x, fpr.fpr_inv_log2)); + r = x - s * FPREngine.fpr_log2; /* * It may happen (quite rarely) that s >= 64; if sigma = 1.2 @@ -119,7 +119,7 @@ int BerExp(FalconRNG p, FalconFPR x, FalconFPR ccs) * case). The bias is negligible since fpr_expm_p63() only computes * with 51 bits of precision or so. */ - z = ((fpr.fpr_expm_p63(r, ccs) << 1) - 1) >>> s; + z = ((FPREngine.fpr_expm_p63(r, ccs) << 1) - 1) >>> s; /* * Sample a bit with probability exp(-x). Since x = s*log(2) + r, @@ -145,11 +145,11 @@ int BerExp(FalconRNG p, FalconFPR x, FalconFPR ccs) * The value of sigma MUST lie between 1 and 2 (i.e. isigma lies between * 0.5 and 1); in Falcon, sigma should always be between 1.2 and 1.9. */ - int sampler(SamplerCtx ctx, FalconFPR mu, FalconFPR isigma) + private static int sampler(SamplerCtx ctx, double mu, double isigma) { SamplerCtx spc; int s; - FalconFPR r, dss, ccs; + double r, dss, ccs; spc = ctx; @@ -157,18 +157,18 @@ int sampler(SamplerCtx ctx, FalconFPR mu, FalconFPR isigma) * Center is mu. We compute mu = s + r where s is an integer * and 0 <= r < 1. */ - s = (int)fpr.fpr_floor(mu); - r = fpr.fpr_sub(mu, fpr.fpr_of(s)); + s = (int)FPREngine.fpr_floor(mu); + r = mu - s; /* * dss = 1/(2*sigma^2) = 0.5*(isigma^2). */ - dss = fpr.fpr_half(fpr.fpr_sqr(isigma)); + dss = isigma * isigma * 0.5; /* * ccs = sigma_min / sigma = sigma_min * isigma. */ - ccs = fpr.fpr_mul(isigma, spc.sigma_min); + ccs = isigma * spc.sigma_min; /* * We now need to sample on center r. @@ -176,7 +176,7 @@ int sampler(SamplerCtx ctx, FalconFPR mu, FalconFPR isigma) for (; ; ) { int z0, z, b; - FalconFPR x; + double x; /* * Sample z for a Gaussian distribution. Then get a @@ -218,8 +218,9 @@ int sampler(SamplerCtx ctx, FalconFPR mu, FalconFPR isigma) * center and standard deviation that the whole sampler * can be said to be constant-time. */ - x = fpr.fpr_mul(fpr.fpr_sqr(fpr.fpr_sub(fpr.fpr_of(z), r)), dss); - x = fpr.fpr_sub(x, fpr.fpr_mul(fpr.fpr_of(z0 * z0), fpr.fpr_inv_2sqrsigma0)); + x = z - r; + x = x * x * dss; + x -= (double)(z0 * z0) * FPREngine.fpr_inv_2sqrsigma0; if (BerExp(spc.p, x, ccs) != 0) { /* diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/frodo/FrodoEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/frodo/FrodoEngine.java index d62bc7be8a..66c88c602b 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/frodo/FrodoEngine.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/frodo/FrodoEngine.java @@ -322,7 +322,7 @@ private short[] unpack(byte[] in, int n1, int n2) private short[] encode(byte[] k) { int l, byte_index = 0; - byte mask = 1; + int bit = 0; short[] K = new short[mbar*nbar]; int temp; // 1. for i = 0; i < mbar; i += 1 @@ -335,16 +335,13 @@ private short[] encode(byte[] k) temp = 0; for (l = 0; l < B; l++) { - //mask - int mult = ((k[byte_index] & mask) == mask) ? 1 : 0; - temp += (1 << l) * mult; - mask <<= 1; - if (mask == 0) - { - mask = 1; - byte_index++; - } + temp += ((k[byte_index] >>> bit) & 1) << l; + + ++bit; + byte_index += bit >>> 3; + bit &= 7; } + // 4. K[i][j] = ec(tmp) = tmp * q/2^B K[i*nbar+j] = (short) (temp * (q / (1 << B))); } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/FastFourierTransform.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/FastFourierTransform.java index fc3fbed416..96fb29de84 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/FastFourierTransform.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/FastFourierTransform.java @@ -131,8 +131,8 @@ static void computeRadixBig(int[] f0, int[] f1, int[] f, int mf, int fft) n <<= (mf - 2); int fftSize = 1 << (fft - 2); - int Q[] = new int[2 * fftSize]; - int R[] = new int[2 * fftSize]; + int Q[] = new int[2 * fftSize + 1]; + int R[] = new int[2 * fftSize + 1]; int Q0[] = new int[fftSize]; int Q1[] = new int[fftSize]; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCEngine.java index 98a3c7ba11..49244d85fd 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCEngine.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCEngine.java @@ -20,8 +20,7 @@ class HQCEngine private int SEED_SIZE = 40; private byte G_FCT_DOMAIN = 3; - private byte H_FCT_DOMAIN = 4; - private byte K_FCT_DOMAIN = 5; + private byte K_FCT_DOMAIN = 4; private int N_BYTE; private int n1n2; @@ -87,10 +86,12 @@ public void genKeyPair(byte[] pk, byte[] sk, byte[] seed) { // Randomly generate seeds for secret keys and public keys byte[] secretKeySeed = new byte[SEED_SIZE]; + byte[] sigma = new byte[K_BYTE]; KeccakRandomGenerator randomGenerator = new KeccakRandomGenerator(256); randomGenerator.randomGeneratorInit(seed, null, seed.length, 0); randomGenerator.squeeze(secretKeySeed, 40); + randomGenerator.squeeze(sigma, K_BYTE); // 1. Randomly generate secret keys x, y KeccakRandomGenerator secretKeySeedExpander = new KeccakRandomGenerator(256); @@ -99,8 +100,8 @@ public void genKeyPair(byte[] pk, byte[] sk, byte[] seed) long[] xLongBytes = new long[N_BYTE_64]; long[] yLongBytes = new long[N_BYTE_64]; - generateRandomFixedWeight(xLongBytes, secretKeySeedExpander, w); generateRandomFixedWeight(yLongBytes, secretKeySeedExpander, w); + generateRandomFixedWeight(xLongBytes, secretKeySeedExpander, w); // 2. Randomly generate h byte[] publicKeySeed = new byte[SEED_SIZE]; @@ -120,7 +121,7 @@ public void genKeyPair(byte[] pk, byte[] sk, byte[] seed) Utils.fromLongArrayToByteArray(sBytes, s); byte[] tmpPk = Arrays.concatenate(publicKeySeed, sBytes); - byte[] tmpSk = Arrays.concatenate(secretKeySeed, tmpPk); + byte[] tmpSk = Arrays.concatenate(secretKeySeed, sigma, tmpPk); System.arraycopy(tmpPk, 0, pk, 0, tmpPk.length); System.arraycopy(tmpSk, 0, sk, 0, tmpSk.length); @@ -133,12 +134,11 @@ public void genKeyPair(byte[] pk, byte[] sk, byte[] seed) * * @param u u * @param v v - * @param d d * @param K session key * @param pk public key * @param seed seed **/ - public void encaps(byte[] u, byte[] v, byte[] K, byte[] d, byte[] pk, byte[] seed, byte[] salt) + public void encaps(byte[] u, byte[] v, byte[] K, byte[] pk, byte[] seed, byte[] salt) { // 1. Randomly generate m byte[] m = new byte[K_BYTE]; @@ -148,6 +148,9 @@ public void encaps(byte[] u, byte[] v, byte[] K, byte[] d, byte[] pk, byte[] see randomGenerator.randomGeneratorInit(seed, null, seed.length, 0); randomGenerator.squeeze(secretKeySeed, 40); + byte[] sigma = new byte[K_BYTE]; + randomGenerator.squeeze(sigma, K_BYTE); + byte[] publicKeySeed = new byte[SEED_SIZE]; randomGenerator.squeeze(publicKeySeed, 40); @@ -156,12 +159,12 @@ public void encaps(byte[] u, byte[] v, byte[] K, byte[] d, byte[] pk, byte[] see // 2. Generate theta byte[] theta = new byte[SHA512_BYTES]; - byte[] tmp = new byte[K_BYTE + SEED_SIZE + SALT_SIZE_BYTES]; + byte[] tmp = new byte[K_BYTE + (SALT_SIZE_BYTES * 2) + SALT_SIZE_BYTES]; randomGenerator.squeeze(salt, SALT_SIZE_BYTES); System.arraycopy(m, 0, tmp, 0, m.length); - System.arraycopy(pk, 0, tmp, K_BYTE, SEED_SIZE); - System.arraycopy(salt, 0, tmp, K_BYTE + SEED_SIZE, SALT_SIZE_BYTES); + System.arraycopy(pk, 0, tmp, K_BYTE, SALT_SIZE_BYTES * 2); + System.arraycopy(salt, 0, tmp, K_BYTE + (SALT_SIZE_BYTES * 2), SALT_SIZE_BYTES); KeccakRandomGenerator shakeDigest = new KeccakRandomGenerator(256); shakeDigest.SHAKE256_512_ds(theta, tmp, tmp.length, new byte[]{G_FCT_DOMAIN}); @@ -176,13 +179,8 @@ public void encaps(byte[] u, byte[] v, byte[] K, byte[] d, byte[] pk, byte[] see Utils.fromLongArrayToByteArray(v, vTmp); - // 4. Compute d - shakeDigest.SHAKE256_512_ds(d, m, m.length, new byte[]{H_FCT_DOMAIN}); - // 5. Compute session key K - byte[] hashInputK = new byte[K_BYTE + N_BYTE + N1N2_BYTE]; - hashInputK = Arrays.concatenate(m, u); - hashInputK = Arrays.concatenate(hashInputK, v); + byte[] hashInputK = Arrays.concatenate(m, u, v); shakeDigest.SHAKE256_512_ds(K, hashInputK, hashInputK.length, new byte[]{K_FCT_DOMAIN}); } @@ -194,32 +192,32 @@ public void encaps(byte[] u, byte[] v, byte[] K, byte[] d, byte[] pk, byte[] see * @param ss session key * @param ct ciphertext * @param sk secret key + * @return 0 if decapsulation is successful, -1 otherwise **/ - public void decaps(byte[] ss, byte[] ct, byte[] sk) + public int decaps(byte[] ss, byte[] ct, byte[] sk) { //Extract Y and Public Keys from sk - long[] x = new long[N_BYTE_64]; long[] y = new long[N_BYTE_64]; byte[] pk = new byte[40 + N_BYTE]; - extractKeysFromSecretKeys(x, y, pk, sk); + byte[] sigma = new byte[K_BYTE]; + extractKeysFromSecretKeys(y, sigma, pk, sk); // Extract u, v, d from ciphertext byte[] u = new byte[N_BYTE]; byte[] v = new byte[N1N2_BYTE]; - byte[] d = new byte[SHA512_BYTES]; byte[] salt = new byte[SALT_SIZE_BYTES]; - extractCiphertexts(u, v, d, salt, ct); + extractCiphertexts(u, v, salt, ct); // 1. Decrypt -> m' byte[] mPrimeBytes = new byte[k]; - decrypt(mPrimeBytes, mPrimeBytes, u, v, y); + int result = decrypt(mPrimeBytes, mPrimeBytes, sigma, u, v, y); // 2. Compute theta' byte[] theta = new byte[SHA512_BYTES]; - byte[] tmp = new byte[K_BYTE + SALT_SIZE_BYTES + SEED_SIZE]; + byte[] tmp = new byte[K_BYTE + (SALT_SIZE_BYTES * 2) + SALT_SIZE_BYTES]; System.arraycopy(mPrimeBytes, 0, tmp, 0, mPrimeBytes.length); - System.arraycopy(pk, 0, tmp, K_BYTE, SEED_SIZE); - System.arraycopy(salt, 0, tmp, K_BYTE + SEED_SIZE, SALT_SIZE_BYTES); + System.arraycopy(pk, 0, tmp, K_BYTE, SALT_SIZE_BYTES * 2); + System.arraycopy(salt, 0, tmp, K_BYTE + (SALT_SIZE_BYTES * 2), SALT_SIZE_BYTES); KeccakRandomGenerator shakeDigest = new KeccakRandomGenerator(256); shakeDigest.SHAKE256_512_ds(theta, tmp, tmp.length, new byte[]{G_FCT_DOMAIN}); @@ -236,40 +234,32 @@ public void decaps(byte[] ss, byte[] ct, byte[] sk) encrypt(u2Bytes, vTmp, h, s, mPrimeBytes, theta); Utils.fromLongArrayToByteArray(v2Bytes, vTmp); - // 4. Compute d' = H(m') - byte[] dPrime = new byte[SHA512_BYTES]; - shakeDigest.SHAKE256_512_ds(dPrime, mPrimeBytes, mPrimeBytes.length, new byte[]{H_FCT_DOMAIN}); - // 5. Compute session key KPrime byte[] hashInputK = new byte[K_BYTE + N_BYTE + N1N2_BYTE]; - hashInputK = Arrays.concatenate(mPrimeBytes, u); - hashInputK = Arrays.concatenate(hashInputK, v); - shakeDigest.SHAKE256_512_ds(ss, hashInputK, hashInputK.length, new byte[]{K_FCT_DOMAIN}); - int result = 1; // Compare u, v, d - if (!Arrays.areEqual(u, u2Bytes)) + if (!Arrays.constantTimeAreEqual(u, u2Bytes)) { - result = 0; + result = 1; } - if (!Arrays.areEqual(v, v2Bytes)) + if (!Arrays.constantTimeAreEqual(v, v2Bytes)) { - result = 0; + result = 1; } - if (!Arrays.areEqual(d, dPrime)) + result -= 1; + + for (int i = 0; i < K_BYTE; i++) { - result = 0; + hashInputK[i] = (byte)(((mPrimeBytes[i] & result) ^ (sigma[i] & ~result)) & 0xff); } + System.arraycopy(u, 0, hashInputK, K_BYTE, N_BYTE); + System.arraycopy(v, 0, hashInputK, K_BYTE + N_BYTE, N1N2_BYTE); - if (result == 0) - { //abort - for (int i = 0; i < getSessionKeySize(); i++) - { - ss[i] = 0; - } - } + shakeDigest.SHAKE256_512_ds(ss, hashInputK, hashInputK.length, new byte[]{K_FCT_DOMAIN}); + + return -result; } int getSessionKeySize() @@ -296,9 +286,9 @@ private void encrypt(byte[] u, long[] v, long[] h, byte[] s, byte[] m, byte[] th long[] e = new long[N_BYTE_64]; long[] r1 = new long[N_BYTE_64]; long[] r2 = new long[N_BYTE_64]; - generateRandomFixedWeight(r1, randomGenerator, wr); generateRandomFixedWeight(r2, randomGenerator, wr); generateRandomFixedWeight(e, randomGenerator, we); + generateRandomFixedWeight(r1, randomGenerator, wr); // Calculate u long[] uLong = new long[N_BYTE_64]; @@ -327,7 +317,7 @@ private void encrypt(byte[] u, long[] v, long[] h, byte[] s, byte[] m, byte[] th Utils.resizeArray(v, n1n2, tmpLong, n, N1N2_BYTE_64, N1N2_BYTE_64); } - private void decrypt(byte[] output, byte[] m, byte[] u, byte[] v, long[] y) + private int decrypt(byte[] output, byte[] m, byte[] sigma, byte[] u, byte[] v, long[] y) { long[] uLongs = new long[N_BYTE_64]; Utils.fromByteArrayToLongArray(uLongs, u); @@ -348,6 +338,7 @@ private void decrypt(byte[] output, byte[] m, byte[] u, byte[] v, long[] y) ReedSolomon.decode(m, tmp, n1, fft, delta, k, g); System.arraycopy(m, 0, output, 0, output.length); + return 0; } private void generateRandomFixedWeight(long[] output, KeccakRandomGenerator random, int weight) @@ -427,26 +418,25 @@ private void extractPublicKeys(long[] h, byte[] s, byte[] pk) System.arraycopy(pk, 40, s, 0, s.length); } - private void extractKeysFromSecretKeys(long[] x, long[] y, byte[] pk, byte[] sk) + private void extractKeysFromSecretKeys(long[] y, byte[] sigma, byte[] pk, byte[] sk) { byte[] secretKeySeed = new byte[SEED_SIZE]; System.arraycopy(sk, 0, secretKeySeed, 0, secretKeySeed.length); + System.arraycopy(sk, SEED_SIZE, sigma, 0, K_BYTE); // Randomly generate secret keys x, y KeccakRandomGenerator secretKeySeedExpander = new KeccakRandomGenerator(256); secretKeySeedExpander.seedExpanderInit(secretKeySeed, secretKeySeed.length); - generateRandomFixedWeight(x, secretKeySeedExpander, w); generateRandomFixedWeight(y, secretKeySeedExpander, w); - System.arraycopy(sk, SEED_SIZE, pk, 0, pk.length); + System.arraycopy(sk, SEED_SIZE + K_BYTE, pk, 0, pk.length); } - private void extractCiphertexts(byte[] u, byte[] v, byte[] d, byte[] salt, byte[] ct) + private void extractCiphertexts(byte[] u, byte[] v, byte[] salt, byte[] ct) { System.arraycopy(ct, 0, u, 0, u.length); System.arraycopy(ct, u.length, v, 0, v.length); - System.arraycopy(ct, u.length + v.length, d, 0, d.length); - System.arraycopy(ct, u.length + v.length + d.length, salt, 0, salt.length); + System.arraycopy(ct, u.length + v.length, salt, 0, salt.length); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMExtractor.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMExtractor.java index 0de5cc5f85..bc3cb1483b 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMExtractor.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMExtractor.java @@ -30,12 +30,11 @@ public byte[] extractSecret(byte[] encapsulation) engine.decaps(session_key, encapsulation, sk); - return Arrays.copyOfRange(session_key, 0, key.getParameters().getK()); + return Arrays.copyOfRange(session_key, 0, 32); } public int getEncapsulationLength() - { - // Hash + salt - return key.getParameters().getN_BYTES() + key.getParameters().getN1N2_BYTES() + 64 + 16; + { // Hash + salt + return key.getParameters().getN_BYTES() + key.getParameters().getN1N2_BYTES() + 16; } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMGenerator.java index 38de8c44ef..47caa9476e 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKEMGenerator.java @@ -26,17 +26,16 @@ public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recip byte[] K = new byte[key.getParameters().getSHA512_BYTES()]; byte[] u = new byte[key.getParameters().getN_BYTES()]; byte[] v = new byte[key.getParameters().getN1N2_BYTES()]; - byte[] d = new byte[key.getParameters().getSHA512_BYTES()]; byte[] salt = new byte[key.getParameters().getSALT_SIZE_BYTES()]; byte[] pk = key.getPublicKey(); byte[] seed = new byte[48]; sr.nextBytes(seed); - engine.encaps(u, v, K, d, pk, seed, salt); + engine.encaps(u, v, K, pk, seed, salt); - byte[] cipherText = Arrays.concatenate(u, v, d, salt); + byte[] cipherText = Arrays.concatenate(u, v, salt); - return new SecretWithEncapsulationImpl(Arrays.copyOfRange(K, 0, key.getParameters().getK()), cipherText); + return new SecretWithEncapsulationImpl(Arrays.copyOfRange(K, 0, 32), cipherText); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKeyPairGenerator.java index fdd23c7fa8..0a85e3f875 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKeyPairGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCKeyPairGenerator.java @@ -45,7 +45,7 @@ private AsymmetricCipherKeyPair genKeyPair(byte[] seed) { HQCEngine engine = hqcKeyGenerationParameters.getParameters().getEngine(); byte[] pk = new byte[40 + N_BYTE]; - byte[] sk = new byte[40 + 40 + N_BYTE]; + byte[] sk = new byte[40 + 40 + k + N_BYTE]; engine.genKeyPair(pk, sk, seed); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCParameters.java index 1090848fa8..86b965ec98 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCParameters.java @@ -118,7 +118,7 @@ HQCEngine getEngine() public int getSessionKeySize() { - return k * 8; + return 32 * 8; } public String getName() diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/ReedSolomon.java b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/ReedSolomon.java index 8da0b7035d..18457241d4 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/ReedSolomon.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/hqc/ReedSolomon.java @@ -191,8 +191,7 @@ private static void computeZx(int[] output, int[] sigma, int deg, int[] syndrome for (int i = 2; i <= delta; i++) { int mask = i - deg < 1 ? 0xffff : 0; - output[i] = mask & sigma[i - 1]; - + output[i] ^= (mask) & syndromes[i - 1]; for (int j = 1; j < i; j++) { output[i] ^= (mask) & GFCalculator.mult(sigma[j], syndromes[i - j - 1]); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPrivateKeyParameters.java index 19fe2ebcb1..1ce0facb74 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPrivateKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPrivateKeyParameters.java @@ -26,6 +26,23 @@ public class HSSPrivateKeyParameters private HSSPublicKeyParameters publicKey; + public HSSPrivateKeyParameters(LMSPrivateKeyParameters key, long index, long indexLimit) + { + super(true); + + this.l = 1; + this.keys = Collections.singletonList(key); + this.sig = Collections.emptyList(); + this.index = index; + this.indexLimit = indexLimit; + this.isShard = false; + + // + // Correct Intermediate LMS values will be constructed during reset to index. + // + resetKeyToIndex(); + } + public HSSPrivateKeyParameters(int l, List keys, List sig, long index, long indexLimit) { super(true); @@ -104,7 +121,16 @@ else if (src instanceof byte[]) try // 1.5 / 1.6 compatibility { in = new DataInputStream(new ByteArrayInputStream((byte[])src)); - return getInstance(in); + try + { + return getInstance(in); + } + catch (Exception e) + { + // old style single LMS key. + LMSPrivateKeyParameters lmsKey = LMSPrivateKeyParameters.getInstance(src); + return new HSSPrivateKeyParameters(lmsKey, lmsKey.getIndex(), lmsKey.getIndexLimit()); + } } finally { @@ -186,7 +212,7 @@ long getIndexLimit() public long getUsagesRemaining() { - return indexLimit - index; + return getIndexLimit() - getIndex(); } LMSPrivateKeyParameters getRootKey() @@ -207,24 +233,26 @@ public HSSPrivateKeyParameters extractKeyShard(int usageCount) { synchronized (this) { - - if (getUsagesRemaining() < usageCount) + if (usageCount < 0) + { + throw new IllegalArgumentException("usageCount cannot be negative"); + } + if (usageCount > indexLimit - index) { throw new IllegalArgumentException("usageCount exceeds usages remaining in current leaf"); } - long maxIndexForShard = index + usageCount; - long shardStartIndex = index; + long shardIndex = index; + long shardIndexLimit = index + usageCount; - // - // Move this keys index along - // - index += usageCount; + // Move this key's index along + index = shardIndexLimit; List keys = new ArrayList(this.getKeys()); List sig = new ArrayList(this.getSig()); - HSSPrivateKeyParameters shard = makeCopy(new HSSPrivateKeyParameters(l, keys, sig, shardStartIndex, maxIndexForShard, true)); + HSSPrivateKeyParameters shard = makeCopy( + new HSSPrivateKeyParameters(l, keys, sig, shardIndex, shardIndexLimit, true)); resetKeyToIndex(); @@ -232,7 +260,6 @@ public HSSPrivateKeyParameters extractKeyShard(int usageCount) } } - synchronized List getKeys() { return keys; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPublicKeyParameters.java index ec7aadf0db..bd3d479681 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPublicKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/HSSPublicKeyParameters.java @@ -136,7 +136,7 @@ public LMSContext generateLMSContext(byte[] sigEnc) public boolean verify(LMSContext context) { - boolean failed = false; + boolean passed = true; LMSSignedPubKey[] sigKeys = context.getSignedPubKeys(); @@ -151,13 +151,10 @@ public boolean verify(LMSContext context) { LMSSignature sig = sigKeys[i].getSignature(); byte[] msg = sigKeys[i].getPublicKey().toByteArray(); - if (!LMS.verifySignature(key, sig, msg)) - { - failed = true; - } + passed &= LMS.verifySignature(key, sig, msg); key = sigKeys[i].getPublicKey(); } - return !failed & key.verify(context); + return passed & key.verify(context); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSPrivateKeyParameters.java index a90a4ed8f8..0ba5c9edac 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSPrivateKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSPrivateKeyParameters.java @@ -253,14 +253,22 @@ public LMSPrivateKeyParameters extractKeyShard(int usageCount) { synchronized (this) { - if (q + usageCount >= maxQ) + if (usageCount < 0) + { + throw new IllegalArgumentException("usageCount cannot be negative"); + } + if (usageCount > maxQ - q) { throw new IllegalArgumentException("usageCount exceeds usages remaining"); } - LMSPrivateKeyParameters keyParameters = new LMSPrivateKeyParameters(this, q, q + usageCount); - q += usageCount; - return keyParameters; + int shardIndex = q; + int shardIndexLimit = q + usageCount; + + // Move this key's index along + q = shardIndexLimit; + + return new LMSPrivateKeyParameters(this, shardIndex, shardIndexLimit); } } @@ -284,9 +292,15 @@ public byte[] getMasterSecret() return Arrays.clone(masterSecret); } + public int getIndexLimit() + { + return maxQ; + } + + // TODO Only needs 'int' public long getUsagesRemaining() { - return maxQ - getIndex(); + return getIndexLimit() - getIndex(); } public LMSPublicKeyParameters getPublicKey() diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSSigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSSigner.java index 30242ab904..ad7d52903c 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSSigner.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSSigner.java @@ -15,11 +15,41 @@ public void init(boolean forSigning, CipherParameters param) { if (forSigning) { - privKey = (LMSPrivateKeyParameters)param; + if (param instanceof HSSPrivateKeyParameters) + { + HSSPrivateKeyParameters hssPriv = (HSSPrivateKeyParameters)param; + if (hssPriv.getL() == 1) + { + privKey = hssPriv.getRootKey(); + } + else + { + throw new IllegalArgumentException("only a single level HSS key can be used with LMS"); + } + } + else + { + privKey = (LMSPrivateKeyParameters)param; + } } else { - pubKey = (LMSPublicKeyParameters)param; + if (param instanceof HSSPublicKeyParameters) + { + HSSPublicKeyParameters hssPub = (HSSPublicKeyParameters)param; + if (hssPub.getL() == 1) + { + pubKey = hssPub.getLMSPublicKey(); + } + else + { + throw new IllegalArgumentException("only a single level HSS key can be used with LMS"); + } + } + else + { + pubKey = (LMSPublicKeyParameters)param; + } } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSigParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSigParameters.java index 9f4311b86a..69230d38a1 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSigParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/lms/LMSigParameters.java @@ -94,7 +94,7 @@ public ASN1ObjectIdentifier getDigestOID() return digestOid; } - static LMSigParameters getParametersForType(int type) + public static LMSigParameters getParametersForType(int type) { return paramBuilders.get(type); } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/GF16Utils.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/GF16Utils.java new file mode 100644 index 0000000000..20d993d0c5 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/GF16Utils.java @@ -0,0 +1,245 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import org.bouncycastle.util.GF16; + +class GF16Utils +{ + static final long NIBBLE_MASK_MSB = 0x7777777777777777L; + static final long MASK_MSB = 0x8888888888888888L; + static final long MASK_LSB = 0x1111111111111111L; + static final long NIBBLE_MASK_LSB = ~MASK_LSB; + + /** + * Multiplies each limb of a GF(16) vector (subarray of 'in') by the GF(16) element 'a' + * and XORs the result into the corresponding subarray of acc. + *

    + * This version uses explicit array offsets. + * + * @param mVecLimbs the number of limbs in the vector + * @param in the input long array containing the vector; the vector starts at index inOffset + * @param inOffset the starting index in 'in' + * @param b the GF(16) element (0–255) to multiply by + * @param acc the accumulator long array; the target vector starts at index accOffset + * @param accOffset the starting index in 'acc' + */ + static void mVecMulAdd(int mVecLimbs, long[] in, int inOffset, int b, long[] acc, int accOffset) + { + long a, r64, a_msb, a_msb3; + long b32 = b & 0x00000000FFFFFFFFL; + long b32and1 = b32 & 1; + long b32_1_1 = ((b32 >>> 1) & 1); + long b32_2_1 = ((b32 >>> 2) & 1); + long b32_3_1 = ((b32 >>> 3) & 1); + for (int i = 0; i < mVecLimbs; i++) + { + // In the original code there is a conditional XOR with unsigned_char_blocker; + // here we simply use b directly. + a = in[inOffset++]; + r64 = a & -b32and1; + + a_msb = a & MASK_MSB; + a &= NIBBLE_MASK_MSB; + a_msb3 = a_msb >>> 3; + a = (a << 1) ^ (a_msb3 + (a_msb3 << 1)); + r64 ^= a & -b32_1_1; + + a_msb = a & MASK_MSB; + a &= NIBBLE_MASK_MSB; + a_msb3 = a_msb >>> 3; + a = (a << 1) ^ (a_msb3 + (a_msb3 << 1)); + r64 ^= a & -b32_2_1; + + a_msb = a & MASK_MSB; + a &= NIBBLE_MASK_MSB; + a_msb3 = a_msb >>> 3; + a = (a << 1) ^ (a_msb3 + (a_msb3 << 1)); + acc[accOffset++] ^= r64 ^ (a & -b32_3_1); + } + } + + + /** + * Performs the multiplication and accumulation of a block of an upper‐triangular matrix + * times a second matrix. + * + * @param mVecLimbs number of limbs per m-vector. + * @param bsMat the “basis” matrix (as a flat long[] array); each entry occupies mVecLimbs elements. + * @param mat the second matrix (as a flat byte[] array) stored row‐major, + * with dimensions (bsMatCols x matCols). + * @param acc the accumulator (as a flat long[] array) with dimensions (bsMatRows x matCols); + * each “entry” is an m‐vector (length mVecLimbs). + * @param bsMatRows number of rows in the bsMat (the “triangular” matrix’s row count). + * @param matCols number of columns in the matrix “mat.” + */ + static void mulAddMUpperTriangularMatXMat(int mVecLimbs, long[] bsMat, byte[] mat, long[] acc, int accOff, + int bsMatRows, int matCols) + { + int bsMatEntriesUsed = 0; + int matColsmVecLimbs = matCols * mVecLimbs; + for (int r = 0, rmatCols = 0, rmatColsmVecLimbs = 0; r < bsMatRows; r++, rmatCols += matCols, rmatColsmVecLimbs += matColsmVecLimbs) + { + // For each row r, the inner loop goes from column triangular*r to bsMatCols-1. + for (int c = r, cmatCols = rmatCols; c < bsMatRows; c++, cmatCols += matCols) + { + for (int k = 0, kmVecLimbs = 0; k < matCols; k++, kmVecLimbs += mVecLimbs) + { + // For acc: add into the m-vector at row r, column k. + mVecMulAdd(mVecLimbs, bsMat, bsMatEntriesUsed, mat[cmatCols + k], acc, accOff + rmatColsmVecLimbs + kmVecLimbs); + } + bsMatEntriesUsed += mVecLimbs; + } + } + } + + /** + * Multiplies the transpose of a single matrix with m matrices and adds the result into acc. + * + * @param mVecLimbs number of limbs per m-vector. + * @param mat the matrix to be transposed (as a flat byte[] array), dimensions: (matRows x matCols). + * @param bsMat the m-matrix (as a flat long[] array), with each entry of length mVecLimbs. + * Its logical dimensions: (matRows x bsMatCols). + * @param acc the accumulator (as a flat long[] array) with dimensions (matCols x bsMatCols); + * each entry is an m-vector. + * @param matRows number of rows in the matrix “mat.” + * @param matCols number of columns in “mat.” + */ + static void mulAddMatTransXMMat(int mVecLimbs, byte[] mat, long[] bsMat, int bsMatOff, long[] acc, + int matRows, int matCols) + { + int multiply = matCols * mVecLimbs; + for (int r = 0, rmultiply = 0; r < matCols; r++, rmultiply += multiply) + { + for (int c = 0, cmatCols = 0, cmultiply = 0; c < matRows; c++, cmatCols += matCols, cmultiply += multiply) + { + byte matVal = mat[cmatCols + r]; + for (int k = 0, kmVecLimbs = 0; k < matCols; k++, kmVecLimbs += mVecLimbs) + { + mVecMulAdd(mVecLimbs, bsMat, bsMatOff + cmultiply + kmVecLimbs, matVal, acc, rmultiply + kmVecLimbs); + } + } + } + } + + /** + * Multiplies a matrix (given as a byte array) with a bit‐sliced matrix (given as a long array) + * and accumulates the result into the acc array. + * + *

    + * The operation iterates over the rows and columns of the matrix. For each element in the matrix, + * it multiplies a corresponding vector (from bsMat) by the scalar value (from mat) and adds the + * result to the accumulator vector in acc. + *

    + * + * @param mVecLimbs the number of limbs (elements) in each vector + * @param mat the matrix as a byte array with dimensions [matRows x matCols] + * @param bsMat the bit‐sliced matrix as a long array + * @param acc the accumulator array (long[]) where results are accumulated + * @param matRows the number of rows in the matrix + * @param matCols the number of columns in the matrix + */ + static void mulAddMatXMMat(int mVecLimbs, byte[] mat, long[] bsMat, long[] acc, int matRows, int matCols) + { + int multiply = mVecLimbs * matRows; + for (int r = 0, rmatCols = 0, rmultiply = 0; r < matRows; r++, rmatCols += matCols, rmultiply += multiply) + { + for (int c = 0, cmultiply = 0; c < matCols; c++, cmultiply += multiply) + { + // Retrieve the scalar from the matrix for row r and column c. + byte matVal = mat[rmatCols + c]; + for (int k = 0, kmVecLimbs = 0; k < matRows; k++, kmVecLimbs += mVecLimbs) + { + mVecMulAdd(mVecLimbs, bsMat, cmultiply + kmVecLimbs, matVal, acc, rmultiply + kmVecLimbs); + } + } + } + } + + static void mulAddMatXMMat(int mVecLimbs, byte[] mat, long[] bsMat, int bsMatOff, long[] acc, + int matRows, int matCols, int bsMatCols) + { + int multiply = mVecLimbs * bsMatCols; + for (int r = 0, rmultiply = 0, rmatCols = 0; r < matRows; r++, rmultiply += multiply, rmatCols += matCols) + { + for (int c = 0, cmultiply = 0; c < matCols; c++, cmultiply += multiply) + { + // Retrieve the scalar from the matrix for row r and column c. + byte matVal = mat[rmatCols + c]; + for (int k = 0, kmVecLimbs = 0; k < bsMatCols; k++, kmVecLimbs += mVecLimbs) + { + mVecMulAdd(mVecLimbs, bsMat, cmultiply + kmVecLimbs + bsMatOff, matVal, acc, rmultiply + kmVecLimbs); + } + } + } + } + + /** + * Multiplies m (possibly upper triangular) matrices with the transpose of a single matrix + * and adds the result to the accumulator. + * + *

    + * For each row {@code r} in the bit‑sliced matrix and for each column {@code c} (starting from + * {@code triangular * r}) in the bit‑sliced matrix, this method iterates over all rows {@code k} + * of the single matrix, and for each element, it multiplies the vector (from {@code bsMat}) + * by the scalar (from {@code mat}) and adds the result to the corresponding vector in {@code acc}. + *

    + * + * @param mVecLimbs the number of limbs (elements) in each vector. + * @param bsMat the bit‑sliced matrix stored as a long array. + * @param mat the matrix stored as a byte array. + * @param acc the accumulator array where the results are added. + * @param bsMatRows the number of rows in the bit‑sliced matrix. + * @param matRows the number of rows in the matrix. + */ + static void mulAddMUpperTriangularMatXMatTrans(int mVecLimbs, long[] bsMat, byte[] mat, long[] acc, int bsMatRows, int matRows) + { + int bsMatEntriesUsed = 0; + int multiply = mVecLimbs * matRows; + for (int r = 0, rmultiply = 0; r < bsMatRows; r++, rmultiply += multiply) + { + // For upper triangular, start c at triangular * r; otherwise, triangular is zero. + for (int c = r; c < bsMatRows; c++) + { + for (int k = 0, kbsMatRows = 0, kmVecLimbs = 0; k < matRows; k++, kbsMatRows += bsMatRows, kmVecLimbs += mVecLimbs) + { + mVecMulAdd(mVecLimbs, bsMat, bsMatEntriesUsed, mat[kbsMatRows + c], acc, rmultiply + kmVecLimbs); + } + bsMatEntriesUsed += mVecLimbs; + } + } + } + + /** + * Performs a GF(16) carryless multiplication of a nibble (lower 4 bits of a) + * with a 64-bit word b, then reduces modulo the polynomial x⁴ + x + 1 on each byte. + * + * @param a a GF(16) element (only the low 4 bits are used) + * @param b a 64-bit word representing 16 GF(16) elements (packed 4 bits per element) + * @return the reduced 64-bit word after multiplication + */ + static long mulFx8(byte a, long b) + { + // Convert 'a' to an unsigned int so that bit operations work as expected. + int aa = a & 0xFF; + // Carryless multiplication: for each bit in 'aa' (considering only the lower 4 bits), + // if that bit is set, multiply 'b' (by 1, 2, 4, or 8) and XOR the result. + long p = (-(aa & 1) & b) ^ (-((aa >> 1) & 1) & (b << 1)) ^ (-((aa >> 2) & 1) & (b << 2)) ^ (-((aa >> 3) & 1) & (b << 3)); + + // Reduction mod (x^4 + x + 1): process each byte in parallel. + long topP = p & 0xf0f0f0f0f0f0f0f0L; + return (p ^ (topP >>> 4) ^ (topP >>> 3)) & 0x0f0f0f0f0f0f0f0fL; + } + + static void matMul(byte[] a, byte[] b, int bOff, byte[] c, int colrowAB, int rowA) + { + for (int i = 0, aRowStart = 0, cOff = 0; i < rowA; i++) + { + byte result = 0; + for (int k = 0; k < colrowAB; k++) + { + result ^= GF16.mul(a[aRowStart++], b[bOff + k]); + } + c[cOff++] = result; + } + } +} + diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyGenerationParameters.java new file mode 100644 index 0000000000..0ca1b7f1b4 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyGenerationParameters.java @@ -0,0 +1,24 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class MayoKeyGenerationParameters + extends KeyGenerationParameters +{ + private final MayoParameters params; + + public MayoKeyGenerationParameters( + SecureRandom random, + MayoParameters mayoParameters) + { + super(random, 256); + this.params = mayoParameters; + } + + public MayoParameters getParameters() + { + return params; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyPairGenerator.java new file mode 100644 index 0000000000..4d0df2b02b --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyPairGenerator.java @@ -0,0 +1,149 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.GF16; +import org.bouncycastle.util.Longs; + +/** + * Implementation of the MAYO asymmetric key pair generator following the MAYO signature scheme specifications. + *

    + * This generator produces {@link MayoPublicKeyParameters} and {@link MayoPrivateKeyParameters} based on the + * MAYO algorithm parameters. The implementation follows the specification defined in the official MAYO + * documentation and reference implementation. + *

    + * + *

    References:

    + * + * + */ +public class MayoKeyPairGenerator + implements AsymmetricCipherKeyPairGenerator +{ + private MayoParameters p; + private SecureRandom random; + + public void init(KeyGenerationParameters param) + { + this.p = ((MayoKeyGenerationParameters)param).getParameters(); + this.random = param.getRandom(); + } + + /** + * Generates a new asymmetric key pair following the MAYO algorithm specifications. + *

    + * The key generation process follows these steps: + *

    + *
      + *
    1. Initializes parameter dimensions from {@link MayoParameters}
    2. + *
    3. Generates secret key seed using a secure random generator
    4. + *
    5. Derives public key seed using SHAKE-256
    6. + *
    7. Expands matrix parameters P1 and P2
    8. + *
    9. Performs GF(16) matrix operations for key material generation
    10. + *
    11. Assembles and packages the public key components
    12. + *
    13. Securely clears temporary buffers containing sensitive data
    14. + *
    + * + * @return A valid MAYO key pair containing public and private key parameters + */ + @Override + public AsymmetricCipherKeyPair generateKeyPair() + { + // Retrieve parameters from p. + int mVecLimbs = p.getMVecLimbs(); + int m = p.getM(); + int v = p.getV(); + int o = p.getO(); + int oBytes = p.getOBytes(); + int p1Limbs = p.getP1Limbs(); + int p3Limbs = p.getP3Limbs(); + int pkSeedBytes = p.getPkSeedBytes(); + int skSeedBytes = p.getSkSeedBytes(); + + byte[] cpk = new byte[p.getCpkBytes()]; + // seed_sk points to csk. + byte[] seed_sk = new byte[p.getCskBytes()]; + + // Allocate S = new byte[PK_SEED_BYTES_MAX + O_BYTES_MAX] + byte[] seed_pk = new byte[pkSeedBytes + oBytes]; + + // Allocate P as a long array of size (P1_LIMBS_MAX + P2_LIMBS_MAX) + long[] P = new long[p1Limbs + p.getP2Limbs()]; + + // Allocate P3 as a long array of size (O_MAX * O_MAX * M_VEC_LIMBS_MAX), zero-initialized. + long[] P3 = new long[o * o * mVecLimbs]; + + byte[] O = new byte[v * o]; + + // Generate secret key seed (seed_sk) using a secure random generator. + random.nextBytes(seed_sk); + + // S ← shake256(seed_sk, pk_seed_bytes + O_bytes) + SHAKEDigest shake = new SHAKEDigest(256); + shake.update(seed_sk, 0, skSeedBytes); + shake.doFinal(seed_pk, 0, pkSeedBytes + oBytes); + + // o ← Decode_o(S[ param_pk_seed_bytes : param_pk_seed_bytes + O_bytes ]) + // Decode nibbles from S starting at offset param_pk_seed_bytes into O, + // with expected output length = param_v * param_o. + GF16.decode(seed_pk, pkSeedBytes, O, 0, O.length); + + // Expand P1 and P2 into the array P using seed_pk. + Utils.expandP1P2(p, P, seed_pk); + + // Compute P1 * O + P2 and store the result in P2. + // GF16Utils.P1TimesO(p, P, O, P2); + // Here, bsMatRows and bsMatCols are both paramV, and matCols is paramO, triangular=1. + GF16Utils.mulAddMUpperTriangularMatXMat(mVecLimbs, P, O, P, p1Limbs, v, o); + + // Compute P3 = O^T * (P1*O + P2). + // Here, treat P2 as the bsMat for the multiplication. + // Dimensions: mat = O (size: paramV x paramO), bsMat = P2 (size: paramV x paramO), + // and acc (P3) will have dimensions: (paramO x paramO), each entry being an m-vector. + GF16Utils.mulAddMatTransXMMat(mVecLimbs, O, P, p1Limbs, P3, v, o); + + // Store seed_pk into the public key cpk. + System.arraycopy(seed_pk, 0, cpk, 0, pkSeedBytes); + + // Allocate an array for the "upper" part of P3. + long[] P3_upper = new long[p3Limbs]; + + // Compute Upper(P3) and store the result in P3_upper. + int mVecsStored = 0; + int omVecLimbs = o * mVecLimbs; + for (int r = 0, rmVecLimbs = 0, romVecLimbs = 0; r < o; r++, romVecLimbs += omVecLimbs, rmVecLimbs += mVecLimbs) + { + for (int c = r, cmVecLimbs = rmVecLimbs, comVecLimbs = romVecLimbs; c < o; c++, cmVecLimbs += mVecLimbs, comVecLimbs += omVecLimbs) + { + // Copy the vector at (r, c) into the output. + System.arraycopy(P3, romVecLimbs + cmVecLimbs, P3_upper, mVecsStored, mVecLimbs); + + // If off-diagonal, add (XOR) the vector at (c, r) into the same output vector. + if (r != c) + { + Longs.xorTo(mVecLimbs, P3, comVecLimbs + rmVecLimbs, P3_upper, mVecsStored); + } + mVecsStored += mVecLimbs; + } + } + + // Pack the m-vectors in P3_upper into cpk (after the seed_pk). + // The number of m-vectors to pack is (param_P3_limbs / m_vec_limbs), + // and param_m is used as the m value. + Utils.packMVecs(P3_upper, cpk, pkSeedBytes, p3Limbs / mVecLimbs, m); + // Securely clear sensitive data. + Arrays.clear(O); + Arrays.clear(P3); + + return new AsymmetricCipherKeyPair(new MayoPublicKeyParameters(p, cpk), new MayoPrivateKeyParameters(p, seed_sk)); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyParameters.java new file mode 100644 index 0000000000..4b932949dc --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoKeyParameters.java @@ -0,0 +1,22 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; + +public class MayoKeyParameters + extends AsymmetricKeyParameter +{ + private final MayoParameters params; + + public MayoKeyParameters( + boolean isPrivate, + MayoParameters params) + { + super(isPrivate); + this.params = params; + } + + public MayoParameters getParameters() + { + return params; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoParameters.java new file mode 100644 index 0000000000..28c01ad0c4 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoParameters.java @@ -0,0 +1,288 @@ +package org.bouncycastle.pqc.crypto.mayo; + +public class MayoParameters +{ + public static final MayoParameters mayo1 = new MayoParameters( + "MAYO_1", // name + 86, // n + 78, // m + 5, // m_vec_limbs + 8, // o + 86 - 8, // v = n - o = 78 + 10 * 8 + 1, // A_cols = k * o + 1 = 10 * 8 + 1 = 81 + 10, // k + // q + 39, // m_bytes + 312, // O_bytes + 39, // v_bytes + 40, // r_bytes + 120159, // P1_bytes + 24336, // P2_bytes + 24, // csk_bytes + 1420, // cpk_bytes + 454, // sig_bytes + new int[]{8, 1, 1, 0}, // F_TAIL_78 + 24, // salt_bytes + 32, // digest_bytes + 24 // sk_seed_bytes + ); + + public static final MayoParameters mayo2 = new MayoParameters( + "MAYO_2", // name + 81, // n + 64, // m + 4, // m_vec_limbs + 17, // o + 81 - 17, // v = 64 + 4 * 17 + 1, // A_cols = 4 * 17 + 1 = 69 + 4, // k + 32, // m_bytes + 544, // O_bytes + 32, // v_bytes + 34, // r_bytes + 66560, // P1_bytes + 34816, // P2_bytes + 24, // csk_bytes + 4912, // cpk_bytes + 186, // sig_bytes + new int[]{8, 0, 2, 8}, //F_TAIL_64 + 24, // salt_bytes + 32, // digest_bytes + 24 // sk_seed_bytes + ); + + public static final MayoParameters mayo3 = new MayoParameters( + "MAYO_3", // name + 118, // n + 108, // m + 7, // m_vec_limbs + 10, // o + 118 - 10, // v = 108 + 11 * 10 + 1, // A_cols = 11 * 10 + 1 = 111 + 11, // k + 54, // m_bytes + 540, // O_bytes + 54, // v_bytes + 55, // r_bytes + 317844, // P1_bytes + 58320, // P2_bytes + 32, // csk_bytes + 2986, // cpk_bytes + 681, // sig_bytes + new int[]{8, 0, 1, 7}, //F_TAIL_108 + 32, // salt_bytes + 48, // digest_bytes + 32 // sk_seed_bytes + ); + + public static final MayoParameters mayo5 = new MayoParameters( + "MAYO_5", // name + 154, // n + 142, // m + 9, // m_vec_limbs + 12, // o + 154 - 12, // v = 142 + 12 * 12 + 1, // A_cols = 12 * 12 + 1 = 145 + 12, // k + 71, // m_bytes + 852, // O_bytes + 71, // v_bytes + 72, // r_bytes + 720863, // P1_bytes + 120984, // P2_bytes + 40, // csk_bytes + 5554, // cpk_bytes + 964, // sig_bytes + new int[]{4, 0, 8, 1}, //F_TAIL_142 + 40, // salt_bytes + 64, // digest_bytes + 40 // sk_seed_bytes + ); + + private final String name; + private final int n; + private final int m; + private final int mVecLimbs; + private final int o; + private final int v; + private final int ACols; + private final int k; + //private final int q; q = 16 + private final int mBytes; + private final int OBytes; + private final int vBytes; + private final int rBytes; + private final int P1Bytes; + private final int P2Bytes; + private final int cskBytes; + private final int cpkBytes; + private final int sigBytes; + private final int[] fTail; + private final int saltBytes; + private final int digestBytes; + private static final int pkSeedBytes = 16; + private final int skSeedBytes; + + private MayoParameters(String name, int n, int m, int mVecLimbs, int o, int v, int ACols, int k, + int mBytes, int OBytes, int vBytes, int rBytes, int P1Bytes, int P2Bytes, + int cskBytes, int cpkBytes, int sigBytes, int[] fTail, + int saltBytes, int digestBytes, int skSeedBytes) + { + this.name = name; + this.n = n; + this.m = m; + this.mVecLimbs = mVecLimbs; + this.o = o; + this.v = v; + this.ACols = ACols; + this.k = k; + this.mBytes = mBytes; + this.OBytes = OBytes; + this.vBytes = vBytes; + this.rBytes = rBytes; + this.P1Bytes = P1Bytes; + this.P2Bytes = P2Bytes; + this.cskBytes = cskBytes; + this.cpkBytes = cpkBytes; + this.sigBytes = sigBytes; + this.fTail = fTail; + this.saltBytes = saltBytes; + this.digestBytes = digestBytes; + this.skSeedBytes = skSeedBytes; + } + + public String getName() + { + return name; + } + + public int getN() + { + return n; + } + + public int getM() + { + return m; + } + + public int getMVecLimbs() + { + return mVecLimbs; + } + + public int getO() + { + return o; + } + + public int getV() + { + return v; + } + + public int getACols() + { + return ACols; + } + + public int getK() + { + return k; + } + + public int getMBytes() + { + return mBytes; + } + + public int getOBytes() + { + return OBytes; + } + + public int getVBytes() + { + return vBytes; + } + + public int getRBytes() + { + return rBytes; + } + + public int getP1Bytes() + { + return P1Bytes; + } + + public int getP2Bytes() + { + return P2Bytes; + } + + public int getCskBytes() + { + return cskBytes; + } + + public int getCpkBytes() + { + return cpkBytes; + } + + public int getSigBytes() + { + return sigBytes; + } + + public int[] getFTail() + { + return fTail; + } + + public int getSaltBytes() + { + return saltBytes; + } + + public int getDigestBytes() + { + return digestBytes; + } + + public int getPkSeedBytes() + { + return pkSeedBytes; + } + + public int getSkSeedBytes() + { + return skSeedBytes; + } + + /** + * Computes: (v * (v + 1) / 2) * mVecLimbs + */ + public int getP1Limbs() + { + return ((v * (v + 1)) >> 1) * mVecLimbs; + } + + /** + * Computes: v * o * mVecLimbs + */ + public int getP2Limbs() + { + return v * o * mVecLimbs; + } + + /** + * Computes: (o * (o + 1) / 2) * mVecLimbs + */ + public int getP3Limbs() + { + return ((o * (o + 1)) >> 1) * mVecLimbs; + } +} + diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoPrivateKeyParameters.java new file mode 100644 index 0000000000..1dcc6324dd --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoPrivateKeyParameters.java @@ -0,0 +1,25 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import org.bouncycastle.util.Arrays; + +public class MayoPrivateKeyParameters + extends MayoKeyParameters +{ + private final byte[] seed_sk; + + public MayoPrivateKeyParameters(MayoParameters params, byte[] seed_sk) + { + super(true, params); + this.seed_sk = Arrays.clone(seed_sk); + } + + public byte[] getEncoded() + { + return Arrays.clone(seed_sk); + } + + public byte[] getSeedSk() + { + return Arrays.clone(seed_sk); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoPublicKeyParameters.java new file mode 100644 index 0000000000..f7df56fb69 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoPublicKeyParameters.java @@ -0,0 +1,25 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import org.bouncycastle.util.Arrays; + +public class MayoPublicKeyParameters + extends MayoKeyParameters +{ + private final byte[] p; + + public MayoPublicKeyParameters(MayoParameters params, byte[] p) + { + super(false, params); + this.p = Arrays.clone(p); + } + + public byte[] getP() + { + return Arrays.clone(p); + } + + public byte[] getEncoded() + { + return Arrays.clone(p); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoSigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoSigner.java new file mode 100644 index 0000000000..3909641eb6 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/MayoSigner.java @@ -0,0 +1,1011 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.MessageSigner; + +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Bytes; +import org.bouncycastle.util.GF16; +import org.bouncycastle.util.Longs; +import org.bouncycastle.util.Pack; + +/** + * Implementation of the MAYO digital signature scheme as specified in the MAYO documentation. + * This class provides functionality for both signature generation and verification. + * + *

    MAYO is a candidate in the NIST Post-Quantum Cryptography: Additional Digital Signature Schemes project, + * currently in Round 2 of evaluations. For more details about the NIST standardization process, see: + * NIST PQC Additional Digital Signatures.

    + * + *

    References:

    + * + */ +public class MayoSigner + implements MessageSigner +{ + private SecureRandom random; + private MayoParameters params; + private MayoPublicKeyParameters pubKey; + private MayoPrivateKeyParameters privKey; + + /** + * Initializes the signer for either signature generation or verification. + * + * @param forSigning {@code true} for signing mode, {@code false} for verification + * @param param CipherParameters containing: + *
      + *
    • {@link ParametersWithRandom} with {@link MayoPrivateKeyParameters} (for signing)
    • + *
    • {@link MayoPublicKeyParameters} (for verification)
    • + *
    + * @throws IllegalArgumentException if invalid parameters are provided + */ + @Override + public void init(boolean forSigning, CipherParameters param) + { + if (forSigning) + { + pubKey = null; + + if (param instanceof ParametersWithRandom) + { + ParametersWithRandom withRandom = (ParametersWithRandom)param; + privKey = (MayoPrivateKeyParameters)withRandom.getParameters(); + random = withRandom.getRandom(); + } + else + { + privKey = (MayoPrivateKeyParameters)param; + random = CryptoServicesRegistrar.getSecureRandom(); + } + params = privKey.getParameters(); + } + else + { + pubKey = (MayoPublicKeyParameters)param; + params = pubKey.getParameters(); + privKey = null; + random = null; + } + } + + /** + * Generates a MAYO signature for the given message using the initialized private key. + * Follows the signature generation process outlined in the MAYO specification document. + * + * @param message The message to be signed + * @return The signature bytes concatenated with the original message + * @see MAYO Spec Algorithm 8 and 10 + */ + @Override + public byte[] generateSignature(byte[] message) + { + int k = params.getK(); + int v = params.getV(); + int o = params.getO(); + int n = params.getN(); + int m = params.getM(); + int vbytes = params.getVBytes(); + int oBytes = params.getOBytes(); + int saltBytes = params.getSaltBytes(); + int mVecLimbs = params.getMVecLimbs(); + int p1Limbs = params.getP1Limbs(); + int pk_seed_bytes = params.getPkSeedBytes(); + int digestBytes = params.getDigestBytes(); + int skSeedBytes = params.getSkSeedBytes(); + byte[] tenc = new byte[params.getMBytes()]; + byte[] t = new byte[m]; + byte[] y = new byte[m]; + byte[] salt = new byte[saltBytes]; + byte[] V = new byte[k * vbytes + params.getRBytes()]; + byte[] Vdec = new byte[v * k]; + int ok = k * o; + int nk = k * n; + byte[] A = new byte[((m + 7) / 8 * 8) * (ok + 1)]; + byte[] x = new byte[nk]; + byte[] r = new byte[ok + 1]; + byte[] s = new byte[nk]; + byte[] tmp = new byte[digestBytes + saltBytes + skSeedBytes + 1]; + byte[] sig = new byte[params.getSigBytes()]; + long[] P = new long[p1Limbs + params.getP2Limbs()]; + byte[] O = new byte[v * o]; + long[] Mtmp = new long[ok * mVecLimbs]; + long[] vPv = new long[k * k * mVecLimbs]; + SHAKEDigest shake = new SHAKEDigest(256); + try + { + byte[] seed_sk = privKey.getSeedSk(); + // Expand secret key + //MayoEngine.mayoExpandSk(params, seed_sk, P, O); + int totalS = pk_seed_bytes + oBytes; + byte[] seed_pk = new byte[totalS]; + + // Generate S = seed_pk || (additional bytes), using SHAKE256. + // Output length is param_pk_seed_bytes + param_O_bytes. + shake.update(seed_sk, 0, seed_sk.length); + shake.doFinal(seed_pk, 0, totalS); + + // Decode the portion of S after the first param_pk_seed_bytes into O. + // (In C, this is: decode(S + param_pk_seed_bytes, O, param_v * param_o)) + GF16.decode(seed_pk, pk_seed_bytes, O, 0, O.length); + + // Expand P1 and P2 into the long array P using seed_pk. + Utils.expandP1P2(params, P, seed_pk); + + // Compute L_i = (P1 + P1^t)*O + P2. + // Here, we assume that P1P1tTimesO writes into the portion of P starting at offsetP2. + //MayoEngine.P1P1tTimesO(params, P, O, P, p1Limbs); + int bsMatEntriesUsed = 0; + int omVecLimbs = o * mVecLimbs; + for (int i = 0, io = 0, iomVecLimbs = 0; i < v; i++, io += o, iomVecLimbs += omVecLimbs) + { + for (int c = i, co = io, comVecLimbs = iomVecLimbs; c < v; c++, co += o, comVecLimbs += omVecLimbs) + { + if (c == i) + { + bsMatEntriesUsed += mVecLimbs; + continue; + } + for (int j = 0, jmVecLimbs = p1Limbs; j < o; j++, jmVecLimbs += mVecLimbs) + { + // Multiply the m-vector at P1 for the current matrix entry, + // and accumulate into acc for row r. + GF16Utils.mVecMulAdd(mVecLimbs, P, bsMatEntriesUsed, O[co + j], P, iomVecLimbs + jmVecLimbs); + // Similarly, accumulate into acc for row c. + GF16Utils.mVecMulAdd(mVecLimbs, P, bsMatEntriesUsed, O[io + j], P, comVecLimbs + jmVecLimbs); + } + bsMatEntriesUsed += mVecLimbs; + } + } + // Securely clear sensitive temporary data. + Arrays.fill(seed_pk, (byte)0); + + // Hash message + shake.update(message, 0, message.length); + shake.doFinal(tmp, 0, digestBytes); + + // Generate random salt + random.nextBytes(salt); + + System.arraycopy(salt, 0, tmp, digestBytes, salt.length); + + // Hash to salt + System.arraycopy(seed_sk, 0, tmp, digestBytes + saltBytes, skSeedBytes); + + shake.update(tmp, 0, digestBytes + saltBytes + skSeedBytes); + shake.doFinal(salt, 0, saltBytes); + + // Hash to t + System.arraycopy(salt, 0, tmp, digestBytes, saltBytes); + shake.update(tmp, 0, digestBytes + saltBytes); + shake.doFinal(tenc, 0, params.getMBytes()); + GF16.decode(tenc, t, m); + int size = v * k * mVecLimbs; + long[] Pv = new long[size]; + byte[] Ox = new byte[v]; + for (int ctr = 0; ctr <= 255; ctr++) + { + tmp[tmp.length - 1] = (byte)ctr; + + // Generate V + shake.update(tmp, 0, tmp.length); + shake.doFinal(V, 0, V.length); + + // Decode vectors + for (int i = 0; i < k; i++) + { + GF16.decode(V, i * vbytes, Vdec, i * v, v); + } + + //computeMandVPV(params, Vdec, P, params.getP1Limbs(), P, Mtmp, vPv); + // Compute VL: VL = Vdec * L + GF16Utils.mulAddMatXMMat(mVecLimbs, Vdec, P, p1Limbs, Mtmp, k, v, o); + + // Compute VP1V: + // Allocate temporary array for Pv. Its length is V_MAX * K_MAX * M_VEC_LIMBS_MAX. + // Compute Pv = P1 * V^T (using upper triangular multiplication) + GF16Utils.mulAddMUpperTriangularMatXMatTrans(mVecLimbs, P, Vdec, Pv, v, k); + // Compute VP1V = Vdec * Pv + GF16Utils.mulAddMatXMMat(mVecLimbs, Vdec, Pv, vPv, k, v); + + computeRHS(vPv, t, y); + computeA(Mtmp, A); + + // Clear trailing bytes +// for (int i = 0; i < m; ++i) +// { +// A[(i + 1) * (ok + 1) - 1] = 0; +// } + + GF16.decode(V, k * vbytes, r, 0, ok); + + if (sampleSolution(A, y, r, x)) + { + break; + } + else + { + Arrays.fill(Mtmp, 0L); + Arrays.fill(vPv, 0L); + } + } + + // Compute final signature components + + for (int i = 0, io = 0, in = 0, iv = 0; i < k; i++, io += o, in += n, iv += v) + { + GF16Utils.matMul(O, x, io, Ox, o, v); + Bytes.xor(v, Vdec, iv, Ox, s, in); + System.arraycopy(x, io, s, in + v, o); + } + + // Encode and add salt + GF16.encode(s, sig, nk); + System.arraycopy(salt, 0, sig, sig.length - saltBytes, saltBytes); + + return Arrays.concatenate(sig, message); + } + finally + { + // Secure cleanup + Arrays.fill(tenc, (byte)0); + Arrays.fill(t, (byte)0); + Arrays.fill(y, (byte)0); + Arrays.fill(salt, (byte)0); + Arrays.fill(V, (byte)0); + Arrays.fill(Vdec, (byte)0); + Arrays.fill(A, (byte)0); + Arrays.fill(x, (byte)0); + Arrays.fill(r, (byte)0); + Arrays.fill(s, (byte)0); + Arrays.fill(tmp, (byte)0); + } + } + + /** + * Verifies a MAYO signature against the initialized public key and message. + * Implements the verification process specified in the MAYO documentation. + * + * @param message The original message + * @param signature The signature to verify + * @return {@code true} if the signature is valid, {@code false} otherwise + * @see MAYO Spec Algorithm 9 and 11 + */ + @Override + public boolean verifySignature(byte[] message, byte[] signature) + { + final int m = params.getM(); + final int n = params.getN(); + final int k = params.getK(); + int kn = k * n; + int p1Limbs = params.getP1Limbs(); + int p2Limbs = params.getP2Limbs(); + int p3Limbs = params.getP3Limbs(); + final int mBytes = params.getMBytes(); + final int sigBytes = params.getSigBytes(); + final int digestBytes = params.getDigestBytes(); + final int saltBytes = params.getSaltBytes(); + int mVecLimbs = params.getMVecLimbs(); + byte[] tEnc = new byte[mBytes]; + byte[] t = new byte[m]; + byte[] y = new byte[m << 1]; + byte[] s = new byte[kn]; + long[] pk = new long[p1Limbs + p2Limbs + p3Limbs]; + byte[] tmp = new byte[digestBytes + saltBytes]; + byte[] cpk = pubKey.getEncoded(); + + // Expand public key + // mayo_expand_pk + Utils.expandP1P2(params, pk, cpk); + Utils.unpackMVecs(cpk, params.getPkSeedBytes(), pk, p1Limbs + p2Limbs, p3Limbs / mVecLimbs, m); + + // Hash message + SHAKEDigest shake = new SHAKEDigest(256); + shake.update(message, 0, message.length); + shake.doFinal(tmp, 0, digestBytes); + + // Compute t + shake.update(tmp, 0, digestBytes); + shake.update(signature, sigBytes - saltBytes, saltBytes); + shake.doFinal(tEnc, 0, mBytes); + GF16.decode(tEnc, t, m); + + // Decode signature + GF16.decode(signature, s, kn); + + // Evaluate public map + //evalPublicMap(params, s, P1, P2, P3, y); + long[] SPS = new long[k * k * mVecLimbs]; + long[] PS = new long[kn * mVecLimbs]; + mayoGenericMCalculatePS(params, pk, p1Limbs, p1Limbs + p2Limbs, s, params.getV(), params.getO(), k, PS); + mayoGenericMCalculateSPS(PS, s, mVecLimbs, k, n, SPS); + byte[] zero = new byte[m]; + computeRHS(SPS, zero, y); + + // Compare results + return Arrays.constantTimeAreEqual(m, y, 0, t, 0); + } + + void computeRHS(long[] vPv, byte[] t, byte[] y) + { + final int m = params.getM(); + final int mVecLimbs = params.getMVecLimbs(); + final int k = params.getK(); + final int[] fTail = params.getFTail(); + + final int topPos = ((m - 1) & 15) << 2; + + // Zero out tails of m_vecs if necessary + if ((m & 15) != 0) + { + long mask = (1L << ((m & 15) << 2)) - 1; + final int kSquared = k * k; + + for (int i = 0, index = mVecLimbs - 1; i < kSquared; i++, index += mVecLimbs) + { + vPv[index] &= mask; + } + } + + long[] temp = new long[mVecLimbs]; + byte[] tempBytes = new byte[mVecLimbs << 3]; + int kmVecLimbs = k * mVecLimbs; + + for (int i = k - 1, imVecLimbs = i * mVecLimbs, ikmVecLimbs = imVecLimbs * k; i >= 0; i--, + imVecLimbs -= mVecLimbs, ikmVecLimbs -= kmVecLimbs) + { + for (int j = i, jmVecLimbs = imVecLimbs, jkmVecLimbs = ikmVecLimbs; j < k; j++, + jmVecLimbs += mVecLimbs, jkmVecLimbs += kmVecLimbs) + { + // Multiply by X (shift up 4 bits) + int top = (int)((temp[mVecLimbs - 1] >>> topPos) & 0xF); + temp[mVecLimbs - 1] <<= 4; + + for (int limb = mVecLimbs - 2; limb >= 0; limb--) + { + temp[limb + 1] ^= temp[limb] >>> 60; + temp[limb] <<= 4; + } + Pack.longToLittleEndian(temp, tempBytes, 0); + + // Reduce mod f(X) + for (int jj = 0; jj < 4; jj++) + { + int ft = fTail[jj]; + if (ft == 0) + { + continue; + } + + long product = GF16.mul(top, ft); + if ((jj & 1) == 0) + { + tempBytes[jj >> 1] ^= (byte)(product & 0xF); + } + else + { + tempBytes[jj >> 1] ^= (byte)((product & 0xF) << 4); + } + } + Pack.littleEndianToLong(tempBytes, 0, temp); + + // Extract from vPv and add + int matrixIndex = ikmVecLimbs + jmVecLimbs; + int symmetricIndex = jkmVecLimbs + imVecLimbs; + boolean isDiagonal = (i == j); + + for (int limb = 0; limb < mVecLimbs; limb++) + { + long value = vPv[matrixIndex + limb]; + if (!isDiagonal) + { + value ^= vPv[symmetricIndex + limb]; + } + temp[limb] ^= value; + } + } + } + Pack.longToLittleEndian(temp, tempBytes, 0); + // Compute y + for (int i = 0; i < m; i += 2) + { + int bytePos = i >> 1; + y[i] = (byte)(t[i] ^ (tempBytes[bytePos] & 0xF)); + y[i + 1] = (byte)(t[i + 1] ^ ((tempBytes[bytePos] >>> 4) & 0xF)); + } + } + + private static final int F_TAIL_LEN = 4; + private static final long EVEN_BYTES = 0x00FF00FF00FF00FFL; + private static final long EVEN_2BYTES = 0x0000FFFF0000FFFFL; + + void computeA(long[] Mtmp, byte[] AOut) + { + final int k = params.getK(); + final int o = params.getO(); + final int m = params.getM(); + final int mVecLimbs = params.getMVecLimbs(); + final int ACols = params.getACols(); + final int[] fTailArr = params.getFTail(); + + int bitsToShift = 0; + int wordsToShift = 0; + final int MAYO_M_OVER_8 = (m + 7) >>> 3; + int ok = o * k; + int omVecLimbs = o * mVecLimbs; + final int AWidth = ((ok + 15) >> 4) << 4; + long[] A = new long[(AWidth * MAYO_M_OVER_8) << 4]; + + // Zero out tails of m_vecs if necessary + if ((m & 15) != 0) + { + long mask = 1L << ((m & 15) << 2); + mask -= 1; + for (int i = 0, idx = mVecLimbs - 1; i < ok; i++, idx += mVecLimbs) + { + Mtmp[idx] &= mask; + } + } + + for (int i = 0, io = 0, iomVecLimbs = 0; i < k; i++, io += o, iomVecLimbs += omVecLimbs) + { + for (int j = k - 1, jomVecLimbs = j * omVecLimbs, jo = j * o; j >= i; j--, jomVecLimbs -= omVecLimbs, jo -= o) + { + // Process Mj + for (int c = 0, cmVecLimbs = 0; c < o; c++, cmVecLimbs += mVecLimbs) + { + for (int limb = 0, limbAWidhth = 0; limb < mVecLimbs; limb++, limbAWidhth += AWidth) + { + long value = Mtmp[jomVecLimbs + limb + cmVecLimbs]; + + int aIndex = io + c + wordsToShift + limbAWidhth; + A[aIndex] ^= value << bitsToShift; + + if (bitsToShift > 0) + { + A[aIndex + AWidth] ^= value >>> (64 - bitsToShift); + } + } + } + + if (i != j) + { + // Process Mi + for (int c = 0, cmVecLimbs = 0; c < o; c++, cmVecLimbs += mVecLimbs) + { + for (int limb = 0, limbAWidhth = 0; limb < mVecLimbs; limb++, limbAWidhth += AWidth) + { + long value = Mtmp[iomVecLimbs + limb + cmVecLimbs]; + int aIndex = jo + c + wordsToShift + limbAWidhth; + A[aIndex] ^= value << bitsToShift; + + if (bitsToShift > 0) + { + A[aIndex + AWidth] ^= value >>> (64 - bitsToShift); + } + } + } + } + + bitsToShift += 4; + if (bitsToShift == 64) + { + wordsToShift += AWidth; + bitsToShift = 0; + } + } + } + + // Transpose blocks + for (int c = 0; c < AWidth * ((m + (((k + 1) * k) >> 1) + 15) >>> 4); c += 16) + { + transpose16x16Nibbles(A, c); + } + + // Generate tab array + byte[] tab = new byte[F_TAIL_LEN << 2]; + for (int i = 0, idx = 0; i < F_TAIL_LEN; i++) + { + int ft = fTailArr[i]; + tab[idx++] = (byte)GF16.mul(ft, 1); + tab[idx++] = (byte)GF16.mul(ft, 2); + tab[idx++] = (byte)GF16.mul(ft, 4); + tab[idx++] = (byte)GF16.mul(ft, 8); + } + + // Final processing + for (int c = 0; c < AWidth; c += 16) + { + for (int r = m; r < m + (((k + 1) * k) >>> 1); r++) + { + int pos = (r >>> 4) * AWidth + c + (r & 15); + long t0 = A[pos] & GF16Utils.MASK_LSB; + long t1 = (A[pos] >>> 1) & GF16Utils.MASK_LSB; + long t2 = (A[pos] >>> 2) & GF16Utils.MASK_LSB; + long t3 = (A[pos] >>> 3) & GF16Utils.MASK_LSB; + + for (int t = 0, t4 = 0; t < F_TAIL_LEN; t++, t4 += 4) + { + int targetRow = r + t - m; + int targetPos = (targetRow >> 4) * AWidth + c + (targetRow & 15); + A[targetPos] ^= (t0 * tab[t4]) ^ (t1 * tab[t4 + 1]) + ^ (t2 * tab[t4 + 2]) ^ (t3 * tab[t4 + 3]); + } + } + } + + byte[] Abytes = Pack.longToLittleEndian(A); + // Decode to output + for (int r = 0; r < m; r += 16) + { + for (int c = 0; c < ACols - 1; c += 16) + { + for (int i = 0; i + r < m; i++) + { + GF16.decode(Abytes, (((r * AWidth) >> 4) + c + i) << 3, + AOut, (r + i) * ACols + c, Math.min(16, ACols - 1 - c)); + } + } + } + } + + private static void transpose16x16Nibbles(long[] M, int offset) + { + for (int i = 0; i < 16; i += 2) + { + int idx1 = offset + i; + int idx2 = idx1 + 1; + long t = ((M[idx1] >>> 4) ^ M[idx2]) & 0x0F0F0F0F0F0F0F0FL; + M[idx1] ^= t << 4; + M[idx2] ^= t; + } + + for (int i = 0, base = offset; i < 16; i += 4) + { + long t0 = ((M[base] >>> 8) ^ M[base + 2]) & EVEN_BYTES; + long t1 = ((M[base + 1] >>> 8) ^ M[base + 3]) & EVEN_BYTES; + M[base++] ^= t0 << 8; + M[base++] ^= t1 << 8; + M[base++] ^= t0; + M[base++] ^= t1; + } + + for (int i = 0; i < 4; i++) + { + int base = offset + i; + long t0 = ((M[base] >>> 16) ^ M[base + 4]) & EVEN_2BYTES; + long t1 = ((M[base + 8] >>> 16) ^ M[base + 12]) & EVEN_2BYTES; + M[base] ^= t0 << 16; + M[base + 8] ^= t1 << 16; + M[base + 4] ^= t0; + M[base + 12] ^= t1; + } + + for (int i = 0; i < 8; i++) + { + int base = offset + i; + long t = ((M[base] >>> 32) ^ M[base + 8]) & 0x00000000FFFFFFFFL; + M[base] ^= t << 32; + M[base + 8] ^= t; + } + } + + /** + * Samples a solution for the MAYO signature equation using the provided parameters. + * + * @param A Coefficient matrix + * @param y Target vector + * @param r Randomness vector + * @param x Output solution vector + * @return {@code true} if a valid solution was found, {@code false} otherwise + * @see MAYO Spec Algorithm 2 + */ + boolean sampleSolution(byte[] A, byte[] y, byte[] r, byte[] x) + { + final int k = params.getK(); + final int o = params.getO(); + final int m = params.getM(); + final int aCols = params.getACols(); + int ok = k * o; + // Initialize x with r values + System.arraycopy(r, 0, x, 0, ok); + + // Compute Ar matrix product + byte[] Ar = new byte[m]; + + // Clear last column of A +// for (int i = 0; i < m; i++) +// { +// A[ok + i * (ok + 1)] = 0; +// } + GF16Utils.matMul(A, r, 0, Ar, ok + 1, m); + + // Update last column of A with y - Ar + for (int i = 0, idx = ok; i < m; i++, idx += ok + 1) + { + A[idx] = (byte)(y[i] ^ Ar[i]); + } + + // Perform row echelon form transformation + ef(A, m, aCols); + + // Check matrix rank + boolean fullRank = false; + for (int i = 0, idx = (m - 1) * aCols; i < aCols - 1; i++, idx++) + { + fullRank |= (A[idx] != 0); + } + if (!fullRank) + { + return false; + } + + // Constant-time back substitution + for (int row = m - 1, rowAcols = row * aCols; row >= 0; row--, rowAcols -= aCols) + { + byte finished = 0; + int colUpperBound = Math.min(row + (32 / (m - row)), ok); + + for (int col = row; col <= colUpperBound; col++) + { + byte correctCol = (byte)((-(A[rowAcols + col] & 0xFF)) >> 31); + + // Update x[col] using constant-time mask + byte u = (byte)(correctCol & ~finished & A[rowAcols + aCols - 1]); + x[col] ^= u; + + // Update matrix entries + for (int i = 0, iaCols_col = col, iaCols_aCols1 = aCols - 1; i < row; i += 8, + iaCols_col += aCols << 3, iaCols_aCols1 += aCols << 3) + { + long tmp = 0; + // Pack 8 GF(16) elements into long + for (int j = 0, jaCols = 0; j < 8; j++, jaCols += aCols) + { + tmp ^= (long)(A[iaCols_col + jaCols] & 0xFF) << (j << 3); + } + + // GF(16) multiplication + tmp = GF16Utils.mulFx8(u, tmp); + + // Unpack and update + for (int j = 0, jaCols = 0; j < 8; j++, jaCols += aCols) + { + A[iaCols_aCols1 + jaCols] ^= (byte)((tmp >> (j << 3)) & 0x0F); + } + } + finished |= correctCol; + } + } + return true; + } + + /** + * Converts a matrix A (given as a flat array of GF(16) elements, one per byte) + * into row echelon form (with ones on the first nonzero entries) in constant time. + * + * @param A the input matrix, stored rowwise; each element is in [0,15] + * @param nrows the number of rows + * @param ncols the number of columns (GF(16) elements per row) + * @see MAYO Spec Algorithm 1 + */ + void ef(byte[] A, int nrows, int ncols) + { + // Each 64-bit long can hold 16 nibbles (16 GF(16) elements). + int rowLen = (ncols + 15) >> 4; + + // Allocate temporary arrays. + long[] pivotRow = new long[rowLen]; + long[] pivotRow2 = new long[rowLen]; + // The packed matrix: one contiguous array storing nrows rows, each rowLen longs long. + long[] packedA = new long[nrows * rowLen]; + int len = params.getO() * params.getK() + 16; + byte[] bytes = new byte[len >> 1]; + int len_4 = len >> 4; + + // Pack the matrix rows. + for (int i = 0, incols = 0, irowLen = 0; i < nrows; i++, incols += ncols, irowLen += rowLen) + { + //packRow(A, i, ncols); + // Process each 64-bit word (each holds 16 nibbles). + for (int word = 0; word < rowLen; word++) + { + long wordVal = 0; + for (int nibble = 0; nibble < 16; nibble++) + { + int col = (word << 4) + nibble; + if (col < ncols) + { + wordVal |= ((long)A[incols + col] & 0xF) << (nibble << 2); + } + } + packedA[word + irowLen] = wordVal; + } + } + + int pivotRowIndex = 0; + // Loop over each pivot column (each column corresponds to one GF(16) element) + for (int pivotCol = 0; pivotCol < ncols; pivotCol++) + { + int lowerBound = Math.max(0, pivotCol + nrows - ncols); + int upperBound = Math.min(nrows - 1, pivotCol); + + // Zero out pivot row buffers. + Arrays.clear(pivotRow); + Arrays.clear(pivotRow2); + + // Try to select a pivot row in constant time. + int pivot = 0; + long pivotIsZero = -1L; // all bits set (0xFFFFFFFFFFFFFFFF) + int searchUpper = Math.min(nrows - 1, upperBound + 32); + for (int row = lowerBound, rowRowLen = lowerBound * rowLen; row <= searchUpper; row++, rowRowLen += rowLen) + { + long isPivotRow = ~ctCompare64(row, pivotRowIndex); + //ct64IsGreaterThan(a, b): Returns 0xFFFFFFFFFFFFFFFF if a > b, 0 otherwise. + long belowPivotRow = ((long)pivotRowIndex - (long)row) >> 63; + for (int j = 0; j < rowLen; j++) + { + // The expression below accumulates (in constant time) the candidate pivot row. + pivotRow[j] ^= (isPivotRow | (belowPivotRow & pivotIsZero)) & packedA[rowRowLen + j]; + } + // Extract candidate pivot element from the packed row. + pivot = (int)((pivotRow[pivotCol >>> 4] >>> ((pivotCol & 15) << 2)) & 0xF); + pivotIsZero = ~((-(long)pivot) >> 63); + } + + // Multiply the pivot row by the inverse of the pivot element. + vecMulAddU64(rowLen, pivotRow, GF16.inv((byte)pivot), pivotRow2); + + // Conditionally write the pivot row back into the correct row (if pivot is nonzero). + for (int row = lowerBound, rowRowLen = lowerBound * rowLen; row <= upperBound; row++, rowRowLen += rowLen) + { + long doCopy = ~ctCompare64(row, pivotRowIndex) & ~pivotIsZero; + long doNotCopy = ~doCopy; + for (int col = 0, rowRowLen_col = rowRowLen; col < rowLen; col++, rowRowLen_col++) + { + // Since the masks are disjoint, addition is equivalent to OR. + packedA[rowRowLen_col] = (doNotCopy & packedA[rowRowLen_col]) | (doCopy & pivotRow2[col]); + } + } + + // Eliminate entries below the pivot. + for (int row = lowerBound, rowRowLen = lowerBound * rowLen; row < nrows; row++, rowRowLen += rowLen) + { + int belowPivot = (row > pivotRowIndex) ? -1 : 0; + //int eltToElim = mExtractElementFromPacked(packedA, row, rowLen, pivotCol); + int eltToElim = (int)((packedA[rowRowLen + (pivotCol >>> 4)] >>> ((pivotCol & 15) << 2)) & 0xF); + vecMulAddU64(rowLen, pivotRow2, (byte)(belowPivot & eltToElim), packedA, rowRowLen); + } + + // If pivot is nonzero, increment pivotRowIndex. + if (pivot != 0) + { + pivotRowIndex++; + } + } + + int outIndex = 0; + // At this point, packedA holds the row-echelon form of the original matrix. + // (Depending on your application you might want to unpack it back to A.) + for (int i = 0, irowLen = 0; i < nrows; i++, irowLen += rowLen) + { + Pack.longToLittleEndian(packedA, irowLen, len_4, bytes, 0); + GF16.decode(bytes, 0, A, outIndex, ncols); + outIndex += ncols; + } + } + + /** + * Constant-time comparison: returns 0 if a==b, else returns all 1s (0xFFFFFFFFFFFFFFFF). + */ + private static long ctCompare64(int a, int b) + { + // Compute (-(a XOR b)) >> 63 then XOR with UINT64_BLOCKER. + return (-(long)(a ^ b)) >> 63; + } + + /** + * Multiplies each word of the input vector (in) by a GF(16) scalar (a), + * then XORs the result into the accumulator vector (acc). + *

    + * This version updates the acc array starting at index 0. + * + * @param legs the number of 64-bit words in the vector. + * @param in the input vector. + * @param a the GF(16) scalar (as a byte; only low 4 bits used). + * @param acc the accumulator vector which is updated. + */ + private static void vecMulAddU64(int legs, long[] in, byte a, long[] acc) + { + int tab = mulTable(a & 0xFF); + for (int i = 0; i < legs; i++) + { + long val = ((in[i] & GF16Utils.MASK_LSB) * (tab & 0xFF)) + ^ (((in[i] >>> 1) & GF16Utils.MASK_LSB) * ((tab >>> 8) & 0xF)) + ^ (((in[i] >>> 2) & GF16Utils.MASK_LSB) * ((tab >>> 16) & 0xF)) + ^ (((in[i] >>> 3) & GF16Utils.MASK_LSB) * ((tab >>> 24) & 0xF)); + acc[i] ^= val; + } + } + + /** + * Overloaded version of vecMulAddU64 that writes to acc starting at accOffset. + * + * @param legs the number of 64-bit words. + * @param in the input vector. + * @param a the GF(16) scalar. + * @param acc the accumulator vector. + * @param accOffset the starting index in acc. + */ + private static void vecMulAddU64(int legs, long[] in, byte a, long[] acc, int accOffset) + { + int tab = mulTable(a & 0xFF); + for (int i = 0; i < legs; i++) + { + long val = ((in[i] & GF16Utils.MASK_LSB) * (tab & 0xFF)) + ^ (((in[i] >>> 1) & GF16Utils.MASK_LSB) * ((tab >>> 8) & 0xF)) + ^ (((in[i] >>> 2) & GF16Utils.MASK_LSB) * ((tab >>> 16) & 0xF)) + ^ (((in[i] >>> 3) & GF16Utils.MASK_LSB) * ((tab >>> 24) & 0xF)); + acc[accOffset + i] ^= val; + } + } + + /** + * Computes a multiplication table for nibble-packed vectors. + *

    + * Implements arithmetic for GF(16) elements modulo (x^4 + x + 1). + * + * @param b a GF(16) element (only lower 4 bits are used) + * @return a 32-bit integer representing the multiplication table. + */ + private static int mulTable(int b) + { + int x = b * 0x08040201; + int highHalf = x & 0xf0f0f0f0; + return x ^ (highHalf >>> 4) ^ (highHalf >>> 3); + } + + private static void mayoGenericMCalculatePS(MayoParameters p, long[] P1, int p2, int p3, byte[] S, + int v, int o, int k, long[] PS) + { + int n = o + v; + int mVecLimbs = p.getMVecLimbs(); + long[] accumulator = new long[(mVecLimbs * p.getK() * p.getN() * mVecLimbs) << 4]; + int o_mVecLimbs = o * mVecLimbs; + int pUsed = 0; + for (int row = 0, krow = 0, orow_mVecLimbs = 0; row < v; row++, krow += k, orow_mVecLimbs += o_mVecLimbs) + { + for (int j = row; j < v; j++) + { + for (int col = 0, ncol = 0; col < k; col++, ncol += n) + { + Longs.xorTo(mVecLimbs, P1, pUsed, accumulator, (((krow + col) << 4) + (S[ncol + j] & 0xFF)) * mVecLimbs); + } + pUsed += mVecLimbs; + } + + for (int j = 0, orow_j_mVecLimbs = orow_mVecLimbs; j < o; j++, orow_j_mVecLimbs += mVecLimbs) + { + for (int col = 0, ncol = 0; col < k; col++, ncol += n) + { + Longs.xorTo(mVecLimbs, P1, p2 + orow_j_mVecLimbs, accumulator, (((krow + col) << 4) + (S[ncol + j + v] & 0xFF)) * mVecLimbs); + } + } + } + + pUsed = 0; + for (int row = v, krow = v * k; row < n; row++, krow += k) + { + for (int j = row; j < n; j++) + { + for (int col = 0, ncol = 0; col < k; col++, ncol += n) + { + Longs.xorTo(mVecLimbs, P1, p3 + pUsed, accumulator, (((krow + col) << 4) + (S[ncol + j] & 0xFF)) * mVecLimbs); + } + pUsed += mVecLimbs; + } + } + + mVecMultiplyBins(mVecLimbs, n * k, accumulator, PS); + } + + private static void mayoGenericMCalculateSPS(long[] PS, byte[] S, int mVecLimbs, int k, int n, long[] SPS) + { + int kk = k * k; + final int accumulatorSize = (mVecLimbs * kk) << 4; + final long[] accumulator = new long[accumulatorSize]; + int kmVecLimbs = k * mVecLimbs; + + // Accumulation phase + for (int row = 0, nrow = 0, krowmVecLimbs16 = 0; row < k; row++, nrow += n, krowmVecLimbs16 += kmVecLimbs << 4) + { + for (int j = 0, jkmVecLimbs = 0; j < n; j++, jkmVecLimbs += kmVecLimbs) + { + final int sValmVecLimbs = (S[nrow + j] & 0xFF) * mVecLimbs + krowmVecLimbs16; // Unsigned byte value + for (int col = 0, colmVecLimbs = 0; col < k; col++, colmVecLimbs += mVecLimbs) + { + Longs.xorTo(mVecLimbs, PS, jkmVecLimbs + colmVecLimbs, accumulator, sValmVecLimbs + (colmVecLimbs << 4)); + } + } + } + + // Processing phase + mVecMultiplyBins(mVecLimbs, kk, accumulator, SPS); + } + + private static void mVecMultiplyBins(int mVecLimbs, int len, long[] bins, long[] ps) + { + long a, b, t; + int mVecLimbs2 = mVecLimbs + mVecLimbs, + mVecLimbs3 = mVecLimbs2 + mVecLimbs, + mVecLimbs4 = mVecLimbs3 + mVecLimbs, + mVecLimbs5 = mVecLimbs4 + mVecLimbs, + mVecLimbs6 = mVecLimbs5 + mVecLimbs, + mVecLimbs7 = mVecLimbs6 + mVecLimbs, + mVecLimbs8 = mVecLimbs7 + mVecLimbs, + mVecLimbs9 = mVecLimbs8 + mVecLimbs, + mVecLimbs10 = mVecLimbs9 + mVecLimbs, + mVecLimbs11 = mVecLimbs10 + mVecLimbs, + mVecLimbs12 = mVecLimbs11 + mVecLimbs, + mVecLimbs13 = mVecLimbs12 + mVecLimbs, + mVecLimbs14 = mVecLimbs13 + mVecLimbs, + mVecLimbs15 = mVecLimbs14 + mVecLimbs; + for (int i = 0, imVecLimbs4 = 0; i < len; i++, imVecLimbs4 += (mVecLimbs << 4)) + { + for (int j = 0, off = imVecLimbs4; j < mVecLimbs; j++, off++) + { + b = bins[off + mVecLimbs5]; + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs10] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + a = bins[off + mVecLimbs11]; + t = (a & GF16Utils.MASK_MSB) >>> 3; + a = bins[off + mVecLimbs12] ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs7] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + t = (a & GF16Utils.MASK_MSB) >>> 3; + a = bins[off + mVecLimbs6] ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs14] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + t = (a & GF16Utils.MASK_MSB) >>> 3; + a = bins[off + mVecLimbs3] ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs15] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + t = (a & GF16Utils.MASK_MSB) >>> 3; + a = bins[off + mVecLimbs8] ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs13] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + t = (a & GF16Utils.MASK_MSB) >>> 3; + a = bins[off + mVecLimbs4] ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs9] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + t = (a & GF16Utils.MASK_MSB) >>> 3; + a = bins[off + mVecLimbs2] ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + + t = b & GF16Utils.MASK_LSB; + b = bins[off + mVecLimbs] ^ ((b & GF16Utils.NIBBLE_MASK_LSB) >>> 1) ^ ((t << 3) + t); + + t = (a & GF16Utils.MASK_MSB) >>> 3; + ps[(imVecLimbs4 >> 4) + j] = b ^ ((a & GF16Utils.NIBBLE_MASK_MSB) << 1) ^ ((t << 1) + t); + } + } + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/Utils.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/Utils.java new file mode 100644 index 0000000000..934b5ae2f1 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mayo/Utils.java @@ -0,0 +1,115 @@ +package org.bouncycastle.pqc.crypto.mayo; + +import org.bouncycastle.crypto.BlockCipher; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.modes.CTRModeCipher; +import org.bouncycastle.crypto.modes.SICBlockCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Pack; + +class Utils +{ + public static void unpackMVecs(byte[] in, int inOff, long[] out, int outOff, int vecs, int m) + { + int mVecLimbs = (m + 15) >> 4; + int bytesToCopy = m >> 1; // Number of bytes to copy per vector + // Temporary buffer to hold mVecLimbs longs (each long is 8 bytes) + int lastblockLen = 8 - (mVecLimbs << 3) + bytesToCopy; + int i, j; + // Process vectors in reverse order + for (i = vecs - 1, outOff += i * mVecLimbs, inOff += i * bytesToCopy; i >= 0; i--, outOff -= mVecLimbs, inOff -= bytesToCopy) + { + // Convert each 8-byte block in tmp into a long using Pack + for (j = 0; j < mVecLimbs - 1; j++) + { + out[outOff + j] = Pack.littleEndianToLong(in, inOff + (j << 3)); + } + out[outOff + j] = Pack.littleEndianToLong(in, inOff + (j << 3), lastblockLen); + } + } + + /** + * Packs m-vectors from an array of 64-bit limbs into a packed byte array. + * + * @param in the input long array containing the m-vectors + * @param out the output byte array that will contain the packed data + * @param vecs the number of vectors + * @param m the m parameter (used to compute m_vec_limbs and copy lengths) + */ + public static void packMVecs(long[] in, byte[] out, int outOff, int vecs, int m) + { + int mVecLimbs = (m + 15) >> 4; + int bytesToCopy = m >> 1; // Number of bytes per vector to write + int lastBlockLen = 8 - (mVecLimbs << 3) + bytesToCopy; + int j; + // Process each vector in order + for (int i = 0, inOff = 0; i < vecs; i++, outOff += bytesToCopy, inOff += mVecLimbs) + { + // Convert each long into 8 bytes using Pack + for (j = 0; j < mVecLimbs - 1; j++) + { + Pack.longToLittleEndian(in[inOff + j], out, outOff + (j << 3)); + } + Pack.longToLittleEndian(in[inOff + j], out, outOff + (j << 3), lastBlockLen); + } + } + + /** + * Expands P1 and P2 using AES_128_CTR as a PRF and then unpacks the resulting bytes + * into an array of 64-bit limbs. + * + * @param p Mayo parameters + * @param P The output long array which will hold the unpacked limbs. + * Its length should be at least ((P1_bytes + P2_bytes) / 8) limbs. + * @param seed_pk The seed (used as the key) for the PRF. + */ + public static void expandP1P2(MayoParameters p, long[] P, byte[] seed_pk) + { + // Compute total number of bytes to generate: P1_bytes + P2_bytes. + int outLen = p.getP1Bytes() + p.getP2Bytes(); + // Temporary byte array to hold the PRF output. + byte[] temp = new byte[outLen]; + + //AES_128_CTR(temp, outLen, seed_pk, p.getPkSeedBytes()); + // Create a 16-byte IV (all zeros) + byte[] iv = new byte[16]; // automatically zero-initialized + + // Set up AES engine in CTR (SIC) mode. + BlockCipher aesEngine = AESEngine.newInstance(); + // SICBlockCipher implements CTR mode for AES. + CTRModeCipher ctrCipher = SICBlockCipher.newInstance(aesEngine); + // Wrap the key with the IV. + ParametersWithIV params = new ParametersWithIV(new KeyParameter(Arrays.copyOf(seed_pk, p.getPkSeedBytes())), iv); + ctrCipher.init(true, params); + + // CTR mode is a stream cipher: encrypting zero bytes produces the keystream. + int blockSize = ctrCipher.getBlockSize(); // typically 16 bytes + byte[] zeroBlock = new byte[blockSize]; // block of zeros + byte[] blockOut = new byte[blockSize]; + + int offset = 0; + // Process full blocks + while (offset + blockSize <= outLen) + { + ctrCipher.processBlock(zeroBlock, 0, blockOut, 0); + System.arraycopy(blockOut, 0, temp, offset, blockSize); + offset += blockSize; + } + // Process any remaining partial block. + if (offset < outLen) + { + ctrCipher.processBlock(zeroBlock, 0, blockOut, 0); + int remaining = outLen - offset; + System.arraycopy(blockOut, 0, temp, offset, remaining); + } + + // The number of vectors is the total limbs divided by mVecLimbs. + int numVectors = (p.getP1Limbs() + p.getP2Limbs()) / p.getMVecLimbs(); + + // Unpack the byte array 'temp' into the long array 'P' + // using our previously defined unpackMVecs method. + unpackMVecs(temp, 0, P, 0, numVectors, p.getM()); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/HashMLDSASigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/HashMLDSASigner.java new file mode 100644 index 0000000000..a7cdbce059 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/HashMLDSASigner.java @@ -0,0 +1,156 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.params.ParametersWithContext; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.DigestUtils; + +public class HashMLDSASigner + implements Signer +{ + private static final byte[] EMPTY_CONTEXT = new byte[0]; + + private MLDSAPublicKeyParameters pubKey; + private MLDSAPrivateKeyParameters privKey; + private SecureRandom random; + + private MLDSAEngine engine; + private Digest digest; + + public HashMLDSASigner() + { + } + + public void init(boolean forSigning, CipherParameters param) + { + byte[] ctx = EMPTY_CONTEXT; + if (param instanceof ParametersWithContext) + { + ParametersWithContext withContext = (ParametersWithContext)param; + ctx = withContext.getContext(); + param = withContext.getParameters(); + + if (ctx.length > 255) + { + throw new IllegalArgumentException("context too long"); + } + } + + MLDSAParameters parameters; + if (forSigning) + { + pubKey = null; + + if (param instanceof ParametersWithRandom) + { + ParametersWithRandom withRandom = (ParametersWithRandom)param; + privKey = (MLDSAPrivateKeyParameters)withRandom.getParameters(); + random = withRandom.getRandom(); + } + else + { + privKey = (MLDSAPrivateKeyParameters)param; + random = null; + } + + parameters = privKey.getParameters(); + engine = parameters.getEngine(random); + engine.initSign(privKey.tr, true, ctx); + } + else + { + pubKey = (MLDSAPublicKeyParameters)param; + privKey = null; + random = null; + parameters = pubKey.getParameters(); + engine = parameters.getEngine(null); + engine.initVerify(pubKey.rho, pubKey.t1, true, ctx); + } + digest = engine.shake256Digest; + byte[] digestOIDEncoding; + try + { + digestOIDEncoding = DigestUtils.getDigestOid(digest.getAlgorithmName()).getEncoded(ASN1Encoding.DER); + } + catch (IOException e) + { + throw new IllegalStateException("oid encoding failed: " + e.getMessage()); + } + digest.update(digestOIDEncoding, 0, digestOIDEncoding.length); + } + + public void update(byte b) + { + digest.update(b); + } + + public void update(byte[] in, int off, int len) + { + digest.update(in, off, len); + } + + public byte[] generateSignature() + throws CryptoException, DataLengthException + { + byte[] rnd = new byte[MLDSAEngine.RndBytes]; + if (random != null) + { + random.nextBytes(rnd); + } + byte[] mu = engine.generateMu(engine.shake256Digest); + return engine.generateSignature(mu, engine.getShake256Digest(), privKey.rho, privKey.k, privKey.t0, privKey.s1, privKey.s2, rnd); + } + + public boolean verifySignature(byte[] signature) + { + byte[] mu = engine.generateMu(engine.shake256Digest); + return engine.verifyInternalMuSignature(mu, signature, signature.length, engine.getShake256Digest(), pubKey.rho, pubKey.t1); + } + + /** + * reset the internal state + */ + public void reset() + { + digest.reset(); + } + +// TODO: these are probably no longer correct and also need to be marked as protected +// protected byte[] internalGenerateSignature(byte[] message, SecureRandom random) +// { +// MLDSAEngine engine = privKey.getParameters().getEngine(random); +// +// return engine.signInternal(message, message.length, privKey.rho, privKey.k, privKey.t0, privKey.s1, privKey.s2, random); +// } +// +// protected boolean internalVerifySignature(byte[] message, byte[] signature) +// { +// MLDSAEngine engine = pubKey.getParameters().getEngine(random); +// +// return engine.verifyInternal(signature, signature.length, message, message.length, pubKey.rho, pubKey.t1); +// } + +// private static Digest createDigest(MLDSAParameters parameters) +// { + //TODO: MLDSA44 may use SHA2-256, SHA3-256, SHAKE128 + // MLDSA65 may use SHA3-384, SHA2-512 + // MLDSA44/65/87 may use SHA2-512, SHA3-512, SHAKE256 + +// switch (parameters.getType()) +// { +// case MLDSAParameters.TYPE_PURE: +// case MLDSAParameters.TYPE_SHA2_512: +// return new SHAKEDigest(256); +// default: +// throw new IllegalArgumentException("unknown parameters type"); +// } +// } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAEngine.java new file mode 100644 index 0000000000..f016d90dbc --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAEngine.java @@ -0,0 +1,588 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.util.Arrays; + +class MLDSAEngine +{ + private final SecureRandom random; + final SHAKEDigest shake256Digest = new SHAKEDigest(256); + + public final static int DilithiumN = 256; + public final static int DilithiumQ = 8380417; + public final static int DilithiumQinv = 58728449; // q^(-1) mod 2^32 + public final static int DilithiumD = 13; + //public final static int DilithiumRootOfUnity = 1753; + public final static int SeedBytes = 32; + public final static int CrhBytes = 64; + public final static int RndBytes = 32; + public final static int TrBytes = 64; + + public final static int DilithiumPolyT1PackedBytes = 320; + public final static int DilithiumPolyT0PackedBytes = 416; + + private final int DilithiumPolyVecHPackedBytes; + + private final int DilithiumPolyZPackedBytes; + private final int DilithiumPolyW1PackedBytes; + private final int DilithiumPolyEtaPackedBytes; + + private final int DilithiumMode; + + private final int DilithiumK; + private final int DilithiumL; + private final int DilithiumEta; + private final int DilithiumTau; + private final int DilithiumBeta; + private final int DilithiumGamma1; + private final int DilithiumGamma2; + private final int DilithiumOmega; + private final int DilithiumCTilde; + + private final int CryptoPublicKeyBytes; + private final int CryptoSecretKeyBytes; + private final int CryptoBytes; + + private final int PolyUniformGamma1NBlocks; + + private final Symmetric symmetric; + + protected Symmetric GetSymmetric() + { + return symmetric; + } + +// int getDilithiumPolyVecHPackedBytes() +// { +// return DilithiumPolyVecHPackedBytes; +// } + + int getDilithiumPolyZPackedBytes() + { + return DilithiumPolyZPackedBytes; + } + + int getDilithiumPolyW1PackedBytes() + { + return DilithiumPolyW1PackedBytes; + } + + int getDilithiumPolyEtaPackedBytes() + { + return DilithiumPolyEtaPackedBytes; + } + +// int getDilithiumMode() +// { +// return DilithiumMode; +// } + + int getDilithiumK() + { + return DilithiumK; + } + + int getDilithiumL() + { + return DilithiumL; + } + + int getDilithiumEta() + { + return DilithiumEta; + } + + int getDilithiumTau() + { + return DilithiumTau; + } + + int getDilithiumBeta() + { + return DilithiumBeta; + } + + int getDilithiumGamma1() + { + return DilithiumGamma1; + } + + int getDilithiumGamma2() + { + return DilithiumGamma2; + } + + int getDilithiumOmega() + { + return DilithiumOmega; + } + + int getDilithiumCTilde() + { + return DilithiumCTilde; + } + + int getCryptoPublicKeyBytes() + { + return CryptoPublicKeyBytes; + } + +// int getCryptoSecretKeyBytes() +// { +// return CryptoSecretKeyBytes; +// } +// +// int getCryptoBytes() +// { +// return CryptoBytes; +// } + + int getPolyUniformGamma1NBlocks() + { + return this.PolyUniformGamma1NBlocks; + } + + MLDSAEngine(int mode, SecureRandom random) + { + this.DilithiumMode = mode; + switch (mode) + { + case 2: + this.DilithiumK = 4; + this.DilithiumL = 4; + this.DilithiumEta = 2; + this.DilithiumTau = 39; + this.DilithiumBeta = 78; + this.DilithiumGamma1 = (1 << 17); + this.DilithiumGamma2 = ((DilithiumQ - 1) / 88); + this.DilithiumOmega = 80; + this.DilithiumPolyZPackedBytes = 576; + this.DilithiumPolyW1PackedBytes = 192; + this.DilithiumPolyEtaPackedBytes = 96; + this.DilithiumCTilde = 32; + break; + case 3: + this.DilithiumK = 6; + this.DilithiumL = 5; + this.DilithiumEta = 4; + this.DilithiumTau = 49; + this.DilithiumBeta = 196; + this.DilithiumGamma1 = (1 << 19); + this.DilithiumGamma2 = ((DilithiumQ - 1) / 32); + this.DilithiumOmega = 55; + this.DilithiumPolyZPackedBytes = 640; + this.DilithiumPolyW1PackedBytes = 128; + this.DilithiumPolyEtaPackedBytes = 128; + this.DilithiumCTilde = 48; + break; + case 5: + this.DilithiumK = 8; + this.DilithiumL = 7; + this.DilithiumEta = 2; + this.DilithiumTau = 60; + this.DilithiumBeta = 120; + this.DilithiumGamma1 = (1 << 19); + this.DilithiumGamma2 = ((DilithiumQ - 1) / 32); + this.DilithiumOmega = 75; + this.DilithiumPolyZPackedBytes = 640; + this.DilithiumPolyW1PackedBytes = 128; + this.DilithiumPolyEtaPackedBytes = 96; + this.DilithiumCTilde = 64; + break; + default: + throw new IllegalArgumentException("The mode " + mode + "is not supported by Crystals Dilithium!"); + } + + this.symmetric = new Symmetric.ShakeSymmetric(); + + this.random = random; + this.DilithiumPolyVecHPackedBytes = this.DilithiumOmega + this.DilithiumK; + this.CryptoPublicKeyBytes = SeedBytes + this.DilithiumK * DilithiumPolyT1PackedBytes; + this.CryptoSecretKeyBytes = + ( + 2 * SeedBytes + + TrBytes + + DilithiumL * this.DilithiumPolyEtaPackedBytes + + DilithiumK * this.DilithiumPolyEtaPackedBytes + + DilithiumK * DilithiumPolyT0PackedBytes + ); + this.CryptoBytes = DilithiumCTilde + DilithiumL * this.DilithiumPolyZPackedBytes + this.DilithiumPolyVecHPackedBytes; + + if (this.DilithiumGamma1 == (1 << 17)) + { + this.PolyUniformGamma1NBlocks = ((576 + symmetric.stream256BlockBytes - 1) / symmetric.stream256BlockBytes); + } + else if (this.DilithiumGamma1 == (1 << 19)) + { + this.PolyUniformGamma1NBlocks = ((640 + symmetric.stream256BlockBytes - 1) / symmetric.stream256BlockBytes); + } + else + { + throw new RuntimeException("Wrong Dilithium Gamma1!"); + } + } + + //Internal functions are deterministic. No randomness is sampled inside them + byte[][] generateKeyPairInternal(byte[] seed) + { + byte[] buf = new byte[2 * SeedBytes + CrhBytes]; + byte[] tr = new byte[TrBytes]; + + byte[] rho = new byte[SeedBytes], + rhoPrime = new byte[CrhBytes], + key = new byte[SeedBytes]; + + PolyVecMatrix aMatrix = new PolyVecMatrix(this); + + PolyVecL s1 = new PolyVecL(this), s1hat; + PolyVecK s2 = new PolyVecK(this), t1 = new PolyVecK(this), t0 = new PolyVecK(this); + + + shake256Digest.update(seed, 0, SeedBytes); + + //Domain separation + shake256Digest.update((byte)DilithiumK); + shake256Digest.update((byte)DilithiumL); + + shake256Digest.doFinal(buf, 0, 2 * SeedBytes + CrhBytes); + // System.out.print("buf = "); + // Helper.printByteArray(buf); + + System.arraycopy(buf, 0, rho, 0, SeedBytes); + System.arraycopy(buf, SeedBytes, rhoPrime, 0, CrhBytes); + System.arraycopy(buf, SeedBytes + CrhBytes, key, 0, SeedBytes); + // System.out.println("key = "); + // Helper.printByteArray(key); + + aMatrix.expandMatrix(rho); + // System.out.print(aMatrix.toString("aMatrix")); + + // System.out.println("rhoPrime = "); + // Helper.printByteArray(rhoPrime); + s1.uniformEta(rhoPrime, (short)0); + // System.out.println(s1.toString("s1")); + + s2.uniformEta(rhoPrime, (short)DilithiumL); + + s1hat = new PolyVecL(this); + + s1.copyTo(s1hat); + s1hat.polyVecNtt(); + + // System.out.println(s1hat.toString("s1hat")); + + aMatrix.pointwiseMontgomery(t1, s1hat); + // System.out.println(t1.toString("t1")); + + t1.reduce(); + t1.invNttToMont(); + + t1.addPolyVecK(s2); + // System.out.println(s2.toString("s2")); + // System.out.println(t1.toString("t1")); + t1.conditionalAddQ(); + t1.power2Round(t0); + + // System.out.println(t1.toString("t1")); + // System.out.println(t0.toString("t0")); + + + byte[] encT1 = Packing.packPublicKey(t1, this); + // System.out.println("pk engine = "); + // Helper.printByteArray(pk); + + shake256Digest.update(rho, 0, rho.length); + shake256Digest.update(encT1, 0, encT1.length); + shake256Digest.doFinal(tr, 0, TrBytes); + + byte[][] sk = Packing.packSecretKey(rho, tr, key, t0, s1, s2, this); + + return new byte[][]{sk[0], sk[1], sk[2], sk[3], sk[4], sk[5], encT1, seed}; + } + + byte[] deriveT1(byte[] rho, byte[] key, byte[] tr, byte[] s1Enc, byte[] s2Enc, byte[] t0Enc) + { + PolyVecMatrix aMatrix = new PolyVecMatrix(this); + + PolyVecL s1 = new PolyVecL(this), s1hat; + PolyVecK s2 = new PolyVecK(this), t1 = new PolyVecK(this), t0 = new PolyVecK(this); + + Packing.unpackSecretKey(t0, s1, s2, t0Enc, s1Enc, s2Enc, this); + + // System.out.print("rho = "); + // Helper.printByteArray(rho); + + // System.out.println("key = "); + // Helper.printByteArray(key); + + aMatrix.expandMatrix(rho); + // System.out.print(aMatrix.toString("aMatrix")); + + s1hat = new PolyVecL(this); + + s1.copyTo(s1hat); + s1hat.polyVecNtt(); + + // System.out.println(s1hat.toString("s1hat")); + + aMatrix.pointwiseMontgomery(t1, s1hat); + // System.out.println(t1.toString("t1")); + + t1.reduce(); + t1.invNttToMont(); + + t1.addPolyVecK(s2); + // System.out.println(s2.toString("s2")); + // System.out.println(t1.toString("t1")); + t1.conditionalAddQ(); + t1.power2Round(t0); + + // System.out.println(t1.toString("t1")); + // System.out.println(t0.toString("t0")); + + byte[] encT1 = Packing.packPublicKey(t1, this); + // System.out.println("enc t1 = "); + // Helper.printByteArray(encT1); + return encT1; + } + + SHAKEDigest getShake256Digest() + { + return new SHAKEDigest(shake256Digest); + } + + void initSign(byte[] tr, boolean isPreHash, byte[] ctx) + { + shake256Digest.update(tr, 0, TrBytes); + absorbCtx(isPreHash, ctx); + } + + void initVerify(byte[] rho, byte[] encT1, boolean isPreHash, byte[] ctx) + { + byte[] mu = new byte[TrBytes]; + + shake256Digest.update(rho, 0, rho.length); + shake256Digest.update(encT1, 0, encT1.length); + shake256Digest.doFinal(mu, 0, TrBytes); + + shake256Digest.update(mu, 0, TrBytes); + absorbCtx(isPreHash, ctx); + } + + void absorbCtx(boolean isPreHash, byte[] ctx) + { + if (ctx != null) + { + shake256Digest.update(isPreHash ? (byte)1 : (byte)0); + shake256Digest.update((byte)ctx.length); + shake256Digest.update(ctx, 0, ctx.length); + } + } + + byte[] signInternal(byte[] msg, int msglen, byte[] rho, byte[] key, byte[] t0Enc, byte[] s1Enc, byte[] s2Enc, byte[] rnd) + { + SHAKEDigest shake256 = new SHAKEDigest(shake256Digest); + + shake256.update(msg, 0, msglen); + + return generateSignature(generateMu(shake256), shake256, rho, key, t0Enc, s1Enc, s2Enc, rnd); + } + + byte[] generateMu(SHAKEDigest shake256Digest) + { + byte[] mu = new byte[CrhBytes]; + + shake256Digest.doFinal(mu, 0, CrhBytes); + return mu; + } + + byte[] generateSignature(byte[] mu, SHAKEDigest shake256Digest, byte[] rho, byte[] key, byte[] t0Enc, byte[] s1Enc, byte[] s2Enc, byte[] rnd) + { + byte[] outSig = new byte[CryptoBytes]; + byte[] rhoPrime = new byte[CrhBytes]; + short nonce = 0; + PolyVecL s1 = new PolyVecL(this), y = new PolyVecL(this), z = new PolyVecL(this); + PolyVecK t0 = new PolyVecK(this), s2 = new PolyVecK(this), w1 = new PolyVecK(this), w0 = new PolyVecK(this), h = new PolyVecK(this); + Poly cp = new Poly(this); + PolyVecMatrix aMatrix = new PolyVecMatrix(this); + + Packing.unpackSecretKey(t0, s1, s2, t0Enc, s1Enc, s2Enc, this); + + byte[] keyMu = Arrays.copyOf(key, SeedBytes + RndBytes + CrhBytes); + System.arraycopy(rnd, 0, keyMu, SeedBytes, RndBytes); + System.arraycopy(mu, 0, keyMu, SeedBytes + RndBytes, CrhBytes); + shake256Digest.update(keyMu, 0, SeedBytes + RndBytes + CrhBytes); + shake256Digest.doFinal(rhoPrime, 0, CrhBytes); + + aMatrix.expandMatrix(rho); + + s1.polyVecNtt(); + s2.polyVecNtt(); + + t0.polyVecNtt(); + + int count = 0; + while (count < 1000) + { + count++; + // Sample intermediate vector + y.uniformGamma1(rhoPrime, nonce++); + + y.copyTo(z); + z.polyVecNtt(); + + // Matrix-vector multiplication + aMatrix.pointwiseMontgomery(w1, z); + w1.reduce(); + w1.invNttToMont(); + + // Decompose w and call the random oracle + w1.conditionalAddQ(); + w1.decompose(w0); + + w1.packW1(this, outSig, 0); + + shake256Digest.update(mu, 0, CrhBytes); + shake256Digest.update(outSig, 0, DilithiumK * DilithiumPolyW1PackedBytes); + shake256Digest.doFinal(outSig, 0, DilithiumCTilde); + + cp.challenge(outSig, 0, DilithiumCTilde); + cp.polyNtt(); + + // Compute z, reject if it reveals secret + z.pointwisePolyMontgomery(cp, s1); + z.invNttToMont(); + z.addPolyVecL(y); + z.reduce(); + if (z.checkNorm(DilithiumGamma1 - DilithiumBeta)) + { + continue; + } + + h.pointwisePolyMontgomery(cp, s2); + h.invNttToMont(); + w0.subtract(h); + w0.reduce(); + if (w0.checkNorm(DilithiumGamma2 - DilithiumBeta)) + { + continue; + } + + h.pointwisePolyMontgomery(cp, t0); + h.invNttToMont(); + h.reduce(); + if (h.checkNorm(DilithiumGamma2)) + { + continue; + } + + w0.addPolyVecK(h); + w0.conditionalAddQ(); + int n = h.makeHint(w0, w1); + if (n > DilithiumOmega) + { + continue; + } + + Packing.packSignature(outSig, z, h, this); + return outSig; + } + + // TODO[pqc] Shouldn't this throw an exception here (or in caller)? + return null; + } + + boolean verifyInternalMu(byte[] providedMu) + { + byte[] mu = new byte[CrhBytes]; + + shake256Digest.doFinal(mu, 0); + + return Arrays.constantTimeAreEqual(mu, providedMu); + } + + boolean verifyInternalMuSignature(byte[] mu, byte[] sig, int siglen, SHAKEDigest shake256Digest, byte[] rho, byte[] encT1) + { + byte[] buf = new byte[Math.max(CrhBytes + DilithiumK * DilithiumPolyW1PackedBytes, DilithiumCTilde)]; + + // Mu + System.arraycopy(mu, 0, buf, 0, mu.length); + + return doVerifyInternal(buf, sig, siglen, shake256Digest, rho, encT1); + } + + boolean verifyInternal(byte[] sig, int siglen, SHAKEDigest shake256Digest, byte[] rho, byte[] encT1) + { + byte[] buf = new byte[Math.max(CrhBytes + DilithiumK * DilithiumPolyW1PackedBytes, DilithiumCTilde)]; + + // Mu + shake256Digest.doFinal(buf, 0); + + return doVerifyInternal(buf, sig, siglen, shake256Digest, rho, encT1); + } + + private boolean doVerifyInternal(byte[] buf, byte[] sig, int siglen, SHAKEDigest shake256Digest, byte[] rho, byte[] encT1) + { + if (siglen != CryptoBytes) + { + return false; + } + + PolyVecK h = new PolyVecK(this); + PolyVecL z = new PolyVecL(this); + + if (!Packing.unpackSignature(z, h, sig, this)) + { + return false; + } + + if (z.checkNorm(getDilithiumGamma1() - getDilithiumBeta())) + { + return false; + } + + Poly cp = new Poly(this); + PolyVecMatrix aMatrix = new PolyVecMatrix(this); + PolyVecK t1 = new PolyVecK(this), w1 = new PolyVecK(this); + + t1 = Packing.unpackPublicKey(t1, encT1, this); + + // Matrix-vector multiplication; compute Az - c2^dt1 + cp.challenge(sig, 0, DilithiumCTilde); + + aMatrix.expandMatrix(rho); + + z.polyVecNtt(); + aMatrix.pointwiseMontgomery(w1, z); + + cp.polyNtt(); + + t1.shiftLeft(); + t1.polyVecNtt(); + t1.pointwisePolyMontgomery(cp, t1); + + w1.subtract(t1); + w1.reduce(); + w1.invNttToMont(); + + w1.conditionalAddQ(); + w1.useHint(w1, h); + + w1.packW1(this, buf, CrhBytes); + + shake256Digest.update(buf, 0, CrhBytes + DilithiumK * DilithiumPolyW1PackedBytes); + shake256Digest.doFinal(buf, 0, DilithiumCTilde); + + return Arrays.constantTimeAreEqual(DilithiumCTilde, sig, 0, buf, 0); + } + + byte[][] generateKeyPair() + { + byte[] seedBuf = new byte[SeedBytes]; + random.nextBytes(seedBuf); + return generateKeyPairInternal(seedBuf); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyGenerationParameters.java new file mode 100644 index 0000000000..affee92b3e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyGenerationParameters.java @@ -0,0 +1,24 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class MLDSAKeyGenerationParameters + extends KeyGenerationParameters +{ + private final MLDSAParameters params; + + public MLDSAKeyGenerationParameters( + SecureRandom random, + MLDSAParameters mldsaParameters) + { + super(random, 256); + this.params = mldsaParameters; + } + + public MLDSAParameters getParameters() + { + return params; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyPairGenerator.java new file mode 100644 index 0000000000..b0e3069c39 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyPairGenerator.java @@ -0,0 +1,31 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class MLDSAKeyPairGenerator + implements AsymmetricCipherKeyPairGenerator +{ + private MLDSAParameters parameters; + private SecureRandom random; + + public void init(KeyGenerationParameters param) + { + this.parameters = ((MLDSAKeyGenerationParameters)param).getParameters(); + this.random = param.getRandom(); + } + + public AsymmetricCipherKeyPair generateKeyPair() + { + MLDSAEngine engine = parameters.getEngine(random); + + byte[][] keyPair = engine.generateKeyPair(); + MLDSAPublicKeyParameters pubKey = new MLDSAPublicKeyParameters(parameters, keyPair[0], keyPair[6]); + MLDSAPrivateKeyParameters privKey = new MLDSAPrivateKeyParameters(parameters, keyPair[0], keyPair[1], keyPair[2], keyPair[3], keyPair[4], keyPair[5], keyPair[6], keyPair[7]); + + return new AsymmetricCipherKeyPair(pubKey, privKey); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyParameters.java new file mode 100644 index 0000000000..ab1c630e1f --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAKeyParameters.java @@ -0,0 +1,22 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; + +public class MLDSAKeyParameters + extends AsymmetricKeyParameter +{ + private final MLDSAParameters params; + + public MLDSAKeyParameters( + boolean isPrivate, + MLDSAParameters params) + { + super(isPrivate); + this.params = params; + } + + public MLDSAParameters getParameters() + { + return params; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAParameters.java new file mode 100644 index 0000000000..6896fd05b2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAParameters.java @@ -0,0 +1,48 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import java.security.SecureRandom; + +public class MLDSAParameters +{ + public static final int TYPE_PURE = 0; + public static final int TYPE_SHA2_512 = 1; + + public static final MLDSAParameters ml_dsa_44 = new MLDSAParameters("ml-dsa-44", 2, TYPE_PURE); + public static final MLDSAParameters ml_dsa_65 = new MLDSAParameters("ml-dsa-65", 3, TYPE_PURE); + public static final MLDSAParameters ml_dsa_87 = new MLDSAParameters("ml-dsa-87", 5, TYPE_PURE); + + public static final MLDSAParameters ml_dsa_44_with_sha512 = new MLDSAParameters("ml-dsa-44-with-sha512", 2, TYPE_SHA2_512); + public static final MLDSAParameters ml_dsa_65_with_sha512 = new MLDSAParameters("ml-dsa-65-with-sha512", 3, TYPE_SHA2_512); + public static final MLDSAParameters ml_dsa_87_with_sha512 = new MLDSAParameters("ml-dsa-87-with-sha512", 5, TYPE_SHA2_512); + + private final int k; + private final String name; + private final int preHashDigest; + + private MLDSAParameters(String name, int k, int preHashDigest) + { + this.name = name; + this.k = k; + this.preHashDigest = preHashDigest; + } + + public boolean isPreHash() + { + return preHashDigest != TYPE_PURE; + } + + public int getType() + { + return preHashDigest; + } + + MLDSAEngine getEngine(SecureRandom random) + { + return new MLDSAEngine(k, random); + } + + public String getName() + { + return name; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAPrivateKeyParameters.java new file mode 100644 index 0000000000..3fe15f5739 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAPrivateKeyParameters.java @@ -0,0 +1,213 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.util.Arrays; + +public class MLDSAPrivateKeyParameters + extends MLDSAKeyParameters +{ + public static final int BOTH = 0; + public static final int SEED_ONLY = 1; + public static final int EXPANDED_KEY = 2; + + final byte[] rho; + final byte[] k; + final byte[] tr; + final byte[] s1; + final byte[] s2; + final byte[] t0; + + private final byte[] t1; + private final byte[] seed; + + private final int prefFormat; + + public MLDSAPrivateKeyParameters(MLDSAParameters params, byte[] encoding) + { + this(params, encoding, null); + } + + public MLDSAPrivateKeyParameters(MLDSAParameters params, byte[] rho, byte[] K, byte[] tr, byte[] s1, byte[] s2, byte[] t0, byte[] t1) + { + this(params, rho, K, tr, s1, s2, t0, t1, null); + } + + public MLDSAPrivateKeyParameters(MLDSAParameters params, byte[] rho, byte[] K, byte[] tr, byte[] s1, byte[] s2, byte[] t0, byte[] t1, byte[] seed) + { + super(true, params); + this.rho = Arrays.clone(rho); + this.k = Arrays.clone(K); + this.tr = Arrays.clone(tr); + this.s1 = Arrays.clone(s1); + this.s2 = Arrays.clone(s2); + this.t0 = Arrays.clone(t0); + this.t1 = Arrays.clone(t1); + this.seed = Arrays.clone(seed); + this.prefFormat = (seed != null) ? BOTH : EXPANDED_KEY; + } + + public MLDSAPrivateKeyParameters(MLDSAParameters params, byte[] encoding, MLDSAPublicKeyParameters pubKey) + { + super(true, params); + + MLDSAEngine eng = params.getEngine(null); + if (encoding.length == MLDSAEngine.SeedBytes) + { + byte[][] keyDetails = eng.generateKeyPairInternal(encoding); + + this.rho = keyDetails[0]; + this.k = keyDetails[1]; + this.tr = keyDetails[2]; + this.s1 = keyDetails[3]; + this.s2 = keyDetails[4]; + this.t0 = keyDetails[5]; + this.t1 = keyDetails[6]; + this.seed = keyDetails[7]; + } + else + { + int index = 0; + this.rho = Arrays.copyOfRange(encoding, 0, MLDSAEngine.SeedBytes); + index += MLDSAEngine.SeedBytes; + this.k = Arrays.copyOfRange(encoding, index, index + MLDSAEngine.SeedBytes); + index += MLDSAEngine.SeedBytes; + this.tr = Arrays.copyOfRange(encoding, index, index + MLDSAEngine.TrBytes); + index += MLDSAEngine.TrBytes; + int delta = eng.getDilithiumL() * eng.getDilithiumPolyEtaPackedBytes(); + this.s1 = Arrays.copyOfRange(encoding, index, index + delta); + index += delta; + delta = eng.getDilithiumK() * eng.getDilithiumPolyEtaPackedBytes(); + this.s2 = Arrays.copyOfRange(encoding, index, index + delta); + index += delta; + delta = eng.getDilithiumK() * MLDSAEngine.DilithiumPolyT0PackedBytes; + this.t0 = Arrays.copyOfRange(encoding, index, index + delta); + index += delta; + this.t1 = eng.deriveT1(rho, k, tr, s1, s2, t0); + this.seed = null; + } + + if (pubKey != null) + { + if (!Arrays.constantTimeAreEqual(this.t1, pubKey.getT1())) + { + throw new IllegalArgumentException("passed in public key does not match private values"); + } + } + + this.prefFormat = (seed != null) ? BOTH : EXPANDED_KEY; + } + + private MLDSAPrivateKeyParameters(MLDSAPrivateKeyParameters params, int preferredFormat) + { + super(true, params.getParameters()); + + this.rho = params.rho; + this.k = params.k; + this.tr = params.tr; + this.s1 = params.s1; + this.s2 = params.s2; + this.t0 = params.t0; + this.t1 = params.t1; + this.seed = params.seed; + this.prefFormat = preferredFormat; + } + + public MLDSAPrivateKeyParameters getParametersWithFormat(int format) + { + if (this.prefFormat == format) + { + return this; + } + + switch (format) + { + case BOTH: + case SEED_ONLY: + { + if (this.seed == null) + { + throw new IllegalStateException("no seed available"); + } + break; + } + case EXPANDED_KEY: + break; + default: + throw new IllegalArgumentException("unknown format"); + } + + return new MLDSAPrivateKeyParameters(this, format); + } + + public int getPreferredFormat() + { + return prefFormat; + } + + public byte[] getEncoded() + { + return Arrays.concatenate(new byte[][]{rho, k, tr, s1, s2, t0}); + } + + public byte[] getK() + { + return Arrays.clone(k); + } + + /** + * @deprecated Use {@link #getEncoded()} instead. + */ + public byte[] getPrivateKey() + { + return getEncoded(); + } + + public byte[] getPublicKey() + { + return MLDSAPublicKeyParameters.getEncoded(rho, t1); + } + + public byte[] getSeed() + { + return Arrays.clone(seed); + } + + public MLDSAPublicKeyParameters getPublicKeyParameters() + { + if (this.t1 == null) + { + return null; + } + + return new MLDSAPublicKeyParameters(getParameters(), rho, t1); + } + + public byte[] getRho() + { + return Arrays.clone(rho); + } + + public byte[] getS1() + { + return Arrays.clone(s1); + } + + public byte[] getS2() + { + return Arrays.clone(s2); + } + + public byte[] getT0() + { + return Arrays.clone(t0); + } + + public byte[] getT1() + { + return Arrays.clone(t1); + } + + public byte[] getTr() + { + return Arrays.clone(tr); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAPublicKeyParameters.java new file mode 100644 index 0000000000..f4aad99cb5 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSAPublicKeyParameters.java @@ -0,0 +1,56 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.util.Arrays; + +public class MLDSAPublicKeyParameters + extends MLDSAKeyParameters +{ + static byte[] getEncoded(byte[] rho, byte[] t1) + { + return Arrays.concatenate(rho, t1); + } + + final byte[] rho; + final byte[] t1; + + public MLDSAPublicKeyParameters(MLDSAParameters params, byte[] encoding) + { + super(false, params); + this.rho = Arrays.copyOfRange(encoding, 0, MLDSAEngine.SeedBytes); + this.t1 = Arrays.copyOfRange(encoding, MLDSAEngine.SeedBytes, encoding.length); + if (t1.length == 0) + { + throw new IllegalArgumentException("encoding too short"); + } + } + + public MLDSAPublicKeyParameters(MLDSAParameters params, byte[] rho, byte[] t1) + { + super(false, params); + if (rho == null) + { + throw new NullPointerException("rho cannot be null"); + } + if (t1 == null) + { + throw new NullPointerException("t1 cannot be null"); + } + this.rho = Arrays.clone(rho); + this.t1 = Arrays.clone(t1); + } + + public byte[] getEncoded() + { + return getEncoded(rho, t1); + } + + public byte[] getRho() + { + return Arrays.clone(rho); + } + + public byte[] getT1() + { + return Arrays.clone(t1); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSASigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSASigner.java new file mode 100644 index 0000000000..521a9aede2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/MLDSASigner.java @@ -0,0 +1,208 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.params.ParametersWithContext; +import org.bouncycastle.crypto.params.ParametersWithRandom; + +public class MLDSASigner + implements Signer +{ + private static final byte[] EMPTY_CONTEXT = new byte[0]; + private MLDSAPublicKeyParameters pubKey; + private MLDSAPrivateKeyParameters privKey; + private SecureRandom random; + private MLDSAEngine engine; + private SHAKEDigest msgDigest; + + public MLDSASigner() + { + } + + public void init(boolean forSigning, CipherParameters param) + { + byte[] ctx = EMPTY_CONTEXT; + if (param instanceof ParametersWithContext) + { + ParametersWithContext withContext = (ParametersWithContext)param; + ctx = withContext.getContext(); + param = withContext.getParameters(); + + if (ctx.length > 255) + { + throw new IllegalArgumentException("context too long"); + } + } + + MLDSAParameters parameters; + if (forSigning) + { + pubKey = null; + + if (param instanceof ParametersWithRandom) + { + ParametersWithRandom withRandom = (ParametersWithRandom)param; + privKey = (MLDSAPrivateKeyParameters)withRandom.getParameters(); + random = withRandom.getRandom(); + } + else + { + privKey = (MLDSAPrivateKeyParameters)param; + random = null; + } + + parameters = privKey.getParameters(); + engine = parameters.getEngine(random); + + engine.initSign(privKey.tr, false, ctx); + } + else + { + pubKey = (MLDSAPublicKeyParameters)param; + privKey = null; + random = null; + + parameters = pubKey.getParameters(); + engine = parameters.getEngine(null); + + engine.initVerify(pubKey.rho, pubKey.t1, false, ctx); + } + + if (parameters.isPreHash()) + { + throw new IllegalArgumentException("\"pure\" ml-dsa must use non pre-hash parameters"); + } + + reset(); + } + + public void update(byte b) + { + msgDigest.update(b); + } + + public void update(byte[] in, int off, int len) + { + msgDigest.update(in, off, len); + } + + public byte[] generateMu() + throws CryptoException, DataLengthException + { + byte[] mu = engine.generateMu(msgDigest); + + reset(); + + return mu; + } + + public byte[] generateMuSignature(byte[] mu) + throws CryptoException, DataLengthException + { + if (mu.length != MLDSAEngine.CrhBytes) + { + throw new DataLengthException("mu value must be " + MLDSAEngine.CrhBytes + " bytes"); + } + byte[] rnd = new byte[MLDSAEngine.RndBytes]; + if (random != null) + { + random.nextBytes(rnd); + } + + msgDigest.reset(); + + byte[] sig = engine.generateSignature(mu, msgDigest, privKey.rho, privKey.k, privKey.t0, privKey.s1, privKey.s2, rnd); + + reset(); + + return sig; + } + + public byte[] generateSignature() + throws CryptoException, DataLengthException + { + byte[] rnd = new byte[MLDSAEngine.RndBytes]; + if (random != null) + { + random.nextBytes(rnd); + } + + byte[] mu = engine.generateMu(msgDigest); + byte[] sig = engine.generateSignature(mu, msgDigest, privKey.rho, privKey.k, privKey.t0, privKey.s1, privKey.s2, rnd); + + reset(); + + return sig; + } + + public boolean verifyMu(byte[] mu) + { + if (mu.length != MLDSAEngine.CrhBytes) + { + throw new DataLengthException("mu value must be " + MLDSAEngine.CrhBytes + " bytes"); + } + + boolean isTrue = engine.verifyInternalMu(mu); + + reset(); + + return isTrue; + } + + public boolean verifySignature(byte[] signature) + { + boolean isTrue = engine.verifyInternal(signature, signature.length, msgDigest, pubKey.rho, pubKey.t1); + + reset(); + + return isTrue; + } + + public boolean verifyMuSignature(byte[] mu, byte[] signature) + { + if (mu.length != MLDSAEngine.CrhBytes) + { + throw new DataLengthException("mu value must be " + MLDSAEngine.CrhBytes + " bytes"); + } + + msgDigest.reset(); + + boolean isTrue = engine.verifyInternalMuSignature(mu, signature, signature.length, msgDigest, pubKey.rho, pubKey.t1); + + reset(); + + return isTrue; + } + + public void reset() + { + msgDigest = engine.getShake256Digest(); + } + + protected byte[] internalGenerateSignature(byte[] message, byte[] random) + { + MLDSAEngine engine = privKey.getParameters().getEngine(this.random); + + engine.initSign(privKey.tr, false, null); + + return engine.signInternal(message, message.length, privKey.rho, privKey.k, privKey.t0, privKey.s1, privKey.s2, random); + } + + protected boolean internalVerifySignature(byte[] message, byte[] signature) + { + MLDSAEngine engine = pubKey.getParameters().getEngine(random); + + engine.initVerify(pubKey.rho, pubKey.t1, false, null); + + SHAKEDigest msgDigest = engine.getShake256Digest(); + + msgDigest.update(message, 0, message.length); + + return engine.verifyInternal(signature, signature.length, msgDigest, pubKey.rho, pubKey.t1); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Ntt.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Ntt.java new file mode 100644 index 0000000000..6af28663df --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Ntt.java @@ -0,0 +1,98 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.util.Arrays; + +class Ntt +{ + static final int[] nttZetas = { + 0, 25847, -2608894, -518909, 237124, -777960, -876248, 466468, + 1826347, 2353451, -359251, -2091905, 3119733, -2884855, 3111497, 2680103, + 2725464, 1024112, -1079900, 3585928, -549488, -1119584, 2619752, -2108549, + -2118186, -3859737, -1399561, -3277672, 1757237, -19422, 4010497, 280005, + 2706023, 95776, 3077325, 3530437, -1661693, -3592148, -2537516, 3915439, + -3861115, -3043716, 3574422, -2867647, 3539968, -300467, 2348700, -539299, + -1699267, -1643818, 3505694, -3821735, 3507263, -2140649, -1600420, 3699596, + 811944, 531354, 954230, 3881043, 3900724, -2556880, 2071892, -2797779, + -3930395, -1528703, -3677745, -3041255, -1452451, 3475950, 2176455, -1585221, + -1257611, 1939314, -4083598, -1000202, -3190144, -3157330, -3632928, 126922, + 3412210, -983419, 2147896, 2715295, -2967645, -3693493, -411027, -2477047, + -671102, -1228525, -22981, -1308169, -381987, 1349076, 1852771, -1430430, + -3343383, 264944, 508951, 3097992, 44288, -1100098, 904516, 3958618, + -3724342, -8578, 1653064, -3249728, 2389356, -210977, 759969, -1316856, + 189548, -3553272, 3159746, -1851402, -2409325, -177440, 1315589, 1341330, + 1285669, -1584928, -812732, -1439742, -3019102, -3881060, -3628969, 3839961, + 2091667, 3407706, 2316500, 3817976, -3342478, 2244091, -2446433, -3562462, + 266997, 2434439, -1235728, 3513181, -3520352, -3759364, -1197226, -3193378, + 900702, 1859098, 909542, 819034, 495491, -1613174, -43260, -522500, + -655327, -3122442, 2031748, 3207046, -3556995, -525098, -768622, -3595838, + 342297, 286988, -2437823, 4108315, 3437287, -3342277, 1735879, 203044, + 2842341, 2691481, -2590150, 1265009, 4055324, 1247620, 2486353, 1595974, + -3767016, 1250494, 2635921, -3548272, -2994039, 1869119, 1903435, -1050970, + -1333058, 1237275, -3318210, -1430225, -451100, 1312455, 3306115, -1962642, + -1279661, 1917081, -2546312, -1374803, 1500165, 777191, 2235880, 3406031, + -542412, -2831860, -1671176, -1846953, -2584293, -3724270, 594136, -3776993, + -2013608, 2432395, 2454455, -164721, 1957272, 3369112, 185531, -1207385, + -3183426, 162844, 1616392, 3014001, 810149, 1652634, -3694233, -1799107, + -3038916, 3523897, 3866901, 269760, 2213111, -975884, 1717735, 472078, + -426683, 1723600, -1803090, 1910376, -1667432, -1104333, -260646, -3833893, + -2939036, -2235985, -420899, -2286327, 183443, -976891, 1612842, -3545687, + -554416, 3919660, -48306, -1362209, 3937738, 1400424, -846154, 1976782 + }; + + static int[] ntt(int[] a) + { + int[] r = Arrays.copyOfRange(a, 0, a.length); + + int len, start, j, k; + int zeta, t; + + k = 0; + for (len = 128; len > 0; len >>>= 1) + { + for (start = 0; start < MLDSAEngine.DilithiumN; start = j + len) + { + zeta = nttZetas[++k]; + for (j = start; j < start + len; ++j) + { + t = Reduce.montgomeryReduce(((long)zeta * (long)r[j + len])); + r[j + len] = r[j] - t; + r[j] = r[j] + t; + } + } + } + return r; + } + + + static int[] invNttToMont(int[] a) + { + int start, len, j, k; + int t, zeta; + final int f = 41978; // (mont^2)/256 + + int[] out = Arrays.copyOfRange(a, 0, a.length); + + k = 256; + for (len = 1; len < MLDSAEngine.DilithiumN; len <<= 1) + { + for (start = 0; start < MLDSAEngine.DilithiumN; start = j + len) + { + zeta = (-1) * nttZetas[--k]; + for (j = start; j < start + len; ++j) + { + t = out[j]; + out[j] = t + out[j + len]; + out[j + len] = t - out[j + len]; + out[j + len] = Reduce.montgomeryReduce((long)((long)zeta * (long)out[j + len])); + } + } + } + + for (j = 0; j < MLDSAEngine.DilithiumN; ++j) + { + out[j] = Reduce.montgomeryReduce((long)((long)f * (long)out[j])); + } + return out; + } +} + diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Packing.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Packing.java new file mode 100644 index 0000000000..c577fea200 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Packing.java @@ -0,0 +1,154 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.util.Arrays; + +class Packing +{ + static byte[] packPublicKey(PolyVecK t1, MLDSAEngine engine) + { + byte[] out = new byte[engine.getCryptoPublicKeyBytes() - MLDSAEngine.SeedBytes]; + + for (int i = 0; i < engine.getDilithiumK(); ++i) + { + System.arraycopy(t1.getVectorIndex(i).polyt1Pack(), 0, out, i * MLDSAEngine.DilithiumPolyT1PackedBytes, MLDSAEngine.DilithiumPolyT1PackedBytes); + } + return out; + } + + static PolyVecK unpackPublicKey(PolyVecK t1, byte[] publicKey, MLDSAEngine engine) + { + int i; + + for (i = 0; i < engine.getDilithiumK(); ++i) + { + t1.getVectorIndex(i).polyt1Unpack(Arrays.copyOfRange(publicKey, i * MLDSAEngine.DilithiumPolyT1PackedBytes, (i + 1) * MLDSAEngine.DilithiumPolyT1PackedBytes)); + } + return t1; + } + + static byte[][] packSecretKey(byte[] rho, byte[] tr, byte[] key, PolyVecK t0, PolyVecL s1, PolyVecK s2, MLDSAEngine engine) + { + byte[][] out = new byte[6][]; + + out[0] = rho; + out[1] = key; + out[2] = tr; + + out[3] = new byte[engine.getDilithiumL() * engine.getDilithiumPolyEtaPackedBytes()]; + for (int i = 0; i < engine.getDilithiumL(); ++i) + { + s1.getVectorIndex(i).polyEtaPack(out[3], i * engine.getDilithiumPolyEtaPackedBytes()); + } + + out[4] = new byte[engine.getDilithiumK() * engine.getDilithiumPolyEtaPackedBytes()]; + for (int i = 0; i < engine.getDilithiumK(); ++i) + { + s2.getVectorIndex(i).polyEtaPack(out[4], i * engine.getDilithiumPolyEtaPackedBytes()); + } + + out[5] = new byte[engine.getDilithiumK() * MLDSAEngine.DilithiumPolyT0PackedBytes]; + for (int i = 0; i < engine.getDilithiumK(); ++i) + { + t0.getVectorIndex(i).polyt0Pack(out[5], i * MLDSAEngine.DilithiumPolyT0PackedBytes); + } + return out; + } + + /** + * @param t0 + * @param s1 + * @param s2 + * @param engine + * @return Byte matrix where byte[0] = rho, byte[1] = tr, byte[2] = key + */ + static void unpackSecretKey(PolyVecK t0, PolyVecL s1, PolyVecK s2, byte[] t0Enc, byte[] s1Enc, byte[] s2Enc, MLDSAEngine engine) + { + for (int i = 0; i < engine.getDilithiumL(); ++i) + { + s1.getVectorIndex(i).polyEtaUnpack(s1Enc, i * engine.getDilithiumPolyEtaPackedBytes()); + } + + for (int i = 0; i < engine.getDilithiumK(); ++i) + { + s2.getVectorIndex(i).polyEtaUnpack(s2Enc, i * engine.getDilithiumPolyEtaPackedBytes()); + } + + for (int i = 0; i < engine.getDilithiumK(); ++i) + { + t0.getVectorIndex(i).polyt0Unpack(t0Enc, i * MLDSAEngine.DilithiumPolyT0PackedBytes); + } + } + + static void packSignature(byte[] sig, PolyVecL z, PolyVecK h, MLDSAEngine engine) + { + int end = engine.getDilithiumCTilde(); + for (int i = 0; i < engine.getDilithiumL(); ++i) + { + z.getVectorIndex(i).zPack(sig, end); + end += engine.getDilithiumPolyZPackedBytes(); + } + + for (int i = 0; i < engine.getDilithiumOmega() + engine.getDilithiumK(); ++i) + { + sig[end + i] = 0; + } + + int k = 0; + for (int i = 0; i < engine.getDilithiumK(); ++i) + { + for (int j = 0; j < MLDSAEngine.DilithiumN; ++j) + { + if (h.getVectorIndex(i).getCoeffIndex(j) != 0) + { + sig[end + k++] = (byte)j; + } + } + sig[end + engine.getDilithiumOmega() + i] = (byte)k; + } + } + + static boolean unpackSignature(PolyVecL z, PolyVecK h, byte[] sig, MLDSAEngine engine) + { + int i, j, k; + + int end = engine.getDilithiumCTilde(); + for (i = 0; i < engine.getDilithiumL(); ++i) + { + z.getVectorIndex(i).zUnpack(Arrays.copyOfRange(sig, end + i * engine.getDilithiumPolyZPackedBytes(), end + (i + 1) * engine.getDilithiumPolyZPackedBytes())); + } + end += engine.getDilithiumL() * engine.getDilithiumPolyZPackedBytes(); + + k = 0; + for (i = 0; i < engine.getDilithiumK(); ++i) + { + for (j = 0; j < MLDSAEngine.DilithiumN; ++j) + { + h.getVectorIndex(i).setCoeffIndex(j, 0); + } + + if ((sig[end + engine.getDilithiumOmega() + i] & 0xFF) < k || (sig[end + engine.getDilithiumOmega() + i] & 0xFF) > engine.getDilithiumOmega()) + { + return false; + } + + for (j = k; j < (sig[end + engine.getDilithiumOmega() + i] & 0xFF); ++j) + { + if (j > k && (sig[end + j] & 0xFF) <= (sig[end + j - 1] & 0xFF)) + { + return false; + } + h.getVectorIndex(i).setCoeffIndex((sig[end + j] & 0xFF), 1); + } + + k = (int)(sig[end + engine.getDilithiumOmega() + i]); + } + for (j = k; j < engine.getDilithiumOmega(); ++j) + { + if ((sig[end + j] & 0xFF) != 0) + { + return false; + } + } + return true; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Poly.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Poly.java new file mode 100644 index 0000000000..6804be37a6 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Poly.java @@ -0,0 +1,799 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.crypto.digests.SHAKEDigest; + +class Poly +{ + private final static int DilithiumN = MLDSAEngine.DilithiumN; + + private final int polyUniformNBlocks; + private int[] coeffs; + private final MLDSAEngine engine; + + private final Symmetric symmetric; + + public Poly(MLDSAEngine engine) + { + this.coeffs = new int[DilithiumN]; + this.engine = engine; + this.symmetric = engine.GetSymmetric(); + this.polyUniformNBlocks = (768 + symmetric.stream128BlockBytes - 1) / symmetric.stream128BlockBytes; + } + + void copyTo(Poly z) + { + System.arraycopy(coeffs, 0, z.coeffs, 0, DilithiumN); + } + + public int getCoeffIndex(int i) + { + return this.coeffs[i]; + } + + public int[] getCoeffs() + { + return this.coeffs; + } + + public void setCoeffIndex(int i, int val) + { + this.coeffs[i] = val; + } + + public void setCoeffs(int[] coeffs) + { + this.coeffs = coeffs; + } + + public void uniformBlocks(byte[] seed, short nonce) + { + int i, ctr, off, + buflen = polyUniformNBlocks * symmetric.stream128BlockBytes; + byte[] buf = new byte[buflen + 2]; + + symmetric.stream128init(seed, nonce); + + symmetric.stream128squeezeBlocks(buf, 0, buflen); + + ctr = rejectUniform(this, 0, DilithiumN, buf, buflen); + + // ctr can be less than N + + while (ctr < DilithiumN) + { + off = buflen % 3; + for (i = 0; i < off; ++i) + { + buf[i] = buf[buflen - off + i]; + } + symmetric.stream128squeezeBlocks(buf, off, symmetric.stream128BlockBytes); + buflen = symmetric.stream128BlockBytes + off; + ctr += rejectUniform(this, ctr, DilithiumN - ctr, buf, buflen); + } + + } + + private static int rejectUniform(Poly outputPoly, int coeffOff, int len, byte[] inpBuf, int buflen) + { + int ctr, pos; + int t; + + ctr = pos = 0; + while (ctr < len && pos + 3 <= buflen) + { + t = (inpBuf[pos++] & 0xFF); + t |= (inpBuf[pos++] & 0xFF) << 8; + t |= (inpBuf[pos++] & 0xFF) << 16; + t &= 0x7FFFFF; + + if (t < MLDSAEngine.DilithiumQ) + { + outputPoly.setCoeffIndex(coeffOff + ctr, t); + ctr++; + } + } + + return ctr; + + } + + public void uniformEta(byte[] seed, short nonce) + { + int ctr, polyUniformEtaNBlocks, eta = engine.getDilithiumEta(); + + if (engine.getDilithiumEta() == 2) + { + polyUniformEtaNBlocks = ((136 + symmetric.stream256BlockBytes - 1) / symmetric.stream256BlockBytes); // TODO: change with class + } + else if (engine.getDilithiumEta() == 4) + { + polyUniformEtaNBlocks = ((227 + symmetric.stream256BlockBytes - 1) / symmetric.stream256BlockBytes); // TODO: change with class + } + else + { + throw new RuntimeException("Wrong Dilithium Eta!"); + } + + int buflen = polyUniformEtaNBlocks * symmetric.stream256BlockBytes; + + byte[] buf = new byte[buflen]; + + symmetric.stream256init(seed, nonce); + symmetric.stream256squeezeBlocks(buf, 0, buflen); + + ctr = rejectEta(this, 0, DilithiumN, buf, buflen, eta); + + while (ctr < MLDSAEngine.DilithiumN) + { + symmetric.stream256squeezeBlocks(buf, 0, symmetric.stream256BlockBytes); + ctr += rejectEta(this, ctr, DilithiumN - ctr, buf, symmetric.stream256BlockBytes, eta); + } + + } + + private static int rejectEta(Poly outputPoly, int coeffOff, int len, byte[] buf, int buflen, int eta) + { + int ctr, pos; + int t0, t1; + + ctr = pos = 0; + + while (ctr < len && pos < buflen) + { + t0 = (buf[pos] & 0xFF) & 0x0F; + t1 = (buf[pos++] & 0xFF) >> 4; + if (eta == 2) + { + if (t0 < 15) + { + t0 = t0 - (205 * t0 >> 10) * 5; + outputPoly.setCoeffIndex(coeffOff + ctr, 2 - t0); + ctr++; + } + if (t1 < 15 && ctr < len) + { + t1 = t1 - (205 * t1 >> 10) * 5; + outputPoly.setCoeffIndex(coeffOff + ctr, 2 - t1); + ctr++; + } + } + else if (eta == 4) + { + if (t0 < 9) + { + outputPoly.setCoeffIndex(coeffOff + ctr, 4 - t0); + ctr++; + } + if (t1 < 9 && ctr < len) + { + outputPoly.setCoeffIndex(coeffOff + ctr, 4 - t1); + ctr++; + } + // System.out.printf("ctr %d coeff %d\n", ctr, outputPoly.getCoeffIndex(ctr - 1)); + } + } + return ctr; + } + + public void polyNtt() + { + this.setCoeffs(Ntt.ntt(this.coeffs)); + } + + public void pointwiseMontgomery(Poly v, Poly w) + { + int i; + for (i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, Reduce.montgomeryReduce((long)((long)v.getCoeffIndex(i) * (long)w.getCoeffIndex(i)))); + } + } + + public void pointwiseAccountMontgomery(PolyVecL u, PolyVecL v) + { + int i; + Poly t = new Poly(engine); + + this.pointwiseMontgomery(u.getVectorIndex(0), v.getVectorIndex(0)); + + for (i = 1; i < engine.getDilithiumL(); ++i) + { + t.pointwiseMontgomery(u.getVectorIndex(i), v.getVectorIndex(i)); + this.addPoly(t); + } + + + } + + public void addPoly(Poly a) + { + int i; + for (i = 0; i < DilithiumN; i++) + { + this.setCoeffIndex(i, this.getCoeffIndex(i) + a.getCoeffIndex(i)); + } + } + + + public void reduce() + { + for (int i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, Reduce.reduce32(this.getCoeffIndex(i))); + } + } + + public void invNttToMont() + { + this.setCoeffs(Ntt.invNttToMont(this.getCoeffs())); + } + + public void conditionalAddQ() + { + for (int i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, Reduce.conditionalAddQ(this.getCoeffIndex(i))); + } + } + + public void power2Round(Poly a) + { + for (int i = 0; i < DilithiumN; ++i) + { + int[] p2r = Rounding.power2Round(this.getCoeffIndex(i)); + this.setCoeffIndex(i, p2r[0]); + a.setCoeffIndex(i, p2r[1]); + } + } + + public byte[] polyt1Pack() + { + byte[] out = new byte[MLDSAEngine.DilithiumPolyT1PackedBytes]; + + for (int i = 0; i < DilithiumN / 4; ++i) + { + out[5 * i + 0] = (byte)(this.coeffs[4 * i + 0] >> 0); + out[5 * i + 1] = (byte)((this.coeffs[4 * i + 0] >> 8) | (this.coeffs[4 * i + 1] << 2)); + out[5 * i + 2] = (byte)((this.coeffs[4 * i + 1] >> 6) | (this.coeffs[4 * i + 2] << 4)); + out[5 * i + 3] = (byte)((this.coeffs[4 * i + 2] >> 4) | (this.coeffs[4 * i + 3] << 6)); + out[5 * i + 4] = (byte)(this.coeffs[4 * i + 3] >> 2); + } + return out; + } + + public void polyt1Unpack(byte[] a) + { + int i; + + for (i = 0; i < DilithiumN / 4; ++i) + { + this.setCoeffIndex(4 * i + 0, (((a[5 * i + 0] & 0xFF) >> 0) | ((int)(a[5 * i + 1] & 0xFF) << 8)) & 0x3FF); + this.setCoeffIndex(4 * i + 1, (((a[5 * i + 1] & 0xFF) >> 2) | ((int)(a[5 * i + 2] & 0xFF) << 6)) & 0x3FF); + this.setCoeffIndex(4 * i + 2, (((a[5 * i + 2] & 0xFF) >> 4) | ((int)(a[5 * i + 3] & 0xFF) << 4)) & 0x3FF); + this.setCoeffIndex(4 * i + 3, (((a[5 * i + 3] & 0xFF) >> 6) | ((int)(a[5 * i + 4] & 0xFF) << 2)) & 0x3FF); + } + } + + public byte[] polyEtaPack(byte[] out, int outOff) + { + int i; + byte[] t = new byte[8]; + + if (engine.getDilithiumEta() == 2) + { + for (i = 0; i < DilithiumN / 8; ++i) + { + t[0] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 0)); + t[1] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 1)); + t[2] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 2)); + t[3] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 3)); + t[4] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 4)); + t[5] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 5)); + t[6] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 6)); + t[7] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(8 * i + 7)); + + out[outOff + 3 * i + 0] = (byte)((t[0] >> 0) | (t[1] << 3) | (t[2] << 6)); + out[outOff + 3 * i + 1] = (byte)((t[2] >> 2) | (t[3] << 1) | (t[4] << 4) | (t[5] << 7)); + out[outOff + 3 * i + 2] = (byte)((t[5] >> 1) | (t[6] << 2) | (t[7] << 5)); + } + } + else if (engine.getDilithiumEta() == 4) + { + for (i = 0; i < DilithiumN / 2; ++i) + { + t[0] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(2 * i + 0)); + t[1] = (byte)(engine.getDilithiumEta() - this.getCoeffIndex(2 * i + 1)); + out[outOff + i] = (byte)(t[0] | t[1] << 4); + } + } + else + { + throw new RuntimeException("Eta needs to be 2 or 4!"); + } + return out; + } + + public void polyEtaUnpack(byte[] a, int aOff) + { + int i, eta = engine.getDilithiumEta(); + + if (engine.getDilithiumEta() == 2) + { + for (i = 0; i < DilithiumN / 8; ++i) + { + int base = aOff + 3 * i; + this.setCoeffIndex(8 * i + 0, (((a[base + 0] & 0xFF) >> 0)) & 7); + this.setCoeffIndex(8 * i + 1, (((a[base + 0] & 0xFF) >> 3)) & 7); + this.setCoeffIndex(8 * i + 2, ((a[base + 0] & 0xFF) >> 6) | ((a[base + 1] & 0xFF) << 2) & 7); + this.setCoeffIndex(8 * i + 3, (((a[base + 1] & 0xFF) >> 1)) & 7); + this.setCoeffIndex(8 * i + 4, (((a[base + 1] & 0xFF) >> 4)) & 7); + this.setCoeffIndex(8 * i + 5, ((a[base + 1] & 0xFF) >> 7) | ((a[base + 2] & 0xFF) << 1) & 7); + this.setCoeffIndex(8 * i + 6, (((a[base + 2] & 0xFF) >> 2)) & 7); + this.setCoeffIndex(8 * i + 7, (((a[base + 2] & 0xFF) >> 5)) & 7); + + this.setCoeffIndex(8 * i + 0, eta - this.getCoeffIndex(8 * i + 0)); + this.setCoeffIndex(8 * i + 1, eta - this.getCoeffIndex(8 * i + 1)); + this.setCoeffIndex(8 * i + 2, eta - this.getCoeffIndex(8 * i + 2)); + this.setCoeffIndex(8 * i + 3, eta - this.getCoeffIndex(8 * i + 3)); + this.setCoeffIndex(8 * i + 4, eta - this.getCoeffIndex(8 * i + 4)); + this.setCoeffIndex(8 * i + 5, eta - this.getCoeffIndex(8 * i + 5)); + this.setCoeffIndex(8 * i + 6, eta - this.getCoeffIndex(8 * i + 6)); + this.setCoeffIndex(8 * i + 7, eta - this.getCoeffIndex(8 * i + 7)); + } + } + else if (engine.getDilithiumEta() == 4) + { + for (i = 0; i < DilithiumN / 2; ++i) + { + this.setCoeffIndex(2 * i + 0, a[aOff + i] & 0x0F); + this.setCoeffIndex(2 * i + 1, (a[aOff + i] & 0xFF) >> 4); + this.setCoeffIndex(2 * i + 0, eta - this.getCoeffIndex(2 * i + 0)); + this.setCoeffIndex(2 * i + 1, eta - this.getCoeffIndex(2 * i + 1)); + } + } + } + + public byte[] polyt0Pack(byte[] out, int outOff) + { + int i; + int[] t = new int[8]; + + for (i = 0; i < DilithiumN / 8; ++i) + { + t[0] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 0); + t[1] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 1); + t[2] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 2); + t[3] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 3); + t[4] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 4); + t[5] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 5); + t[6] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 6); + t[7] = (1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 7); + + int base = outOff + 13 * i; + out[base + 0] = (byte)(t[0]); + out[base + 1] = (byte)(t[0] >> 8); + out[base + 1] = (byte)(out[base + 1] | (byte)(t[1] << 5)); + out[base + 2] = (byte)(t[1] >> 3); + out[base + 3] = (byte)(t[1] >> 11); + out[base + 3] = (byte)(out[base + 3] | (byte)(t[2] << 2)); + out[base + 4] = (byte)(t[2] >> 6); + out[base + 4] = (byte)(out[base + 4] | (byte)(t[3] << 7)); + out[base + 5] = (byte)(t[3] >> 1); + out[base + 6] = (byte)(t[3] >> 9); + out[base + 6] = (byte)(out[base + 6] | (byte)(t[4] << 4)); + out[base + 7] = (byte)(t[4] >> 4); + out[base + 8] = (byte)(t[4] >> 12); + out[base + 8] = (byte)(out[base + 8] | (byte)(t[5] << 1)); + out[base + 9] = (byte)(t[5] >> 7); + out[base + 9] = (byte)(out[base + 9] | (byte)(t[6] << 6)); + out[base + 10] = (byte)(t[6] >> 2); + out[base + 11] = (byte)(t[6] >> 10); + out[base + 11] = (byte)(out[base + 11] | (byte)(t[7] << 3)); + out[base + 12] = (byte)(t[7] >> 5); + } + return out; + } + + public void polyt0Unpack(byte[] a, int aOff) + { + int i; + for (i = 0; i < DilithiumN / 8; ++i) + { + int base = aOff + 13 * i; + this.setCoeffIndex(8 * i + 0, + ( + (a[base + 0] & 0xFF) | + ((a[base + 1] & 0xFF) << 8) + ) & 0x1FFF); + this.setCoeffIndex(8 * i + 1, + ( + (((a[base + 1] & 0xFF) >> 5) | + ((a[base + 2] & 0xFF) << 3)) | + ((a[base + 3] & 0xFF) << 11) + ) & 0x1FFF); + + this.setCoeffIndex(8 * i + 2, + ( + (((a[base + 3] & 0xFF) >> 2) | + ((a[base + 4] & 0xFF) << 6)) + ) & 0x1FFF); + + this.setCoeffIndex(8 * i + 3, + ( + (((a[base + 4] & 0xFF) >> 7) | + ((a[base + 5] & 0xFF) << 1)) | + ((a[base + 6] & 0xFF) << 9) + ) & 0x1FFF); + + this.setCoeffIndex(8 * i + 4, + ( + (((a[base + 6] & 0xFF) >> 4) | + ((a[base + 7] & 0xFF) << 4)) | + ((a[base + 8] & 0xFF) << 12) + ) & 0x1FFF); + + this.setCoeffIndex(8 * i + 5, + ( + (((a[base + 8] & 0xFF) >> 1) | + ((a[base + 9] & 0xFF) << 7)) + ) & 0x1FFF); + + this.setCoeffIndex(8 * i + 6, + ( + (((a[base + 9] & 0xFF) >> 6) | + ((a[base + 10] & 0xFF) << 2)) | + ((a[base + 11] & 0xFF) << 10) + ) & 0x1FFF); + + this.setCoeffIndex(8 * i + 7, + ( + ((a[base + 11] & 0xFF) >> 3 | + ((a[base + 12] & 0xFF) << 5)) + ) & 0x1FFF); + + + this.setCoeffIndex(8 * i + 0, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 0))); + this.setCoeffIndex(8 * i + 1, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 1))); + this.setCoeffIndex(8 * i + 2, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 2))); + this.setCoeffIndex(8 * i + 3, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 3))); + this.setCoeffIndex(8 * i + 4, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 4))); + this.setCoeffIndex(8 * i + 5, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 5))); + this.setCoeffIndex(8 * i + 6, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 6))); + this.setCoeffIndex(8 * i + 7, ((1 << (MLDSAEngine.DilithiumD - 1)) - this.getCoeffIndex(8 * i + 7))); + } + } + + + public void uniformGamma1(byte[] seed, short nonce) + { + byte[] buf = new byte[engine.getPolyUniformGamma1NBlocks() * symmetric.stream256BlockBytes]; + + symmetric.stream256init(seed, nonce); + symmetric.stream256squeezeBlocks(buf, 0, engine.getPolyUniformGamma1NBlocks() * symmetric.stream256BlockBytes);// todo this is final + + this.unpackZ(buf); + } + + private void unpackZ(byte[] a) + { + int gamma1 = engine.getDilithiumGamma1(); + if (gamma1 == (1 << 17)) + { + for (int i = 0; i < DilithiumN / 4; ++i) + { + this.setCoeffIndex(4 * i + 0, + ( + (((a[9 * i + 0] & 0xFF)) | + ((a[9 * i + 1] & 0xFF) << 8)) | + ((a[9 * i + 2] & 0xFF) << 16) + ) & 0x3FFFF); + this.setCoeffIndex(4 * i + 1, + ( + (((a[9 * i + 2] & 0xFF) >> 2) | + ((a[9 * i + 3] & 0xFF) << 6)) | + ((a[9 * i + 4] & 0xFF) << 14) + ) & 0x3FFFF); + this.setCoeffIndex(4 * i + 2, + ( + (((a[9 * i + 4] & 0xFF) >> 4) | + ((a[9 * i + 5] & 0xFF) << 4)) | + ((a[9 * i + 6] & 0xFF) << 12) + ) & 0x3FFFF); + this.setCoeffIndex(4 * i + 3, + ( + (((a[9 * i + 6] & 0xFF) >> 6) | + ((a[9 * i + 7] & 0xFF) << 2)) | + ((a[9 * i + 8] & 0xFF) << 10) + ) & 0x3FFFF); + + + this.setCoeffIndex(4 * i + 0, gamma1 - this.getCoeffIndex(4 * i + 0)); + this.setCoeffIndex(4 * i + 1, gamma1 - this.getCoeffIndex(4 * i + 1)); + this.setCoeffIndex(4 * i + 2, gamma1 - this.getCoeffIndex(4 * i + 2)); + this.setCoeffIndex(4 * i + 3, gamma1 - this.getCoeffIndex(4 * i + 3)); + } + } + else if (gamma1 == (1 << 19)) + { + for (int i = 0; i < DilithiumN / 2; ++i) + { + this.setCoeffIndex(2 * i + 0, + ( + (((a[5 * i + 0] & 0xFF)) | + ((a[5 * i + 1] & 0xFF) << 8)) | + ((a[5 * i + 2] & 0xFF) << 16) + ) & 0xFFFFF); + this.setCoeffIndex(2 * i + 1, + ( + (((a[5 * i + 2] & 0xFF) >> 4) | + ((a[5 * i + 3] & 0xFF) << 4)) | + ((a[5 * i + 4] & 0xFF) << 12) + ) & 0xFFFFF); + + this.setCoeffIndex(2 * i + 0, gamma1 - this.getCoeffIndex(2 * i + 0)); + this.setCoeffIndex(2 * i + 1, gamma1 - this.getCoeffIndex(2 * i + 1)); + } + } + else + { + throw new RuntimeException("Wrong Dilithiumn Gamma1!"); + } + } + + public void decompose(Poly a) + { + int gamma2 = engine.getDilithiumGamma2(); + for (int i = 0; i < DilithiumN; ++i) + { + int[] decomp = Rounding.decompose(this.getCoeffIndex(i), gamma2); + this.setCoeffIndex(i, decomp[1]); + a.setCoeffIndex(i, decomp[0]); + } + } + + void packW1(byte[] r, int rOff) + { +// byte[] out = new byte[engine.getDilithiumPolyW1PackedBytes()]; + + int gamma2 = engine.getDilithiumGamma2(); + if (gamma2 == (MLDSAEngine.DilithiumQ - 1) / 88) + { + for (int i = 0; i < DilithiumN / 4; ++i) + { + r[rOff + 3 * i + 0] = (byte)(((byte)getCoeffIndex(4 * i + 0)) | (getCoeffIndex(4 * i + 1) << 6)); + r[rOff + 3 * i + 1] = (byte)((byte)(getCoeffIndex(4 * i + 1) >> 2) | (getCoeffIndex(4 * i + 2) << 4)); + r[rOff + 3 * i + 2] = (byte)((byte)(getCoeffIndex(4 * i + 2) >> 4) | (getCoeffIndex(4 * i + 3) << 2)); + } + } + else if (engine.getDilithiumGamma2() == (MLDSAEngine.DilithiumQ - 1) / 32) + { + for (int i = 0; i < DilithiumN / 2; ++i) + { + r[rOff + i] = (byte)(getCoeffIndex(2 * i + 0) | (getCoeffIndex(2 * i + 1) << 4)); + } + } + } + + public void challenge(byte[] seed, int seedOff, int seedLen) + { + int i, b = 0, pos; + long signs; + byte[] buf = new byte[symmetric.stream256BlockBytes]; + + SHAKEDigest shake256Digest = new SHAKEDigest(256); + shake256Digest.update(seed, seedOff, seedLen); + shake256Digest.doOutput(buf, 0, symmetric.stream256BlockBytes); + + signs = (long)0; + for (i = 0; i < 8; ++i) + { + signs |= (long)(buf[i] & 0xFF) << 8 * i; + } + + pos = 8; + + for (i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, 0); + } + for (i = DilithiumN - engine.getDilithiumTau(); i < DilithiumN; ++i) + { + do + { + if (pos >= symmetric.stream256BlockBytes) + { + shake256Digest.doOutput(buf, 0, symmetric.stream256BlockBytes); + pos = 0; + } + b = (buf[pos++] & 0xFF); + } + while (b > i); + + this.setCoeffIndex(i, this.getCoeffIndex(b)); + this.setCoeffIndex(b, (int)(1 - 2 * (signs & 1))); + signs = (long)(signs >> 1); + } + } + + public boolean checkNorm(int B) + { + int i, t; + + if (B > (MLDSAEngine.DilithiumQ - 1) / 8) + { + return true; + } + + for (i = 0; i < DilithiumN; ++i) + { + t = this.getCoeffIndex(i) >> 31; + t = this.getCoeffIndex(i) - (t & 2 * this.getCoeffIndex(i)); + + if (t >= B) + { + return true; + } + } + return false; + } + + public void subtract(Poly inpPoly) + { + for (int i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, this.getCoeffIndex(i) - inpPoly.getCoeffIndex(i)); + } + } + + public int polyMakeHint(Poly a0, Poly a1) + { + int i, s = 0; + + for (i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, Rounding.makeHint(a0.getCoeffIndex(i), a1.getCoeffIndex(i), engine)); + s += this.getCoeffIndex(i); + } + return s; + } + + public void polyUseHint(Poly a, Poly h) + { + for (int i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, Rounding.useHint(a.getCoeffIndex(i), h.getCoeffIndex(i), engine.getDilithiumGamma2())); + } + } + + public void zPack(byte[] z, int zOff) + { + int gamma1 = engine.getDilithiumGamma1(); + if (gamma1 == (1 << 17)) + { + for (int i = 0; i < DilithiumN / 4; ++i) + { + int t0 = gamma1 - getCoeffIndex(4 * i + 0); + int t1 = gamma1 - getCoeffIndex(4 * i + 1); + int t2 = gamma1 - getCoeffIndex(4 * i + 2); + int t3 = gamma1 - getCoeffIndex(4 * i + 3); + + z[zOff + 9 * i + 0] = (byte)t0; + z[zOff + 9 * i + 1] = (byte)(t0 >> 8); + z[zOff + 9 * i + 2] = (byte)((byte)(t0 >> 16) | (t1 << 2)); + z[zOff + 9 * i + 3] = (byte)(t1 >> 6); + z[zOff + 9 * i + 4] = (byte)((byte)(t1 >> 14) | (t2 << 4)); + z[zOff + 9 * i + 5] = (byte)(t2 >> 4); + z[zOff + 9 * i + 6] = (byte)((byte)(t2 >> 12) | (t3 << 6)); + z[zOff + 9 * i + 7] = (byte)(t3 >> 2); + z[zOff + 9 * i + 8] = (byte)(t3 >> 10); + } + } + else if (gamma1 == (1 << 19)) + { + for (int i = 0; i < DilithiumN / 2; ++i) + { + int t0 = gamma1 - getCoeffIndex(2 * i + 0); + int t1 = gamma1 - getCoeffIndex(2 * i + 1); + + z[zOff + 5 * i + 0] = (byte)t0; + z[zOff + 5 * i + 1] = (byte)(t0 >> 8); + z[zOff + 5 * i + 2] = (byte)((byte)(t0 >> 16) | (t1 << 4)); + z[zOff + 5 * i + 3] = (byte)(t1 >> 4); + z[zOff + 5 * i + 4] = (byte)(t1 >> 12); + } + } + else + { + throw new RuntimeException("Wrong Dilithium Gamma1!"); + } + } + + void zUnpack(byte[] a) + { + int i; + if (engine.getDilithiumGamma1() == (1 << 17)) + { + for (i = 0; i < DilithiumN / 4; ++i) + { + this.setCoeffIndex(4 * i + 0, + (((int)(a[9 * i + 0] & 0xFF) + | (int)((a[9 * i + 1] & 0xFF) << 8)) + | (int)((a[9 * i + 2] & 0xFF) << 16)) + & 0x3FFFF); + + this.setCoeffIndex(4 * i + 1, + (((int)((a[9 * i + 2] & 0xFF) >>> 2) + | (int)((a[9 * i + 3] & 0xFF) << 6)) + | (int)((a[9 * i + 4] & 0xFF) << 14)) + & 0x3FFFF); + + this.setCoeffIndex(4 * i + 2, + (((int)((a[9 * i + 4] & 0xFF) >>> 4) + | (int)((a[9 * i + 5] & 0xFF) << 4)) + | (int)((a[9 * i + 6] & 0xFF) << 12)) + & 0x3FFFF); + + this.setCoeffIndex(4 * i + 3, + (((int)((a[9 * i + 6] & 0xFF) >>> 6) + | (int)((a[9 * i + 7] & 0xFF) << 2)) + | (int)((a[9 * i + 8] & 0xFF) << 10)) + & 0x3FFFF); + + this.setCoeffIndex(4 * i + 0, engine.getDilithiumGamma1() - this.getCoeffIndex(4 * i + 0)); + this.setCoeffIndex(4 * i + 1, engine.getDilithiumGamma1() - this.getCoeffIndex(4 * i + 1)); + this.setCoeffIndex(4 * i + 2, engine.getDilithiumGamma1() - this.getCoeffIndex(4 * i + 2)); + this.setCoeffIndex(4 * i + 3, engine.getDilithiumGamma1() - this.getCoeffIndex(4 * i + 3)); + } + } + else if (engine.getDilithiumGamma1() == (1 << 19)) + { + for (i = 0; i < DilithiumN / 2; ++i) + { + this.setCoeffIndex(2 * i + 0, + (int)(((((int)(a[5 * i + 0] & 0xFF)) + | (int)((a[5 * i + 1] & 0xFF) << 8)) + | (int)((a[5 * i + 2] & 0xFF) << 16)) + & 0xFFFFF) + ); + + this.setCoeffIndex(2 * i + 1, + (int)(((((int)((a[5 * i + 2] & 0xFF) >>> 4)) + | (int)((a[5 * i + 3] & 0xFF) << 4)) + | (int)((a[5 * i + 4] & 0xFF) << 12)) + & 0xFFFFF) + ); + + this.setCoeffIndex(2 * i + 0, engine.getDilithiumGamma1() - this.getCoeffIndex(2 * i + 0)); + this.setCoeffIndex(2 * i + 1, engine.getDilithiumGamma1() - this.getCoeffIndex(2 * i + 1)); + } + } + else + { + throw new RuntimeException("Wrong Dilithium Gamma1!"); + } + } + + public void shiftLeft() + { + for (int i = 0; i < DilithiumN; ++i) + { + this.setCoeffIndex(i, this.getCoeffIndex(i) << MLDSAEngine.DilithiumD); + } + } + + public String toString() + { + StringBuffer out = new StringBuffer(); + out.append("["); + for (int i = 0; i < coeffs.length; i++) + { + out.append(coeffs[i]); + if (i != coeffs.length - 1) + { + out.append(", "); + } + } + out.append("]"); + return out.toString(); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecK.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecK.java new file mode 100644 index 0000000000..ba00307d12 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecK.java @@ -0,0 +1,179 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +class PolyVecK +{ + private final Poly[] vec; + + PolyVecK(MLDSAEngine engine) + { + int dilithiumK = engine.getDilithiumK(); + + this.vec = new Poly[dilithiumK]; + for (int i = 0; i < dilithiumK; i++) + { + vec[i] = new Poly(engine); + } + } + + Poly getVectorIndex(int i) + { + return vec[i]; + } + + void setVectorIndex(int i, Poly p) + { + this.vec[i] = p; + } + + public void uniformEta(byte[] seed, short nonce) + { + short n = nonce; + for (int i = 0; i < vec.length; ++i) + { + vec[i].uniformEta(seed, n++); + } + } + + public void reduce() + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).reduce(); + } + } + + public void invNttToMont() + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).invNttToMont(); + } + } + + public void addPolyVecK(PolyVecK b) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).addPoly(b.getVectorIndex(i)); + } + } + + public void conditionalAddQ() + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).conditionalAddQ(); + } + } + + public void power2Round(PolyVecK pvk) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).power2Round(pvk.getVectorIndex(i)); + } + } + + public void polyVecNtt() + { + int i; + for (i = 0; i < vec.length; ++i) + { + this.vec[i].polyNtt(); + } + } + + public void decompose(PolyVecK v) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).decompose(v.getVectorIndex(i)); + } + } + + public void packW1(MLDSAEngine engine, byte[] r, int rOff) + { + for (int i = 0; i < vec.length; ++i) + { + getVectorIndex(i).packW1(r, rOff + i * engine.getDilithiumPolyW1PackedBytes()); + } + } + + public void pointwisePolyMontgomery(Poly a, PolyVecK v) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).pointwiseMontgomery(a, v.getVectorIndex(i)); + } + } + + public void subtract(PolyVecK inpVec) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).subtract(inpVec.getVectorIndex(i)); + } + } + + public boolean checkNorm(int bound) + { + for (int i = 0; i < vec.length; ++i) + { + if (this.getVectorIndex(i).checkNorm(bound)) + { + return true; + } + } + + return false; + } + + public int makeHint(PolyVecK v0, PolyVecK v1) + { + int s = 0; + for (int i = 0; i < vec.length; ++i) + { + s += this.getVectorIndex(i).polyMakeHint(v0.getVectorIndex(i), v1.getVectorIndex(i)); + } + + return s; + } + + public void useHint(PolyVecK u, PolyVecK h) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).polyUseHint(u.getVectorIndex(i), h.getVectorIndex(i)); + } + } + + public void shiftLeft() + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).shiftLeft(); + } + } + + @Override + public String toString() + { + String out = "["; + for (int i = 0; i < vec.length; i++) + { + out += i + " " + this.getVectorIndex(i).toString(); + if (i == vec.length - 1) + { + continue; + } + out += ",\n"; + } + out += "]"; + return out; + } + + public String toString(String name) + { + return name + ": " + this.toString(); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecL.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecL.java new file mode 100644 index 0000000000..045f67c99d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecL.java @@ -0,0 +1,137 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +class PolyVecL +{ + private final Poly[] vec; + + PolyVecL(MLDSAEngine engine) + { + int dilithiumL = engine.getDilithiumL(); + + this.vec = new Poly[dilithiumL]; + for (int i = 0; i < dilithiumL; i++) + { + vec[i] = new Poly(engine); + } + } + + public PolyVecL() + throws Exception + { + throw new Exception("Requires Parameter"); + } + + public Poly getVectorIndex(int i) + { + return vec[i]; + } + + void uniformBlocks(byte[] rho, int t) + { + for (int i = 0; i < vec.length; ++i) + { + vec[i].uniformBlocks(rho, (short)(t + i)); + } + } + + public void uniformEta(byte[] seed, short nonce) + { + int i; + short n = nonce; + for (i = 0; i < vec.length; ++i) + { + getVectorIndex(i).uniformEta(seed, n++); + } + + } + + void copyTo(PolyVecL z) + { + for (int i = 0; i < vec.length; i++) + { + vec[i].copyTo(z.vec[i]); + } + } + + public void polyVecNtt() + { + for (int i = 0; i < vec.length; ++i) + { + this.vec[i].polyNtt(); + } + } + + public void uniformGamma1(byte[] seed, short nonce) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).uniformGamma1(seed, (short)(vec.length * nonce + i)); + } + } + + public void pointwisePolyMontgomery(Poly a, PolyVecL v) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).pointwiseMontgomery(a, v.getVectorIndex(i)); + } + } + + public void invNttToMont() + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).invNttToMont(); + } + } + + public void addPolyVecL(PolyVecL v) + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).addPoly(v.getVectorIndex(i)); + } + } + + public void reduce() + { + for (int i = 0; i < vec.length; ++i) + { + this.getVectorIndex(i).reduce(); + } + } + + public boolean checkNorm(int bound) + { + for (int i = 0; i < vec.length; ++i) + { + if (this.getVectorIndex(i).checkNorm(bound)) + { + return true; + } + } + return false; + } + + @Override + public String toString() + { + String out = "\n["; + for (int i = 0; i < vec.length; i++) + { + out += "Inner Matrix " + i + " " + this.getVectorIndex(i).toString(); + if (i == vec.length - 1) + { + continue; + } + out += ",\n"; + } + out += "]"; + return out; + } + + public String toString(String name) + { + return name + ": " + this.toString(); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecMatrix.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecMatrix.java new file mode 100644 index 0000000000..562377fa97 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/PolyVecMatrix.java @@ -0,0 +1,61 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +class PolyVecMatrix +{ + private final PolyVecL[] matrix; + + /** + * PolyVecL Matrix of size K + * + * @param engine source engine for the matrix to be used by. + */ + PolyVecMatrix(MLDSAEngine engine) + { + int K = engine.getDilithiumK(); + + this.matrix = new PolyVecL[K]; + for (int i = 0; i < K; i++) + { + matrix[i] = new PolyVecL(engine); + } + } + + public void pointwiseMontgomery(PolyVecK t, PolyVecL v) + { + for (int i = 0; i < matrix.length; ++i) + { + t.getVectorIndex(i).pointwiseAccountMontgomery(matrix[i], v); + } + } + + public void expandMatrix(byte[] rho) + { + for (int i = 0; i < matrix.length; ++i) + { + matrix[i].uniformBlocks(rho, i << 8); + } + } + + private String addString() + { + String out = "["; + for (int i = 0; i < matrix.length; i++) + { + out += "Outer Matrix " + i + " ["; + out += matrix[i].toString(); + if (i == matrix.length - 1) + { + out += "]\n"; + continue; + } + out += "],\n"; + } + out += "]\n"; + return out; + } + + public String toString(String name) + { + return name.concat(": \n" + this.addString()); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Reduce.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Reduce.java new file mode 100644 index 0000000000..9ea32ce546 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Reduce.java @@ -0,0 +1,28 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +class Reduce +{ + static int montgomeryReduce(long a) + { + int t; + t = (int)(a * MLDSAEngine.DilithiumQinv); + t = (int)((a - ((long)t) * MLDSAEngine.DilithiumQ) >>> 32); + // System.out.printf("%d, ", t); + return t; + + } + + static int reduce32(int a) + { + int t; + t = (a + (1 << 22)) >> 23; + t = a - t * MLDSAEngine.DilithiumQ; + return t; + } + + static int conditionalAddQ(int a) + { + a += (a >> 31) & MLDSAEngine.DilithiumQ; + return a; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Rounding.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Rounding.java new file mode 100644 index 0000000000..a7428b9c7c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Rounding.java @@ -0,0 +1,90 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +class Rounding +{ + public static int[] power2Round(int a) + { + int[] out = new int[2]; + + out[0] = (a + (1 << (MLDSAEngine.DilithiumD - 1)) - 1) >> MLDSAEngine.DilithiumD; + out[1] = a - (out[0] << MLDSAEngine.DilithiumD); + return out; + } + + public static int[] decompose(int a, int gamma2) + { + int a1, a0; + + a1 = (a + 127) >> 7; + if (gamma2 == (MLDSAEngine.DilithiumQ - 1) / 32) + { + a1 = (a1 * 1025 + (1 << 21)) >> 22; + a1 &= 15; + } + else if (gamma2 == (MLDSAEngine.DilithiumQ - 1) / 88) + { + a1 = (a1 * 11275 + (1 << 23)) >> 24; + a1 ^= ((43 - a1) >> 31) & a1; + } + else + { + throw new RuntimeException("Wrong Gamma2!"); + } + + a0 = a - a1 * 2 * gamma2; + a0 -= (((MLDSAEngine.DilithiumQ - 1) / 2 - a0) >> 31) & MLDSAEngine.DilithiumQ; + return new int[]{a0, a1}; + } + + public static int makeHint(int a0, int a1, MLDSAEngine engine) + { + int g2 = engine.getDilithiumGamma2(), q = MLDSAEngine.DilithiumQ; + if (a0 <= g2 || a0 > q - g2 || (a0 == q - g2 && a1 == 0)) + { + return 0; + } + return 1; + } + + public static int useHint(int a, int hint, int gamma2) + { + int a0, a1; + + int[] intArray = decompose(a, gamma2); + a0 = intArray[0]; + a1 = intArray[1]; + // System.out.printf("a0: %d, a1: %d\n", a0, a1); + + if (hint == 0) + { + return a1; + } + + if (gamma2 == (MLDSAEngine.DilithiumQ - 1) / 32) + { + if (a0 > 0) + { + return (a1 + 1) & 15; + } + else + { + return (a1 - 1) & 15; + } + } + else if (gamma2 == (MLDSAEngine.DilithiumQ - 1) / 88) + { + if (a0 > 0) + { + return (a1 == 43) ? 0 : a1 + 1; + } + else + { + return (a1 == 0) ? 43 : a1 - 1; + } + } + else + { + throw new RuntimeException("Wrong Gamma2!"); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Symmetric.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Symmetric.java new file mode 100644 index 0000000000..1fc4d278b1 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mldsa/Symmetric.java @@ -0,0 +1,80 @@ +package org.bouncycastle.pqc.crypto.mldsa; + +import org.bouncycastle.crypto.digests.SHAKEDigest; + +abstract class Symmetric +{ + + final int stream128BlockBytes; + final int stream256BlockBytes; + + Symmetric(int stream128, int stream256) + { + this.stream128BlockBytes = stream128; + this.stream256BlockBytes = stream256; + } + + abstract void stream128init(byte[] seed, short nonce); + + abstract void stream256init(byte[] seed, short nonce); + + abstract void stream128squeezeBlocks(byte[] output, int offset, int size); + + abstract void stream256squeezeBlocks(byte[] output, int offset, int size); + + static class ShakeSymmetric + extends Symmetric + { + private final SHAKEDigest digest128; + private final SHAKEDigest digest256; + + ShakeSymmetric() + { + super(168, 136); + digest128 = new SHAKEDigest(128); + digest256 = new SHAKEDigest(256); + } + + private void streamInit(SHAKEDigest digest, byte[] seed, short nonce) + { + digest.reset(); + // byte[] temp = new byte[seed.length + 2]; + // System.arraycopy(seed, 0, temp, 0, seed.length); + + // temp[seed.length] = (byte) nonce; + // temp[seed.length] = (byte) (nonce >> 8); + byte[] temp = new byte[2]; + // System.arraycopy(seed, 0, temp, 0, seed.length); + temp[0] = (byte)nonce; + temp[1] = (byte)(nonce >> 8); + + digest.update(seed, 0, seed.length); + digest.update(temp, 0, temp.length); + } + + + @Override + void stream128init(byte[] seed, short nonce) + { + streamInit(digest128, seed, nonce); + } + + @Override + void stream256init(byte[] seed, short nonce) + { + streamInit(digest256, seed, nonce); + } + + @Override + void stream128squeezeBlocks(byte[] output, int offset, int size) + { + digest128.doOutput(output, offset, size); + } + + @Override + void stream256squeezeBlocks(byte[] output, int offset, int size) + { + digest256.doOutput(output, offset, size); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/CBD.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/CBD.java similarity index 91% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/CBD.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/CBD.java index 946cef3f23..a7df3c7fc8 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/CBD.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/CBD.java @@ -1,9 +1,9 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; final class CBD { - public static void kyberCBD(Poly r, byte[] bytes, int eta) + public static void mlkemCBD(Poly r, byte[] bytes, int eta) { long t, d; int a, b; @@ -11,7 +11,7 @@ public static void kyberCBD(Poly r, byte[] bytes, int eta) switch (eta) { case 3: - for (int i = 0; i < KyberEngine.KyberN / 4; i++) + for (int i = 0; i < MLKEMEngine.KyberN / 4; i++) { t = convertByteTo24BitUnsignedInt(bytes, 3 * i); d = t & 0x00249249; @@ -28,7 +28,7 @@ public static void kyberCBD(Poly r, byte[] bytes, int eta) break; default: // Only for Kyber512 where eta = 2 - for (int i = 0; i < KyberEngine.KyberN / 8; i++) + for (int i = 0; i < MLKEMEngine.KyberN / 8; i++) { t = convertByteTo32BitUnsignedInt(bytes, 4 * i); // ? Problem d = t & 0x55555555; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMEngine.java similarity index 76% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberEngine.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMEngine.java index 2bd3802d47..b41116e7a2 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberEngine.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMEngine.java @@ -1,14 +1,13 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; - -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.encoders.Hex; +package org.bouncycastle.pqc.crypto.mlkem; import java.security.SecureRandom; -class KyberEngine +import org.bouncycastle.util.Arrays; + +class MLKEMEngine { private SecureRandom random; - private KyberIndCpa indCpa; + private MLKEMIndCpa indCpa; // constant parameters public final static int KyberN = 256; @@ -137,7 +136,7 @@ public int getKyberEta1() return KyberEta1; } - public KyberEngine(int k, boolean usingAes) + public MLKEMEngine(int k) { this.KyberK = k; switch (k) @@ -178,17 +177,9 @@ public KyberEngine(int k, boolean usingAes) this.CryptoPublicKeyBytes = KyberPublicKeyBytes; this.CryptoCipherTextBytes = KyberCipherTextBytes; + this.symmetric = new Symmetric.ShakeSymmetric(); - if(usingAes) - { - symmetric = new Symmetric.AesSymmetric(); - } - else - { - symmetric = new Symmetric.ShakeSymmetric(); - } - - this.indCpa = new KyberIndCpa(this); + this.indCpa = new MLKEMIndCpa(this); } public void init(SecureRandom random) @@ -198,7 +189,18 @@ public void init(SecureRandom random) public byte[][] generateKemKeyPair() { - byte[][] indCpaKeyPair = indCpa.generateKeyPair(); + byte[] d = new byte[KyberSymBytes]; + byte[] z = new byte[KyberSymBytes]; + random.nextBytes(d); + random.nextBytes(z); + + return generateKemKeyPairInternal(d, z); + } + + //Internal functions are deterministic. No randomness is sampled inside them + public byte[][] generateKemKeyPairInternal(byte[] d, byte[] z) + { + byte[][] indCpaKeyPair = indCpa.generateKeyPair(d); byte[] s = new byte[KyberIndCpaSecretKeyBytes]; @@ -208,41 +210,26 @@ public byte[][] generateKemKeyPair() symmetric.hash_h(hashedPublicKey, indCpaKeyPair[0], 0); - byte[] z = new byte[KyberSymBytes]; - random.nextBytes(z); - byte[] outputPublicKey = new byte[KyberIndCpaPublicKeyBytes]; System.arraycopy(indCpaKeyPair[0], 0, outputPublicKey, 0, KyberIndCpaPublicKeyBytes); - return new byte[][]{ Arrays.copyOfRange(outputPublicKey, 0, outputPublicKey.length - 32), Arrays.copyOfRange(outputPublicKey, outputPublicKey.length - 32, outputPublicKey.length), s, hashedPublicKey, z }; + return new byte[][] + { + Arrays.copyOfRange(outputPublicKey, 0, outputPublicKey.length - 32), + Arrays.copyOfRange(outputPublicKey, outputPublicKey.length - 32, outputPublicKey.length), + s, + hashedPublicKey, + z, + Arrays.concatenate(d, z) + }; } - public byte[][] kemEncrypt(byte[] publicKeyInput) + public byte[][] kemEncryptInternal(byte[] publicKeyInput, byte[] randBytes) { - // Input validation (6.2 ML-KEM Encaps) - // Type Check - if (publicKeyInput.length != KyberIndCpaPublicKeyBytes) - { - throw new IllegalArgumentException("Input validation Error: Type check failed for ml-kem encapsulation"); - } - // Modulus Check - PolyVec polyVec = new PolyVec(this); - byte[] seed = indCpa.unpackPublicKey(polyVec, publicKeyInput); - byte[] ek = indCpa.packPublicKey(polyVec, seed); - if (!Arrays.areEqual(ek, publicKeyInput)) - { - throw new IllegalArgumentException("Input validation: Modulus check failed for ml-kem encapsulation"); - } - - byte[] outputCipherText; byte[] buf = new byte[2 * KyberSymBytes]; byte[] kr = new byte[2 * KyberSymBytes]; - byte[] randBytes = new byte[KyberSymBytes]; - - random.nextBytes(randBytes); - System.arraycopy(randBytes, 0, buf, 0, KyberSymBytes); // SHA3-256 Public Key @@ -252,43 +239,74 @@ public byte[][] kemEncrypt(byte[] publicKeyInput) symmetric.hash_g(kr, buf); // IndCpa Encryption - outputCipherText = indCpa.encrypt(Arrays.copyOfRange(buf, 0, KyberSymBytes), publicKeyInput, Arrays.copyOfRange(kr, 32, kr.length)); + outputCipherText = indCpa.encrypt(publicKeyInput, Arrays.copyOfRange(buf, 0, KyberSymBytes), Arrays.copyOfRange(kr, 32, kr.length)); byte[] outputSharedSecret = new byte[sessionKeyLength]; System.arraycopy(kr, 0, outputSharedSecret, 0, outputSharedSecret.length); - + byte[][] outBuf = new byte[2][]; outBuf[0] = outputSharedSecret; outBuf[1] = outputCipherText; - return outBuf; } - public byte[] kemDecrypt(byte[] cipherText, byte[] secretKey) + public byte[] kemDecryptInternal(byte[] secretKey, byte[] cipherText) { byte[] buf = new byte[2 * KyberSymBytes], - kr = new byte[2 * KyberSymBytes]; + kr = new byte[2 * KyberSymBytes]; byte[] publicKey = Arrays.copyOfRange(secretKey, KyberIndCpaSecretKeyBytes, secretKey.length); - System.arraycopy(indCpa.decrypt(cipherText, secretKey), 0, buf, 0, KyberSymBytes); + System.arraycopy(indCpa.decrypt(secretKey, cipherText), 0, buf, 0, KyberSymBytes); System.arraycopy(secretKey, KyberSecretKeyBytes - 2 * KyberSymBytes, buf, KyberSymBytes, KyberSymBytes); symmetric.hash_g(kr, buf); - byte[] cmp = indCpa.encrypt(Arrays.copyOfRange(buf, 0, KyberSymBytes), publicKey, Arrays.copyOfRange(kr, KyberSymBytes, kr.length)); + byte[] implicit_rejection = new byte[KyberSymBytes + KyberCipherTextBytes]; - boolean fail = !(Arrays.constantTimeAreEqual(cipherText, cmp)); + System.arraycopy(secretKey, KyberSecretKeyBytes - KyberSymBytes, implicit_rejection, 0, KyberSymBytes); - symmetric.hash_h(kr, cipherText, KyberSymBytes); + System.arraycopy(cipherText, 0, implicit_rejection, KyberSymBytes, KyberCipherTextBytes); - cmov(kr, Arrays.copyOfRange(secretKey, KyberSecretKeyBytes - KyberSymBytes, KyberSecretKeyBytes), KyberSymBytes, fail); + symmetric.kdf(implicit_rejection, implicit_rejection ); // J(z||c) + + byte[] cmp = indCpa.encrypt(publicKey, Arrays.copyOfRange(buf, 0, KyberSymBytes), Arrays.copyOfRange(kr, KyberSymBytes, kr.length)); + + boolean fail = !(Arrays.constantTimeAreEqual(cipherText, cmp)); + + cmov(kr, implicit_rejection, KyberSymBytes, fail); return Arrays.copyOfRange(kr, 0, sessionKeyLength); } + public byte[][] kemEncrypt(byte[] publicKeyInput, byte[] randBytes) + { + //TODO: do input validation elsewhere? + // Input validation (6.2 ML-KEM Encaps) + // Type Check + if (publicKeyInput.length != KyberIndCpaPublicKeyBytes) + { + throw new IllegalArgumentException("Input validation Error: Type check failed for ml-kem encapsulation"); + } + // Modulus Check + PolyVec polyVec = new PolyVec(this); + byte[] seed = indCpa.unpackPublicKey(polyVec, publicKeyInput); + byte[] ek = indCpa.packPublicKey(polyVec, seed); + if (!Arrays.areEqual(ek, publicKeyInput)) + { + throw new IllegalArgumentException("Input validation: Modulus check failed for ml-kem encapsulation"); + } + + return kemEncryptInternal(publicKeyInput, randBytes); + } + public byte[] kemDecrypt(byte[] secretKey, byte[] cipherText) + { + //TODO: do input validation + return kemDecryptInternal(secretKey, cipherText); + } + private void cmov(byte[] r, byte[] x, int xlen, boolean b) { if (b) diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMExtractor.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMExtractor.java new file mode 100644 index 0000000000..6f19f835e6 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMExtractor.java @@ -0,0 +1,31 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import org.bouncycastle.crypto.EncapsulatedSecretExtractor; + +public class MLKEMExtractor + implements EncapsulatedSecretExtractor +{ + private final MLKEMPrivateKeyParameters privateKey; + private final MLKEMEngine engine; + + public MLKEMExtractor(MLKEMPrivateKeyParameters privateKey) + { + if (privateKey == null) + { + throw new NullPointerException("'privateKey' cannot be null"); + } + + this.privateKey = privateKey; + this.engine = privateKey.getParameters().getEngine(); + } + + public byte[] extractSecret(byte[] encapsulation) + { + return engine.kemDecrypt(privateKey.getEncoded(), encapsulation); + } + + public int getEncapsulationLength() + { + return engine.getCryptoCipherTextBytes(); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMGenerator.java new file mode 100644 index 0000000000..61c693724d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMGenerator.java @@ -0,0 +1,42 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.EncapsulatedSecretGenerator; +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.pqc.crypto.util.SecretWithEncapsulationImpl; + +public class MLKEMGenerator + implements EncapsulatedSecretGenerator +{ + // the source of randomness + private final SecureRandom sr; + + public MLKEMGenerator(SecureRandom random) + { + this.sr = random; + } + + public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recipientKey) + { + MLKEMPublicKeyParameters key = (MLKEMPublicKeyParameters)recipientKey; + MLKEMEngine engine = key.getParameters().getEngine(); + engine.init(sr); + + byte[] randBytes = new byte[32]; + engine.getRandomBytes(randBytes); + + byte[][] kemEncrypt = engine.kemEncrypt(key.getEncoded(), randBytes); + return new SecretWithEncapsulationImpl(kemEncrypt[0], kemEncrypt[1]); + } + public SecretWithEncapsulation internalGenerateEncapsulated(AsymmetricKeyParameter recipientKey, byte[] randBytes) + { + MLKEMPublicKeyParameters key = (MLKEMPublicKeyParameters)recipientKey; + MLKEMEngine engine = key.getParameters().getEngine(); + engine.init(sr); + + byte[][] kemEncrypt = engine.kemEncryptInternal(key.getEncoded(), randBytes); + return new SecretWithEncapsulationImpl(kemEncrypt[0], kemEncrypt[1]); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberIndCpa.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMIndCpa.java similarity index 91% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberIndCpa.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMIndCpa.java index dd6fac3d72..c5d7527c33 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberIndCpa.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMIndCpa.java @@ -1,13 +1,11 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; -import org.bouncycastle.crypto.digests.SHAKEDigest; import org.bouncycastle.util.Arrays; -class KyberIndCpa +class MLKEMIndCpa { - private KyberEngine engine; + private MLKEMEngine engine; private int kyberK; - private int eta1; private int indCpaPublicKeyBytes; private int polyVecBytes; private int indCpaBytes; @@ -16,11 +14,10 @@ class KyberIndCpa private Symmetric symmetric; - public KyberIndCpa(KyberEngine engine) + public MLKEMIndCpa(MLKEMEngine engine) { this.engine = engine; this.kyberK = engine.getKyberK(); - this.eta1 = engine.getKyberEta1(); this.indCpaPublicKeyBytes = engine.getKyberPublicKeyBytes(); this.polyVecBytes = engine.getKyberPolyVecBytes(); this.indCpaBytes = engine.getKyberIndCpaBytes(); @@ -31,9 +28,9 @@ public KyberIndCpa(KyberEngine engine) KyberGenerateMatrixNBlocks = ( ( - 12 * KyberEngine.KyberN + 12 * MLKEMEngine.KyberN / 8 * (1 << 12) - / KyberEngine.KyberQ + symmetric.xofBlockBytes + / MLKEMEngine.KyberQ + symmetric.xofBlockBytes ) / symmetric.xofBlockBytes ); @@ -45,20 +42,16 @@ public KyberIndCpa(KyberEngine engine) * * @return KeyPair where each key is represented as bytes */ - byte[][] generateKeyPair() + byte[][] generateKeyPair(byte[] d) { PolyVec secretKey = new PolyVec(engine), publicKey = new PolyVec(engine), e = new PolyVec(engine); - byte[] d = new byte[32]; - - // (p, sigma) <- G(d) - - engine.getRandomBytes(d); + // (p, sigma) <- G(d || k) byte[] buf = new byte[64]; - symmetric.hash_g(buf, d); + symmetric.hash_g(buf, Arrays.append(d, (byte)kyberK)); byte[] publicSeed = new byte[32]; // p in docs byte[] noiseSeed = new byte[32]; // sigma in docs @@ -141,7 +134,7 @@ byte[][] generateKeyPair() return new byte[][]{packPublicKey(publicKey, publicSeed), packSecretKey(secretKey)}; } - public byte[] encrypt(byte[] msg, byte[] publicKeyInput, byte[] coins) + public byte[] encrypt(byte[] publicKeyInput, byte[] msg, byte[] coins) { int i; byte[] seed; @@ -295,15 +288,15 @@ public byte[] packPublicKey(PolyVec publicKeyPolyVec, byte[] seed) { byte[] buf = new byte[indCpaPublicKeyBytes]; System.arraycopy(publicKeyPolyVec.toBytes(), 0, buf, 0, polyVecBytes); - System.arraycopy(seed, 0, buf, polyVecBytes, KyberEngine.KyberSymBytes); + System.arraycopy(seed, 0, buf, polyVecBytes, MLKEMEngine.KyberSymBytes); return buf; } public byte[] unpackPublicKey(PolyVec publicKeyPolyVec, byte[] publicKey) { - byte[] outputSeed = new byte[KyberEngine.KyberSymBytes]; + byte[] outputSeed = new byte[MLKEMEngine.KyberSymBytes]; publicKeyPolyVec.fromBytes(publicKey); - System.arraycopy(publicKey, polyVecBytes, outputSeed, 0, KyberEngine.KyberSymBytes); + System.arraycopy(publicKey, polyVecBytes, outputSeed, 0, MLKEMEngine.KyberSymBytes); return outputSeed; } @@ -322,7 +315,6 @@ public void unpackSecretKey(PolyVec secretKeyPolyVec, byte[] secretKey) public void generateMatrix(PolyVec[] aMatrix, byte[] seed, boolean transposed) { int i, j, k, ctr, off; - SHAKEDigest kyberXOF; byte[] buf = new byte[KyberGenerateMatrixNBlocks * symmetric.xofBlockBytes + 2]; for (i = 0; i < kyberK; i++) { @@ -339,9 +331,9 @@ public void generateMatrix(PolyVec[] aMatrix, byte[] seed, boolean transposed) symmetric.xofSqueezeBlocks(buf, 0, symmetric.xofBlockBytes * KyberGenerateMatrixNBlocks); int buflen = KyberGenerateMatrixNBlocks * symmetric.xofBlockBytes; - ctr = rejectionSampling(aMatrix[i].getVectorIndex(j), 0, KyberEngine.KyberN, buf, buflen); + ctr = rejectionSampling(aMatrix[i].getVectorIndex(j), 0, MLKEMEngine.KyberN, buf, buflen); - while (ctr < KyberEngine.KyberN) + while (ctr < MLKEMEngine.KyberN) { off = buflen % 3; for (k = 0; k < off; k++) @@ -351,7 +343,7 @@ public void generateMatrix(PolyVec[] aMatrix, byte[] seed, boolean transposed) symmetric.xofSqueezeBlocks(buf, off, symmetric.xofBlockBytes * 2); buflen = off + symmetric.xofBlockBytes; // Error in code Section Unsure - ctr += rejectionSampling(aMatrix[i].getVectorIndex(j), ctr, KyberEngine.KyberN - ctr, buf, buflen); + ctr += rejectionSampling(aMatrix[i].getVectorIndex(j), ctr, MLKEMEngine.KyberN - ctr, buf, buflen); } } } @@ -368,12 +360,12 @@ private static int rejectionSampling(Poly outputBuffer, int coeffOff, int len, b val0 = (short)(((((short)(inpBuf[pos] & 0xFF)) >> 0) | (((short)(inpBuf[pos + 1] & 0xFF)) << 8)) & 0xFFF); val1 = (short)(((((short)(inpBuf[pos + 1] & 0xFF)) >> 4) | (((short)(inpBuf[pos + 2] & 0xFF)) << 4)) & 0xFFF); pos = pos + 3; - if (val0 < (short)KyberEngine.KyberQ) + if (val0 < (short)MLKEMEngine.KyberQ) { outputBuffer.setCoeffIndex(coeffOff + ctr, (short)val0); ctr++; } - if (ctr < len && val1 < (short)KyberEngine.KyberQ) + if (ctr < len && val1 < (short)MLKEMEngine.KyberQ) { outputBuffer.setCoeffIndex(coeffOff + ctr, (short)val1); ctr++; @@ -383,10 +375,9 @@ private static int rejectionSampling(Poly outputBuffer, int coeffOff, int len, b } - public byte[] decrypt(byte[] cipherText, byte[] secretKey) + public byte[] decrypt(byte[] secretKey, byte[] cipherText) { - int i; - byte[] outputMessage = new byte[KyberEngine.getKyberIndCpaMsgBytes()]; + byte[] outputMessage = new byte[MLKEMEngine.getKyberIndCpaMsgBytes()]; PolyVec bp = new PolyVec(engine), secretKeyPolyVec = new PolyVec(engine); Poly v = new Poly(engine), mp = new Poly(engine); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyGenerationParameters.java new file mode 100644 index 0000000000..7d92602345 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyGenerationParameters.java @@ -0,0 +1,24 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class MLKEMKeyGenerationParameters + extends KeyGenerationParameters +{ + private final MLKEMParameters params; + + public MLKEMKeyGenerationParameters( + SecureRandom random, + MLKEMParameters mlkemParameters) + { + super(random, 256); + this.params = mlkemParameters; + } + + public MLKEMParameters getParameters() + { + return params; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyPairGenerator.java new file mode 100644 index 0000000000..22c1d686db --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyPairGenerator.java @@ -0,0 +1,57 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class MLKEMKeyPairGenerator + implements AsymmetricCipherKeyPairGenerator +{ + private MLKEMParameters mlkemParams; + + private SecureRandom random; + + private void initialize( + KeyGenerationParameters param) + { + this.mlkemParams = ((MLKEMKeyGenerationParameters)param).getParameters(); + this.random = param.getRandom(); + + } + + private AsymmetricCipherKeyPair genKeyPair() + { + MLKEMEngine engine = mlkemParams.getEngine(); + + engine.init(random); + + byte[][] keyPair = engine.generateKemKeyPair(); + + MLKEMPublicKeyParameters pubKey = new MLKEMPublicKeyParameters(mlkemParams, keyPair[0], keyPair[1]); + MLKEMPrivateKeyParameters privKey = new MLKEMPrivateKeyParameters(mlkemParams, keyPair[2], keyPair[3], keyPair[4], keyPair[0], keyPair[1], keyPair[5]); + + return new AsymmetricCipherKeyPair(pubKey, privKey); + } + + public void init(KeyGenerationParameters param) + { + this.initialize(param); + } + + public AsymmetricCipherKeyPair generateKeyPair() + { + return genKeyPair(); + } + + public AsymmetricCipherKeyPair internalGenerateKeyPair(byte[] d, byte[] z) + { + byte[][] keyPair = mlkemParams.getEngine().generateKemKeyPairInternal(d, z); + + MLKEMPublicKeyParameters pubKey = new MLKEMPublicKeyParameters(mlkemParams, keyPair[0], keyPair[1]); + MLKEMPrivateKeyParameters privKey = new MLKEMPrivateKeyParameters(mlkemParams, keyPair[2], keyPair[3], keyPair[4], keyPair[0], keyPair[1], keyPair[5]); + + return new AsymmetricCipherKeyPair(pubKey, privKey); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyParameters.java similarity index 51% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyParameters.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyParameters.java index 9fa5567283..227a46c65a 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMKeyParameters.java @@ -1,21 +1,21 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; -public class KyberKeyParameters +public class MLKEMKeyParameters extends AsymmetricKeyParameter { - private KyberParameters params; + private MLKEMParameters params; - public KyberKeyParameters( + public MLKEMKeyParameters( boolean isPrivate, - KyberParameters params) + MLKEMParameters params) { super(isPrivate); this.params = params; } - public KyberParameters getParameters() + public MLKEMParameters getParameters() { return params; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMParameters.java new file mode 100644 index 0000000000..0dbc69bece --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMParameters.java @@ -0,0 +1,37 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import org.bouncycastle.pqc.crypto.KEMParameters; + +public class MLKEMParameters + implements KEMParameters +{ + public static final MLKEMParameters ml_kem_512 = new MLKEMParameters("ML-KEM-512", 2, 256); + public static final MLKEMParameters ml_kem_768 = new MLKEMParameters("ML-KEM-768", 3, 256); + public static final MLKEMParameters ml_kem_1024 = new MLKEMParameters("ML-KEM-1024", 4, 256); + + private final String name; + private final int k; + private final int sessionKeySize; + + private MLKEMParameters(String name, int k, int sessionKeySize) + { + this.name = name; + this.k = k; + this.sessionKeySize = sessionKeySize; + } + + public String getName() + { + return name; + } + + public MLKEMEngine getEngine() + { + return new MLKEMEngine(k); + } + + public int getSessionKeySize() + { + return sessionKeySize; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMPrivateKeyParameters.java new file mode 100644 index 0000000000..596bb9d864 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMPrivateKeyParameters.java @@ -0,0 +1,176 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import org.bouncycastle.util.Arrays; + +public class MLKEMPrivateKeyParameters + extends MLKEMKeyParameters +{ + public static final int BOTH = 0; + public static final int SEED_ONLY = 1; + public static final int EXPANDED_KEY = 2; + + final byte[] s; + final byte[] hpk; + final byte[] nonce; + final byte[] t; + final byte[] rho; + final byte[] seed; + + private final int prefFormat; + + public MLKEMPrivateKeyParameters(MLKEMParameters params, byte[] s, byte[] hpk, byte[] nonce, byte[] t, byte[] rho) + { + this(params, s, hpk, nonce, t, rho, null); + } + + public MLKEMPrivateKeyParameters(MLKEMParameters params, byte[] s, byte[] hpk, byte[] nonce, byte[] t, byte[] rho, byte[] seed) + { + super(true, params); + + this.s = Arrays.clone(s); + this.hpk = Arrays.clone(hpk); + this.nonce = Arrays.clone(nonce); + this.t = Arrays.clone(t); + this.rho = Arrays.clone(rho); + this.seed = Arrays.clone(seed); + this.prefFormat = BOTH; + } + + public MLKEMPrivateKeyParameters(MLKEMParameters params, byte[] encoding) + { + this(params, encoding, null); + } + + public MLKEMPrivateKeyParameters(MLKEMParameters params, byte[] encoding, MLKEMPublicKeyParameters pubKey) + { + super(true, params); + + MLKEMEngine eng = params.getEngine(); + if (encoding.length == MLKEMEngine.KyberSymBytes * 2) + { + byte[][] keyData = eng.generateKemKeyPairInternal( + Arrays.copyOfRange(encoding, 0, MLKEMEngine.KyberSymBytes), + Arrays.copyOfRange(encoding, MLKEMEngine.KyberSymBytes, encoding.length)); + this.s = keyData[2]; + this.hpk = keyData[3]; + this.nonce = keyData[4]; + this.t = keyData[0]; + this.rho = keyData[1]; + this.seed = keyData[5]; + } + else + { + int index = 0; + this.s = Arrays.copyOfRange(encoding, 0, eng.getKyberIndCpaSecretKeyBytes()); + index += eng.getKyberIndCpaSecretKeyBytes(); + this.t = Arrays.copyOfRange(encoding, index, index + eng.getKyberIndCpaPublicKeyBytes() - MLKEMEngine.KyberSymBytes); + index += eng.getKyberIndCpaPublicKeyBytes() - MLKEMEngine.KyberSymBytes; + this.rho = Arrays.copyOfRange(encoding, index, index + 32); + index += 32; + this.hpk = Arrays.copyOfRange(encoding, index, index + 32); + index += 32; + this.nonce = Arrays.copyOfRange(encoding, index, index + MLKEMEngine.KyberSymBytes); + this.seed = null; + } + + if (pubKey != null) + { + if (!Arrays.constantTimeAreEqual(this.t, pubKey.t) || !Arrays.constantTimeAreEqual(this.rho, pubKey.rho)) + { + throw new IllegalArgumentException("passed in public key does not match private values"); + } + } + + this.prefFormat = (seed == null) ? EXPANDED_KEY : BOTH; + } + + private MLKEMPrivateKeyParameters(MLKEMPrivateKeyParameters params, int preferredFormat) + { + super(true, params.getParameters()); + + this.s = params.s; + this.t = params.t; + this.rho = params.rho; + this.hpk = params.hpk; + this.nonce = params.nonce; + this.seed = params.seed; + this.prefFormat = preferredFormat; + } + + public MLKEMPrivateKeyParameters getParametersWithFormat(int format) + { + if (this.prefFormat == format) + { + return this; + } + + switch (format) + { + case BOTH: + case SEED_ONLY: + { + if (this.seed == null) + { + throw new IllegalStateException("no seed available"); + } + break; + } + case EXPANDED_KEY: + break; + default: + throw new IllegalArgumentException("unknown format"); + } + + return new MLKEMPrivateKeyParameters(this, format); + } + + public int getPreferredFormat() + { + return prefFormat; + } + + public byte[] getEncoded() + { + return Arrays.concatenate(new byte[][]{ s, t, rho, hpk, nonce }); + } + + public byte[] getHPK() + { + return Arrays.clone(hpk); + } + + public byte[] getNonce() + { + return Arrays.clone(nonce); + } + + public byte[] getPublicKey() + { + return MLKEMPublicKeyParameters.getEncoded(t, rho); + } + + public MLKEMPublicKeyParameters getPublicKeyParameters() + { + return new MLKEMPublicKeyParameters(getParameters(), t, rho); + } + + public byte[] getRho() + { + return Arrays.clone(rho); + } + + public byte[] getS() + { + return Arrays.clone(s); + } + + public byte[] getT() + { + return Arrays.clone(t); + } + + public byte[] getSeed() + { + return Arrays.clone(seed); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMPublicKeyParameters.java similarity index 61% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberPublicKeyParameters.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMPublicKeyParameters.java index e51a5f4519..5f2676d730 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/KyberPublicKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/MLKEMPublicKeyParameters.java @@ -1,9 +1,9 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; import org.bouncycastle.util.Arrays; -public class KyberPublicKeyParameters - extends KyberKeyParameters +public class MLKEMPublicKeyParameters + extends MLKEMKeyParameters { static byte[] getEncoded(byte[] t, byte[] rho) { @@ -13,18 +13,18 @@ static byte[] getEncoded(byte[] t, byte[] rho) final byte[] t; final byte[] rho; - public KyberPublicKeyParameters(KyberParameters params, byte[] t, byte[] rho) + public MLKEMPublicKeyParameters(MLKEMParameters params, byte[] t, byte[] rho) { super(false, params); this.t = Arrays.clone(t); this.rho = Arrays.clone(rho); } - public KyberPublicKeyParameters(KyberParameters params, byte[] encoding) + public MLKEMPublicKeyParameters(MLKEMParameters params, byte[] encoding) { super(false, params); - this.t = Arrays.copyOfRange(encoding, 0, encoding.length - KyberEngine.KyberSymBytes); - this.rho = Arrays.copyOfRange(encoding, encoding.length - KyberEngine.KyberSymBytes, encoding.length); + this.t = Arrays.copyOfRange(encoding, 0, encoding.length - MLKEMEngine.KyberSymBytes); + this.rho = Arrays.copyOfRange(encoding, encoding.length - MLKEMEngine.KyberSymBytes, encoding.length); } public byte[] getEncoded() @@ -32,12 +32,6 @@ public byte[] getEncoded() return getEncoded(t, rho); } - /** @deprecated Use {@link #getEncoded()} instead. */ - public byte[] getPublicKey() - { - return getEncoded(); - } - public byte[] getRho() { return Arrays.clone(rho); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Ntt.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Ntt.java similarity index 94% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Ntt.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Ntt.java index c16cf71637..100647de08 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Ntt.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Ntt.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; class Ntt { @@ -29,7 +29,7 @@ class Ntt public static short[] ntt(short[] inp) { - short[] r = new short[KyberEngine.KyberN]; + short[] r = new short[MLKEMEngine.KyberN]; System.arraycopy(inp, 0, r, 0, r.length); int len, start, j, k; short t, zeta; @@ -53,8 +53,8 @@ public static short[] ntt(short[] inp) public static short[] invNtt(short[] inp) { - short[] r = new short[KyberEngine.KyberN]; - System.arraycopy(inp, 0, r, 0, KyberEngine.KyberN); + short[] r = new short[MLKEMEngine.KyberN]; + System.arraycopy(inp, 0, r, 0, MLKEMEngine.KyberN); int len, start, j, k; short t, zeta; k = 0; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Poly.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Poly.java similarity index 80% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Poly.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Poly.java index ab46fedbd7..d7402a5ea7 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Poly.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Poly.java @@ -1,22 +1,22 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; class Poly { private short[] coeffs; - private KyberEngine engine; + private MLKEMEngine engine; private int polyCompressedBytes; private int eta1; private int eta2; private Symmetric symmetric; - public Poly(KyberEngine engine) + public Poly(MLKEMEngine engine) { - this.coeffs = new short[KyberEngine.KyberN]; + this.coeffs = new short[MLKEMEngine.KyberN]; this.engine = engine; polyCompressedBytes = engine.getKyberPolyCompressedBytes(); this.eta1 = engine.getKyberEta1(); - this.eta2 = KyberEngine.getKyberEta2(); + this.eta2 = MLKEMEngine.getKyberEta2(); this.symmetric = engine.getSymmetric(); } @@ -54,7 +54,7 @@ public void polyInverseNttToMont() public void reduce() { int i; - for (i = 0; i < KyberEngine.KyberN; i++) + for (i = 0; i < MLKEMEngine.KyberN; i++) { this.setCoeffIndex(i, Reduce.barretReduce(this.getCoeffIndex(i))); } @@ -63,7 +63,7 @@ public void reduce() public static void baseMultMontgomery(Poly r, Poly a, Poly b) { int i; - for (i = 0; i < KyberEngine.KyberN / 4; i++) + for (i = 0; i < MLKEMEngine.KyberN / 4; i++) { Ntt.baseMult(r, 4 * i, a.getCoeffIndex(4 * i), a.getCoeffIndex(4 * i + 1), @@ -79,7 +79,7 @@ public static void baseMultMontgomery(Poly r, Poly a, Poly b) public void addCoeffs(Poly b) { int i; - for (i = 0; i < KyberEngine.KyberN; i++) + for (i = 0; i < MLKEMEngine.KyberN; i++) { this.setCoeffIndex(i, (short)(this.getCoeffIndex(i) + b.getCoeffIndex(i))); } @@ -88,8 +88,8 @@ public void addCoeffs(Poly b) public void convertToMont() { int i; - final short f = (short)(((long)1 << 32) % KyberEngine.KyberQ); - for (i = 0; i < KyberEngine.KyberN; i++) + final short f = (short)(((long)1 << 32) % MLKEMEngine.KyberQ); + for (i = 0; i < MLKEMEngine.KyberN; i++) { this.setCoeffIndex(i, Reduce.montgomeryReduce(this.getCoeffIndex(i) * f)); } @@ -109,7 +109,7 @@ public byte[] compressPoly() if (polyCompressedBytes == 128) { - for (i = 0; i < KyberEngine.KyberN / 8; i++) + for (i = 0; i < MLKEMEngine.KyberN / 8; i++) { for (j = 0; j < 8; j++) { @@ -139,7 +139,7 @@ public byte[] compressPoly() } else if (polyCompressedBytes == 160) { - for (i = 0; i < KyberEngine.KyberN / 8; i++) + for (i = 0; i < MLKEMEngine.KyberN / 8; i++) { for (j = 0; j < 8; j++) { @@ -186,10 +186,10 @@ public void decompressPoly(byte[] compressedPolyCipherText) if (engine.getKyberPolyCompressedBytes() == 128) { - for (i = 0; i < KyberEngine.KyberN / 2; i++) + for (i = 0; i < MLKEMEngine.KyberN / 2; i++) { - this.setCoeffIndex(2 * i + 0, (short)((((short)((compressedPolyCipherText[count] & 0xFF) & 15) * KyberEngine.KyberQ) + 8) >> 4)); - this.setCoeffIndex(2 * i + 1, (short)((((short)((compressedPolyCipherText[count] & 0xFF) >> 4) * KyberEngine.KyberQ) + 8) >> 4)); + this.setCoeffIndex(2 * i + 0, (short)((((short)((compressedPolyCipherText[count] & 0xFF) & 15) * MLKEMEngine.KyberQ) + 8) >> 4)); + this.setCoeffIndex(2 * i + 1, (short)((((short)((compressedPolyCipherText[count] & 0xFF) >> 4) * MLKEMEngine.KyberQ) + 8) >> 4)); count += 1; } } @@ -197,7 +197,7 @@ else if (engine.getKyberPolyCompressedBytes() == 160) { int j; byte[] t = new byte[8]; - for (i = 0; i < KyberEngine.KyberN / 8; i++) + for (i = 0; i < MLKEMEngine.KyberN / 8; i++) { t[0] = (byte)((compressedPolyCipherText[count + 0] & 0xFF) >> 0); t[1] = (byte)(((compressedPolyCipherText[count + 0] & 0xFF) >> 5) | ((compressedPolyCipherText[count + 1] & 0xFF) << 3)); @@ -210,7 +210,7 @@ else if (engine.getKyberPolyCompressedBytes() == 160) count += 5; for (j = 0; j < 8; j++) { - this.setCoeffIndex(8 * i + j, (short)(((t[j] & 31) * KyberEngine.KyberQ + 16) >> 5)); + this.setCoeffIndex(8 * i + j, (short)(((t[j] & 31) * MLKEMEngine.KyberQ + 16) >> 5)); } } } @@ -223,10 +223,10 @@ else if (engine.getKyberPolyCompressedBytes() == 160) public byte[] toBytes() { - byte[] r = new byte[KyberEngine.KyberPolyBytes]; + byte[] r = new byte[MLKEMEngine.KyberPolyBytes]; short t0, t1; this.conditionalSubQ(); - for (int i = 0; i < KyberEngine.KyberN / 2; i++) + for (int i = 0; i < MLKEMEngine.KyberN / 2; i++) { t0 = this.getCoeffIndex(2 * i); t1 = this.getCoeffIndex(2 * i + 1); @@ -242,7 +242,7 @@ public byte[] toBytes() public void fromBytes(byte[] inpBytes) { int i; - for (i = 0; i < KyberEngine.KyberN / 2; i++) + for (i = 0; i < MLKEMEngine.KyberN / 2; i++) { this.setCoeffIndex(2 * i, (short)( ( @@ -261,25 +261,24 @@ public void fromBytes(byte[] inpBytes) public byte[] toMsg() { - byte[] outMsg = new byte[KyberEngine.getKyberIndCpaMsgBytes()]; + int LOWER = MLKEMEngine.KyberQ >>> 2; + int UPPER = MLKEMEngine.KyberQ - LOWER; + + byte[] outMsg = new byte[MLKEMEngine.getKyberIndCpaMsgBytes()]; this.conditionalSubQ(); - for (int i = 0; i < KyberEngine.KyberN / 8; i++) + for (int i = 0; i < MLKEMEngine.KyberN / 8; i++) { outMsg[i] = 0; for (int j = 0; j < 8; j++) { -// short t = (short)(((((short)(this.getCoeffIndex(8 * i + j) << 1) + KyberEngine.KyberQ / 2) / KyberEngine.KyberQ) & 1)); -// outMsg[i] |= (byte)(t << j); - // we've done it like this as there is a chance a division instruction might - // get generated introducing a timing signal on the secret input - int t = this.getCoeffIndex(8 * i + j) & 0xFFFF; - t <<= 1; - t += 1665; - t *= 80635; - t >>= 28; - t &= 1; + int c_j = this.getCoeffIndex(8 * i + j); + + // KyberSlash: division by Q is not constant time. +// int t = (((c_j << 1) + (KyberEngine.KyberQ / 2)) / KyberEngine.KyberQ) & 1; + int t = ((LOWER - c_j) & (c_j - UPPER)) >>> 31; + outMsg[i] |= (byte)(t << j); } } @@ -290,16 +289,16 @@ public void fromMsg(byte[] msg) { int i, j; short mask; - if (msg.length != KyberEngine.KyberN / 8) + if (msg.length != MLKEMEngine.KyberN / 8) { throw new RuntimeException("KYBER_INDCPA_MSGBYTES must be equal to KYBER_N/8 bytes!"); } - for (i = 0; i < KyberEngine.KyberN / 8; i++) + for (i = 0; i < MLKEMEngine.KyberN / 8; i++) { for (j = 0; j < 8; j++) { mask = (short)((-1) * (short)(((msg[i] & 0xFF) >> j) & 1)); - this.setCoeffIndex(8 * i + j, (short)(mask & (short)((KyberEngine.KyberQ + 1) / 2))); + this.setCoeffIndex(8 * i + j, (short)(mask & (short)((MLKEMEngine.KyberQ + 1) / 2))); } } } @@ -307,7 +306,7 @@ public void fromMsg(byte[] msg) public void conditionalSubQ() { int i; - for (i = 0; i < KyberEngine.KyberN; i++) + for (i = 0; i < MLKEMEngine.KyberN; i++) { this.setCoeffIndex(i, Reduce.conditionalSubQ(this.getCoeffIndex(i))); } @@ -315,22 +314,22 @@ public void conditionalSubQ() public void getEta1Noise(byte[] seed, byte nonce) { - byte[] buf = new byte[KyberEngine.KyberN * eta1 / 4]; + byte[] buf = new byte[MLKEMEngine.KyberN * eta1 / 4]; symmetric.prf(buf, seed, nonce); - CBD.kyberCBD(this, buf, eta1); + CBD.mlkemCBD(this, buf, eta1); } public void getEta2Noise(byte[] seed, byte nonce) { - byte[] buf = new byte[KyberEngine.KyberN * eta2 / 4]; + byte[] buf = new byte[MLKEMEngine.KyberN * eta2 / 4]; symmetric.prf(buf, seed, nonce); - CBD.kyberCBD(this, buf, eta2); + CBD.mlkemCBD(this, buf, eta2); } public void polySubtract(Poly b) { int i; - for (i = 0; i < KyberEngine.KyberN; i++) + for (i = 0; i < MLKEMEngine.KyberN; i++) { this.setCoeffIndex(i, (short)(b.getCoeffIndex(i) - this.getCoeffIndex(i))); } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/PolyVec.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/PolyVec.java similarity index 92% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/PolyVec.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/PolyVec.java index e1ca688a73..d6613e904f 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/PolyVec.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/PolyVec.java @@ -1,15 +1,15 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; import org.bouncycastle.util.Arrays; class PolyVec { Poly[] vec; - private KyberEngine engine; + private MLKEMEngine engine; private int kyberK; private int polyVecBytes; - public PolyVec(KyberEngine engine) + public PolyVec(MLKEMEngine engine) { this.engine = engine; this.kyberK = engine.getKyberK(); @@ -63,7 +63,7 @@ public byte[] compressPolyVec() t = new short[4]; for (i = 0; i < kyberK; i++) { - for (j = 0; j < KyberEngine.KyberN / 4; j++) + for (j = 0; j < MLKEMEngine.KyberN / 4; j++) { for (k = 0; k < 4; k++) { @@ -98,7 +98,7 @@ else if (engine.getKyberPolyVecCompressedBytes() == kyberK * 352) t = new short[8]; for (i = 0; i < kyberK; i++) { - for (j = 0; j < KyberEngine.KyberN / 8; j++) + for (j = 0; j < MLKEMEngine.KyberN / 8; j++) { for (k = 0; k < 8; k++) { @@ -150,7 +150,7 @@ public void decompressPolyVec(byte[] compressedPolyVecCipherText) short[] t = new short[4]; for (i = 0; i < kyberK; i++) { - for (j = 0; j < KyberEngine.KyberN / 4; j++) + for (j = 0; j < MLKEMEngine.KyberN / 4; j++) { t[0] = (short)(((compressedPolyVecCipherText[count] & 0xFF) >> 0) | (short)((compressedPolyVecCipherText[count + 1] & 0xFF) << 8)); t[1] = (short)(((compressedPolyVecCipherText[count + 1] & 0xFF) >> 2) | (short)((compressedPolyVecCipherText[count + 2] & 0xFF) << 6)); @@ -159,7 +159,7 @@ public void decompressPolyVec(byte[] compressedPolyVecCipherText) count += 5; for (k = 0; k < 4; k++) { - this.vec[i].setCoeffIndex(4 * j + k, (short)(((t[k] & 0x3FF) * KyberEngine.KyberQ + 512) >> 10)); + this.vec[i].setCoeffIndex(4 * j + k, (short)(((t[k] & 0x3FF) * MLKEMEngine.KyberQ + 512) >> 10)); } } @@ -171,7 +171,7 @@ else if (engine.getKyberPolyVecCompressedBytes() == (kyberK * 352)) short[] t = new short[8]; for (i = 0; i < kyberK; i++) { - for (j = 0; j < KyberEngine.KyberN / 8; j++) + for (j = 0; j < MLKEMEngine.KyberN / 8; j++) { t[0] = (short)(((compressedPolyVecCipherText[count] & 0xFF) >> 0) | ((short)(compressedPolyVecCipherText[count + 1] & 0xFF) << 8)); t[1] = (short)(((compressedPolyVecCipherText[count + 1] & 0xFF) >> 3) | ((short)(compressedPolyVecCipherText[count + 2] & 0xFF) << 5)); @@ -184,7 +184,7 @@ else if (engine.getKyberPolyVecCompressedBytes() == (kyberK * 352)) count += 11; for (k = 0; k < 8; k++) { - this.vec[i].setCoeffIndex(8 * j + k, (short)(((t[k] & 0x7FF) * KyberEngine.KyberQ + 1024) >> 11)); + this.vec[i].setCoeffIndex(8 * j + k, (short)(((t[k] & 0x7FF) * MLKEMEngine.KyberQ + 1024) >> 11)); } } } @@ -195,7 +195,7 @@ else if (engine.getKyberPolyVecCompressedBytes() == (kyberK * 352)) } } - public static void pointwiseAccountMontgomery(Poly out, PolyVec inp1, PolyVec inp2, KyberEngine engine) + public static void pointwiseAccountMontgomery(Poly out, PolyVec inp1, PolyVec inp2, MLKEMEngine engine) { int i; Poly t = new Poly(engine); @@ -232,7 +232,7 @@ public byte[] toBytes() byte[] r = new byte[polyVecBytes]; for (int i = 0; i < kyberK; i++) { - System.arraycopy(this.vec[i].toBytes(), 0, r, i * KyberEngine.KyberPolyBytes, KyberEngine.KyberPolyBytes); + System.arraycopy(this.vec[i].toBytes(), 0, r, i * MLKEMEngine.KyberPolyBytes, MLKEMEngine.KyberPolyBytes); } return r; @@ -242,7 +242,7 @@ public void fromBytes(byte[] inputBytes) { for (int i = 0; i < kyberK; i++) { - this.getVectorIndex(i).fromBytes(Arrays.copyOfRange(inputBytes, i * KyberEngine.KyberPolyBytes, (i + 1) * KyberEngine.KyberPolyBytes)); + this.getVectorIndex(i).fromBytes(Arrays.copyOfRange(inputBytes, i * MLKEMEngine.KyberPolyBytes, (i + 1) * MLKEMEngine.KyberPolyBytes)); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Reduce.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Reduce.java similarity index 55% rename from core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Reduce.java rename to core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Reduce.java index c852a13e1d..c0b51d2c07 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/crystals/kyber/Reduce.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Reduce.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.crystals.kyber; +package org.bouncycastle.pqc.crypto.mlkem; class Reduce { @@ -8,8 +8,8 @@ public static short montgomeryReduce(int a) int t; short u; - u = (short)(a * KyberEngine.KyberQinv); - t = (int)(u * KyberEngine.KyberQ); + u = (short)(a * MLKEMEngine.KyberQinv); + t = (int)(u * MLKEMEngine.KyberQ); t = a - t; t >>= 16; return (short)t; @@ -19,16 +19,16 @@ public static short barretReduce(short a) { short t; long shift = (((long)1) << 26); - short v = (short)((shift + (KyberEngine.KyberQ / 2)) / KyberEngine.KyberQ); + short v = (short)((shift + (MLKEMEngine.KyberQ / 2)) / MLKEMEngine.KyberQ); t = (short)((v * a) >> 26); - t = (short)(t * KyberEngine.KyberQ); + t = (short)(t * MLKEMEngine.KyberQ); return (short)(a - t); } public static short conditionalSubQ(short a) { - a -= KyberEngine.KyberQ; - a += (a >> 15) & KyberEngine.KyberQ; + a -= MLKEMEngine.KyberQ; + a += (a >> 15) & MLKEMEngine.KyberQ; return a; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Symmetric.java b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Symmetric.java new file mode 100644 index 0000000000..40c309dedf --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/mlkem/Symmetric.java @@ -0,0 +1,94 @@ +package org.bouncycastle.pqc.crypto.mlkem; + +import org.bouncycastle.crypto.digests.SHA3Digest; +import org.bouncycastle.crypto.digests.SHAKEDigest; + +abstract class Symmetric +{ + + final int xofBlockBytes; + + abstract void hash_h(byte[] out, byte[] in, int outOffset); + + abstract void hash_g(byte[] out, byte[] in); + + abstract void xofAbsorb(byte[] seed, byte x, byte y); + + abstract void xofSqueezeBlocks(byte[] out, int outOffset, int outLen); + + abstract void prf(byte[] out, byte[] key, byte nonce); + + abstract void kdf(byte[] out, byte[] in); + + Symmetric(int blockBytes) + { + this.xofBlockBytes = blockBytes; + } + + + static class ShakeSymmetric + extends Symmetric + { + private final SHAKEDigest xof; + private final SHA3Digest sha3Digest512; + private final SHA3Digest sha3Digest256; + private final SHAKEDigest shakeDigest; + + ShakeSymmetric() + { + super(168); + this.xof = new SHAKEDigest(128); + this.shakeDigest = new SHAKEDigest(256); + this.sha3Digest256 = new SHA3Digest(256); + this.sha3Digest512 = new SHA3Digest(512); + } + + @Override + void hash_h(byte[] out, byte[] in, int outOffset) + { + sha3Digest256.update(in, 0, in.length); + sha3Digest256.doFinal(out, outOffset); + } + + @Override + void hash_g(byte[] out, byte[] in) + { + sha3Digest512.update(in, 0, in.length); + sha3Digest512.doFinal(out, 0); + } + + @Override + void xofAbsorb(byte[] seed, byte a, byte b) + { + xof.reset(); + byte[] buf = new byte[seed.length + 2]; + System.arraycopy(seed, 0, buf, 0, seed.length); + buf[seed.length] = a; + buf[seed.length + 1] = b; + xof.update(buf, 0, seed.length + 2); + } + + @Override + void xofSqueezeBlocks(byte[] out, int outOffset, int outLen) + { + xof.doOutput(out, outOffset, outLen); + } + + @Override + void prf(byte[] out, byte[] seed, byte nonce) + { + byte[] extSeed = new byte[seed.length + 1]; + System.arraycopy(seed, 0, extSeed, 0, seed.length); + extSeed[seed.length] = nonce; + shakeDigest.update(extSeed, 0, extSeed.length); + shakeDigest.doFinal(out, 0, out.length); + } + + @Override + void kdf(byte[] out, byte[] in) + { + shakeDigest.update(in, 0, in.length); + shakeDigest.doFinal(out, 0, out.length); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/newhope/package-info.java b/core/src/main/java/org/bouncycastle/pqc/crypto/newhope/package-info.java new file mode 100644 index 0000000000..c6a07b174d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/newhope/package-info.java @@ -0,0 +1,4 @@ +/** + * Low level implementation of the NewHope key exchange algorithm. + */ +package org.bouncycastle.pqc.crypto.newhope; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMExtractor.java b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMExtractor.java index fc50f1800d..b6b0b13b51 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMExtractor.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMExtractor.java @@ -11,7 +11,6 @@ public class NTRUKEMExtractor implements EncapsulatedSecretExtractor { - private final NTRUParameters params; private final NTRUPrivateKeyParameters ntruPrivateKey; /** @@ -22,53 +21,50 @@ public class NTRUKEMExtractor */ public NTRUKEMExtractor(NTRUPrivateKeyParameters ntruPrivateKey) { - this.params = ntruPrivateKey.getParameters(); + if (ntruPrivateKey == null) + { + throw new NullPointerException("'ntruPrivateKey' cannot be null"); + } + this.ntruPrivateKey = ntruPrivateKey; } - - @Override public byte[] extractSecret(byte[] encapsulation) { -// assert this.ntruPrivateKey != null; - NTRUParameterSet parameterSet = this.params.parameterSet; + NTRUParameterSet parameterSet = ntruPrivateKey.getParameters().getParameterSet(); + + if (encapsulation == null) + { + throw new NullPointerException("'encapsulation' cannot be null"); + } + if (encapsulation.length != parameterSet.ntruCiphertextBytes()) + { + throw new IllegalArgumentException("encapsulation"); + } byte[] sk = this.ntruPrivateKey.privateKey; - int i, fail; - byte[] rm; - byte[] buf = new byte[parameterSet.prfKeyBytes() + parameterSet.ntruCiphertextBytes()]; NTRUOWCPA owcpa = new NTRUOWCPA(parameterSet); - OWCPADecryptResult owcpaResult = owcpa.decrypt(encapsulation, ntruPrivateKey.privateKey); - rm = owcpaResult.rm; - fail = owcpaResult.fail; + OWCPADecryptResult owcpaResult = owcpa.decrypt(encapsulation, sk); + byte[] rm = owcpaResult.rm; + int fail = owcpaResult.fail; /* If fail = 0 then c = Enc(h, rm). There is no need to re-encapsulate. */ /* See comment in owcpa_dec for details. */ SHA3Digest sha3256 = new SHA3Digest(256); - byte[] k = new byte[sha3256.getDigestSize()]; sha3256.update(rm, 0, rm.length); sha3256.doFinal(k, 0); /* shake(secret PRF key || input ciphertext) */ - for (i = 0; i < parameterSet.prfKeyBytes(); i++) - { - buf[i] = sk[i + parameterSet.owcpaSecretKeyBytes()]; - } - for (i = 0; i < parameterSet.ntruCiphertextBytes(); i++) - { - buf[parameterSet.prfKeyBytes() + i] = encapsulation[i]; - } - sha3256.reset(); - sha3256.update(buf, 0, buf.length); + sha3256.update(sk, parameterSet.owcpaSecretKeyBytes(), parameterSet.prfKeyBytes()); + sha3256.update(encapsulation, 0, encapsulation.length); sha3256.doFinal(rm, 0); cmov(k, rm, (byte)fail); byte[] sharedKey = Arrays.copyOfRange(k, 0, parameterSet.sharedKeyBytes()); - Arrays.clear(k); return sharedKey; @@ -85,6 +81,6 @@ private void cmov(byte[] r, byte[] x, byte b) public int getEncapsulationLength() { - return params.parameterSet.ntruCiphertextBytes(); + return ntruPrivateKey.getParameters().getParameterSet().ntruCiphertextBytes(); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMGenerator.java index cfee683d2e..43d9c98219 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKEMGenerator.java @@ -29,44 +29,51 @@ public class NTRUKEMGenerator */ public NTRUKEMGenerator(SecureRandom random) { + if (random == null) + { + throw new NullPointerException("'random' cannot be null"); + } + this.random = random; } public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recipientKey) { - NTRUParameterSet parameterSet = ((NTRUPublicKeyParameters)recipientKey).getParameters().parameterSet; + if (recipientKey == null) + { + throw new NullPointerException("'recipientKey' cannot be null"); + } + + NTRUPublicKeyParameters publicKey = (NTRUPublicKeyParameters)recipientKey; + + NTRUParameterSet parameterSet = publicKey.getParameters().getParameterSet(); NTRUSampling sampling = new NTRUSampling(parameterSet); NTRUOWCPA owcpa = new NTRUOWCPA(parameterSet); - Polynomial r; - Polynomial m; byte[] rm = new byte[parameterSet.owcpaMsgBytes()]; byte[] rmSeed = new byte[parameterSet.sampleRmBytes()]; random.nextBytes(rmSeed); PolynomialPair pair = sampling.sampleRm(rmSeed); - r = pair.r(); - m = pair.m(); + Polynomial r = pair.r(); + Polynomial m = pair.m(); - byte[] rm1 = r.s3ToBytes(parameterSet.owcpaMsgBytes()); - System.arraycopy(rm1, 0, rm, 0, rm1.length); - byte[] rm2 = m.s3ToBytes(rm.length - parameterSet.packTrinaryBytes()); - System.arraycopy(rm2, 0, rm, parameterSet.packTrinaryBytes(), rm2.length); + r.s3ToBytes(rm, 0); + m.s3ToBytes(rm, parameterSet.packTrinaryBytes()); SHA3Digest sha3256 = new SHA3Digest(256); - sha3256.update(rm, 0, rm.length); - byte[] k = new byte[sha3256.getDigestSize()]; + sha3256.update(rm, 0, rm.length); sha3256.doFinal(k, 0); r.z3ToZq(); - byte[] c = owcpa.encrypt(r, m, ((NTRUPublicKeyParameters)recipientKey).publicKey); - byte[] sharedKey = Arrays.copyOfRange(k, 0, parameterSet.sharedKeyBytes()); + byte[] c = owcpa.encrypt(r, m, publicKey.publicKey); + byte[] sharedKey = Arrays.copyOfRange(k, 0, parameterSet.sharedKeyBytes()); Arrays.clear(k); - + return new SecretWithEncapsulationImpl(sharedKey, c); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKeyPairGenerator.java index 381c7cb534..64c4590958 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKeyPairGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUKeyPairGenerator.java @@ -6,6 +6,7 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; import org.bouncycastle.crypto.KeyGenerationParameters; import org.bouncycastle.pqc.math.ntru.parameters.NTRUParameterSet; +import org.bouncycastle.util.Arrays; /** * Key generator for NTRU. @@ -19,32 +20,31 @@ public class NTRUKeyPairGenerator private NTRUKeyGenerationParameters params; private SecureRandom random; - @Override public void init(KeyGenerationParameters param) { this.params = (NTRUKeyGenerationParameters)param; this.random = param.getRandom(); } - @Override public AsymmetricCipherKeyPair generateKeyPair() { -// assert this.random != null; - NTRUParameterSet parameterSet = this.params.getParameters().parameterSet; + NTRUParameters parameters = params.getParameters(); + NTRUParameterSet parameterSet = parameters.getParameterSet(); + byte[] seed = new byte[parameterSet.sampleFgBytes()]; random.nextBytes(seed); NTRUOWCPA owcpa = new NTRUOWCPA(parameterSet); OWCPAKeyPair owcpaKeys = owcpa.keypair(seed); + byte[] publicKey = owcpaKeys.publicKey; - byte[] privateKey = new byte[parameterSet.ntruSecretKeyBytes()]; - byte[] owcpaPrivateKey = owcpaKeys.privateKey; - System.arraycopy(owcpaPrivateKey, 0, privateKey, 0, owcpaPrivateKey.length); byte[] prfBytes = new byte[parameterSet.prfKeyBytes()]; random.nextBytes(prfBytes); - System.arraycopy(prfBytes, 0, privateKey, parameterSet.owcpaSecretKeyBytes(), prfBytes.length); + byte[] privateKey = Arrays.concatenate(owcpaKeys.privateKey, prfBytes); - return new AsymmetricCipherKeyPair(new NTRUPublicKeyParameters(params.getParameters(), publicKey), new NTRUPrivateKeyParameters(params.getParameters(), privateKey)); + return new AsymmetricCipherKeyPair( + new NTRUPublicKeyParameters(parameters, publicKey), + new NTRUPrivateKeyParameters(parameters, privateKey)); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUOWCPA.java b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUOWCPA.java index 2e9b7e63c6..1590a9a4e3 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUOWCPA.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUOWCPA.java @@ -52,10 +52,8 @@ public OWCPAKeyPair keypair(byte[] seed) g = pair.g(); invfMod3.s3Inv(f); - byte[] fs3ToBytes = f.s3ToBytes(params.owcpaMsgBytes()); - System.arraycopy(fs3ToBytes, 0, privateKey, 0, fs3ToBytes.length); - byte[] s3Res = invfMod3.s3ToBytes(privateKey.length - this.params.packTrinaryBytes()); - System.arraycopy(s3Res, 0, privateKey, this.params.packTrinaryBytes(), s3Res.length); + f.s3ToBytes(privateKey, 0); + invfMod3.s3ToBytes(privateKey, params.packTrinaryBytes()); f.z3ToZq(); g.z3ToZq(); @@ -152,7 +150,7 @@ public OWCPADecryptResult decrypt(byte[] ciphertext, byte[] privateKey) finv3.s3FromBytes(Arrays.copyOfRange(sk, params.packTrinaryBytes(), sk.length)); m.s3Mul(mf, finv3); - byte[] arr1 = m.s3ToBytes(rm.length - params.packTrinaryBytes()); + m.s3ToBytes(rm, params.packTrinaryBytes()); fail = 0; @@ -193,9 +191,7 @@ public OWCPADecryptResult decrypt(byte[] ciphertext, byte[] privateKey) fail |= checkR(r); r.trinaryZqToZ3(); - byte[] arr2 = r.s3ToBytes(params.owcpaMsgBytes()); - System.arraycopy(arr2, 0, rm, 0, arr2.length); - System.arraycopy(arr1, 0, rm, params.packTrinaryBytes(), arr1.length); + r.s3ToBytes(rm, 0); return new OWCPADecryptResult(rm, fail); } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUParameters.java index 2d8582496a..c334f0cc8a 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/ntru/NTRUParameters.java @@ -1,6 +1,5 @@ package org.bouncycastle.pqc.crypto.ntru; -import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.pqc.crypto.KEMParameters; import org.bouncycastle.pqc.math.ntru.parameters.NTRUHPS2048509; import org.bouncycastle.pqc.math.ntru.parameters.NTRUHPS2048677; @@ -45,10 +44,7 @@ public class NTRUParameters public static final NTRUParameters ntruhrss1373 = new NTRUParameters("ntruhrss1373", new NTRUHRSS1373()); private final String name; - /** - * Currently selected parameter set - */ - final NTRUParameterSet parameterSet; + private final NTRUParameterSet parameterSet; private NTRUParameters(String name, NTRUParameterSet parameterSet) { @@ -61,6 +57,21 @@ public String getName() return name; } + NTRUParameterSet getParameterSet() + { + return parameterSet; + } + + int getPrivateKeyLength() + { + return getParameterSet().ntruSecretKeyBytes(); + } + + int getPublicKeyLength() + { + return getParameterSet().ntruPublicKeyBytes(); + } + public int getSessionKeySize() { return parameterSet.sharedKeyBytes() * 8; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/ADRS.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/ADRS.java new file mode 100644 index 0000000000..472ce5c9e6 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/ADRS.java @@ -0,0 +1,104 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Pack; + +class ADRS +{ + static final int WOTS_HASH = 0; + static final int WOTS_PK = 1; + static final int TREE = 2; + static final int FORS_TREE = 3; + static final int FORS_PK = 4; + static final int WOTS_PRF = 5; + static final int FORS_PRF = 6; + + static final int OFFSET_LAYER = 0; + static final int OFFSET_TREE = 4; + static final int OFFSET_TREE_HGT = 24; + static final int OFFSET_TREE_INDEX = 28; + static final int OFFSET_TYPE = 16; + static final int OFFSET_KP_ADDR = 20; + static final int OFFSET_CHAIN_ADDR = 24; + static final int OFFSET_HASH_ADDR = 28; + + final byte[] value = new byte[32]; + + ADRS() + { + } + + ADRS(ADRS adrs) + { + System.arraycopy(adrs.value, 0, this.value, 0, adrs.value.length); + } + + public void setLayerAddress(int layer) + { + Pack.intToBigEndian(layer, value, OFFSET_LAYER); + } + + public int getLayerAddress() + { + return Pack.bigEndianToInt(value, OFFSET_LAYER); + } + + public void setTreeAddress(long tree) + { + // tree address is 12 bytes + Pack.longToBigEndian(tree, value, OFFSET_TREE + 4); + } + + public long getTreeAddress() + { + return Pack.bigEndianToLong(value, OFFSET_TREE + 4); + } + + public void setTreeHeight(int height) + { + Pack.intToBigEndian(height, value, OFFSET_TREE_HGT); + } + + public void setTreeIndex(int index) + { + Pack.intToBigEndian(index, value, OFFSET_TREE_INDEX); + } + + public int getTreeIndex() + { + return Pack.bigEndianToInt(value, OFFSET_TREE_INDEX); + } + + // resets part of value to zero in line with 2.7.3 + public void setTypeAndClear(int type) + { + Pack.intToBigEndian(type, value, OFFSET_TYPE); + + Arrays.fill(value, 20, value.length, (byte)0); + } + + public void changeType(int type) + { + Pack.intToBigEndian(type, value, OFFSET_TYPE); + } + + public void setKeyPairAddress(int keyPairAddr) + { + Pack.intToBigEndian(keyPairAddr, value, OFFSET_KP_ADDR); + } + + public int getKeyPairAddress() + { + return Pack.bigEndianToInt(value, OFFSET_KP_ADDR); + } + + public void setHashAddress(int hashAddr) + { + Pack.intToBigEndian(hashAddr, value, OFFSET_HASH_ADDR); + } + + public void setChainAddress(int chainAddr) + { + Pack.intToBigEndian(chainAddr, value, OFFSET_CHAIN_ADDR); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/Fors.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/Fors.java new file mode 100644 index 0000000000..3123c56fba --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/Fors.java @@ -0,0 +1,167 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.math.BigInteger; +import java.util.LinkedList; + +import org.bouncycastle.util.Arrays; + +class Fors +{ + SLHDSAEngine engine; + + public Fors(SLHDSAEngine engine) + { + this.engine = engine; + } + + // Input: Secret seed SK.seed, start index s, target node height z, public seed PK.seed, address ADRS + // Output: n-byte root node - top node on Stack + byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) + { + if ((s >>> z) << z != s) + { + return null; + } + + LinkedList stack = new LinkedList(); + ADRS adrs = new ADRS(adrsParam); + + for (int idx = 0; idx < (1 << z); idx++) + { + adrs.setTypeAndClear(ADRS.FORS_PRF); + adrs.setKeyPairAddress(adrsParam.getKeyPairAddress()); + adrs.setTreeHeight(0); + adrs.setTreeIndex(s + idx); + + byte[] sk = engine.PRF(pkSeed, skSeed, adrs); + + adrs.changeType(ADRS.FORS_TREE); + + byte[] node = engine.F(pkSeed, adrs, sk); + + adrs.setTreeHeight(1); + + int adrsTreeHeight = 1; + int adrsTreeIndex = s + idx; + + // while ( Top node on Stack has same height as node ) + while (!stack.isEmpty() && ((NodeEntry)stack.get(0)).nodeHeight == adrsTreeHeight) + { + adrsTreeIndex = (adrsTreeIndex - 1) / 2; + adrs.setTreeIndex(adrsTreeIndex); + + NodeEntry current = ((NodeEntry)stack.remove(0)); + node = engine.H(pkSeed, adrs, current.nodeValue, node); + + // topmost node is now one layer higher + adrs.setTreeHeight(++adrsTreeHeight); + } + + stack.add(0, new NodeEntry(node, adrsTreeHeight)); + } + + return ((NodeEntry)stack.get(0)).nodeValue; + } + + public SIG_FORS[] sign(byte[] md, byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) + { + ADRS adrs = new ADRS(paramAdrs); + +// int[] idxs = message_to_idxs(md, engine.K, engine.A); + int[] idxs = base2B(md, engine.A, engine.K); + SIG_FORS[] sig_fors = new SIG_FORS[engine.K]; +// compute signature elements + int t = engine.T; + for (int i = 0; i < engine.K; i++) + { +// get next index + int idx = idxs[i]; +// pick private key element + adrs.setTypeAndClear(ADRS.FORS_PRF); + adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + adrs.setTreeHeight(0); + adrs.setTreeIndex(i * t + idx); + + byte[] sk = engine.PRF(pkSeed, skSeed, adrs); + + adrs.changeType(ADRS.FORS_TREE); + + byte[][] authPath = new byte[engine.A][]; +// compute auth path + for (int j = 0; j < engine.A; j++) + { + int s = (idx / (1 << j)) ^ 1; + authPath[j] = treehash(skSeed, i * t + s * (1 << j), j, pkSeed, adrs); + } + sig_fors[i] = new SIG_FORS(sk, authPath); + } + return sig_fors; + } + + public byte[] pkFromSig(SIG_FORS[] sig_fors, byte[] message, byte[] pkSeed, ADRS adrs) + { + byte[][] node = new byte[2][]; + byte[][] root = new byte[engine.K][]; + int t = engine.T; + +// int[] idxs = message_to_idxs(message, engine.K, engine.A); + int[] idxs = base2B(message, engine.A, engine.K); + // compute roots + for (int i = 0; i < engine.K; i++) + { + // get next index + int idx = idxs[i]; + // compute leaf + byte[] sk = sig_fors[i].getSK(); + adrs.setTreeHeight(0); + adrs.setTreeIndex(i * t + idx); + node[0] = engine.F(pkSeed, adrs, sk); + // compute root from leaf and AUTH + byte[][] authPath = sig_fors[i].getAuthPath(); + + adrs.setTreeIndex(i * t + idx); + for (int j = 0; j < engine.A; j++) + { + adrs.setTreeHeight(j + 1); + if (((idx / (1 << j)) % 2) == 0) + { + adrs.setTreeIndex(adrs.getTreeIndex() / 2); + node[1] = engine.H(pkSeed, adrs, node[0], authPath[j]); + } + else + { + adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2); + node[1] = engine.H(pkSeed, adrs, authPath[j], node[0]); + } + node[0] = node[1]; + } + root[i] = node[0]; + } + ADRS forspkADRS = new ADRS(adrs); // copy address to create FTS public key address + forspkADRS.setTypeAndClear(ADRS.FORS_PK); + forspkADRS.setKeyPairAddress(adrs.getKeyPairAddress()); + return engine.T_l(pkSeed, forspkADRS, Arrays.concatenate(root)); + } + + static int[] base2B(byte[] msg, int b, int outLen) + { + int[] baseB = new int[outLen]; + int i = 0; + int bits = 0; + BigInteger total = BigInteger.ZERO; + + for (int o = 0; o < outLen; o++) + { + while (bits < b) + { + total = total.shiftLeft(8).add(BigInteger.valueOf(msg[i] & 0xff)); + i+= 1; + bits += 8; + } + bits -= b; + baseB[o] = (total.shiftRight(bits).mod(BigInteger.valueOf(2).pow(b))).intValue(); + } + + return baseB; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/HT.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/HT.java new file mode 100644 index 0000000000..8bf4c0440c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/HT.java @@ -0,0 +1,214 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.util.LinkedList; + +import org.bouncycastle.util.Arrays; + +class HT +{ + private final byte[] skSeed; + private final byte[] pkSeed; + SLHDSAEngine engine; + WotsPlus wots; + + final byte[] htPubKey; + + public HT(SLHDSAEngine engine, byte[] skSeed, byte[] pkSeed) + { + this.skSeed = skSeed; + this.pkSeed = pkSeed; + + this.engine = engine; + this.wots = new WotsPlus(engine); + + ADRS adrs = new ADRS(); + adrs.setLayerAddress(engine.D - 1); + adrs.setTreeAddress(0); + + if (skSeed != null) + { + htPubKey = xmss_PKgen(skSeed, pkSeed, adrs); + } + else + { + htPubKey = null; + } + } + + byte[] sign(byte[] M, long idx_tree, int idx_leaf) + { + // init + ADRS adrs = new ADRS(); + // sign + // adrs.setType(ADRS.TREE); + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + SIG_XMSS SIG_tmp = xmss_sign(M, skSeed, idx_leaf, pkSeed, adrs); + SIG_XMSS[] SIG_HT = new SIG_XMSS[engine.D]; + SIG_HT[0] = SIG_tmp; + + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + + byte[] root = xmss_pkFromSig(idx_leaf, SIG_tmp, M, pkSeed, adrs); + + for (int j = 1; j < engine.D; j++) + { + idx_leaf = (int)(idx_tree & ((1 << engine.H_PRIME) - 1)); // least significant bits of idx_tree; + idx_tree >>>= engine.H_PRIME; // most significant bits of idx_tree; + adrs.setLayerAddress(j); + adrs.setTreeAddress(idx_tree); + SIG_tmp = xmss_sign(root, skSeed, idx_leaf, pkSeed, adrs); + SIG_HT[j] = SIG_tmp; + if (j < engine.D - 1) + { + root = xmss_pkFromSig(idx_leaf, SIG_tmp, root, pkSeed, adrs); + } + } + + byte[][] totSigs = new byte[SIG_HT.length][]; + for (int i = 0; i != totSigs.length; i++) + { + totSigs[i] = Arrays.concatenate(SIG_HT[i].sig, Arrays.concatenate(SIG_HT[i].auth)); + } + + return Arrays.concatenate(totSigs); + } + + byte[] xmss_PKgen(byte[] skSeed, byte[] pkSeed, ADRS adrs) + { + return treehash(skSeed, 0, engine.H_PRIME, pkSeed, adrs); + } + + // Input: index idx, XMSS signature SIG_XMSS = (sig || AUTH), n-byte message M, public seed PK.seed, address ADRS + // Output: n-byte root value node[0] + byte[] xmss_pkFromSig(int idx, SIG_XMSS sig_xmss, byte[] M, byte[] pkSeed, ADRS paramAdrs) + { + ADRS adrs = new ADRS(paramAdrs); + + // compute WOTS+ pk from WOTS+ sig + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(idx); + byte[] sig = sig_xmss.getWOTSSig(); + byte[][] AUTH = sig_xmss.getXMSSAUTH(); + + byte[] node0 = wots.pkFromSig(sig, M, pkSeed, adrs); + byte[] node1 = null; + + // compute root from WOTS+ pk and AUTH + adrs.setTypeAndClear(ADRS.TREE); + adrs.setTreeIndex(idx); + for (int k = 0; k < engine.H_PRIME; k++) + { + adrs.setTreeHeight(k + 1); + if (((idx / (1 << k)) % 2) == 0) + { + adrs.setTreeIndex(adrs.getTreeIndex() / 2); + node1 = engine.H(pkSeed, adrs, node0, AUTH[k]); + } + else + { + adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2); + node1 = engine.H(pkSeed, adrs, AUTH[k], node0); + } + node0 = node1; + } + return node0; + } + + // # Input: n-byte message M, secret seed SK.seed, index idx, public seed PK.seed, + // address ADRS + // # Output: XMSS signature SIG_XMSS = (sig || AUTH) + SIG_XMSS xmss_sign(byte[] M, byte[] skSeed, int idx, byte[] pkSeed, ADRS paramAdrs) + { + byte[][] AUTH = new byte[engine.H_PRIME][]; + + ADRS adrs = new ADRS(paramAdrs); + + adrs.setTypeAndClear(ADRS.TREE); + adrs.setLayerAddress(paramAdrs.getLayerAddress()); + adrs.setTreeAddress(paramAdrs.getTreeAddress()); + + // build authentication path + for (int j = 0; j < engine.H_PRIME; j++) + { + int k = (idx >>> j) ^ 1; + AUTH[j] = treehash(skSeed, k << j, j, pkSeed, adrs); + } + adrs = new ADRS(paramAdrs); + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(idx); + + byte[] sig = wots.sign(M, skSeed, pkSeed, adrs); + + return new SIG_XMSS(sig, AUTH); + } + + // Input: Secret seed SK.seed, start index s, target node height z, public seed PK.seed, address ADRS + // Output: n-byte root node - top node on Stack + byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) + { + if ((s >>> z) << z != s) + { + return null; + } + + LinkedList stack = new LinkedList(); + ADRS adrs = new ADRS(adrsParam); + + for (int idx = 0; idx < (1 << z); idx++) + { + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(s + idx); + byte[] node = wots.pkGen(skSeed, pkSeed, adrs); + + adrs.setTypeAndClear(ADRS.TREE); + adrs.setTreeHeight(1); + adrs.setTreeIndex(s + idx); + + int adrsTreeHeight = 1; + int adrsTreeIndex = s + idx; + + // while ( Top node on Stack has same height as node ) + while (!stack.isEmpty() && ((NodeEntry)stack.get(0)).nodeHeight == adrsTreeHeight) + { + adrsTreeIndex = (adrsTreeIndex - 1) / 2; + adrs.setTreeIndex(adrsTreeIndex); + + NodeEntry current = ((NodeEntry)stack.remove(0)); + node = engine.H(pkSeed, adrs, current.nodeValue, node); + + // topmost node is now one layer higher + adrs.setTreeHeight(++adrsTreeHeight); + } + + stack.add(0, new NodeEntry(node, adrsTreeHeight)); + } + + return ((NodeEntry)stack.get(0)).nodeValue; + } + + // # Input: Message M, signature SIG_HT, public seed PK.seed, tree index idx_tree, +// leaf index idx_leaf, HT public key PK_HT. +// # Output: Boolean + public boolean verify(byte[] M, SIG_XMSS[] sig_ht, byte[] pkSeed, long idx_tree, int idx_leaf, byte[] PK_HT) + { + // init + ADRS adrs = new ADRS(); + // verify + SIG_XMSS SIG_tmp = sig_ht[0]; + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + byte[] node = xmss_pkFromSig(idx_leaf, SIG_tmp, M, pkSeed, adrs); + for (int j = 1; j < engine.D; j++) + { + idx_leaf = (int)(idx_tree & ((1 << engine.H_PRIME) - 1)); // least significant bits of idx_tree; + idx_tree >>>= engine.H_PRIME; // most significant bits of idx_tree; + SIG_tmp = sig_ht[j]; + adrs.setLayerAddress(j); + adrs.setTreeAddress(idx_tree); + node = xmss_pkFromSig(idx_leaf, SIG_tmp, node, pkSeed, adrs); + } + return Arrays.areEqual(PK_HT, node); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/HashSLHDSASigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/HashSLHDSASigner.java new file mode 100644 index 0000000000..16a725bd93 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/HashSLHDSASigner.java @@ -0,0 +1,305 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.params.ParametersWithContext; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.DigestUtils; +import org.bouncycastle.util.Arrays; + +/** + * SLH-DA signer. + */ +public class HashSLHDSASigner + implements Signer +{ + private byte[] msgPrefix; + private SLHDSAPublicKeyParameters pubKey; + private SLHDSAPrivateKeyParameters privKey; + private SecureRandom random; + + private Digest digest; + + public HashSLHDSASigner() + { + } + + public void init(boolean forSigning, CipherParameters param) + { + ParametersWithContext withContext = null; + if (param instanceof ParametersWithContext) + { + withContext = (ParametersWithContext)param; + param = ((ParametersWithContext)param).getParameters(); + + if (withContext.getContextLength() > 255) + { + throw new IllegalArgumentException("context too long"); + } + } + + SLHDSAParameters parameters; + if (forSigning) + { + pubKey = null; + + if (param instanceof ParametersWithRandom) + { + privKey = ((SLHDSAPrivateKeyParameters)((ParametersWithRandom)param).getParameters()); + random = ((ParametersWithRandom)param).getRandom(); + } + else + { + privKey = (SLHDSAPrivateKeyParameters)param; + random = null; + } + + parameters = privKey.getParameters(); + } + else + { + pubKey = (SLHDSAPublicKeyParameters)param; + privKey = null; + random = null; + + parameters = pubKey.getParameters(); + } + + initDigest(parameters, withContext); + } + + private void initDigest(SLHDSAParameters parameters, ParametersWithContext withContext) + { + digest = createDigest(parameters); + + ASN1ObjectIdentifier digestOID = DigestUtils.getDigestOid(digest.getAlgorithmName()); + + // TODO[asn1] Encode this into the message prefix directly? + byte[] digestOIDEncoding; + try + { + digestOIDEncoding = digestOID.getEncoded(ASN1Encoding.DER); + } + catch (IOException e) + { + throw new IllegalStateException("oid encoding failed: " + e.getMessage()); + } + + int ctxLength = withContext == null ? 0 : withContext.getContextLength(); + + msgPrefix = new byte[2 + ctxLength + digestOIDEncoding.length]; + msgPrefix[0] = 1; + msgPrefix[1] = (byte)ctxLength; + if (withContext != null) + { + withContext.copyContextTo(msgPrefix, 2, ctxLength); + } + System.arraycopy(digestOIDEncoding, 0, msgPrefix, 2 + ctxLength, digestOIDEncoding.length); + } + + public void update(byte b) + { + digest.update(b); + } + + public void update(byte[] in, int off, int len) + { + digest.update(in, off, len); + } + + public byte[] generateSignature() throws CryptoException, DataLengthException + { + // TODO Redundant with the engine created in internalGenerateSignature + SLHDSAEngine engine = privKey.getParameters().getEngine(); + + engine.init(privKey.pk.seed); + + byte[] hash = new byte[digest.getDigestSize()]; + digest.doFinal(hash, 0); + + // generate randomizer + byte[] optRand = new byte[engine.N]; + if (random != null) + { + random.nextBytes(optRand); + } + else + { + System.arraycopy(privKey.pk.seed, 0, optRand, 0, optRand.length); + } + + return internalGenerateSignature(privKey, msgPrefix, hash, optRand); + } + + public boolean verifySignature(byte[] signature) + { + byte[] hash = new byte[digest.getDigestSize()]; + digest.doFinal(hash, 0); + + return internalVerifySignature(pubKey, msgPrefix, hash, signature); + } + + public void reset() + { + digest.reset(); + } + + protected byte[] internalGenerateSignature(byte[] message, byte[] optRand) + { + return internalGenerateSignature(privKey, null, message, optRand); + } + + private static byte[] internalGenerateSignature(SLHDSAPrivateKeyParameters privKey, byte[] msgPrefix, byte[] msg, + byte[] optRand) + { + // TODO Check init via privKey != null + + SLHDSAEngine engine = privKey.getParameters().getEngine(); + engine.init(privKey.pk.seed); + + Fors fors = new Fors(engine); + byte[] R = engine.PRF_msg(privKey.sk.prf, optRand, msgPrefix, msg); + + IndexedDigest idxDigest = engine.H_msg(R, privKey.pk.seed, privKey.pk.root, msgPrefix, msg); + byte[] mHash = idxDigest.digest; + long idx_tree = idxDigest.idx_tree; + int idx_leaf = idxDigest.idx_leaf; + // FORS sign + ADRS adrs = new ADRS(); + adrs.setTypeAndClear(ADRS.FORS_TREE); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + SIG_FORS[] sig_fors = fors.sign(mHash, privKey.sk.seed, privKey.pk.seed, adrs); + // get FORS public key - spec shows M? + adrs = new ADRS(); + adrs.setTypeAndClear(ADRS.FORS_TREE); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + byte[] PK_FORS = fors.pkFromSig(sig_fors, mHash, privKey.pk.seed, adrs); + + // sign FORS public key with HT + ADRS treeAdrs = new ADRS(); + treeAdrs.setTypeAndClear(ADRS.TREE); + + HT ht = new HT(engine, privKey.getSeed(), privKey.getPublicSeed()); + byte[] SIG_HT = ht.sign(PK_FORS, idx_tree, idx_leaf); + + byte[][] sigComponents = new byte[sig_fors.length + 2][]; + sigComponents[0] = R; + + for (int i = 0; i != sig_fors.length; i++) + { + sigComponents[1 + i] = Arrays.concatenate(sig_fors[i].sk, Arrays.concatenate(sig_fors[i].authPath)); + } + sigComponents[sigComponents.length - 1] = SIG_HT; + + return Arrays.concatenate(sigComponents); + } + + protected boolean internalVerifySignature(byte[] message, byte[] signature) + { + return internalVerifySignature(pubKey, null, message, signature); + } + + private static boolean internalVerifySignature(SLHDSAPublicKeyParameters pubKey, byte[] msgPrefix, byte[] msg, + byte[] signature) + { + // TODO Check init via pubKey != null + + //# Input: Message M, signature SIG, public key PK + //# Output: Boolean + + // init + SLHDSAEngine engine = pubKey.getParameters().getEngine(); + + engine.init(pubKey.getSeed()); + + ADRS adrs = new ADRS(); + + if (((1 + engine.K * (1 + engine.A) + engine.H + engine.D *engine.WOTS_LEN)* engine.N) != signature.length) + { + return false; + } + + SIG sig = new SIG(engine.N, engine.K, engine.A, engine.D, engine.H_PRIME, engine.WOTS_LEN, signature); + + byte[] R = sig.getR(); + SIG_FORS[] sig_fors = sig.getSIG_FORS(); + SIG_XMSS[] SIG_HT = sig.getSIG_HT(); + + // compute message digest and index + IndexedDigest idxDigest = engine.H_msg(R, pubKey.getSeed(), pubKey.getRoot(), msgPrefix, msg); + byte[] mHash = idxDigest.digest; + long idx_tree = idxDigest.idx_tree; + int idx_leaf = idxDigest.idx_leaf; + + // compute FORS public key + adrs.setTypeAndClear(ADRS.FORS_TREE); + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + byte[] PK_FORS = new Fors(engine).pkFromSig(sig_fors, mHash, pubKey.getSeed(), adrs); + // verify HT signature + adrs.setTypeAndClear(ADRS.TREE); + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + HT ht = new HT(engine, null, pubKey.getSeed()); + return ht.verify(PK_FORS, SIG_HT, pubKey.getSeed(), idx_tree, idx_leaf, pubKey.getRoot()); + } + + private static Digest createDigest(SLHDSAParameters parameters) + { + switch (parameters.getType()) + { + case SLHDSAParameters.TYPE_PURE: + String name = parameters.getName(); + if (name.startsWith("sha2")) + { + if (SLHDSAParameters.sha2_128f == parameters + || SLHDSAParameters.sha2_128s == parameters) + { + return SHA256Digest.newInstance(); + } + else + { + return new SHA512Digest(); + } + } + else + { + if (SLHDSAParameters.shake_128f == parameters + || SLHDSAParameters.shake_128s == parameters) + { + return new SHAKEDigest(128); + } + else + { + return new SHAKEDigest(256); + } + } + case SLHDSAParameters.TYPE_SHA2_256: + return SHA256Digest.newInstance(); + case SLHDSAParameters.TYPE_SHA2_512: + return new SHA512Digest(); + case SLHDSAParameters.TYPE_SHAKE128: + return new SHAKEDigest(128); + case SLHDSAParameters.TYPE_SHAKE256: + return new SHAKEDigest(256); + default: + throw new IllegalArgumentException("unknown parameters type"); + } + } +} + diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/IndexedDigest.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/IndexedDigest.java new file mode 100644 index 0000000000..e43f1c5a20 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/IndexedDigest.java @@ -0,0 +1,15 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class IndexedDigest +{ + final long idx_tree; + final int idx_leaf; + final byte[] digest; + + IndexedDigest(long idx_tree, int idx_leaf, byte[] digest) + { + this.idx_tree = idx_tree; + this.idx_leaf = idx_leaf; + this.digest = digest; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/NodeEntry.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/NodeEntry.java new file mode 100644 index 0000000000..e9d57b9bc3 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/NodeEntry.java @@ -0,0 +1,13 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class NodeEntry +{ + final byte[] nodeValue; + final int nodeHeight; + + NodeEntry(byte[] nodeValue, int nodeHeight) + { + this.nodeValue = nodeValue; + this.nodeHeight = nodeHeight; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/PK.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/PK.java new file mode 100644 index 0000000000..36794f4067 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/PK.java @@ -0,0 +1,13 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class PK +{ + final byte[] seed; + final byte[] root; + + PK(byte[] seed, byte[] root) + { + this.seed = seed; + this.root = root; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG.java new file mode 100644 index 0000000000..918b7a0924 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG.java @@ -0,0 +1,66 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class SIG +{ + private final byte[] r; + private final SIG_FORS[] sig_fors; + private final SIG_XMSS[] sig_ht; + + public SIG(int n, int k, int a, int d, int hPrime, int wots_len, byte[] signature) + { + this.r = new byte[n]; + System.arraycopy(signature, 0, r, 0, n); + + this.sig_fors = new SIG_FORS[k]; + int offset = n; + for (int i = 0; i != k; i++) + { + byte[] sk = new byte[n]; + System.arraycopy(signature, offset, sk, 0, n); + offset += n; + byte[][] authPath = new byte[a][]; + for (int j = 0; j != a; j++) + { + authPath[j] = new byte[n]; + System.arraycopy(signature, offset, authPath[j], 0, n); + offset += n; + } + sig_fors[i] = new SIG_FORS(sk, authPath); + } + + sig_ht = new SIG_XMSS[d]; + for (int i = 0; i != d; i++) + { + byte[] sig = new byte[wots_len * n]; + System.arraycopy(signature, offset, sig, 0, sig.length); + offset += sig.length; + byte[][] authPath = new byte[hPrime][]; + for (int j = 0; j != hPrime; j++) + { + authPath[j] = new byte[n]; + System.arraycopy(signature, offset, authPath[j], 0, n); + offset += n; + } + sig_ht[i] = new SIG_XMSS(sig, authPath); + } + if (offset != signature.length) + { + throw new IllegalArgumentException("signature wrong length"); + } + } + + public byte[] getR() + { + return r; + } + + public SIG_FORS[] getSIG_FORS() + { + return sig_fors; + } + + public SIG_XMSS[] getSIG_HT() + { + return sig_ht; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG_FORS.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG_FORS.java new file mode 100644 index 0000000000..76977003c3 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG_FORS.java @@ -0,0 +1,23 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class SIG_FORS +{ + final byte[][] authPath; + final byte[] sk; + + SIG_FORS(byte[] sk, byte[][] authPath) + { + this.authPath = authPath; + this.sk = sk; + } + + byte[] getSK() + { + return sk; + } + + public byte[][] getAuthPath() + { + return authPath; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG_XMSS.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG_XMSS.java new file mode 100644 index 0000000000..1d6011f7cd --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SIG_XMSS.java @@ -0,0 +1,23 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class SIG_XMSS +{ + final byte[] sig; + final byte[][] auth; + + public SIG_XMSS(byte[] sig, byte[][] auth) + { + this.sig = sig; + this.auth = auth; + } + + public byte[] getWOTSSig() + { + return sig; + } + + public byte[][] getXMSSAUTH() + { + return auth; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SK.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SK.java new file mode 100644 index 0000000000..1a698b1d39 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SK.java @@ -0,0 +1,13 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +class SK +{ + final byte[] seed; + final byte[] prf; + + SK(byte[] seed, byte[] prf) + { + this.seed = seed; + this.prf = prf; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAEngine.java new file mode 100644 index 0000000000..58c8d8b765 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAEngine.java @@ -0,0 +1,457 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.Xof; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.generators.MGF1BytesGenerator; +import org.bouncycastle.crypto.macs.HMac; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.MGFParameters; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Bytes; +import org.bouncycastle.util.Memoable; +import org.bouncycastle.util.Pack; + +abstract class SLHDSAEngine +{ + final int N; + + final int WOTS_W; + final int WOTS_LOGW; + final int WOTS_LEN; + final int WOTS_LEN1; + final int WOTS_LEN2; + + final int D; + final int A; // FORS_HEIGHT + final int K; // FORS_TREES + final int H; // FULL_HEIGHT + final int H_PRIME; // H / D + + final int T; // T = 1 << A + + public SLHDSAEngine(int n, int w, int d, int a, int k, int h) + { + this.N = n; + + /* SPX_WOTS_LEN2 is floor(log(len_1 * (w - 1)) / log(w)) + 1; we precompute */ + if (w == 16) + { + WOTS_LOGW = 4; + WOTS_LEN1 = (8 * N / WOTS_LOGW); + if (N <= 8) + { + WOTS_LEN2 = 2; + } + else if (N <= 136) + { + WOTS_LEN2 = 3; + } + else if (N <= 256) + { + WOTS_LEN2 = 4; + } + else + { + throw new IllegalArgumentException("cannot precompute SPX_WOTS_LEN2 for n outside {2, .., 256}"); + } + } + else if (w == 256) + { + WOTS_LOGW = 8; + WOTS_LEN1 = (8 * N / WOTS_LOGW); + if (N <= 1) + { + WOTS_LEN2 = 1; + } + else if (N <= 256) + { + WOTS_LEN2 = 2; + } + else + { + throw new IllegalArgumentException("cannot precompute SPX_WOTS_LEN2 for n outside {2, .., 256}"); + } + } + else + { + throw new IllegalArgumentException("wots_w assumed 16 or 256"); + } + this.WOTS_W = w; + this.WOTS_LEN = WOTS_LEN1 + WOTS_LEN2; + + this.D = d; + this.A = a; + this.K = k; + this.H = h; + this.H_PRIME = h / d; + this.T = 1 << a; + } + + abstract void init(byte[] pkSeed); + + abstract byte[] F(byte[] pkSeed, ADRS adrs, byte[] m1); + + abstract byte[] H(byte[] pkSeed, ADRS adrs, byte[] m1, byte[] m2); + + abstract IndexedDigest H_msg(byte[] prf, byte[] pkSeed, byte[] pkRoot, byte[] msgPrefix, byte[] msg); + + abstract byte[] T_l(byte[] pkSeed, ADRS adrs, byte[] m); + + abstract byte[] PRF(byte[] pkSeed, byte[] skSeed, ADRS adrs); + + abstract byte[] PRF_msg(byte[] prf, byte[] randomiser, byte[] msgPrefix, byte[] msg); + + static class Sha2Engine + extends SLHDSAEngine + { + private final HMac treeHMac; + private final MGF1BytesGenerator mgf1; + private final byte[] hmacBuf; + private final Digest msgDigest; + private final byte[] msgDigestBuf; + private final int bl; + private final Digest sha256 = new SHA256Digest(); + private final byte[] sha256Buf = new byte[sha256.getDigestSize()]; + + private Memoable msgMemo; + private Memoable sha256Memo; + + public Sha2Engine(int n, int w, int d, int a, int k, int h) + { + super(n, w, d, a, k, h); + if (n == 16) + { + this.msgDigest = new SHA256Digest(); + this.treeHMac = new HMac(new SHA256Digest()); + this.mgf1 = new MGF1BytesGenerator(new SHA256Digest()); + this.bl = 64; + } + else + { + this.msgDigest = new SHA512Digest(); + this.treeHMac = new HMac(new SHA512Digest()); + this.mgf1 = new MGF1BytesGenerator(new SHA512Digest()); + this.bl = 128; + } + + this.hmacBuf = new byte[treeHMac.getMacSize()]; + this.msgDigestBuf = new byte[msgDigest.getDigestSize()]; + } + + void init(byte[] pkSeed) + { + final byte[] padding = new byte[bl]; + + msgDigest.update(pkSeed, 0, pkSeed.length); + msgDigest.update(padding, 0, bl - N); // toByte(0, 64 - n) + msgMemo = ((Memoable)msgDigest).copy(); + + msgDigest.reset(); + + sha256.update(pkSeed, 0, pkSeed.length); + sha256.update(padding, 0, 64 - pkSeed.length); // toByte(0, 64 - n) + sha256Memo = ((Memoable)sha256).copy(); + + sha256.reset(); + } + + public byte[] F(byte[] pkSeed, ADRS adrs, byte[] m1) + { + byte[] compressedADRS = compressedADRS(adrs); + + ((Memoable)sha256).reset(sha256Memo); + + sha256.update(compressedADRS, 0, compressedADRS.length); + sha256.update(m1, 0, m1.length); + sha256.doFinal(sha256Buf, 0); + + return Arrays.copyOfRange(sha256Buf, 0, N); + } + + public byte[] H(byte[] pkSeed, ADRS adrs, byte[] m1, byte[] m2) + { + byte[] compressedADRS = compressedADRS(adrs); + + ((Memoable)msgDigest).reset(msgMemo); + + msgDigest.update(compressedADRS, 0, compressedADRS.length); + + msgDigest.update(m1, 0, m1.length); + msgDigest.update(m2, 0, m2.length); + + msgDigest.doFinal(msgDigestBuf, 0); + + return Arrays.copyOfRange(msgDigestBuf, 0, N); + } + + IndexedDigest H_msg(byte[] prf, byte[] pkSeed, byte[] pkRoot, byte[] msgPrefix, byte[] msg) + { + int forsMsgBytes = ((A * K) + 7) / 8; + int leafBits = H / D; + int treeBits = H - leafBits; + int leafBytes = (leafBits + 7) / 8; + int treeBytes = (treeBits + 7) / 8; + int m = forsMsgBytes + leafBytes + treeBytes; + byte[] out = new byte[m]; + byte[] dig = new byte[msgDigest.getDigestSize()]; + + msgDigest.update(prf, 0, prf.length); + msgDigest.update(pkSeed, 0, pkSeed.length); + msgDigest.update(pkRoot, 0, pkRoot.length); + if (msgPrefix != null) + { + msgDigest.update(msgPrefix, 0, msgPrefix.length); + } + msgDigest.update(msg, 0, msg.length); + msgDigest.doFinal(dig, 0); + + out = bitmask(Arrays.concatenate(prf, pkSeed, dig), out); + + // tree index + // currently, only indexes up to 64 bits are supported + byte[] treeIndexBuf = new byte[8]; + System.arraycopy(out, forsMsgBytes, treeIndexBuf, 8 - treeBytes, treeBytes); + long treeIndex = Pack.bigEndianToLong(treeIndexBuf, 0); + treeIndex &= (~0L) >>> (64 - treeBits); + + byte[] leafIndexBuf = new byte[4]; + System.arraycopy(out, forsMsgBytes + treeBytes, leafIndexBuf, 4 - leafBytes, leafBytes); + + int leafIndex = Pack.bigEndianToInt(leafIndexBuf, 0); + leafIndex &= (~0) >>> (32 - leafBits); + + return new IndexedDigest(treeIndex, leafIndex, Arrays.copyOfRange(out, 0, forsMsgBytes)); + } + + public byte[] T_l(byte[] pkSeed, ADRS adrs, byte[] m) + { + byte[] compressedADRS = compressedADRS(adrs); + + ((Memoable)msgDigest).reset(msgMemo); + + msgDigest.update(compressedADRS, 0, compressedADRS.length); + msgDigest.update(m, 0, m.length); + msgDigest.doFinal(msgDigestBuf, 0); + + return Arrays.copyOfRange(msgDigestBuf, 0, N); + } + + byte[] PRF(byte[] pkSeed, byte[] skSeed, ADRS adrs) + { + int n = skSeed.length; + + ((Memoable)sha256).reset(sha256Memo); + + byte[] compressedADRS = compressedADRS(adrs); + + sha256.update(compressedADRS, 0, compressedADRS.length); + sha256.update(skSeed, 0, skSeed.length); + sha256.doFinal(sha256Buf, 0); + + return Arrays.copyOfRange(sha256Buf, 0, n); + } + + public byte[] PRF_msg(byte[] prf, byte[] randomiser, byte[] msgPrefix, byte[] msg) + { + treeHMac.init(new KeyParameter(prf)); + treeHMac.update(randomiser, 0, randomiser.length); + if (msgPrefix != null) + { + treeHMac.update(msgPrefix, 0, msgPrefix.length); + } + treeHMac.update(msg, 0, msg.length); + treeHMac.doFinal(hmacBuf, 0); + + return Arrays.copyOfRange(hmacBuf, 0, N); + } + + private byte[] compressedADRS(ADRS adrs) + { + byte[] rv = new byte[22]; + System.arraycopy(adrs.value, ADRS.OFFSET_LAYER + 3, rv, 0, 1); // LSB layer address + System.arraycopy(adrs.value, ADRS.OFFSET_TREE + 4, rv, 1, 8); // LS 8 bytes Tree address + System.arraycopy(adrs.value, ADRS.OFFSET_TYPE + 3, rv, 9, 1); // LSB type + System.arraycopy(adrs.value, 20, rv, 10, 12); + + return rv; + } + + protected byte[] bitmask(byte[] key, byte[] m) + { + byte[] mask = new byte[m.length]; + mgf1.init(new MGFParameters(key)); + mgf1.generateBytes(mask, 0, mask.length); + Bytes.xorTo(m.length, m, mask); + return mask; + } + + protected byte[] bitmask(byte[] key, byte[] m1, byte[] m2) + { + byte[] mask = new byte[m1.length + m2.length]; + mgf1.init(new MGFParameters(key)); + mgf1.generateBytes(mask, 0, mask.length); + Bytes.xorTo(m1.length, m1, mask); + Bytes.xorTo(m2.length, m2, 0, mask, m1.length); + return mask; + } + + protected byte[] bitmask256(byte[] key, byte[] m) + { + byte[] mask = new byte[m.length]; + MGF1BytesGenerator mgf1 = new MGF1BytesGenerator(new SHA256Digest()); + mgf1.init(new MGFParameters(key)); + mgf1.generateBytes(mask, 0, mask.length); + Bytes.xorTo(m.length, m, mask); + return mask; + } + } + + static class Shake256Engine + extends SLHDSAEngine + { + private final Xof treeDigest; + private final Xof maskDigest; + + public Shake256Engine(int n, int w, int d, int a, int k, int h) + { + super(n, w, d, a, k, h); + + this.treeDigest = new SHAKEDigest(256); + this.maskDigest = new SHAKEDigest(256); + } + + void init(byte[] pkSeed) + { + + } + + byte[] F(byte[] pkSeed, ADRS adrs, byte[] m1) + { + byte[] mTheta = m1; + + byte[] rv = new byte[N]; + + treeDigest.update(pkSeed, 0, pkSeed.length); + treeDigest.update(adrs.value, 0, adrs.value.length); + treeDigest.update(mTheta, 0, mTheta.length); + treeDigest.doFinal(rv, 0, rv.length); + + return rv; + } + + byte[] H(byte[] pkSeed, ADRS adrs, byte[] m1, byte[] m2) + { + byte[] rv = new byte[N]; + + treeDigest.update(pkSeed, 0, pkSeed.length); + treeDigest.update(adrs.value, 0, adrs.value.length); + + treeDigest.update(m1, 0, m1.length); + treeDigest.update(m2, 0, m2.length); + + treeDigest.doFinal(rv, 0, rv.length); + + return rv; + } + + IndexedDigest H_msg(byte[] R, byte[] pkSeed, byte[] pkRoot, byte[] msgPrefix, byte[] msg) + { + int forsMsgBytes = ((A * K) + 7) / 8; + int leafBits = H / D; + int treeBits = H - leafBits; + int leafBytes = (leafBits + 7) / 8; + int treeBytes = (treeBits + 7) / 8; + int m = forsMsgBytes + leafBytes + treeBytes; + byte[] out = new byte[m]; + + treeDigest.update(R, 0, R.length); + treeDigest.update(pkSeed, 0, pkSeed.length); + treeDigest.update(pkRoot, 0, pkRoot.length); + if (msgPrefix != null) + { + treeDigest.update(msgPrefix, 0, msgPrefix.length); + } + treeDigest.update(msg, 0, msg.length); + treeDigest.doFinal(out, 0, out.length); + + // tree index + // currently, only indexes up to 64 bits are supported + byte[] treeIndexBuf = new byte[8]; + System.arraycopy(out, forsMsgBytes, treeIndexBuf, 8 - treeBytes, treeBytes); + long treeIndex = Pack.bigEndianToLong(treeIndexBuf, 0); + treeIndex &= (~0L) >>> (64 - treeBits); + + byte[] leafIndexBuf = new byte[4]; + System.arraycopy(out, forsMsgBytes + treeBytes, leafIndexBuf, 4 - leafBytes, leafBytes); + + int leafIndex = Pack.bigEndianToInt(leafIndexBuf, 0); + leafIndex &= (~0) >>> (32 - leafBits); + + return new IndexedDigest(treeIndex, leafIndex, Arrays.copyOfRange(out, 0, forsMsgBytes)); + } + + byte[] T_l(byte[] pkSeed, ADRS adrs, byte[] m) + { + byte[] mTheta = m; + + byte[] rv = new byte[N]; + + treeDigest.update(pkSeed, 0, pkSeed.length); + treeDigest.update(adrs.value, 0, adrs.value.length); + treeDigest.update(mTheta, 0, mTheta.length); + treeDigest.doFinal(rv, 0, rv.length); + + return rv; + } + + byte[] PRF(byte[] pkSeed, byte[] skSeed, ADRS adrs) + { + treeDigest.update(pkSeed, 0, pkSeed.length); + treeDigest.update(adrs.value, 0, adrs.value.length); + treeDigest.update(skSeed, 0, skSeed.length); + + byte[] prf = new byte[N]; + treeDigest.doFinal(prf, 0, N); + return prf; + } + + public byte[] PRF_msg(byte[] prf, byte[] randomiser, byte[] msgPrefix, byte[] msg) + { + treeDigest.update(prf, 0, prf.length); + treeDigest.update(randomiser, 0, randomiser.length); + if (msgPrefix != null) + { + treeDigest.update(msgPrefix, 0, msgPrefix.length); + } + treeDigest.update(msg, 0, msg.length); + + byte[] out = new byte[N]; + treeDigest.doFinal(out, 0, out.length); + return out; + } + + protected byte[] bitmask(byte[] pkSeed, ADRS adrs, byte[] m) + { + byte[] mask = new byte[m.length]; + maskDigest.update(pkSeed, 0, pkSeed.length); + maskDigest.update(adrs.value, 0, adrs.value.length); + maskDigest.doFinal(mask, 0, mask.length); + Bytes.xorTo(m.length, m, mask); + return mask; + } + + protected byte[] bitmask(byte[] pkSeed, ADRS adrs, byte[] m1, byte[] m2) + { + byte[] mask = new byte[m1.length + m2.length]; + maskDigest.update(pkSeed, 0, pkSeed.length); + maskDigest.update(adrs.value, 0, adrs.value.length); + maskDigest.doFinal(mask, 0, mask.length); + Bytes.xorTo(m1.length, m1, mask); + Bytes.xorTo(m2.length, m2, 0, mask, m1.length); + return mask; + } + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAEngineProvider.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAEngineProvider.java new file mode 100644 index 0000000000..14a6aae5c6 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAEngineProvider.java @@ -0,0 +1,8 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +interface SLHDSAEngineProvider +{ + int getN(); + + SLHDSAEngine get(); +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyGenerationParameters.java new file mode 100644 index 0000000000..ce4f67967d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyGenerationParameters.java @@ -0,0 +1,22 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class SLHDSAKeyGenerationParameters + extends KeyGenerationParameters +{ + private final SLHDSAParameters parameters; + + public SLHDSAKeyGenerationParameters(SecureRandom random, SLHDSAParameters parameters) + { + super(random, -1); + this.parameters = parameters; + } + + SLHDSAParameters getParameters() + { + return parameters; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyPairGenerator.java new file mode 100644 index 0000000000..2016709406 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyPairGenerator.java @@ -0,0 +1,59 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class SLHDSAKeyPairGenerator + implements AsymmetricCipherKeyPairGenerator +{ + private SecureRandom random; + private SLHDSAParameters parameters; + + public void init(KeyGenerationParameters param) + { + random = param.getRandom(); + parameters = ((SLHDSAKeyGenerationParameters)param).getParameters(); + } + + public AsymmetricCipherKeyPair internalGenerateKeyPair(byte[] skSeed, byte[] skPrf, byte[] pkSeed) + { + return implGenerateKeyPair(parameters.getEngine(), skSeed, skPrf, pkSeed); + } + + public AsymmetricCipherKeyPair generateKeyPair() + { + SLHDSAEngine engine = parameters.getEngine(); + + byte[] skSeed = sec_rand(engine.N); + byte[] skPrf = sec_rand(engine.N); + byte[] pkSeed = sec_rand(engine.N); + + return implGenerateKeyPair(engine, skSeed, skPrf, pkSeed); + } + + private AsymmetricCipherKeyPair implGenerateKeyPair(SLHDSAEngine engine, byte[] skSeed, byte[] skPrf, byte[] pkSeed) + { + SK sk = new SK(skSeed, skPrf); + + engine.init(pkSeed); + + // TODO + PK pk = new PK(pkSeed, new HT(engine, sk.seed, pkSeed).htPubKey); + + return new AsymmetricCipherKeyPair( + new SLHDSAPublicKeyParameters(parameters, pk), + new SLHDSAPrivateKeyParameters(parameters, sk, pk)); + } + + private byte[] sec_rand(int n) + { + byte[] rv = new byte[n]; + + random.nextBytes(rv); + + return rv; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyParameters.java new file mode 100644 index 0000000000..fe6095fd71 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAKeyParameters.java @@ -0,0 +1,20 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; + +public class SLHDSAKeyParameters + extends AsymmetricKeyParameter +{ + private final SLHDSAParameters parameters; + + protected SLHDSAKeyParameters(boolean isPrivate, SLHDSAParameters parameters) + { + super(isPrivate); + this.parameters = parameters; + } + + public SLHDSAParameters getParameters() + { + return parameters; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAParameters.java new file mode 100644 index 0000000000..a10794ba99 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAParameters.java @@ -0,0 +1,175 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +public class SLHDSAParameters +{ + public static final int TYPE_PURE = 0; + public static final int TYPE_SHA2_256 = 1; + public static final int TYPE_SHA2_512 = 2; + public static final int TYPE_SHAKE128 = 3; + public static final int TYPE_SHAKE256 = 4; + + // "Pure" SLH-DSA Parameters + // SHA-2 + public static final SLHDSAParameters sha2_128f = new SLHDSAParameters( + "sha2-128f", new Sha2EngineProvider(16, 16, 22, 6, 33, 66), TYPE_PURE); + public static final SLHDSAParameters sha2_128s = new SLHDSAParameters( + "sha2-128s", new Sha2EngineProvider(16, 16, 7, 12, 14, 63), TYPE_PURE); + + public static final SLHDSAParameters sha2_192f = new SLHDSAParameters( + "sha2-192f", new Sha2EngineProvider(24, 16, 22, 8, 33, 66), TYPE_PURE); + public static final SLHDSAParameters sha2_192s = new SLHDSAParameters( + "sha2-192s", new Sha2EngineProvider(24, 16, 7, 14, 17, 63), TYPE_PURE); + + public static final SLHDSAParameters sha2_256f = new SLHDSAParameters( + "sha2-256f", new Sha2EngineProvider(32, 16, 17, 9, 35, 68), TYPE_PURE); + public static final SLHDSAParameters sha2_256s = new SLHDSAParameters( + "sha2-256s", new Sha2EngineProvider(32, 16, 8, 14, 22, 64), TYPE_PURE); + + // SHAKE-256. + public static final SLHDSAParameters shake_128f = new SLHDSAParameters( + "shake-128f", new Shake256EngineProvider(16, 16, 22, 6, 33, 66), TYPE_PURE); + public static final SLHDSAParameters shake_128s = new SLHDSAParameters( + "shake-128s", new Shake256EngineProvider(16, 16, 7, 12, 14, 63), TYPE_PURE); + + public static final SLHDSAParameters shake_192f = new SLHDSAParameters( + "shake-192f", new Shake256EngineProvider(24, 16, 22, 8, 33, 66), TYPE_PURE); + public static final SLHDSAParameters shake_192s = new SLHDSAParameters( + "shake-192s", new Shake256EngineProvider(24, 16, 7, 14, 17, 63), TYPE_PURE); + + public static final SLHDSAParameters shake_256f = new SLHDSAParameters( + "shake-256f", new Shake256EngineProvider(32, 16, 17, 9, 35, 68), TYPE_PURE); + public static final SLHDSAParameters shake_256s = new SLHDSAParameters( + "shake-256s", new Shake256EngineProvider(32, 16, 8, 14, 22, 64), TYPE_PURE); + + + // "Pre-hash" SLH-DSA Parameters + // SHA-2 + public static final SLHDSAParameters sha2_128f_with_sha256 = new SLHDSAParameters( + "sha2-128f-with-sha256", new Sha2EngineProvider(16, 16, 22, 6, 33, 66), TYPE_SHA2_256); + public static final SLHDSAParameters sha2_128s_with_sha256 = new SLHDSAParameters( + "sha2-128s-with-sha256", new Sha2EngineProvider(16, 16, 7, 12, 14, 63), TYPE_SHA2_256); + + public static final SLHDSAParameters sha2_192f_with_sha512 = new SLHDSAParameters( + "sha2-192f-with-sha512", new Sha2EngineProvider(24, 16, 22, 8, 33, 66), TYPE_SHA2_512); + public static final SLHDSAParameters sha2_192s_with_sha512 = new SLHDSAParameters( + "sha2-192s-with-sha512", new Sha2EngineProvider(24, 16, 7, 14, 17, 63), TYPE_SHA2_512); + + public static final SLHDSAParameters sha2_256f_with_sha512 = new SLHDSAParameters( + "sha2-256f-with-sha512", new Sha2EngineProvider(32, 16, 17, 9, 35, 68), TYPE_SHA2_512); + public static final SLHDSAParameters sha2_256s_with_sha512 = new SLHDSAParameters( + "sha2-256s-with-sha512", new Sha2EngineProvider(32, 16, 8, 14, 22, 64), TYPE_SHA2_512); + + // SHAKE-256. + public static final SLHDSAParameters shake_128f_with_shake128 = new SLHDSAParameters( + "shake-128f-with-shake128", new Shake256EngineProvider(16, 16, 22, 6, 33, 66), TYPE_SHAKE128); + public static final SLHDSAParameters shake_128s_with_shake128 = new SLHDSAParameters( + "shake-128s-with-shake128", new Shake256EngineProvider(16, 16, 7, 12, 14, 63), TYPE_SHAKE128); + + public static final SLHDSAParameters shake_192f_with_shake256 = new SLHDSAParameters( + "shake-192f-with-shake256", new Shake256EngineProvider(24, 16, 22, 8, 33, 66), TYPE_SHAKE256); + public static final SLHDSAParameters shake_192s_with_shake256 = new SLHDSAParameters( + "shake-192s-with-shake256", new Shake256EngineProvider(24, 16, 7, 14, 17, 63), TYPE_SHAKE256); + + public static final SLHDSAParameters shake_256f_with_shake256 = new SLHDSAParameters( + "shake-256f-with-shake256", new Shake256EngineProvider(32, 16, 17, 9, 35, 68), TYPE_SHAKE256); + public static final SLHDSAParameters shake_256s_with_shake256 = new SLHDSAParameters( + "shake-256s-with-shake256", new Shake256EngineProvider(32, 16, 8, 14, 22, 64), TYPE_SHAKE256); + + private final String name; + private final SLHDSAEngineProvider engineProvider; + private final int preHashDigest; + + private SLHDSAParameters(String name, SLHDSAEngineProvider engineProvider, int preHashDigest) + { + this.name = name; + this.engineProvider = engineProvider; + this.preHashDigest = preHashDigest; + } + + public String getName() + { + return name; + } + + public int getType() + { + return preHashDigest; + } + + public int getN() + { + return engineProvider.getN(); + } + + SLHDSAEngine getEngine() + { + return engineProvider.get(); + } + + public boolean isPreHash() + { + return preHashDigest != TYPE_PURE; + } + + private static class Sha2EngineProvider + implements SLHDSAEngineProvider + { + private final int n; + private final int w; + private final int d; + private final int a; + private final int k; + private final int h; + + public Sha2EngineProvider(int n, int w, int d, int a, int k, int h) + { + this.n = n; + this.w = w; + this.d = d; + this.a = a; + this.k = k; + this.h = h; + } + + public int getN() + { + return n; + } + + public SLHDSAEngine get() + { + return new SLHDSAEngine.Sha2Engine(n, w, d, a, k, h); + } + } + + private static class Shake256EngineProvider + implements SLHDSAEngineProvider + { + private final int n; + private final int w; + private final int d; + private final int a; + private final int k; + private final int h; + + public Shake256EngineProvider(int n, int w, int d, int a, int k, int h) + { + this.n = n; + this.w = w; + this.d = d; + this.a = a; + this.k = k; + this.h = h; + } + + public int getN() + { + return n; + } + + public SLHDSAEngine get() + { + return new SLHDSAEngine.Shake256Engine(n, w, d, a, k, h); + } + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAPrivateKeyParameters.java new file mode 100644 index 0000000000..764a51dcb9 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAPrivateKeyParameters.java @@ -0,0 +1,69 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import org.bouncycastle.util.Arrays; + +public class SLHDSAPrivateKeyParameters + extends SLHDSAKeyParameters +{ + final SK sk; + final PK pk; + + public SLHDSAPrivateKeyParameters(SLHDSAParameters parameters, byte[] skpkEncoded) + { + super(true, parameters); + int n = parameters.getN(); + if (skpkEncoded.length != 4 * n) + { + throw new IllegalArgumentException("private key encoding does not match parameters"); + } + this.sk = new SK(Arrays.copyOfRange(skpkEncoded, 0, n), Arrays.copyOfRange(skpkEncoded, n, 2 * n)); + this.pk = new PK(Arrays.copyOfRange(skpkEncoded, 2 * n, 3 * n), Arrays.copyOfRange(skpkEncoded, 3 * n, 4 * n)); + } + + public SLHDSAPrivateKeyParameters(SLHDSAParameters parameters, byte[] skSeed, byte[] prf, byte[] pkSeed, byte[] pkRoot) + { + super(true, parameters); + this.sk = new SK(skSeed, prf); + this.pk = new PK(pkSeed, pkRoot); + } + SLHDSAPrivateKeyParameters(SLHDSAParameters parameters, SK sk, PK pk) + { + super(true, parameters); + this.sk = sk; + this.pk = pk; + } + + public byte[] getSeed() + { + return Arrays.clone(sk.seed); + } + + public byte[] getPrf() + { + return Arrays.clone(sk.prf); + } + + public byte[] getPublicSeed() + { + return Arrays.clone(pk.seed); + } + public byte[] getRoot() + { + return Arrays.clone(pk.root); + } + + public byte[] getPublicKey() + { + return Arrays.concatenate(pk.seed, pk.root); + } + + public byte[] getEncoded() + { + return Arrays.concatenate(new byte[][]{ sk.seed, sk.prf, pk.seed, pk.root }); + } + + public byte[] getEncodedPublicKey() + { + return Arrays.concatenate(pk.seed, pk.root); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAPublicKeyParameters.java new file mode 100644 index 0000000000..5789fa335a --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSAPublicKeyParameters.java @@ -0,0 +1,41 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import org.bouncycastle.util.Arrays; + +public class SLHDSAPublicKeyParameters + extends SLHDSAKeyParameters +{ + private final PK pk; + + public SLHDSAPublicKeyParameters(SLHDSAParameters parameters, byte[] pkValues) + { + super(false, parameters); + int n = parameters.getN(); + if (pkValues.length != 2 * n) + { + throw new IllegalArgumentException("public key encoding does not match parameters"); + } + this.pk = new PK(Arrays.copyOfRange(pkValues, 0, n), Arrays.copyOfRange(pkValues, n, 2 * n)); + } + + SLHDSAPublicKeyParameters(SLHDSAParameters parameters, PK pk) + { + super(false, parameters); + this.pk = pk; + } + + public byte[] getSeed() + { + return Arrays.clone(pk.seed); + } + + public byte[] getRoot() + { + return Arrays.clone(pk.root); + } + + public byte[] getEncoded() + { + return Arrays.concatenate(pk.seed, pk.root); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSASigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSASigner.java new file mode 100644 index 0000000000..ff3ad48583 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/SLHDSASigner.java @@ -0,0 +1,225 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.params.ParametersWithContext; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.MessageSigner; +import org.bouncycastle.util.Arrays; + +/** + * SLH-DA signer. + *

    + * This version is based on the 3rd submission with deference to the updated reference + * implementation on github as at November 9th 2021. This version includes the changes + * for the countermeasure for the long-message second preimage attack - see + * "https://github.com/sphincs/sphincsplus/commit/61cd2695c6f984b4f4d6ed675378ed9a486cbede" + * for further details. + *

    + */ +public class SLHDSASigner + implements MessageSigner +{ + private static final byte[] DEFAULT_PREFIX = new byte[]{ 0, 0 }; + + private byte[] msgPrefix; + private SLHDSAPublicKeyParameters pubKey; + private SLHDSAPrivateKeyParameters privKey; + private SecureRandom random; + + /** + * Base constructor. + */ + public SLHDSASigner() + { + } + + public void init(boolean forSigning, CipherParameters param) + { + if (param instanceof ParametersWithContext) + { + ParametersWithContext withContext = (ParametersWithContext)param; + param = withContext.getParameters(); + + int ctxLength = withContext.getContextLength(); + if (ctxLength > 255) + { + throw new IllegalArgumentException("context too long"); + } + + msgPrefix = new byte[2 + ctxLength]; + msgPrefix[0] = 0; + msgPrefix[1] = (byte)ctxLength; + withContext.copyContextTo(msgPrefix, 2, ctxLength); + } + else + { + msgPrefix = DEFAULT_PREFIX; + } + + SLHDSAParameters parameters; + if (forSigning) + { + pubKey = null; + + if (param instanceof ParametersWithRandom) + { + ParametersWithRandom withRandom = (ParametersWithRandom)param; + privKey = (SLHDSAPrivateKeyParameters)withRandom.getParameters(); + random = withRandom.getRandom(); + } + else + { + privKey = (SLHDSAPrivateKeyParameters)param; + random = null; + } + + parameters = privKey.getParameters(); + } + else + { + pubKey = (SLHDSAPublicKeyParameters)param; + privKey = null; + random = null; + + parameters = pubKey.getParameters(); + } + + if (parameters.isPreHash()) + { + throw new IllegalArgumentException("\"pure\" slh-dsa must use non pre-hash parameters"); + } + } + + public byte[] generateSignature(byte[] message) + { + // TODO Redundant with the engine created in internalGenerateSignature + SLHDSAEngine engine = privKey.getParameters().getEngine(); + + engine.init(privKey.pk.seed); + + // generate randomizer + byte[] optRand = new byte[engine.N]; + if (random != null) + { + random.nextBytes(optRand); + } + else + { + System.arraycopy(privKey.pk.seed, 0, optRand, 0, optRand.length); + } + + return internalGenerateSignature(privKey, msgPrefix, message, optRand); + } + + // Equivalent to slh_verify_internal from specs + public boolean verifySignature(byte[] message, byte[] signature) + { + return internalVerifySignature(pubKey, msgPrefix, message, signature); + } + + protected boolean internalVerifySignature(byte[] message, byte[] signature) + { + return internalVerifySignature(pubKey, null, message, signature); + } + + private static boolean internalVerifySignature(SLHDSAPublicKeyParameters pubKey, byte[] msgPrefix, byte[] msg, + byte[] signature) + { + // TODO Check init via pubKey != null + + //# Input: Message M, signature SIG, public key PK + //# Output: Boolean + + // init + SLHDSAEngine engine = pubKey.getParameters().getEngine(); + + engine.init(pubKey.getSeed()); + + ADRS adrs = new ADRS(); + + if (((1 + engine.K * (1 + engine.A) + engine.H + engine.D * engine.WOTS_LEN) * engine.N) != signature.length) + { + return false; + } + + SIG sig = new SIG(engine.N, engine.K, engine.A, engine.D, engine.H_PRIME, engine.WOTS_LEN, signature); + + byte[] R = sig.getR(); + SIG_FORS[] sig_fors = sig.getSIG_FORS(); + SIG_XMSS[] SIG_HT = sig.getSIG_HT(); + + // compute message digest and index + IndexedDigest idxDigest = engine.H_msg(R, pubKey.getSeed(), pubKey.getRoot(), msgPrefix, msg); + byte[] mHash = idxDigest.digest; + long idx_tree = idxDigest.idx_tree; + int idx_leaf = idxDigest.idx_leaf; + + // compute FORS public key + adrs.setTypeAndClear(ADRS.FORS_TREE); + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + byte[] PK_FORS = new Fors(engine).pkFromSig(sig_fors, mHash, pubKey.getSeed(), adrs); + // verify HT signature + adrs.setTypeAndClear(ADRS.TREE); + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + HT ht = new HT(engine, null, pubKey.getSeed()); + return ht.verify(PK_FORS, SIG_HT, pubKey.getSeed(), idx_tree, idx_leaf, pubKey.getRoot()); + } + + protected byte[] internalGenerateSignature(byte[] message, byte[] optRand) + { + return internalGenerateSignature(privKey, null, message, optRand); + } + + private static byte[] internalGenerateSignature(SLHDSAPrivateKeyParameters privKey, byte[] msgPrefix, byte[] msg, + byte[] optRand) + { + // TODO Check init via privKey != null + + SLHDSAEngine engine = privKey.getParameters().getEngine(); + engine.init(privKey.pk.seed); + + Fors fors = new Fors(engine); + byte[] R = engine.PRF_msg(privKey.sk.prf, optRand, msgPrefix, msg); + + IndexedDigest idxDigest = engine.H_msg(R, privKey.pk.seed, privKey.pk.root, msgPrefix, msg); + byte[] mHash = idxDigest.digest; + long idx_tree = idxDigest.idx_tree; + int idx_leaf = idxDigest.idx_leaf; + // FORS sign + ADRS adrs = new ADRS(); + adrs.setTypeAndClear(ADRS.FORS_TREE); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + SIG_FORS[] sig_fors = fors.sign(mHash, privKey.sk.seed, privKey.pk.seed, adrs); + // get FORS public key - spec shows M? + adrs = new ADRS(); + adrs.setTypeAndClear(ADRS.FORS_TREE); + adrs.setTreeAddress(idx_tree); + adrs.setKeyPairAddress(idx_leaf); + byte[] PK_FORS = fors.pkFromSig(sig_fors, mHash, privKey.pk.seed, adrs); + + // sign FORS public key with HT + ADRS treeAdrs = new ADRS(); + treeAdrs.setTypeAndClear(ADRS.TREE); + + HT ht = new HT(engine, privKey.getSeed(), privKey.getPublicSeed()); + byte[] SIG_HT = ht.sign(PK_FORS, idx_tree, idx_leaf); + + byte[][] sigComponents = new byte[sig_fors.length + 2][]; + sigComponents[0] = R; + + for (int i = 0; i != sig_fors.length; i++) + { + sigComponents[1 + i] = Arrays.concatenate(sig_fors[i].sk, Arrays.concatenate(sig_fors[i].authPath)); + } + sigComponents[sigComponents.length - 1] = SIG_HT; + + return Arrays.concatenate(sigComponents); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/WotsPlus.java b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/WotsPlus.java new file mode 100644 index 0000000000..abe5a344d3 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/slhdsa/WotsPlus.java @@ -0,0 +1,166 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Pack; + +class WotsPlus +{ + private final SLHDSAEngine engine; + private final int w; + + WotsPlus(SLHDSAEngine engine) + { + this.engine = engine; + this.w = this.engine.WOTS_W; + } + + byte[] pkGen(byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) + { + ADRS wotspkADRS = new ADRS(paramAdrs); // copy address to create OTS public key address + + byte[][] tmp = new byte[engine.WOTS_LEN][]; + for (int i = 0; i < engine.WOTS_LEN; i++) + { + ADRS adrs = new ADRS(paramAdrs); + adrs.setTypeAndClear(ADRS.WOTS_PRF); + adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + adrs.setChainAddress(i); + adrs.setHashAddress(0); + + byte[] sk = engine.PRF(pkSeed, skSeed, adrs); + + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + adrs.setChainAddress(i); + adrs.setHashAddress(0); + tmp[i] = chain(sk, 0, w - 1, pkSeed, adrs); + } + + wotspkADRS.setTypeAndClear(ADRS.WOTS_PK); + wotspkADRS.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + + return engine.T_l(pkSeed, wotspkADRS, Arrays.concatenate(tmp)); + } + + // #Input: Input string X, start index i, number of steps s, public seed PK.seed, address ADRS + // #Output: value of F iterated s times on X + byte[] chain(byte[] X, int i, int s, byte[] pkSeed, ADRS adrs) + { + if (s == 0) + { + return Arrays.clone(X); + } + if ((i + s) > (this.w - 1)) + { + return null; + } + byte[] result = X; + for (int j = 0; j < s; ++j) + { + adrs.setHashAddress(i + j); + result = engine.F(pkSeed, adrs, result); + } + return result; + } + + // #Input: Message M, secret seed SK.seed, public seed PK.seed, address ADRS + // #Output: WOTS+ signature sig + public byte[] sign(byte[] M, byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) + { + ADRS adrs = new ADRS(paramAdrs); + + int[] msg = new int[engine.WOTS_LEN]; + + // convert message to base w + base_w(M, 0, w, msg, 0, engine.WOTS_LEN1); + + // compute checksum + int csum = 0; + for (int i = 0; i < engine.WOTS_LEN1; i++) + { + csum += w - 1 - msg[i]; + } + + // convert csum to base w + if ((engine.WOTS_LOGW % 8) != 0) + { + csum = csum << (8 - ((engine.WOTS_LEN2 * engine.WOTS_LOGW) % 8)); + } + int len_2_bytes = (engine.WOTS_LEN2 * engine.WOTS_LOGW + 7) / 8; + byte[] csum_bytes = Pack.intToBigEndian(csum); + base_w(csum_bytes, 4 - len_2_bytes, w, msg, engine.WOTS_LEN1, engine.WOTS_LEN2); + + byte[][] sig = new byte[engine.WOTS_LEN][]; + for (int i = 0; i < engine.WOTS_LEN; i++) + { + adrs.setTypeAndClear(ADRS.WOTS_PRF); + adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + adrs.setChainAddress(i); + adrs.setHashAddress(0); + byte[] sk = engine.PRF(pkSeed, skSeed, adrs); + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + adrs.setChainAddress(i); + adrs.setHashAddress(0); + sig[i] = chain(sk, 0, msg[i], pkSeed, adrs); + } + return Arrays.concatenate(sig); + } + + // + // Input: len_X-byte string X, int w, output length out_len + // Output: out_len int array basew + void base_w(byte[] X, int XOff, int w, int[] output, int outOff, int outLen) + { + int total = 0; + int bits = 0; + + for (int consumed = 0; consumed < outLen; consumed++) + { + if (bits == 0) + { + total = X[XOff++]; + bits += 8; + } + bits -= engine.WOTS_LOGW; + output[outOff++] = ((total >>> bits) & (w - 1)); + } + } + + public byte[] pkFromSig(byte[] sig, byte[] M, byte[] pkSeed, ADRS adrs) + { + ADRS wotspkADRS = new ADRS(adrs); + + int[] msg = new int[engine.WOTS_LEN]; + + // convert message to base w + base_w(M, 0, w, msg, 0, engine.WOTS_LEN1); + + // compute checksum + int csum = 0; + for (int i = 0; i < engine.WOTS_LEN1; i++ ) + { + csum += w - 1 - msg[i]; + } + + // convert csum to base w + csum = csum << (8 - ((engine.WOTS_LEN2 * engine.WOTS_LOGW) % 8)); + int len_2_bytes = (engine.WOTS_LEN2 * engine.WOTS_LOGW + 7) / 8; + byte[] csum_bytes = Pack.intToBigEndian(csum); + base_w(csum_bytes, 4 - len_2_bytes, w, msg, engine.WOTS_LEN1, engine.WOTS_LEN2); + + byte[] sigI = new byte[engine.N]; + byte[][] tmp = new byte[engine.WOTS_LEN][]; + for (int i = 0; i < engine.WOTS_LEN; i++ ) + { + adrs.setChainAddress(i); + System.arraycopy(sig, i * engine.N, sigI, 0, engine.N); + tmp[i] = chain(sigI, msg[i], w - 1 - msg[i], pkSeed, adrs); + } + + wotspkADRS.setTypeAndClear(ADRS.WOTS_PK); + wotspkADRS.setKeyPairAddress(adrs.getKeyPairAddress()); + + return engine.T_l(pkSeed, wotspkADRS, Arrays.concatenate(tmp)); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/GF16Utils.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/GF16Utils.java new file mode 100644 index 0000000000..2da96b17c2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/GF16Utils.java @@ -0,0 +1,209 @@ +package org.bouncycastle.pqc.crypto.snova; + +import org.bouncycastle.util.GF16; + +class GF16Utils +{ + static void encodeMergeInHalf(byte[] m, int mlen, byte[] menc) + { + int i, half = (mlen + 1) >>> 1; + // Process pairs of 4-bit values + for (i = 0; i < mlen / 2; i++, half++) + { + menc[i] = (byte)(m[i] | (m[half] << 4)); + } + // If there is an extra nibble (odd number of nibbles), store it directly in lower 4 bits. + if ((mlen & 1) == 1) + { + menc[i] = m[i]; + } + } + + static void decodeMergeInHalf(byte[] byteArray, byte[] gf16Array, int nGf16) + { + int i, half = (nGf16 + 1) >>> 1; + // Process pairs of 4-bit values + for (i = 0; i < half; i++) + { + gf16Array[i] = (byte)(byteArray[i] & 0x0F); + gf16Array[i + half] = (byte)((byteArray[i] >>> 4) & 0x0F); + } + } + + static void gf16mTranMulMul(byte[] sign, int signOff, byte[] a, byte[] b, byte[] q1, byte[] q2, byte[] tmp, + byte[] left, byte[] right, int rank) + { + for (int i = 0, leftOff = 0, dOff = 0; i < rank; i++, leftOff += rank) + { + for (int j = 0; j < rank; j++) + { + byte result = 0; + for (int k = 0, aOff = signOff + j, bOff = i; k < rank; ++k, aOff += rank, bOff += rank) + { + result ^= GF16.mul(sign[aOff], q1[bOff]); + } + tmp[j] = result; + } + + for (int j = 0, jxl = 0; j < rank; j++, jxl += rank) + { + byte result = 0; + for (int k = 0; k < rank; ++k) + { + result ^= GF16.mul(a[jxl + k], tmp[k]); + } + left[i + jxl] = result; + } + for (int j = 0; j < rank; j++) + { + tmp[j] = GF16.innerProduct(q2, leftOff, sign, signOff + j, rank); + } + + for (int j = 0; j < rank; j++) + { + right[dOff++] = GF16.innerProduct(tmp, 0, b, j, rank); + } + } + } + + // tmp = a * b, d = tmp * c -> d = (a * b) * c + static void gf16mMulMul(byte[] a, byte[] b, byte[] c, byte[] tmp, byte[] d, int rank) + { + for (int i = 0, leftOff = 0, dOff = 0; i < rank; i++, leftOff += rank) + { + for (int j = 0; j < rank; j++) + { + tmp[j] = GF16.innerProduct(a, leftOff, b, j, rank); + } + + for (int j = 0; j < rank; j++) + { + d[dOff++] = GF16.innerProduct(tmp, 0, c, j, rank); + } + } + } + + static void gf16mMul(byte[] a, byte[] b, byte[] c, int rank) + { + for (int i = 0, aOff = 0, cOff = 0; i < rank; i++, aOff += rank) + { + for (int j = 0; j < rank; j++) + { + c[cOff++] = GF16.innerProduct(a, aOff, b, j, rank); + } + } + } + + static void gf16mMulMulTo(byte[] a, byte[] b, byte[] c, byte[] tmp, byte[] d, int rank) + { + for (int i = 0, leftOff = 0, dOff = 0; i < rank; i++, leftOff += rank) + { + for (int j = 0; j < rank; j++) + { + tmp[j] = GF16.innerProduct(a, leftOff, b, j, rank); + } + + for (int j = 0; j < rank; j++) + { + d[dOff++] ^= GF16.innerProduct(tmp, 0, c, j, rank); + } + } + } + + static void gf16mMulTo(byte[] a, byte[] b, byte[] c, int rank) + { + for (int i = 0, aOff = 0, cOff = 0; i < rank; i++, aOff += rank) + { + for (int j = 0; j < rank; j++) + { + c[cOff++] ^= GF16.innerProduct(a, aOff, b, j, rank); + } + } + } + + // d = a * b, e = b * c + static void gf16mMulToTo(byte[] a, byte[] b, byte[] c, byte[] d, byte[] e, int rank) + { + for (int i = 0, leftOff = 0, outOff = 0; i < rank; i++, leftOff += rank) + { + for (int j = 0; j < rank; j++) + { + d[outOff] ^= GF16.innerProduct(a, leftOff, b, j, rank); + e[outOff++] ^= GF16.innerProduct(b, leftOff, c, j, rank); + } + } + } + + static void gf16mMulTo(byte[] a, byte[] b, byte[] c, int cOff, int rank) + { + for (int i = 0, aOff = 0; i < rank; i++, aOff += rank) + { + for (int j = 0; j < rank; j++) + { + c[cOff++] ^= GF16.innerProduct(a, aOff, b, j, rank); + } + } + } + + // d ^= a * b + c * d + static void gf16mMulTo(byte[] a, byte[] b, byte[] c, byte[] d, byte[] e, int eOff, int rank) + { + for (int i = 0, leftOff = 0; i < rank; i++, leftOff += rank) + { + for (int j = 0; j < rank; j++) + { + e[eOff++] ^= GF16.innerProduct(a, leftOff, b, j, rank) ^ GF16.innerProduct(c, leftOff, d, j, rank); + } + } + } + + static void gf16mMulTo(byte[] a, byte[] b, int bOff, byte[] c, int cOff, int rank) + { + for (int i = 0, aOff = 0; i < rank; i++, aOff += rank) + { + for (int j = 0; j < rank; j++) + { + c[cOff++] ^= GF16.innerProduct(a, aOff, b, bOff + j, rank); + } + } + } + + /** + * Conversion 4 bit -> 32 bit representation + */ + static int gf16FromNibble(int idx) + { + int middle = idx | (idx << 4); + return ((middle & 0x41) | ((middle << 2) & 0x208)); + } + + private static final int GF16_MASK = 0x249; // Mask for GF(2^4) reduction + + // Constant-time GF16 != 0 check + static int ctGF16IsNotZero(byte val) + { + int v = val & 0xFF; + return (v | (v >>> 1) | (v >>> 2) | (v >>> 3)) & 1; + } + + // GF16 reduction modulo x^4 + x + 1 + private static int gf16Reduce(int idx) + { + int res = idx & 0x49249249; + int upper = idx >>> 12; + res ^= upper ^ (upper << 3); + upper = res >>> 12; + res ^= upper ^ (upper << 3); + upper = res >>> 12; + res ^= upper ^ (upper << 3); + return res & GF16_MASK; + } + + // Convert 32-bit reduced value to 4-bit nibble + static byte gf16ToNibble(int val) + { + int res = gf16Reduce(val); + res |= res >>> 4; + return (byte)((res & 0x5) | ((res >>> 2) & 0xA)); + } +} \ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/MapGroup1.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/MapGroup1.java new file mode 100644 index 0000000000..ff4e7531ee --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/MapGroup1.java @@ -0,0 +1,118 @@ +package org.bouncycastle.pqc.crypto.snova; + +import org.bouncycastle.util.GF16; + +class MapGroup1 +{ + public final byte[][][][] p11; // [m][v][v] + public final byte[][][][] p12; // [m][v][o] + public final byte[][][][] p21; // [m][o][v] + public final byte[][][] aAlpha; // [m][alpha] + public final byte[][][] bAlpha; // [m][alpha] + public final byte[][][] qAlpha1;// [m][alpha] + public final byte[][][] qAlpha2;// [m][alpha] + + public MapGroup1(SnovaParameters params) + { + int m = params.getM(); + int v = params.getV(); + int o = params.getO(); + int alpha = params.getAlpha(); + int lsq = params.getLsq(); + p11 = new byte[m][v][v][lsq]; + p12 = new byte[m][v][o][lsq]; + p21 = new byte[m][o][v][lsq]; + aAlpha = new byte[m][alpha][lsq]; + bAlpha = new byte[m][alpha][lsq]; + qAlpha1 = new byte[m][alpha][lsq]; + qAlpha2 = new byte[m][alpha][lsq]; + } + + void decode(byte[] input, int len, boolean isl4or5) + { + //TODO: when (lsq & 1) == 1 + int inOff = decodeP(input, 0, p11, len); + inOff += decodeP(input, inOff, p12, len - inOff); + inOff += decodeP(input, inOff, p21, len - inOff); + if (isl4or5) + { + inOff += decodeAlpha(input, inOff, aAlpha, len - inOff); + inOff += decodeAlpha(input, inOff, bAlpha, len - inOff); + inOff += decodeAlpha(input, inOff, qAlpha1, len - inOff); + decodeAlpha(input, inOff, qAlpha2, len - inOff); + } + } + + static int decodeP(byte[] input, int inOff, byte[][][][] p, int len) + { + int rlt = 0; + for (int i = 0; i < p.length; ++i) + { + rlt += decodeAlpha(input, inOff + rlt, p[i], len); + } + return rlt; + } + + private static int decodeAlpha(byte[] input, int inOff, byte[][][] alpha, int len) + { + int rlt = 0; + for (int i = 0; i < alpha.length; ++i) + { + rlt += decodeArray(input, inOff + rlt, alpha[i], len - rlt); + } + return rlt; + } + + static int decodeArray(byte[] input, int inOff, byte[][] array, int len) + { + int rlt = 0; + for (int j = 0; j < array.length; ++j) + { + int tmp = Math.min(array[j].length, len << 1); + GF16.decode(input, inOff + rlt, array[j], 0, tmp); + tmp = (tmp + 1) >> 1; + rlt += tmp; + len -= tmp; + } + return rlt; + } + + void fill(byte[] input, boolean isl4or5) + { + int inOff = fillP(input, 0, p11, input.length); + inOff += fillP(input, inOff, p12, input.length - inOff); + inOff += fillP(input, inOff, p21, input.length - inOff); + if (isl4or5) + { + inOff += fillAlpha(input, inOff, aAlpha, input.length - inOff); + inOff += fillAlpha(input, inOff, bAlpha, input.length - inOff); + inOff += fillAlpha(input, inOff, qAlpha1, input.length - inOff); + fillAlpha(input, inOff, qAlpha2, input.length - inOff); + } + } + + static int fillP(byte[] input, int inOff, byte[][][][] p, int len) + { + int rlt = 0; + for (int i = 0; i < p.length; ++i) + { + rlt += fillAlpha(input, inOff + rlt, p[i], len - rlt); + } + return rlt; + } + + static int fillAlpha(byte[] input, int inOff, byte[][][] alpha, int len) + { + int rlt = 0; + for (int i = 0; i < alpha.length; ++i) + { + for (int j = 0; j < alpha[i].length; ++j) + { + int tmp = Math.min(alpha[i][j].length, len - rlt); + System.arraycopy(input, inOff + rlt, alpha[i][j], 0, tmp); + rlt += tmp; + } + } + return rlt; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/MapGroup2.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/MapGroup2.java new file mode 100644 index 0000000000..946ad2ab99 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/MapGroup2.java @@ -0,0 +1,19 @@ +package org.bouncycastle.pqc.crypto.snova; + +class MapGroup2 +{ + public final byte[][][][] f11; // [m][v][v] + public final byte[][][][] f12; // [m][v][o] + public final byte[][][][] f21; // [m][o][v] + + public MapGroup2(SnovaParameters params) + { + int m = params.getM(); + int v = params.getV(); + int o = params.getO(); + int lsq = params.getLsq(); + f11 = new byte[m][v][v][lsq]; + f12 = new byte[m][v][o][lsq]; + f21 = new byte[m][o][v][lsq]; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaEngine.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaEngine.java new file mode 100644 index 0000000000..1651dab43d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaEngine.java @@ -0,0 +1,587 @@ +package org.bouncycastle.pqc.crypto.snova; + +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.modes.CTRModeCipher; +import org.bouncycastle.crypto.modes.SICBlockCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.GF16; +import org.bouncycastle.util.Integers; +import org.bouncycastle.util.Pack; + +class SnovaEngine +{ + private final static Map fixedAbqSet = new HashMap();//key is o + private final static Map sSet = new HashMap(); //key is l + private final static Map xSSet = new HashMap(); //key is l + private final SnovaParameters params; + private final int l; + private final int lsq; + private final int m; + private final int v; + private final int o; + private final int alpha; + private final int n; + final byte[][] S; + final int[][] xS; + + public SnovaEngine(SnovaParameters params) + { + this.params = params; + this.l = params.getL(); + this.lsq = params.getLsq(); + this.m = params.getM(); + this.v = params.getV(); + this.o = params.getO(); + this.alpha = params.getAlpha(); + this.n = params.getN(); + if (!xSSet.containsKey(Integers.valueOf(l))) + { + byte[][] S = new byte[l][lsq]; + int[][] xS = new int[l][lsq]; + be_aI(S[0], 0, (byte)1); + beTheS(S[1]); + for (int index = 2; index < l; ++index) + { + GF16Utils.gf16mMul(S[index - 1], S[1], S[index], l); + } + + for (int index = 0; index < l; ++index) + { + for (int ij = 0; ij < lsq; ++ij) + { + xS[index][ij] = GF16Utils.gf16FromNibble(S[index][ij]); + } + } + sSet.put(Integers.valueOf(l), S); + xSSet.put(Integers.valueOf(l), xS); + } + S = (byte[][])sSet.get(Integers.valueOf(l)); + xS = (int[][])xSSet.get(Integers.valueOf(l)); + if (l < 4 && !fixedAbqSet.containsKey(Integers.valueOf(o))) + { + int alphaxl = alpha * l; + int alphaxlsq = alphaxl * l; + int oxalphaxl = o * alphaxl; + int oxalphaxlsq = o * alphaxlsq; + byte[] fixedAbq = new byte[oxalphaxlsq << 2]; + byte[] rngOut = new byte[oxalphaxlsq + oxalphaxl]; + byte[] q12 = new byte[oxalphaxl << 2]; + byte[] seed = "SNOVA_ABQ".getBytes(); + SHAKEDigest shake = new SHAKEDigest(256); + shake.update(seed, 0, seed.length); + shake.doFinal(rngOut, 0, rngOut.length); + GF16.decode(rngOut, fixedAbq, oxalphaxlsq << 1); + GF16.decode(rngOut, alphaxlsq, q12, 0, oxalphaxl << 1); + // Post-processing for invertible matrices + for (int pi = 0, pixAlphaxlsq = 0, pixalphaxl = 0; pi < o; ++pi, pixAlphaxlsq += alphaxlsq, pixalphaxl += alphaxl) + { + for (int a = 0, axl = pixalphaxl, axlsq = pixAlphaxlsq; a < alpha; ++a, axl += l, axlsq += lsq) + { + makeInvertibleByAddingAS(fixedAbq, axlsq); + makeInvertibleByAddingAS(fixedAbq, oxalphaxlsq + axlsq); + genAFqS(q12, axl, fixedAbq, (oxalphaxlsq << 1) + axlsq); + genAFqS(q12, oxalphaxl + axl, fixedAbq, (oxalphaxlsq << 1) + oxalphaxlsq + axlsq); + } + } + fixedAbqSet.put(Integers.valueOf(o), fixedAbq); + } + } + + private void beTheS(byte[] target) + { + // Set all elements to 8 - (i + j) in GF16 (4-bit values) + for (int i = 0, il = 0; i < l; ++i, il += l) + { + for (int j = 0; j < l; ++j) + { + int value = 8 - (i + j); + target[il + j] = (byte)(value & 0x0F); // Mask to 4 bits + } + } + + // Special case for rank 5 + if (l == 5) + { + target[24] = (byte)9; // Set (4,4) to 9 + } + } + + private void be_aI(byte[] target, int off, byte a) + { + // Ensure 'a' iss a valid 4-bit GF16 element + int l1 = l + 1; + for (int i = 0; i < l; ++i, off += l1) + { + target[off] = a; + } + } + + // Constant-time GF16 matrix generation + private void genAFqSCT(byte[] c, int cOff, byte[] ptMatrix) + { + int[] xTemp = new int[lsq]; + int l1 = l + 1; + // Initialize diagonal with c[0] + int cX = GF16Utils.gf16FromNibble(c[cOff]); + for (int ij = 0, ijl1 = 0; ij < l; ij++, ijl1 += l1) + { + xTemp[ijl1] = cX; + } + + // Process middle coefficients + for (int i1 = 1; i1 < l - 1; i1++) + { + cX = GF16Utils.gf16FromNibble(c[cOff + i1]); + for (int ij = 0; ij < lsq; ij++) + { + xTemp[ij] ^= cX * xS[i1][ij]; + } + } + + // Handle last coefficient with constant-time selection + int zero = GF16Utils.ctGF16IsNotZero(c[cOff + l - 1]); + int val = zero * c[cOff + l - 1] + (1 - zero) * (15 + GF16Utils.ctGF16IsNotZero(c[cOff]) - c[cOff]); + cX = GF16Utils.gf16FromNibble((byte)val); + + for (int ij = 0; ij < lsq; ij++) + { + xTemp[ij] ^= cX * xS[l - 1][ij]; + ptMatrix[ij] = GF16Utils.gf16ToNibble(xTemp[ij]); + } + Arrays.fill(xTemp, 0); // Secure clear + } + + private void makeInvertibleByAddingAS(byte[] source, int off) + { + if (gf16Determinant(source, off) != 0) + { + return; + } + + for (int a = 1; a < 16; a++) + { + generateASMatrixTo(source, off, (byte)a); + + if (gf16Determinant(source, off) != 0) + { + return; + } + } + } + + private byte gf16Determinant(byte[] matrix, int off) + { + switch (l) + { + case 2: + return determinant2x2(matrix, off); + case 3: + return determinant3x3(matrix, off); + case 4: + return determinant4x4(matrix, off); + case 5: + return determinant5x5(matrix, off); + default: + throw new IllegalStateException(); + } + } + + private byte determinant2x2(byte[] m, int off) + { + return (byte)(GF16.mul(m[off], m[off + 3]) ^ GF16.mul(m[off + 1], m[off + 2])); + } + + private byte determinant3x3(byte[] m, int off) + { + byte m00 = m[off++]; + byte m01 = m[off++]; + byte m02 = m[off++]; + byte m10 = m[off++]; + byte m11 = m[off++]; + byte m12 = m[off++]; + byte m20 = m[off++]; + byte m21 = m[off++]; + byte m22 = m[off]; + return (byte)(GF16.mul(m00, GF16.mul(m11, m22) ^ GF16.mul(m12, m21)) ^ + GF16.mul(m01, GF16.mul(m10, m22) ^ GF16.mul(m12, m20)) ^ + GF16.mul(m02, GF16.mul(m10, m21) ^ GF16.mul(m11, m20))); + } + + private byte determinant4x4(byte[] m, int off) + { + byte m00 = m[off++]; + byte m01 = m[off++]; + byte m02 = m[off++]; + byte m03 = m[off++]; + byte m10 = m[off++]; + byte m11 = m[off++]; + byte m12 = m[off++]; + byte m13 = m[off++]; + byte m20 = m[off++]; + byte m21 = m[off++]; + byte m22 = m[off++]; + byte m23 = m[off++]; + byte m30 = m[off++]; + byte m31 = m[off++]; + byte m32 = m[off++]; + byte m33 = m[off]; + + byte m22xm33_m23xm32 = (byte)(GF16.mul(m22, m33) ^ GF16.mul(m23, m32)); + byte m21xm33_m23xm31 = (byte)(GF16.mul(m21, m33) ^ GF16.mul(m23, m31)); + byte m21xm32_m22xm31 = (byte)(GF16.mul(m21, m32) ^ GF16.mul(m22, m31)); + byte m20xm33_m23xm30 = (byte)(GF16.mul(m20, m33) ^ GF16.mul(m23, m30)); + byte m20xm32_m32xm30 = (byte)(GF16.mul(m20, m32) ^ GF16.mul(m22, m30)); + byte m20xm31_m21xm30 = (byte)(GF16.mul(m20, m31) ^ GF16.mul(m21, m30)); + // POD -> entry[a][b] * (entry[c][d] * entry[e][f] + entry[g][h] * entry[i][j]) + return (byte)(GF16.mul(m00, GF16.mul(m11, m22xm33_m23xm32) ^ + GF16.mul(m12, m21xm33_m23xm31) ^ GF16.mul(m13, m21xm32_m22xm31)) ^ + GF16.mul(m01, GF16.mul(m10, m22xm33_m23xm32) ^ + GF16.mul(m12, m20xm33_m23xm30) ^ GF16.mul(m13, m20xm32_m32xm30)) ^ + GF16.mul(m02, GF16.mul(m10, m21xm33_m23xm31) ^ + GF16.mul(m11, m20xm33_m23xm30) ^ GF16.mul(m13, m20xm31_m21xm30)) ^ + GF16.mul(m03, GF16.mul(m10, m21xm32_m22xm31) ^ + GF16.mul(m11, m20xm32_m32xm30) ^ GF16.mul(m12, m20xm31_m21xm30))); + } + + private byte determinant5x5(byte[] m, int off) + { + byte m00 = m[off++]; + byte m01 = m[off++]; + byte m02 = m[off++]; + byte m03 = m[off++]; + byte m04 = m[off++]; + byte m10 = m[off++]; + byte m11 = m[off++]; + byte m12 = m[off++]; + byte m13 = m[off++]; + byte m14 = m[off++]; + byte m20 = m[off++]; + byte m21 = m[off++]; + byte m22 = m[off++]; + byte m23 = m[off++]; + byte m24 = m[off++]; + byte m30 = m[off++]; + byte m31 = m[off++]; + byte m32 = m[off++]; + byte m33 = m[off++]; + byte m34 = m[off++]; + byte m40 = m[off++]; + byte m41 = m[off++]; + byte m42 = m[off++]; + byte m43 = m[off++]; + byte m44 = m[off]; + + byte m10xm21_m11xm20 = (byte)(GF16.mul(m10, m21) ^ GF16.mul(m11, m20)); + byte m10xm22_m12xm20 = (byte)(GF16.mul(m10, m22) ^ GF16.mul(m12, m20)); + byte m10xm23_m13xm20 = (byte)(GF16.mul(m10, m23) ^ GF16.mul(m13, m20)); + byte m10xm24_m14xm20 = (byte)(GF16.mul(m10, m24) ^ GF16.mul(m14, m20)); + byte m11xm22_m12xm21 = (byte)(GF16.mul(m11, m22) ^ GF16.mul(m12, m21)); + byte m11xm23_m13xm21 = (byte)(GF16.mul(m11, m23) ^ GF16.mul(m13, m21)); + byte m11xm24_m14xm21 = (byte)(GF16.mul(m11, m24) ^ GF16.mul(m14, m21)); + byte m12xm23_m13xm22 = (byte)(GF16.mul(m12, m23) ^ GF16.mul(m13, m22)); + byte m12xm24_m14xm22 = (byte)(GF16.mul(m12, m24) ^ GF16.mul(m14, m22)); + byte m13xm24_m14xm23 = (byte)(GF16.mul(m13, m24) ^ GF16.mul(m14, m23)); + + byte result = (byte)GF16.mul(//determinant3x3(m, off, 0, 1, 2), + (GF16.mul(m00, m11xm22_m12xm21) ^ + GF16.mul(m01, m10xm22_m12xm20) ^ + GF16.mul(m02, m10xm21_m11xm20)), + (GF16.mul(m33, m44) ^ GF16.mul(m34, m43))); + result ^= GF16.mul(//determinant3x3(m, off, 0, 1, 3), + (GF16.mul(m00, m11xm23_m13xm21) ^ + GF16.mul(m01, m10xm23_m13xm20) ^ + GF16.mul(m03, m10xm21_m11xm20)), + (GF16.mul(m32, m44) ^ GF16.mul(m34, m42))); + result ^= GF16.mul(//determinant3x3(m, off, 0, 1, 4), + (GF16.mul(m00, m11xm24_m14xm21) ^ + GF16.mul(m01, m10xm24_m14xm20) ^ + GF16.mul(m04, m10xm21_m11xm20)), + (GF16.mul(m32, m43) ^ GF16.mul(m33, m42))); + result ^= GF16.mul(//determinant3x3(m, off, 0, 2, 3), + (GF16.mul(m00, m12xm23_m13xm22) ^ + GF16.mul(m02, m10xm23_m13xm20) ^ + GF16.mul(m03, m10xm22_m12xm20)), + (GF16.mul(m31, m44) ^ GF16.mul(m34, m41))); + result ^= GF16.mul(//determinant3x3(m, off, 0, 2, 4), + (GF16.mul(m00, m12xm24_m14xm22) ^ + GF16.mul(m02, m10xm24_m14xm20) ^ + GF16.mul(m04, m10xm22_m12xm20)), + (GF16.mul(m31, m43) ^ GF16.mul(m33, m41))); + result ^= GF16.mul(//determinant3x3(m, off, 0, 3, 4), + (GF16.mul(m00, m13xm24_m14xm23) ^ + GF16.mul(m03, m10xm24_m14xm20) ^ + GF16.mul(m04, m10xm23_m13xm20)), + (GF16.mul(m31, m42) ^ GF16.mul(m32, m41))); + result ^= GF16.mul(//determinant3x3(m, off, 1, 2, 3), + (GF16.mul(m01, m12xm23_m13xm22) ^ + GF16.mul(m02, m11xm23_m13xm21) ^ + GF16.mul(m03, m11xm22_m12xm21)), + (GF16.mul(m30, m44) ^ GF16.mul(m34, m40))); + result ^= GF16.mul(//determinant3x3(m, off, 1, 2, 4), + (GF16.mul(m01, m12xm24_m14xm22) ^ + GF16.mul(m02, m11xm24_m14xm21) ^ + GF16.mul(m04, m11xm22_m12xm21)), + (GF16.mul(m30, m43) ^ GF16.mul(m33, m40))); + result ^= GF16.mul(//determinant3x3(m, off, 1, 3, 4), + (GF16.mul(m01, m13xm24_m14xm23) ^ + GF16.mul(m03, m11xm24_m14xm21) ^ + GF16.mul(m04, m11xm23_m13xm21)), + (GF16.mul(m30, m42) ^ GF16.mul(m32, m40))); + result ^= GF16.mul(//determinant3x3(m, off, 2, 3, 4), + (GF16.mul(m02, m13xm24_m14xm23) ^ + GF16.mul(m03, m12xm24_m14xm22) ^ + GF16.mul(m04, m12xm23_m13xm22)), + (GF16.mul(m30, m41) ^ GF16.mul(m31, m40))); + return result; + } + + private void generateASMatrixTo(byte[] target, int off, byte a) + { + for (int i = 0, ixl = off; i < l; i++, ixl += l) + { + for (int j = 0; j < l; j++) + { + byte coefficient = (byte)(8 - (i + j)); + if (l == 5 && i == 4 && j == 4) + { + coefficient = 9; + } + target[ixl + j] ^= GF16.mul(coefficient, a); + } + } + } + + private void genAFqS(byte[] c, int cOff, byte[] ptMatrix, int off) + { + // Initialize with be_aI + be_aI(ptMatrix, off, c[cOff]); + + // Process middle terms + for (int i = 1; i < l - 1; ++i) + { + gf16mScaleTo(S[i], c[cOff + i], ptMatrix, off); + } + + // Handle last term with special case + byte lastScalar = (byte)((c[cOff + l - 1] != 0) ? c[cOff + l - 1] : 16 - (c[cOff] + (c[cOff] == 0 ? 1 : 0))); + gf16mScaleTo(S[l - 1], lastScalar, ptMatrix, off); + } + + private void gf16mScaleTo(byte[] a, byte k, byte[] c, int cOff) + { + for (int i = 0, il = 0; i < l; ++i, il += l) + { + for (int j = 0; j < l; ++j) + { + c[il + j + cOff] ^= GF16.mul(a[il + j], k); + } + } + } + + private void genF(MapGroup2 map2, MapGroup1 map1, byte[][][] T12) + { + // Copy initial matrices + copy4DMatrix(map1.p11, map2.f11, m, v, v, lsq); + copy4DMatrix(map1.p12, map2.f12, m, v, o, lsq); + copy4DMatrix(map1.p21, map2.f21, m, o, v, lsq); + + for (int i = 0; i < m; i++) + { + for (int j = 0; j < v; j++) + { + for (int k = 0; k < o; k++) + { + for (int index = 0; index < v; index++) + { + GF16Utils.gf16mMulToTo(map1.p11[i][j][index], T12[index][k], map1.p11[i][index][j], map2.f12[i][j][k], map2.f21[i][k][j], l); + } + } + } + } + } + + private static void copy4DMatrix(byte[][][][] src, byte[][][][] dest, int dim1, int dim2, int dim3, int lsq) + { + for (int i = 0; i < dim1; i++) + { + for (int j = 0; j < dim2; j++) + { + for (int k = 0; k < dim3; k++) + { + System.arraycopy(src[i][j][k], 0, dest[i][j][k], 0, lsq); + } + } + } + } + + public void genP22(byte[] outP22, int outOff, byte[][][] T12, byte[][][][] P21, byte[][][][] F12) + { + // Initialize P22 with zeros + int oxlsq = o * lsq; + int oxoxlsq = oxlsq * o; + byte[] P22 = new byte[m * oxoxlsq]; + + for (int i = 0, ixoxolsq = 0; i < m; i++, ixoxolsq += oxoxlsq) + { + for (int j = 0, jxoxlsq = ixoxolsq; j < o; j++, jxoxlsq += oxlsq) + { + for (int k = 0, kxlsq = jxoxlsq; k < o; k++, kxlsq += lsq) + { + for (int index = 0; index < v; index++) + { + // P22[i][j][k] ^= (T12[index][j] * F12[i][index][k]) ^ (P21[i][j][index] * T12[index][k]) + GF16Utils.gf16mMulTo(T12[index][j], F12[i][index][k], P21[i][j][index], T12[index][k], P22, kxlsq, l); + } + } + } + } + + // Convert GF16 elements to packed bytes + GF16.encode(P22, outP22, outOff, P22.length); + } + + private void genSeedsAndT12(byte[][][] T12, byte[] skSeed) + { + int gf16sPrngPrivate = v * o * l; + int bytesPrngPrivate = (gf16sPrngPrivate + 1) >>> 1; + byte[] prngOutput = new byte[bytesPrngPrivate]; + + // Generate PRNG output using SHAKE-256 + SHAKEDigest shake = new SHAKEDigest(256); + shake.update(skSeed, 0, skSeed.length); + shake.doFinal(prngOutput, 0, prngOutput.length); + + // Convert bytes to GF16 array + byte[] gf16PrngOutput = new byte[gf16sPrngPrivate]; + GF16.decode(prngOutput, gf16PrngOutput, gf16sPrngPrivate); + + // Generate T12 matrices + int ptArray = 0; + for (int j = 0; j < v; j++) + { + for (int k = 0; k < o; k++) + { + //gen_a_FqS_ct + genAFqSCT(gf16PrngOutput, ptArray, T12[j][k]); + ptArray += l; + } + } + } + + public void genABQP(MapGroup1 map1, byte[] pkSeed) + { + int gf16sPrngPublic = lsq * (2 * m * alpha + m * (n * n - m * m)) + l * 2 * m * alpha; + byte[] qTemp = new byte[(m * alpha * l) << 1]; + byte[] prngOutput = new byte[(gf16sPrngPublic + 1) >> 1]; + + if (params.isPkExpandShake()) + { + final int SHAKE128_RATE = 168; // 1344-bit rate = 168 bytes + long blockCounter = 0; + int offset = 0; + int remaining = prngOutput.length; + byte[] counterBytes = new byte[8]; + SHAKEDigest shake = new SHAKEDigest(128); + while (remaining > 0) + { + // Process seed + counter + shake.update(pkSeed, 0, pkSeed.length); + Pack.longToLittleEndian(blockCounter, counterBytes, 0); + shake.update(counterBytes, 0, 8); + + // Calculate bytes to generate in this iteration + int bytesToGenerate = Math.min(remaining, SHAKE128_RATE); + + // Generate output (XOF mode) + shake.doFinal(prngOutput, offset, bytesToGenerate); + + offset += bytesToGenerate; + remaining -= bytesToGenerate; + blockCounter++; + } + } + else + { + // Create a 16-byte IV (all zeros) + byte[] iv = new byte[16]; // automatically zero-initialized + // AES-CTR-based expansion + // Set up AES engine in CTR (SIC) mode. + // SICBlockCipher implements CTR mode for AES. + CTRModeCipher ctrCipher = SICBlockCipher.newInstance(AESEngine.newInstance()); + ctrCipher.init(true, new ParametersWithIV(new KeyParameter(pkSeed), iv)); + int blockSize = ctrCipher.getBlockSize(); // typically 16 bytes + byte[] zeroBlock = new byte[blockSize]; // block of zeros + + int offset = 0; + // Process full blocks + while (offset + blockSize <= prngOutput.length) + { + ctrCipher.processBlock(zeroBlock, 0, prngOutput, offset); + offset += blockSize; + } + // Process any remaining partial block. + if (offset < prngOutput.length) + { + ctrCipher.processBlock(zeroBlock, 0, zeroBlock, 0); + int remaining = prngOutput.length - offset; + System.arraycopy(zeroBlock, 0, prngOutput, offset, remaining); + } + } + if ((lsq & 1) == 0) + { + map1.decode(prngOutput, (gf16sPrngPublic - qTemp.length) >> 1, l >= 4); + } + else + { + byte[] temp = new byte[gf16sPrngPublic - qTemp.length]; + GF16.decode(prngOutput, temp, temp.length); + map1.fill(temp, l >= 4); + } + if (l >= 4) + { + GF16.decode(prngOutput, (gf16sPrngPublic - qTemp.length) >> 1, qTemp, 0, qTemp.length); + int ptArray = 0; + // Post-processing for invertible matrices + int offset = m * alpha * l; + for (int pi = 0; pi < m; ++pi) + { + for (int a = 0; a < alpha; ++a) + { + makeInvertibleByAddingAS(map1.aAlpha[pi][a], 0); + makeInvertibleByAddingAS(map1.bAlpha[pi][a], 0); + genAFqS(qTemp, ptArray, map1.qAlpha1[pi][a], 0); + genAFqS(qTemp, offset, map1.qAlpha2[pi][a], 0); + ptArray += l; + offset += l; + } + } + } + else + { + int oxalphaxlsq = o * alpha * lsq; + byte[] fixedAbq = (byte[])fixedAbqSet.get(Integers.valueOf(o)); + MapGroup1.fillAlpha(fixedAbq, 0, map1.aAlpha, m * oxalphaxlsq); + MapGroup1.fillAlpha(fixedAbq, oxalphaxlsq, map1.bAlpha, (m - 1) * oxalphaxlsq); + MapGroup1.fillAlpha(fixedAbq, oxalphaxlsq * 2, map1.qAlpha1, (m - 2) * oxalphaxlsq); + MapGroup1.fillAlpha(fixedAbq, oxalphaxlsq * 3, map1.qAlpha2, (m - 3) * oxalphaxlsq); + } + } + + public void genMap1T12Map2(SnovaKeyElements keyElements, byte[] pkSeed, byte[] skSeed) + { + // Generate T12 matrix + genSeedsAndT12(keyElements.T12, skSeed); + + // Generate map components + genABQP(keyElements.map1, pkSeed); + + // Generate F matrices + genF(keyElements.map2, keyElements.map1, keyElements.T12); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyElements.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyElements.java new file mode 100644 index 0000000000..0915e590e2 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyElements.java @@ -0,0 +1,69 @@ +package org.bouncycastle.pqc.crypto.snova; + +class SnovaKeyElements +{ + public final MapGroup1 map1; + public final byte[][][] T12; // [v][o] + public final MapGroup2 map2; + + public SnovaKeyElements(SnovaParameters params) + { + int o = params.getO(); + int v = params.getV(); + int lsq = params.getLsq(); + map1 = new MapGroup1(params); + T12 = new byte[v][o][lsq]; + map2 = new MapGroup2(params); + } + + static int copy3d(byte[][][] alpha, byte[] output, int outOff) + { + for (int i = 0; i < alpha.length; ++i) + { + for (int j = 0; j < alpha[i].length; ++j) + { + System.arraycopy(alpha[i][j], 0, output, outOff, alpha[i][j].length); + outOff += alpha[i][j].length; + } + } + return outOff; + } + + static int copy4d(byte[][][][] alpha, byte[] output, int outOff) + { + for (int i = 0; i < alpha.length; ++i) + { + outOff = copy3d(alpha[i], output, outOff); + } + return outOff; + } + + static int copy3d(byte[] input, int inOff, byte[][][] alpha) + { + for (int i = 0; i < alpha.length; ++i) + { + for (int j = 0; j < alpha[i].length; ++j) + { + System.arraycopy(input, inOff, alpha[i][j], 0, alpha[i][j].length); + inOff += alpha[i][j].length; + } + } + return inOff; + } + + static int copy4d(byte[] input, int inOff, byte[][][][] alpha) + { + for (int i = 0; i < alpha.length; ++i) + { + for (int j = 0; j < alpha[i].length; ++j) + { + for (int k = 0; k < alpha[i][j].length; ++k) + { + System.arraycopy(input, inOff, alpha[i][j][k], 0, alpha[i][j][k].length); + inOff += alpha[i][j][k].length; + } + } + } + return inOff; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyGenerationParameters.java new file mode 100644 index 0000000000..ef25e9605d --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyGenerationParameters.java @@ -0,0 +1,22 @@ +package org.bouncycastle.pqc.crypto.snova; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.KeyGenerationParameters; + +public class SnovaKeyGenerationParameters + extends KeyGenerationParameters +{ + private final SnovaParameters params; + + public SnovaKeyGenerationParameters(SecureRandom random, SnovaParameters params) + { + super(random, -1); // Security parameter not used directly + this.params = params; + } + + public SnovaParameters getParameters() + { + return params; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyPairGenerator.java new file mode 100644 index 0000000000..5eb5c11c38 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaKeyPairGenerator.java @@ -0,0 +1,90 @@ +package org.bouncycastle.pqc.crypto.snova; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.util.Arrays; + +public class SnovaKeyPairGenerator + implements AsymmetricCipherKeyPairGenerator +{ + private SnovaEngine engine; + private static final int seedLength = 48; + static final int publicSeedLength = 16; + static final int privateSeedLength = 32; + private SnovaParameters params; + private SecureRandom random; + private boolean initialized; + + @Override + public void init(KeyGenerationParameters param) + { + SnovaKeyGenerationParameters snovaParams = (SnovaKeyGenerationParameters)param; + this.params = snovaParams.getParameters(); + this.random = snovaParams.getRandom(); + this.initialized = true; + this.engine = new SnovaEngine(params); + } + + @Override + public AsymmetricCipherKeyPair generateKeyPair() + { + if (!initialized) + { + throw new IllegalStateException("SNOVA key pair generator not initialized"); + } + + // Generate seed pair according to SNOVA specifications + byte[] seedPair = new byte[seedLength]; + random.nextBytes(seedPair); + + byte[] pk = new byte[params.getPublicKeyLength()]; + byte[] sk = new byte[params.getPrivateKeyLength()]; + + byte[] ptPublicKeySeed = Arrays.copyOfRange(seedPair, 0, publicSeedLength); + byte[] ptPrivateKeySeed = Arrays.copyOfRange(seedPair, publicSeedLength, seedPair.length); + + SnovaKeyElements keyElements = new SnovaKeyElements(params); + System.arraycopy(ptPublicKeySeed, 0, pk, 0, ptPublicKeySeed.length); + engine.genMap1T12Map2(keyElements, ptPublicKeySeed, ptPrivateKeySeed); + + // Generate P22 matrix + engine.genP22(pk, ptPublicKeySeed.length, keyElements.T12, keyElements.map1.p21, keyElements.map2.f12); + + + // Pack public key components + System.arraycopy(ptPublicKeySeed, 0, pk, 0, ptPublicKeySeed.length); + + if (params.isSkIsSeed()) + { + sk = seedPair; + } + else + { + int o = params.getO(); + int lsq = params.getLsq(); + int v = params.getV(); + int length = o * params.getAlpha() * lsq * 4 + v * o * lsq + (o * v * v + o * v * o + o * o * v) * lsq; + + byte[] input = new byte[length]; + int inOff = 0; + inOff = SnovaKeyElements.copy3d(keyElements.map1.aAlpha, input, inOff); + inOff = SnovaKeyElements.copy3d(keyElements.map1.bAlpha, input, inOff); + inOff = SnovaKeyElements.copy3d(keyElements.map1.qAlpha1, input, inOff); + inOff = SnovaKeyElements.copy3d(keyElements.map1.qAlpha2, input, inOff); + inOff = SnovaKeyElements.copy3d(keyElements.T12, input, inOff); + inOff = SnovaKeyElements.copy4d(keyElements.map2.f11, input, inOff); + inOff = SnovaKeyElements.copy4d(keyElements.map2.f12, input, inOff); + SnovaKeyElements.copy4d(keyElements.map2.f21, input, inOff); + GF16Utils.encodeMergeInHalf(input, length, sk); + System.arraycopy(seedPair, 0, sk, sk.length - seedLength, seedLength); + } + + return new AsymmetricCipherKeyPair( + new SnovaPublicKeyParameters(params, pk), + new SnovaPrivateKeyParameters(params, sk) + ); + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaParameters.java new file mode 100644 index 0000000000..fcce21df1c --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaParameters.java @@ -0,0 +1,198 @@ +package org.bouncycastle.pqc.crypto.snova; + +public class SnovaParameters +{ + + public static final SnovaParameters SNOVA_24_5_4_SSK = + new SnovaParameters("SNOVA_24_5_4_SSK", 24, 5, 4, true, false); + public static final SnovaParameters SNOVA_24_5_4_ESK = + new SnovaParameters("SNOVA_24_5_4_ESK", 24, 5, 4, false, false); + public static final SnovaParameters SNOVA_24_5_4_SHAKE_SSK = + new SnovaParameters("SNOVA_24_5_4_SHAKE_SSK", 24, 5, 4, true, true); + public static final SnovaParameters SNOVA_24_5_4_SHAKE_ESK = + new SnovaParameters("SNOVA_24_5_4_SHAKE_ESK", 24, 5, 4, false, true); + + public static final SnovaParameters SNOVA_24_5_5_SSK = + new SnovaParameters("SNOVA_24_5_5_SSK", 24, 5, 5, true, false); + public static final SnovaParameters SNOVA_24_5_5_ESK = + new SnovaParameters("SNOVA_24_5_5_ESK", 24, 5, 5, false, false); + public static final SnovaParameters SNOVA_24_5_5_SHAKE_SSK = + new SnovaParameters("SNOVA_24_5_5_SHAKE_SSK", 24, 5, 5, true, true); + public static final SnovaParameters SNOVA_24_5_5_SHAKE_ESK = + new SnovaParameters("SNOVA_24_5_5_SHAKE_ESK", 24, 5, 5, false, true); + + public static final SnovaParameters SNOVA_25_8_3_SSK = + new SnovaParameters("SNOVA_25_8_3_SSK", 25, 8, 3, true, false); + public static final SnovaParameters SNOVA_25_8_3_ESK = + new SnovaParameters("SNOVA_25_8_3_ESK", 25, 8, 3, false, false); + public static final SnovaParameters SNOVA_25_8_3_SHAKE_SSK = + new SnovaParameters("SNOVA_25_8_3_SHAKE_SSK", 25, 8, 3, true, true); + public static final SnovaParameters SNOVA_25_8_3_SHAKE_ESK = + new SnovaParameters("SNOVA_25_8_3_SHAKE_ESK", 25, 8, 3, false, true); + + public static final SnovaParameters SNOVA_29_6_5_SSK = + new SnovaParameters("SNOVA_29_6_5_SSK", 29, 6, 5, true, false); + public static final SnovaParameters SNOVA_29_6_5_ESK = + new SnovaParameters("SNOVA_29_6_5_ESK", 29, 6, 5, false, false); + public static final SnovaParameters SNOVA_29_6_5_SHAKE_SSK = + new SnovaParameters("SNOVA_29_6_5_SHAKE_SSK", 29, 6, 5, true, true); + public static final SnovaParameters SNOVA_29_6_5_SHAKE_ESK = + new SnovaParameters("SNOVA_29_6_5_SHAKE_ESK", 29, 6, 5, false, true); + + public static final SnovaParameters SNOVA_37_8_4_SSK = + new SnovaParameters("SNOVA_37_8_4_SSK", 37, 8, 4, true, false); + public static final SnovaParameters SNOVA_37_8_4_ESK = + new SnovaParameters("SNOVA_37_8_4_ESK", 37, 8, 4, false, false); + public static final SnovaParameters SNOVA_37_8_4_SHAKE_SSK = + new SnovaParameters("SNOVA_37_8_4_SHAKE_SSK", 37, 8, 4, true, true); + public static final SnovaParameters SNOVA_37_8_4_SHAKE_ESK = + new SnovaParameters("SNOVA_37_8_4_SHAKE_ESK", 37, 8, 4, false, true); + + // SNOVA_37_17_2 variants + public static final SnovaParameters SNOVA_37_17_2_SSK = + new SnovaParameters("SNOVA_37_17_2_SSK", 37, 17, 2, true, false); + public static final SnovaParameters SNOVA_37_17_2_ESK = + new SnovaParameters("SNOVA_37_17_2_ESK", 37, 17, 2, false, false); + public static final SnovaParameters SNOVA_37_17_2_SHAKE_SSK = + new SnovaParameters("SNOVA_37_17_2_SHAKE_SSK", 37, 17, 2, true, true); + public static final SnovaParameters SNOVA_37_17_2_SHAKE_ESK = + new SnovaParameters("SNOVA_37_17_2_SHAKE_ESK", 37, 17, 2, false, true); + + // SNOVA_49_11_3 variants + public static final SnovaParameters SNOVA_49_11_3_SSK = + new SnovaParameters("SNOVA_49_11_3_SSK", 49, 11, 3, true, false); + public static final SnovaParameters SNOVA_49_11_3_ESK = + new SnovaParameters("SNOVA_49_11_3_ESK", 49, 11, 3, false, false); + public static final SnovaParameters SNOVA_49_11_3_SHAKE_SSK = + new SnovaParameters("SNOVA_49_11_3_SHAKE_SSK", 49, 11, 3, true, true); + public static final SnovaParameters SNOVA_49_11_3_SHAKE_ESK = + new SnovaParameters("SNOVA_49_11_3_SHAKE_ESK", 49, 11, 3, false, true); + + // SNOVA_56_25_2 variants + public static final SnovaParameters SNOVA_56_25_2_SSK = + new SnovaParameters("SNOVA_56_25_2_SSK", 56, 25, 2, true, false); + public static final SnovaParameters SNOVA_56_25_2_ESK = + new SnovaParameters("SNOVA_56_25_2_ESK", 56, 25, 2, false, false); + public static final SnovaParameters SNOVA_56_25_2_SHAKE_SSK = + new SnovaParameters("SNOVA_56_25_2_SHAKE_SSK", 56, 25, 2, true, true); + public static final SnovaParameters SNOVA_56_25_2_SHAKE_ESK = + new SnovaParameters("SNOVA_56_25_2_SHAKE_ESK", 56, 25, 2, false, true); + + // SNOVA_60_10_4 variants + public static final SnovaParameters SNOVA_60_10_4_SSK = + new SnovaParameters("SNOVA_60_10_4_SSK", 60, 10, 4, true, false); + public static final SnovaParameters SNOVA_60_10_4_ESK = + new SnovaParameters("SNOVA_60_10_4_ESK", 60, 10, 4, false, false); + public static final SnovaParameters SNOVA_60_10_4_SHAKE_SSK = + new SnovaParameters("SNOVA_60_10_4_SHAKE_SSK", 60, 10, 4, true, true); + public static final SnovaParameters SNOVA_60_10_4_SHAKE_ESK = + new SnovaParameters("SNOVA_60_10_4_SHAKE_ESK", 60, 10, 4, false, true); + + // SNOVA_66_15_4 variants + public static final SnovaParameters SNOVA_66_15_3_SSK = + new SnovaParameters("SNOVA_66_15_3_SSK", 66, 15, 3, true, false); + public static final SnovaParameters SNOVA_66_15_3_ESK = + new SnovaParameters("SNOVA_66_15_3_ESK", 66, 15, 3, false, false); + public static final SnovaParameters SNOVA_66_15_3_SHAKE_SSK = + new SnovaParameters("SNOVA_66_15_3_SHAKE_SSK", 66, 15, 3, true, true); + public static final SnovaParameters SNOVA_66_15_3_SHAKE_ESK = + new SnovaParameters("SNOVA_66_15_3_SHAKE_ESK", 66, 15, 3, false, true); + + // SNOVA_75_33_2 variants + public static final SnovaParameters SNOVA_75_33_2_SSK = + new SnovaParameters("SNOVA_75_33_2_SSK", 75, 33, 2, true, false); + public static final SnovaParameters SNOVA_75_33_2_ESK = + new SnovaParameters("SNOVA_75_33_2_ESK", 75, 33, 2, false, false); + public static final SnovaParameters SNOVA_75_33_2_SHAKE_SSK = + new SnovaParameters("SNOVA_75_33_2_SHAKE_SSK", 75, 33, 2, true, true); + public static final SnovaParameters SNOVA_75_33_2_SHAKE_ESK = + new SnovaParameters("SNOVA_75_33_2_SHAKE_ESK", 75, 33, 2, false, true); + + private final String name; + private final int v; + private final int o; + private final int l; + private final int lsq; + private final int alpha; + private final boolean skIsSeed; + private final boolean pkExpandShake; + + private SnovaParameters(String name, int v, int o, int l, boolean skIsSeed, boolean pkExpandShake) + { + this.name = name; + this.v = v; + this.o = o; + this.l = l; + this.lsq = l * l; + this.alpha = lsq + l; + this.skIsSeed = skIsSeed; + this.pkExpandShake = pkExpandShake; + } + + // Getter methods + public String getName() + { + return name; + } + + public int getV() + { + return v; + } + + public int getO() + { + return o; + } + + public int getL() + { + return l; + } + + public boolean isSkIsSeed() + { + return skIsSeed; + } + + public boolean isPkExpandShake() + { + return pkExpandShake; + } + + public int getM() + { + return o; + } + + public int getAlpha() + { + return alpha; + } + + public int getPublicKeyLength() + { + return SnovaKeyPairGenerator.publicSeedLength + ((o * o * o * lsq + 1) >>> 1); + } + + public int getPrivateKeyLength() + { + return ((lsq * (4 * o * alpha + o * (v * v + v * o + o * v) + v * o) + 1) >> 1) + + SnovaKeyPairGenerator.privateSeedLength + SnovaKeyPairGenerator.publicSeedLength; + } + + public int getN() + { + return v + o; + } + + public int getLsq() + { + return lsq; + } + + public int getSaltLength() + { + return 16; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaPrivateKeyParameters.java new file mode 100644 index 0000000000..a8643bcc98 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaPrivateKeyParameters.java @@ -0,0 +1,33 @@ +package org.bouncycastle.pqc.crypto.snova; + +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.util.Arrays; + +public class SnovaPrivateKeyParameters + extends AsymmetricKeyParameter +{ + private final byte[] privateKey; + private final SnovaParameters parameters; + + public SnovaPrivateKeyParameters(SnovaParameters parameters, byte[] privateKey) + { + super(true); + this.privateKey = Arrays.clone(privateKey); + this.parameters = parameters; + } + + public byte[] getPrivateKey() + { + return Arrays.clone(privateKey); + } + + public byte[] getEncoded() + { + return Arrays.clone(privateKey); + } + + public SnovaParameters getParameters() + { + return parameters; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaPublicKeyParameters.java new file mode 100644 index 0000000000..40001e0269 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaPublicKeyParameters.java @@ -0,0 +1,33 @@ +package org.bouncycastle.pqc.crypto.snova; + +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.util.Arrays; + +public class SnovaPublicKeyParameters + extends AsymmetricKeyParameter +{ + private final byte[] publicKey; + private final SnovaParameters parameters; + + public SnovaPublicKeyParameters(SnovaParameters parameters, byte[] publicKey) + { + super(false); + this.publicKey = Arrays.clone(publicKey); + this.parameters = parameters; + } + + public byte[] getPublicKey() + { + return Arrays.clone(publicKey); + } + + public byte[] getEncoded() + { + return Arrays.clone(publicKey); + } + + public SnovaParameters getParameters() + { + return parameters; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaSigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaSigner.java new file mode 100644 index 0000000000..764a289458 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/snova/SnovaSigner.java @@ -0,0 +1,512 @@ +package org.bouncycastle.pqc.crypto.snova; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.MessageSigner; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.GF16; + +public class SnovaSigner + implements MessageSigner +{ + private SnovaParameters params; + private SnovaEngine engine; + private SecureRandom random; + private final SHAKEDigest shake = new SHAKEDigest(256); + private SnovaPublicKeyParameters pubKey; + private SnovaPrivateKeyParameters privKey; + + @Override + public void init(boolean forSigning, CipherParameters param) + { + if (forSigning) + { + pubKey = null; + + if (param instanceof ParametersWithRandom) + { + ParametersWithRandom withRandom = (ParametersWithRandom)param; + privKey = (SnovaPrivateKeyParameters)withRandom.getParameters(); + random = withRandom.getRandom(); + } + else + { + privKey = (SnovaPrivateKeyParameters)param; + random = CryptoServicesRegistrar.getSecureRandom(); + } + params = privKey.getParameters(); + } + else + { + pubKey = (SnovaPublicKeyParameters)param; + params = pubKey.getParameters(); + privKey = null; + random = null; + } + engine = new SnovaEngine(params); + } + + @Override + public byte[] generateSignature(byte[] message) + { + byte[] hash = getMessageHash(message); + byte[] salt = new byte[params.getSaltLength()]; + random.nextBytes(salt); + byte[] signature = new byte[((params.getN() * params.getLsq() + 1) >>> 1) + params.getSaltLength()]; + SnovaKeyElements keyElements = new SnovaKeyElements(params); + byte[] publicKeySeed; + byte[] ptPrivateKeySeed; + if (params.isSkIsSeed()) + { + byte[] seedPair = privKey.getPrivateKey(); + publicKeySeed = Arrays.copyOfRange(seedPair, 0, SnovaKeyPairGenerator.publicSeedLength); + ptPrivateKeySeed = Arrays.copyOfRange(seedPair, SnovaKeyPairGenerator.publicSeedLength, seedPair.length); + engine.genMap1T12Map2(keyElements, publicKeySeed, ptPrivateKeySeed); + } + else + { + byte[] privateKey = privKey.getPrivateKey(); + byte[] tmp = new byte[(privateKey.length - SnovaKeyPairGenerator.publicSeedLength - SnovaKeyPairGenerator.privateSeedLength) << 1]; + GF16Utils.decodeMergeInHalf(privateKey, tmp, tmp.length); + int inOff = 0; + inOff = SnovaKeyElements.copy3d(tmp, inOff, keyElements.map1.aAlpha); + inOff = SnovaKeyElements.copy3d(tmp, inOff, keyElements.map1.bAlpha); + inOff = SnovaKeyElements.copy3d(tmp, inOff, keyElements.map1.qAlpha1); + inOff = SnovaKeyElements.copy3d(tmp, inOff, keyElements.map1.qAlpha2); + inOff = SnovaKeyElements.copy3d(tmp, inOff, keyElements.T12); + inOff = SnovaKeyElements.copy4d(tmp, inOff, keyElements.map2.f11); + inOff = SnovaKeyElements.copy4d(tmp, inOff, keyElements.map2.f12); + SnovaKeyElements.copy4d(tmp, inOff, keyElements.map2.f21); + publicKeySeed = Arrays.copyOfRange(privateKey, privateKey.length - SnovaKeyPairGenerator.publicSeedLength - SnovaKeyPairGenerator.privateSeedLength, privateKey.length - SnovaKeyPairGenerator.privateSeedLength); + ptPrivateKeySeed = Arrays.copyOfRange(privateKey, privateKey.length - SnovaKeyPairGenerator.privateSeedLength, privateKey.length); + } + signDigestCore(signature, hash, salt, keyElements.map1.aAlpha, keyElements.map1.bAlpha, keyElements.map1.qAlpha1, keyElements.map1.qAlpha2, + keyElements.T12, keyElements.map2.f11, keyElements.map2.f12, keyElements.map2.f21, publicKeySeed, ptPrivateKeySeed); + return Arrays.concatenate(signature, message); + } + + @Override + public boolean verifySignature(byte[] message, byte[] signature) + { + byte[] hash = getMessageHash(message); + MapGroup1 map1 = new MapGroup1(params); + byte[] pk = pubKey.getEncoded(); + byte[] publicKeySeed = Arrays.copyOf(pk, SnovaKeyPairGenerator.publicSeedLength); + byte[] p22_source = Arrays.copyOfRange(pk, SnovaKeyPairGenerator.publicSeedLength, pk.length); + engine.genABQP(map1, publicKeySeed); + byte[][][][] p22 = new byte[params.getM()][params.getO()][params.getO()][params.getLsq()]; + if ((params.getLsq() & 1) == 0) + { + MapGroup1.decodeP(p22_source, 0, p22, p22_source.length << 1); + } + else + { + byte[] p22_gf16s = new byte[p22_source.length << 1]; + GF16.decode(p22_source, p22_gf16s, p22_gf16s.length); + MapGroup1.fillP(p22_gf16s, 0, p22, p22_gf16s.length); + } + + return verifySignatureCore(hash, signature, publicKeySeed, map1, p22); + } + + void createSignedHash( + byte[] ptPublicKeySeed, int seedLengthPublic, + byte[] digest, int bytesDigest, + byte[] arraySalt, int saltOff, int bytesSalt, + byte[] signedHashOut, int bytesHash) + { + // 1. Absorb public key seed + shake.update(ptPublicKeySeed, 0, seedLengthPublic); + + // 2. Absorb message digest + shake.update(digest, 0, bytesDigest); + + // 3. Absorb salt + shake.update(arraySalt, saltOff, bytesSalt); + + // 4. Finalize absorption and squeeze output + shake.doFinal(signedHashOut, 0, bytesHash); + } + + void signDigestCore(byte[] ptSignature, byte[] digest, byte[] arraySalt, + byte[][][] Aalpha, byte[][][] Balpha, + byte[][][] Qalpha1, byte[][][] Qalpha2, + byte[][][] T12, byte[][][][] F11, + byte[][][][] F12, byte[][][][] F21, + byte[] ptPublicKeySeed, byte[] ptPrivateKeySeed) + { + // Initialize constants from parameters + final int m = params.getM(); + final int l = params.getL(); + final int lsq = params.getLsq(); + final int alpha = params.getAlpha(); + final int v = params.getV(); + final int o = params.getO(); + final int n = params.getN(); + final int mxlsq = m * lsq; + final int oxlsq = o * lsq; + final int vxlsq = v * lsq; + final int bytesHash = (oxlsq + 1) >>> 1; + final int bytesSalt = 16; + + // Initialize matrices and arrays + byte[][] Gauss = new byte[mxlsq][mxlsq + 1]; + byte[][] Temp = new byte[lsq][lsq]; + byte[] solution = new byte[mxlsq]; + + byte[][][] Left = new byte[alpha][v][lsq]; + byte[][][] Right = new byte[alpha][v][lsq]; + byte[] leftXTmp = new byte[lsq]; + byte[] rightXtmp = new byte[lsq]; + byte[] FvvGF16Matrix = new byte[lsq]; + byte[] hashInGF16 = new byte[mxlsq]; + byte[] vinegarGf16 = new byte[n * lsq]; + byte[] signedHash = new byte[bytesHash]; + byte[] vinegarBytes = new byte[(vxlsq + 1) >>> 1]; + + // Temporary matrices + byte[] gf16mTemp0 = new byte[l]; + + int flagRedo; + byte numSign = 0; + byte valLeft, valB, valA, valRight; + // Step 1: Create signed hash + createSignedHash(ptPublicKeySeed, ptPublicKeySeed.length, digest, digest.length, + arraySalt, 0, arraySalt.length, signedHash, bytesHash); + GF16.decode(signedHash, 0, hashInGF16, 0, hashInGF16.length); + + do + { + // Initialize Gauss matrix + for (int i = 0; i < Gauss.length; ++i) + { + Arrays.fill(Gauss[i], (byte)0); + } + numSign++; + + // Fill last column of Gauss matrix + for (int i = 0; i < mxlsq; i++) + { + Gauss[i][mxlsq] = hashInGF16[i]; + } + + // Generate vinegar values + shake.update(ptPrivateKeySeed, 0, ptPrivateKeySeed.length); + shake.update(digest, 0, digest.length); + shake.update(arraySalt, 0, arraySalt.length); + shake.update(numSign); + shake.doFinal(vinegarBytes, 0, vinegarBytes.length); + + GF16.decode(vinegarBytes, vinegarGf16, vinegarBytes.length << 1); + + for (int i = 0, ixlsq = 0; i < m; i++, ixlsq += lsq) + { + Arrays.fill(FvvGF16Matrix, (byte)0); + // Evaluate vinegar part of central map + for (int a = 0, miPrime = i; a < alpha; a++, miPrime++) + { + if (miPrime >= o) + { + miPrime -= o; + } + for (int j = 0, jxlsq = 0; j < v; j++, jxlsq += lsq) + { + GF16Utils.gf16mTranMulMul(vinegarGf16, jxlsq, Aalpha[i][a], Balpha[i][a], Qalpha1[i][a], + Qalpha2[i][a], gf16mTemp0, Left[a][j], Right[a][j], l); + } + + for (int j = 0; j < v; j++) + { + // Gaussian elimination setup + for (int k = 0; k < v; k++) + { + GF16Utils.gf16mMulMulTo(Left[a][j], F11[miPrime][j][k], Right[a][k], gf16mTemp0, FvvGF16Matrix, l); + } + } + } + + for (int j = 0, off = 0; j < l; j++) + { + for (int k = 0; k < l; k++) + { + Gauss[ixlsq + off][mxlsq] ^= FvvGF16Matrix[off++]; + } + } +// } +// // TODO: think about why this two loops can merge together? +// // Compute the coefficients of Xo and put into Gauss matrix and compute the coefficients of Xo^t and add into Gauss matrix +// for (int i = 0, ixlsq = 0; i < m; ++i, ixlsq += lsq) +// { + for (int index = 0, idxlsq = 0; index < o; ++index, idxlsq += lsq) + { + for (int a = 0, mi_prime = i; a < alpha; ++a, ++mi_prime) + { + if (mi_prime >= o) + { + mi_prime -= o; + } + // Initialize Temp to zero + for (int ti = 0; ti < lsq; ++ti) + { + Arrays.fill(Temp[ti], (byte)0); + } + // Process each j for Left part + for (int j = 0; j < v; ++j) + { + GF16Utils.gf16mMulMul(Left[a][j], F12[mi_prime][j][index], Qalpha2[i][a], gf16mTemp0, leftXTmp, l); + GF16Utils.gf16mMulMul(Qalpha1[i][a], F21[mi_prime][index][j], Right[a][j], gf16mTemp0, rightXtmp, l); + // Accumulate into Temp from leftXTmp and Balpha[mi][a] + // rlra_l is short for "rowLeft_rowA times l" + for (int ti = 0, colB_colRight = 0, rlraxl = 0; ti < lsq; ++ti, ++colB_colRight) + { + if (colB_colRight == l) + { + colB_colRight = 0; + rlraxl += l; + } + valLeft = leftXTmp[rlraxl]; + valRight = rightXtmp[colB_colRight]; + // clrrxl is short for "rowLeft_rowA times l" + // rbcaxl is short for "rowB_colA times l" + for (int tj = 0, rowB_colA = 0, colLeft_rowRight = 0, clrrxl = 0, rbcaxl = 0; tj < lsq; + ++tj, ++rowB_colA, rbcaxl += l) + { + if (rowB_colA == l) + { + rowB_colA = 0; + rbcaxl = 0; + colLeft_rowRight++; + clrrxl += l; + valLeft = leftXTmp[rlraxl + colLeft_rowRight]; + valRight = rightXtmp[clrrxl + colB_colRight]; + } + valB = Balpha[i][a][rbcaxl + colB_colRight]; + valA = Aalpha[i][a][rlraxl + rowB_colA]; + Temp[ti][tj] ^= GF16.mul(valLeft, valB) ^ GF16.mul(valA, valRight); + } + } + } + // Add Temp to Gauss matrix + for (int ti = 0; ti < lsq; ++ti) + { + for (int tj = 0; tj < lsq; ++tj) + { + Gauss[ixlsq + ti][idxlsq + tj] ^= Temp[ti][tj]; + } + } + } + } + } + // Gaussian elimination implementation + flagRedo = performGaussianElimination(Gauss, solution, mxlsq); + } + while (flagRedo != 0); + + // Copy vinegar variables + for (int idx = 0, idxlsq = 0; idx < v; idx++, idxlsq += lsq) + { + for (int i = 0, ixlsq = 0; i < o; i++, ixlsq += lsq) + { + GF16Utils.gf16mMulTo(T12[idx][i], solution, ixlsq, vinegarGf16, idxlsq, l); + } + } + + // Copy remaining oil variables + System.arraycopy(solution, 0, vinegarGf16, vxlsq, oxlsq); + GF16.encode(vinegarGf16, ptSignature, vinegarGf16.length); + + System.arraycopy(arraySalt, 0, ptSignature, ptSignature.length - bytesSalt, bytesSalt); + } + + boolean verifySignatureCore(byte[] digest, byte[] signature, byte[] publicKeySeed, MapGroup1 map1, byte[][][][] p22) + { + final int lsq = params.getLsq(); + final int o = params.getO(); + final int oxlsq = o * lsq; + final int bytesHash = (oxlsq + 1) >>> 1; + final int bytesSalt = params.getSaltLength(); + final int m = params.getM(); + final int n = params.getN(); + final int nxlsq = n * lsq; + + int bytesSignature = ((nxlsq) + 1) >>> 1; + + // Step 1: Regenerate signed hash using public key seed, digest and salt + byte[] signedHash = new byte[bytesHash]; + createSignedHash(publicKeySeed, publicKeySeed.length, digest, digest.length, + signature, bytesSignature, bytesSalt, signedHash, bytesHash); + + // Handle odd-length adjustment (if needed) + if (((oxlsq) & 1) != 0) + { + signedHash[bytesHash - 1] &= 0x0F; + } + + // Step 2: Convert signature to GF16 matrices + byte[] decodedSig = new byte[nxlsq]; + GF16.decode(signature, 0, decodedSig, 0, decodedSig.length); + + // Step 3: Evaluate signature using public key + byte[] computedHashBytes = new byte[m * lsq]; + evaluation(computedHashBytes, map1, p22, decodedSig);//signatureGF16Matrix); + + // Convert computed hash matrix to bytes + byte[] encodedHash = new byte[bytesHash]; + GF16.encode(computedHashBytes, encodedHash, computedHashBytes.length); + + // Step 4: Compare hashes + return Arrays.areEqual(signedHash, encodedHash); + } + + private void evaluation(byte[] hashMatrix, MapGroup1 map1, byte[][][][] p22, byte[] signature) + { + final int m = params.getM(); + final int alpha = params.getAlpha(); + final int n = params.getN(); + final int l = params.getL(); + final int lsq = params.getLsq(); + final int o = params.getO(); + + byte[][][] Left = new byte[alpha][n][lsq]; + byte[][][] Right = new byte[alpha][n][lsq]; + byte[] temp = new byte[lsq]; + + // Evaluate Left and Right matrices + for (int mi = 0, mixlsq = 0; mi < m; mi++, mixlsq += lsq) + { + for (int si = 0, sixlsq = 0; si < n; si++, sixlsq += lsq) + { + for (int a = 0; a < alpha; a++) + { + // Left[mi][a][si] = Aalpha * (sig^T * Qalpha1) + // Right[mi][a][si] = (Qalpha2 * sig) * Balpha + GF16Utils.gf16mTranMulMul(signature, sixlsq, map1.aAlpha[mi][a], map1.bAlpha[mi][a], map1.qAlpha1[mi][a], + map1.qAlpha2[mi][a], temp, Left[a][si], Right[a][si], l); + } + } + + // Process P matrices and accumulate results + for (int a = 0, miPrime = mi; a < alpha; a++, miPrime++) + { + if (miPrime >= o) + { + miPrime -= o; + } + for (int ni = 0; ni < n; ni++) + { + // sum_t0 = sum(P[miPrime][ni][nj] * Right[mi][a][nj]) + byte[] p = getPMatrix(map1, p22, miPrime, ni, 0); + GF16Utils.gf16mMul(p, Right[a][0], temp, l); + for (int nj = 1; nj < n; nj++) + { + p = getPMatrix(map1, p22, miPrime, ni, nj); + GF16Utils.gf16mMulTo(p, Right[a][nj], temp, l); + } + + // hashMatrix += Left[mi][a][ni] * temp + GF16Utils.gf16mMulTo(Left[a][ni], temp, hashMatrix, mixlsq, l); + } + } + } + } + + private byte[] getPMatrix(MapGroup1 map1, byte[][][][] p22, int mi, int ni, int nj) + { + final int v = params.getV(); + if (ni < v) + { + if (nj < v) + { + return map1.p11[mi][ni][nj]; + } + else + { + return map1.p12[mi][ni][nj - v]; + } + } + else + { + if (nj < v) + { + return map1.p21[mi][ni - v][nj]; + } + else + { + return p22[mi][ni - v][nj - v]; + } + } + } + + private int performGaussianElimination(byte[][] Gauss, byte[] solution, int size) + { + final int cols = size + 1; + + for (int i = 0; i < size; i++) + { + // Find pivot + int pivot = i; + while (pivot < size && Gauss[pivot][i] == 0) + { + pivot++; + } + + // Check for singularity + if (pivot >= size) + { + return 1; // Flag for redo + } + + // Swap rows if needed + if (pivot != i) + { + byte[] tempRow = Gauss[i]; + Gauss[i] = Gauss[pivot]; + Gauss[pivot] = tempRow; + } + + // Normalize pivot row + byte invPivot = GF16.inv(Gauss[i][i]); + for (int j = i; j < cols; j++) + { + Gauss[i][j] = GF16.mul(Gauss[i][j], invPivot); + } + + // Eliminate below + for (int j = i + 1; j < size; j++) + { + byte factor = Gauss[j][i]; + if (factor != 0) + { + for (int k = i; k < cols; k++) + { + Gauss[j][k] ^= GF16.mul(Gauss[i][k], factor); + } + } + } + } + + // Back substitution + for (int i = size - 1; i >= 0; i--) + { + byte tmp = Gauss[i][size]; + for (int j = i + 1; j < size; j++) + { + tmp ^= GF16.mul(Gauss[i][j], solution[j]); + } + solution[i] = tmp; + } + return 0; + } + + private byte[] getMessageHash(byte[] message) + { + byte[] hash = new byte[shake.getDigestSize()]; + shake.update(message, 0, message.length); + shake.doFinal(hash, 0); + return hash; + } +} diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/SPHINCS256Signer.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/SPHINCS256Signer.java index 7f61a1fe6d..0c8a3205b7 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/SPHINCS256Signer.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/SPHINCS256Signer.java @@ -406,13 +406,12 @@ boolean verify(HashFunctions hs, byte[] m, byte[] sm, byte[] pk) smlen -= SPHINCS256Config.SUBTREE_HEIGHT * SPHINCS256Config.HASH_BYTES; } + // Because we use custom offsets on tpk, rather than incurring an + // expensive copy, we use a manual constant time comparison. boolean verified = true; for (i = 0; i < SPHINCS256Config.HASH_BYTES; i++) { - if (root[i] != tpk[i + Horst.N_MASKS * SPHINCS256Config.HASH_BYTES]) - { - verified = false; - } + verified &= root[i] == tpk[i + Horst.N_MASKS * SPHINCS256Config.HASH_BYTES]; } return verified; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/package-info.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/package-info.java new file mode 100644 index 0000000000..ac3805cb08 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincs/package-info.java @@ -0,0 +1,4 @@ +/** + * Low level implementation of the SPHINCS-256 signature algorithm. + */ +package org.bouncycastle.pqc.crypto.sphincs; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/ADRS.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/ADRS.java index 9f0fe1be67..e564339267 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/ADRS.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/ADRS.java @@ -5,14 +5,14 @@ class ADRS { - public static final int WOTS_HASH = 0; - public static final int WOTS_PK = 1; - public static final int TREE = 2; - public static final int FORS_TREE = 3; - public static final int FORS_PK = 4; - public static final int WOTS_PRF = 5; - public static final int FORS_PRF = 6; - + static final int WOTS_HASH = 0; + static final int WOTS_PK = 1; + static final int TREE = 2; + static final int FORS_TREE = 3; + static final int FORS_PK = 4; + static final int WOTS_PRF = 5; + static final int FORS_PRF = 6; + static final int OFFSET_LAYER = 0; static final int OFFSET_TREE = 4; static final int OFFSET_TREE_HGT = 24; @@ -21,7 +21,7 @@ class ADRS static final int OFFSET_KP_ADDR = 20; static final int OFFSET_CHAIN_ADDR = 24; static final int OFFSET_HASH_ADDR = 28; - + final byte[] value = new byte[32]; ADRS() @@ -59,11 +59,6 @@ public void setTreeHeight(int height) Pack.intToBigEndian(height, value, OFFSET_TREE_HGT); } - public int getTreeHeight() - { - return Pack.bigEndianToInt(value, OFFSET_TREE_HGT); - } - public void setTreeIndex(int index) { Pack.intToBigEndian(index, value, OFFSET_TREE_INDEX); @@ -75,7 +70,7 @@ public int getTreeIndex() } // resets part of value to zero in line with 2.7.3 - public void setType(int type) + public void setTypeAndClear(int type) { Pack.intToBigEndian(type, value, OFFSET_TYPE); @@ -87,11 +82,6 @@ public void changeType(int type) Pack.intToBigEndian(type, value, OFFSET_TYPE); } - public int getType() - { - return Pack.bigEndianToInt(value, OFFSET_TYPE); - } - public void setKeyPairAddress(int keyPairAddr) { Pack.intToBigEndian(keyPairAddr, value, OFFSET_KP_ADDR); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/Fors.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/Fors.java index 4eba0bcef6..855bc38605 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/Fors.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/Fors.java @@ -17,18 +17,17 @@ public Fors(SPHINCSPlusEngine engine) // Output: n-byte root node - top node on Stack byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) { - LinkedList stack = new LinkedList(); - - if (s % (1 << z) != 0) + if ((s >>> z) << z != s) { return null; } + LinkedList stack = new LinkedList(); ADRS adrs = new ADRS(adrsParam); for (int idx = 0; idx < (1 << z); idx++) { - adrs.setType(ADRS.FORS_PRF); + adrs.setTypeAndClear(ADRS.FORS_PRF); adrs.setKeyPairAddress(adrsParam.getKeyPairAddress()); adrs.setTreeHeight(0); adrs.setTreeIndex(s + idx); @@ -41,19 +40,23 @@ byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) adrs.setTreeHeight(1); + int adrsTreeHeight = 1; + int adrsTreeIndex = s + idx; + // while ( Top node on Stack has same height as node ) - while (!stack.isEmpty() - && ((NodeEntry)stack.get(0)).nodeHeight == adrs.getTreeHeight()) + while (!stack.isEmpty() && ((NodeEntry)stack.get(0)).nodeHeight == adrsTreeHeight) { - adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2); - NodeEntry current = ((NodeEntry)stack.remove(0)); + adrsTreeIndex = (adrsTreeIndex - 1) / 2; + adrs.setTreeIndex(adrsTreeIndex); + NodeEntry current = ((NodeEntry)stack.remove(0)); node = engine.H(pkSeed, adrs, current.nodeValue, node); - //topmost node is now one layer higher - adrs.setTreeHeight(adrs.getTreeHeight() + 1); + + // topmost node is now one layer higher + adrs.setTreeHeight(++adrsTreeHeight); } - stack.add(0, new NodeEntry(node, adrs.getTreeHeight())); + stack.add(0, new NodeEntry(node, adrsTreeHeight)); } return ((NodeEntry)stack.get(0)).nodeValue; @@ -72,7 +75,7 @@ public SIG_FORS[] sign(byte[] md, byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) // get next index int idx = idxs[i]; // pick private key element - adrs.setType(ADRS.FORS_PRF); + adrs.setTypeAndClear(ADRS.FORS_PRF); adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); adrs.setTreeHeight(0); adrs.setTreeIndex(i * t + idx); @@ -132,7 +135,7 @@ public byte[] pkFromSig(SIG_FORS[] sig_fors, byte[] message, byte[] pkSeed, ADRS root[i] = node[0]; } ADRS forspkADRS = new ADRS(adrs); // copy address to create FTS public key address - forspkADRS.setType(ADRS.FORS_PK); + forspkADRS.setTypeAndClear(ADRS.FORS_PK); forspkADRS.setKeyPairAddress(adrs.getKeyPairAddress()); return engine.T_l(pkSeed, forspkADRS, Arrays.concatenate(root)); } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/HT.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/HT.java index 3a3236076e..c84f39d546 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/HT.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/HT.java @@ -87,7 +87,7 @@ byte[] xmss_pkFromSig(int idx, SIG_XMSS sig_xmss, byte[] M, byte[] pkSeed, ADRS ADRS adrs = new ADRS(paramAdrs); // compute WOTS+ pk from WOTS+ sig - adrs.setType(ADRS.WOTS_HASH); + adrs.setTypeAndClear(ADRS.WOTS_HASH); adrs.setKeyPairAddress(idx); byte[] sig = sig_xmss.getWOTSSig(); byte[][] AUTH = sig_xmss.getXMSSAUTH(); @@ -96,7 +96,7 @@ byte[] xmss_pkFromSig(int idx, SIG_XMSS sig_xmss, byte[] M, byte[] pkSeed, ADRS byte[] node1 = null; // compute root from WOTS+ pk and AUTH - adrs.setType(ADRS.TREE); + adrs.setTypeAndClear(ADRS.TREE); adrs.setTreeIndex(idx); for (int k = 0; k < engine.H_PRIME; k++) { @@ -125,18 +125,18 @@ SIG_XMSS xmss_sign(byte[] M, byte[] skSeed, int idx, byte[] pkSeed, ADRS paramAd ADRS adrs = new ADRS(paramAdrs); - adrs.setType(ADRS.TREE); + adrs.setTypeAndClear(ADRS.TREE); adrs.setLayerAddress(paramAdrs.getLayerAddress()); adrs.setTreeAddress(paramAdrs.getTreeAddress()); // build authentication path for (int j = 0; j < engine.H_PRIME; j++) { - int k = (idx / (1 << j)) ^ 1; - AUTH[j] = treehash(skSeed, k * (1 << j), j, pkSeed, adrs); + int k = (idx >>> j) ^ 1; + AUTH[j] = treehash(skSeed, k << j, j, pkSeed, adrs); } adrs = new ADRS(paramAdrs); - adrs.setType(ADRS.WOTS_PK); + adrs.setTypeAndClear(ADRS.WOTS_HASH); adrs.setKeyPairAddress(idx); byte[] sig = wots.sign(M, skSeed, pkSeed, adrs); @@ -144,46 +144,47 @@ SIG_XMSS xmss_sign(byte[] M, byte[] skSeed, int idx, byte[] pkSeed, ADRS paramAd return new SIG_XMSS(sig, AUTH); } - // - // Input: Secret seed SK.seed, start index s, target node height z, public seed - //PK.seed, address ADRS + // Input: Secret seed SK.seed, start index s, target node height z, public seed PK.seed, address ADRS // Output: n-byte root node - top node on Stack byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) { - ADRS adrs = new ADRS(adrsParam); - - LinkedList stack = new LinkedList(); - - if (s % (1 << z) != 0) + if ((s >>> z) << z != s) { return null; } + LinkedList stack = new LinkedList(); + ADRS adrs = new ADRS(adrsParam); + for (int idx = 0; idx < (1 << z); idx++) { - adrs.setType(ADRS.WOTS_HASH); + adrs.setTypeAndClear(ADRS.WOTS_HASH); adrs.setKeyPairAddress(s + idx); byte[] node = wots.pkGen(skSeed, pkSeed, adrs); - adrs.setType(ADRS.TREE); + adrs.setTypeAndClear(ADRS.TREE); adrs.setTreeHeight(1); adrs.setTreeIndex(s + idx); + int adrsTreeHeight = 1; + int adrsTreeIndex = s + idx; + // while ( Top node on Stack has same height as node ) - while (!stack.isEmpty() - && ((NodeEntry)stack.get(0)).nodeHeight == adrs.getTreeHeight()) + while (!stack.isEmpty() && ((NodeEntry)stack.get(0)).nodeHeight == adrsTreeHeight) { - adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2); - NodeEntry current = ((NodeEntry)stack.remove(0)); + adrsTreeIndex = (adrsTreeIndex - 1) / 2; + adrs.setTreeIndex(adrsTreeIndex); + NodeEntry current = ((NodeEntry)stack.remove(0)); node = engine.H(pkSeed, adrs, current.nodeValue, node); - //topmost node is now one layer higher - adrs.setTreeHeight(adrs.getTreeHeight() + 1); + + // topmost node is now one layer higher + adrs.setTreeHeight(++adrsTreeHeight); } - stack.add(0, new NodeEntry(node, adrs.getTreeHeight())); + stack.add(0, new NodeEntry(node, adrsTreeHeight)); } - + return ((NodeEntry)stack.get(0)).nodeValue; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/SPHINCSPlusSigner.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/SPHINCSPlusSigner.java index 47a943dd98..f8e3d53ee5 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/SPHINCSPlusSigner.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/SPHINCSPlusSigner.java @@ -83,20 +83,20 @@ public byte[] generateSignature(byte[] message) int idx_leaf = idxDigest.idx_leaf; // FORS sign ADRS adrs = new ADRS(); - adrs.setType(ADRS.FORS_TREE); + adrs.setTypeAndClear(ADRS.FORS_TREE); adrs.setTreeAddress(idx_tree); adrs.setKeyPairAddress(idx_leaf); SIG_FORS[] sig_fors = fors.sign(mHash, privKey.sk.seed, privKey.pk.seed, adrs); // get FORS public key - spec shows M? adrs = new ADRS(); - adrs.setType(ADRS.FORS_TREE); + adrs.setTypeAndClear(ADRS.FORS_TREE); adrs.setTreeAddress(idx_tree); adrs.setKeyPairAddress(idx_leaf); byte[] PK_FORS = fors.pkFromSig(sig_fors, mHash, privKey.pk.seed, adrs); // sign FORS public key with HT ADRS treeAdrs = new ADRS(); - treeAdrs.setType(ADRS.TREE); + treeAdrs.setTypeAndClear(ADRS.TREE); HT ht = new HT(engine, privKey.getSeed(), privKey.getPublicSeed()); byte[] SIG_HT = ht.sign(PK_FORS, idx_tree, idx_leaf); @@ -137,13 +137,13 @@ public boolean verifySignature(byte[] message, byte[] signature) int idx_leaf = idxDigest.idx_leaf; // compute FORS public key - adrs.setType(ADRS.FORS_TREE); + adrs.setTypeAndClear(ADRS.FORS_TREE); adrs.setLayerAddress(0); adrs.setTreeAddress(idx_tree); adrs.setKeyPairAddress(idx_leaf); byte[] PK_FORS = new Fors(engine).pkFromSig(sig_fors, mHash, pubKey.getSeed(), adrs); // verify HT signature - adrs.setType(ADRS.TREE); + adrs.setTypeAndClear(ADRS.TREE); adrs.setLayerAddress(0); adrs.setTreeAddress(idx_tree); adrs.setKeyPairAddress(idx_leaf); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/WotsPlus.java b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/WotsPlus.java index b0df11112e..e8ee7e44a3 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/WotsPlus.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/sphincsplus/WotsPlus.java @@ -22,21 +22,21 @@ byte[] pkGen(byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) for (int i = 0; i < engine.WOTS_LEN; i++) { ADRS adrs = new ADRS(paramAdrs); - adrs.setType(ADRS.WOTS_PRF); + adrs.setTypeAndClear(ADRS.WOTS_PRF); adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); adrs.setChainAddress(i); adrs.setHashAddress(0); byte[] sk = engine.PRF(pkSeed, skSeed, adrs); - adrs.setType(ADRS.WOTS_HASH); + adrs.setTypeAndClear(ADRS.WOTS_HASH); adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); adrs.setChainAddress(i); adrs.setHashAddress(0); tmp[i] = chain(sk, 0, w - 1, pkSeed, adrs); } - wotspkADRS.setType(ADRS.WOTS_PK); + wotspkADRS.setTypeAndClear(ADRS.WOTS_PK); wotspkADRS.setKeyPairAddress(paramAdrs.getKeyPairAddress()); return engine.T_l(pkSeed, wotspkADRS, Arrays.concatenate(tmp)); @@ -93,12 +93,12 @@ public byte[] sign(byte[] M, byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) byte[][] sig = new byte[engine.WOTS_LEN][]; for (int i = 0; i < engine.WOTS_LEN; i++) { - adrs.setType(ADRS.WOTS_PRF); + adrs.setTypeAndClear(ADRS.WOTS_PRF); adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); adrs.setChainAddress(i); adrs.setHashAddress(0); byte[] sk = engine.PRF(pkSeed, skSeed, adrs); - adrs.setType(ADRS.WOTS_HASH); + adrs.setTypeAndClear(ADRS.WOTS_HASH); adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); adrs.setChainAddress(i); adrs.setHashAddress(0); @@ -158,7 +158,7 @@ public byte[] pkFromSig(byte[] sig, byte[] M, byte[] pkSeed, ADRS adrs) tmp[i] = chain(sigI, msg[i], w - 1 - msg[i], pkSeed, adrs); } - wotspkADRS.setType(ADRS.WOTS_PK); + wotspkADRS.setTypeAndClear(ADRS.WOTS_PK); wotspkADRS.setKeyPairAddress(adrs.getKeyPairAddress()); return engine.T_l(pkSeed, wotspkADRS, Arrays.concatenate(tmp)); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PQCOtherInfoGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PQCOtherInfoGenerator.java index 39a4f1ec9e..cb7d03ccd7 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PQCOtherInfoGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PQCOtherInfoGenerator.java @@ -4,27 +4,19 @@ import java.security.SecureRandom; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.EncapsulatedSecretExtractor; import org.bouncycastle.crypto.EncapsulatedSecretGenerator; -import org.bouncycastle.crypto.KeyGenerationParameters; import org.bouncycastle.crypto.SecretWithEncapsulation; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.util.DEROtherInfo; -import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; -import org.bouncycastle.pqc.crypto.ExchangePair; import org.bouncycastle.pqc.crypto.KEMParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyPairGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.newhope.NHAgreement; -import org.bouncycastle.pqc.crypto.newhope.NHExchangePairGenerator; -import org.bouncycastle.pqc.crypto.newhope.NHKeyPairGenerator; -import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUKEMExtractor; import org.bouncycastle.pqc.crypto.ntru.NTRUKEMGenerator; import org.bouncycastle.pqc.crypto.ntru.NTRUKeyGenerationParameters; @@ -79,15 +71,15 @@ public PartyU(KEMParameters kemParams, AlgorithmIdentifier algorithmID, byte[] p { super(algorithmID, partyUInfo, partyVInfo, random); - if (kemParams instanceof KyberParameters) + if (kemParams instanceof MLKEMParameters) { - KyberKeyPairGenerator kPg = new KyberKeyPairGenerator(); + MLKEMKeyPairGenerator kPg = new MLKEMKeyPairGenerator(); - kPg.init(new KyberKeyGenerationParameters(random, (KyberParameters)kemParams)); + kPg.init(new MLKEMKeyGenerationParameters(random, (MLKEMParameters)kemParams)); aKp = kPg.generateKeyPair(); - encSE = new KyberKEMExtractor((KyberPrivateKeyParameters)aKp.getPrivate()); + encSE = new MLKEMExtractor((MLKEMPrivateKeyParameters)aKp.getPrivate()); } else if (kemParams instanceof NTRUParameters) { @@ -152,9 +144,9 @@ public PartyV(KEMParameters kemParams, AlgorithmIdentifier algorithmID, byte[] p { super(algorithmID, partyUInfo, partyVInfo, random); - if (kemParams instanceof KyberParameters) + if (kemParams instanceof MLKEMParameters) { - encSG = new KyberKEMGenerator(random); + encSG = new MLKEMGenerator(random); } else if (kemParams instanceof NTRUParameters) { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java index 5442f6c2ce..b6cdef63c4 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java @@ -13,6 +13,7 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -35,8 +36,6 @@ import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; @@ -44,7 +43,14 @@ import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPrivateKeyParameters; import org.bouncycastle.pqc.crypto.lms.HSSPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.lms.LMSPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPrivateKeyParameters; @@ -58,6 +64,10 @@ import org.bouncycastle.pqc.crypto.rainbow.RainbowPrivateKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; import org.bouncycastle.pqc.crypto.saber.SABERPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPrivateKeyParameters; @@ -148,29 +158,17 @@ else if (algOID.equals(PQCObjectIdentifiers.newHope)) } else if (algOID.equals(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig)) { - byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(); + ASN1OctetString lmsKey = parseOctetString(keyInfo.getPrivateKey(), 64); + byte[] keyEnc = lmsKey.getOctets(); ASN1BitString pubKey = keyInfo.getPublicKeyData(); - if (Pack.bigEndianToInt(keyEnc, 0) == 1) - { - if (pubKey != null) - { - byte[] pubEnc = pubKey.getOctets(); - - return LMSPrivateKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length), Arrays.copyOfRange(pubEnc, 4, pubEnc.length)); - } - return LMSPrivateKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); - } - else + if (pubKey != null) { - if (pubKey != null) - { - byte[] pubEnc = pubKey.getOctets(); + byte[] pubEnc = pubKey.getOctets(); - return HSSPrivateKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length), pubEnc); - } - return HSSPrivateKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); + return HSSPrivateKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length), pubEnc); } + return HSSPrivateKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); } else if (algOID.on(BCObjectIdentifiers.sphincsPlus) || algOID.on(BCObjectIdentifiers.sphincsPlus_interop)) { @@ -189,6 +187,13 @@ else if (algOID.on(BCObjectIdentifiers.sphincsPlus) || algOID.on(BCObjectIdentif return new SPHINCSPlusPrivateKeyParameters(spParams, ASN1OctetString.getInstance(obj).getOctets()); } } + else if (Utils.slhdsaParams.containsKey(algOID)) + { + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(algOID); + ASN1OctetString slhdsaKey = parseOctetString(keyInfo.getPrivateKey(), spParams.getN() * 4); + + return new SLHDSAPrivateKeyParameters(spParams, slhdsaKey.getOctets()); + } else if (algOID.on(BCObjectIdentifiers.picnic)) { byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(); @@ -224,12 +229,41 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_ntru)) return new NTRUPrivateKeyParameters(spParams, keyEnc); } - else if (algOID.on(BCObjectIdentifiers.pqc_kem_kyber)) + else if (algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_512) || + algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_768) || + algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_1024)) { - ASN1OctetString kyberKey = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()); - KyberParameters kyberParams = Utils.kyberParamsLookup(algOID); + ASN1Primitive mlkemKey = parsePrimitiveString(keyInfo.getPrivateKey(), 64); + MLKEMParameters mlkemParams = Utils.mlkemParamsLookup(algOID); + + MLKEMPublicKeyParameters pubParams = null; + if (keyInfo.getPublicKeyData() != null) + { + pubParams = PublicKeyFactory.MLKEMConverter.getPublicKeyParams(mlkemParams, keyInfo.getPublicKeyData()); + } + + if (mlkemKey instanceof ASN1OctetString) + { + // TODO This should be explicitly EXPANDED_KEY or SEED (tag already removed) but is length-flexible + return new MLKEMPrivateKeyParameters(mlkemParams, ((ASN1OctetString)mlkemKey).getOctets(), pubParams); + } + else if (mlkemKey instanceof ASN1Sequence) + { + ASN1Sequence keySeq = (ASN1Sequence)mlkemKey; + byte[] seed = ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(); + byte[] encoding = ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets(); - return new KyberPrivateKeyParameters(kyberParams, kyberKey.getOctets()); + // TODO This should only allow seed but is length-flexible + MLKEMPrivateKeyParameters mlkemPriv = new MLKEMPrivateKeyParameters(mlkemParams, seed, pubParams); + if (!Arrays.constantTimeAreEqual(mlkemPriv.getEncoded(), encoding)) + { + throw new IllegalArgumentException("inconsistent " + mlkemParams.getName() + " private key"); + } + + return mlkemPriv; + } + + throw new IllegalArgumentException("invalid " + mlkemParams.getName() + " private key"); } else if (algOID.on(BCObjectIdentifiers.pqc_kem_ntrulprime)) { @@ -256,11 +290,45 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_sntruprime)) ASN1OctetString.getInstance(keyEnc.getObjectAt(3)).getOctets(), ASN1OctetString.getInstance(keyEnc.getObjectAt(4)).getOctets()); } + else if (Utils.mldsaParams.containsKey(algOID)) + { + ASN1Encodable mldsaKey = parsePrimitiveString(keyInfo.getPrivateKey(), 32); + MLDSAParameters mldsaParams = Utils.mldsaParamsLookup(algOID); + + MLDSAPublicKeyParameters pubParams = null; + if (keyInfo.getPublicKeyData() != null) + { + pubParams = PublicKeyFactory.MLDSAConverter.getPublicKeyParams(mldsaParams, keyInfo.getPublicKeyData()); + } + + if (mldsaKey instanceof ASN1OctetString) + { + // TODO This should be explicitly EXPANDED_KEY or SEED (tag already removed) but is length-flexible + return new MLDSAPrivateKeyParameters(mldsaParams, ((ASN1OctetString)mldsaKey).getOctets(), pubParams); + } + else if (mldsaKey instanceof ASN1Sequence) + { + ASN1Sequence keySeq = (ASN1Sequence)mldsaKey; + byte[] seed = ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(); + byte[] encoding = ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets(); + + // TODO This should only allow seed but is length-flexible + MLDSAPrivateKeyParameters mldsaPriv = new MLDSAPrivateKeyParameters(mldsaParams, seed, pubParams); + if (!Arrays.constantTimeAreEqual(mldsaPriv.getEncoded(), encoding)) + { + throw new IllegalArgumentException("inconsistent " + mldsaParams.getName() + " private key"); + } + + return mldsaPriv; + } + + throw new IllegalArgumentException("invalid " + mldsaParams.getName() + " private key"); + } else if (algOID.equals(BCObjectIdentifiers.dilithium2) || algOID.equals(BCObjectIdentifiers.dilithium3) || algOID.equals(BCObjectIdentifiers.dilithium5)) { ASN1Encodable keyObj = keyInfo.parsePrivateKey(); - DilithiumParameters spParams = Utils.dilithiumParamsLookup(algOID); + DilithiumParameters dilParams = Utils.dilithiumParamsLookup(algOID); if (keyObj instanceof ASN1Sequence) { @@ -274,9 +342,9 @@ else if (algOID.equals(BCObjectIdentifiers.dilithium2) if (keyInfo.getPublicKeyData() != null) { - DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); + DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(dilParams, keyInfo.getPublicKeyData()); - return new DilithiumPrivateKeyParameters(spParams, + return new DilithiumPrivateKeyParameters(dilParams, ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), @@ -287,7 +355,7 @@ else if (algOID.equals(BCObjectIdentifiers.dilithium2) } else { - return new DilithiumPrivateKeyParameters(spParams, + return new DilithiumPrivateKeyParameters(dilParams, ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), @@ -302,10 +370,10 @@ else if (keyObj instanceof DEROctetString) byte[] data = ASN1OctetString.getInstance(keyObj).getOctets(); if (keyInfo.getPublicKeyData() != null) { - DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); - return new DilithiumPrivateKeyParameters(spParams, data, pubParams); + DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(dilParams, keyInfo.getPublicKeyData()); + return new DilithiumPrivateKeyParameters(dilParams, data, pubParams); } - return new DilithiumPrivateKeyParameters(spParams, data, null); + return new DilithiumPrivateKeyParameters(dilParams, data, null); } else { @@ -419,12 +487,84 @@ else if (algOID.equals(PQCObjectIdentifiers.mcElieceCca2)) return new McElieceCCA2PrivateKeyParameters(mKey.getN(), mKey.getK(), mKey.getField(), mKey.getGoppaPoly(), mKey.getP(), Utils.getDigestName(mKey.getDigest().getAlgorithm())); } + else if (algOID.on(BCObjectIdentifiers.mayo)) + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(); + MayoParameters mayoParams = Utils.mayoParamsLookup(algOID); + return new MayoPrivateKeyParameters(mayoParams, keyEnc); + } + else if (algOID.on(BCObjectIdentifiers.snova)) + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(); + SnovaParameters snovaParams = Utils.snovaParamsLookup(algOID); + return new SnovaPrivateKeyParameters(snovaParams, keyEnc); + } else { throw new RuntimeException("algorithm identifier in private key not recognised"); } } + /** + * So it seems for the new PQC algorithms, there's a couple of approaches to what goes in the OCTET STRING + */ + private static ASN1OctetString parseOctetString(ASN1OctetString octStr, int expectedLength) + throws IOException + { + byte[] data = octStr.getOctets(); + // + // it's the right length for a RAW encoding, just return it. + // + if (data.length == expectedLength) + { + return octStr; + } + + // + // possible internal OCTET STRING, possibly long form with or without the internal OCTET STRING + ASN1OctetString obj = Utils.parseOctetData(data); + + if (obj != null) + { + return ASN1OctetString.getInstance(obj); + } + + return octStr; + } + + /** + * So it seems for the new PQC algorithms, there's a couple of approaches to what goes in the OCTET STRING + * and in this case there may also be SEQUENCE. + */ + private static ASN1Primitive parsePrimitiveString(ASN1OctetString octStr, int expectedLength) + throws IOException + { + byte[] data = octStr.getOctets(); + // + // it's the right length for a RAW encoding, just return it. + // + if (data.length == expectedLength) + { + return octStr; + } + + // + // possible internal OCTET STRING, possibly long form with or without the internal OCTET STRING + // or possible SEQUENCE + ASN1Encodable obj = Utils.parseData(data); + + if (obj instanceof ASN1OctetString) + { + return ASN1OctetString.getInstance(obj); + } + if (obj instanceof ASN1Sequence) + { + return ASN1Sequence.getInstance(obj); + } + + return octStr; + } + private static short[] convert(byte[] octets) { short[] rv = new short[octets.length / 2]; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java index 1c97591500..b5d8f692dd 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java @@ -3,9 +3,11 @@ import java.io.IOException; import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -25,13 +27,15 @@ import org.bouncycastle.pqc.crypto.cmce.CMCEPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPrivateKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPrivateKeyParameters; import org.bouncycastle.pqc.crypto.lms.Composer; import org.bouncycastle.pqc.crypto.lms.HSSPrivateKeyParameters; import org.bouncycastle.pqc.crypto.lms.LMSPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntruprime.NTRULPRimePrivateKeyParameters; @@ -39,6 +43,8 @@ import org.bouncycastle.pqc.crypto.picnic.PicnicPrivateKeyParameters; import org.bouncycastle.pqc.crypto.rainbow.RainbowPrivateKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPrivateKeyParameters; import org.bouncycastle.pqc.crypto.xmss.BDS; @@ -136,11 +142,19 @@ else if (privateKey instanceof HSSPrivateKeyParameters) else if (privateKey instanceof SPHINCSPlusPrivateKeyParameters) { SPHINCSPlusPrivateKeyParameters params = (SPHINCSPlusPrivateKeyParameters)privateKey; - + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.sphincsPlusOidLookup(params.getParameters())); return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes, params.getPublicKey()); } + else if (privateKey instanceof SLHDSAPrivateKeyParameters) + { + SLHDSAPrivateKeyParameters params = (SLHDSAPrivateKeyParameters)privateKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.slhdsaOidLookup(params.getParameters())); + + return new PrivateKeyInfo(algorithmIdentifier, params.getEncoded(), attributes); + } else if (privateKey instanceof PicnicPrivateKeyParameters) { PicnicPrivateKeyParameters params = (PicnicPrivateKeyParameters)privateKey; @@ -230,13 +244,21 @@ else if (privateKey instanceof FalconPrivateKeyParameters) return new PrivateKeyInfo(algorithmIdentifier, falconPriv, attributes); } - else if (privateKey instanceof KyberPrivateKeyParameters) + else if (privateKey instanceof MLKEMPrivateKeyParameters) { - KyberPrivateKeyParameters params = (KyberPrivateKeyParameters)privateKey; + MLKEMPrivateKeyParameters params = (MLKEMPrivateKeyParameters)privateKey; - AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.kyberOidLookup(params.getParameters())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mlkemOidLookup(params.getParameters())); - return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + if (params.getPreferredFormat() == MLKEMPrivateKeyParameters.SEED_ONLY) + { + return new PrivateKeyInfo(algorithmIdentifier, new DERTaggedObject(false, 0, new DEROctetString(params.getSeed())), attributes); + } + else if (params.getPreferredFormat() == MLKEMPrivateKeyParameters.EXPANDED_KEY) + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + } + return new PrivateKeyInfo(algorithmIdentifier, getBasicPQCEncoding(params.getSeed(), params.getEncoded()), attributes); } else if (privateKey instanceof NTRULPRimePrivateKeyParameters) { @@ -269,6 +291,22 @@ else if (privateKey instanceof SNTRUPrimePrivateKeyParameters) return new PrivateKeyInfo(algorithmIdentifier, new DERSequence(v), attributes); } + else if (privateKey instanceof MLDSAPrivateKeyParameters) + { + MLDSAPrivateKeyParameters params = (MLDSAPrivateKeyParameters)privateKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mldsaOidLookup(params.getParameters())); + + if (params.getPreferredFormat() == MLDSAPrivateKeyParameters.SEED_ONLY) + { + return new PrivateKeyInfo(algorithmIdentifier, new DERTaggedObject(false, 0, new DEROctetString(params.getSeed())), attributes); + } + else if (params.getPreferredFormat() == MLDSAPrivateKeyParameters.EXPANDED_KEY) + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + } + return new PrivateKeyInfo(algorithmIdentifier, getBasicPQCEncoding(params.getSeed(), params.getEncoded()), attributes); + } else if (privateKey instanceof DilithiumPrivateKeyParameters) { DilithiumPrivateKeyParameters params = (DilithiumPrivateKeyParameters)privateKey; @@ -300,6 +338,20 @@ else if (privateKey instanceof RainbowPrivateKeyParameters) byte[] encoding = params.getEncoded(); return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(encoding), attributes); } + else if (privateKey instanceof MayoPrivateKeyParameters) + { + MayoPrivateKeyParameters params = (MayoPrivateKeyParameters)privateKey; + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mayoOidLookup(params.getParameters())); + byte[] encoding = params.getEncoded(); + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(encoding), attributes); + } + else if (privateKey instanceof SnovaPrivateKeyParameters) + { + SnovaPrivateKeyParameters params = (SnovaPrivateKeyParameters)privateKey; + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.snovaOidLookup(params.getParameters())); + byte[] encoding = params.getEncoded(); + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(encoding), attributes); + } else { throw new IOException("key parameters not recognized"); @@ -356,6 +408,17 @@ private static XMSSPrivateKey xmssCreateKeyStructure(XMSSPrivateKeyParameters ke } } + private static ASN1Sequence getBasicPQCEncoding(byte[] seed, byte[] expanded) + { + ASN1EncodableVector v = new ASN1EncodableVector(2); + + v.add(new DEROctetString(seed)); + + v.add(new DEROctetString(expanded)); + + return new DERSequence(v); + } + private static XMSSMTPrivateKey xmssmtCreateKeyStructure(XMSSMTPrivateKeyParameters keyParams) throws IOException { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java index b5b0decbae..db2e8d0a34 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java @@ -12,13 +12,13 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; import org.bouncycastle.pqc.asn1.CMCEPublicKey; -import org.bouncycastle.pqc.asn1.KyberPublicKey; import org.bouncycastle.pqc.asn1.McElieceCCA2PublicKey; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; @@ -31,8 +31,6 @@ import org.bouncycastle.pqc.crypto.cmce.CMCEPublicKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; @@ -40,7 +38,13 @@ import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPublicKeyParameters; import org.bouncycastle.pqc.crypto.lms.HSSPublicKeyParameters; -import org.bouncycastle.pqc.crypto.lms.LMSPublicKeyParameters; +import org.bouncycastle.pqc.crypto.lms.LMSKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPublicKeyParameters; @@ -54,6 +58,10 @@ import org.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; import org.bouncycastle.pqc.crypto.saber.SABERPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPublicKeyParameters; @@ -87,6 +95,7 @@ public class PublicKeyFactory converters.put(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, new LMSConverter()); converters.put(PQCObjectIdentifiers.mcElieceCca2, new McElieceCCA2Converter()); converters.put(BCObjectIdentifiers.sphincsPlus, new SPHINCSPlusConverter()); + converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, new SPHINCSPlusConverter()); @@ -105,23 +114,10 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3, new SPHINCSPlusConverter()); - - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_128f_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_192s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_192f_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, new SPHINCSPlusConverter()); @@ -138,7 +134,7 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.sphincsPlus_shake_256s, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_shake_256f, new SPHINCSPlusConverter()); converters.put(new ASN1ObjectIdentifier("1.3.9999.6.4.10"), new SPHINCSPlusConverter()); - + converters.put(BCObjectIdentifiers.mceliece348864_r3, new CMCEConverter()); converters.put(BCObjectIdentifiers.mceliece348864f_r3, new CMCEConverter()); converters.put(BCObjectIdentifiers.mceliece460896_r3, new CMCEConverter()); @@ -193,12 +189,12 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.ntruhrss1373, new NtruConverter()); converters.put(BCObjectIdentifiers.falcon_512, new FalconConverter()); converters.put(BCObjectIdentifiers.falcon_1024, new FalconConverter()); - converters.put(BCObjectIdentifiers.kyber512, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber768, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber1024, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber512_aes, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber768_aes, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber1024_aes, new KyberConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_512, new MLKEMConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_768, new MLKEMConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, new MLKEMConverter()); + converters.put(BCObjectIdentifiers.kyber512_aes, new MLKEMConverter()); + converters.put(BCObjectIdentifiers.kyber768_aes, new MLKEMConverter()); + converters.put(BCObjectIdentifiers.kyber1024_aes, new MLKEMConverter()); converters.put(BCObjectIdentifiers.ntrulpr653, new NTRULPrimeConverter()); converters.put(BCObjectIdentifiers.ntrulpr761, new NTRULPrimeConverter()); converters.put(BCObjectIdentifiers.ntrulpr857, new NTRULPrimeConverter()); @@ -211,6 +207,12 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.sntrup953, new SNTRUPrimeConverter()); converters.put(BCObjectIdentifiers.sntrup1013, new SNTRUPrimeConverter()); converters.put(BCObjectIdentifiers.sntrup1277, new SNTRUPrimeConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_44, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_65, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_87, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, new MLDSAConverter()); converters.put(BCObjectIdentifiers.dilithium2, new DilithiumConverter()); converters.put(BCObjectIdentifiers.dilithium3, new DilithiumConverter()); converters.put(BCObjectIdentifiers.dilithium5, new DilithiumConverter()); @@ -229,6 +231,81 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.rainbow_V_classic, new RainbowConverter()); converters.put(BCObjectIdentifiers.rainbow_V_circumzenithal, new RainbowConverter()); converters.put(BCObjectIdentifiers.rainbow_V_compressed, new RainbowConverter()); + + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, new SLHDSAConverter()); + + converters.put(BCObjectIdentifiers.mayo1, new MayoConverter()); + converters.put(BCObjectIdentifiers.mayo2, new MayoConverter()); + converters.put(BCObjectIdentifiers.mayo3, new MayoConverter()); + converters.put(BCObjectIdentifiers.mayo5, new MayoConverter()); + + converters.put(BCObjectIdentifiers.snova_24_5_4_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_4_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_4_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_4_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_5_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_5_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_5_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_24_5_5_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_25_8_3_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_25_8_3_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_25_8_3_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_25_8_3_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_29_6_5_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_29_6_5_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_29_6_5_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_29_6_5_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_8_4_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_8_4_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_8_4_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_8_4_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_17_2_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_17_2_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_17_2_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_37_17_2_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_49_11_3_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_49_11_3_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_49_11_3_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_49_11_3_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_56_25_2_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_56_25_2_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_56_25_2_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_56_25_2_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_60_10_4_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_60_10_4_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_60_10_4_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_60_10_4_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_66_15_3_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_66_15_3_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_66_15_3_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_66_15_3_shake_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_75_33_2_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_75_33_2_ssk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_75_33_2_shake_esk, new SnovaConverter()); + converters.put(BCObjectIdentifiers.snova_75_33_2_shake_ssk, new SnovaConverter()); } /** @@ -413,21 +490,21 @@ private static class LMSConverter AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { - byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + byte[] keyEnc = keyInfo.getPublicKeyData().getOctets(); + ASN1OctetString data = (ASN1OctetString)Utils.parseData(keyEnc); - if (Pack.bigEndianToInt(keyEnc, 0) == 1) - { - return LMSPublicKeyParameters.getInstance(Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); - } - else + if (data != null) { - // public key with extra tree height - if (keyEnc.length == 64) - { - keyEnc = Arrays.copyOfRange(keyEnc, 4, keyEnc.length); - } - return HSSPublicKeyParameters.getInstance(keyEnc); + return getLmsKeyParameters(data.getOctets()); } + + return getLmsKeyParameters(keyEnc); + } + + private LMSKeyParameters getLmsKeyParameters(byte[] keyEnc) + throws IOException + { + return HSSPublicKeyParameters.getInstance(keyEnc); } } @@ -471,7 +548,7 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje return new CMCEPublicKeyParameters(spParams, keyEnc); } catch (Exception e) - { + { byte[] keyEnc = keyInfo.getPublicKeyData().getOctets(); CMCEParameters spParams = Utils.mcElieceParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); @@ -482,13 +559,13 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } private static class SABERConverter - extends SubjectPublicKeyInfoConverter + extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) - throws IOException + throws IOException { byte[] keyEnc = ASN1OctetString.getInstance( - ASN1Sequence.getInstance(keyInfo.parsePublicKey()).getObjectAt(0)).getOctets(); + ASN1Sequence.getInstance(keyInfo.parsePublicKey()).getObjectAt(0)).getOctets(); SABERParameters saberParams = Utils.saberParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); @@ -509,10 +586,10 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } private static class FrodoConverter - extends SubjectPublicKeyInfoConverter + extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) - throws IOException + throws IOException { byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); @@ -523,10 +600,10 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } private static class PicnicConverter - extends SubjectPublicKeyInfoConverter + extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) - throws IOException + throws IOException { byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); @@ -542,7 +619,19 @@ private static class NtruConverter AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { - byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + byte[] keyEnc = keyInfo.getPublicKeyData().getOctets(); + ASN1OctetString data = Utils.parseOctetData(keyEnc); + + if (data != null) + { + return getNtruPublicKeyParameters(keyInfo, data.getOctets()); + } + + return getNtruPublicKeyParameters(keyInfo, keyEnc); + } + + private NTRUPublicKeyParameters getNtruPublicKeyParameters(SubjectPublicKeyInfo keyInfo, byte[] keyEnc) + { NTRUParameters ntruParams = Utils.ntruParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); @@ -566,25 +655,42 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } - private static class KyberConverter + static class MLKEMConverter extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { - KyberParameters kyberParameters = Utils.kyberParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + MLKEMParameters parameters = Utils.mlkemParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + // we're a raw encoding + return new MLKEMPublicKeyParameters(parameters, keyInfo.getPublicKeyData().getOctets()); + } + + static MLKEMPublicKeyParameters getPublicKeyParams(MLKEMParameters parameters, ASN1BitString publicKeyData) + { try { - ASN1Primitive obj = keyInfo.parsePublicKey(); - KyberPublicKey kyberKey = KyberPublicKey.getInstance(obj); + ASN1Primitive obj = ASN1Primitive.fromByteArray(publicKeyData.getOctets()); + if (obj instanceof ASN1Sequence) + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(obj); - return new KyberPublicKeyParameters(kyberParameters, kyberKey.getT(), kyberKey.getRho()); + return new MLKEMPublicKeyParameters(parameters, + ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(), + ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets()); + } + else + { + byte[] encKey = ASN1OctetString.getInstance(obj).getOctets(); + + return new MLKEMPublicKeyParameters(parameters, encKey); + } } catch (Exception e) { // we're a raw encoding - return new KyberPublicKeyParameters(kyberParameters, keyInfo.getPublicKeyData().getOctets()); + return new MLKEMPublicKeyParameters(parameters, publicKeyData.getOctets()); } } } @@ -616,7 +722,7 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje return new SNTRUPrimePublicKeyParameters(ntruLPRimeParams, keyEnc); } } - + static class DilithiumConverter extends SubjectPublicKeyInfoConverter { @@ -656,11 +762,50 @@ static DilithiumPublicKeyParameters getPublicKeyParams(DilithiumParameters dilit } } + static class MLDSAConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + MLDSAParameters dilithiumParams = Utils.mldsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return getPublicKeyParams(dilithiumParams, keyInfo.getPublicKeyData()); + } + + static MLDSAPublicKeyParameters getPublicKeyParams(MLDSAParameters mlDsaParams, ASN1BitString publicKeyData) + { + try + { + ASN1Primitive obj = ASN1Primitive.fromByteArray(publicKeyData.getOctets()); + if (obj instanceof ASN1Sequence) + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(obj); + + return new MLDSAPublicKeyParameters(mlDsaParams, + ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(), + ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets()); + } + else + { + byte[] encKey = ASN1OctetString.getInstance(obj).getOctets(); + + return new MLDSAPublicKeyParameters(mlDsaParams, encKey); + } + } + catch (Exception e) + { + // we're a raw encoding + return new MLDSAPublicKeyParameters(mlDsaParams, publicKeyData.getOctets()); + } + } + } + private static class BIKEConverter - extends SubjectPublicKeyInfoConverter + extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) - throws IOException + throws IOException { try { @@ -682,10 +827,10 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } private static class HQCConverter - extends SubjectPublicKeyInfoConverter + extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) - throws IOException + throws IOException { try { @@ -707,6 +852,31 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } + private static class SLHDSAConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + try + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SLHDSAPublicKeyParameters(spParams, Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); + } + catch (Exception e) + { + byte[] keyEnc = keyInfo.getPublicKeyData().getOctets(); + + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SLHDSAPublicKeyParameters(spParams, keyEnc); + } + } + } + private static class RainbowConverter extends SubjectPublicKeyInfoConverter { @@ -720,4 +890,32 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje return new RainbowPublicKeyParameters(rainbowParams, keyEnc); } } + + private static class MayoConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + + MayoParameters mayoParams = Utils.mayoParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new MayoPublicKeyParameters(mayoParams, keyEnc); + } + } + + private static class SnovaConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + + SnovaParameters snovaParams = Utils.snovaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SnovaPublicKeyParameters(snovaParams, keyEnc); + } + } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java b/core/src/main/java/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java index a6062e2ce2..f8f9c436bf 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java @@ -19,13 +19,15 @@ import org.bouncycastle.pqc.crypto.bike.BIKEPublicKeyParameters; import org.bouncycastle.pqc.crypto.cmce.CMCEPublicKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPublicKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPublicKeyParameters; import org.bouncycastle.pqc.crypto.lms.Composer; import org.bouncycastle.pqc.crypto.lms.HSSPublicKeyParameters; import org.bouncycastle.pqc.crypto.lms.LMSPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPublicKeyParameters; import org.bouncycastle.pqc.crypto.ntruprime.NTRULPRimePublicKeyParameters; @@ -33,6 +35,8 @@ import org.bouncycastle.pqc.crypto.picnic.PicnicPublicKeyParameters; import org.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPublicKeyParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSMTPublicKeyParameters; @@ -89,7 +93,7 @@ else if (publicKey instanceof LMSPublicKeyParameters) byte[] encoding = Composer.compose().u32str(1).bytes(params).build(); AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); - return new SubjectPublicKeyInfo(algorithmIdentifier, new DEROctetString(encoding)); + return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); } else if (publicKey instanceof HSSPublicKeyParameters) { @@ -98,7 +102,16 @@ else if (publicKey instanceof HSSPublicKeyParameters) byte[] encoding = Composer.compose().u32str(params.getL()).bytes(params.getLMSPublicKey()).build(); AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); - return new SubjectPublicKeyInfo(algorithmIdentifier, new DEROctetString(encoding)); + return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); + } + else if (publicKey instanceof SLHDSAPublicKeyParameters) + { + SLHDSAPublicKeyParameters params = (SLHDSAPublicKeyParameters)publicKey; + + byte[] encoding = params.getEncoded(); + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.slhdsaOidLookup(params.getParameters())); + return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); } else if (publicKey instanceof SPHINCSPlusPublicKeyParameters) { @@ -185,7 +198,7 @@ else if (publicKey instanceof SABERPublicKeyParameters) byte[] encoding = params.getEncoded(); AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.saberOidLookup(params.getParameters())); - + return new SubjectPublicKeyInfo(algorithmIdentifier, new DERSequence(new DEROctetString(encoding))); } else if (publicKey instanceof PicnicPublicKeyParameters) @@ -204,7 +217,7 @@ else if (publicKey instanceof NTRUPublicKeyParameters) byte[] encoding = params.getEncoded(); AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.ntruOidLookup(params.getParameters())); - return new SubjectPublicKeyInfo(algorithmIdentifier, new DEROctetString(encoding)); + return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); } else if (publicKey instanceof FalconPublicKeyParameters) { @@ -219,11 +232,11 @@ else if (publicKey instanceof FalconPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, keyEnc); } - else if (publicKey instanceof KyberPublicKeyParameters) + else if (publicKey instanceof MLKEMPublicKeyParameters) { - KyberPublicKeyParameters params = (KyberPublicKeyParameters)publicKey; + MLKEMPublicKeyParameters params = (MLKEMPublicKeyParameters)publicKey; - AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.kyberOidLookup(params.getParameters())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mlkemOidLookup(params.getParameters())); return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); } @@ -253,9 +266,17 @@ else if (publicKey instanceof DilithiumPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); } + else if (publicKey instanceof MLDSAPublicKeyParameters) + { + MLDSAPublicKeyParameters params = (MLDSAPublicKeyParameters)publicKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mldsaOidLookup(params.getParameters())); + + return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); + } else if (publicKey instanceof BIKEPublicKeyParameters) { - BIKEPublicKeyParameters params = (BIKEPublicKeyParameters) publicKey; + BIKEPublicKeyParameters params = (BIKEPublicKeyParameters)publicKey; byte[] encoding = params.getEncoded(); @@ -283,6 +304,20 @@ else if (publicKey instanceof RainbowPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, new DEROctetString(encoding)); } + else if (publicKey instanceof MayoPublicKeyParameters) + { + MayoPublicKeyParameters params = (MayoPublicKeyParameters)publicKey; + byte[] encoding = params.getEncoded(); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mayoOidLookup(params.getParameters())); + return new SubjectPublicKeyInfo(algorithmIdentifier, new DEROctetString(encoding)); + } + else if (publicKey instanceof SnovaPublicKeyParameters) + { + SnovaPublicKeyParameters params = (SnovaPublicKeyParameters)publicKey; + byte[] encoding = params.getEncoded(); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.snovaOidLookup(params.getParameters())); + return new SubjectPublicKeyInfo(algorithmIdentifier, new DEROctetString(encoding)); + } else { throw new IOException("key parameters not recognized"); diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/util/Utils.java b/core/src/main/java/org/bouncycastle/pqc/crypto/util/Utils.java index 5a92b52a99..6a3b4b2f66 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/util/Utils.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/util/Utils.java @@ -1,9 +1,15 @@ package org.bouncycastle.pqc.crypto.util; +import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.BERTags; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; @@ -18,16 +24,20 @@ import org.bouncycastle.pqc.crypto.bike.BIKEParameters; import org.bouncycastle.pqc.crypto.cmce.CMCEParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; import org.bouncycastle.pqc.crypto.ntruprime.NTRULPRimeParameters; import org.bouncycastle.pqc.crypto.ntruprime.SNTRUPrimeParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicParameters; import org.bouncycastle.pqc.crypto.rainbow.RainbowParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSKeyParameters; @@ -73,9 +83,6 @@ class Utils static final Map falconOids = new HashMap(); static final Map falconParams = new HashMap(); - static final Map kyberOids = new HashMap(); - static final Map kyberParams = new HashMap(); - static final Map ntruprimeOids = new HashMap(); static final Map ntruprimeParams = new HashMap(); @@ -94,6 +101,21 @@ class Utils static final Map rainbowOids = new HashMap(); static final Map rainbowParams = new HashMap(); + static final Map mlkemOids = new HashMap(); + static final Map mlkemParams = new HashMap(); + + static final Map mldsaOids = new HashMap(); + static final Map mldsaParams = new HashMap(); + + static final Map slhdsaOids = new HashMap(); + static final Map slhdsaParams = new HashMap(); + + static final Map mayoOids = new HashMap(); + static final Map mayoParams = new HashMap(); + + static final Map snovaOids = new HashMap(); + static final Map snovaParams = new HashMap(); + static { categories.put(PQCObjectIdentifiers.qTESLA_p_I, Integers.valueOf(QTESLASecurityCategory.PROVABLY_SECURE_I)); @@ -220,13 +242,13 @@ class Utils falconParams.put(BCObjectIdentifiers.falcon_512, FalconParameters.falcon_512); falconParams.put(BCObjectIdentifiers.falcon_1024, FalconParameters.falcon_1024); - kyberOids.put(KyberParameters.kyber512, BCObjectIdentifiers.kyber512); - kyberOids.put(KyberParameters.kyber768, BCObjectIdentifiers.kyber768); - kyberOids.put(KyberParameters.kyber1024, BCObjectIdentifiers.kyber1024); + mlkemOids.put(MLKEMParameters.ml_kem_512, NISTObjectIdentifiers.id_alg_ml_kem_512); + mlkemOids.put(MLKEMParameters.ml_kem_768, NISTObjectIdentifiers.id_alg_ml_kem_768); + mlkemOids.put(MLKEMParameters.ml_kem_1024, NISTObjectIdentifiers.id_alg_ml_kem_1024); - kyberParams.put(BCObjectIdentifiers.kyber512, KyberParameters.kyber512); - kyberParams.put(BCObjectIdentifiers.kyber768, KyberParameters.kyber768); - kyberParams.put(BCObjectIdentifiers.kyber1024, KyberParameters.kyber1024); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_512, MLKEMParameters.ml_kem_512); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_768, MLKEMParameters.ml_kem_768); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, MLKEMParameters.ml_kem_1024); ntruprimeOids.put(NTRULPRimeParameters.ntrulpr653, BCObjectIdentifiers.ntrulpr653); ntruprimeOids.put(NTRULPRimeParameters.ntrulpr761, BCObjectIdentifiers.ntrulpr761); @@ -256,6 +278,20 @@ class Utils sntruprimeParams.put(BCObjectIdentifiers.sntrup1013, SNTRUPrimeParameters.sntrup1013); sntruprimeParams.put(BCObjectIdentifiers.sntrup1277, SNTRUPrimeParameters.sntrup1277); + mldsaOids.put(MLDSAParameters.ml_dsa_44, NISTObjectIdentifiers.id_ml_dsa_44); + mldsaOids.put(MLDSAParameters.ml_dsa_65, NISTObjectIdentifiers.id_ml_dsa_65); + mldsaOids.put(MLDSAParameters.ml_dsa_87, NISTObjectIdentifiers.id_ml_dsa_87); + mldsaOids.put(MLDSAParameters.ml_dsa_44_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + mldsaOids.put(MLDSAParameters.ml_dsa_65_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + mldsaOids.put(MLDSAParameters.ml_dsa_87_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_44, MLDSAParameters.ml_dsa_44); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_65, MLDSAParameters.ml_dsa_65); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_87, MLDSAParameters.ml_dsa_87); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, MLDSAParameters.ml_dsa_44_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, MLDSAParameters.ml_dsa_65_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, MLDSAParameters.ml_dsa_87_with_sha512); + dilithiumOids.put(DilithiumParameters.dilithium2, BCObjectIdentifiers.dilithium2); dilithiumOids.put(DilithiumParameters.dilithium3, BCObjectIdentifiers.dilithium3); dilithiumOids.put(DilithiumParameters.dilithium5, BCObjectIdentifiers.dilithium5); @@ -294,6 +330,71 @@ class Utils rainbowOids.put(RainbowParameters.rainbowVcircumzenithal, BCObjectIdentifiers.rainbow_V_circumzenithal); rainbowOids.put(RainbowParameters.rainbowVcompressed, BCObjectIdentifiers.rainbow_V_compressed); + slhdsaOids.put(SLHDSAParameters.sha2_128s, NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + slhdsaOids.put(SLHDSAParameters.sha2_128f, NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + slhdsaOids.put(SLHDSAParameters.sha2_192s, NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + slhdsaOids.put(SLHDSAParameters.sha2_192f, NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + slhdsaOids.put(SLHDSAParameters.sha2_256s, NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + slhdsaOids.put(SLHDSAParameters.sha2_256f, NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + slhdsaOids.put(SLHDSAParameters.shake_128s, NISTObjectIdentifiers.id_slh_dsa_shake_128s); + slhdsaOids.put(SLHDSAParameters.shake_128f, NISTObjectIdentifiers.id_slh_dsa_shake_128f); + slhdsaOids.put(SLHDSAParameters.shake_192s, NISTObjectIdentifiers.id_slh_dsa_shake_192s); + slhdsaOids.put(SLHDSAParameters.shake_192f, NISTObjectIdentifiers.id_slh_dsa_shake_192f); + slhdsaOids.put(SLHDSAParameters.shake_256s, NISTObjectIdentifiers.id_slh_dsa_shake_256s); + slhdsaOids.put(SLHDSAParameters.shake_256f, NISTObjectIdentifiers.id_slh_dsa_shake_256f); + + slhdsaOids.put(SLHDSAParameters.sha2_128s_with_sha256, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + slhdsaOids.put(SLHDSAParameters.sha2_128f_with_sha256, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + slhdsaOids.put(SLHDSAParameters.sha2_192s_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + slhdsaOids.put(SLHDSAParameters.sha2_192f_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + slhdsaOids.put(SLHDSAParameters.sha2_256s_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + slhdsaOids.put(SLHDSAParameters.sha2_256f_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + slhdsaOids.put(SLHDSAParameters.shake_128s_with_shake128, NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + slhdsaOids.put(SLHDSAParameters.shake_128f_with_shake128, NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + slhdsaOids.put(SLHDSAParameters.shake_192s_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + slhdsaOids.put(SLHDSAParameters.shake_192f_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + slhdsaOids.put(SLHDSAParameters.shake_256s_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + slhdsaOids.put(SLHDSAParameters.shake_256f_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, SLHDSAParameters.sha2_128s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, SLHDSAParameters.sha2_128f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, SLHDSAParameters.sha2_192s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, SLHDSAParameters.sha2_192f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, SLHDSAParameters.sha2_256s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, SLHDSAParameters.sha2_256f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, SLHDSAParameters.shake_128s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, SLHDSAParameters.shake_128f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, SLHDSAParameters.shake_192s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, SLHDSAParameters.shake_192f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, SLHDSAParameters.shake_256s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, SLHDSAParameters.shake_256f); + + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, SLHDSAParameters.sha2_128s_with_sha256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, SLHDSAParameters.sha2_128f_with_sha256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, SLHDSAParameters.sha2_192s_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, SLHDSAParameters.sha2_192f_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, SLHDSAParameters.sha2_256s_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, SLHDSAParameters.sha2_256f_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, SLHDSAParameters.shake_128s_with_shake128); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, SLHDSAParameters.shake_128f_with_shake128); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, SLHDSAParameters.shake_192s_with_shake256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, SLHDSAParameters.shake_192f_with_shake256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, SLHDSAParameters.shake_256s_with_shake256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, SLHDSAParameters.shake_256f_with_shake256); + + sphincsPlusOids.put(SLHDSAParameters.sha2_128s, BCObjectIdentifiers.sphincsPlus_sha2_128s); + sphincsPlusOids.put(SLHDSAParameters.sha2_128f, BCObjectIdentifiers.sphincsPlus_sha2_128f); + sphincsPlusOids.put(SLHDSAParameters.sha2_192s, BCObjectIdentifiers.sphincsPlus_sha2_192s); + sphincsPlusOids.put(SLHDSAParameters.sha2_192f, BCObjectIdentifiers.sphincsPlus_sha2_192f); + sphincsPlusOids.put(SLHDSAParameters.sha2_256s, BCObjectIdentifiers.sphincsPlus_sha2_256s); + sphincsPlusOids.put(SLHDSAParameters.sha2_256f, BCObjectIdentifiers.sphincsPlus_sha2_256f); + sphincsPlusOids.put(SLHDSAParameters.shake_128s, BCObjectIdentifiers.sphincsPlus_shake_128s); + sphincsPlusOids.put(SLHDSAParameters.shake_128f, BCObjectIdentifiers.sphincsPlus_shake_128f); + sphincsPlusOids.put(SLHDSAParameters.shake_192s, BCObjectIdentifiers.sphincsPlus_shake_192s); + sphincsPlusOids.put(SLHDSAParameters.shake_192f, BCObjectIdentifiers.sphincsPlus_shake_192f); + sphincsPlusOids.put(SLHDSAParameters.shake_256s, BCObjectIdentifiers.sphincsPlus_shake_256s); + sphincsPlusOids.put(SLHDSAParameters.shake_256f, BCObjectIdentifiers.sphincsPlus_shake_256f); + sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128s_robust, BCObjectIdentifiers.sphincsPlus_sha2_128s_r3); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128f_robust, BCObjectIdentifiers.sphincsPlus_sha2_128f_r3); sphincsPlusOids.put(SPHINCSPlusParameters.shake_128s_robust, BCObjectIdentifiers.sphincsPlus_shake_128s_r3); @@ -312,27 +413,26 @@ class Utils sphincsPlusOids.put(SPHINCSPlusParameters.shake_256f_robust, BCObjectIdentifiers.sphincsPlus_shake_256f_r3); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_256s, BCObjectIdentifiers.sphincsPlus_haraka_256s_r3); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_256f, BCObjectIdentifiers.sphincsPlus_haraka_256f_r3); - sphincsPlusOids.put(SPHINCSPlusParameters.haraka_128s_simple, BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_128f_simple, BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_192s_simple, BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_192f_simple, BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_256s_simple, BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_256f_simple, BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple); - + sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128s, BCObjectIdentifiers.sphincsPlus_sha2_128s); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128f, BCObjectIdentifiers.sphincsPlus_sha2_128f); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_128s, BCObjectIdentifiers.sphincsPlus_shake_128s); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_128f, BCObjectIdentifiers.sphincsPlus_shake_128f); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_192s, BCObjectIdentifiers.sphincsPlus_sha2_192s); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_192f, BCObjectIdentifiers.sphincsPlus_sha2_192f); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_192s, BCObjectIdentifiers.sphincsPlus_shake_192s); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_192f, BCObjectIdentifiers.sphincsPlus_shake_192f); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_256s, BCObjectIdentifiers.sphincsPlus_sha2_256s); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_256f, BCObjectIdentifiers.sphincsPlus_sha2_256f); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_128s, BCObjectIdentifiers.sphincsPlus_shake_128s); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_128f, BCObjectIdentifiers.sphincsPlus_shake_128f); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_192s, BCObjectIdentifiers.sphincsPlus_shake_192s); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_192f, BCObjectIdentifiers.sphincsPlus_shake_192f); sphincsPlusOids.put(SPHINCSPlusParameters.shake_256s, BCObjectIdentifiers.sphincsPlus_shake_256s); sphincsPlusOids.put(SPHINCSPlusParameters.shake_256f, BCObjectIdentifiers.sphincsPlus_shake_256f); - + sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128s, SPHINCSPlusParameters.sha2_128s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128f, SPHINCSPlusParameters.sha2_128f); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_128s, SPHINCSPlusParameters.shake_128s); @@ -345,7 +445,6 @@ class Utils sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_256f, SPHINCSPlusParameters.sha2_256f); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256s, SPHINCSPlusParameters.shake_256s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256f, SPHINCSPlusParameters.shake_256f); - sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, SPHINCSPlusParameters.sha2_128s_robust); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, SPHINCSPlusParameters.sha2_128f_robust); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, SPHINCSPlusParameters.shake_128s_robust); @@ -364,7 +463,6 @@ class Utils sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, SPHINCSPlusParameters.shake_256f_robust); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3, SPHINCSPlusParameters.haraka_256s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3, SPHINCSPlusParameters.haraka_256f); - sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, SPHINCSPlusParameters.sha2_128s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, SPHINCSPlusParameters.sha2_128f); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, SPHINCSPlusParameters.shake_128s); @@ -383,6 +481,116 @@ class Utils sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, SPHINCSPlusParameters.shake_256f); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, SPHINCSPlusParameters.haraka_256s_simple); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, SPHINCSPlusParameters.haraka_256f_simple); + + mayoOids.put(MayoParameters.mayo1, BCObjectIdentifiers.mayo1); + mayoOids.put(MayoParameters.mayo2, BCObjectIdentifiers.mayo2); + mayoOids.put(MayoParameters.mayo3, BCObjectIdentifiers.mayo3); + mayoOids.put(MayoParameters.mayo5, BCObjectIdentifiers.mayo5); + + mayoParams.put(BCObjectIdentifiers.mayo1, MayoParameters.mayo1); + mayoParams.put(BCObjectIdentifiers.mayo2, MayoParameters.mayo2); + mayoParams.put(BCObjectIdentifiers.mayo3, MayoParameters.mayo3); + mayoParams.put(BCObjectIdentifiers.mayo5, MayoParameters.mayo5); + + snovaOids.put(SnovaParameters.SNOVA_24_5_4_SSK, BCObjectIdentifiers.snova_24_5_4_ssk); + snovaOids.put(SnovaParameters.SNOVA_24_5_4_ESK, BCObjectIdentifiers.snova_24_5_4_esk); + snovaOids.put(SnovaParameters.SNOVA_24_5_4_SHAKE_SSK, BCObjectIdentifiers.snova_24_5_4_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_24_5_4_SHAKE_ESK, BCObjectIdentifiers.snova_24_5_4_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_24_5_5_SSK, BCObjectIdentifiers.snova_24_5_5_ssk); + snovaOids.put(SnovaParameters.SNOVA_24_5_5_ESK, BCObjectIdentifiers.snova_24_5_5_esk); + snovaOids.put(SnovaParameters.SNOVA_24_5_5_SHAKE_SSK, BCObjectIdentifiers.snova_24_5_5_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_24_5_5_SHAKE_ESK, BCObjectIdentifiers.snova_24_5_5_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_25_8_3_SSK, BCObjectIdentifiers.snova_25_8_3_ssk); + snovaOids.put(SnovaParameters.SNOVA_25_8_3_ESK, BCObjectIdentifiers.snova_25_8_3_esk); + snovaOids.put(SnovaParameters.SNOVA_25_8_3_SHAKE_SSK, BCObjectIdentifiers.snova_25_8_3_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_25_8_3_SHAKE_ESK, BCObjectIdentifiers.snova_25_8_3_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_29_6_5_SSK, BCObjectIdentifiers.snova_29_6_5_ssk); + snovaOids.put(SnovaParameters.SNOVA_29_6_5_ESK, BCObjectIdentifiers.snova_29_6_5_esk); + snovaOids.put(SnovaParameters.SNOVA_29_6_5_SHAKE_SSK, BCObjectIdentifiers.snova_29_6_5_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_29_6_5_SHAKE_ESK, BCObjectIdentifiers.snova_29_6_5_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_37_8_4_SSK, BCObjectIdentifiers.snova_37_8_4_ssk); + snovaOids.put(SnovaParameters.SNOVA_37_8_4_ESK, BCObjectIdentifiers.snova_37_8_4_esk); + snovaOids.put(SnovaParameters.SNOVA_37_8_4_SHAKE_SSK, BCObjectIdentifiers.snova_37_8_4_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_37_8_4_SHAKE_ESK, BCObjectIdentifiers.snova_37_8_4_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_37_17_2_SSK, BCObjectIdentifiers.snova_37_17_2_ssk); + snovaOids.put(SnovaParameters.SNOVA_37_17_2_ESK, BCObjectIdentifiers.snova_37_17_2_esk); + snovaOids.put(SnovaParameters.SNOVA_37_17_2_SHAKE_SSK, BCObjectIdentifiers.snova_37_17_2_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_37_17_2_SHAKE_ESK, BCObjectIdentifiers.snova_37_17_2_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_49_11_3_SSK, BCObjectIdentifiers.snova_49_11_3_ssk); + snovaOids.put(SnovaParameters.SNOVA_49_11_3_ESK, BCObjectIdentifiers.snova_49_11_3_esk); + snovaOids.put(SnovaParameters.SNOVA_49_11_3_SHAKE_SSK, BCObjectIdentifiers.snova_49_11_3_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_49_11_3_SHAKE_ESK, BCObjectIdentifiers.snova_49_11_3_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_56_25_2_SSK, BCObjectIdentifiers.snova_56_25_2_ssk); + snovaOids.put(SnovaParameters.SNOVA_56_25_2_ESK, BCObjectIdentifiers.snova_56_25_2_esk); + snovaOids.put(SnovaParameters.SNOVA_56_25_2_SHAKE_SSK, BCObjectIdentifiers.snova_56_25_2_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_56_25_2_SHAKE_ESK, BCObjectIdentifiers.snova_56_25_2_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_60_10_4_SSK, BCObjectIdentifiers.snova_60_10_4_ssk); + snovaOids.put(SnovaParameters.SNOVA_60_10_4_ESK, BCObjectIdentifiers.snova_60_10_4_esk); + snovaOids.put(SnovaParameters.SNOVA_60_10_4_SHAKE_SSK, BCObjectIdentifiers.snova_60_10_4_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_60_10_4_SHAKE_ESK, BCObjectIdentifiers.snova_60_10_4_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_66_15_3_SSK, BCObjectIdentifiers.snova_66_15_3_ssk); + snovaOids.put(SnovaParameters.SNOVA_66_15_3_ESK, BCObjectIdentifiers.snova_66_15_3_esk); + snovaOids.put(SnovaParameters.SNOVA_66_15_3_SHAKE_SSK, BCObjectIdentifiers.snova_66_15_3_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_66_15_3_SHAKE_ESK, BCObjectIdentifiers.snova_66_15_3_shake_esk); + snovaOids.put(SnovaParameters.SNOVA_75_33_2_SSK, BCObjectIdentifiers.snova_75_33_2_ssk); + snovaOids.put(SnovaParameters.SNOVA_75_33_2_ESK, BCObjectIdentifiers.snova_75_33_2_esk); + snovaOids.put(SnovaParameters.SNOVA_75_33_2_SHAKE_SSK, BCObjectIdentifiers.snova_75_33_2_shake_ssk); + snovaOids.put(SnovaParameters.SNOVA_75_33_2_SHAKE_ESK, BCObjectIdentifiers.snova_75_33_2_shake_esk); + + snovaParams.put(BCObjectIdentifiers.snova_24_5_4_ssk, SnovaParameters.SNOVA_24_5_4_SSK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_4_esk, SnovaParameters.SNOVA_24_5_4_ESK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_4_shake_ssk, SnovaParameters.SNOVA_24_5_4_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_4_shake_esk, SnovaParameters.SNOVA_24_5_4_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_5_ssk, SnovaParameters.SNOVA_24_5_5_SSK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_5_esk, SnovaParameters.SNOVA_24_5_5_ESK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_5_shake_ssk, SnovaParameters.SNOVA_24_5_5_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_24_5_5_shake_esk, SnovaParameters.SNOVA_24_5_5_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_25_8_3_ssk, SnovaParameters.SNOVA_25_8_3_SSK); + snovaParams.put(BCObjectIdentifiers.snova_25_8_3_esk, SnovaParameters.SNOVA_25_8_3_ESK); + snovaParams.put(BCObjectIdentifiers.snova_25_8_3_shake_ssk, SnovaParameters.SNOVA_25_8_3_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_25_8_3_shake_esk, SnovaParameters.SNOVA_25_8_3_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_29_6_5_ssk, SnovaParameters.SNOVA_29_6_5_SSK); + snovaParams.put(BCObjectIdentifiers.snova_29_6_5_esk, SnovaParameters.SNOVA_29_6_5_ESK); + snovaParams.put(BCObjectIdentifiers.snova_29_6_5_shake_ssk, SnovaParameters.SNOVA_29_6_5_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_29_6_5_shake_esk, SnovaParameters.SNOVA_29_6_5_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_37_8_4_ssk, SnovaParameters.SNOVA_37_8_4_SSK); + snovaParams.put(BCObjectIdentifiers.snova_37_8_4_esk, SnovaParameters.SNOVA_37_8_4_ESK); + snovaParams.put(BCObjectIdentifiers.snova_37_8_4_shake_ssk, SnovaParameters.SNOVA_37_8_4_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_37_8_4_shake_esk, SnovaParameters.SNOVA_37_8_4_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_37_17_2_ssk, SnovaParameters.SNOVA_37_17_2_SSK); + snovaParams.put(BCObjectIdentifiers.snova_37_17_2_esk, SnovaParameters.SNOVA_37_17_2_ESK); + snovaParams.put(BCObjectIdentifiers.snova_37_17_2_shake_ssk, SnovaParameters.SNOVA_37_17_2_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_37_17_2_shake_esk, SnovaParameters.SNOVA_37_17_2_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_49_11_3_ssk, SnovaParameters.SNOVA_49_11_3_SSK); + snovaParams.put(BCObjectIdentifiers.snova_49_11_3_esk, SnovaParameters.SNOVA_49_11_3_ESK); + snovaParams.put(BCObjectIdentifiers.snova_49_11_3_shake_ssk, SnovaParameters.SNOVA_49_11_3_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_49_11_3_shake_esk, SnovaParameters.SNOVA_49_11_3_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_56_25_2_ssk, SnovaParameters.SNOVA_56_25_2_SSK); + snovaParams.put(BCObjectIdentifiers.snova_56_25_2_esk, SnovaParameters.SNOVA_56_25_2_ESK); + snovaParams.put(BCObjectIdentifiers.snova_56_25_2_shake_ssk, SnovaParameters.SNOVA_56_25_2_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_56_25_2_shake_esk, SnovaParameters.SNOVA_56_25_2_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_60_10_4_ssk, SnovaParameters.SNOVA_60_10_4_SSK); + snovaParams.put(BCObjectIdentifiers.snova_60_10_4_esk, SnovaParameters.SNOVA_60_10_4_ESK); + snovaParams.put(BCObjectIdentifiers.snova_60_10_4_shake_ssk, SnovaParameters.SNOVA_60_10_4_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_60_10_4_shake_esk, SnovaParameters.SNOVA_60_10_4_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_66_15_3_ssk, SnovaParameters.SNOVA_66_15_3_SSK); + snovaParams.put(BCObjectIdentifiers.snova_66_15_3_esk, SnovaParameters.SNOVA_66_15_3_ESK); + snovaParams.put(BCObjectIdentifiers.snova_66_15_3_shake_ssk, SnovaParameters.SNOVA_66_15_3_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_66_15_3_shake_esk, SnovaParameters.SNOVA_66_15_3_SHAKE_ESK); + snovaParams.put(BCObjectIdentifiers.snova_75_33_2_ssk, SnovaParameters.SNOVA_75_33_2_SSK); + snovaParams.put(BCObjectIdentifiers.snova_75_33_2_esk, SnovaParameters.SNOVA_75_33_2_ESK); + snovaParams.put(BCObjectIdentifiers.snova_75_33_2_shake_ssk, SnovaParameters.SNOVA_75_33_2_SHAKE_SSK); + snovaParams.put(BCObjectIdentifiers.snova_75_33_2_shake_esk, SnovaParameters.SNOVA_75_33_2_SHAKE_ESK); + } + + static ASN1ObjectIdentifier slhdsaOidLookup(SLHDSAParameters params) + { + return (ASN1ObjectIdentifier)slhdsaOids.get(params); + } + + static SLHDSAParameters slhdsaParamsLookup(ASN1ObjectIdentifier oid) + { + return (SLHDSAParameters)slhdsaParams.get(oid); } static int qTeslaLookupSecurityCategory(AlgorithmIdentifier algorithm) @@ -605,14 +813,14 @@ static NTRUParameters ntruParamsLookup(ASN1ObjectIdentifier oid) return (NTRUParameters)ntruParams.get(oid); } - static ASN1ObjectIdentifier kyberOidLookup(KyberParameters params) + static ASN1ObjectIdentifier mlkemOidLookup(MLKEMParameters params) { - return (ASN1ObjectIdentifier)kyberOids.get(params); + return (ASN1ObjectIdentifier)mlkemOids.get(params); } - static KyberParameters kyberParamsLookup(ASN1ObjectIdentifier oid) + static MLKEMParameters mlkemParamsLookup(ASN1ObjectIdentifier oid) { - return (KyberParameters)kyberParams.get(oid); + return (MLKEMParameters)mlkemParams.get(oid); } static ASN1ObjectIdentifier ntrulprimeOidLookup(NTRULPRimeParameters params) @@ -635,6 +843,16 @@ static SNTRUPrimeParameters sntruprimeParamsLookup(ASN1ObjectIdentifier oid) return (SNTRUPrimeParameters)sntruprimeParams.get(oid); } + static ASN1ObjectIdentifier mldsaOidLookup(MLDSAParameters params) + { + return (ASN1ObjectIdentifier)mldsaOids.get(params); + } + + static MLDSAParameters mldsaParamsLookup(ASN1ObjectIdentifier oid) + { + return (MLDSAParameters)mldsaParams.get(oid); + } + static ASN1ObjectIdentifier dilithiumOidLookup(DilithiumParameters params) { return (ASN1ObjectIdentifier)dilithiumOids.get(params); @@ -674,4 +892,100 @@ static RainbowParameters rainbowParamsLookup(ASN1ObjectIdentifier oid) { return (RainbowParameters)rainbowParams.get(oid); } + + static ASN1ObjectIdentifier mayoOidLookup(MayoParameters params) + { + return (ASN1ObjectIdentifier)mayoOids.get(params); + } + + static MayoParameters mayoParamsLookup(ASN1ObjectIdentifier oid) + { + return (MayoParameters)mayoParams.get(oid); + } + + static ASN1ObjectIdentifier snovaOidLookup(SnovaParameters params) + { + return (ASN1ObjectIdentifier)snovaOids.get(params); + } + + static SnovaParameters snovaParamsLookup(ASN1ObjectIdentifier oid) + { + return (SnovaParameters)snovaParams.get(oid); + } + + private static boolean isRaw(byte[] data) + { + // check well-formed first + ByteArrayInputStream bIn = new ByteArrayInputStream(data); + + int tag = bIn.read(); + int len = readLen(bIn); + if (len != bIn.available()) + { + return true; + } + + return false; + } + + static ASN1OctetString parseOctetData(byte[] data) + { + // check well-formed first + if (!isRaw(data)) + { + if (data[0] == BERTags.OCTET_STRING) + { + return ASN1OctetString.getInstance(data); + } + } + + return null; + } + + static ASN1Primitive parseData(byte[] data) + { + // check well-formed first + if (!isRaw(data)) + { + if (data[0] == (BERTags.SEQUENCE | BERTags.CONSTRUCTED)) + { + return ASN1Sequence.getInstance(data); + } + + if (data[0] == BERTags.OCTET_STRING) + { + return ASN1OctetString.getInstance(data); + } + + if ((data[0] & 0xff) == BERTags.TAGGED) + { + return ASN1OctetString.getInstance(ASN1TaggedObject.getInstance(data), false); + } + } + + return null; + } + + /** + * ASN.1 length reader. + */ + static int readLen(ByteArrayInputStream bIn) + { + int length = bIn.read(); + if (length < 0) + { + return -1; + } + if (length != (length & 0x7f)) + { + int count = length & 0x7f; + length = 0; + while (count-- != 0) + { + length = (length << 8) + bIn.read(); + } + } + + return length; + } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/xmss/package-info.java b/core/src/main/java/org/bouncycastle/pqc/crypto/xmss/package-info.java new file mode 100644 index 0000000000..64857136dc --- /dev/null +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/xmss/package-info.java @@ -0,0 +1,4 @@ +/** + * Low level implementation of the XMSS and XMSS^MT signature algorithms. + */ +package org.bouncycastle.pqc.crypto.xmss; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMExtractor.java b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMExtractor.java index 1323060a98..657df1a12b 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMExtractor.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMExtractor.java @@ -1,62 +1,54 @@ package org.bouncycastle.pqc.crypto.xwing; import org.bouncycastle.crypto.EncapsulatedSecretExtractor; -import org.bouncycastle.crypto.agreement.X25519Agreement; -import org.bouncycastle.crypto.digests.SHA3Digest; -import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; import org.bouncycastle.crypto.params.X25519PublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Strings; +/** + * Implements the decapsulation process of the X-Wing hybrid Key Encapsulation Mechanism (KEM). + *

    + * This class allows the recipient to derive the shared secret from a given ciphertext using their private key, + * as defined in the X-Wing KEM specification. + *

    + * + * @see X-Wing KEM Draft + */ public class XWingKEMExtractor implements EncapsulatedSecretExtractor { + private static final int MLKEM_CIPHERTEXT_SIZE = 1088; private final XWingPrivateKeyParameters key; - private final KyberKEMExtractor kemExtractor; + private final MLKEMExtractor mlkemExtractor; public XWingKEMExtractor(XWingPrivateKeyParameters privParams) { this.key = privParams; - this.kemExtractor = new KyberKEMExtractor((KyberPrivateKeyParameters)key.getKyberPrivateKey()); + this.mlkemExtractor = new MLKEMExtractor(key.getKyberPrivateKey()); } @Override public byte[] extractSecret(byte[] encapsulation) { - // Decryption - byte[] kybSecret = kemExtractor.extractSecret(Arrays.copyOfRange(encapsulation, 0, encapsulation.length - X25519PublicKeyParameters.KEY_SIZE)); - X25519Agreement xdhAgree = new X25519Agreement(); + // 1. Split ciphertext into ML-KEM and X25519 parts + byte[] ctM = Arrays.copyOfRange(encapsulation, 0, MLKEM_CIPHERTEXT_SIZE); + byte[] ctX = Arrays.copyOfRange(encapsulation, MLKEM_CIPHERTEXT_SIZE, encapsulation.length); - byte[] k = new byte[kybSecret.length + xdhAgree.getAgreementSize()]; + // 2. Compute X25519 shared secret + byte[] ssX = XWingKEMGenerator.computeSSX(new X25519PublicKeyParameters(ctX, 0), key.getXDHPrivateKey()); - System.arraycopy(kybSecret, 0, k, 0, kybSecret.length); + // 3. Compute combiner: SHA3-256(ssM || ssX || ctX || pkX || XWING_LABEL) + byte[] kemSecret = XWingKEMGenerator.computeSharedSecret(key.getXDHPublicKey().getEncoded(), + mlkemExtractor.extractSecret(ctM), ctX, ssX); - Arrays.clear(kybSecret); - - xdhAgree.init(key.getXDHPrivateKey()); - - X25519PublicKeyParameters ephXdhPub = new X25519PublicKeyParameters(Arrays.copyOfRange(encapsulation, encapsulation.length - X25519PublicKeyParameters.KEY_SIZE, encapsulation.length)); - - xdhAgree.calculateAgreement(ephXdhPub, k, kybSecret.length); - - SHA3Digest sha3 = new SHA3Digest(256); - - sha3.update(Strings.toByteArray("\\.//^\\"), 0, 6); - sha3.update(k, 0, k.length); - sha3.update(ephXdhPub.getEncoded(), 0, X25519PublicKeyParameters.KEY_SIZE); - sha3.update(((X25519PrivateKeyParameters)key.getXDHPrivateKey()).generatePublicKey().getEncoded(), 0, X25519PublicKeyParameters.KEY_SIZE); - - byte[] kemSecret = new byte[32]; - - sha3.doFinal(kemSecret, 0); + // 4. Cleanup intermediate values + Arrays.clear(ssX); return kemSecret; } public int getEncapsulationLength() { - return kemExtractor.getEncapsulationLength() + X25519PublicKeyParameters.KEY_SIZE; + return mlkemExtractor.getEncapsulationLength() + X25519PublicKeyParameters.KEY_SIZE; } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMGenerator.java index 2efb29e7bb..807ae7bfd3 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKEMGenerator.java @@ -10,61 +10,88 @@ import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; import org.bouncycastle.crypto.params.X25519PublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.util.SecretWithEncapsulationImpl; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; +/** + * Implements the encapsulation process of the X-Wing hybrid Key Encapsulation Mechanism (KEM). + *

    + * X-Wing is a general-purpose hybrid post-quantum/traditional KEM that combines X25519 and ML-KEM-768, + * as specified in the IETF draft: draft-connolly-cfrg-xwing-kem-07. + *

    + *

    + * This class facilitates the generation of ciphertexts and shared secrets using a recipient's public key. + *

    + * + * @see X-Wing KEM Draft + */ public class XWingKEMGenerator implements EncapsulatedSecretGenerator { - // the source of randomness - private final SecureRandom sr; + private final SecureRandom random; + private static final byte[] XWING_LABEL = Strings.toByteArray("\\.//^\\"); public XWingKEMGenerator(SecureRandom random) { - this.sr = random; + this.random = random; } public SecretWithEncapsulation generateEncapsulated(AsymmetricKeyParameter recipientKey) { XWingPublicKeyParameters key = (XWingPublicKeyParameters)recipientKey; + MLKEMPublicKeyParameters kyberPub = key.getKyberPublicKey(); + X25519PublicKeyParameters xdhPub = key.getXDHPublicKey(); + byte[] xdhPubBytes = xdhPub.getEncoded(); - KyberKEMGenerator kybKem = new KyberKEMGenerator(sr); - - SecretWithEncapsulation kybSecWithEnc = kybKem.generateEncapsulated(key.getKyberPublicKey()); - X25519Agreement xdhAgree = new X25519Agreement(); - byte[] kybSecret = kybSecWithEnc.getSecret(); - byte[] k = new byte[kybSecret.length + xdhAgree.getAgreementSize()]; - - System.arraycopy(kybSecret, 0, k, 0, kybSecret.length); - - Arrays.clear(kybSecret); + // 1. Perform ML-KEM encapsulation + MLKEMGenerator mlkemGen = new MLKEMGenerator(random); + SecretWithEncapsulation mlkemSec = mlkemGen.generateEncapsulated(kyberPub); + byte[] ctM = mlkemSec.getEncapsulation(); + // 2. Generate ephemeral X25519 key pair X25519KeyPairGenerator xdhGen = new X25519KeyPairGenerator(); + xdhGen.init(new X25519KeyGenerationParameters(random)); + AsymmetricCipherKeyPair ephXdhKp = xdhGen.generateKeyPair(); + byte[] ctX = ((X25519PublicKeyParameters)ephXdhKp.getPublic()).getEncoded(); - xdhGen.init(new X25519KeyGenerationParameters(sr)); + // 3. Perform X25519 agreement + byte[] ssX = computeSSX(xdhPub, (X25519PrivateKeyParameters)ephXdhKp.getPrivate()); - AsymmetricCipherKeyPair ephXdh = xdhGen.generateKeyPair(); + // 4. Compute shared secret: SHA3-256(ssM || ssX || ctX || pkX || label) + byte[] ss = computeSharedSecret(xdhPubBytes, mlkemSec.getSecret(), ctX, ssX); - xdhAgree.init(ephXdh.getPrivate()); + // 5. Cleanup intermediate values + Arrays.clear(ssX); - xdhAgree.calculateAgreement(key.getXDHPublicKey(), k, kybSecret.length); + // 6. Return shared secret and encapsulation (ctM || ctX) + return new SecretWithEncapsulationImpl(ss, Arrays.concatenate(ctM, ctX)); + } - X25519PublicKeyParameters ephXdhPub = (X25519PublicKeyParameters)ephXdh.getPublic(); + static byte[] computeSSX(X25519PublicKeyParameters xdhPub, X25519PrivateKeyParameters ephXdhPriv) + { + X25519Agreement xdhAgreement = new X25519Agreement(); + xdhAgreement.init(ephXdhPriv); + byte[] ssX = new byte[xdhAgreement.getAgreementSize()]; + xdhAgreement.calculateAgreement(xdhPub, ssX, 0); + return ssX; + } + static byte[] computeSharedSecret(byte[] xdhPubBytes, byte[] ssM, byte[] ctX, byte[] ssX) + { SHA3Digest sha3 = new SHA3Digest(256); - - sha3.update(Strings.toByteArray("\\.//^\\"), 0, 6); - sha3.update(k, 0, k.length); - sha3.update(ephXdhPub.getEncoded(), 0, X25519PublicKeyParameters.KEY_SIZE); - sha3.update(((X25519PublicKeyParameters)key.getXDHPublicKey()).getEncoded(), 0, X25519PublicKeyParameters.KEY_SIZE); - - byte[] kemSecret = new byte[32]; - - sha3.doFinal(kemSecret, 0); - - return new SecretWithEncapsulationImpl(kemSecret, Arrays.concatenate(kybSecWithEnc.getEncapsulation(), ephXdhPub.getEncoded())); + sha3.update(ssM, 0, ssM.length); + sha3.update(ssX, 0, ssX.length); + sha3.update(ctX, 0, ctX.length); + sha3.update(xdhPubBytes, 0, xdhPubBytes.length); + sha3.update(XWING_LABEL, 0, XWING_LABEL.length); + + byte[] ss = new byte[32]; + sha3.doFinal(ss, 0); + return ss; } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKeyPairGenerator.java index c0407e6214..694ac2dcfd 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKeyPairGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingKeyPairGenerator.java @@ -5,12 +5,28 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.crypto.digests.SHAKEDigest; import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyPairGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; +import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; +import org.bouncycastle.crypto.params.X25519PublicKeyParameters; +import org.bouncycastle.crypto.prng.FixedSecureRandom; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; +import org.bouncycastle.util.Arrays; +/** + * Generates key pairs compatible with the X-Wing hybrid Key Encapsulation Mechanism (KEM). + *

    + * This class produces key pairs that include both X25519 and ML-KEM-768 components, + * suitable for use in the X-Wing KEM as specified in the IETF draft. + *

    + * + * @see X-Wing KEM Draft + */ public class XWingKeyPairGenerator implements AsymmetricCipherKeyPairGenerator { @@ -22,22 +38,39 @@ private void initialize( this.random = param.getRandom(); } - private AsymmetricCipherKeyPair genKeyPair() + static AsymmetricCipherKeyPair genKeyPair(byte[] seed) { - KyberKeyPairGenerator kyberKeyGen = new KyberKeyPairGenerator(); + // Step 2: Expand seed to 96 bytes using SHAKE256 + SHAKEDigest shake = new SHAKEDigest(256); + shake.update(seed, 0, seed.length); + byte[] expanded = new byte[96]; + shake.doOutput(expanded, 0, expanded.length); - kyberKeyGen.init(new KyberKeyGenerationParameters(random, KyberParameters.kyber768)); + // Step 3: Split expanded bytes + byte[] mlkemSeed = Arrays.copyOfRange(expanded, 0, 64); + byte[] skX = Arrays.copyOfRange(expanded, 64, 96); - X25519KeyPairGenerator x25519KeyGen = new X25519KeyPairGenerator(); + // Step 4a: Generate ML-KEM key pair deterministically + SecureRandom mlkemRandom = new FixedSecureRandom(mlkemSeed); + MLKEMKeyPairGenerator mlkemKeyGen = new MLKEMKeyPairGenerator(); + mlkemKeyGen.init(new MLKEMKeyGenerationParameters(mlkemRandom, MLKEMParameters.ml_kem_768)); + AsymmetricCipherKeyPair mlkemKp = mlkemKeyGen.generateKeyPair(); + MLKEMPublicKeyParameters mlkemPub = (MLKEMPublicKeyParameters)mlkemKp.getPublic(); + MLKEMPrivateKeyParameters mlkemPriv = (MLKEMPrivateKeyParameters)mlkemKp.getPrivate(); - x25519KeyGen.init(new X25519KeyGenerationParameters(random)); - - AsymmetricCipherKeyPair kybKp = kyberKeyGen.generateKeyPair(); - AsymmetricCipherKeyPair xdhKp = x25519KeyGen.generateKeyPair(); + // Step 4b: Generate X25519 key pair deterministically + SecureRandom xdhRandom = new FixedSecureRandom(skX); + X25519KeyPairGenerator xdhKeyGen = new X25519KeyPairGenerator(); + xdhKeyGen.init(new X25519KeyGenerationParameters(xdhRandom)); + AsymmetricCipherKeyPair xdhKp = xdhKeyGen.generateKeyPair(); + X25519PublicKeyParameters xdhPub = (X25519PublicKeyParameters)xdhKp.getPublic(); + X25519PrivateKeyParameters xdhPriv = (X25519PrivateKeyParameters)xdhKp.getPrivate(); + // Step 5: Create X-Wing keys return new AsymmetricCipherKeyPair( - new XWingPublicKeyParameters(kybKp.getPublic(), xdhKp.getPublic()), - new XWingPrivateKeyParameters(kybKp.getPrivate(), xdhKp.getPrivate())); + new XWingPublicKeyParameters(mlkemPub, xdhPub), + new XWingPrivateKeyParameters(seed, mlkemPriv, xdhPriv, mlkemPub, xdhPub) + ); } public void init(KeyGenerationParameters param) @@ -47,7 +80,9 @@ public void init(KeyGenerationParameters param) public AsymmetricCipherKeyPair generateKeyPair() { - return genKeyPair(); + // Step 1: Generate 32-byte random seed + byte[] seed = new byte[32]; + random.nextBytes(seed); + return genKeyPair(seed); } - } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPrivateKeyParameters.java index 0137d5130d..a26020e197 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPrivateKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPrivateKeyParameters.java @@ -1,45 +1,72 @@ package org.bouncycastle.pqc.crypto.xwing; -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; +import org.bouncycastle.crypto.params.X25519PublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.util.Arrays; public class XWingPrivateKeyParameters extends XWingKeyParameters { - private final KyberPrivateKeyParameters kybPriv; - private final X25519PrivateKeyParameters xdhPriv; + private final transient byte[] seed; + private final transient MLKEMPrivateKeyParameters kyberPrivateKey; + private final transient X25519PrivateKeyParameters xdhPrivateKey; + private final transient MLKEMPublicKeyParameters kyberPublicKey; + private final transient X25519PublicKeyParameters xdhPublicKey; - XWingPrivateKeyParameters(AsymmetricKeyParameter kybPriv, AsymmetricKeyParameter xdhPriv) + public XWingPrivateKeyParameters(byte[] seed, + MLKEMPrivateKeyParameters kyberPrivateKey, + X25519PrivateKeyParameters xdhPrivateKey, + MLKEMPublicKeyParameters kyberPublicKey, + X25519PublicKeyParameters xdhPublicKey) { super(true); + this.seed = Arrays.clone(seed); + this.kyberPrivateKey = kyberPrivateKey; + this.xdhPrivateKey = xdhPrivateKey; + this.kyberPublicKey = kyberPublicKey; + this.xdhPublicKey = xdhPublicKey; + } - this.kybPriv = (KyberPrivateKeyParameters)kybPriv; - this.xdhPriv = (X25519PrivateKeyParameters)xdhPriv; + public XWingPrivateKeyParameters(byte[] seed) + { + super(true); + XWingPrivateKeyParameters key = (XWingPrivateKeyParameters)XWingKeyPairGenerator.genKeyPair(seed).getPrivate(); + this.seed = key.seed; + this.kyberPrivateKey = key.kyberPrivateKey; + this.xdhPrivateKey = key.xdhPrivateKey; + this.kyberPublicKey = key.kyberPublicKey; + this.xdhPublicKey = key.xdhPublicKey; } - public XWingPrivateKeyParameters(byte[] encoding) + public byte[] getSeed() { - super(false); + return Arrays.clone(seed); + } - this.kybPriv = new KyberPrivateKeyParameters(KyberParameters.kyber768, Arrays.copyOfRange(encoding, 0, encoding.length - X25519PrivateKeyParameters.KEY_SIZE)); - this.xdhPriv = new X25519PrivateKeyParameters(encoding, encoding.length - X25519PrivateKeyParameters.KEY_SIZE); + MLKEMPrivateKeyParameters getKyberPrivateKey() + { + return kyberPrivateKey; } - KyberPrivateKeyParameters getKyberPrivateKey() + MLKEMPublicKeyParameters getKyberPublicKey() { - return kybPriv; + return kyberPublicKey; } X25519PrivateKeyParameters getXDHPrivateKey() { - return xdhPriv; + return xdhPrivateKey; + } + + X25519PublicKeyParameters getXDHPublicKey() + { + return xdhPublicKey; } public byte[] getEncoded() { - return Arrays.concatenate(kybPriv.getEncoded(), xdhPriv.getEncoded()); + return Arrays.clone(seed); } } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPublicKeyParameters.java index c7d5319d78..d1894564a6 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPublicKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/crypto/xwing/XWingPublicKeyParameters.java @@ -2,21 +2,21 @@ import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.X25519PublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.util.Arrays; public class XWingPublicKeyParameters extends XWingKeyParameters { - private final KyberPublicKeyParameters kybPub; + private final MLKEMPublicKeyParameters kybPub; private final X25519PublicKeyParameters xdhPub; XWingPublicKeyParameters(AsymmetricKeyParameter kybPub, AsymmetricKeyParameter xdhPub) { super(false); - this.kybPub = (KyberPublicKeyParameters)kybPub; + this.kybPub = (MLKEMPublicKeyParameters)kybPub; this.xdhPub = (X25519PublicKeyParameters)xdhPub; } @@ -24,11 +24,11 @@ public XWingPublicKeyParameters(byte[] encoding) { super(false); - this.kybPub = new KyberPublicKeyParameters(KyberParameters.kyber768, Arrays.copyOfRange(encoding, 0, encoding.length - X25519PublicKeyParameters.KEY_SIZE)); + this.kybPub = new MLKEMPublicKeyParameters(MLKEMParameters.ml_kem_768, Arrays.copyOfRange(encoding, 0, encoding.length - X25519PublicKeyParameters.KEY_SIZE)); this.xdhPub = new X25519PublicKeyParameters(encoding, encoding.length - X25519PublicKeyParameters.KEY_SIZE); } - KyberPublicKeyParameters getKyberPublicKey() + MLKEMPublicKeyParameters getKyberPublicKey() { return kybPub; } diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSEngine.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSEngine.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSEngine.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSEngine.java index c0dec946d5..676ac77ab0 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSEngine.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSEngine.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.math.BigInteger; import java.security.SecureRandom; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSEngineProvider.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSEngineProvider.java similarity index 62% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSEngineProvider.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSEngineProvider.java index 8fad283be1..7546096bc1 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSEngineProvider.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSEngineProvider.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; public interface GeMSSEngineProvider { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyGenerationParameters.java similarity index 90% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyGenerationParameters.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyGenerationParameters.java index adfd87efc7..bc7922f5b2 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyGenerationParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyGenerationParameters.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.security.SecureRandom; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyPairGenerator.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyPairGenerator.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyPairGenerator.java index f16272d316..716331e94e 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyPairGenerator.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyPairGenerator.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.security.SecureRandom; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyParameters.java similarity index 89% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyParameters.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyParameters.java index 507d71c39d..211a7fdcc3 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSKeyParameters.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSParameters.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSParameters.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSParameters.java index 4c23af6dcf..3dd7c071de 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSParameters.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSPrivateKeyParameters.java similarity index 89% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSPrivateKeyParameters.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSPrivateKeyParameters.java index c270d897c7..4505d91e79 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSPrivateKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSPrivateKeyParameters.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import org.bouncycastle.util.Arrays; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSPublicKeyParameters.java similarity index 90% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSPublicKeyParameters.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSPublicKeyParameters.java index 9d841bcb66..33b3fb1802 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSPublicKeyParameters.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSPublicKeyParameters.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import org.bouncycastle.util.Arrays; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSSigner.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSSigner.java similarity index 97% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSSigner.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSSigner.java index a84d7f93bf..2c72583bf5 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSSigner.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSSigner.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.security.SecureRandom; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSUtils.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSUtils.java similarity index 97% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSUtils.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSUtils.java index 0af8f7bd32..9c03ed5c71 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/GeMSSUtils.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/GeMSSUtils.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; public class GeMSSUtils { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Mul_GF2x.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Mul_GF2x.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Mul_GF2x.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Mul_GF2x.java index 3f2d1f1671..fa05339512 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Mul_GF2x.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Mul_GF2x.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; abstract class Mul_GF2x { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Pointer.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Pointer.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Pointer.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Pointer.java index 140024c63c..b7184d4b59 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Pointer.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Pointer.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.security.SecureRandom; import java.util.Arrays; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/PointerUnion.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/PointerUnion.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/PointerUnion.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/PointerUnion.java index 02512b0676..a74db502e2 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/PointerUnion.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/PointerUnion.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; import java.security.SecureRandom; diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Rem_GF2n.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Rem_GF2n.java similarity index 99% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Rem_GF2n.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Rem_GF2n.java index 175158a2a9..1b61c3d253 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/Rem_GF2n.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/Rem_GF2n.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; abstract class Rem_GF2n { diff --git a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/SecretKeyHFE.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/SecretKeyHFE.java similarity index 92% rename from core/src/main/java/org/bouncycastle/pqc/crypto/gemss/SecretKeyHFE.java rename to core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/SecretKeyHFE.java index 7b431bea66..8a34aa79f6 100644 --- a/core/src/main/java/org/bouncycastle/pqc/crypto/gemss/SecretKeyHFE.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gemss/SecretKeyHFE.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.gemss; +package org.bouncycastle.pqc.legacy.crypto.gemss; class SecretKeyHFE { diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gmss/GMSSRootSig.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gmss/GMSSRootSig.java index 10eee9f453..e4c81301a5 100644 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gmss/GMSSRootSig.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/gmss/GMSSRootSig.java @@ -414,7 +414,7 @@ else if (test > 0) test--; } if (test == 0) - { // if all hashes done copy result to siganture + { // if all hashes done copy result to signature // array System.arraycopy(privateKeyOTS, 0, sign, counter * mdsize, mdsize); @@ -477,7 +477,7 @@ else if (test > 0) test--; } if (test == 0) - { // if all hashes done copy result to siganture + { // if all hashes done copy result to signature // array System.arraycopy(privateKeyOTS, 0, sign, counter * mdsize, mdsize); @@ -542,7 +542,7 @@ else if (test8 > 0) test8--; } if (test8 == 0) - { // if all hashes done copy result to siganture + { // if all hashes done copy result to signature // array System.arraycopy(privateKeyOTS, 0, sign, counter * mdsize, mdsize); diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceFujisakiCipher.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceFujisakiCipher.java index 8309055ad3..6221f76b88 100644 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceFujisakiCipher.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceFujisakiCipher.java @@ -30,8 +30,6 @@ public class McElieceFujisakiCipher */ public static final String OID = "1.3.6.1.4.1.8301.3.1.3.4.2.1"; - private static final String DEFAULT_PRNG_NAME = "SHA1PRNG"; - private Digest messDigest; private SecureRandom sr; diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceKobaraImaiCipher.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceKobaraImaiCipher.java index 6555410479..ffb1c2dcb8 100644 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceKobaraImaiCipher.java +++ b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/mceliece/McElieceKobaraImaiCipher.java @@ -13,6 +13,8 @@ import org.bouncycastle.pqc.legacy.math.linearalgebra.ByteUtils; import org.bouncycastle.pqc.legacy.math.linearalgebra.GF2Vector; import org.bouncycastle.pqc.legacy.math.linearalgebra.IntegerFunctions; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; /** * This class implements the Kobara/Imai conversion of the McEliecePKCS. This is @@ -23,20 +25,20 @@ public class McElieceKobaraImaiCipher implements MessageEncryptor { + public static byte[] getPublicConstant() + { + return Arrays.clone(PUBLIC_CONSTANT); + } /** * The OID of the algorithm. */ public static final String OID = "1.3.6.1.4.1.8301.3.1.3.4.2.3"; - private static final String DEFAULT_PRNG_NAME = "SHA1PRNG"; - /** * A predetermined public constant. */ - public static final byte[] PUBLIC_CONSTANT = "a predetermined public constant" - .getBytes(); - + private static final byte[] PUBLIC_CONSTANT = Strings.toByteArray("a predetermined public constant"); private Digest messDigest; diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/Layer.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/Layer.java deleted file mode 100644 index 4cc2aed6de..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/Layer.java +++ /dev/null @@ -1,322 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -import java.security.SecureRandom; - -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.GF2Field; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.RainbowUtil; -import org.bouncycastle.util.Arrays; - - -/** - * This class represents a layer of the Rainbow Oil- and Vinegar Map. Each Layer - * consists of oi polynomials with their coefficients, generated at random. - *

    - * To sign a document, we solve a LES (linear equation system) for each layer in - * order to find the oil variables of that layer and to be able to use the - * variables to compute the signature. This functionality is implemented in the - * RainbowSignature-class, by the aid of the private key. - *

    - * Each layer is a part of the private key. - *

    - * More information about the layer can be found in the paper of Jintai Ding, - * Dieter Schmidt: Rainbow, a New Multivariable Polynomial Signature Scheme. - * ACNS 2005: 164-175 (https://dx.doi.org/10.1007/11496137_12) - */ -public class Layer -{ - private int vi; // number of vinegars in this layer - private int viNext; // number of vinegars in next layer - private int oi; // number of oils in this layer - - /* - * k : index of polynomial - * - * i,j : indices of oil and vinegar variables - */ - private short[/* k */][/* i */][/* j */] coeff_alpha; - private short[/* k */][/* i */][/* j */] coeff_beta; - private short[/* k */][/* i */] coeff_gamma; - private short[/* k */] coeff_eta; - - /** - * Constructor - * - * @param vi number of vinegar variables of this layer - * @param viNext number of vinegar variables of next layer. It's the same as - * (num of oils) + (num of vinegars) of this layer. - * @param coeffAlpha alpha-coefficients in the polynomials of this layer - * @param coeffBeta beta-coefficients in the polynomials of this layer - * @param coeffGamma gamma-coefficients in the polynomials of this layer - * @param coeffEta eta-coefficients in the polynomials of this layer - */ - public Layer(byte vi, byte viNext, short[][][] coeffAlpha, - short[][][] coeffBeta, short[][] coeffGamma, short[] coeffEta) - { - this.vi = vi & 0xff; - this.viNext = viNext & 0xff; - this.oi = this.viNext - this.vi; - - // the secret coefficients of all polynomials in this layer - this.coeff_alpha = coeffAlpha; - this.coeff_beta = coeffBeta; - this.coeff_gamma = coeffGamma; - this.coeff_eta = coeffEta; - } - - /** - * This function generates the coefficients of all polynomials in this layer - * at random using random generator. - * - * @param sr the random generator which is to be used - */ - public Layer(int vi, int viNext, SecureRandom sr) - { - this.vi = vi; - this.viNext = viNext; - this.oi = viNext - vi; - - // the coefficients of all polynomials in this layer - this.coeff_alpha = new short[this.oi][this.oi][this.vi]; - this.coeff_beta = new short[this.oi][this.vi][this.vi]; - this.coeff_gamma = new short[this.oi][this.viNext]; - this.coeff_eta = new short[this.oi]; - - int numOfPoly = this.oi; // number of polynomials per layer - - // Alpha coeffs - for (int k = 0; k < numOfPoly; k++) - { - for (int i = 0; i < this.oi; i++) - { - for (int j = 0; j < this.vi; j++) - { - coeff_alpha[k][i][j] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - } - // Beta coeffs - for (int k = 0; k < numOfPoly; k++) - { - for (int i = 0; i < this.vi; i++) - { - for (int j = 0; j < this.vi; j++) - { - coeff_beta[k][i][j] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - } - // Gamma coeffs - for (int k = 0; k < numOfPoly; k++) - { - for (int i = 0; i < this.viNext; i++) - { - coeff_gamma[k][i] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - // Eta - for (int k = 0; k < numOfPoly; k++) - { - coeff_eta[k] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - - /** - * This method plugs in the vinegar variables into the polynomials of this - * layer and computes the coefficients of the Oil-variables as well as the - * free coefficient in each polynomial. - *

    - * It is needed for computing the Oil variables while signing. - * - * @param x vinegar variables of this layer that should be plugged into - * the polynomials. - * @return coeff the coefficients of Oil variables and the free coeff in the - * polynomials of this layer. - */ - public short[][] plugInVinegars(short[] x) - { - // temporary variable needed for the multiplication - short tmpMult = 0; - // coeff: 1st index = which polynomial, 2nd index=which variable - short[][] coeff = new short[oi][oi + 1]; // gets returned - // free coefficient per polynomial - short[] sum = new short[oi]; - - /* - * evaluate the beta-part of the polynomials (it contains no oil - * variables) - */ - for (int k = 0; k < oi; k++) - { - for (int i = 0; i < vi; i++) - { - for (int j = 0; j < vi; j++) - { - // tmp = beta * xi (plug in) - tmpMult = GF2Field.multElem(coeff_beta[k][i][j], x[i]); - // tmp = tmp * xj - tmpMult = GF2Field.multElem(tmpMult, x[j]); - // accumulate into the array for the free coefficients. - sum[k] = GF2Field.addElem(sum[k], tmpMult); - } - } - } - - /* evaluate the alpha-part (it contains oils) */ - for (int k = 0; k < oi; k++) - { - for (int i = 0; i < oi; i++) - { - for (int j = 0; j < vi; j++) - { - // alpha * xj (plug in) - tmpMult = GF2Field.multElem(coeff_alpha[k][i][j], x[j]); - // accumulate - coeff[k][i] = GF2Field.addElem(coeff[k][i], tmpMult); - } - } - } - /* evaluate the gama-part of the polynomial (containing no oils) */ - for (int k = 0; k < oi; k++) - { - for (int i = 0; i < vi; i++) - { - // gamma * xi (plug in) - tmpMult = GF2Field.multElem(coeff_gamma[k][i], x[i]); - // accumulate in the array for the free coefficients (per - // polynomial). - sum[k] = GF2Field.addElem(sum[k], tmpMult); - } - } - /* evaluate the gama-part of the polynomial (but containing oils) */ - for (int k = 0; k < oi; k++) - { - for (int i = vi; i < viNext; i++) - { // oils - // accumulate the coefficients of the oil variables (per - // polynomial). - coeff[k][i - vi] = GF2Field.addElem(coeff_gamma[k][i], - coeff[k][i - vi]); - } - } - /* evaluate the eta-part of the polynomial */ - for (int k = 0; k < oi; k++) - { - // accumulate in the array for the free coefficients per polynomial. - sum[k] = GF2Field.addElem(sum[k], coeff_eta[k]); - } - - /* put the free coefficients (sum) into the coeff-array as last column */ - for (int k = 0; k < oi; k++) - { - coeff[k][oi] = sum[k]; - } - return coeff; - } - - /** - * Getter for the number of vinegar variables of this layer. - * - * @return the number of vinegar variables of this layer. - */ - public int getVi() - { - return vi; - } - - /** - * Getter for the number of vinegar variables of the next layer. - * - * @return the number of vinegar variables of the next layer. - */ - public int getViNext() - { - return viNext; - } - - /** - * Getter for the number of Oil variables of this layer. - * - * @return the number of oil variables of this layer. - */ - public int getOi() - { - return oi; - } - - /** - * Getter for the alpha-coefficients of the polynomials in this layer. - * - * @return the coefficients of alpha-terms of this layer. - */ - public short[][][] getCoeffAlpha() - { - return coeff_alpha; - } - - /** - * Getter for the beta-coefficients of the polynomials in this layer. - * - * @return the coefficients of beta-terms of this layer. - */ - - public short[][][] getCoeffBeta() - { - return coeff_beta; - } - - /** - * Getter for the gamma-coefficients of the polynomials in this layer. - * - * @return the coefficients of gamma-terms of this layer - */ - public short[][] getCoeffGamma() - { - return coeff_gamma; - } - - /** - * Getter for the eta-coefficients of the polynomials in this layer. - * - * @return the coefficients eta of this layer - */ - public short[] getCoeffEta() - { - return coeff_eta; - } - - /** - * This function compares this Layer with another object. - * - * @param other the other object - * @return the result of the comparison - */ - public boolean equals(Object other) - { - if (other == null || !(other instanceof Layer)) - { - return false; - } - Layer otherLayer = (Layer)other; - - return vi == otherLayer.getVi() - && viNext == otherLayer.getViNext() - && oi == otherLayer.getOi() - && RainbowUtil.equals(coeff_alpha, otherLayer.getCoeffAlpha()) - && RainbowUtil.equals(coeff_beta, otherLayer.getCoeffBeta()) - && RainbowUtil.equals(coeff_gamma, otherLayer.getCoeffGamma()) - && RainbowUtil.equals(coeff_eta, otherLayer.getCoeffEta()); - } - - public int hashCode() - { - int hash = vi; - hash = hash * 37 + viNext; - hash = hash * 37 + oi; - hash = hash * 37 + Arrays.hashCode(coeff_alpha); - hash = hash * 37 + Arrays.hashCode(coeff_beta); - hash = hash * 37 + Arrays.hashCode(coeff_gamma); - hash = hash * 37 + Arrays.hashCode(coeff_eta); - - return hash; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyGenerationParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyGenerationParameters.java deleted file mode 100644 index 6fac377c1f..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyGenerationParameters.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.KeyGenerationParameters; - -public class RainbowKeyGenerationParameters - extends KeyGenerationParameters -{ - private RainbowParameters params; - - public RainbowKeyGenerationParameters( - SecureRandom random, - RainbowParameters params) - { - // TODO: key size? - super(random, params.getVi()[params.getVi().length - 1] - params.getVi()[0]); - this.params = params; - } - - public RainbowParameters getParameters() - { - return params; - } -} - diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyPairGenerator.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyPairGenerator.java deleted file mode 100644 index b936c4b528..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyPairGenerator.java +++ /dev/null @@ -1,418 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.KeyGenerationParameters; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.ComputeInField; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.GF2Field; - -/** - * This class implements AsymmetricCipherKeyPairGenerator. It is used - * as a generator for the private and public key of the Rainbow Signature - * Scheme. - *

    - * Detailed information about the key generation is to be found in the paper of - * Jintai Ding, Dieter Schmidt: Rainbow, a New Multivariable Polynomial - * Signature Scheme. ACNS 2005: 164-175 (https://dx.doi.org/10.1007/11496137_12) - */ -public class RainbowKeyPairGenerator - implements AsymmetricCipherKeyPairGenerator -{ - private boolean initialized = false; - private SecureRandom sr; - private RainbowKeyGenerationParameters rainbowParams; - - /* linear affine map L1: */ - private short[][] A1; // matrix of the lin. affine map L1(n-v1 x n-v1 matrix) - private short[][] A1inv; // inverted A1 - private short[] b1; // translation element of the lin.affine map L1 - - /* linear affine map L2: */ - private short[][] A2; // matrix of the lin. affine map (n x n matrix) - private short[][] A2inv; // inverted A2 - private short[] b2; // translation elemt of the lin.affine map L2 - - /* components of F: */ - private int numOfLayers; // u (number of sets S) - private Layer layers[]; // layers of polynomials of F - private int[] vi; // set of vinegar vars per layer. - - /* components of Public Key */ - private short[][] pub_quadratic; // quadratic(mixed) coefficients - private short[][] pub_singular; // singular coefficients - private short[] pub_scalar; // scalars - - // TODO - - /** - * The standard constructor tries to generate the Rainbow algorithm identifier - * with the corresponding OID. - */ - public RainbowKeyPairGenerator() - { - } - - - /** - * This function generates a Rainbow key pair. - * - * @return the generated key pair - */ - public AsymmetricCipherKeyPair genKeyPair() - { - RainbowPrivateKeyParameters privKey; - RainbowPublicKeyParameters pubKey; - - if (!initialized) - { - initializeDefault(); - } - - /* choose all coefficients at random */ - keygen(); - - /* now marshall them to PrivateKey */ - privKey = new RainbowPrivateKeyParameters(A1inv, b1, A2inv, b2, vi, layers); - - - /* marshall to PublicKey */ - pubKey = new RainbowPublicKeyParameters(vi[vi.length - 1] - vi[0], pub_quadratic, pub_singular, pub_scalar); - - return new AsymmetricCipherKeyPair(pubKey, privKey); - } - - // TODO - public void initialize( - KeyGenerationParameters param) - { - this.rainbowParams = (RainbowKeyGenerationParameters)param; - - // set source of randomness - this.sr = rainbowParams.getRandom(); - - // unmarshalling: - this.vi = this.rainbowParams.getParameters().getVi(); - this.numOfLayers = this.rainbowParams.getParameters().getNumOfLayers(); - - this.initialized = true; - } - - private void initializeDefault() - { - RainbowKeyGenerationParameters rbKGParams = new RainbowKeyGenerationParameters(CryptoServicesRegistrar.getSecureRandom(), new RainbowParameters()); - initialize(rbKGParams); - } - - /** - * This function calls the functions for the random generation of the coefficients - * and the matrices needed for the private key and the method for computing the public key. - */ - private void keygen() - { - generateL1(); - generateL2(); - generateF(); - computePublicKey(); - } - - /** - * This function generates the invertible affine linear map L1 = A1*x + b1 - *

    - * The translation part b1, is stored in a separate array. The inverse of - * the matrix-part of L1 A1inv is also computed here. - *

    - * This linear map hides the output of the map F. It is on k^(n-v1). - *

    - */ - private void generateL1() - { - - // dimension = n-v1 = vi[last] - vi[first] - int dim = vi[vi.length - 1] - vi[0]; - this.A1 = new short[dim][dim]; - this.A1inv = null; - ComputeInField c = new ComputeInField(); - - /* generation of A1 at random */ - while (A1inv == null) - { - for (int i = 0; i < dim; i++) - { - for (int j = 0; j < dim; j++) - { - A1[i][j] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - A1inv = c.inverse(A1); - } - - /* generation of the translation vector at random */ - b1 = new short[dim]; - for (int i = 0; i < dim; i++) - { - b1[i] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - - /** - * This function generates the invertible affine linear map L2 = A2*x + b2 - *

    - * The translation part b2, is stored in a separate array. The inverse of - * the matrix-part of L2 A2inv is also computed here. - *

    - * This linear map hides the output of the map F. It is on k^(n). - *

    - */ - private void generateL2() - { - - // dimension = n = vi[last] - int dim = vi[vi.length - 1]; - this.A2 = new short[dim][dim]; - this.A2inv = null; - ComputeInField c = new ComputeInField(); - - /* generation of A2 at random */ - while (this.A2inv == null) - { - for (int i = 0; i < dim; i++) - { - for (int j = 0; j < dim; j++) - { // one col extra for b - A2[i][j] = (short)(sr.nextInt() & GF2Field.MASK); - } - } - this.A2inv = c.inverse(A2); - } - /* generation of the translation vector at random */ - b2 = new short[dim]; - for (int i = 0; i < dim; i++) - { - b2[i] = (short)(sr.nextInt() & GF2Field.MASK); - } - - } - - /** - * This function generates the private map F, which consists of u-1 layers. - * Each layer consists of oi polynomials where oi = vi[i+1]-vi[i]. - *

    - * The methods for the generation of the coefficients of these polynomials - * are called here. - *

    - */ - private void generateF() - { - - this.layers = new Layer[this.numOfLayers]; - for (int i = 0; i < this.numOfLayers; i++) - { - layers[i] = new Layer(this.vi[i], this.vi[i + 1], sr); - } - } - - /** - * This function computes the public key from the private key. - *

    - * The composition of F with L2 is computed, followed by applying L1 to the - * composition's result. The singular and scalar values constitute to the - * public key as is, the quadratic terms are compacted in - * compactPublicKey() - *

    - */ - private void computePublicKey() - { - - ComputeInField c = new ComputeInField(); - int rows = this.vi[this.vi.length - 1] - this.vi[0]; - int vars = this.vi[this.vi.length - 1]; - // Fpub - short[][][] coeff_quadratic_3dim = new short[rows][vars][vars]; - this.pub_singular = new short[rows][vars]; - this.pub_scalar = new short[rows]; - - // Coefficients of layers of Private Key F - short[][][] coeff_alpha; - short[][][] coeff_beta; - short[][] coeff_gamma; - short[] coeff_eta; - - // Needed for counters; - int oils = 0; - int vins = 0; - int crnt_row = 0; // current row (polynomial) - - short vect_tmp[] = new short[vars]; // vector tmp; - short sclr_tmp = 0; - - // Composition of F and L2: Insert L2 = A2*x+b2 in F - for (int l = 0; l < this.layers.length; l++) - { - // get coefficients of current layer - coeff_alpha = this.layers[l].getCoeffAlpha(); - coeff_beta = this.layers[l].getCoeffBeta(); - coeff_gamma = this.layers[l].getCoeffGamma(); - coeff_eta = this.layers[l].getCoeffEta(); - oils = coeff_alpha[0].length;// this.layers[l].getOi(); - vins = coeff_beta[0].length;// this.layers[l].getVi(); - // compute polynomials of layer - for (int p = 0; p < oils; p++) - { - // multiply alphas - for (int x1 = 0; x1 < oils; x1++) - { - for (int x2 = 0; x2 < vins; x2++) - { - // multiply polynomial1 with polynomial2 - vect_tmp = c.multVect(coeff_alpha[p][x1][x2], - this.A2[x1 + vins]); - coeff_quadratic_3dim[crnt_row + p] = c.addSquareMatrix( - coeff_quadratic_3dim[crnt_row + p], c - .multVects(vect_tmp, this.A2[x2])); - // mul poly1 with scalar2 - vect_tmp = c.multVect(this.b2[x2], vect_tmp); - this.pub_singular[crnt_row + p] = c.addVect(vect_tmp, - this.pub_singular[crnt_row + p]); - // mul scalar1 with poly2 - vect_tmp = c.multVect(coeff_alpha[p][x1][x2], - this.A2[x2]); - vect_tmp = c.multVect(b2[x1 + vins], vect_tmp); - this.pub_singular[crnt_row + p] = c.addVect(vect_tmp, - this.pub_singular[crnt_row + p]); - // mul scalar1 with scalar2 - sclr_tmp = GF2Field.multElem(coeff_alpha[p][x1][x2], - this.b2[x1 + vins]); - this.pub_scalar[crnt_row + p] = GF2Field.addElem( - this.pub_scalar[crnt_row + p], GF2Field - .multElem(sclr_tmp, this.b2[x2])); - } - } - // multiply betas - for (int x1 = 0; x1 < vins; x1++) - { - for (int x2 = 0; x2 < vins; x2++) - { - // multiply polynomial1 with polynomial2 - vect_tmp = c.multVect(coeff_beta[p][x1][x2], - this.A2[x1]); - coeff_quadratic_3dim[crnt_row + p] = c.addSquareMatrix( - coeff_quadratic_3dim[crnt_row + p], c - .multVects(vect_tmp, this.A2[x2])); - // mul poly1 with scalar2 - vect_tmp = c.multVect(this.b2[x2], vect_tmp); - this.pub_singular[crnt_row + p] = c.addVect(vect_tmp, - this.pub_singular[crnt_row + p]); - // mul scalar1 with poly2 - vect_tmp = c.multVect(coeff_beta[p][x1][x2], - this.A2[x2]); - vect_tmp = c.multVect(this.b2[x1], vect_tmp); - this.pub_singular[crnt_row + p] = c.addVect(vect_tmp, - this.pub_singular[crnt_row + p]); - // mul scalar1 with scalar2 - sclr_tmp = GF2Field.multElem(coeff_beta[p][x1][x2], - this.b2[x1]); - this.pub_scalar[crnt_row + p] = GF2Field.addElem( - this.pub_scalar[crnt_row + p], GF2Field - .multElem(sclr_tmp, this.b2[x2])); - } - } - // multiply gammas - for (int n = 0; n < vins + oils; n++) - { - // mul poly with scalar - vect_tmp = c.multVect(coeff_gamma[p][n], this.A2[n]); - this.pub_singular[crnt_row + p] = c.addVect(vect_tmp, - this.pub_singular[crnt_row + p]); - // mul scalar with scalar - this.pub_scalar[crnt_row + p] = GF2Field.addElem( - this.pub_scalar[crnt_row + p], GF2Field.multElem( - coeff_gamma[p][n], this.b2[n])); - } - // add eta - this.pub_scalar[crnt_row + p] = GF2Field.addElem( - this.pub_scalar[crnt_row + p], coeff_eta[p]); - } - crnt_row = crnt_row + oils; - } - - // Apply L1 = A1*x+b1 to composition of F and L2 - { - // temporary coefficient arrays - short[][][] tmp_c_quad = new short[rows][vars][vars]; - short[][] tmp_c_sing = new short[rows][vars]; - short[] tmp_c_scal = new short[rows]; - for (int r = 0; r < rows; r++) - { - for (int q = 0; q < A1.length; q++) - { - tmp_c_quad[r] = c.addSquareMatrix(tmp_c_quad[r], c - .multMatrix(A1[r][q], coeff_quadratic_3dim[q])); - tmp_c_sing[r] = c.addVect(tmp_c_sing[r], c.multVect( - A1[r][q], this.pub_singular[q])); - tmp_c_scal[r] = GF2Field.addElem(tmp_c_scal[r], GF2Field - .multElem(A1[r][q], this.pub_scalar[q])); - } - tmp_c_scal[r] = GF2Field.addElem(tmp_c_scal[r], b1[r]); - } - // set public key - coeff_quadratic_3dim = tmp_c_quad; - this.pub_singular = tmp_c_sing; - this.pub_scalar = tmp_c_scal; - } - compactPublicKey(coeff_quadratic_3dim); - } - - /** - * The quadratic (or mixed) terms of the public key are compacted from a n x - * n matrix per polynomial to an upper diagonal matrix stored in one integer - * array of n (n + 1) / 2 elements per polynomial. The ordering of elements - * is lexicographic and the result is updating this.pub_quadratic, - * which stores the quadratic elements of the public key. - * - * @param coeff_quadratic_to_compact 3-dimensional array containing a n x n Matrix for each of the - * n - v1 polynomials - */ - private void compactPublicKey(short[][][] coeff_quadratic_to_compact) - { - int polynomials = coeff_quadratic_to_compact.length; - int n = coeff_quadratic_to_compact[0].length; - int entries = n * (n + 1) / 2;// the small gauss - this.pub_quadratic = new short[polynomials][entries]; - int offset = 0; - - for (int p = 0; p < polynomials; p++) - { - offset = 0; - for (int x = 0; x < n; x++) - { - for (int y = x; y < n; y++) - { - if (y == x) - { - this.pub_quadratic[p][offset] = coeff_quadratic_to_compact[p][x][y]; - } - else - { - this.pub_quadratic[p][offset] = GF2Field.addElem( - coeff_quadratic_to_compact[p][x][y], - coeff_quadratic_to_compact[p][y][x]); - } - offset++; - } - } - } - } - - public void init(KeyGenerationParameters param) - { - this.initialize(param); - } - - public AsymmetricCipherKeyPair generateKeyPair() - { - return genKeyPair(); - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyParameters.java deleted file mode 100644 index 5e164fa41b..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowKeyParameters.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; - -public class RainbowKeyParameters - extends AsymmetricKeyParameter -{ - private int docLength; - - public RainbowKeyParameters( - boolean isPrivate, - int docLength) - { - super(isPrivate); - this.docLength = docLength; - } - - /** - * @return the docLength - */ - public int getDocLength() - { - return this.docLength; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowParameters.java deleted file mode 100644 index 3872ded350..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowParameters.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -import org.bouncycastle.crypto.CipherParameters; - -public class RainbowParameters - implements CipherParameters -{ - - /** - * DEFAULT PARAMS - */ - /* - * Vi = vinegars per layer whereas n is vu (vu = 33 = n) such that - * - * v1 = 6; o1 = 12-6 = 6 - * - * v2 = 12; o2 = 17-12 = 5 - * - * v3 = 17; o3 = 22-17 = 5 - * - * v4 = 22; o4 = 33-22 = 11 - * - * v5 = 33; (o5 = 0) - */ - private final int[] DEFAULT_VI = {6, 12, 17, 22, 33}; - - private int[] vi;// set of vinegar vars per layer. - - /** - * Default Constructor The elements of the array containing the number of - * Vinegar variables in each layer are set to the default values here. - */ - public RainbowParameters() - { - this.vi = this.DEFAULT_VI; - } - - /** - * Constructor with parameters - * - * @param vi The elements of the array containing the number of Vinegar - * variables per layer are set to the values of the input array. - */ - public RainbowParameters(int[] vi) - { - this.vi = vi; - - checkParams(); - } - - private void checkParams() - { - if (vi == null) - { - throw new IllegalArgumentException("no layers defined."); - } - if (vi.length > 1) - { - for (int i = 0; i < vi.length - 1; i++) - { - if (vi[i] >= vi[i + 1]) - { - throw new IllegalArgumentException( - "v[i] has to be smaller than v[i+1]"); - } - } - } - else - { - throw new IllegalArgumentException( - "Rainbow needs at least 1 layer, such that v1 < v2."); - } - } - - /** - * Getter for the number of layers - * - * @return the number of layers - */ - public int getNumOfLayers() - { - return this.vi.length - 1; - } - - /** - * Getter for the number of all the polynomials in Rainbow - * - * @return the number of the polynomials - */ - public int getDocLength() - { - return vi[vi.length - 1] - vi[0]; - } - - /** - * Getter for the array containing the number of Vinegar-variables per layer - * - * @return the numbers of vinegars per layer - */ - public int[] getVi() - { - return this.vi; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowPrivateKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowPrivateKeyParameters.java deleted file mode 100644 index 90d4b3459f..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowPrivateKeyParameters.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -public class RainbowPrivateKeyParameters - extends RainbowKeyParameters -{ - /** - * Constructor - * - * @param A1inv the inverse of A1(the matrix part of the affine linear map L1) - * (n-v1 x n-v1 matrix) - * @param b1 translation vector, part of the linear affine map L1 - * @param A2inv the inverse of A2(the matrix part of the affine linear map L2) - * (n x n matrix) - * @param b2 translation vector, part of the linear affine map L2 - * @param vi the number of Vinegar-variables per layer - * @param layers the polynomials with their coefficients of private map F - */ - public RainbowPrivateKeyParameters(short[][] A1inv, short[] b1, - short[][] A2inv, short[] b2, int[] vi, Layer[] layers) - { - super(true, vi[vi.length - 1] - vi[0]); - - this.A1inv = A1inv; - this.b1 = b1; - this.A2inv = A2inv; - this.b2 = b2; - this.vi = vi; - this.layers = layers; - } - - /* - * invertible affine linear map L1 - */ - // the inverse of A1, (n-v1 x n-v1 matrix) - private short[][] A1inv; - - // translation vector of L1 - private short[] b1; - - /* - * invertible affine linear map L2 - */ - // the inverse of A2, (n x n matrix) - private short[][] A2inv; - - // translation vector of L2 - private short[] b2; - - /* - * components of F - */ - // the number of Vinegar-variables per layer. - private int[] vi; - - // contains the polynomials with their coefficients of private map F - private Layer[] layers; - - /** - * Getter for the translation part of the private quadratic map L1. - * - * @return b1 the translation part of L1 - */ - public short[] getB1() - { - return this.b1; - } - - /** - * Getter for the inverse matrix of A1. - * - * @return the A1inv inverse - */ - public short[][] getInvA1() - { - return this.A1inv; - } - - /** - * Getter for the translation part of the private quadratic map L2. - * - * @return b2 the translation part of L2 - */ - public short[] getB2() - { - return this.b2; - } - - /** - * Getter for the inverse matrix of A2 - * - * @return the A2inv - */ - public short[][] getInvA2() - { - return this.A2inv; - } - - /** - * Returns the layers contained in the private key - * - * @return layers - */ - public Layer[] getLayers() - { - return this.layers; - } - - /** - * /** Returns the array of vi-s - * - * @return the vi - */ - public int[] getVi() - { - return vi; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowPublicKeyParameters.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowPublicKeyParameters.java deleted file mode 100644 index baff2225f7..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowPublicKeyParameters.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -public class RainbowPublicKeyParameters - extends RainbowKeyParameters -{ - private short[][] coeffquadratic; - private short[][] coeffsingular; - private short[] coeffscalar; - - /** - * Constructor - * - * @param docLength - * @param coeffQuadratic - * @param coeffSingular - * @param coeffScalar - */ - public RainbowPublicKeyParameters(int docLength, - short[][] coeffQuadratic, short[][] coeffSingular, - short[] coeffScalar) - { - super(false, docLength); - - this.coeffquadratic = coeffQuadratic; - this.coeffsingular = coeffSingular; - this.coeffscalar = coeffScalar; - - } - - /** - * @return the coeffquadratic - */ - public short[][] getCoeffQuadratic() - { - return coeffquadratic; - } - - /** - * @return the coeffsingular - */ - public short[][] getCoeffSingular() - { - return coeffsingular; - } - - /** - * @return the coeffscalar - */ - public short[] getCoeffScalar() - { - return coeffscalar; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowSigner.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowSigner.java deleted file mode 100644 index 05e522503b..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/RainbowSigner.java +++ /dev/null @@ -1,311 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow; - -import java.security.SecureRandom; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.pqc.crypto.MessageSigner; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.ComputeInField; -import org.bouncycastle.pqc.legacy.crypto.rainbow.util.GF2Field; - -/** - * It implements the sign and verify functions for the Rainbow Signature Scheme. - * Here the message, which has to be signed, is updated. The use of - * different hash functions is possible. - *

    - * Detailed information about the signature and the verify-method is to be found - * in the paper of Jintai Ding, Dieter Schmidt: Rainbow, a New Multivariable - * Polynomial Signature Scheme. ACNS 2005: 164-175 - * (https://dx.doi.org/10.1007/11496137_12) - */ -public class RainbowSigner - implements MessageSigner -{ - private static final int MAXITS = 65536; - - // Source of randomness - private SecureRandom random; - - // The length of a document that can be signed with the privKey - int signableDocumentLength; - - // Container for the oil and vinegar variables of all the layers - private short[] x; - - private ComputeInField cf = new ComputeInField(); - - RainbowKeyParameters key; - - public void init(boolean forSigning, - CipherParameters param) - { - if (forSigning) - { - if (param instanceof ParametersWithRandom) - { - ParametersWithRandom rParam = (ParametersWithRandom)param; - - this.random = rParam.getRandom(); - this.key = (RainbowPrivateKeyParameters)rParam.getParameters(); - - } - else - { - - this.random = CryptoServicesRegistrar.getSecureRandom(); - this.key = (RainbowPrivateKeyParameters)param; - } - } - else - { - this.key = (RainbowPublicKeyParameters)param; - } - - this.signableDocumentLength = this.key.getDocLength(); - } - - - /** - * initial operations before solving the Linear equation system. - * - * @param layer the current layer for which a LES is to be solved. - * @param msg the message that should be signed. - * @return Y_ the modified document needed for solving LES, (Y_ = - * A1^{-1}*(Y-b1)) linear map L1 = A1 x + b1. - */ - private short[] initSign(Layer[] layer, short[] msg) - { - - /* preparation: Modifies the document with the inverse of L1 */ - // tmp = Y - b1: - short[] tmpVec = new short[msg.length]; - - tmpVec = cf.addVect(((RainbowPrivateKeyParameters)this.key).getB1(), msg); - - // Y_ = A1^{-1} * (Y - b1) : - short[] Y_ = cf.multiplyMatrix(((RainbowPrivateKeyParameters)this.key).getInvA1(), tmpVec); - - /* generates the vinegar vars of the first layer at random */ - for (int i = 0; i < layer[0].getVi(); i++) - { - x[i] = (short)random.nextInt(); - x[i] = (short)(x[i] & GF2Field.MASK); - } - - return Y_; - } - - /** - * This function signs the message that has been updated, making use of the - * private key. - *

    - * For computing the signature, L1 and L2 are needed, as well as LES should - * be solved for each layer in order to find the Oil-variables in the layer. - *

    - * The Vinegar-variables of the first layer are random generated. - * - * @param message the message - * @return the signature of the message. - */ - public byte[] generateSignature(byte[] message) - { - Layer[] layer = ((RainbowPrivateKeyParameters)this.key).getLayers(); - int numberOfLayers = layer.length; - - x = new short[((RainbowPrivateKeyParameters)this.key).getInvA2().length]; // all variables - - short[] Y_; // modified document - short[] y_i; // part of Y_ each polynomial - int counter; // index of the current part of the doc - - short[] solVec; // the solution of LES pro layer - short[] tmpVec; - - // the signature as an array of shorts: - short[] signature; - // the signature as a byte-array: - byte[] S = new byte[layer[numberOfLayers - 1].getViNext()]; - - short[] msgHashVals = makeMessageRepresentative(message); - int itCount = 0; - - // shows if an exception is caught - boolean ok; - do - { - ok = true; - counter = 0; - try - { - Y_ = initSign(layer, msgHashVals); - - for (int i = 0; i < numberOfLayers; i++) - { - - y_i = new short[layer[i].getOi()]; - solVec = new short[layer[i].getOi()]; // solution of LES - - /* copy oi elements of Y_ into y_i */ - for (int k = 0; k < layer[i].getOi(); k++) - { - y_i[k] = Y_[counter]; - counter++; // current index of Y_ - } - - /* - * plug in the vars of the previous layer in order to get - * the vars of the current layer - */ - solVec = cf.solveEquation(layer[i].plugInVinegars(x), y_i); - - if (solVec == null) - { // LES is not solveable - throw new Exception("LES is not solveable!"); - } - - /* copy the new vars into the x-array */ - for (int j = 0; j < solVec.length; j++) - { - x[layer[i].getVi() + j] = solVec[j]; - } - } - - /* apply the inverse of L2: (signature = A2^{-1}*(b2+x)) */ - tmpVec = cf.addVect(((RainbowPrivateKeyParameters)this.key).getB2(), x); - signature = cf.multiplyMatrix(((RainbowPrivateKeyParameters)this.key).getInvA2(), tmpVec); - - /* cast signature from short[] to byte[] */ - for (int i = 0; i < S.length; i++) - { - S[i] = ((byte)signature[i]); - } - } - catch (Exception se) - { - // if one of the LESs was not solveable - sign again - ok = false; - } - } - while (!ok && ++itCount < MAXITS); - /* return the signature in bytes */ - - if (itCount == MAXITS) - { - throw new IllegalStateException("unable to generate signature - LES not solvable"); - } - - return S; - } - - /** - * This function verifies the signature of the message that has been - * updated, with the aid of the public key. - * - * @param message the message - * @param signature the signature of the message - * @return true if the signature has been verified, false otherwise. - */ - public boolean verifySignature(byte[] message, byte[] signature) - { - short[] sigInt = new short[signature.length]; - short tmp; - - for (int i = 0; i < signature.length; i++) - { - tmp = (short)signature[i]; - tmp &= (short)0xff; - sigInt[i] = tmp; - } - - short[] msgHashVal = makeMessageRepresentative(message); - - // verify - short[] verificationResult = verifySignatureIntern(sigInt); - - // compare - boolean verified = true; - if (msgHashVal.length != verificationResult.length) - { - return false; - } - for (int i = 0; i < msgHashVal.length; i++) - { - verified = verified && msgHashVal[i] == verificationResult[i]; - } - - return verified; - } - - /** - * Signature verification using public key - * - * @param signature vector of dimension n - * @return document hash of length n - v1 - */ - private short[] verifySignatureIntern(short[] signature) - { - - short[][] coeff_quadratic = ((RainbowPublicKeyParameters)this.key).getCoeffQuadratic(); - short[][] coeff_singular = ((RainbowPublicKeyParameters)this.key).getCoeffSingular(); - short[] coeff_scalar = ((RainbowPublicKeyParameters)this.key).getCoeffScalar(); - - short[] rslt = new short[coeff_quadratic.length];// n - v1 - int n = coeff_singular[0].length; - int offset = 0; // array position - short tmp = 0; // for scalar - - for (int p = 0; p < coeff_quadratic.length; p++) - { // no of polynomials - offset = 0; - for (int x = 0; x < n; x++) - { - // calculate quadratic terms - for (int y = x; y < n; y++) - { - tmp = GF2Field.multElem(coeff_quadratic[p][offset], - GF2Field.multElem(signature[x], signature[y])); - rslt[p] = GF2Field.addElem(rslt[p], tmp); - offset++; - } - // calculate singular terms - tmp = GF2Field.multElem(coeff_singular[p][x], signature[x]); - rslt[p] = GF2Field.addElem(rslt[p], tmp); - } - // add scalar - rslt[p] = GF2Field.addElem(rslt[p], coeff_scalar[p]); - } - - return rslt; - } - - /** - * This function creates the representative of the message which gets signed - * or verified. - * - * @param message the message - * @return message representative - */ - private short[] makeMessageRepresentative(byte[] message) - { - // the message representative - short[] output = new short[this.signableDocumentLength]; - - int h = 0; - int i = 0; - do - { - if (i >= message.length) - { - break; - } - output[i] = (short)message[h]; - output[i] &= (short)0xff; - h++; - i++; - } - while (i < output.length); - - return output; - } -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/ComputeInField.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/ComputeInField.java deleted file mode 100644 index 181a6c4967..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/ComputeInField.java +++ /dev/null @@ -1,493 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow.util; - -/** - * This class offers different operations on matrices in field GF2^8. - *

    - * Implemented are functions: - * - finding inverse of a matrix - * - solving linear equation systems using the Gauss-Elimination method - * - basic operations like matrix multiplication, addition and so on. - */ - -public class ComputeInField -{ - - private short[][] A; // used by solveEquation and inverse - short[] x; - - /** - * Constructor with no parameters - */ - public ComputeInField() - { - } - - - /** - * This function finds a solution of the equation Bx = b. - * Exception is thrown if the linear equation system has no solution - * - * @param B this matrix is the left part of the - * equation (B in the equation above) - * @param b the right part of the equation - * (b in the equation above) - * @return x the solution of the equation if it is solvable - * null otherwise - * @throws RuntimeException if LES is not solvable - */ - public short[] solveEquation(short[][] B, short[] b) - { - if (B.length != b.length) - { - return null; // not solvable in this form - } - - try - { - - - // initialize - // this matrix stores B and b from the equation B*x = b - // b is stored as the last column. - // B contains one column more than rows. - // In this column we store a free coefficient that should be later subtracted from b - A = new short[B.length][B.length + 1]; - // stores the solution of the LES - x = new short[B.length]; - - // copy B into the global matrix A - for (int i = 0; i < B.length; i++) - { // rows - for (int j = 0; j < B[0].length; j++) - { // cols - A[i][j] = B[i][j]; - } - } - - // copy the vector b into the global A - //the free coefficient, stored in the last column of A( A[i][b.length] - // is to be subtracted from b - for (int i = 0; i < b.length; i++) - { - A[i][b.length] = GF2Field.addElem(b[i], A[i][b.length]); - } - - // call the methods for gauss elimination and backward substitution - computeZerosUnder(false); // obtain zeros under the diagonal - substitute(); - - return x; - - } - catch (RuntimeException rte) - { - return null; // the LES is not solvable! - } - } - - /** - * This function computes the inverse of a given matrix using the Gauss- - * Elimination method. - *

    - * An exception is thrown if the matrix has no inverse - * - * @param coef the matrix which inverse matrix is needed - * @return inverse matrix of the input matrix. - * If the matrix is singular, null is returned. - * @throws RuntimeException if the given matrix is not invertible - */ - public short[][] inverse(short[][] coef) - { - try - { - // Initialization: - short factor; - short[][] inverse; - A = new short[coef.length][2 * coef.length]; - if (coef.length != coef[0].length) - { - throw new RuntimeException( - "The matrix is not invertible. Please choose another one!"); - } - - // prepare: Copy coef and the identity matrix into the global A. - for (int i = 0; i < coef.length; i++) - { - for (int j = 0; j < coef.length; j++) - { - //copy the input matrix coef into A - A[i][j] = coef[i][j]; - } - // copy the identity matrix into A. - for (int j = coef.length; j < 2 * coef.length; j++) - { - A[i][j] = 0; - } - A[i][i + A.length] = 1; - } - - // Elimination operations to get the identity matrix from the left side of A. - // modify A to get 0s under the diagonal. - computeZerosUnder(true); - - // modify A to get only 1s on the diagonal: A[i][j] =A[i][j]/A[i][i]. - for (int i = 0; i < A.length; i++) - { - factor = GF2Field.invElem(A[i][i]); - for (int j = i; j < 2 * A.length; j++) - { - A[i][j] = GF2Field.multElem(A[i][j], factor); - } - } - - //modify A to get only 0s above the diagonal. - computeZerosAbove(); - - // copy the result (the second half of A) in the matrix inverse. - inverse = new short[A.length][A.length]; - for (int i = 0; i < A.length; i++) - { - for (int j = A.length; j < 2 * A.length; j++) - { - inverse[i][j - A.length] = A[i][j]; - } - } - return inverse; - - } - catch (RuntimeException rte) - { - // The matrix is not invertible! A new one should be generated! - return null; - } - } - - /** - * Elimination under the diagonal. - * This function changes a matrix so that it contains only zeros under the - * diagonal(Ai,i) using only Gauss-Elimination operations. - *

    - * It is used in solveEquaton as well as in the function for - * finding an inverse of a matrix: {@link}inverse. Both of them use the - * Gauss-Elimination Method. - *

    - * The result is stored in the global matrix A - *

    - * - * @param usedForInverse This parameter shows if the function is used by the - * solveEquation-function or by the inverse-function and according - * to this creates matrices of different sizes. - * @throws RuntimeException in case a multiplicative inverse of 0 is needed - */ - private void computeZerosUnder(boolean usedForInverse) - throws RuntimeException - { - - //the number of columns in the global A where the tmp results are stored - int length; - short tmp = 0; - - //the function is used in inverse() - A should have 2 times more columns than rows - if (usedForInverse) - { - length = 2 * A.length; - } - //the function is used in solveEquation - A has 1 column more than rows - else - { - length = A.length + 1; - } - - //elimination operations to modify A so that that it contains only 0s under the diagonal - for (int k = 0; k < A.length - 1; k++) - { // the fixed row - for (int i = k + 1; i < A.length; i++) - { // rows - short factor1 = A[i][k]; - short factor2 = GF2Field.invElem(A[k][k]); - - //The element which multiplicative inverse is needed, is 0 - //in this case is the input matrix not invertible - if (factor2 == 0) - { - throw new IllegalStateException("Matrix not invertible! We have to choose another one!"); - } - - for (int j = k; j < length; j++) - {// columns - // tmp=A[k,j] / A[k,k] - tmp = GF2Field.multElem(A[k][j], factor2); - // tmp = A[i,k] * A[k,j] / A[k,k] - tmp = GF2Field.multElem(factor1, tmp); - // A[i,j]=A[i,j]-A[i,k]/A[k,k]*A[k,j]; - A[i][j] = GF2Field.addElem(A[i][j], tmp); - } - } - } - } - - /** - * Elimination above the diagonal. - * This function changes a matrix so that it contains only zeros above the - * diagonal(Ai,i) using only Gauss-Elimination operations. - *

    - * It is used in the inverse-function - * The result is stored in the global matrix A - *

    - * - * @throws RuntimeException in case a multiplicative inverse of 0 is needed - */ - private void computeZerosAbove() - throws RuntimeException - { - short tmp = 0; - for (int k = A.length - 1; k > 0; k--) - { // the fixed row - for (int i = k - 1; i >= 0; i--) - { // rows - short factor1 = A[i][k]; - short factor2 = GF2Field.invElem(A[k][k]); - if (factor2 == 0) - { - throw new RuntimeException("The matrix is not invertible"); - } - for (int j = k; j < 2 * A.length; j++) - { // columns - // tmp = A[k,j] / A[k,k] - tmp = GF2Field.multElem(A[k][j], factor2); - // tmp = A[i,k] * A[k,j] / A[k,k] - tmp = GF2Field.multElem(factor1, tmp); - // A[i,j] = A[i,j] - A[i,k] / A[k,k] * A[k,j]; - A[i][j] = GF2Field.addElem(A[i][j], tmp); - } - } - } - } - - - /** - * This function uses backward substitution to find x - * of the linear equation system (LES) B*x = b, - * where A a triangle-matrix is (contains only zeros under the diagonal) - * and b is a vector - *

    - * If the multiplicative inverse of 0 is needed, an exception is thrown. - * In this case is the LES not solvable - *

    - * - * @throws RuntimeException in case a multiplicative inverse of 0 is needed - */ - private void substitute() - throws IllegalStateException - { - - // for the temporary results of the operations in field - short tmp, temp; - - temp = GF2Field.invElem(A[A.length - 1][A.length - 1]); - if (temp == 0) - { - throw new IllegalStateException("The equation system is not solvable"); - } - - // backward substitution - x[A.length - 1] = GF2Field.multElem(A[A.length - 1][A.length], temp); - for (int i = A.length - 2; i >= 0; i--) - { - tmp = A[i][A.length]; - for (int j = A.length - 1; j > i; j--) - { - temp = GF2Field.multElem(A[i][j], x[j]); - tmp = GF2Field.addElem(tmp, temp); - } - - temp = GF2Field.invElem(A[i][i]); - if (temp == 0) - { - throw new IllegalStateException("Not solvable equation system"); - } - x[i] = GF2Field.multElem(tmp, temp); - } - } - - - /** - * This function multiplies two given matrices. - * If the given matrices cannot be multiplied due - * to different sizes, an exception is thrown. - * - * @param M1 -the 1st matrix - * @param M2 -the 2nd matrix - * @return A = M1*M2 - * @throws RuntimeException in case the given matrices cannot be multiplied - * due to different dimensions. - */ - public short[][] multiplyMatrix(short[][] M1, short[][] M2) - throws RuntimeException - { - - if (M1[0].length != M2.length) - { - throw new RuntimeException("Multiplication is not possible!"); - } - short tmp = 0; - A = new short[M1.length][M2[0].length]; - for (int i = 0; i < M1.length; i++) - { - for (int j = 0; j < M2.length; j++) - { - for (int k = 0; k < M2[0].length; k++) - { - tmp = GF2Field.multElem(M1[i][j], M2[j][k]); - A[i][k] = GF2Field.addElem(A[i][k], tmp); - } - } - } - return A; - } - - /** - * This function multiplies a given matrix with a one-dimensional array. - *

    - * An exception is thrown, if the number of columns in the matrix and - * the number of rows in the one-dim. array differ. - * - * @param M1 the matrix to be multiplied - * @param m the one-dimensional array to be multiplied - * @return M1*m - * @throws RuntimeException in case of dimension inconsistency - */ - public short[] multiplyMatrix(short[][] M1, short[] m) - throws RuntimeException - { - if (M1[0].length != m.length) - { - throw new RuntimeException("Multiplication is not possible!"); - } - short tmp = 0; - short[] B = new short[M1.length]; - for (int i = 0; i < M1.length; i++) - { - for (int j = 0; j < m.length; j++) - { - tmp = GF2Field.multElem(M1[i][j], m[j]); - B[i] = GF2Field.addElem(B[i], tmp); - } - } - return B; - } - - /** - * Addition of two vectors - * - * @param vector1 first summand, always of dim n - * @param vector2 second summand, always of dim n - * @return addition of vector1 and vector2 - * @throws RuntimeException in case the addition is impossible - * due to inconsistency in the dimensions - */ - public short[] addVect(short[] vector1, short[] vector2) - { - if (vector1.length != vector2.length) - { - throw new RuntimeException("Multiplication is not possible!"); - } - short rslt[] = new short[vector1.length]; - for (int n = 0; n < rslt.length; n++) - { - rslt[n] = GF2Field.addElem(vector1[n], vector2[n]); - } - return rslt; - } - - /** - * Multiplication of column vector with row vector - * - * @param vector1 column vector, always n x 1 - * @param vector2 row vector, always 1 x n - * @return resulting n x n matrix of multiplication - * @throws RuntimeException in case the multiplication is impossible due to - * inconsistency in the dimensions - */ - public short[][] multVects(short[] vector1, short[] vector2) - { - if (vector1.length != vector2.length) - { - throw new RuntimeException("Multiplication is not possible!"); - } - short rslt[][] = new short[vector1.length][vector2.length]; - for (int i = 0; i < vector1.length; i++) - { - for (int j = 0; j < vector2.length; j++) - { - rslt[i][j] = GF2Field.multElem(vector1[i], vector2[j]); - } - } - return rslt; - } - - /** - * Multiplies vector with scalar - * - * @param scalar galois element to multiply vector with - * @param vector vector to be multiplied - * @return vector multiplied with scalar - */ - public short[] multVect(short scalar, short[] vector) - { - short rslt[] = new short[vector.length]; - for (int n = 0; n < rslt.length; n++) - { - rslt[n] = GF2Field.multElem(scalar, vector[n]); - } - return rslt; - } - - /** - * Multiplies matrix with scalar - * - * @param scalar galois element to multiply matrix with - * @param matrix 2-dim n x n matrix to be multiplied - * @return matrix multiplied with scalar - */ - public short[][] multMatrix(short scalar, short[][] matrix) - { - short[][] rslt = new short[matrix.length][matrix[0].length]; - for (int i = 0; i < matrix.length; i++) - { - for (int j = 0; j < matrix[0].length; j++) - { - rslt[i][j] = GF2Field.multElem(scalar, matrix[i][j]); - } - } - return rslt; - } - - /** - * Adds the n x n matrices matrix1 and matrix2 - * - * @param matrix1 first summand - * @param matrix2 second summand - * @return addition of matrix1 and matrix2; both having the dimensions n x n - * @throws RuntimeException in case the addition is not possible because of - * different dimensions of the matrices - */ - public short[][] addSquareMatrix(short[][] matrix1, short[][] matrix2) - { - if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) - { - throw new RuntimeException("Addition is not possible!"); - } - - short[][] rslt = new short[matrix1.length][matrix1.length];// - for (int i = 0; i < matrix1.length; i++) - { - for (int j = 0; j < matrix2.length; j++) - { - rslt[i][j] = GF2Field.addElem(matrix1[i][j], matrix2[i][j]); - } - } - return rslt; - } - -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/GF2Field.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/GF2Field.java deleted file mode 100644 index 2016cb7fc6..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/GF2Field.java +++ /dev/null @@ -1,139 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow.util; - -/** - * This class provides the basic operations like addition, multiplication and - * finding the multiplicative inverse of an element in GF2^8. - *

    - * The operations are implemented using the irreducible polynomial - * 1+x^2+x^3+x^6+x^8 ( 1 0100 1101 = 0x14d ) - *

    - * This class makes use of lookup tables(exps and logs) for implementing the - * operations in order to increase the efficiency of Rainbow. - */ -public class GF2Field -{ - - public static final int MASK = 0xff; - - /* - * this lookup table is needed for multiplication and computing the - * multiplicative inverse - */ - static final short exps[] = {1, 2, 4, 8, 16, 32, 64, 128, 77, 154, 121, 242, - 169, 31, 62, 124, 248, 189, 55, 110, 220, 245, 167, 3, 6, 12, 24, - 48, 96, 192, 205, 215, 227, 139, 91, 182, 33, 66, 132, 69, 138, 89, - 178, 41, 82, 164, 5, 10, 20, 40, 80, 160, 13, 26, 52, 104, 208, - 237, 151, 99, 198, 193, 207, 211, 235, 155, 123, 246, 161, 15, 30, - 60, 120, 240, 173, 23, 46, 92, 184, 61, 122, 244, 165, 7, 14, 28, - 56, 112, 224, 141, 87, 174, 17, 34, 68, 136, 93, 186, 57, 114, 228, - 133, 71, 142, 81, 162, 9, 18, 36, 72, 144, 109, 218, 249, 191, 51, - 102, 204, 213, 231, 131, 75, 150, 97, 194, 201, 223, 243, 171, 27, - 54, 108, 216, 253, 183, 35, 70, 140, 85, 170, 25, 50, 100, 200, - 221, 247, 163, 11, 22, 44, 88, 176, 45, 90, 180, 37, 74, 148, 101, - 202, 217, 255, 179, 43, 86, 172, 21, 42, 84, 168, 29, 58, 116, 232, - 157, 119, 238, 145, 111, 222, 241, 175, 19, 38, 76, 152, 125, 250, - 185, 63, 126, 252, 181, 39, 78, 156, 117, 234, 153, 127, 254, 177, - 47, 94, 188, 53, 106, 212, 229, 135, 67, 134, 65, 130, 73, 146, - 105, 210, 233, 159, 115, 230, 129, 79, 158, 113, 226, 137, 95, 190, - 49, 98, 196, 197, 199, 195, 203, 219, 251, 187, 59, 118, 236, 149, - 103, 206, 209, 239, 147, 107, 214, 225, 143, 83, 166, 1}; - - /* - * this lookup table is needed for multiplication and computing the - * multiplicative inverse - */ - static final short logs[] = {0, 0, 1, 23, 2, 46, 24, 83, 3, 106, 47, 147, - 25, 52, 84, 69, 4, 92, 107, 182, 48, 166, 148, 75, 26, 140, 53, - 129, 85, 170, 70, 13, 5, 36, 93, 135, 108, 155, 183, 193, 49, 43, - 167, 163, 149, 152, 76, 202, 27, 230, 141, 115, 54, 205, 130, 18, - 86, 98, 171, 240, 71, 79, 14, 189, 6, 212, 37, 210, 94, 39, 136, - 102, 109, 214, 156, 121, 184, 8, 194, 223, 50, 104, 44, 253, 168, - 138, 164, 90, 150, 41, 153, 34, 77, 96, 203, 228, 28, 123, 231, 59, - 142, 158, 116, 244, 55, 216, 206, 249, 131, 111, 19, 178, 87, 225, - 99, 220, 172, 196, 241, 175, 72, 10, 80, 66, 15, 186, 190, 199, 7, - 222, 213, 120, 38, 101, 211, 209, 95, 227, 40, 33, 137, 89, 103, - 252, 110, 177, 215, 248, 157, 243, 122, 58, 185, 198, 9, 65, 195, - 174, 224, 219, 51, 68, 105, 146, 45, 82, 254, 22, 169, 12, 139, - 128, 165, 74, 91, 181, 151, 201, 42, 162, 154, 192, 35, 134, 78, - 188, 97, 239, 204, 17, 229, 114, 29, 61, 124, 235, 232, 233, 60, - 234, 143, 125, 159, 236, 117, 30, 245, 62, 56, 246, 217, 63, 207, - 118, 250, 31, 132, 160, 112, 237, 20, 144, 179, 126, 88, 251, 226, - 32, 100, 208, 221, 119, 173, 218, 197, 64, 242, 57, 176, 247, 73, - 180, 11, 127, 81, 21, 67, 145, 16, 113, 187, 238, 191, 133, 200, - 161}; - - /** - * This function calculates the sum of two elements as an operation in GF2^8 - * - * @param x the first element that is to be added - * @param y the second element that should be add - * @return the sum of the two elements x and y in GF2^8 - */ - public static short addElem(short x, short y) - { - return (short)(x ^ y); - } - - /** - * This function computes the multiplicative inverse of a given element in - * GF2^8 The 0 has no multiplicative inverse and in this case 0 is returned. - * - * @param x the element which multiplicative inverse is to be computed - * @return the multiplicative inverse of the given element, in case it - * exists or 0, otherwise - */ - public static short invElem(short x) - { - if (x == 0) - { - return 0; - } - return (exps[255 - logs[x]]); - } - - /** - * This function multiplies two elements in GF2^8. If one of the two - * elements is 0, 0 is returned. - * - * @param x the first element to be multiplied. - * @param y the second element to be multiplied. - * @return the product of the two input elements in GF2^8. - */ - public static short multElem(short x, short y) - { - if (x == 0 || y == 0) - { - return 0; - } - else - { - return (exps[(logs[x] + logs[y]) % 255]); - } - } - - /** - * This function returns the values of exps-lookup table which correspond to - * the input - * - * @param x the index in the lookup table exps - * @return exps-value, corresponding to the input - */ - public static short getExp(short x) - { - return exps[x]; - } - - /** - * This function returns the values of logs-lookup table which correspond to - * the input - * - * @param x the index in the lookup table logs - * @return logs-value, corresponding to the input - */ - public static short getLog(short x) - { - return logs[x]; - } - - -} diff --git a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/RainbowUtil.java b/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/RainbowUtil.java deleted file mode 100644 index da65aa6301..0000000000 --- a/core/src/main/java/org/bouncycastle/pqc/legacy/crypto/rainbow/util/RainbowUtil.java +++ /dev/null @@ -1,230 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.rainbow.util; - -/** - * This class is needed for the conversions while encoding and decoding, as well as for - * comparison between arrays of some dimensions - */ -public class RainbowUtil -{ - - /** - * This function converts an one-dimensional array of bytes into a - * one-dimensional array of int - * - * @param in the array to be converted - * @return out - * the one-dimensional int-array that corresponds the input - */ - public static int[] convertArraytoInt(byte[] in) - { - int[] out = new int[in.length]; - for (int i = 0; i < in.length; i++) - { - out[i] = in[i] & GF2Field.MASK; - } - return out; - } - - /** - * This function converts an one-dimensional array of bytes into a - * one-dimensional array of type short - * - * @param in the array to be converted - * @return out - * one-dimensional short-array that corresponds the input - */ - public static short[] convertArray(byte[] in) - { - short[] out = new short[in.length]; - for (int i = 0; i < in.length; i++) - { - out[i] = (short)(in[i] & GF2Field.MASK); - } - return out; - } - - /** - * This function converts a matrix of bytes into a matrix of type short - * - * @param in the matrix to be converted - * @return out - * short-matrix that corresponds the input - */ - public static short[][] convertArray(byte[][] in) - { - short[][] out = new short[in.length][in[0].length]; - for (int i = 0; i < in.length; i++) - { - for (int j = 0; j < in[0].length; j++) - { - out[i][j] = (short)(in[i][j] & GF2Field.MASK); - } - } - return out; - } - - /** - * This function converts a 3-dimensional array of bytes into a 3-dimensional array of type short - * - * @param in the array to be converted - * @return out - * short-array that corresponds the input - */ - public static short[][][] convertArray(byte[][][] in) - { - short[][][] out = new short[in.length][in[0].length][in[0][0].length]; - for (int i = 0; i < in.length; i++) - { - for (int j = 0; j < in[0].length; j++) - { - for (int k = 0; k < in[0][0].length; k++) - { - out[i][j][k] = (short)(in[i][j][k] & GF2Field.MASK); - } - } - } - return out; - } - - /** - * This function converts an array of type int into an array of type byte - * - * @param in the array to be converted - * @return out - * the byte-array that corresponds the input - */ - public static byte[] convertIntArray(int[] in) - { - byte[] out = new byte[in.length]; - for (int i = 0; i < in.length; i++) - { - out[i] = (byte)in[i]; - } - return out; - } - - - /** - * This function converts an array of type short into an array of type byte - * - * @param in the array to be converted - * @return out - * the byte-array that corresponds the input - */ - public static byte[] convertArray(short[] in) - { - byte[] out = new byte[in.length]; - for (int i = 0; i < in.length; i++) - { - out[i] = (byte)in[i]; - } - return out; - } - - /** - * This function converts a matrix of type short into a matrix of type byte - * - * @param in the matrix to be converted - * @return out - * the byte-matrix that corresponds the input - */ - public static byte[][] convertArray(short[][] in) - { - byte[][] out = new byte[in.length][in[0].length]; - for (int i = 0; i < in.length; i++) - { - for (int j = 0; j < in[0].length; j++) - { - out[i][j] = (byte)in[i][j]; - } - } - return out; - } - - /** - * This function converts a 3-dimensional array of type short into a 3-dimensional array of type byte - * - * @param in the array to be converted - * @return out - * the byte-array that corresponds the input - */ - public static byte[][][] convertArray(short[][][] in) - { - byte[][][] out = new byte[in.length][in[0].length][in[0][0].length]; - for (int i = 0; i < in.length; i++) - { - for (int j = 0; j < in[0].length; j++) - { - for (int k = 0; k < in[0][0].length; k++) - { - out[i][j][k] = (byte)in[i][j][k]; - } - } - } - return out; - } - - /** - * Compare two short arrays. No null checks are performed. - * - * @param left the first short array - * @param right the second short array - * @return the result of the comparison - */ - public static boolean equals(short[] left, short[] right) - { - if (left.length != right.length) - { - return false; - } - boolean result = true; - for (int i = left.length - 1; i >= 0; i--) - { - result &= left[i] == right[i]; - } - return result; - } - - /** - * Compare two two-dimensional short arrays. No null checks are performed. - * - * @param left the first short array - * @param right the second short array - * @return the result of the comparison - */ - public static boolean equals(short[][] left, short[][] right) - { - if (left.length != right.length) - { - return false; - } - boolean result = true; - for (int i = left.length - 1; i >= 0; i--) - { - result &= equals(left[i], right[i]); - } - return result; - } - - /** - * Compare two three-dimensional short arrays. No null checks are performed. - * - * @param left the first short array - * @param right the second short array - * @return the result of the comparison - */ - public static boolean equals(short[][][] left, short[][][] right) - { - if (left.length != right.length) - { - return false; - } - boolean result = true; - for (int i = left.length - 1; i >= 0; i--) - { - result &= equals(left[i], right[i]); - } - return result; - } - -} diff --git a/core/src/main/java/org/bouncycastle/pqc/math/ntru/Polynomial.java b/core/src/main/java/org/bouncycastle/pqc/math/ntru/Polynomial.java index f207f25cc4..1d400dcb7f 100644 --- a/core/src/main/java/org/bouncycastle/pqc/math/ntru/Polynomial.java +++ b/core/src/main/java/org/bouncycastle/pqc/math/ntru/Polynomial.java @@ -12,7 +12,7 @@ public abstract class Polynomial */ // TODO: maybe the maths library needs to move. public short[] coeffs; - + protected NTRUParameterSet params; public Polynomial(NTRUParameterSet params) @@ -141,30 +141,40 @@ public void rqSumZeroFromBytes(byte[] a) public byte[] s3ToBytes(int messageSize) { byte[] msg = new byte[messageSize]; - byte c; + s3ToBytes(msg, 0); + return msg; + } - for (int i = 0; i < params.packDegree() / 5; i++) + public void s3ToBytes(byte[] msg, int msgOff) + { + int degree = params.packDegree(), limit = degree - 5; + + int i = 0; + while (i <= limit) { - c = (byte)(this.coeffs[5 * i + 4] & 255); - c = (byte)(3 * c + this.coeffs[5 * i + 3] & 255); - c = (byte)(3 * c + this.coeffs[5 * i + 2] & 255); - c = (byte)(3 * c + this.coeffs[5 * i + 1] & 255); - c = (byte)(3 * c + this.coeffs[5 * i + 0] & 255); - msg[i] = c; + int c0 = (coeffs[i + 0] & 0xFF); + int c1 = (coeffs[i + 1] & 0xFF) * 3; + int c2 = (coeffs[i + 2] & 0xFF) * 9; + int c3 = (coeffs[i + 3] & 0xFF) * 27; + int c4 = (coeffs[i + 4] & 0xFF) * 81; + + msg[msgOff++] = (byte)(c0 + c1 + c2 + c3 + c4); + i += 5; } - // if 5 does not divide NTRU_N-1 - if (params.packDegree() > (params.packDegree() / 5) * 5) + if (i < degree) { - int i = params.packDegree() / 5; - c = 0; - for (int j = params.packDegree() - (5 * i) - 1; j >= 0; j--) + int j = degree - 1; + int c = coeffs[j] & 0xFF; + + while (--j >= i) { - c = (byte)(3 * c + this.coeffs[5 * i + j] & 255); + c *= 3; + c += coeffs[j] & 0xFF; } - msg[i] = c; + + msg[msgOff++] = (byte)c; } - return msg; } /** @@ -388,7 +398,7 @@ private void r2InvToRqInv(Polynomial ai, Polynomial a, Polynomial b, Polynomial c.coeffs[0] += 2; this.rqMul(c, s); } - + void s3Inv(Polynomial a, Polynomial f, Polynomial g, Polynomial v, Polynomial w) { int n = this.coeffs.length; diff --git a/core/src/main/java/org/bouncycastle/pqc/math/ntru/parameters/NTRUHRSS1373.java b/core/src/main/java/org/bouncycastle/pqc/math/ntru/parameters/NTRUHRSS1373.java index 2bdfafc77d..ef1f9e20e0 100644 --- a/core/src/main/java/org/bouncycastle/pqc/math/ntru/parameters/NTRUHRSS1373.java +++ b/core/src/main/java/org/bouncycastle/pqc/math/ntru/parameters/NTRUHRSS1373.java @@ -2,7 +2,7 @@ /** - * NTRU-HRSS parameter set with n = 701. + * NTRU-HRSS parameter set with n = 1373. * * @see NTRUHRSSParameterSet */ diff --git a/core/src/main/java/org/bouncycastle/util/Arrays.java b/core/src/main/java/org/bouncycastle/util/Arrays.java index 27371dd423..db6f127dcf 100644 --- a/core/src/main/java/org/bouncycastle/util/Arrays.java +++ b/core/src/main/java/org/bouncycastle/util/Arrays.java @@ -1209,6 +1209,14 @@ public static void clear(int[] data) } } + public static void clear(long[] data) + { + if (null != data) + { + java.util.Arrays.fill(data, 0); + } + } + public static boolean isNullOrContainsNull(Object[] array) { if (null == array) @@ -1240,4 +1248,38 @@ public static boolean isNullOrEmpty(Object[] array) { return null == array || array.length < 1; } + + public static boolean segmentsOverlap(int aOff, int aLen, int bOff, int bLen) + { + return aLen > 0 + && bLen > 0 + && aOff - bOff < bLen + && bOff - aOff < aLen; + } + + public static void validateRange(byte[] buf, int from, int to) + { + if (buf == null) + { + throw new NullPointerException("'buf' cannot be null"); + } + if ((from | (buf.length - from) | (to - from) | (buf.length - to)) < 0) + { + throw new IndexOutOfBoundsException("buf.length: " + buf.length + ", from: " + from + ", to: " + to); + } + } + + public static void validateSegment(byte[] buf, int off, int len) + { + if (buf == null) + { + throw new NullPointerException("'buf' cannot be null"); + } + int available = buf.length - off; + int remaining = available - len; + if ((off | len | available | remaining) < 0) + { + throw new IndexOutOfBoundsException("buf.length: " + buf.length + ", off: " + off + ", len: " + len); + } + } } diff --git a/core/src/main/java/org/bouncycastle/util/Bytes.java b/core/src/main/java/org/bouncycastle/util/Bytes.java index 4db85758a0..b3081734da 100644 --- a/core/src/main/java/org/bouncycastle/util/Bytes.java +++ b/core/src/main/java/org/bouncycastle/util/Bytes.java @@ -16,6 +16,14 @@ public static void xor(int len, byte[] x, byte[] y, byte[] z) } } + public static void xor(int len, byte[] x, int xOff, byte[] y, byte[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff++] = (byte)(x[xOff++] ^ y[i]); + } + } + public static void xor(int len, byte[] x, int xOff, byte[] y, int yOff, byte[] z, int zOff) { for (int i = 0; i < len; ++i) @@ -24,6 +32,22 @@ public static void xor(int len, byte[] x, int xOff, byte[] y, int yOff, byte[] z } } + public static void xor(int len, byte[] x, byte[] y, byte[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff++] = (byte)(x[i] ^ y[i]); + } + } + + public static void xor(int len, byte[] x, byte[] y, int yOff, byte[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff++] = (byte)(x[i] ^ y[yOff++]); + } + } + public static void xorTo(int len, byte[] x, byte[] z) { for (int i = 0; i < len; ++i) @@ -32,6 +56,14 @@ public static void xorTo(int len, byte[] x, byte[] z) } } + public static void xorTo(int len, byte[] x, int xOff, byte[] z) + { + for (int i = 0; i < len; ++i) + { + z[i] ^= x[xOff++]; + } + } + public static void xorTo(int len, byte[] x, int xOff, byte[] z, int zOff) { for (int i = 0; i < len; ++i) diff --git a/core/src/main/java/org/bouncycastle/util/GF16.java b/core/src/main/java/org/bouncycastle/util/GF16.java new file mode 100644 index 0000000000..3cb0878965 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/util/GF16.java @@ -0,0 +1,178 @@ +package org.bouncycastle.util; + +public class GF16 +{ + private static final byte[] F_STAR = {1, 2, 4, 8, 3, 6, 12, 11, 5, 10, 7, 14, 15, 13, 9}; + private static final byte[] MT4B = new byte[256]; + private static final byte[] INV4B = new byte[16]; + + static byte mt(int p, int q) + { + return MT4B[((p) << 4) ^ (q)]; + } + + static + { + // Initialize multiplication table + for (int i = 0; i < 15; i++) + { + for (int j = 0; j < 15; j++) + { + MT4B[(F_STAR[i] << 4) ^ F_STAR[j]] = F_STAR[(i + j) % 15]; + } + } + + int g = F_STAR[1], g_inv = F_STAR[14], gn = 1, gn_inv = 1; + // Initialize inversion table + INV4B[1] = 1; + for (int i = 0; i < 14; i++) + { + gn = mt(gn, g); + gn_inv = mt(gn_inv, g_inv); + INV4B[gn] = (byte)gn_inv; + } + } + + /** + * GF(16) multiplication mod x^4 + x + 1. + *

    + * This method multiplies two elements in GF(16) (represented as integers 0–15) + * using carryless multiplication followed by reduction modulo x^4 + x + 1. + * Please ensure a <= 0x0F and b <= 0x0F + * + * @param a an element in GF(16) (only the lower 4 bits are used) + * @param b an element in GF(16) (only the lower 4 bits are used) + * @return the product a * b in GF(16) + */ + public static byte mul(byte a, byte b) + { + return MT4B[a << 4 | b]; + } + + /** + * GF(16) multiplication mod x^4 + x + 1. + *

    + * This method multiplies two elements in GF(16) (represented as integers 0–15) + * using carryless multiplication followed by reduction modulo x^4 + x + 1. + * Please ensure a <= 0x0F and b <= 0x0F + * + * @param a an element in GF(16) (only the lower 4 bits are used) + * @param b an element in GF(16) (only the lower 4 bits are used) + * @return the product a * b in GF(16) + */ + public static int mul(int a, int b) + { + return MT4B[a << 4 | b]; + } + + /** + * Computes the multiplicative inverse in GF(16) for a GF(16) element. + */ + public static byte inv(byte a) + { + return INV4B[a & 0xF]; +// int a2 = GF16.mul(a, a); +// int a4 = GF16.mul(a2, a2); +// int a8 = GF16.mul(a4, a4); +// int a6 = GF16.mul(a2, a4); +// return (byte)GF16.mul(a8, a6); + } + + /** + * Decodes an encoded byte array. + * Each byte in the input contains two nibbles (4-bit values); the lower nibble is stored first, + * followed by the upper nibble. + * + * @param input the input byte array (each byte holds two 4-bit values) + * @param output the output array that will hold the decoded nibbles (one per byte) + * @param outputLen the total number of nibbles to decode + */ + public static void decode(byte[] input, byte[] output, int outputLen) + { + int i, decIndex = 0, blocks = outputLen >> 1; + // Process pairs of nibbles from each byte + for (i = 0; i < blocks; i++) + { + // Extract the lower nibble + output[decIndex++] = (byte)(input[i] & 0x0F); + // Extract the upper nibble (shift right 4 bits) + output[decIndex++] = (byte)((input[i] >>> 4) & 0x0F); + } + // If there is an extra nibble (odd number of nibbles), decode only the lower nibble + if ((outputLen & 1) == 1) + { + output[decIndex] = (byte)(input[i] & 0x0F); + } + } + + public static void decode(byte[] input, int inOff, byte[] output, int outOff, int outputLen) + { + // Process pairs of nibbles from each byte + int blocks = outputLen >> 1; + for (int i = 0; i < blocks; i++) + { + // Extract the lower nibble + output[outOff++] = (byte)(input[inOff] & 0x0F); + // Extract the upper nibble (shift right 4 bits) + output[outOff++] = (byte)((input[inOff++] >>> 4) & 0x0F); + } + // If there is an extra nibble (odd number of nibbles), decode only the lower nibble + if ((outputLen & 1) == 1) + { + output[outOff] = (byte)(input[inOff] & 0x0F); + } + } + + /** + * Encodes an array of 4-bit values into a byte array. + * Two 4-bit values are packed into one byte, with the first nibble stored in the lower 4 bits + * and the second nibble stored in the upper 4 bits. + * + * @param input the input array of 4-bit values (stored as bytes, only lower 4 bits used) + * @param output the output byte array that will hold the encoded bytes + * @param inputLen the number of nibbles in the input array + */ + public static void encode(byte[] input, byte[] output, int inputLen) + { + int i, inOff = 0, blocks = inputLen >> 1; + // Process pairs of 4-bit values + for (i = 0; i < blocks; i++) + { + int lowerNibble = input[inOff++] & 0x0F; + int upperNibble = (input[inOff++] & 0x0F) << 4; + output[i] = (byte)(lowerNibble | upperNibble); + } + // If there is an extra nibble (odd number of nibbles), store it directly in lower 4 bits. + if ((inputLen & 1) == 1) + { + output[i] = (byte)(input[inOff] & 0x0F); + } + } + + public static void encode(byte[] input, byte[] output, int outOff, int inputLen) + { + int i, inOff = 0, blocks = inputLen >> 1; + // Process pairs of 4-bit values + for (i = 0; i < blocks; i++) + { + int lowerNibble = input[inOff++] & 0x0F; + int upperNibble = (input[inOff++] & 0x0F) << 4; + output[outOff++] = (byte)(lowerNibble | upperNibble); + } + // If there is an extra nibble (odd number of nibbles), store it directly in lower 4 bits. + if ((inputLen & 1) == 1) + { + output[outOff] = (byte)(input[inOff] & 0x0F); + } + } + + public static byte innerProduct(byte[] a, int aOff, byte[] b, int bOff, int rank) + { + byte result = 0; + for (int k = 0; k < rank; ++k, bOff += rank) + { + result ^= mul(a[aOff++], b[bOff]); + } + return result; + } +} diff --git a/core/src/main/java/org/bouncycastle/util/Longs.java b/core/src/main/java/org/bouncycastle/util/Longs.java index 443e310f4f..eaaada9b0e 100644 --- a/core/src/main/java/org/bouncycastle/util/Longs.java +++ b/core/src/main/java/org/bouncycastle/util/Longs.java @@ -52,4 +52,12 @@ public static Long valueOf(long value) { return Long.valueOf(value); } + + public static void xorTo(int len, long[] x, int xOff, long[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff + i] ^= x[xOff + i]; + } + } } diff --git a/core/src/main/java/org/bouncycastle/util/Pack.java b/core/src/main/java/org/bouncycastle/util/Pack.java index a2ce48f90e..1aeee73858 100644 --- a/core/src/main/java/org/bouncycastle/util/Pack.java +++ b/core/src/main/java/org/bouncycastle/util/Pack.java @@ -104,6 +104,16 @@ public static void bigEndianToLong(byte[] bs, int bsOff, long[] ns, int nsOff, i } } + public static long bigEndianToLong(byte[] bs, int off, int len) + { + long x = 0; + for (int i = 0; i < len; ++i) + { + x |= (bs[i + off] & 0xFFL) << ((7 - i) << 3); + } + return x; + } + public static byte[] longToBigEndian(long n) { byte[] bs = new byte[8]; @@ -165,6 +175,15 @@ public static short littleEndianToShort(byte[] bs, int off) return (short)n; } + public static void littleEndianToShort(byte[] bs, int bOff, short[] ns, int nOff, int count) + { + for (int i = 0; i < count; ++i) + { + ns[nOff + i] = littleEndianToShort(bs, bOff); + bOff += 2; + } + } + public static int littleEndianToInt(byte[] bs, int off) { int n = bs[off] & 0xff; @@ -235,6 +254,14 @@ public static void shortToLittleEndian(short n, byte[] bs, int off) bs[++off] = (byte)(n >>> 8); } + public static void shortToLittleEndian(short[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) + { + for (int i = 0; i < nsLen; ++i) + { + shortToLittleEndian(ns[nsOff + i], bs, bsOff); + bsOff += 2; + } + } public static byte[] shortToBigEndian(short n) { @@ -306,6 +333,16 @@ public static void littleEndianToLong(byte[] bs, int off, long[] ns) } } + public static long littleEndianToLong(byte[] input, int off, int len) + { + long result = 0; + for (int i = 0; i < len; ++i) + { + result |= (input[off + i] & 0xFFL) << (i << 3); + } + return result; + } + public static void littleEndianToLong(byte[] bs, int bsOff, long[] ns, int nsOff, int nsLen) { for (int i = 0; i < nsLen; ++i) @@ -327,6 +364,14 @@ public static void longToLittleEndian_High(long n, byte[] bs, int off, int len) } } + public static void longToLittleEndian(long n, byte[] bs, int off, int len) + { + for (int i = 0; i < len; ++i) + { + bs[off + i] = (byte)(n >>> (i << 3)); + } + } + // public static void longToLittleEndian_Low(long n, byte[] bs, int off, int len) // { // longToLittleEndian_High(n << ((8 - len) << 3), bs, off, len); @@ -386,4 +431,6 @@ public static void longToLittleEndian(long[] ns, int nsOff, int nsLen, byte[] bs bsOff += 8; } } + + } diff --git a/core/src/main/java/org/bouncycastle/util/Properties.java b/core/src/main/java/org/bouncycastle/util/Properties.java index 6630de95d8..62c7c724f8 100644 --- a/core/src/main/java/org/bouncycastle/util/Properties.java +++ b/core/src/main/java/org/bouncycastle/util/Properties.java @@ -48,6 +48,32 @@ public static boolean isOverrideSet(String propertyName) } } + /** + * Return whether a particular override has been set to true. + * + * @param propertyName the property name for the override. + * @return true if the property is set to "true", false otherwise. + */ + public static boolean isOverrideSet(String propertyName, boolean defIsTrue) + { + try + { + String value = getPropertyValue(propertyName); + if (value == null) + { + return defIsTrue; + } + else + { + return isSetTrue(value); + } + } + catch (AccessControlException e) + { + return false; + } + } + /** * Return whether a particular override has been set to false. * diff --git a/core/src/main/java/org/bouncycastle/util/encoders/package-info.java b/core/src/main/java/org/bouncycastle/util/encoders/package-info.java new file mode 100644 index 0000000000..52dc3096fa --- /dev/null +++ b/core/src/main/java/org/bouncycastle/util/encoders/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for producing and reading Base64 and Hex strings. + */ +package org.bouncycastle.util.encoders; diff --git a/core/src/main/java/org/bouncycastle/util/io/Streams.java b/core/src/main/java/org/bouncycastle/util/io/Streams.java index c72a476fa1..21eb4a4ebe 100644 --- a/core/src/main/java/org/bouncycastle/util/io/Streams.java +++ b/core/src/main/java/org/bouncycastle/util/io/Streams.java @@ -5,6 +5,8 @@ import java.io.InputStream; import java.io.OutputStream; +import org.bouncycastle.util.Arrays; + /** * Utility methods to assist with stream processing. */ @@ -160,16 +162,7 @@ public static int readFully(InputStream inStr, byte[] buf, int off, int len) public static void validateBufferArguments(byte[] buf, int off, int len) { - if (buf == null) - { - throw new NullPointerException(); - } - int available = buf.length - off; - int remaining = available - len; - if ((off | len | available | remaining) < 0) - { - throw new IndexOutOfBoundsException(); - } + Arrays.validateSegment(buf, off, len); } public static void writeBufTo(ByteArrayOutputStream buf, OutputStream output) diff --git a/core/src/main/java/org/bouncycastle/util/io/package-info.java b/core/src/main/java/org/bouncycastle/util/io/package-info.java new file mode 100644 index 0000000000..51134bbc0a --- /dev/null +++ b/core/src/main/java/org/bouncycastle/util/io/package-info.java @@ -0,0 +1,4 @@ +/** + * General purpose I/O helper classes and wrappers. + */ +package org.bouncycastle.util.io; diff --git a/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java b/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java index 2d681b9bee..53008fcca2 100644 --- a/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java +++ b/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java @@ -5,6 +5,8 @@ import java.io.Reader; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import org.bouncycastle.util.encoders.Base64; @@ -14,8 +16,11 @@ public class PemReader extends BufferedReader { + public static final String LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME = "org.bouncycastle.pemreader.lax"; + private static final String BEGIN = "-----BEGIN "; private static final String END = "-----END "; + private static final Logger LOG = Logger.getLogger(PemReader.class.getName()); public PemReader(Reader reader) { @@ -75,6 +80,16 @@ private PemObject loadObject(String type) continue; } + if (System.getProperty(LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME, "false").equalsIgnoreCase("true")) + { + String trimmedLine = line.trim(); + if (!trimmedLine.equals(line) && LOG.isLoggable(Level.WARNING)) + { + LOG.log(Level.WARNING, "PEM object contains whitespaces on -----END line", new Exception("trace")); + } + line = trimmedLine; + } + if (line.indexOf(endMarker) == 0) { break; diff --git a/core/src/main/java/org/bouncycastle/util/io/pem/package-info.java b/core/src/main/java/org/bouncycastle/util/io/pem/package-info.java new file mode 100644 index 0000000000..67618e262e --- /dev/null +++ b/core/src/main/java/org/bouncycastle/util/io/pem/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for reading and writing raw PEM objects. + */ +package org.bouncycastle.util.io.pem; diff --git a/core/src/main/java/org/bouncycastle/util/package-info.java b/core/src/main/java/org/bouncycastle/util/package-info.java new file mode 100644 index 0000000000..2454b1dfeb --- /dev/null +++ b/core/src/main/java/org/bouncycastle/util/package-info.java @@ -0,0 +1,4 @@ +/** + * General purpose utility classes used throughout the APIs. + */ +package org.bouncycastle.util; diff --git a/core/src/main/java/org/bouncycastle/util/test/SimpleTest.java b/core/src/main/java/org/bouncycastle/util/test/SimpleTest.java index 742c1a7470..2d29635e54 100644 --- a/core/src/main/java/org/bouncycastle/util/test/SimpleTest.java +++ b/core/src/main/java/org/bouncycastle/util/test/SimpleTest.java @@ -16,7 +16,7 @@ private TestResult success() return SimpleTestResult.successful(this, "Okay"); } - protected void fail( + public void fail( String message) { throw new TestFailedException(SimpleTestResult.failed(this, message)); @@ -31,7 +31,7 @@ protected void isTrue( } } - protected void isTrue( + public void isTrue( String message, boolean value) { @@ -163,7 +163,7 @@ protected void fail( throw new TestFailedException(SimpleTestResult.failed(this, message, throwable)); } - protected void fail( + public void fail( String message, Object expected, Object found) @@ -178,7 +178,7 @@ protected boolean areEqual( return Arrays.areEqual(a, b); } - protected boolean areEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex) + public boolean areEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex) { return Arrays.areEqual(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex); } @@ -273,7 +273,7 @@ void operation() throws Exception; } - protected Exception testException(String failMessage, String exceptionClass, TestExceptionOperation operation) + public Exception testException(String failMessage, String exceptionClass, TestExceptionOperation operation) { try { @@ -286,7 +286,7 @@ protected Exception testException(String failMessage, String exceptionClass, Tes { isTrue(e.getMessage(), e.getMessage().indexOf(failMessage) >= 0); } - isTrue(e.getClass().getName().indexOf(exceptionClass) >= 0); + isTrue(e.getMessage(),e.getClass().getName().indexOf(exceptionClass) >= 0); return e; } return null; diff --git a/core/src/main/java/org/bouncycastle/util/test/package-info.java b/core/src/main/java/org/bouncycastle/util/test/package-info.java new file mode 100644 index 0000000000..6ca01ff062 --- /dev/null +++ b/core/src/main/java/org/bouncycastle/util/test/package-info.java @@ -0,0 +1,4 @@ +/** + * Light weight test API. If you can use Junit! + */ +package org.bouncycastle.util.test; diff --git a/core/src/main/jdk1.1/java/security/cert/CertUtil.java b/core/src/main/jdk1.1/java/security/cert/CertUtil.java index cf1aae2029..323790723d 100644 --- a/core/src/main/jdk1.1/java/security/cert/CertUtil.java +++ b/core/src/main/jdk1.1/java/security/cert/CertUtil.java @@ -1,17 +1,15 @@ package java.security.cert; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; +import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.OIDTokenizer; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.util.Strings; @@ -336,12 +334,7 @@ static byte[] parseOID(String oid) throws IOException { throw new IOException("token: " + token + ": " + ex.toString()); } - ASN1Object derData = new ASN1ObjectIdentifier(oid); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + return new ASN1ObjectIdentifier(oid).getEncoded(ASN1Encoding.DER); } /** @@ -452,12 +445,7 @@ private static byte[] parseIPv6(String data) private static byte[] parseURI(String data) throws IOException { // TODO do parsing test - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + return new DERIA5String(data).getEncoded(ASN1Encoding.DER); } /** @@ -479,13 +467,8 @@ private static byte[] parseRfc822(String data) throws IOException { throw new IOException("wrong format of rfc822Name:" + data); } - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + // TODO more test for illegal characters + return new DERIA5String(data).getEncoded(ASN1Encoding.DER); } /** @@ -502,13 +485,8 @@ private static byte[] parseRfc822(String data) throws IOException */ private static byte[] parseDNSName(String data) throws IOException { - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + // TODO more test for illegal characters + return new DERIA5String(data).getEncoded(ASN1Encoding.DER); } /** @@ -524,12 +502,8 @@ private static byte[] parseDNSName(String data) throws IOException */ private static byte[] parseX509Name(String data) throws IOException { - // TODO more test for illegal charateers - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(new X509Name(trimX509Name(data))); - derOutStream.close(); - return outStream.toByteArray(); + // TODO more test for illegal characters + return new X509Name(trimX509Name(data)).getEncoded(ASN1Encoding.DER); } /** diff --git a/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java b/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java index a72e50b073..de5b72eb83 100644 --- a/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java +++ b/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java @@ -1,7 +1,5 @@ package java.security.cert; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.PublicKey; @@ -20,18 +18,15 @@ import java.util.List; import java.util.Set; -import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1OutputStream; +import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.ASN1Util; import org.bouncycastle.asn1.BERTags; -import org.bouncycastle.asn1.ASN1GeneralizedTime; -import org.bouncycastle.asn1.DERGeneralizedTime; -import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; @@ -79,10 +74,8 @@ * TODO: implement name constraints * TODO: implement match check for path to names
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, + * Uses {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.bouncycastle.asn1.ASN1OutputStream DEROutputStream}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.OIDTokenizer OIDTokenizer}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name}, @@ -286,8 +279,7 @@ public void setIssuer(String issuerDN) throws IOException * Note that the byte array specified here is cloned to protect against * subsequent modifications.
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, + * Uses {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name} * @@ -307,9 +299,7 @@ public void setIssuer(byte[] issuerDN) throws IOException } else { - ByteArrayInputStream inStream = new ByteArrayInputStream(issuerDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); + ASN1Object obj = ASN1Primitive.fromByteArray(issuerDN); if (obj instanceof ASN1Sequence) { this.issuerDNX509 = new X509Name((ASN1Sequence)obj); @@ -373,8 +363,7 @@ public void setSubject(String subjectDN) throws IOException * the ASN.1 notation for this structure, see * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, + * Uses {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name} * @@ -394,10 +383,7 @@ public void setSubject(byte[] subjectDN) throws IOException } else { - ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - + ASN1Object obj = ASN1Primitive.fromByteArray(subjectDN); if (obj instanceof ASN1Sequence) { this.subjectDNX509 = new X509Name((ASN1Sequence)obj); @@ -589,8 +575,15 @@ public void setPrivateKeyValid(Date privateKeyValid) */ public void setSubjectPublicKeyAlgID(String oid) throws IOException { - CertUtil.parseOID(oid); - subjectKeyAlgID = new ASN1ObjectIdentifier(oid); + if (oid != null) + { + CertUtil.parseOID(oid); + subjectKeyAlgID = new ASN1ObjectIdentifier(oid); + } + else + { + subjectKeyAlgID = null; + } } /** @@ -730,11 +723,11 @@ public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException { if (keyPurposeSet == null || keyPurposeSet.isEmpty()) { - this.keyPurposeSet = keyPurposeSet; + this.keyPurposeSet = null; } else { - this.keyPurposeSet = new HashSet(); + HashSet checkKeyPurposeSet = new HashSet(); Iterator iter = keyPurposeSet.iterator(); Object obj; KeyPurposeId purposeID; @@ -743,15 +736,16 @@ public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException obj = iter.next(); if (obj instanceof String) { - purposeID = (KeyPurposeId)keyPurposeIdMap.get((String)obj); + String str = (String)obj; + purposeID = (KeyPurposeId)keyPurposeIdMap.get(str); if (purposeID == null) { - throw new IOException("unknown purposeID " - + (String)obj); + throw new IOException("unknown purposeID " + str); } - this.keyPurposeSet.add(purposeID); + checkKeyPurposeSet.add(purposeID); } } + this.keyPurposeSet = Collections.unmodifiableSet(checkKeyPurposeSet); } } @@ -851,8 +845,7 @@ else if (data instanceof byte[]) } else { - throw new IOException( - "parsing error: unknown data type"); + throw new IOException("parsing error: unknown data type"); } } } @@ -903,6 +896,7 @@ public void addSubjectAlternativeName(int type, String name) tmpList.add(Integers.valueOf(type)); tmpList.add(name); subjectAltNames.add(tmpList); + // FIXME Surely this affects the entry we just added to subjectAltNames?? tmpList.set(1, encoded); subjectAltNamesByte.add(tmpList); } @@ -1089,7 +1083,7 @@ public void setPolicy(Set certPolicySet) throws IOException } else { - policyOID = new HashSet(); + HashSet checkPolicyOID = new HashSet(); Iterator iter = certPolicySet.iterator(); Object item; while (iter.hasNext()) @@ -1098,15 +1092,15 @@ public void setPolicy(Set certPolicySet) throws IOException if (item instanceof String) { CertUtil.parseOID((String)item); - policyOID.add(new ASN1ObjectIdentifier((String)item)); + checkPolicyOID.add(new ASN1ObjectIdentifier((String)item)); } else { - throw new IOException( - "certPolicySet contains null values or non String objects"); + throw new IOException("certPolicySet contains null values or non String objects"); } } - policy = new HashSet(certPolicySet); + this.policy = Collections.unmodifiableSet(new HashSet(certPolicySet)); + this.policyOID = Collections.unmodifiableSet(checkPolicyOID); } } @@ -1192,8 +1186,7 @@ else if (data instanceof byte[]) } else { - throw new IOException( - "parsing error: unknown data type"); + throw new IOException("parsing error: unknown data type"); } } } @@ -1243,6 +1236,7 @@ public void addPathToName(int type, String name) throws IOException tmpList.add(Integers.valueOf(type)); tmpList.add(name); pathToNames.add(tmpList); + // FIXME Surely this affects the entry we just added to pathToNames?? tmpList.set(1, encoded); pathToNamesByte.add(tmpList); throw new UnsupportedOperationException(); @@ -1335,7 +1329,7 @@ public String getIssuerAsString() { if (issuerDN instanceof String) { - return new String((String)issuerDN); + return (String)issuerDN; } else if (issuerDNX509 != null) { @@ -1359,8 +1353,7 @@ else if (issuerDNX509 != null) * Note that the byte array returned is cloned to protect against subsequent * modifications.
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1OutputStream DEROutputStream}, - * {@link org.bouncycastle.asn1.x509.X509Name X509Name} to gnerate byte[] + * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} to generate byte[] * output for String issuerDN. * * @return a byte array containing the required issuer distinguished name in @@ -1377,13 +1370,7 @@ public byte[] getIssuerAsBytes() throws IOException } else if (issuerDNX509 != null) { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - - derOutStream.writeObject(issuerDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); + return issuerDNX509.getEncoded(ASN1Encoding.DER); } return null; @@ -1408,7 +1395,7 @@ public String getSubjectAsString() { if (subjectDN instanceof String) { - return new String((String)subjectDN); + return (String)subjectDN; } else if (subjectDNX509 != null) { @@ -1432,8 +1419,7 @@ else if (subjectDNX509 != null) * Note that the byte array returned is cloned to protect against subsequent * modifications.
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1OutputStream DEROutputStream}, - * {@link org.bouncycastle.asn1.x509.X509Name X509Name} to gnerate byte[] + * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} to generate byte[] * output for String subjectDN. * * @return a byte array containing the required subject distinguished name @@ -1450,13 +1436,7 @@ public byte[] getSubjectAsBytes() throws IOException } else if (subjectDNX509 != null) { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - - derOutStream.writeObject(subjectDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); + return subjectDNX509.getEncoded(ASN1Encoding.DER); } return null; @@ -1629,19 +1609,7 @@ public boolean[] getKeyUsage() */ public Set getExtendedKeyUsage() { - if (keyPurposeSet == null || keyPurposeSet.isEmpty()) - { - return keyPurposeSet; - } - - Set returnSet = new HashSet(); - Iterator iter = keyPurposeSet.iterator(); - while (iter.hasNext()) - { - returnSet.add(iter.next().toString()); - } - - return Collections.unmodifiableSet(returnSet); + return keyPurposeSet; } /** @@ -1699,7 +1667,7 @@ public boolean getMatchAllSubjectAltNames() */ public Collection getSubjectAlternativeNames() { - if (subjectAltNames != null) + if (subjectAltNames == null) { return null; } @@ -1708,19 +1676,18 @@ public Collection getSubjectAlternativeNames() List returnList; Iterator iter = subjectAltNames.iterator(); List obj; + Object data; while (iter.hasNext()) { obj = (List)iter.next(); returnList = new ArrayList(); returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else + data = obj.get(1); + if (data instanceof byte[]) { - returnList.add(obj.get(1)); + data = org.bouncycastle.util.Arrays.clone((byte[])data); } + returnList.add(data); returnAltNames.add(returnList); } @@ -1790,12 +1757,7 @@ public int getBasicConstraints() */ public Set getPolicy() { - if (policy == null) - { - return null; - } - - return Collections.unmodifiableSet(policy); + return policy; } /** @@ -1838,20 +1800,18 @@ public Collection getPathToNames() List returnList; Iterator iter = pathToNames.iterator(); List obj; - + Object data; while (iter.hasNext()) { obj = (List)iter.next(); returnList = new ArrayList(); returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else + data = obj.get(1); + if (data instanceof byte[]) { - returnList.add(obj.get(1)); + data = org.bouncycastle.util.Arrays.clone((byte[])data); } + returnList.add(data); returnPathToNames.add(returnList); } @@ -1864,8 +1824,7 @@ public Collection getPathToNames() * TODO: implement output for currently unsupported options(name * constraints)
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, + * Uses {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.x509.KeyPurposeId KeyPurposeId} * * @return a String describing the contents of the @@ -1895,19 +1854,13 @@ public String toString() { if (subjectKeyID != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - subjectKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray(subjectKeyID); sb.append(" Subject Key Identifier: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } if (authorityKeyID != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - authorityKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray(authorityKeyID); sb.append(" Authority Key Identifier: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } @@ -1960,10 +1913,7 @@ public String toString() while (iter.hasNext()) { obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray((byte[])obj.get(1)); sb.append(" Type: ").append(obj.get(0)).append(" Data: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } @@ -1984,10 +1934,7 @@ public String toString() while (iter.hasNext()) { obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray((byte[])obj.get(1)); sb.append(" Type: ").append(obj.get(0)).append(" Data: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } @@ -2007,11 +1954,10 @@ public String toString() *
    * TODO: implement missing tests (name constraints and path to names)
    *
    - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, + * Uses {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, - * {@link org.bouncycastle.asn1.DERGeneralizedTime DERGeneralizedTime}, + * {@link org.bouncycastle.asn1.ASN1GeneralizedTime ASN1GeneralizedTime}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name}, * {@link org.bouncycastle.asn1.x509.X509Extensions X509Extensions}, * {@link org.bouncycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage}, @@ -2042,8 +1988,7 @@ public boolean match(Certificate cert) { return false; } - if (serialNumber != null - && !serialNumber.equals(certX509.getSerialNumber())) + if (serialNumber != null && !serialNumber.equals(certX509.getSerialNumber())) { return false; } @@ -2051,16 +1996,14 @@ public boolean match(Certificate cert) { if (issuerDNX509 != null) { - if (!issuerDNX509.equals(PrincipalUtil - .getIssuerX509Principal(certX509), true)) + if (!issuerDNX509.equals(PrincipalUtil.getIssuerX509Principal(certX509), true)) { return false; } } if (subjectDNX509 != null) { - if (!subjectDNX509.equals(PrincipalUtil - .getSubjectX509Principal(certX509), true)) + if (!subjectDNX509.equals(PrincipalUtil.getSubjectX509Principal(certX509), true)) { return false; } @@ -2072,50 +2015,40 @@ public boolean match(Certificate cert) } if (subjectKeyID != null) { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectKeyIdentifier - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); if (data == null) { return false; } try { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); + byte[] testData = ASN1OctetString.getInstance(data).getOctets(); if (!Arrays.equals(subjectKeyID, testData)) { return false; } } - catch (IOException ex) + catch (Exception ex) { return false; } } if (authorityKeyID != null) { - byte[] data = certX509 - .getExtensionValue(X509Extensions.AuthorityKeyIdentifier - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (data == null) { return false; } try { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); + byte[] testData = ASN1OctetString.getInstance(data).getOctets(); if (!Arrays.equals(authorityKeyID, testData)) { return false; } } - catch (IOException ex) + catch (Exception ex) { return false; } @@ -2137,31 +2070,19 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.PrivateKeyUsagePeriod - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.PrivateKeyUsagePeriod.getId()); if (data != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); // TODO fix this, Sequence contains tagged objects - ASN1Sequence derObject = (ASN1Sequence)derInputStream - .readObject(); - ASN1GeneralizedTime derDate = DERGeneralizedTime - .getInstance(derObject.getObjectAt(0)); - SimpleDateFormat dateF = new SimpleDateFormat( - "yyyyMMddHHmmssZ"); + ASN1Sequence derObject = ASN1Sequence.getInstance( + ASN1OctetString.getInstance(data).getOctets()); + ASN1GeneralizedTime derDate = ASN1GeneralizedTime.getInstance(derObject.getObjectAt(0)); + SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssZ"); if (privateKeyValid.before(dateF.parse(derDate.getTime()))) { return false; } - derDate = DERGeneralizedTime.getInstance(derObject - .getObjectAt(1)); + derDate = ASN1GeneralizedTime.getInstance(derObject.getObjectAt(1)); if (privateKeyValid.after(dateF.parse(derDate.getTime()))) { return false; @@ -2177,7 +2098,8 @@ public boolean match(Certificate cert) { try { - SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certX509.getPublicKey().getEncoded()); + SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance( + certX509.getPublicKey().getEncoded()); AlgorithmIdentifier algInfo = publicKeyInfo.getAlgorithmId(); if (!algInfo.getAlgorithm().equals(subjectKeyAlgID)) { @@ -2191,8 +2113,7 @@ public boolean match(Certificate cert) } if (subjectPublicKeyByte != null) { - if (!Arrays.equals(subjectPublicKeyByte, certX509.getPublicKey() - .getEncoded())) + if (!Arrays.equals(subjectPublicKeyByte, certX509.getPublicKey().getEncoded())) { return false; } @@ -2223,21 +2144,14 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.ExtendedKeyUsage - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.ExtendedKeyUsage.getId()); if (data != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance( - (ASN1Sequence)derInputStream.readObject()); + ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(data); tempIter = keyPurposeSet.iterator(); while (tempIter.hasNext()) { - if (!extendedKeyUsage - .hasKeyPurposeId((KeyPurposeId)tempIter.next())) + if (!extendedKeyUsage.hasKeyPurposeId((KeyPurposeId)tempIter.next())) { return false; } @@ -2265,30 +2179,21 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.CertificatePolicies - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (data == null) { return false; } if (!policyOID.isEmpty()) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration policySequence = ((ASN1Sequence)derInputStream - .readObject()).getObjects(); + ASN1Sequence seq = ASN1Sequence.getInstance( + ASN1OctetString.getInstance(data).getOctets()); + Enumeration policySequence = seq.getObjects(); ASN1Sequence policyObject; boolean test = false; while (policySequence.hasMoreElements() && !test) { - policyObject = (ASN1Sequence)policySequence - .nextElement(); + policyObject = (ASN1Sequence)policySequence.nextElement(); if (policyOID.contains(policyObject.getObjectAt(0))) { test = true; @@ -2309,20 +2214,14 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectAlternativeName - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.SubjectAlternativeName.getId()); if (data == null) { return false; } - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration altNamesSequence = ((ASN1Sequence)derInputStream.readObject()).getObjects(); + ASN1Sequence seq = ASN1Sequence.getInstance( + ASN1OctetString.getInstance(data).getOctets()); + Enumeration altNamesSequence = seq.getObjects(); boolean test = false; Set testSet = new HashSet(subjectAltNamesByte); while (altNamesSequence.hasMoreElements() && !test) @@ -2386,8 +2285,7 @@ public Object clone() } if (subjectPublicKeyByte != null) { - copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte - .clone(); + copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte.clone(); } if (keyUsage != null) { @@ -2395,22 +2293,16 @@ public Object clone() } if (keyPurposeSet != null) { - copy.keyPurposeSet = new HashSet(keyPurposeSet); + copy.keyPurposeSet = keyPurposeSet; } if (policy != null) { - copy.policy = new HashSet(policy); - copy.policyOID = new HashSet(); - Iterator iter = policyOID.iterator(); - while (iter.hasNext()) - { - copy.policyOID.add(new ASN1ObjectIdentifier( - ((ASN1ObjectIdentifier)iter.next()).getId())); - } + copy.policy = policy; + copy.policyOID = policyOID; } if (subjectAltNames != null) { - copy.subjectAltNames = new HashSet(getSubjectAlternativeNames()); + copy.subjectAltNames = (Set)getSubjectAlternativeNames(); Iterator iter = subjectAltNamesByte.iterator(); List obj; List cloneObj; @@ -2425,7 +2317,7 @@ public Object clone() } if (pathToNames != null) { - copy.pathToNames = new HashSet(getPathToNames()); + copy.pathToNames = (Set)getPathToNames(); Iterator iter = pathToNamesByte.iterator(); List obj; List cloneObj; diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/slhdsa/Fors.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/slhdsa/Fors.java new file mode 100644 index 0000000000..0578f53a53 --- /dev/null +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/slhdsa/Fors.java @@ -0,0 +1,168 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.math.BigInteger; +import java.util.ArrayList; + +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; + +class Fors +{ + SLHDSAEngine engine; + + public Fors(SLHDSAEngine engine) + { + this.engine = engine; + } + + // Input: Secret seed SK.seed, start index s, target node height z, public seed PK.seed, address ADRS + // Output: n-byte root node - top node on Stack + byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) + { + if ((s >>> z) << z != s) + { + return null; + } + + ArrayList stack = new ArrayList(); + ADRS adrs = new ADRS(adrsParam); + + for (int idx = 0; idx < (1 << z); idx++) + { + adrs.setTypeAndClear(ADRS.FORS_PRF); + adrs.setKeyPairAddress(adrsParam.getKeyPairAddress()); + adrs.setTreeHeight(0); + adrs.setTreeIndex(s + idx); + + byte[] sk = engine.PRF(pkSeed, skSeed, adrs); + + adrs.changeType(ADRS.FORS_TREE); + + byte[] node = engine.F(pkSeed, adrs, sk); + + adrs.setTreeHeight(1); + + int adrsTreeHeight = 1; + int adrsTreeIndex = s + idx; + + // while ( Top node on Stack has same height as node ) + while (!stack.isEmpty() && ((NodeEntry)stack.get(0)).nodeHeight == adrsTreeHeight) + { + adrsTreeIndex = (adrsTreeIndex - 1) / 2; + adrs.setTreeIndex(adrsTreeIndex); + + NodeEntry current = ((NodeEntry)stack.remove(0)); + node = engine.H(pkSeed, adrs, current.nodeValue, node); + + // topmost node is now one layer higher + adrs.setTreeHeight(++adrsTreeHeight); + } + + stack.add(0, new NodeEntry(node, adrsTreeHeight)); + } + + return ((NodeEntry)stack.get(0)).nodeValue; + } + + public SIG_FORS[] sign(byte[] md, byte[] skSeed, byte[] pkSeed, ADRS paramAdrs) + { + ADRS adrs = new ADRS(paramAdrs); + +// int[] idxs = message_to_idxs(md, engine.K, engine.A); + int[] idxs = base2B(md, engine.A, engine.K); + SIG_FORS[] sig_fors = new SIG_FORS[engine.K]; +// compute signature elements + int t = engine.T; + for (int i = 0; i < engine.K; i++) + { +// get next index + int idx = idxs[i]; +// pick private key element + adrs.setTypeAndClear(ADRS.FORS_PRF); + adrs.setKeyPairAddress(paramAdrs.getKeyPairAddress()); + adrs.setTreeHeight(0); + adrs.setTreeIndex(i * t + idx); + + byte[] sk = engine.PRF(pkSeed, skSeed, adrs); + + adrs.changeType(ADRS.FORS_TREE); + + byte[][] authPath = new byte[engine.A][]; +// compute auth path + for (int j = 0; j < engine.A; j++) + { + int s = (idx / (1 << j)) ^ 1; + authPath[j] = treehash(skSeed, i * t + s * (1 << j), j, pkSeed, adrs); + } + sig_fors[i] = new SIG_FORS(sk, authPath); + } + return sig_fors; + } + + public byte[] pkFromSig(SIG_FORS[] sig_fors, byte[] message, byte[] pkSeed, ADRS adrs) + { + byte[][] node = new byte[2][]; + byte[][] root = new byte[engine.K][]; + int t = engine.T; + +// int[] idxs = message_to_idxs(message, engine.K, engine.A); + int[] idxs = base2B(message, engine.A, engine.K); + // compute roots + for (int i = 0; i < engine.K; i++) + { + // get next index + int idx = idxs[i]; + // compute leaf + byte[] sk = sig_fors[i].getSK(); + adrs.setTreeHeight(0); + adrs.setTreeIndex(i * t + idx); + node[0] = engine.F(pkSeed, adrs, sk); + // compute root from leaf and AUTH + byte[][] authPath = sig_fors[i].getAuthPath(); + + adrs.setTreeIndex(i * t + idx); + for (int j = 0; j < engine.A; j++) + { + adrs.setTreeHeight(j + 1); + if (((idx / (1 << j)) % 2) == 0) + { + adrs.setTreeIndex(adrs.getTreeIndex() / 2); + node[1] = engine.H(pkSeed, adrs, node[0], authPath[j]); + } + else + { + adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2); + node[1] = engine.H(pkSeed, adrs, authPath[j], node[0]); + } + node[0] = node[1]; + } + root[i] = node[0]; + } + ADRS forspkADRS = new ADRS(adrs); // copy address to create FTS public key address + forspkADRS.setTypeAndClear(ADRS.FORS_PK); + forspkADRS.setKeyPairAddress(adrs.getKeyPairAddress()); + return engine.T_l(pkSeed, forspkADRS, Arrays.concatenate(root)); + } + + static int[] base2B(byte[] msg, int b, int outLen) + { + int[] baseB = new int[outLen]; + int i = 0; + int bits = 0; + BigInteger total = BigIntegers.ZERO; + + for (int o = 0; o < outLen; o++) + { + while (bits < b) + { + total = total.shiftLeft(8).add(BigInteger.valueOf(msg[i] & 0xff)); + i+= 1; + bits += 8; + } + bits -= b; + baseB[o] = (total.shiftRight(bits).mod(BigInteger.valueOf(2).pow(b))).intValue(); + } + + return baseB; + } +} diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/slhdsa/HT.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/slhdsa/HT.java new file mode 100644 index 0000000000..bfd9098dc2 --- /dev/null +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/slhdsa/HT.java @@ -0,0 +1,214 @@ +package org.bouncycastle.pqc.crypto.slhdsa; + +import java.util.ArrayList; + +import org.bouncycastle.util.Arrays; + +class HT +{ + private final byte[] skSeed; + private final byte[] pkSeed; + SLHDSAEngine engine; + WotsPlus wots; + + final byte[] htPubKey; + + public HT(SLHDSAEngine engine, byte[] skSeed, byte[] pkSeed) + { + this.skSeed = skSeed; + this.pkSeed = pkSeed; + + this.engine = engine; + this.wots = new WotsPlus(engine); + + ADRS adrs = new ADRS(); + adrs.setLayerAddress(engine.D - 1); + adrs.setTreeAddress(0); + + if (skSeed != null) + { + htPubKey = xmss_PKgen(skSeed, pkSeed, adrs); + } + else + { + htPubKey = null; + } + } + + byte[] sign(byte[] M, long idx_tree, int idx_leaf) + { + // init + ADRS adrs = new ADRS(); + // sign + // adrs.setType(ADRS.TREE); + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + SIG_XMSS SIG_tmp = xmss_sign(M, skSeed, idx_leaf, pkSeed, adrs); + SIG_XMSS[] SIG_HT = new SIG_XMSS[engine.D]; + SIG_HT[0] = SIG_tmp; + + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + + byte[] root = xmss_pkFromSig(idx_leaf, SIG_tmp, M, pkSeed, adrs); + + for (int j = 1; j < engine.D; j++) + { + idx_leaf = (int)(idx_tree & ((1 << engine.H_PRIME) - 1)); // least significant bits of idx_tree; + idx_tree >>>= engine.H_PRIME; // most significant bits of idx_tree; + adrs.setLayerAddress(j); + adrs.setTreeAddress(idx_tree); + SIG_tmp = xmss_sign(root, skSeed, idx_leaf, pkSeed, adrs); + SIG_HT[j] = SIG_tmp; + if (j < engine.D - 1) + { + root = xmss_pkFromSig(idx_leaf, SIG_tmp, root, pkSeed, adrs); + } + } + + byte[][] totSigs = new byte[SIG_HT.length][]; + for (int i = 0; i != totSigs.length; i++) + { + totSigs[i] = Arrays.concatenate(SIG_HT[i].sig, Arrays.concatenate(SIG_HT[i].auth)); + } + + return Arrays.concatenate(totSigs); + } + + byte[] xmss_PKgen(byte[] skSeed, byte[] pkSeed, ADRS adrs) + { + return treehash(skSeed, 0, engine.H_PRIME, pkSeed, adrs); + } + + // Input: index idx, XMSS signature SIG_XMSS = (sig || AUTH), n-byte message M, public seed PK.seed, address ADRS + // Output: n-byte root value node[0] + byte[] xmss_pkFromSig(int idx, SIG_XMSS sig_xmss, byte[] M, byte[] pkSeed, ADRS paramAdrs) + { + ADRS adrs = new ADRS(paramAdrs); + + // compute WOTS+ pk from WOTS+ sig + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(idx); + byte[] sig = sig_xmss.getWOTSSig(); + byte[][] AUTH = sig_xmss.getXMSSAUTH(); + + byte[] node0 = wots.pkFromSig(sig, M, pkSeed, adrs); + byte[] node1 = null; + + // compute root from WOTS+ pk and AUTH + adrs.setTypeAndClear(ADRS.TREE); + adrs.setTreeIndex(idx); + for (int k = 0; k < engine.H_PRIME; k++) + { + adrs.setTreeHeight(k + 1); + if (((idx / (1 << k)) % 2) == 0) + { + adrs.setTreeIndex(adrs.getTreeIndex() / 2); + node1 = engine.H(pkSeed, adrs, node0, AUTH[k]); + } + else + { + adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2); + node1 = engine.H(pkSeed, adrs, AUTH[k], node0); + } + node0 = node1; + } + return node0; + } + + // # Input: n-byte message M, secret seed SK.seed, index idx, public seed PK.seed, + // address ADRS + // # Output: XMSS signature SIG_XMSS = (sig || AUTH) + SIG_XMSS xmss_sign(byte[] M, byte[] skSeed, int idx, byte[] pkSeed, ADRS paramAdrs) + { + byte[][] AUTH = new byte[engine.H_PRIME][]; + + ADRS adrs = new ADRS(paramAdrs); + + adrs.setTypeAndClear(ADRS.TREE); + adrs.setLayerAddress(paramAdrs.getLayerAddress()); + adrs.setTreeAddress(paramAdrs.getTreeAddress()); + + // build authentication path + for (int j = 0; j < engine.H_PRIME; j++) + { + int k = (idx >>> j) ^ 1; + AUTH[j] = treehash(skSeed, k << j, j, pkSeed, adrs); + } + adrs = new ADRS(paramAdrs); + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(idx); + + byte[] sig = wots.sign(M, skSeed, pkSeed, adrs); + + return new SIG_XMSS(sig, AUTH); + } + + // Input: Secret seed SK.seed, start index s, target node height z, public seed PK.seed, address ADRS + // Output: n-byte root node - top node on Stack + byte[] treehash(byte[] skSeed, int s, int z, byte[] pkSeed, ADRS adrsParam) + { + if ((s >>> z) << z != s) + { + return null; + } + + ArrayList stack = new ArrayList(); + ADRS adrs = new ADRS(adrsParam); + + for (int idx = 0; idx < (1 << z); idx++) + { + adrs.setTypeAndClear(ADRS.WOTS_HASH); + adrs.setKeyPairAddress(s + idx); + byte[] node = wots.pkGen(skSeed, pkSeed, adrs); + + adrs.setTypeAndClear(ADRS.TREE); + adrs.setTreeHeight(1); + adrs.setTreeIndex(s + idx); + + int adrsTreeHeight = 1; + int adrsTreeIndex = s + idx; + + // while ( Top node on Stack has same height as node ) + while (!stack.isEmpty() && ((NodeEntry)stack.get(0)).nodeHeight == adrsTreeHeight) + { + adrsTreeIndex = (adrsTreeIndex - 1) / 2; + adrs.setTreeIndex(adrsTreeIndex); + + NodeEntry current = ((NodeEntry)stack.remove(0)); + node = engine.H(pkSeed, adrs, current.nodeValue, node); + + // topmost node is now one layer higher + adrs.setTreeHeight(++adrsTreeHeight); + } + + stack.add(0, new NodeEntry(node, adrsTreeHeight)); + } + + return ((NodeEntry)stack.get(0)).nodeValue; + } + + // # Input: Message M, signature SIG_HT, public seed PK.seed, tree index idx_tree, +// leaf index idx_leaf, HT public key PK_HT. +// # Output: Boolean + public boolean verify(byte[] M, SIG_XMSS[] sig_ht, byte[] pkSeed, long idx_tree, int idx_leaf, byte[] PK_HT) + { + // init + ADRS adrs = new ADRS(); + // verify + SIG_XMSS SIG_tmp = sig_ht[0]; + adrs.setLayerAddress(0); + adrs.setTreeAddress(idx_tree); + byte[] node = xmss_pkFromSig(idx_leaf, SIG_tmp, M, pkSeed, adrs); + for (int j = 1; j < engine.D; j++) + { + idx_leaf = (int)(idx_tree & ((1 << engine.H_PRIME) - 1)); // least significant bits of idx_tree; + idx_tree >>>= engine.H_PRIME; // most significant bits of idx_tree; + SIG_tmp = sig_ht[j]; + adrs.setLayerAddress(j); + adrs.setTreeAddress(idx_tree); + node = xmss_pkFromSig(idx_leaf, SIG_tmp, node, pkSeed, adrs); + } + return Arrays.areEqual(PK_HT, node); + } +} diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java index df725ebc8a..db7f61dbe3 100644 --- a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java @@ -13,6 +13,7 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -29,19 +30,26 @@ import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPrivateKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPrivateKeyParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicPrivateKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; import org.bouncycastle.pqc.crypto.saber.SABERPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPrivateKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PrivateKeyParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; @@ -103,10 +111,22 @@ public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) AlgorithmIdentifier algId = keyInfo.getPrivateKeyAlgorithm(); ASN1ObjectIdentifier algOID = algId.getAlgorithm(); - if (algOID.equals(PQCObjectIdentifiers.newHope)) + if (algOID.equals(PQCObjectIdentifiers.sphincs256)) + { + return new SPHINCSPrivateKeyParameters(ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(), + Utils.sphincs256LookupTreeAlgName(SPHINCS256KeyParams.getInstance(algId.getParameters()))); + } + else if (algOID.equals(PQCObjectIdentifiers.newHope)) { return new NHPrivateKeyParameters(convert(ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets())); } + else if (Utils.shldsaParams.containsKey(algOID)) + { + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(algOID); + + ASN1Encodable obj = keyInfo.parsePrivateKey(); + return new SLHDSAPrivateKeyParameters(spParams, ASN1OctetString.getInstance(obj).getOctets()); + } else if (algOID.on(BCObjectIdentifiers.picnic)) { byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(); @@ -135,18 +155,75 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_saber)) return new SABERPrivateKeyParameters(spParams, keyEnc); } - else if (algOID.on(BCObjectIdentifiers.pqc_kem_kyber)) + else if (algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_512) || + algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_768) || + algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_1024)) { ASN1OctetString kyberKey = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()); - KyberParameters kyberParams = Utils.kyberParamsLookup(algOID); + MLKEMParameters kyberParams = Utils.mlkemParamsLookup(algOID); - return new KyberPrivateKeyParameters(kyberParams, kyberKey.getOctets()); + return new MLKEMPrivateKeyParameters(kyberParams, kyberKey.getOctets()); + } + else if (Utils.mldsaParams.containsKey(algOID)) + { + ASN1Encodable keyObj = keyInfo.parsePrivateKey(); + MLDSAParameters spParams = Utils.mldsaParamsLookup(algOID); + + if (keyObj instanceof ASN1Sequence) + { + ASN1Sequence keyEnc = ASN1Sequence.getInstance(keyObj); + + int version = ASN1Integer.getInstance(keyEnc.getObjectAt(0)).intValueExact(); + if (version != 0) + { + throw new IOException("unknown private key version: " + version); + } + + if (keyInfo.getPublicKeyData() != null) + { + MLDSAPublicKeyParameters pubParams = PublicKeyFactory.MLDSAConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); + + return new MLDSAPrivateKeyParameters(spParams, + ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(4)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(5)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(6)).getOctets(), + pubParams.getT1()); // encT1 + } + else + { + return new MLDSAPrivateKeyParameters(spParams, + ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(4)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(5)).getOctets(), + ASN1BitString.getInstance(keyEnc.getObjectAt(6)).getOctets(), + null); + } + } + else if (keyObj instanceof DEROctetString) + { + byte[] data = ASN1OctetString.getInstance(keyObj).getOctets(); + if (keyInfo.getPublicKeyData() != null) + { + MLDSAPublicKeyParameters pubParams = PublicKeyFactory.MLDSAConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); + return new MLDSAPrivateKeyParameters(spParams, data, pubParams); + } + return new MLDSAPrivateKeyParameters(spParams, data); + } + else + { + throw new IOException("not supported"); + } } else if (algOID.equals(BCObjectIdentifiers.dilithium2) || algOID.equals(BCObjectIdentifiers.dilithium3) || algOID.equals(BCObjectIdentifiers.dilithium5)) { ASN1Encodable keyObj = keyInfo.parsePrivateKey(); - DilithiumParameters spParams = Utils.dilithiumParamsLookup(algOID); + DilithiumParameters dilParams = Utils.dilithiumParamsLookup(algOID); if (keyObj instanceof ASN1Sequence) { @@ -160,9 +237,9 @@ else if (algOID.equals(BCObjectIdentifiers.dilithium2) if (keyInfo.getPublicKeyData() != null) { - DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); + DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(dilParams, keyInfo.getPublicKeyData()); - return new DilithiumPrivateKeyParameters(spParams, + return new DilithiumPrivateKeyParameters(dilParams, ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), @@ -173,7 +250,7 @@ else if (algOID.equals(BCObjectIdentifiers.dilithium2) } else { - return new DilithiumPrivateKeyParameters(spParams, + return new DilithiumPrivateKeyParameters(dilParams, ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), @@ -188,10 +265,10 @@ else if (keyObj instanceof DEROctetString) byte[] data = ASN1OctetString.getInstance(keyObj).getOctets(); if (keyInfo.getPublicKeyData() != null) { - DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); - return new DilithiumPrivateKeyParameters(spParams, data, pubParams); + DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(dilParams, keyInfo.getPublicKeyData()); + return new DilithiumPrivateKeyParameters(dilParams, data, pubParams); } - return new DilithiumPrivateKeyParameters(spParams, data, null); + return new DilithiumPrivateKeyParameters(dilParams, data, null); } else { @@ -222,6 +299,12 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_hqc)) return new HQCPrivateKeyParameters(hqcParams, keyEnc); } + else if (algOID.equals(PQCObjectIdentifiers.mcElieceCca2)) + { + McElieceCCA2PrivateKey mKey = McElieceCCA2PrivateKey.getInstance(keyInfo.parsePrivateKey()); + + return new McElieceCCA2PrivateKeyParameters(mKey.getN(), mKey.getK(), mKey.getField(), mKey.getGoppaPoly(), mKey.getP(), Utils.getDigestName(mKey.getDigest().getAlgorithm())); + } else { throw new RuntimeException("algorithm identifier in private key not recognised"); diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java index 9702a393bc..0363f6ef51 100644 --- a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java @@ -21,13 +21,18 @@ import org.bouncycastle.pqc.crypto.cmce.CMCEPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPrivateKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPrivateKeyParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicPrivateKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPrivateKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PrivateKeyParameters; import org.bouncycastle.util.Pack; /** @@ -61,7 +66,15 @@ public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter private */ public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey, ASN1Set attributes) throws IOException { - if (privateKey instanceof NHPrivateKeyParameters) + if (privateKey instanceof SPHINCSPrivateKeyParameters) + { + SPHINCSPrivateKeyParameters params = (SPHINCSPrivateKeyParameters)privateKey; + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.sphincs256, + new SPHINCS256KeyParams(Utils.sphincs256LookupTreeAlgID(params.getTreeDigest()))); + + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getKeyData())); + } + else if (privateKey instanceof NHPrivateKeyParameters) { NHPrivateKeyParameters params = (NHPrivateKeyParameters)privateKey; @@ -77,6 +90,14 @@ public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter private return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(octets)); } + else if (privateKey instanceof SLHDSAPrivateKeyParameters) + { + SLHDSAPrivateKeyParameters params = (SLHDSAPrivateKeyParameters)privateKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.slhdsaOidLookup(params.getParameters())); + + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes, params.getPublicKey()); + } else if (privateKey instanceof PicnicPrivateKeyParameters) { PicnicPrivateKeyParameters params = (PicnicPrivateKeyParameters)privateKey; @@ -99,6 +120,14 @@ else if (privateKey instanceof CMCEPrivateKeyParameters) CMCEPrivateKey cmcePriv = new CMCEPrivateKey(0, params.getDelta(), params.getC(), params.getG(), params.getAlpha(), params.getS(), cmcePub); return new PrivateKeyInfo(algorithmIdentifier, cmcePriv, attributes); } + else if (privateKey instanceof McElieceCCA2PrivateKeyParameters) + { + McElieceCCA2PrivateKeyParameters priv = (McElieceCCA2PrivateKeyParameters)privateKey; + McElieceCCA2PrivateKey mcEliecePriv = new McElieceCCA2PrivateKey(priv.getN(), priv.getK(), priv.getField(), priv.getGoppaPoly(), priv.getP(), Utils.getAlgorithmIdentifier(priv.getDigest())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.mcElieceCca2); + + return new PrivateKeyInfo(algorithmIdentifier, mcEliecePriv); + } else if (privateKey instanceof FrodoPrivateKeyParameters) { FrodoPrivateKeyParameters params = (FrodoPrivateKeyParameters)privateKey; @@ -130,13 +159,41 @@ else if (privateKey instanceof FalconPrivateKeyParameters) return new PrivateKeyInfo(algorithmIdentifier, falconPriv, attributes); } - else if (privateKey instanceof KyberPrivateKeyParameters) + else if (privateKey instanceof MLKEMPrivateKeyParameters) { - KyberPrivateKeyParameters params = (KyberPrivateKeyParameters)privateKey; + MLKEMPrivateKeyParameters params = (MLKEMPrivateKeyParameters)privateKey; - AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.kyberOidLookup(params.getParameters())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mlkemOidLookup(params.getParameters())); + + byte[] seed = params.getSeed(); + if (seed == null) + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + } + else + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(seed), attributes); + } + } + else if (privateKey instanceof MLDSAPrivateKeyParameters) + { + MLDSAPrivateKeyParameters params = (MLDSAPrivateKeyParameters)privateKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mldsaOidLookup(params.getParameters())); - return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + byte[] seed = params.getSeed(); + if (seed == null) + { + MLDSAPublicKeyParameters pubParams = params.getPublicKeyParameters(); + + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes, pubParams.getEncoded()); + } + else + { + MLDSAPublicKeyParameters pubParams = params.getPublicKeyParameters(); + + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getSeed()), attributes); + } } else if (privateKey instanceof DilithiumPrivateKeyParameters) { diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java index 10908bd5a4..45ea1332a1 100644 --- a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java @@ -12,13 +12,14 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; -import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; import org.bouncycastle.pqc.asn1.CMCEPublicKey; -import org.bouncycastle.pqc.asn1.KyberPublicKey; +import org.bouncycastle.pqc.asn1.McElieceCCA2PublicKey; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; import org.bouncycastle.pqc.crypto.bike.BIKEParameters; @@ -27,19 +28,25 @@ import org.bouncycastle.pqc.crypto.cmce.CMCEPublicKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPublicKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicPublicKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; import org.bouncycastle.pqc.crypto.saber.SABERPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPublicKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PublicKeyParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; @@ -53,10 +60,9 @@ public class PublicKeyFactory static { + converters.put(PQCObjectIdentifiers.sphincs256, new SPHINCSConverter()); converters.put(PQCObjectIdentifiers.newHope, new NHConverter()); - - - + converters.put(PQCObjectIdentifiers.mcElieceCca2, new McElieceCCA2Converter()); converters.put(BCObjectIdentifiers.mceliece348864_r3, new CMCEConverter()); converters.put(BCObjectIdentifiers.mceliece348864f_r3, new CMCEConverter()); converters.put(BCObjectIdentifiers.mceliece460896_r3, new CMCEConverter()); @@ -105,12 +111,18 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.picnicl5full, new PicnicConverter()); converters.put(BCObjectIdentifiers.falcon_512, new FalconConverter()); converters.put(BCObjectIdentifiers.falcon_1024, new FalconConverter()); - converters.put(BCObjectIdentifiers.kyber512, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber768, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber1024, new KyberConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_512, new KyberConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_768, new KyberConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, new KyberConverter()); converters.put(BCObjectIdentifiers.kyber512_aes, new KyberConverter()); converters.put(BCObjectIdentifiers.kyber768_aes, new KyberConverter()); converters.put(BCObjectIdentifiers.kyber1024_aes, new KyberConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_44, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_65, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_87, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, new MLDSAConverter()); converters.put(BCObjectIdentifiers.dilithium2, new DilithiumConverter()); converters.put(BCObjectIdentifiers.dilithium3, new DilithiumConverter()); converters.put(BCObjectIdentifiers.dilithium5, new DilithiumConverter()); @@ -123,6 +135,31 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.hqc128, new HQCConverter()); converters.put(BCObjectIdentifiers.hqc192, new HQCConverter()); converters.put(BCObjectIdentifiers.hqc256, new HQCConverter()); + + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, new SLHDSAConverter()); } /** @@ -211,6 +248,17 @@ abstract AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyI throws IOException; } + private static class SPHINCSConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + return new SPHINCSPublicKeyParameters(keyInfo.getPublicKeyData().getBytes(), + Utils.sphincs256LookupTreeAlgName(SPHINCS256KeyParams.getInstance(keyInfo.getAlgorithm().getParameters()))); + } + } + private static class NHConverter extends SubjectPublicKeyInfoConverter { @@ -221,6 +269,7 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } + private static class CMCEConverter extends SubjectPublicKeyInfoConverter { @@ -261,6 +310,18 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } + private static class McElieceCCA2Converter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + McElieceCCA2PublicKey mKey = McElieceCCA2PublicKey.getInstance(keyInfo.parsePublicKey()); + + return new McElieceCCA2PublicKeyParameters(mKey.getN(), mKey.getT(), mKey.getG(), Utils.getDigestName(mKey.getDigest().getAlgorithm())); + } + } + private static class FrodoConverter extends SubjectPublicKeyInfoConverter { @@ -311,35 +372,64 @@ private static class KyberConverter AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { - KyberParameters kyberParameters = Utils.kyberParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + MLKEMParameters kyberParameters = Utils.mlkemParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + // we're a raw encoding + return new MLKEMPublicKeyParameters(kyberParameters, keyInfo.getPublicKeyData().getOctets()); + } + } + + static class DilithiumConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + DilithiumParameters dilithiumParams = Utils.dilithiumParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return getPublicKeyParams(dilithiumParams, keyInfo.getPublicKeyData()); + } + static DilithiumPublicKeyParameters getPublicKeyParams(DilithiumParameters dilithiumParams, ASN1BitString publicKeyData) + { try { - ASN1Primitive obj = keyInfo.parsePublicKey(); - KyberPublicKey kyberKey = KyberPublicKey.getInstance(obj); + ASN1Primitive obj = ASN1Primitive.fromByteArray(publicKeyData.getOctets()); + if (obj instanceof ASN1Sequence) + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(obj); + + return new DilithiumPublicKeyParameters(dilithiumParams, + ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(), + ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets()); + } + else + { + byte[] encKey = ASN1OctetString.getInstance(obj).getOctets(); - return new KyberPublicKeyParameters(kyberParameters, kyberKey.getT(), kyberKey.getRho()); + return new DilithiumPublicKeyParameters(dilithiumParams, encKey); + } } catch (Exception e) { // we're a raw encoding - return new KyberPublicKeyParameters(kyberParameters, keyInfo.getPublicKeyData().getOctets()); + return new DilithiumPublicKeyParameters(dilithiumParams, publicKeyData.getOctets()); } } } - static class DilithiumConverter + static class MLDSAConverter extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { - DilithiumParameters dilithiumParams = Utils.dilithiumParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + MLDSAParameters dilithiumParams = Utils.mldsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); return getPublicKeyParams(dilithiumParams, keyInfo.getPublicKeyData()); } - static DilithiumPublicKeyParameters getPublicKeyParams(DilithiumParameters dilithiumParams, ASN1BitString publicKeyData) + static MLDSAPublicKeyParameters getPublicKeyParams(MLDSAParameters dilithiumParams, ASN1BitString publicKeyData) { try { @@ -348,7 +438,7 @@ static DilithiumPublicKeyParameters getPublicKeyParams(DilithiumParameters dilit { ASN1Sequence keySeq = ASN1Sequence.getInstance(obj); - return new DilithiumPublicKeyParameters(dilithiumParams, + return new MLDSAPublicKeyParameters(dilithiumParams, ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(), ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets()); } @@ -356,13 +446,13 @@ static DilithiumPublicKeyParameters getPublicKeyParams(DilithiumParameters dilit { byte[] encKey = ASN1OctetString.getInstance(obj).getOctets(); - return new DilithiumPublicKeyParameters(dilithiumParams, encKey); + return new MLDSAPublicKeyParameters(dilithiumParams, encKey); } } catch (Exception e) { // we're a raw encoding - return new DilithiumPublicKeyParameters(dilithiumParams, publicKeyData.getOctets()); + return new MLDSAPublicKeyParameters(dilithiumParams, publicKeyData.getOctets()); } } } @@ -417,4 +507,29 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } } + + private static class SLHDSAConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + try + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SLHDSAPublicKeyParameters(spParams, Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); + } + catch (Exception e) + { + byte[] keyEnc = keyInfo.getPublicKeyData().getOctets(); + + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SLHDSAPublicKeyParameters(spParams, keyEnc); + } + } + } } diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java index 66e3ae3960..579822a06e 100644 --- a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java @@ -4,23 +4,28 @@ import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; +import org.bouncycastle.pqc.asn1.McElieceCCA2PublicKey; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; import org.bouncycastle.pqc.crypto.bike.BIKEPublicKeyParameters; import org.bouncycastle.pqc.crypto.cmce.CMCEPublicKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPublicKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicPublicKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPublicKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PublicKeyParameters; /** * Factory to create ASN.1 subject public key info objects from lightweight public keys. @@ -42,13 +47,30 @@ private SubjectPublicKeyInfoFactory() public static SubjectPublicKeyInfo createSubjectPublicKeyInfo(AsymmetricKeyParameter publicKey) throws IOException { - if (publicKey instanceof NHPublicKeyParameters) + if (publicKey instanceof SPHINCSPublicKeyParameters) + { + SPHINCSPublicKeyParameters params = (SPHINCSPublicKeyParameters)publicKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.sphincs256, + new SPHINCS256KeyParams(Utils.sphincs256LookupTreeAlgID(params.getTreeDigest()))); + return new SubjectPublicKeyInfo(algorithmIdentifier, params.getKeyData()); + } + else if (publicKey instanceof NHPublicKeyParameters) { NHPublicKeyParameters params = (NHPublicKeyParameters)publicKey; AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.newHope); return new SubjectPublicKeyInfo(algorithmIdentifier, params.getPubData()); } + else if (publicKey instanceof SLHDSAPublicKeyParameters) + { + SLHDSAPublicKeyParameters params = (SLHDSAPublicKeyParameters)publicKey; + + byte[] encoding = params.getEncoded(); + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.slhdsaOidLookup(params.getParameters())); + return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); + } else if (publicKey instanceof CMCEPublicKeyParameters) { CMCEPublicKeyParameters params = (CMCEPublicKeyParameters)publicKey; @@ -59,6 +81,14 @@ else if (publicKey instanceof CMCEPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); } + else if (publicKey instanceof McElieceCCA2PublicKeyParameters) + { + McElieceCCA2PublicKeyParameters pub = (McElieceCCA2PublicKeyParameters)publicKey; + McElieceCCA2PublicKey mcEliecePub = new McElieceCCA2PublicKey(pub.getN(), pub.getT(), pub.getG(), Utils.getAlgorithmIdentifier(pub.getDigest())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.mcElieceCca2); + + return new SubjectPublicKeyInfo(algorithmIdentifier, mcEliecePub); + } else if (publicKey instanceof FrodoPublicKeyParameters) { FrodoPublicKeyParameters params = (FrodoPublicKeyParameters)publicKey; @@ -101,11 +131,11 @@ else if (publicKey instanceof FalconPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, keyEnc); } - else if (publicKey instanceof KyberPublicKeyParameters) + else if (publicKey instanceof MLKEMPublicKeyParameters) { - KyberPublicKeyParameters params = (KyberPublicKeyParameters)publicKey; + MLKEMPublicKeyParameters params = (MLKEMPublicKeyParameters)publicKey; - AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.kyberOidLookup(params.getParameters())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mlkemOidLookup(params.getParameters())); return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); } @@ -117,6 +147,14 @@ else if (publicKey instanceof DilithiumPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); } + else if (publicKey instanceof MLDSAPublicKeyParameters) + { + MLDSAPublicKeyParameters params = (MLDSAPublicKeyParameters)publicKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mldsaOidLookup(params.getParameters())); + + return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); + } else if (publicKey instanceof BIKEPublicKeyParameters) { BIKEPublicKeyParameters params = (BIKEPublicKeyParameters) publicKey; diff --git a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/Utils.java b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/Utils.java index 076e69ae32..e880abfdb6 100644 --- a/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/Utils.java +++ b/core/src/main/jdk1.1/org/bouncycastle/pqc/crypto/util/Utils.java @@ -7,30 +7,37 @@ import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; import org.bouncycastle.pqc.crypto.bike.BIKEParameters; import org.bouncycastle.pqc.crypto.cmce.CMCEParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.sphincs.SPHINCSKeyParameters; import org.bouncycastle.util.Integers; class Utils { + static final AlgorithmIdentifier AlgID_qTESLA_p_I = new AlgorithmIdentifier(PQCObjectIdentifiers.qTESLA_p_I); + static final AlgorithmIdentifier AlgID_qTESLA_p_III = new AlgorithmIdentifier(PQCObjectIdentifiers.qTESLA_p_III); + static final AlgorithmIdentifier SPHINCS_SHA3_256 = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha3_256); static final AlgorithmIdentifier SPHINCS_SHA512_256 = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_256); + static final Map categories = new HashMap(); static final Map picnicOids = new HashMap(); @@ -45,9 +52,6 @@ class Utils static final Map mcElieceOids = new HashMap(); static final Map mcElieceParams = new HashMap(); - static final Map sphincsPlusOids = new HashMap(); - static final Map sphincsPlusParams = new HashMap(); - static final Map sikeOids = new HashMap(); static final Map sikeParams = new HashMap(); @@ -57,9 +61,6 @@ class Utils static final Map falconOids = new HashMap(); static final Map falconParams = new HashMap(); - static final Map kyberOids = new HashMap(); - static final Map kyberParams = new HashMap(); - static final Map ntruprimeOids = new HashMap(); static final Map ntruprimeParams = new HashMap(); @@ -78,6 +79,15 @@ class Utils static final Map rainbowOids = new HashMap(); static final Map rainbowParams = new HashMap(); + static final Map mlkemOids = new HashMap(); + static final Map mlkemParams = new HashMap(); + + static final Map mldsaOids = new HashMap(); + static final Map mldsaParams = new HashMap(); + + static final Map shldsaOids = new HashMap(); + static final Map shldsaParams = new HashMap(); + static { mcElieceOids.put(CMCEParameters.mceliece348864r3, BCObjectIdentifiers.mceliece348864_r3); @@ -180,25 +190,33 @@ class Utils picnicParams.put(BCObjectIdentifiers.picnicl3full, PicnicParameters.picnicl3full); picnicParams.put(BCObjectIdentifiers.picnicl5full, PicnicParameters.picnicl5full); - - falconOids.put(FalconParameters.falcon_512, BCObjectIdentifiers.falcon_512); falconOids.put(FalconParameters.falcon_1024, BCObjectIdentifiers.falcon_1024); falconParams.put(BCObjectIdentifiers.falcon_512, FalconParameters.falcon_512); falconParams.put(BCObjectIdentifiers.falcon_1024, FalconParameters.falcon_1024); - kyberOids.put(KyberParameters.kyber512, BCObjectIdentifiers.kyber512); - kyberOids.put(KyberParameters.kyber768, BCObjectIdentifiers.kyber768); - kyberOids.put(KyberParameters.kyber1024, BCObjectIdentifiers.kyber1024); - - kyberParams.put(BCObjectIdentifiers.kyber512, KyberParameters.kyber512); - kyberParams.put(BCObjectIdentifiers.kyber768, KyberParameters.kyber768); - kyberParams.put(BCObjectIdentifiers.kyber1024, KyberParameters.kyber1024); - + mlkemOids.put(MLKEMParameters.ml_kem_512, NISTObjectIdentifiers.id_alg_ml_kem_512); + mlkemOids.put(MLKEMParameters.ml_kem_768, NISTObjectIdentifiers.id_alg_ml_kem_768); + mlkemOids.put(MLKEMParameters.ml_kem_1024,NISTObjectIdentifiers.id_alg_ml_kem_1024); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_512, MLKEMParameters.ml_kem_512); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_768, MLKEMParameters.ml_kem_768); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, MLKEMParameters.ml_kem_1024); + mldsaOids.put(MLDSAParameters.ml_dsa_44, NISTObjectIdentifiers.id_ml_dsa_44); + mldsaOids.put(MLDSAParameters.ml_dsa_65, NISTObjectIdentifiers.id_ml_dsa_65); + mldsaOids.put(MLDSAParameters.ml_dsa_87, NISTObjectIdentifiers.id_ml_dsa_87); + mldsaOids.put(MLDSAParameters.ml_dsa_44_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + mldsaOids.put(MLDSAParameters.ml_dsa_65_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + mldsaOids.put(MLDSAParameters.ml_dsa_87_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_44, MLDSAParameters.ml_dsa_44); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_65, MLDSAParameters.ml_dsa_65); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_87, MLDSAParameters.ml_dsa_87); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, MLDSAParameters.ml_dsa_44_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, MLDSAParameters.ml_dsa_65_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, MLDSAParameters.ml_dsa_87_with_sha512); dilithiumOids.put(DilithiumParameters.dilithium2, BCObjectIdentifiers.dilithium2); dilithiumOids.put(DilithiumParameters.dilithium3, BCObjectIdentifiers.dilithium3); @@ -224,13 +242,103 @@ class Utils hqcOids.put(HQCParameters.hqc192, BCObjectIdentifiers.hqc192); hqcOids.put(HQCParameters.hqc256, BCObjectIdentifiers.hqc256); + shldsaOids.put(SLHDSAParameters.sha2_128s, NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + shldsaOids.put(SLHDSAParameters.sha2_128f, NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + shldsaOids.put(SLHDSAParameters.sha2_192s, NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + shldsaOids.put(SLHDSAParameters.sha2_192f, NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + shldsaOids.put(SLHDSAParameters.sha2_256s, NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + shldsaOids.put(SLHDSAParameters.sha2_256f, NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + shldsaOids.put(SLHDSAParameters.shake_128s, NISTObjectIdentifiers.id_slh_dsa_shake_128s); + shldsaOids.put(SLHDSAParameters.shake_128f, NISTObjectIdentifiers.id_slh_dsa_shake_128f); + shldsaOids.put(SLHDSAParameters.shake_192s, NISTObjectIdentifiers.id_slh_dsa_shake_192s); + shldsaOids.put(SLHDSAParameters.shake_192f, NISTObjectIdentifiers.id_slh_dsa_shake_192f); + shldsaOids.put(SLHDSAParameters.shake_256s, NISTObjectIdentifiers.id_slh_dsa_shake_256s); + shldsaOids.put(SLHDSAParameters.shake_256f, NISTObjectIdentifiers.id_slh_dsa_shake_256f); + + shldsaOids.put(SLHDSAParameters.sha2_128s_with_sha256, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + shldsaOids.put(SLHDSAParameters.sha2_128f_with_sha256, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + shldsaOids.put(SLHDSAParameters.sha2_192s_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + shldsaOids.put(SLHDSAParameters.sha2_192f_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + shldsaOids.put(SLHDSAParameters.sha2_256s_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + shldsaOids.put(SLHDSAParameters.sha2_256f_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + shldsaOids.put(SLHDSAParameters.shake_128s_with_shake128, NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + shldsaOids.put(SLHDSAParameters.shake_128f_with_shake128, NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + shldsaOids.put(SLHDSAParameters.shake_192s_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + shldsaOids.put(SLHDSAParameters.shake_192f_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + shldsaOids.put(SLHDSAParameters.shake_256s_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + shldsaOids.put(SLHDSAParameters.shake_256f_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, SLHDSAParameters.sha2_128s); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, SLHDSAParameters.sha2_128f); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, SLHDSAParameters.sha2_192s); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, SLHDSAParameters.sha2_192f); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, SLHDSAParameters.sha2_256s); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, SLHDSAParameters.sha2_256f); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, SLHDSAParameters.shake_128s); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, SLHDSAParameters.shake_128f); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, SLHDSAParameters.shake_192s); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, SLHDSAParameters.shake_192f); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, SLHDSAParameters.shake_256s); + shldsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, SLHDSAParameters.shake_256f); + + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, SLHDSAParameters.sha2_128s_with_sha256); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, SLHDSAParameters.sha2_128f_with_sha256); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, SLHDSAParameters.sha2_192s_with_sha512); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, SLHDSAParameters.sha2_192f_with_sha512); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, SLHDSAParameters.sha2_256s_with_sha512); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, SLHDSAParameters.sha2_256f_with_sha512); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, SLHDSAParameters.shake_128s_with_shake128); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, SLHDSAParameters.shake_128f_with_shake128); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, SLHDSAParameters.shake_192s_with_shake256); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, SLHDSAParameters.shake_192f_with_shake256); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, SLHDSAParameters.shake_256s_with_shake256); + shldsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, SLHDSAParameters.shake_256f_with_shake256); + } + static ASN1ObjectIdentifier slhdsaOidLookup(SLHDSAParameters params) + { + return (ASN1ObjectIdentifier)shldsaOids.get(params); + } + static SLHDSAParameters slhdsaParamsLookup(ASN1ObjectIdentifier oid) + { + return (SLHDSAParameters)shldsaParams.get(oid); + } + + static AlgorithmIdentifier sphincs256LookupTreeAlgID(String treeDigest) + { + if (treeDigest.equals(SPHINCSKeyParameters.SHA3_256)) + { + return SPHINCS_SHA3_256; + } + else if (treeDigest.equals(SPHINCSKeyParameters.SHA512_256)) + { + return SPHINCS_SHA512_256; + } + else + { + throw new IllegalArgumentException("unknown tree digest: " + treeDigest); + } + } + static String sphincs256LookupTreeAlgName(SPHINCS256KeyParams keyParams) + { + AlgorithmIdentifier treeDigest = keyParams.getTreeDigest(); - + if (treeDigest.getAlgorithm().equals(SPHINCS_SHA3_256.getAlgorithm())) + { + return SPHINCSKeyParameters.SHA3_256; + } + else if (treeDigest.getAlgorithm().equals(SPHINCS_SHA512_256.getAlgorithm())) + { + return SPHINCSKeyParameters.SHA512_256; + } + else + { + throw new IllegalArgumentException("unknown tree digest: " + treeDigest.getAlgorithm()); + } } - + static Digest getDigest(ASN1ObjectIdentifier oid) { if (oid.equals(NISTObjectIdentifiers.id_sha256)) @@ -355,14 +463,25 @@ static FalconParameters falconParamsLookup(ASN1ObjectIdentifier oid) return (FalconParameters)falconParams.get(oid); } - static ASN1ObjectIdentifier kyberOidLookup(KyberParameters params) + + static ASN1ObjectIdentifier mlkemOidLookup(MLKEMParameters params) + { + return (ASN1ObjectIdentifier)mlkemOids.get(params); + } + + static MLKEMParameters mlkemParamsLookup(ASN1ObjectIdentifier oid) + { + return (MLKEMParameters)mlkemParams.get(oid); + } + + static ASN1ObjectIdentifier mldsaOidLookup(MLDSAParameters params) { - return (ASN1ObjectIdentifier)kyberOids.get(params); + return (ASN1ObjectIdentifier)mldsaOids.get(params); } - static KyberParameters kyberParamsLookup(ASN1ObjectIdentifier oid) + static MLDSAParameters mldsaParamsLookup(ASN1ObjectIdentifier oid) { - return (KyberParameters)kyberParams.get(oid); + return (MLDSAParameters)mldsaParams.get(oid); } static ASN1ObjectIdentifier dilithiumOidLookup(DilithiumParameters params) diff --git a/core/src/main/jdk1.2/org/bouncycastle/math/ec/ECCurve.java b/core/src/main/jdk1.2/org/bouncycastle/math/ec/ECCurve.java index 41e6cc796f..8539b62c24 100644 --- a/core/src/main/jdk1.2/org/bouncycastle/math/ec/ECCurve.java +++ b/core/src/main/jdk1.2/org/bouncycastle/math/ec/ECCurve.java @@ -123,6 +123,19 @@ public synchronized Config configure() return new Config(this.coord, this.endomorphism, this.multiplier); } + public int getFieldElementEncodingLength() + { + return (this.getFieldSize() + 7) / 8; + } + + public int getAffinePointEncodingLength(boolean compressed) + { + int fieldLength = getFieldElementEncodingLength(); + return compressed + ? 1 + fieldLength + : 1 + fieldLength * 2; + } + public ECPoint validatePoint(BigInteger x, BigInteger y) { ECPoint p = createPoint(x, y); @@ -379,7 +392,7 @@ public ECMultiplier getMultiplier() public ECPoint decodePoint(byte[] encoded) { ECPoint p = null; - int expectedLength = (this.getFieldSize() + 7) / 8; + int expectedLength = getFieldElementEncodingLength(); byte type = encoded[0]; switch (type) @@ -463,25 +476,15 @@ public ECPoint decodePoint(byte[] encoded) */ public ECLookupTable createCacheSafeLookupTable(final ECPoint[] points, int off, final int len) { - final int FE_BYTES = (this.getFieldSize() + 7) >>> 3; - + final int FE_BYTES = getFieldElementEncodingLength(); final byte[] table = new byte[len * FE_BYTES * 2]; + int opos = 0; + for (int i = 0; i < len; ++i) { - int pos = 0; - for (int i = 0; i < len; ++i) - { - ECPoint p = points[off + i]; - byte[] px = p.getRawXCoord().toBigInteger().toByteArray(); - byte[] py = p.getRawYCoord().toBigInteger().toByteArray(); - - int pxStart = px.length > FE_BYTES ? 1 : 0, pxLen = px.length - pxStart; - int pyStart = py.length > FE_BYTES ? 1 : 0, pyLen = py.length - pyStart; - - System.arraycopy(px, pxStart, table, pos + FE_BYTES - pxLen, pxLen); pos += FE_BYTES; - System.arraycopy(py, pyStart, table, pos + FE_BYTES - pyLen, pyLen); pos += FE_BYTES; - } + ECPoint p = points[off + i]; + p.getRawXCoord().encodeTo(table, opos); opos += FE_BYTES; + p.getRawYCoord().encodeTo(table, opos); opos += FE_BYTES; } - return new AbstractECLookupTable() { public int getSize() @@ -526,7 +529,7 @@ public ECPoint lookupVar(int index) private ECPoint createPoint(byte[] x, byte[] y) { - return createRawPoint(ECCurve.this.fromBigInteger(new BigInteger(1, x)), ECCurve.this.fromBigInteger(new BigInteger(1, y))); + return createRawPoint(fromBigInteger(new BigInteger(1, x)), fromBigInteger(new BigInteger(1, y))); } }; } @@ -593,9 +596,14 @@ protected AbstractFp(BigInteger q) super(FiniteFields.getPrimeField(q)); } + public BigInteger getQ() + { + return getField().getCharacteristic(); + } + public boolean isValidFieldElement(BigInteger x) { - return x != null && x.signum() >= 0 && x.compareTo(this.getField().getCharacteristic()) < 0; + return x != null && x.signum() >= 0 && x.compareTo(this.getQ()) < 0; } public ECFieldElement randomFieldElement(SecureRandom r) @@ -604,7 +612,7 @@ public ECFieldElement randomFieldElement(SecureRandom r) * NOTE: BigInteger comparisons in the rejection sampling are not constant-time, so we * use the product of two independent elements to mitigate side-channels. */ - BigInteger p = this.getField().getCharacteristic(); + BigInteger p = this.getQ(); ECFieldElement fe1 = this.fromBigInteger(implRandomFieldElement(r, p)); ECFieldElement fe2 = this.fromBigInteger(implRandomFieldElement(r, p)); return fe1.multiply(fe2); @@ -616,7 +624,7 @@ public ECFieldElement randomFieldElementMult(SecureRandom r) * NOTE: BigInteger comparisons in the rejection sampling are not constant-time, so we * use the product of two independent elements to mitigate side-channels. */ - BigInteger p = this.getField().getCharacteristic(); + BigInteger p = this.getQ(); ECFieldElement fe1 = this.fromBigInteger(implRandomFieldElementMult(r, p)); ECFieldElement fe2 = this.fromBigInteger(implRandomFieldElementMult(r, p)); return fe1.multiply(fe2); @@ -699,12 +707,11 @@ public Fp(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger if (isInternal) { - this.q = q; knownQs.add(q); } else if (knownQs.contains(q) || validatedQs.contains(q)) { - this.q = q; + // No need to validate } else { @@ -718,16 +725,15 @@ else if (knownQs.contains(q) || validatedQs.contains(q)) } if (Primes.hasAnySmallFactors(q) || !Primes.isMRProbablePrime( - q, CryptoServicesRegistrar.getSecureRandom(), ECCurve.getNumberOfIterations(qBitLength, certainty))) + q, CryptoServicesRegistrar.getSecureRandom(), this.getNumberOfIterations(qBitLength, certainty))) { throw new IllegalArgumentException("Fp q value not prime"); } validatedQs.add(q); - - this.q = q; } + this.q = q; this.r = ECFieldElement.Fp.calculateResidue(q); this.infinity = new ECPoint.Fp(this, null, null); @@ -845,6 +851,11 @@ public static BigInteger inverse(int m, int[] ks, BigInteger x) private static FiniteField buildField(int m, int k1, int k2, int k3) { + if (m > Properties.asInteger("org.bouncycastle.ec.max_f2m_field_size", 1142)) // twice 571 + { + throw new IllegalArgumentException("field size out of range: " + m); + } + int[] exponents = (k2 | k3) == 0 ? new int[]{ 0, k1, m } : new int[]{ 0, k1, k2, k3, m }; @@ -855,6 +866,15 @@ private static FiniteField buildField(int m, int k1, int k2, int k3) protected AbstractF2m(int m, int k1, int k2, int k3) { super(buildField(m, k1, k2, k3)); + + if (Properties.isOverrideSet("org.bouncycastle.ec.disable")) + { + throw new UnsupportedOperationException("F2M disabled by \"org.bouncycastle.ec.disable\""); + } + if (Properties.isOverrideSet("org.bouncycastle.ec.disable_f2m")) + { + throw new UnsupportedOperationException("F2M disabled by \"org.bouncycastle.ec.disable_f2m\""); + } } public ECPoint createPoint(BigInteger x, BigInteger y) @@ -997,7 +1017,7 @@ protected ECFieldElement solveQuadraticEquation(ECFieldElement beta) } int m = this.getFieldSize(); - + // For odd m, use the half-trace if (0 != (m & 1)) { @@ -1245,8 +1265,8 @@ public F2m( this.cofactor = cofactor; this.infinity = new ECPoint.F2m(this, null, null); - this.a = fromBigInteger(a); - this.b = fromBigInteger(b); + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); this.coord = F2M_DEFAULT_COORDS; } diff --git a/core/src/main/jdk1.3/org/bouncycastle/util/io/pem/PemReader.java b/core/src/main/jdk1.3/org/bouncycastle/util/io/pem/PemReader.java new file mode 100644 index 0000000000..3f81a29de9 --- /dev/null +++ b/core/src/main/jdk1.3/org/bouncycastle/util/io/pem/PemReader.java @@ -0,0 +1,109 @@ +package org.bouncycastle.util.io.pem; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; +//import java.util.logging.Level; +//import java.util.logging.Logger; + +import org.bouncycastle.util.encoders.Base64; + +/** + * A generic PEM reader, based on the format outlined in RFC 1421 + */ +public class PemReader + extends BufferedReader +{ + public static final String LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME = "org.bouncycastle.pemreader.lax"; + + private static final String BEGIN = "-----BEGIN "; + private static final String END = "-----END "; + //private static final Logger LOG = Logger.getLogger(PemReader.class.getName()); + + public PemReader(Reader reader) + { + super(reader); + } + + /** + * Read the next PEM object as a blob of raw data with header information. + * + * @return the next object in the stream, null if no objects left. + * @throws IOException in case of a parse error. + */ + public PemObject readPemObject() + throws IOException + { + String line = readLine(); + + while (line != null && !line.startsWith(BEGIN)) + { + line = readLine(); + } + + if (line != null) + { + line = line.substring(BEGIN.length()).trim(); + int index = line.indexOf('-'); + + if (index > 0 && line.endsWith("-----") && (line.length() - index) == 5) + { + String type = line.substring(0, index); + + return loadObject(type); + } + } + + return null; + } + + private PemObject loadObject(String type) + throws IOException + { + String line; + String endMarker = END + type + "-----"; + StringBuffer buf = new StringBuffer(); + List headers = new ArrayList(); + + while ((line = readLine()) != null) + { + int index = line.indexOf(':'); + if (index >= 0) + { + String hdr = line.substring(0, index); + String value = line.substring(index + 1).trim(); + + headers.add(new PemHeader(hdr, value)); + + continue; + } + + if (System.getProperty(LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME, "false").equalsIgnoreCase("true")) + { + String trimmedLine = line.trim(); + //if (!trimmedLine.equals(line) && LOG.isLoggable(Level.WARNING)) + //{ + //LOG.log(Level.WARNING, "PEM object contains whitespaces on -----END line", new Exception("trace")); + //} + line = trimmedLine; + } + + if (line.indexOf(endMarker) == 0) + { + break; + } + + buf.append(line.trim()); + } + + if (line == null) + { + throw new IOException(endMarker + " not found"); + } + + return new PemObject(type, headers, Base64.decode(buf.toString())); + } + +} diff --git a/core/src/main/jdk1.4/org/bouncycastle/asn1/ASN1RelativeOID.java b/core/src/main/jdk1.4/org/bouncycastle/asn1/ASN1RelativeOID.java index c46900018b..eb8e42956f 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/asn1/ASN1RelativeOID.java +++ b/core/src/main/jdk1.4/org/bouncycastle/asn1/ASN1RelativeOID.java @@ -7,6 +7,7 @@ import java.util.Map; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Properties; public class ASN1RelativeOID extends ASN1Primitive @@ -229,6 +230,11 @@ static ASN1RelativeOID createPrimitive(byte[] contents, boolean clone) static boolean isValidContents(byte[] contents) { + if (Properties.isOverrideSet("org.bouncycastle.asn1.allow_wrong_oid_enc")) + { + return true; + } + if (contents.length < 1) { return false; diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/digests/AsconDigest.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/digests/AsconDigest.java index 00e85116c7..3da11c2edd 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/crypto/digests/AsconDigest.java +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/digests/AsconDigest.java @@ -4,6 +4,7 @@ import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.ExtendedDigest; import org.bouncycastle.crypto.OutputLengthException; /* ASCON v1.2 Digest, https://ascon.iaik.tugraz.at/ . @@ -13,7 +14,7 @@ * ASCON v1.2 Digest with reference to C Reference Impl from: https://github.com/ascon/ascon-c . */ public class AsconDigest - implements Digest + implements ExtendedDigest { public static class AsconParameters { @@ -57,6 +58,7 @@ public AsconDigest(AsconParameters parameters) private long x3; private long x4; private final int CRYPTO_BYTES = 32; + protected final int ASCON_HASH_RATE = 8; private final int ASCON_PB_ROUNDS; private long ROR(long x, int n) @@ -135,6 +137,11 @@ public int getDigestSize() return CRYPTO_BYTES; } + public int getByteLength() + { + return ASCON_HASH_RATE; + } + @Override public void update(byte in) { diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/engines/AsconAEAD128.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/engines/AsconAEAD128.java new file mode 100644 index 0000000000..409f136095 --- /dev/null +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/engines/AsconAEAD128.java @@ -0,0 +1,206 @@ +package org.bouncycastle.crypto.engines; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.constraints.DefaultServiceProperties; +import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Pack; + +/** + * Ascon-AEAD128 was introduced as part of the NIST Lightweight Cryptography + * competition and described in the NIST Special Publication SP 800-232 (Initial + * Public Draft). + * For additional details, see: + *

    + * + * @version 1.3 + */ +public class AsconAEAD128 + extends AsconBaseEngine +{ + public AsconAEAD128() + { + CRYPTO_KEYBYTES = 16; + CRYPTO_ABYTES = 16; + ASCON_AEAD_RATE = 16; + ASCON_IV = 0x00001000808c0001L; + algorithmName = "Ascon-AEAD128"; + nr = 8; + m_bufferSizeDecrypt = ASCON_AEAD_RATE + CRYPTO_ABYTES; + m_buf = new byte[m_bufferSizeDecrypt]; + dsep = -9223372036854775808L; //0x80L << 56 + } + + protected long pad(int i) + { + return 0x01L << (i << 3); + } + + @Override + protected long loadBytes(byte[] in, int inOff) + { + return Pack.littleEndianToLong(in, inOff); + } + + @Override + protected void setBytes(long n, byte[] bs, int off) + { + Pack.longToLittleEndian(n, bs, off); + } + + protected void ascon_aeadinit() + { + /* initialize */ + x0 = ASCON_IV; + x1 = K0; + x2 = K1; + x3 = N0; + x4 = N1; + p(12); + x3 ^= K0; + x4 ^= K1; + } + + protected void processFinalAadBlock() + { + if (m_bufPos >= 8) // ASCON_AEAD_RATE == 16 is implied + { + x0 ^= Pack.littleEndianToLong(m_buf, 0); + x1 ^= Pack.littleEndianToLong(m_buf, 8) ^ pad(m_bufPos); + } + else + { + x0 ^= Pack.littleEndianToLong(m_buf, 0) ^ pad(m_bufPos); + } + } + + protected void processFinalDecrypt(byte[] input, int inLen, byte[] output, int outOff) + { + if (inLen >= 8) // ASCON_AEAD_RATE == 16 is implied + { + long c0 = Pack.littleEndianToLong(input, 0); + inLen -= 8; + long c1 = Pack.littleEndianToLong(input, 8, inLen); + Pack.longToLittleEndian(x0 ^ c0, output, outOff); + Pack.longToLittleEndian(x1 ^ c1, output, outOff + 8, inLen); + x0 = c0; + x1 &= -(1L << (inLen << 3)); + x1 |= c1; + x1 ^= pad(inLen); + } + else + { + if (inLen != 0) + { + long c0 = Pack.littleEndianToLong(input, 0, inLen); + Pack.longToLittleEndian(x0 ^ c0, output, outOff, inLen); + x0 &= -(1L << (inLen << 3)); + x0 |= c0; + } + x0 ^= pad(inLen); + } + finishData(DecFinal); + } + + protected void processFinalEncrypt(byte[] input, int inLen, byte[] output, int outOff) + { + if (inLen >= 8) // ASCON_AEAD_RATE == 16 is implied + { + x0 ^= Pack.littleEndianToLong(input, 0); + inLen -= 8; + x1 ^= Pack.littleEndianToLong(input, 8, inLen); + Pack.longToLittleEndian(x0, output, outOff); + Pack.longToLittleEndian(x1, output, outOff + 8); + x1 ^= pad(inLen); + } + else + { + if (inLen != 0) + { + x0 ^= Pack.littleEndianToLong(input, 0, inLen); + Pack.longToLittleEndian(x0, output, outOff, inLen); + } + x0 ^= pad(inLen); + } + finishData(EncFinal); + } + + private void finishData(State nextState) + { + x2 ^= K0; + x3 ^= K1; + p(12); + x3 ^= K0; + x4 ^= K1; + m_state = nextState; + } + + public void init(boolean forEncryption, CipherParameters params) + throws IllegalArgumentException + { + KeyParameter key; + byte[] npub; + if (params instanceof AEADParameters) + { + AEADParameters aeadParameters = (AEADParameters)params; + key = aeadParameters.getKey(); + npub = aeadParameters.getNonce(); + initialAssociatedText = aeadParameters.getAssociatedText(); + + int macSizeBits = aeadParameters.getMacSize(); + if (macSizeBits != CRYPTO_ABYTES * 8) + { + throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits); + } + } + else if (params instanceof ParametersWithIV) + { + ParametersWithIV withIV = (ParametersWithIV)params; + key = (KeyParameter)withIV.getParameters(); + npub = withIV.getIV(); + initialAssociatedText = null; + } + else + { + throw new IllegalArgumentException("invalid parameters passed to Ascon"); + } + + if (key == null) + { + throw new IllegalArgumentException("Ascon Init parameters must include a key"); + } + if (npub == null || npub.length != CRYPTO_ABYTES) + { + throw new IllegalArgumentException("Ascon-AEAD-128 requires exactly " + CRYPTO_ABYTES + " bytes of IV"); + } + + byte[] k = key.getKey(); + if (k.length != CRYPTO_KEYBYTES) + { + throw new IllegalArgumentException("Ascon-AEAD-128 key must be " + CRYPTO_KEYBYTES + " bytes long"); + } + + CryptoServicesRegistrar.checkConstraints(new DefaultServiceProperties( + this.getAlgorithmName(), 128, params, Utils.getPurpose(forEncryption))); + K0 = Pack.littleEndianToLong(k, 0); + K1 = Pack.littleEndianToLong(k, 8); + N0 = Pack.littleEndianToLong(npub, 0); + N1 = Pack.littleEndianToLong(npub, 8); + + m_state = forEncryption ? EncInit : DecInit; + + reset(true); + } + + public String getAlgorithmVersion() + { + return "v1.3"; + } +} + diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/engines/AsconBaseEngine.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/engines/AsconBaseEngine.java new file mode 100644 index 0000000000..347e426025 --- /dev/null +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/engines/AsconBaseEngine.java @@ -0,0 +1,516 @@ +package org.bouncycastle.crypto.engines; + +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Longs; + +abstract class AsconBaseEngine + implements AEADCipher +{ + protected static final int UNINITIALIZED = 0; + protected static final int ENCINIT = 1; + protected static final int ENCAAD = 2; + protected static final int ENCDATA = 3; + protected static final int ENCFINAL = 4; + protected static final int DECINIT = 5; + protected static final int DECAAD = 6; + protected static final int DECDATA = 7; + protected static final int DECFINAL = 8; + + protected static final State Uninitialized = new State(UNINITIALIZED); + protected static final State EncInit = new State(ENCINIT); + protected static final State EncAad = new State(ENCAAD); + protected static final State EncData = new State(ENCDATA); + protected static final State EncFinal = new State(ENCFINAL); + protected static final State DecInit = new State(DECINIT); + protected static final State DecAad = new State(DECAAD); + protected static final State DecData = new State(DECDATA); + protected static final State DecFinal = new State(DECFINAL); + + protected static class State + { + int ord; + + private State(int ord) + { + this.ord = ord; + } + } + + protected State m_state = Uninitialized; + protected String algorithmName; + protected byte[] mac; + protected byte[] initialAssociatedText; + protected int CRYPTO_KEYBYTES; + protected int CRYPTO_ABYTES; + protected int nr; + protected int ASCON_AEAD_RATE; + protected long K0; + protected long K1; + protected long N0; + protected long N1; + protected long ASCON_IV; + protected long x0; + protected long x1; + protected long x2; + protected long x3; + protected long x4; + protected int m_bufferSizeDecrypt; + protected byte[] m_buf; + protected int m_bufPos = 0; + protected long dsep; //domain separation + + protected abstract long pad(int i); + + protected abstract long loadBytes(byte[] in, int inOff); + + protected abstract void setBytes(long n, byte[] bs, int off); + + private void round(long C) + { + long t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C)); + long t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3)); + long t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4); + long t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4)); + long t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1); + x0 = t0 ^ Longs.rotateRight(t0, 19) ^ Longs.rotateRight(t0, 28); + x1 = t1 ^ Longs.rotateRight(t1, 39) ^ Longs.rotateRight(t1, 61); + x2 = ~(t2 ^ Longs.rotateRight(t2, 1) ^ Longs.rotateRight(t2, 6)); + x3 = t3 ^ Longs.rotateRight(t3, 10) ^ Longs.rotateRight(t3, 17); + x4 = t4 ^ Longs.rotateRight(t4, 7) ^ Longs.rotateRight(t4, 41); + } + + protected void p(int nr) + { + if (nr == 12) + { + round(0xf0L); + round(0xe1L); + round(0xd2L); + round(0xc3L); + } + if (nr >= 8) + { + round(0xb4L); + round(0xa5L); + } + round(0x96L); + round(0x87L); + round(0x78L); + round(0x69L); + round(0x5aL); + round(0x4bL); + } + + protected abstract void ascon_aeadinit(); + + protected void checkAAD() + { + switch (m_state.ord) + { + case DECINIT: + m_state = DecAad; + break; + case ENCINIT: + m_state = EncAad; + break; + case DECAAD: + case ENCAAD: + break; + case ENCFINAL: + throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + } + } + + protected boolean checkData() + { + switch (m_state.ord) + { + case DECINIT: + case DECAAD: + finishAAD(DecData); + return false; + case ENCINIT: + case ENCAAD: + finishAAD(EncData); + return true; + case DECDATA: + return false; + case ENCDATA: + return true; + case ENCFINAL: + throw new IllegalStateException(getAlgorithmName() + " cannot be reused for encryption"); + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + } + } + + private void finishAAD(State nextState) + { + // State indicates whether we ever received AAD + switch (m_state.ord) + { + case DECAAD: + case ENCAAD: + processFinalAadBlock(); + p(nr); + break; + default: + break; + } + // domain separation + x4 ^= dsep; + m_bufPos = 0; + m_state = nextState; + } + + protected abstract void processFinalAadBlock(); + + protected abstract void processFinalDecrypt(byte[] input, int inLen, byte[] output, int outOff); + + protected abstract void processFinalEncrypt(byte[] input, int inLen, byte[] output, int outOff); + + protected void processBufferAAD(byte[] buffer, int inOff) + { + x0 ^= loadBytes(buffer, inOff); + if (ASCON_AEAD_RATE == 16) + { + x1 ^= loadBytes(buffer, 8 + inOff); + } + p(nr); + } + + + protected void processBufferDecrypt(byte[] buffer, int bufOff, byte[] output, int outOff) + { + if (outOff + ASCON_AEAD_RATE > output.length) + { + throw new OutputLengthException("output buffer too short"); + } + long t0 = loadBytes(buffer, bufOff); + setBytes(x0 ^ t0, output, outOff); + x0 = t0; + + if (ASCON_AEAD_RATE == 16) + { + long t1 = loadBytes(buffer, bufOff + 8); + setBytes(x1 ^ t1, output, outOff + 8); + x1 = t1; + } + p(nr); + } + + protected void processBufferEncrypt(byte[] buffer, int bufOff, byte[] output, int outOff) + { + if (outOff + ASCON_AEAD_RATE > output.length) + { + throw new OutputLengthException("output buffer too short"); + } + x0 ^= loadBytes(buffer, bufOff); + setBytes(x0, output, outOff); + + if (ASCON_AEAD_RATE == 16) + { + x1 ^= loadBytes(buffer, bufOff + 8); + setBytes(x1, output, outOff + 8); + } + p(nr); + } + + public void processAADByte(byte in) + { + checkAAD(); + m_buf[m_bufPos] = in; + if (++m_bufPos == ASCON_AEAD_RATE) + { + processBufferAAD(m_buf, 0); + m_bufPos = 0; + } + } + + public void processAADBytes(byte[] inBytes, int inOff, int len) + { + if ((inOff + len) > inBytes.length) + { + throw new DataLengthException("input buffer too short"); + } + // Don't enter AAD state until we actually get input + if (len <= 0) + { + return; + } + checkAAD(); + if (m_bufPos > 0) + { + int available = ASCON_AEAD_RATE - m_bufPos; + if (len < available) + { + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return; + } + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, available); + inOff += available; + len -= available; + processBufferAAD(m_buf, 0); + //m_bufPos = 0; + } + while (len >= ASCON_AEAD_RATE) + { + processBufferAAD(inBytes, inOff); + inOff += ASCON_AEAD_RATE; + len -= ASCON_AEAD_RATE; + } + System.arraycopy(inBytes, inOff, m_buf, 0, len); + m_bufPos = len; + } + + public int processByte(byte in, byte[] out, int outOff) + throws DataLengthException + { + return processBytes(new byte[]{in}, 0, 1, out, outOff); + } + + public int processBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) + throws DataLengthException + { + if ((inOff + len) > inBytes.length) + { + throw new DataLengthException("input buffer too short"); + } + boolean forEncryption = checkData(); + int resultLength = 0; + + if (forEncryption) + { + if (m_bufPos > 0) + { + int available = ASCON_AEAD_RATE - m_bufPos; + if (len < available) + { + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return 0; + } + + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, available); + inOff += available; + len -= available; + + processBufferEncrypt(m_buf, 0, outBytes, outOff); + resultLength = ASCON_AEAD_RATE; + //m_bufPos = 0; + } + + while (len >= ASCON_AEAD_RATE) + { + processBufferEncrypt(inBytes, inOff, outBytes, outOff + resultLength); + inOff += ASCON_AEAD_RATE; + len -= ASCON_AEAD_RATE; + resultLength += ASCON_AEAD_RATE; + } + } + else + { + int available = m_bufferSizeDecrypt - m_bufPos; + if (len < available) + { + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return 0; + } + + // NOTE: Need 'while' here because ASCON_AEAD_RATE < CRYPTO_ABYTES in some parameter sets + while (m_bufPos >= ASCON_AEAD_RATE) + { + processBufferDecrypt(m_buf, 0, outBytes, outOff + resultLength); + m_bufPos -= ASCON_AEAD_RATE; + System.arraycopy(m_buf, ASCON_AEAD_RATE, m_buf, 0, m_bufPos); + resultLength += ASCON_AEAD_RATE; + + available += ASCON_AEAD_RATE; + if (len < available) + { + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + return resultLength; + } + } + + available = ASCON_AEAD_RATE - m_bufPos; + System.arraycopy(inBytes, inOff, m_buf, m_bufPos, available); + inOff += available; + len -= available; + processBufferDecrypt(m_buf, 0, outBytes, outOff + resultLength); + resultLength += ASCON_AEAD_RATE; + //m_bufPos = 0; + + while (len >= m_bufferSizeDecrypt) + { + processBufferDecrypt(inBytes, inOff, outBytes, outOff + resultLength); + inOff += ASCON_AEAD_RATE; + len -= ASCON_AEAD_RATE; + resultLength += ASCON_AEAD_RATE; + } + } + + System.arraycopy(inBytes, inOff, m_buf, 0, len); + m_bufPos = len; + + return resultLength; + } + + public int doFinal(byte[] outBytes, int outOff) + throws IllegalStateException, InvalidCipherTextException, DataLengthException + { + boolean forEncryption = checkData(); + int resultLength; + if (forEncryption) + { + resultLength = m_bufPos + CRYPTO_ABYTES; + if (outOff + resultLength > outBytes.length) + { + throw new OutputLengthException("output buffer too short"); + } + processFinalEncrypt(m_buf, m_bufPos, outBytes, outOff); + mac = new byte[CRYPTO_ABYTES]; + setBytes(x3, mac, 0); + setBytes(x4, mac, 8); + System.arraycopy(mac, 0, outBytes, outOff + m_bufPos, CRYPTO_ABYTES); + reset(false); + } + else + { + if (m_bufPos < CRYPTO_ABYTES) + { + throw new InvalidCipherTextException("data too short"); + } + m_bufPos -= CRYPTO_ABYTES; + resultLength = m_bufPos; + if (outOff + resultLength > outBytes.length) + { + throw new OutputLengthException("output buffer too short"); + } + processFinalDecrypt(m_buf, m_bufPos, outBytes, outOff); + x3 ^= loadBytes(m_buf, m_bufPos); + x4 ^= loadBytes(m_buf, m_bufPos + 8); + if ((x3 | x4) != 0L) + { + throw new InvalidCipherTextException("mac check in " + getAlgorithmName() + " failed"); + } + reset(true); + } + return resultLength; + } + + public byte[] getMac() + { + return mac; + } + + public int getUpdateOutputSize(int len) + { + int total = Math.max(0, len); + switch (m_state.ord) + { + case DECINIT: + case DECAAD: + total = Math.max(0, total - CRYPTO_ABYTES); + break; + case DECDATA: + case DECFINAL: + total = Math.max(0, total + m_bufPos - CRYPTO_ABYTES); + break; + case ENCDATA: + case ENCFINAL: + total += m_bufPos; + break; + default: + break; + } + return total - total % ASCON_AEAD_RATE; + } + + public int getOutputSize(int len) + { + int total = Math.max(0, len); + + switch (m_state.ord) + { + case DECINIT: + case DECAAD: + return Math.max(0, total - CRYPTO_ABYTES); + case DECDATA: + case DECFINAL: + return Math.max(0, total + m_bufPos - CRYPTO_ABYTES); + case ENCDATA: + case ENCFINAL: + return total + m_bufPos + CRYPTO_ABYTES; + default: + return total + CRYPTO_ABYTES; + } + } + + public void reset() + { + reset(true); + } + + protected void reset(boolean clearMac) + { + if (clearMac) + { + mac = null; + } + Arrays.clear(m_buf); + m_bufPos = 0; + + switch (m_state.ord) + { + case DECINIT: + case ENCINIT: + break; + case DECAAD: + case DECDATA: + case DECFINAL: + m_state = DecInit; + break; + case ENCAAD: + case ENCDATA: + case ENCFINAL: + m_state = EncFinal; + return; + default: + throw new IllegalStateException(getAlgorithmName() + " needs to be initialized"); + } + ascon_aeadinit(); + if (initialAssociatedText != null) + { + processAADBytes(initialAssociatedText, 0, initialAssociatedText.length); + } + } + + public int getKeyBytesSize() + { + return CRYPTO_KEYBYTES; + } + + public int getIVBytesSize() + { + return CRYPTO_ABYTES; + } + + + public String getAlgorithmName() + { + return algorithmName; + } + + public abstract String getAlgorithmVersion(); + +} diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java index 8edec5c8d4..74bfbef79b 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/generators/OpenBSDBCrypt.java @@ -12,7 +12,10 @@ * Password hashing scheme BCrypt, * designed by Niels Provos and David Mazières, using the * String format and the Base64 encoding - * of the reference implementation on OpenBSD + * of the reference implementation on OpenBSD. + *

    + * Passwords are encoded using UTF-8 when provided as char[]. Encoded passwords longer than + * 72 bytes are truncated and all remaining bytes are ignored. */ public class OpenBSDBCrypt { diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/Polynomial.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/Polynomial.java new file mode 100644 index 0000000000..8d1c78a36d --- /dev/null +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/Polynomial.java @@ -0,0 +1,287 @@ +package org.bouncycastle.crypto.threshold; + +abstract class Polynomial +{ + public static Polynomial newInstance(ShamirSecretSplitter.Algorithm algorithm, ShamirSecretSplitter.Mode mode) + { + if (mode == ShamirSecretSplitter.Mode.Native) + { + return new PolynomialNative(algorithm); + } + else + { + return new PolynomialTable(algorithm); + } + } + + protected abstract byte gfMul(int x, int y); + + protected abstract byte gfDiv(int x, int y); + + protected byte gfPow(int n, byte k) + { + int result = 1; + for (int i = 0; i < 8; i++) + { + if ((k & (1 << i)) != 0) + { + result = gfMul(result & 0xff, n & 0xff); + } + n = gfMul(n & 0xff, n & 0xff); + } + return (byte)result; + } + + public byte[] gfVecMul(byte[] xs, byte[][] yss) + { + byte[] result = new byte[yss[0].length]; + int sum; + for (int j = 0; j < yss[0].length; j++) + { + sum = 0; + for (int k = 0; k < xs.length; k++) + { + sum ^= gfMul(xs[k] & 0xff, yss[k][j] & 0xff); + } + result[j] = (byte)sum; + } + return result; + } +} + +class PolynomialTable + extends Polynomial +{ + private final byte[] LOG; + private final byte[] EXP; + private static final byte[] AES_LOG = { + (byte)0x00, (byte)0xff, (byte)0x19, (byte)0x01, (byte)0x32, (byte)0x02, (byte)0x1a, (byte)0xc6, + (byte)0x4b, (byte)0xc7, (byte)0x1b, (byte)0x68, (byte)0x33, (byte)0xee, (byte)0xdf, (byte)0x03, + (byte)0x64, (byte)0x04, (byte)0xe0, (byte)0x0e, (byte)0x34, (byte)0x8d, (byte)0x81, (byte)0xef, + (byte)0x4c, (byte)0x71, (byte)0x08, (byte)0xc8, (byte)0xf8, (byte)0x69, (byte)0x1c, (byte)0xc1, + (byte)0x7d, (byte)0xc2, (byte)0x1d, (byte)0xb5, (byte)0xf9, (byte)0xb9, (byte)0x27, (byte)0x6a, + (byte)0x4d, (byte)0xe4, (byte)0xa6, (byte)0x72, (byte)0x9a, (byte)0xc9, (byte)0x09, (byte)0x78, + (byte)0x65, (byte)0x2f, (byte)0x8a, (byte)0x05, (byte)0x21, (byte)0x0f, (byte)0xe1, (byte)0x24, + (byte)0x12, (byte)0xf0, (byte)0x82, (byte)0x45, (byte)0x35, (byte)0x93, (byte)0xda, (byte)0x8e, + (byte)0x96, (byte)0x8f, (byte)0xdb, (byte)0xbd, (byte)0x36, (byte)0xd0, (byte)0xce, (byte)0x94, + (byte)0x13, (byte)0x5c, (byte)0xd2, (byte)0xf1, (byte)0x40, (byte)0x46, (byte)0x83, (byte)0x38, + (byte)0x66, (byte)0xdd, (byte)0xfd, (byte)0x30, (byte)0xbf, (byte)0x06, (byte)0x8b, (byte)0x62, + (byte)0xb3, (byte)0x25, (byte)0xe2, (byte)0x98, (byte)0x22, (byte)0x88, (byte)0x91, (byte)0x10, + (byte)0x7e, (byte)0x6e, (byte)0x48, (byte)0xc3, (byte)0xa3, (byte)0xb6, (byte)0x1e, (byte)0x42, + (byte)0x3a, (byte)0x6b, (byte)0x28, (byte)0x54, (byte)0xfa, (byte)0x85, (byte)0x3d, (byte)0xba, + (byte)0x2b, (byte)0x79, (byte)0x0a, (byte)0x15, (byte)0x9b, (byte)0x9f, (byte)0x5e, (byte)0xca, + (byte)0x4e, (byte)0xd4, (byte)0xac, (byte)0xe5, (byte)0xf3, (byte)0x73, (byte)0xa7, (byte)0x57, + (byte)0xaf, (byte)0x58, (byte)0xa8, (byte)0x50, (byte)0xf4, (byte)0xea, (byte)0xd6, (byte)0x74, + (byte)0x4f, (byte)0xae, (byte)0xe9, (byte)0xd5, (byte)0xe7, (byte)0xe6, (byte)0xad, (byte)0xe8, + (byte)0x2c, (byte)0xd7, (byte)0x75, (byte)0x7a, (byte)0xeb, (byte)0x16, (byte)0x0b, (byte)0xf5, + (byte)0x59, (byte)0xcb, (byte)0x5f, (byte)0xb0, (byte)0x9c, (byte)0xa9, (byte)0x51, (byte)0xa0, + (byte)0x7f, (byte)0x0c, (byte)0xf6, (byte)0x6f, (byte)0x17, (byte)0xc4, (byte)0x49, (byte)0xec, + (byte)0xd8, (byte)0x43, (byte)0x1f, (byte)0x2d, (byte)0xa4, (byte)0x76, (byte)0x7b, (byte)0xb7, + (byte)0xcc, (byte)0xbb, (byte)0x3e, (byte)0x5a, (byte)0xfb, (byte)0x60, (byte)0xb1, (byte)0x86, + (byte)0x3b, (byte)0x52, (byte)0xa1, (byte)0x6c, (byte)0xaa, (byte)0x55, (byte)0x29, (byte)0x9d, + (byte)0x97, (byte)0xb2, (byte)0x87, (byte)0x90, (byte)0x61, (byte)0xbe, (byte)0xdc, (byte)0xfc, + (byte)0xbc, (byte)0x95, (byte)0xcf, (byte)0xcd, (byte)0x37, (byte)0x3f, (byte)0x5b, (byte)0xd1, + (byte)0x53, (byte)0x39, (byte)0x84, (byte)0x3c, (byte)0x41, (byte)0xa2, (byte)0x6d, (byte)0x47, + (byte)0x14, (byte)0x2a, (byte)0x9e, (byte)0x5d, (byte)0x56, (byte)0xf2, (byte)0xd3, (byte)0xab, + (byte)0x44, (byte)0x11, (byte)0x92, (byte)0xd9, (byte)0x23, (byte)0x20, (byte)0x2e, (byte)0x89, + (byte)0xb4, (byte)0x7c, (byte)0xb8, (byte)0x26, (byte)0x77, (byte)0x99, (byte)0xe3, (byte)0xa5, + (byte)0x67, (byte)0x4a, (byte)0xed, (byte)0xde, (byte)0xc5, (byte)0x31, (byte)0xfe, (byte)0x18, + (byte)0x0d, (byte)0x63, (byte)0x8c, (byte)0x80, (byte)0xc0, (byte)0xf7, (byte)0x70, (byte)0x07 + }; + /* given a j, (byte)return alpha^j, (byte)where alpha = mimimum primitive element (x + 1 = 3) */ + private static final byte[] AES_EXP = { + (byte)0x01, (byte)0x03, (byte)0x05, (byte)0x0f, (byte)0x11, (byte)0x33, (byte)0x55, (byte)0xff, + (byte)0x1a, (byte)0x2e, (byte)0x72, (byte)0x96, (byte)0xa1, (byte)0xf8, (byte)0x13, (byte)0x35, + (byte)0x5f, (byte)0xe1, (byte)0x38, (byte)0x48, (byte)0xd8, (byte)0x73, (byte)0x95, (byte)0xa4, + (byte)0xf7, (byte)0x02, (byte)0x06, (byte)0x0a, (byte)0x1e, (byte)0x22, (byte)0x66, (byte)0xaa, + (byte)0xe5, (byte)0x34, (byte)0x5c, (byte)0xe4, (byte)0x37, (byte)0x59, (byte)0xeb, (byte)0x26, + (byte)0x6a, (byte)0xbe, (byte)0xd9, (byte)0x70, (byte)0x90, (byte)0xab, (byte)0xe6, (byte)0x31, + (byte)0x53, (byte)0xf5, (byte)0x04, (byte)0x0c, (byte)0x14, (byte)0x3c, (byte)0x44, (byte)0xcc, + (byte)0x4f, (byte)0xd1, (byte)0x68, (byte)0xb8, (byte)0xd3, (byte)0x6e, (byte)0xb2, (byte)0xcd, + (byte)0x4c, (byte)0xd4, (byte)0x67, (byte)0xa9, (byte)0xe0, (byte)0x3b, (byte)0x4d, (byte)0xd7, + (byte)0x62, (byte)0xa6, (byte)0xf1, (byte)0x08, (byte)0x18, (byte)0x28, (byte)0x78, (byte)0x88, + (byte)0x83, (byte)0x9e, (byte)0xb9, (byte)0xd0, (byte)0x6b, (byte)0xbd, (byte)0xdc, (byte)0x7f, + (byte)0x81, (byte)0x98, (byte)0xb3, (byte)0xce, (byte)0x49, (byte)0xdb, (byte)0x76, (byte)0x9a, + (byte)0xb5, (byte)0xc4, (byte)0x57, (byte)0xf9, (byte)0x10, (byte)0x30, (byte)0x50, (byte)0xf0, + (byte)0x0b, (byte)0x1d, (byte)0x27, (byte)0x69, (byte)0xbb, (byte)0xd6, (byte)0x61, (byte)0xa3, + (byte)0xfe, (byte)0x19, (byte)0x2b, (byte)0x7d, (byte)0x87, (byte)0x92, (byte)0xad, (byte)0xec, + (byte)0x2f, (byte)0x71, (byte)0x93, (byte)0xae, (byte)0xe9, (byte)0x20, (byte)0x60, (byte)0xa0, + (byte)0xfb, (byte)0x16, (byte)0x3a, (byte)0x4e, (byte)0xd2, (byte)0x6d, (byte)0xb7, (byte)0xc2, + (byte)0x5d, (byte)0xe7, (byte)0x32, (byte)0x56, (byte)0xfa, (byte)0x15, (byte)0x3f, (byte)0x41, + (byte)0xc3, (byte)0x5e, (byte)0xe2, (byte)0x3d, (byte)0x47, (byte)0xc9, (byte)0x40, (byte)0xc0, + (byte)0x5b, (byte)0xed, (byte)0x2c, (byte)0x74, (byte)0x9c, (byte)0xbf, (byte)0xda, (byte)0x75, + (byte)0x9f, (byte)0xba, (byte)0xd5, (byte)0x64, (byte)0xac, (byte)0xef, (byte)0x2a, (byte)0x7e, + (byte)0x82, (byte)0x9d, (byte)0xbc, (byte)0xdf, (byte)0x7a, (byte)0x8e, (byte)0x89, (byte)0x80, + (byte)0x9b, (byte)0xb6, (byte)0xc1, (byte)0x58, (byte)0xe8, (byte)0x23, (byte)0x65, (byte)0xaf, + (byte)0xea, (byte)0x25, (byte)0x6f, (byte)0xb1, (byte)0xc8, (byte)0x43, (byte)0xc5, (byte)0x54, + (byte)0xfc, (byte)0x1f, (byte)0x21, (byte)0x63, (byte)0xa5, (byte)0xf4, (byte)0x07, (byte)0x09, + (byte)0x1b, (byte)0x2d, (byte)0x77, (byte)0x99, (byte)0xb0, (byte)0xcb, (byte)0x46, (byte)0xca, + (byte)0x45, (byte)0xcf, (byte)0x4a, (byte)0xde, (byte)0x79, (byte)0x8b, (byte)0x86, (byte)0x91, + (byte)0xa8, (byte)0xe3, (byte)0x3e, (byte)0x42, (byte)0xc6, (byte)0x51, (byte)0xf3, (byte)0x0e, + (byte)0x12, (byte)0x36, (byte)0x5a, (byte)0xee, (byte)0x29, (byte)0x7b, (byte)0x8d, (byte)0x8c, + (byte)0x8f, (byte)0x8a, (byte)0x85, (byte)0x94, (byte)0xa7, (byte)0xf2, (byte)0x0d, (byte)0x17, + (byte)0x39, (byte)0x4b, (byte)0xdd, (byte)0x7c, (byte)0x84, (byte)0x97, (byte)0xa2, (byte)0xfd, + (byte)0x1c, (byte)0x24, (byte)0x6c, (byte)0xb4, (byte)0xc7, (byte)0x52, (byte)0xf6, (byte)0x01 + }; + + /* given an alpha^j, (byte)where alpha = mimimum primitive element (x + 1 = 3), (byte)return j */ + private static final byte[] RSA_LOG = { + (byte)0xff, (byte)0x00, (byte)0x01, (byte)0x19, (byte)0x02, (byte)0x32, (byte)0x1a, (byte)0xc6, + (byte)0x03, (byte)0xdf, (byte)0x33, (byte)0xee, (byte)0x1b, (byte)0x68, (byte)0xc7, (byte)0x4b, + (byte)0x04, (byte)0x64, (byte)0xe0, (byte)0x0e, (byte)0x34, (byte)0x8d, (byte)0xef, (byte)0x81, + (byte)0x1c, (byte)0xc1, (byte)0x69, (byte)0xf8, (byte)0xc8, (byte)0x08, (byte)0x4c, (byte)0x71, + (byte)0x05, (byte)0x8a, (byte)0x65, (byte)0x2f, (byte)0xe1, (byte)0x24, (byte)0x0f, (byte)0x21, + (byte)0x35, (byte)0x93, (byte)0x8e, (byte)0xda, (byte)0xf0, (byte)0x12, (byte)0x82, (byte)0x45, + (byte)0x1d, (byte)0xb5, (byte)0xc2, (byte)0x7d, (byte)0x6a, (byte)0x27, (byte)0xf9, (byte)0xb9, + (byte)0xc9, (byte)0x9a, (byte)0x09, (byte)0x78, (byte)0x4d, (byte)0xe4, (byte)0x72, (byte)0xa6, + (byte)0x06, (byte)0xbf, (byte)0x8b, (byte)0x62, (byte)0x66, (byte)0xdd, (byte)0x30, (byte)0xfd, + (byte)0xe2, (byte)0x98, (byte)0x25, (byte)0xb3, (byte)0x10, (byte)0x91, (byte)0x22, (byte)0x88, + (byte)0x36, (byte)0xd0, (byte)0x94, (byte)0xce, (byte)0x8f, (byte)0x96, (byte)0xdb, (byte)0xbd, + (byte)0xf1, (byte)0xd2, (byte)0x13, (byte)0x5c, (byte)0x83, (byte)0x38, (byte)0x46, (byte)0x40, + (byte)0x1e, (byte)0x42, (byte)0xb6, (byte)0xa3, (byte)0xc3, (byte)0x48, (byte)0x7e, (byte)0x6e, + (byte)0x6b, (byte)0x3a, (byte)0x28, (byte)0x54, (byte)0xfa, (byte)0x85, (byte)0xba, (byte)0x3d, + (byte)0xca, (byte)0x5e, (byte)0x9b, (byte)0x9f, (byte)0x0a, (byte)0x15, (byte)0x79, (byte)0x2b, + (byte)0x4e, (byte)0xd4, (byte)0xe5, (byte)0xac, (byte)0x73, (byte)0xf3, (byte)0xa7, (byte)0x57, + (byte)0x07, (byte)0x70, (byte)0xc0, (byte)0xf7, (byte)0x8c, (byte)0x80, (byte)0x63, (byte)0x0d, + (byte)0x67, (byte)0x4a, (byte)0xde, (byte)0xed, (byte)0x31, (byte)0xc5, (byte)0xfe, (byte)0x18, + (byte)0xe3, (byte)0xa5, (byte)0x99, (byte)0x77, (byte)0x26, (byte)0xb8, (byte)0xb4, (byte)0x7c, + (byte)0x11, (byte)0x44, (byte)0x92, (byte)0xd9, (byte)0x23, (byte)0x20, (byte)0x89, (byte)0x2e, + (byte)0x37, (byte)0x3f, (byte)0xd1, (byte)0x5b, (byte)0x95, (byte)0xbc, (byte)0xcf, (byte)0xcd, + (byte)0x90, (byte)0x87, (byte)0x97, (byte)0xb2, (byte)0xdc, (byte)0xfc, (byte)0xbe, (byte)0x61, + (byte)0xf2, (byte)0x56, (byte)0xd3, (byte)0xab, (byte)0x14, (byte)0x2a, (byte)0x5d, (byte)0x9e, + (byte)0x84, (byte)0x3c, (byte)0x39, (byte)0x53, (byte)0x47, (byte)0x6d, (byte)0x41, (byte)0xa2, + (byte)0x1f, (byte)0x2d, (byte)0x43, (byte)0xd8, (byte)0xb7, (byte)0x7b, (byte)0xa4, (byte)0x76, + (byte)0xc4, (byte)0x17, (byte)0x49, (byte)0xec, (byte)0x7f, (byte)0x0c, (byte)0x6f, (byte)0xf6, + (byte)0x6c, (byte)0xa1, (byte)0x3b, (byte)0x52, (byte)0x29, (byte)0x9d, (byte)0x55, (byte)0xaa, + (byte)0xfb, (byte)0x60, (byte)0x86, (byte)0xb1, (byte)0xbb, (byte)0xcc, (byte)0x3e, (byte)0x5a, + (byte)0xcb, (byte)0x59, (byte)0x5f, (byte)0xb0, (byte)0x9c, (byte)0xa9, (byte)0xa0, (byte)0x51, + (byte)0x0b, (byte)0xf5, (byte)0x16, (byte)0xeb, (byte)0x7a, (byte)0x75, (byte)0x2c, (byte)0xd7, + (byte)0x4f, (byte)0xae, (byte)0xd5, (byte)0xe9, (byte)0xe6, (byte)0xe7, (byte)0xad, (byte)0xe8, + (byte)0x74, (byte)0xd6, (byte)0xf4, (byte)0xea, (byte)0xa8, (byte)0x50, (byte)0x58, (byte)0xaf + }; + /* given a j, (byte)return alpha^j, (byte)where alpha = mimimum primitive element (x + 1 = 3) */ + private static final byte[] RSA_EXP = { + (byte)0x01, (byte)0x02, (byte)0x04, (byte)0x08, (byte)0x10, (byte)0x20, (byte)0x40, (byte)0x80, + (byte)0x1d, (byte)0x3a, (byte)0x74, (byte)0xe8, (byte)0xcd, (byte)0x87, (byte)0x13, (byte)0x26, + (byte)0x4c, (byte)0x98, (byte)0x2d, (byte)0x5a, (byte)0xb4, (byte)0x75, (byte)0xea, (byte)0xc9, + (byte)0x8f, (byte)0x03, (byte)0x06, (byte)0x0c, (byte)0x18, (byte)0x30, (byte)0x60, (byte)0xc0, + (byte)0x9d, (byte)0x27, (byte)0x4e, (byte)0x9c, (byte)0x25, (byte)0x4a, (byte)0x94, (byte)0x35, + (byte)0x6a, (byte)0xd4, (byte)0xb5, (byte)0x77, (byte)0xee, (byte)0xc1, (byte)0x9f, (byte)0x23, + (byte)0x46, (byte)0x8c, (byte)0x05, (byte)0x0a, (byte)0x14, (byte)0x28, (byte)0x50, (byte)0xa0, + (byte)0x5d, (byte)0xba, (byte)0x69, (byte)0xd2, (byte)0xb9, (byte)0x6f, (byte)0xde, (byte)0xa1, + (byte)0x5f, (byte)0xbe, (byte)0x61, (byte)0xc2, (byte)0x99, (byte)0x2f, (byte)0x5e, (byte)0xbc, + (byte)0x65, (byte)0xca, (byte)0x89, (byte)0x0f, (byte)0x1e, (byte)0x3c, (byte)0x78, (byte)0xf0, + (byte)0xfd, (byte)0xe7, (byte)0xd3, (byte)0xbb, (byte)0x6b, (byte)0xd6, (byte)0xb1, (byte)0x7f, + (byte)0xfe, (byte)0xe1, (byte)0xdf, (byte)0xa3, (byte)0x5b, (byte)0xb6, (byte)0x71, (byte)0xe2, + (byte)0xd9, (byte)0xaf, (byte)0x43, (byte)0x86, (byte)0x11, (byte)0x22, (byte)0x44, (byte)0x88, + (byte)0x0d, (byte)0x1a, (byte)0x34, (byte)0x68, (byte)0xd0, (byte)0xbd, (byte)0x67, (byte)0xce, + (byte)0x81, (byte)0x1f, (byte)0x3e, (byte)0x7c, (byte)0xf8, (byte)0xed, (byte)0xc7, (byte)0x93, + (byte)0x3b, (byte)0x76, (byte)0xec, (byte)0xc5, (byte)0x97, (byte)0x33, (byte)0x66, (byte)0xcc, + (byte)0x85, (byte)0x17, (byte)0x2e, (byte)0x5c, (byte)0xb8, (byte)0x6d, (byte)0xda, (byte)0xa9, + (byte)0x4f, (byte)0x9e, (byte)0x21, (byte)0x42, (byte)0x84, (byte)0x15, (byte)0x2a, (byte)0x54, + (byte)0xa8, (byte)0x4d, (byte)0x9a, (byte)0x29, (byte)0x52, (byte)0xa4, (byte)0x55, (byte)0xaa, + (byte)0x49, (byte)0x92, (byte)0x39, (byte)0x72, (byte)0xe4, (byte)0xd5, (byte)0xb7, (byte)0x73, + (byte)0xe6, (byte)0xd1, (byte)0xbf, (byte)0x63, (byte)0xc6, (byte)0x91, (byte)0x3f, (byte)0x7e, + (byte)0xfc, (byte)0xe5, (byte)0xd7, (byte)0xb3, (byte)0x7b, (byte)0xf6, (byte)0xf1, (byte)0xff, + (byte)0xe3, (byte)0xdb, (byte)0xab, (byte)0x4b, (byte)0x96, (byte)0x31, (byte)0x62, (byte)0xc4, + (byte)0x95, (byte)0x37, (byte)0x6e, (byte)0xdc, (byte)0xa5, (byte)0x57, (byte)0xae, (byte)0x41, + (byte)0x82, (byte)0x19, (byte)0x32, (byte)0x64, (byte)0xc8, (byte)0x8d, (byte)0x07, (byte)0x0e, + (byte)0x1c, (byte)0x38, (byte)0x70, (byte)0xe0, (byte)0xdd, (byte)0xa7, (byte)0x53, (byte)0xa6, + (byte)0x51, (byte)0xa2, (byte)0x59, (byte)0xb2, (byte)0x79, (byte)0xf2, (byte)0xf9, (byte)0xef, + (byte)0xc3, (byte)0x9b, (byte)0x2b, (byte)0x56, (byte)0xac, (byte)0x45, (byte)0x8a, (byte)0x09, + (byte)0x12, (byte)0x24, (byte)0x48, (byte)0x90, (byte)0x3d, (byte)0x7a, (byte)0xf4, (byte)0xf5, + (byte)0xf7, (byte)0xf3, (byte)0xfb, (byte)0xeb, (byte)0xcb, (byte)0x8b, (byte)0x0b, (byte)0x16, + (byte)0x2c, (byte)0x58, (byte)0xb0, (byte)0x7d, (byte)0xfa, (byte)0xe9, (byte)0xcf, (byte)0x83, + (byte)0x1b, (byte)0x36, (byte)0x6c, (byte)0xd8, (byte)0xad, (byte)0x47, (byte)0x8e, (byte)0x01 + }; + + public PolynomialTable(ShamirSecretSplitter.Algorithm algorithm) + { + switch (algorithm.ord) + { + case ShamirSecretSplitter._AES: + LOG = AES_LOG; + EXP = AES_EXP; + break; + case ShamirSecretSplitter._RSA: + LOG = RSA_LOG; + EXP = RSA_EXP; + break; + default: + throw new IllegalArgumentException("The algorithm is not correct"); + } + } + + protected byte gfMul(int x, int y) + { + if (x == 0 || y == 0) + { + return 0; + } + return (byte)(EXP[((LOG[x] & 0xff) + (LOG[y] & 0xff)) % 255] & 0xff); + } + + protected byte gfDiv(int x, int y) + { + if (x == 0) + { + return 0; + } + return EXP[((LOG[x] & 0xff) - (LOG[y] & 0xff) + 255) % 255]; + } +} + +class PolynomialNative + extends Polynomial +{ + private final int IRREDUCIBLE; + + public PolynomialNative(ShamirSecretSplitter.Algorithm algorithm) + { + switch (algorithm.ord) + { + case ShamirSecretSplitter._AES: + IRREDUCIBLE = 0x11B; + break; + case ShamirSecretSplitter._RSA: + IRREDUCIBLE = 0x11D; + break; + default: + throw new IllegalArgumentException("The algorithm is not correct"); + } + } + + protected byte gfMul(int x, int y) + { + //pmult + int result = 0; + while (y > 0) + { + if ((y & 1) != 0) + { // If the lowest bit of y is 1 + result ^= x; // XOR x into the result + } + x <<= 1; // Shift x left (multiply by 2 in GF) + if ((x & 0x100) != 0) + { // If x is larger than 8 bits, reduce + x ^= IRREDUCIBLE; // XOR with the irreducible polynomial + } + y >>= 1; // Shift y right + } + //mod + while (result >= (1 << 8)) + { + if ((result & (1 << 8)) != 0) + { + result ^= IRREDUCIBLE; + } + result <<= 1; + } + return (byte) (result & 0xFF); + } + + protected byte gfDiv(int x, int y) + { + return gfMul(x, gfPow((byte)y, (byte)254) & 0xff); + } +} diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/ShamirSecretSplitter.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/ShamirSecretSplitter.java new file mode 100644 index 0000000000..92607b5cd3 --- /dev/null +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/ShamirSecretSplitter.java @@ -0,0 +1,153 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.util.Arrays; + + +public class ShamirSecretSplitter + implements SecretSplitter +{ + static final int _AES = 0; + static final int _RSA = 1; + + public static class Algorithm + { + public static final Algorithm AES = new Algorithm(_AES); + public static final Algorithm RSA = new Algorithm(_RSA); + + int ord; + + private Algorithm(int ord) + { + this.ord = ord; + } + } + + static final int _Native = 0; + static final int _Table = 1; + + public static class Mode + { + public static final Mode Native = new Mode(_Native); + public static final Mode Table = new Mode(_Table); + + int ord; + + private Mode(int ord) + { + this.ord = ord; + } + } + + private final Polynomial poly; + /** + * Length of the secret + */ + protected int l; + + protected SecureRandom random; + + public ShamirSecretSplitter(Algorithm algorithm, Mode mode, int l, SecureRandom random) + { + if (l < 0 || l > 65534) + { + throw new IllegalArgumentException("Invalid input: l ranges from 0 to 65534 (2^16-2) bytes."); + } + + poly = Polynomial.newInstance(algorithm, mode); + this.l = l; + this.random = random; + } + + + public SplitSecret split(int m, int n) + { + byte[][] p = initP(m, n); + byte[][] sr = new byte[m][l]; + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[l]; + int i; + for (i = 0; i < m; i++) + { + random.nextBytes(sr[i]); + } + for (i = 0; i < p.length; i++) + { + secretShares[i] = new ShamirSplitSecretShare(poly.gfVecMul(p[i], sr), i + 1); + } + return new ShamirSplitSecret(poly, secretShares); + } + + @Override + public SplitSecret splitAround(SecretShare s, int m, int n) + throws IOException + { + byte[][] p = initP(m, n); + byte[][] sr = new byte[m][l]; + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[l]; + byte[] ss0 = s.getEncoded(); + secretShares[0] = new ShamirSplitSecretShare(ss0, 1); + int i, j; + byte tmp; + for (i = 0; i < m; i++) + { + random.nextBytes(sr[i]); + } + for (i = 0; i < l; i++) + { + tmp = sr[1][i]; + for (j = 2; j < m; j++) + { + tmp ^= sr[j][i]; + } + sr[0][i] = (byte)(tmp ^ ss0[i]); + } + for (i = 1; i < p.length; i++) + { + secretShares[i] = new ShamirSplitSecretShare(poly.gfVecMul(p[i], sr), i + 1); + } + + return new ShamirSplitSecret(poly, secretShares); + } + + @Override + public SplitSecret resplit(byte[] secret, int m, int n) + { + byte[][] p = initP(m, n); + byte[][] sr = new byte[m][l]; + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[l]; + sr[0] = Arrays.clone(secret); + int i; + for (i = 1; i < m; i++) + { + random.nextBytes(sr[i]); + } + for (i = 0; i < p.length; i++) + { + secretShares[i] = new ShamirSplitSecretShare(poly.gfVecMul(p[i], sr), i + 1); + } + return new ShamirSplitSecret(poly, secretShares); + } + + private byte[][] initP(int m, int n) + { + if (m < 1 || m > 255) + { + throw new IllegalArgumentException("Invalid input: m must be less than 256 and positive."); + } + if (n < m || n > 255) + { + throw new IllegalArgumentException("Invalid input: n must be less than 256 and greater than or equal to n."); + } + byte[][] p = new byte[n][m]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + p[i][j] = poly.gfPow((byte)(i + 1), (byte)j); + } + } + return p; + } +} diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/ShamirSplitSecret.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/ShamirSplitSecret.java new file mode 100644 index 0000000000..d148cdd1e8 --- /dev/null +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/threshold/ShamirSplitSecret.java @@ -0,0 +1,91 @@ +package org.bouncycastle.crypto.threshold; + +import java.io.IOException; + +public class ShamirSplitSecret + implements SplitSecret +{ + private final ShamirSplitSecretShare[] secretShares; + private final Polynomial poly; + + public ShamirSplitSecret(ShamirSecretSplitter.Algorithm algorithm, ShamirSecretSplitter.Mode mode, ShamirSplitSecretShare[] secretShares) + { + this.secretShares = secretShares; + this.poly = Polynomial.newInstance(algorithm, mode); + } + + ShamirSplitSecret(Polynomial poly, ShamirSplitSecretShare[] secretShares) + { + this.secretShares = secretShares; + this.poly = poly; + } + + public SecretShare[] getSecretShares() + { + return secretShares; + } + + public ShamirSplitSecret multiple(int mul) + throws IOException + { + byte[] ss; + for (int i = 0; i < secretShares.length; ++i) + { + ss = secretShares[i].getEncoded(); + for (int j = 0; j < ss.length; ++j) + { + ss[j] = poly.gfMul(ss[j] & 0xFF, mul); + } + secretShares[i] = new ShamirSplitSecretShare(ss, i + 1); + } + return this; + } + + public ShamirSplitSecret divide(int div) + throws IOException + { + byte[] ss; + for (int i = 0; i < secretShares.length; ++i) + { + ss = secretShares[i].getEncoded(); + for (int j = 0; j < ss.length; ++j) + { + ss[j] = poly.gfDiv(ss[j] & 0xFF, div); + } + secretShares[i] = new ShamirSplitSecretShare(ss, i + 1); + } + return this; + } + + @Override + public byte[] getSecret() + throws IOException + { + int n = secretShares.length; + byte[] r = new byte[n]; + byte tmp; + byte[] products = new byte[n - 1]; + byte[][] splits = new byte[n][secretShares[0].getEncoded().length]; + for (int i = 0; i < n; i++) + { + splits[i] = secretShares[i].getEncoded(); + tmp = 0; + for (int j = 0; j < n; j++) + { + if (j != i) + { + products[tmp++] = poly.gfDiv(secretShares[j].r, secretShares[i].r ^ secretShares[j].r); + } + } + + tmp = 1; + for (int prdI = 0; prdI != products.length; prdI++) + { + tmp = poly.gfMul(tmp & 0xff, products[prdI] & 0xff); + } + r[i] = tmp; + } + + return poly.gfVecMul(r, splits); + } +} diff --git a/core/src/main/jdk1.4/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java b/core/src/main/jdk1.4/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java new file mode 100644 index 0000000000..a4b3b89fb6 --- /dev/null +++ b/core/src/main/jdk1.4/org/bouncycastle/crypto/util/SubjectPublicKeyInfoFactory.java @@ -0,0 +1,218 @@ +package org.bouncycastle.crypto.util; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERNull; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; +import org.bouncycastle.asn1.cryptopro.GOST3410PublicKeyAlgParameters; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.RSAPublicKey; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.DSAParameter; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.asn1.x9.X962Parameters; +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.asn1.x9.X9ECPoint; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.DSAParameters; +import org.bouncycastle.crypto.params.DSAPublicKeyParameters; +import org.bouncycastle.crypto.params.ECDomainParameters; +import org.bouncycastle.crypto.params.ECGOST3410Parameters; +import org.bouncycastle.crypto.params.ECNamedDomainParameters; +import org.bouncycastle.crypto.params.ECPublicKeyParameters; +import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; +import org.bouncycastle.crypto.params.Ed448PublicKeyParameters; +import org.bouncycastle.crypto.params.RSAKeyParameters; +import org.bouncycastle.crypto.params.X25519PublicKeyParameters; +import org.bouncycastle.crypto.params.X448PublicKeyParameters; +import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; +import org.bouncycastle.internal.asn1.rosstandart.RosstandartObjectIdentifiers; +import org.bouncycastle.util.Arrays; + +/** + * Factory to create ASN.1 subject public key info objects from lightweight public keys. + */ +public class SubjectPublicKeyInfoFactory +{ + private static final byte tag_OctetString = (byte)0x04; + private static Set cryptoProOids = new HashSet(5); + + static + { + cryptoProOids.add(CryptoProObjectIdentifiers.gostR3410_2001_CryptoPro_A); + cryptoProOids.add(CryptoProObjectIdentifiers.gostR3410_2001_CryptoPro_B); + cryptoProOids.add(CryptoProObjectIdentifiers.gostR3410_2001_CryptoPro_C); + cryptoProOids.add(CryptoProObjectIdentifiers.gostR3410_2001_CryptoPro_XchA); + cryptoProOids.add(CryptoProObjectIdentifiers.gostR3410_2001_CryptoPro_XchB); + } + + private SubjectPublicKeyInfoFactory() + { + + } + + /** + * Create a SubjectPublicKeyInfo public key. + * + * @param publicKey the key to be encoded into the info object. + * @return a SubjectPublicKeyInfo representing the key. + * @throws java.io.IOException on an error encoding the key + */ + public static SubjectPublicKeyInfo createSubjectPublicKeyInfo(AsymmetricKeyParameter publicKey) + throws IOException + { + if (publicKey instanceof RSAKeyParameters) + { + RSAKeyParameters pub = (RSAKeyParameters)publicKey; + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(pub.getModulus(), pub.getExponent())); + } + else if (publicKey instanceof DSAPublicKeyParameters) + { + DSAPublicKeyParameters pub = (DSAPublicKeyParameters)publicKey; + + DSAParameter params = null; + DSAParameters dsaParams = pub.getParameters(); + if (dsaParams != null) + { + params = new DSAParameter(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); + } + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, params), new ASN1Integer(pub.getY())); + } + else if (publicKey instanceof ECPublicKeyParameters) + { + ECPublicKeyParameters pub = (ECPublicKeyParameters)publicKey; + ECDomainParameters domainParams = pub.getParameters(); + ASN1Encodable params; + + if (domainParams == null) + { + params = new X962Parameters(DERNull.INSTANCE); // Implicitly CA + } + else if (domainParams instanceof ECGOST3410Parameters) + { + ECGOST3410Parameters gostParams = (ECGOST3410Parameters)domainParams; + + BigInteger bX = pub.getQ().getAffineXCoord().toBigInteger(); + BigInteger bY = pub.getQ().getAffineYCoord().toBigInteger(); + + params = new GOST3410PublicKeyAlgParameters(gostParams.getPublicKeyParamSet(), gostParams.getDigestParamSet()); + + int encKeySize; + int offset; + ASN1ObjectIdentifier algIdentifier; + + + if (cryptoProOids.contains(gostParams.getPublicKeyParamSet())) + { + encKeySize = 64; + offset = 32; + algIdentifier = CryptoProObjectIdentifiers.gostR3410_2001; + } + else + { + boolean is512 = (bX.bitLength() > 256); + if (is512) + { + encKeySize = 128; + offset = 64; + algIdentifier = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512; + } + else + { + encKeySize = 64; + offset = 32; + algIdentifier = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256; + } + } + + byte[] encKey = new byte[encKeySize]; + extractBytes(encKey, encKeySize / 2, 0, bX); + extractBytes(encKey, encKeySize / 2, offset, bY); + + try + { + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(algIdentifier, params), new DEROctetString(encKey)); + } + catch (IOException e) + { + return null; + } + } + else if (domainParams instanceof ECNamedDomainParameters) + { + params = new X962Parameters(((ECNamedDomainParameters)domainParams).getName()); + } + else + { + X9ECParameters ecP = new X9ECParameters( + domainParams.getCurve(), + // TODO Support point compression + new X9ECPoint(domainParams.getG(), false), + domainParams.getN(), + domainParams.getH(), + domainParams.getSeed()); + + params = new X962Parameters(ecP); + } + + // TODO Support point compression + byte[] pubKeyOctets = pub.getQ().getEncoded(false); + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), pubKeyOctets); + } + else if (publicKey instanceof X448PublicKeyParameters) + { + X448PublicKeyParameters key = (X448PublicKeyParameters)publicKey; + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), key.getEncoded()); + } + else if (publicKey instanceof X25519PublicKeyParameters) + { + X25519PublicKeyParameters key = (X25519PublicKeyParameters)publicKey; + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), key.getEncoded()); + } + else if (publicKey instanceof Ed448PublicKeyParameters) + { + Ed448PublicKeyParameters key = (Ed448PublicKeyParameters)publicKey; + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), key.getEncoded()); + } + else if (publicKey instanceof Ed25519PublicKeyParameters) + { + Ed25519PublicKeyParameters key = (Ed25519PublicKeyParameters)publicKey; + + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), key.getEncoded()); + } + else + { + throw new IOException("key parameters not recognized"); + } + } + + private static void extractBytes(byte[] encKey, int size, int offSet, BigInteger bI) + { + byte[] val = bI.toByteArray(); + if (val.length < size) + { + byte[] tmp = new byte[size]; + System.arraycopy(val, 0, tmp, tmp.length - val.length, val.length); + val = tmp; + } + + for (int i = 0; i != size; i++) + { + encKey[offSet + i] = val[val.length - 1 - i]; + } + } +} diff --git a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java index 0e9433110e..a08b5b0b0e 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java +++ b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyFactory.java @@ -13,6 +13,7 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -31,14 +32,18 @@ import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPrivateKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPrivateKeyParameters; @@ -50,9 +55,12 @@ import org.bouncycastle.pqc.crypto.picnic.PicnicPrivateKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; import org.bouncycastle.pqc.crypto.saber.SABERPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPrivateKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PrivateKeyParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; @@ -140,6 +148,13 @@ else if (algOID.on(BCObjectIdentifiers.sphincsPlus) || algOID.on(BCObjectIdentif return new SPHINCSPlusPrivateKeyParameters(spParams, ASN1OctetString.getInstance(obj).getOctets()); } } + else if (Utils.slhdsaParams.containsKey(algOID)) + { + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(algOID); + ASN1OctetString slhdsaKey = parseOctetString(keyInfo.getPrivateKey(), spParams.getN() * 4); + + return new SLHDSAPrivateKeyParameters(spParams, slhdsaKey.getOctets()); + } else if (algOID.on(BCObjectIdentifiers.picnic)) { byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()).getOctets(); @@ -175,12 +190,41 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_ntru)) return new NTRUPrivateKeyParameters(spParams, keyEnc); } - else if (algOID.on(BCObjectIdentifiers.pqc_kem_kyber)) + else if (algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_512) || + algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_768) || + algOID.equals(NISTObjectIdentifiers.id_alg_ml_kem_1024)) { - ASN1OctetString kyberKey = ASN1OctetString.getInstance(keyInfo.parsePrivateKey()); - KyberParameters kyberParams = Utils.kyberParamsLookup(algOID); + ASN1Primitive mlkemKey = parsePrimitiveString(keyInfo.getPrivateKey(), 64); + MLKEMParameters mlkemParams = Utils.mlkemParamsLookup(algOID); + + MLKEMPublicKeyParameters pubParams = null; + if (keyInfo.getPublicKeyData() != null) + { + pubParams = PublicKeyFactory.MLKEMKeyConverter.getPublicKeyParams(mlkemParams, keyInfo.getPublicKeyData()); + } + + if (mlkemKey instanceof ASN1OctetString) + { + // TODO This should be explicitly EXPANDED_KEY or SEED (tag already removed) but is length-flexible + return new MLKEMPrivateKeyParameters(mlkemParams, ((ASN1OctetString)mlkemKey).getOctets(), pubParams); + } + else if (mlkemKey instanceof ASN1Sequence) + { + ASN1Sequence keySeq = (ASN1Sequence)mlkemKey; + byte[] seed = ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(); + byte[] encoding = ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets(); + + // TODO This should only allow seed but is length-flexible + MLKEMPrivateKeyParameters mlkemPriv = new MLKEMPrivateKeyParameters(mlkemParams, seed, pubParams); + if (!Arrays.constantTimeAreEqual(mlkemPriv.getEncoded(), encoding)) + { + throw new IllegalArgumentException("inconsistent " + mlkemParams.getName() + " private key"); + } + + return mlkemPriv; + } - return new KyberPrivateKeyParameters(kyberParams, kyberKey.getOctets()); + throw new IllegalArgumentException("invalid " + mlkemParams.getName() + " private key"); } else if (algOID.on(BCObjectIdentifiers.pqc_kem_ntrulprime)) { @@ -207,11 +251,45 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_sntruprime)) ASN1OctetString.getInstance(keyEnc.getObjectAt(3)).getOctets(), ASN1OctetString.getInstance(keyEnc.getObjectAt(4)).getOctets()); } + else if (Utils.mldsaParams.containsKey(algOID)) + { + ASN1Encodable mldsaKey = parsePrimitiveString(keyInfo.getPrivateKey(), 32); + MLDSAParameters mldsaParams = Utils.mldsaParamsLookup(algOID); + + MLDSAPublicKeyParameters pubParams = null; + if (keyInfo.getPublicKeyData() != null) + { + pubParams = PublicKeyFactory.MLDSAConverter.getPublicKeyParams(mldsaParams, keyInfo.getPublicKeyData()); + } + + if (mldsaKey instanceof ASN1OctetString) + { + // TODO This should be explicitly EXPANDED_KEY or SEED (tag already removed) but is length-flexible + return new MLDSAPrivateKeyParameters(mldsaParams, ((ASN1OctetString)mldsaKey).getOctets(), pubParams); + } + else if (mldsaKey instanceof ASN1Sequence) + { + ASN1Sequence keySeq = (ASN1Sequence)mldsaKey; + byte[] seed = ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(); + byte[] encoding = ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets(); + + // TODO This should only allow seed but is length-flexible + MLDSAPrivateKeyParameters mldsaPriv = new MLDSAPrivateKeyParameters(mldsaParams, seed, pubParams); + if (!Arrays.constantTimeAreEqual(mldsaPriv.getEncoded(), encoding)) + { + throw new IllegalArgumentException("inconsistent " + mldsaParams.getName() + " private key"); + } + + return mldsaPriv; + } + + throw new IllegalArgumentException("invalid " + mldsaParams.getName() + " private key"); + } else if (algOID.equals(BCObjectIdentifiers.dilithium2) || algOID.equals(BCObjectIdentifiers.dilithium3) || algOID.equals(BCObjectIdentifiers.dilithium5)) { ASN1Encodable keyObj = keyInfo.parsePrivateKey(); - DilithiumParameters spParams = Utils.dilithiumParamsLookup(algOID); + DilithiumParameters dilParams = Utils.dilithiumParamsLookup(algOID); if (keyObj instanceof ASN1Sequence) { @@ -225,9 +303,9 @@ else if (algOID.equals(BCObjectIdentifiers.dilithium2) if (keyInfo.getPublicKeyData() != null) { - DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); + DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(dilParams, keyInfo.getPublicKeyData()); - return new DilithiumPrivateKeyParameters(spParams, + return new DilithiumPrivateKeyParameters(dilParams, ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), @@ -238,7 +316,7 @@ else if (algOID.equals(BCObjectIdentifiers.dilithium2) } else { - return new DilithiumPrivateKeyParameters(spParams, + return new DilithiumPrivateKeyParameters(dilParams, ASN1BitString.getInstance(keyEnc.getObjectAt(1)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(2)).getOctets(), ASN1BitString.getInstance(keyEnc.getObjectAt(3)).getOctets(), @@ -253,10 +331,10 @@ else if (keyObj instanceof DEROctetString) byte[] data = ASN1OctetString.getInstance(keyObj).getOctets(); if (keyInfo.getPublicKeyData() != null) { - DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(spParams, keyInfo.getPublicKeyData()); - return new DilithiumPrivateKeyParameters(spParams, data, pubParams); + DilithiumPublicKeyParameters pubParams = PublicKeyFactory.DilithiumConverter.getPublicKeyParams(dilParams, keyInfo.getPublicKeyData()); + return new DilithiumPrivateKeyParameters(dilParams, data, pubParams); } - return new DilithiumPrivateKeyParameters(spParams, data, null); + return new DilithiumPrivateKeyParameters(dilParams, data, null); } else { @@ -287,12 +365,78 @@ else if (algOID.on(BCObjectIdentifiers.pqc_kem_hqc)) return new HQCPrivateKeyParameters(hqcParams, keyEnc); } + else if (algOID.equals(PQCObjectIdentifiers.mcElieceCca2)) + { + McElieceCCA2PrivateKey mKey = McElieceCCA2PrivateKey.getInstance(keyInfo.parsePrivateKey()); + + return new McElieceCCA2PrivateKeyParameters(mKey.getN(), mKey.getK(), mKey.getField(), mKey.getGoppaPoly(), mKey.getP(), Utils.getDigestName(mKey.getDigest().getAlgorithm())); + } else { throw new RuntimeException("algorithm identifier in private key not recognised"); } } + /** + * So it seems for the new PQC algorithms, there's a couple of approaches to what goes in the OCTET STRING + */ + private static ASN1OctetString parseOctetString(ASN1OctetString octStr, int expectedLength) + throws IOException + { + byte[] data = octStr.getOctets(); + // + // it's the right length for a RAW encoding, just return it. + // + if (data.length == expectedLength) + { + return octStr; + } + + // + // possible internal OCTET STRING, possibly long form with or without the internal OCTET STRING + ASN1OctetString obj = Utils.parseOctetData(data); + + if (obj != null) + { + return ASN1OctetString.getInstance(obj); + } + + return octStr; + } + + /** + * So it seems for the new PQC algorithms, there's a couple of approaches to what goes in the OCTET STRING + * and in this case there may also be SEQUENCE. + */ + private static ASN1Primitive parsePrimitiveString(ASN1OctetString octStr, int expectedLength) + throws IOException + { + byte[] data = octStr.getOctets(); + // + // it's the right length for a RAW encoding, just return it. + // + if (data.length == expectedLength) + { + return octStr; + } + + // + // possible internal OCTET STRING, possibly long form with or without the internal OCTET STRING + // or possible SEQUENCE + ASN1Encodable obj = Utils.parseData(data); + + if (obj instanceof ASN1OctetString) + { + return ASN1OctetString.getInstance(obj); + } + if (obj instanceof ASN1Sequence) + { + return ASN1Sequence.getInstance(obj); + } + + return octStr; + } + private static short[] convert(byte[] octets) { short[] rv = new short[octets.length / 2]; diff --git a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java index 87fe06e5dd..e9d2f817be 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java +++ b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PrivateKeyInfoFactory.java @@ -3,9 +3,11 @@ import java.io.IOException; import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -21,18 +23,22 @@ import org.bouncycastle.pqc.crypto.cmce.CMCEPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPrivateKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPrivateKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPrivateKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntruprime.NTRULPRimePrivateKeyParameters; import org.bouncycastle.pqc.crypto.ntruprime.SNTRUPrimePrivateKeyParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicPrivateKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPrivateKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPrivateKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PrivateKeyParameters; import org.bouncycastle.util.Pack; /** @@ -51,7 +57,8 @@ private PrivateKeyInfoFactory() * @return the appropriate PrivateKeyInfo * @throws java.io.IOException on an error encoding the key */ - public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey) throws IOException + public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey) + throws IOException { return createPrivateKeyInfo(privateKey, null); } @@ -64,7 +71,8 @@ public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter private * @return the appropriate PrivateKeyInfo * @throws java.io.IOException on an error encoding the key */ - public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey, ASN1Set attributes) throws IOException + public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey, ASN1Set attributes) + throws IOException { if (privateKey instanceof SPHINCSPrivateKeyParameters) { @@ -98,6 +106,14 @@ else if (privateKey instanceof SPHINCSPlusPrivateKeyParameters) return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes, params.getPublicKey()); } + else if (privateKey instanceof SLHDSAPrivateKeyParameters) + { + SLHDSAPrivateKeyParameters params = (SLHDSAPrivateKeyParameters)privateKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.slhdsaOidLookup(params.getParameters())); + + return new PrivateKeyInfo(algorithmIdentifier, params.getEncoded(), attributes); + } else if (privateKey instanceof PicnicPrivateKeyParameters) { PicnicPrivateKeyParameters params = (PicnicPrivateKeyParameters)privateKey; @@ -120,6 +136,14 @@ else if (privateKey instanceof CMCEPrivateKeyParameters) CMCEPrivateKey cmcePriv = new CMCEPrivateKey(0, params.getDelta(), params.getC(), params.getG(), params.getAlpha(), params.getS(), cmcePub); return new PrivateKeyInfo(algorithmIdentifier, cmcePriv, attributes); } + else if (privateKey instanceof McElieceCCA2PrivateKeyParameters) + { + McElieceCCA2PrivateKeyParameters priv = (McElieceCCA2PrivateKeyParameters)privateKey; + McElieceCCA2PrivateKey mcEliecePriv = new McElieceCCA2PrivateKey(priv.getN(), priv.getK(), priv.getField(), priv.getGoppaPoly(), priv.getP(), Utils.getAlgorithmIdentifier(priv.getDigest())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.mcElieceCca2); + + return new PrivateKeyInfo(algorithmIdentifier, mcEliecePriv); + } else if (privateKey instanceof FrodoPrivateKeyParameters) { FrodoPrivateKeyParameters params = (FrodoPrivateKeyParameters)privateKey; @@ -161,13 +185,21 @@ else if (privateKey instanceof FalconPrivateKeyParameters) return new PrivateKeyInfo(algorithmIdentifier, falconPriv, attributes); } - else if (privateKey instanceof KyberPrivateKeyParameters) + else if (privateKey instanceof MLKEMPrivateKeyParameters) { - KyberPrivateKeyParameters params = (KyberPrivateKeyParameters)privateKey; - - AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.kyberOidLookup(params.getParameters())); + MLKEMPrivateKeyParameters params = (MLKEMPrivateKeyParameters)privateKey; - return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mlkemOidLookup(params.getParameters())); + + byte[] seed = params.getSeed(); + if (seed == null) + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + } + else + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(seed), attributes); + } } else if (privateKey instanceof NTRULPRimePrivateKeyParameters) { @@ -200,6 +232,22 @@ else if (privateKey instanceof SNTRUPrimePrivateKeyParameters) return new PrivateKeyInfo(algorithmIdentifier, new DERSequence(v), attributes); } + else if (privateKey instanceof MLDSAPrivateKeyParameters) + { + MLDSAPrivateKeyParameters params = (MLDSAPrivateKeyParameters)privateKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mldsaOidLookup(params.getParameters())); + + if (params.getPreferredFormat() == MLDSAPrivateKeyParameters.SEED_ONLY) + { + return new PrivateKeyInfo(algorithmIdentifier, new DERTaggedObject(false, 0, new DEROctetString(params.getSeed())), attributes); + } + else if (params.getPreferredFormat() == MLDSAPrivateKeyParameters.EXPANDED_KEY) + { + return new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getEncoded()), attributes); + } + return new PrivateKeyInfo(algorithmIdentifier, getBasicPQCEncoding(params.getSeed(), params.getEncoded()), attributes); + } else if (privateKey instanceof DilithiumPrivateKeyParameters) { DilithiumPrivateKeyParameters params = (DilithiumPrivateKeyParameters)privateKey; @@ -229,4 +277,15 @@ else if (privateKey instanceof HQCPrivateKeyParameters) throw new IOException("key parameters not recognized"); } } + + private static ASN1Sequence getBasicPQCEncoding(byte[] seed, byte[] expanded) + { + ASN1EncodableVector v = new ASN1EncodableVector(2); + + v.add(new DEROctetString(seed)); + + v.add(new DEROctetString(expanded)); + + return new DERSequence(v); + } } diff --git a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java index ce82d7c6c5..566b086915 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java +++ b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/PublicKeyFactory.java @@ -12,13 +12,14 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; -import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; import org.bouncycastle.pqc.asn1.CMCEPublicKey; -import org.bouncycastle.pqc.asn1.KyberPublicKey; +import org.bouncycastle.pqc.asn1.McElieceCCA2PublicKey; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; import org.bouncycastle.pqc.crypto.bike.BIKEParameters; @@ -27,14 +28,16 @@ import org.bouncycastle.pqc.crypto.cmce.CMCEPublicKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPublicKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPublicKeyParameters; @@ -46,9 +49,12 @@ import org.bouncycastle.pqc.crypto.picnic.PicnicPublicKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; import org.bouncycastle.pqc.crypto.saber.SABERPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPublicKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PublicKeyParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; @@ -64,7 +70,9 @@ public class PublicKeyFactory { converters.put(PQCObjectIdentifiers.sphincs256, new SPHINCSConverter()); converters.put(PQCObjectIdentifiers.newHope, new NHConverter()); + converters.put(PQCObjectIdentifiers.mcElieceCca2, new McElieceCCA2Converter()); converters.put(BCObjectIdentifiers.sphincsPlus, new SPHINCSPlusConverter()); + converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, new SPHINCSPlusConverter()); @@ -83,23 +91,10 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3, new SPHINCSPlusConverter()); - - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_128f_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_192s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_192f_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, new SPHINCSPlusConverter()); - converters.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, new SPHINCSPlusConverter()); converters.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, new SPHINCSPlusConverter()); @@ -166,15 +161,17 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.ntruhps2048509, new NtruConverter()); converters.put(BCObjectIdentifiers.ntruhps2048677, new NtruConverter()); converters.put(BCObjectIdentifiers.ntruhps4096821, new NtruConverter()); + converters.put(BCObjectIdentifiers.ntruhps40961229, new NtruConverter()); converters.put(BCObjectIdentifiers.ntruhrss701, new NtruConverter()); + converters.put(BCObjectIdentifiers.ntruhrss1373, new NtruConverter()); converters.put(BCObjectIdentifiers.falcon_512, new FalconConverter()); converters.put(BCObjectIdentifiers.falcon_1024, new FalconConverter()); - converters.put(BCObjectIdentifiers.kyber512, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber768, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber1024, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber512_aes, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber768_aes, new KyberConverter()); - converters.put(BCObjectIdentifiers.kyber1024_aes, new KyberConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_512, new MLKEMKeyConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_768, new MLKEMKeyConverter()); + converters.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, new MLKEMKeyConverter()); + converters.put(BCObjectIdentifiers.kyber512_aes, new MLKEMKeyConverter()); + converters.put(BCObjectIdentifiers.kyber768_aes, new MLKEMKeyConverter()); + converters.put(BCObjectIdentifiers.kyber1024_aes, new MLKEMKeyConverter()); converters.put(BCObjectIdentifiers.ntrulpr653, new NTRULPrimeConverter()); converters.put(BCObjectIdentifiers.ntrulpr761, new NTRULPrimeConverter()); converters.put(BCObjectIdentifiers.ntrulpr857, new NTRULPrimeConverter()); @@ -187,6 +184,12 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.sntrup953, new SNTRUPrimeConverter()); converters.put(BCObjectIdentifiers.sntrup1013, new SNTRUPrimeConverter()); converters.put(BCObjectIdentifiers.sntrup1277, new SNTRUPrimeConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_44, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_65, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_ml_dsa_87, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, new MLDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, new MLDSAConverter()); converters.put(BCObjectIdentifiers.dilithium2, new DilithiumConverter()); converters.put(BCObjectIdentifiers.dilithium3, new DilithiumConverter()); converters.put(BCObjectIdentifiers.dilithium5, new DilithiumConverter()); @@ -199,6 +202,31 @@ public class PublicKeyFactory converters.put(BCObjectIdentifiers.hqc128, new HQCConverter()); converters.put(BCObjectIdentifiers.hqc192, new HQCConverter()); converters.put(BCObjectIdentifiers.hqc256, new HQCConverter()); + + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, new SLHDSAConverter()); + converters.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, new SLHDSAConverter()); } /** @@ -373,6 +401,18 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } + private static class McElieceCCA2Converter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + McElieceCCA2PublicKey mKey = McElieceCCA2PublicKey.getInstance(keyInfo.parsePublicKey()); + + return new McElieceCCA2PublicKeyParameters(mKey.getN(), mKey.getT(), mKey.getG(), Utils.getDigestName(mKey.getDigest().getAlgorithm())); + } + } + private static class FrodoConverter extends SubjectPublicKeyInfoConverter { @@ -431,25 +471,42 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } - private static class KyberConverter + static class MLKEMKeyConverter extends SubjectPublicKeyInfoConverter { AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { - KyberParameters kyberParameters = Utils.kyberParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + MLKEMParameters parameters = Utils.mlkemParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + // we're a raw encoding + return new MLKEMPublicKeyParameters(parameters, keyInfo.getPublicKeyData().getOctets()); + } + static MLKEMPublicKeyParameters getPublicKeyParams(MLKEMParameters parameters, ASN1BitString publicKeyData) + { try { - ASN1Primitive obj = keyInfo.parsePublicKey(); - KyberPublicKey kyberKey = KyberPublicKey.getInstance(obj); + ASN1Primitive obj = ASN1Primitive.fromByteArray(publicKeyData.getOctets()); + if (obj instanceof ASN1Sequence) + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(obj); - return new KyberPublicKeyParameters(kyberParameters, kyberKey.getT(), kyberKey.getRho()); + return new MLKEMPublicKeyParameters(parameters, + ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(), + ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets()); + } + else + { + byte[] encKey = ASN1OctetString.getInstance(obj).getOctets(); + + return new MLKEMPublicKeyParameters(parameters, encKey); + } } catch (Exception e) { // we're a raw encoding - return new KyberPublicKeyParameters(kyberParameters, keyInfo.getPublicKeyData().getOctets()); + return new MLKEMPublicKeyParameters(parameters, publicKeyData.getOctets()); } } } @@ -521,6 +578,45 @@ static DilithiumPublicKeyParameters getPublicKeyParams(DilithiumParameters dilit } } + static class MLDSAConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + MLDSAParameters dilithiumParams = Utils.mldsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return getPublicKeyParams(dilithiumParams, keyInfo.getPublicKeyData()); + } + + static MLDSAPublicKeyParameters getPublicKeyParams(MLDSAParameters dilithiumParams, ASN1BitString publicKeyData) + { + try + { + ASN1Primitive obj = ASN1Primitive.fromByteArray(publicKeyData.getOctets()); + if (obj instanceof ASN1Sequence) + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(obj); + + return new MLDSAPublicKeyParameters(dilithiumParams, + ASN1OctetString.getInstance(keySeq.getObjectAt(0)).getOctets(), + ASN1OctetString.getInstance(keySeq.getObjectAt(1)).getOctets()); + } + else + { + byte[] encKey = ASN1OctetString.getInstance(obj).getOctets(); + + return new MLDSAPublicKeyParameters(dilithiumParams, encKey); + } + } + catch (Exception e) + { + // we're a raw encoding + return new MLDSAPublicKeyParameters(dilithiumParams, publicKeyData.getOctets()); + } + } + } + private static class BIKEConverter extends SubjectPublicKeyInfoConverter { @@ -571,4 +667,29 @@ AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Obje } } } + + private static class SLHDSAConverter + extends SubjectPublicKeyInfoConverter + { + AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) + throws IOException + { + try + { + byte[] keyEnc = ASN1OctetString.getInstance(keyInfo.parsePublicKey()).getOctets(); + + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SLHDSAPublicKeyParameters(spParams, Arrays.copyOfRange(keyEnc, 4, keyEnc.length)); + } + catch (Exception e) + { + byte[] keyEnc = keyInfo.getPublicKeyData().getOctets(); + + SLHDSAParameters spParams = Utils.slhdsaParamsLookup(keyInfo.getAlgorithm().getAlgorithm()); + + return new SLHDSAPublicKeyParameters(spParams, keyEnc); + } + } + } } diff --git a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java index 8de43144a4..33ecbd4c2c 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java +++ b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/SubjectPublicKeyInfoFactory.java @@ -4,28 +4,32 @@ import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; +import org.bouncycastle.pqc.asn1.McElieceCCA2PublicKey; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; import org.bouncycastle.pqc.crypto.bike.BIKEPublicKeyParameters; import org.bouncycastle.pqc.crypto.cmce.CMCEPublicKeyParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumPublicKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; import org.bouncycastle.pqc.crypto.falcon.FalconPublicKeyParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoPublicKeyParameters; import org.bouncycastle.pqc.crypto.hqc.HQCPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.newhope.NHPublicKeyParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUPublicKeyParameters; import org.bouncycastle.pqc.crypto.ntruprime.NTRULPRimePublicKeyParameters; import org.bouncycastle.pqc.crypto.ntruprime.SNTRUPrimePublicKeyParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicPublicKeyParameters; import org.bouncycastle.pqc.crypto.saber.SABERPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSPublicKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusPublicKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCCA2PublicKeyParameters; /** * Factory to create ASN.1 subject public key info objects from lightweight public keys. @@ -62,6 +66,15 @@ else if (publicKey instanceof NHPublicKeyParameters) AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.newHope); return new SubjectPublicKeyInfo(algorithmIdentifier, params.getPubData()); } + else if (publicKey instanceof SLHDSAPublicKeyParameters) + { + SLHDSAPublicKeyParameters params = (SLHDSAPublicKeyParameters)publicKey; + + byte[] encoding = params.getEncoded(); + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.slhdsaOidLookup(params.getParameters())); + return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); + } else if (publicKey instanceof SPHINCSPlusPublicKeyParameters) { SPHINCSPlusPublicKeyParameters params = (SPHINCSPlusPublicKeyParameters)publicKey; @@ -81,6 +94,14 @@ else if (publicKey instanceof CMCEPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, encoding); } + else if (publicKey instanceof McElieceCCA2PublicKeyParameters) + { + McElieceCCA2PublicKeyParameters pub = (McElieceCCA2PublicKeyParameters)publicKey; + McElieceCCA2PublicKey mcEliecePub = new McElieceCCA2PublicKey(pub.getN(), pub.getT(), pub.getG(), Utils.getAlgorithmIdentifier(pub.getDigest())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.mcElieceCca2); + + return new SubjectPublicKeyInfo(algorithmIdentifier, mcEliecePub); + } else if (publicKey instanceof FrodoPublicKeyParameters) { FrodoPublicKeyParameters params = (FrodoPublicKeyParameters)publicKey; @@ -132,11 +153,11 @@ else if (publicKey instanceof FalconPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, keyEnc); } - else if (publicKey instanceof KyberPublicKeyParameters) + else if (publicKey instanceof MLKEMPublicKeyParameters) { - KyberPublicKeyParameters params = (KyberPublicKeyParameters)publicKey; + MLKEMPublicKeyParameters params = (MLKEMPublicKeyParameters)publicKey; - AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.kyberOidLookup(params.getParameters())); + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mlkemOidLookup(params.getParameters())); return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); } @@ -166,6 +187,14 @@ else if (publicKey instanceof DilithiumPublicKeyParameters) return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); } + else if (publicKey instanceof MLDSAPublicKeyParameters) + { + MLDSAPublicKeyParameters params = (MLDSAPublicKeyParameters)publicKey; + + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Utils.mldsaOidLookup(params.getParameters())); + + return new SubjectPublicKeyInfo(algorithmIdentifier, params.getEncoded()); + } else if (publicKey instanceof BIKEPublicKeyParameters) { BIKEPublicKeyParameters params = (BIKEPublicKeyParameters) publicKey; diff --git a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/Utils.java b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/Utils.java index b7095f4950..2c7d923e7a 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/Utils.java +++ b/core/src/main/jdk1.4/org/bouncycastle/pqc/crypto/util/Utils.java @@ -1,32 +1,40 @@ package org.bouncycastle.pqc.crypto.util; +import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.BERTags; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.SPHINCS256KeyParams; import org.bouncycastle.pqc.crypto.bike.BIKEParameters; import org.bouncycastle.pqc.crypto.cmce.CMCEParameters; import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; import org.bouncycastle.pqc.crypto.falcon.FalconParameters; import org.bouncycastle.pqc.crypto.frodo.FrodoParameters; import org.bouncycastle.pqc.crypto.hqc.HQCParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; import org.bouncycastle.pqc.crypto.ntruprime.NTRULPRimeParameters; import org.bouncycastle.pqc.crypto.ntruprime.SNTRUPrimeParameters; import org.bouncycastle.pqc.crypto.picnic.PicnicParameters; import org.bouncycastle.pqc.crypto.saber.SABERParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; import org.bouncycastle.pqc.crypto.sphincs.SPHINCSKeyParameters; import org.bouncycastle.pqc.crypto.sphincsplus.SPHINCSPlusParameters; import org.bouncycastle.util.Integers; @@ -62,9 +70,6 @@ class Utils static final Map falconOids = new HashMap(); static final Map falconParams = new HashMap(); - static final Map kyberOids = new HashMap(); - static final Map kyberParams = new HashMap(); - static final Map ntruprimeOids = new HashMap(); static final Map ntruprimeParams = new HashMap(); @@ -83,6 +88,15 @@ class Utils static final Map rainbowOids = new HashMap(); static final Map rainbowParams = new HashMap(); + static final Map mlkemOids = new HashMap(); + static final Map mlkemParams = new HashMap(); + + static final Map mldsaOids = new HashMap(); + static final Map mldsaParams = new HashMap(); + + static final Map slhdsaOids = new HashMap(); + static final Map slhdsaParams = new HashMap(); + static { mcElieceOids.put(CMCEParameters.mceliece348864r3, BCObjectIdentifiers.mceliece348864_r3); @@ -188,12 +202,16 @@ class Utils ntruOids.put(NTRUParameters.ntruhps2048509, BCObjectIdentifiers.ntruhps2048509); ntruOids.put(NTRUParameters.ntruhps2048677, BCObjectIdentifiers.ntruhps2048677); ntruOids.put(NTRUParameters.ntruhps4096821, BCObjectIdentifiers.ntruhps4096821); + ntruOids.put(NTRUParameters.ntruhps40961229, BCObjectIdentifiers.ntruhps40961229); ntruOids.put(NTRUParameters.ntruhrss701, BCObjectIdentifiers.ntruhrss701); + ntruOids.put(NTRUParameters.ntruhrss1373, BCObjectIdentifiers.ntruhrss1373); ntruParams.put(BCObjectIdentifiers.ntruhps2048509, NTRUParameters.ntruhps2048509); ntruParams.put(BCObjectIdentifiers.ntruhps2048677, NTRUParameters.ntruhps2048677); ntruParams.put(BCObjectIdentifiers.ntruhps4096821, NTRUParameters.ntruhps4096821); + ntruParams.put(BCObjectIdentifiers.ntruhps40961229, NTRUParameters.ntruhps40961229); ntruParams.put(BCObjectIdentifiers.ntruhrss701, NTRUParameters.ntruhrss701); + ntruParams.put(BCObjectIdentifiers.ntruhrss1373, NTRUParameters.ntruhrss1373); falconOids.put(FalconParameters.falcon_512, BCObjectIdentifiers.falcon_512); falconOids.put(FalconParameters.falcon_1024, BCObjectIdentifiers.falcon_1024); @@ -201,13 +219,13 @@ class Utils falconParams.put(BCObjectIdentifiers.falcon_512, FalconParameters.falcon_512); falconParams.put(BCObjectIdentifiers.falcon_1024, FalconParameters.falcon_1024); - kyberOids.put(KyberParameters.kyber512, BCObjectIdentifiers.kyber512); - kyberOids.put(KyberParameters.kyber768, BCObjectIdentifiers.kyber768); - kyberOids.put(KyberParameters.kyber1024, BCObjectIdentifiers.kyber1024); + mlkemOids.put(MLKEMParameters.ml_kem_512, NISTObjectIdentifiers.id_alg_ml_kem_512); + mlkemOids.put(MLKEMParameters.ml_kem_768, NISTObjectIdentifiers.id_alg_ml_kem_768); + mlkemOids.put(MLKEMParameters.ml_kem_1024, NISTObjectIdentifiers.id_alg_ml_kem_1024); - kyberParams.put(BCObjectIdentifiers.kyber512, KyberParameters.kyber512); - kyberParams.put(BCObjectIdentifiers.kyber768, KyberParameters.kyber768); - kyberParams.put(BCObjectIdentifiers.kyber1024, KyberParameters.kyber1024); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_512, MLKEMParameters.ml_kem_512); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_768, MLKEMParameters.ml_kem_768); + mlkemParams.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, MLKEMParameters.ml_kem_1024); ntruprimeOids.put(NTRULPRimeParameters.ntrulpr653, BCObjectIdentifiers.ntrulpr653); ntruprimeOids.put(NTRULPRimeParameters.ntrulpr761, BCObjectIdentifiers.ntrulpr761); @@ -237,6 +255,20 @@ class Utils sntruprimeParams.put(BCObjectIdentifiers.sntrup1013, SNTRUPrimeParameters.sntrup1013); sntruprimeParams.put(BCObjectIdentifiers.sntrup1277, SNTRUPrimeParameters.sntrup1277); + mldsaOids.put(MLDSAParameters.ml_dsa_44, NISTObjectIdentifiers.id_ml_dsa_44); + mldsaOids.put(MLDSAParameters.ml_dsa_65, NISTObjectIdentifiers.id_ml_dsa_65); + mldsaOids.put(MLDSAParameters.ml_dsa_87, NISTObjectIdentifiers.id_ml_dsa_87); + mldsaOids.put(MLDSAParameters.ml_dsa_44_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + mldsaOids.put(MLDSAParameters.ml_dsa_65_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + mldsaOids.put(MLDSAParameters.ml_dsa_87_with_sha512, NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_44, MLDSAParameters.ml_dsa_44); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_65, MLDSAParameters.ml_dsa_65); + mldsaParams.put(NISTObjectIdentifiers.id_ml_dsa_87, MLDSAParameters.ml_dsa_87); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, MLDSAParameters.ml_dsa_44_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, MLDSAParameters.ml_dsa_65_with_sha512); + mldsaParams.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, MLDSAParameters.ml_dsa_87_with_sha512); + dilithiumOids.put(DilithiumParameters.dilithium2, BCObjectIdentifiers.dilithium2); dilithiumOids.put(DilithiumParameters.dilithium3, BCObjectIdentifiers.dilithium3); dilithiumOids.put(DilithiumParameters.dilithium5, BCObjectIdentifiers.dilithium5); @@ -261,6 +293,71 @@ class Utils hqcOids.put(HQCParameters.hqc192, BCObjectIdentifiers.hqc192); hqcOids.put(HQCParameters.hqc256, BCObjectIdentifiers.hqc256); + slhdsaOids.put(SLHDSAParameters.sha2_128s, NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + slhdsaOids.put(SLHDSAParameters.sha2_128f, NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + slhdsaOids.put(SLHDSAParameters.sha2_192s, NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + slhdsaOids.put(SLHDSAParameters.sha2_192f, NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + slhdsaOids.put(SLHDSAParameters.sha2_256s, NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + slhdsaOids.put(SLHDSAParameters.sha2_256f, NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + slhdsaOids.put(SLHDSAParameters.shake_128s, NISTObjectIdentifiers.id_slh_dsa_shake_128s); + slhdsaOids.put(SLHDSAParameters.shake_128f, NISTObjectIdentifiers.id_slh_dsa_shake_128f); + slhdsaOids.put(SLHDSAParameters.shake_192s, NISTObjectIdentifiers.id_slh_dsa_shake_192s); + slhdsaOids.put(SLHDSAParameters.shake_192f, NISTObjectIdentifiers.id_slh_dsa_shake_192f); + slhdsaOids.put(SLHDSAParameters.shake_256s, NISTObjectIdentifiers.id_slh_dsa_shake_256s); + slhdsaOids.put(SLHDSAParameters.shake_256f, NISTObjectIdentifiers.id_slh_dsa_shake_256f); + + slhdsaOids.put(SLHDSAParameters.sha2_128s_with_sha256, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + slhdsaOids.put(SLHDSAParameters.sha2_128f_with_sha256, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + slhdsaOids.put(SLHDSAParameters.sha2_192s_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + slhdsaOids.put(SLHDSAParameters.sha2_192f_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + slhdsaOids.put(SLHDSAParameters.sha2_256s_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + slhdsaOids.put(SLHDSAParameters.sha2_256f_with_sha512, NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + slhdsaOids.put(SLHDSAParameters.shake_128s_with_shake128, NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + slhdsaOids.put(SLHDSAParameters.shake_128f_with_shake128, NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + slhdsaOids.put(SLHDSAParameters.shake_192s_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + slhdsaOids.put(SLHDSAParameters.shake_192f_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + slhdsaOids.put(SLHDSAParameters.shake_256s_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + slhdsaOids.put(SLHDSAParameters.shake_256f_with_shake256, NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, SLHDSAParameters.sha2_128s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, SLHDSAParameters.sha2_128f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, SLHDSAParameters.sha2_192s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, SLHDSAParameters.sha2_192f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, SLHDSAParameters.sha2_256s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, SLHDSAParameters.sha2_256f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, SLHDSAParameters.shake_128s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, SLHDSAParameters.shake_128f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, SLHDSAParameters.shake_192s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, SLHDSAParameters.shake_192f); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, SLHDSAParameters.shake_256s); + slhdsaParams.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, SLHDSAParameters.shake_256f); + + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, SLHDSAParameters.sha2_128s_with_sha256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, SLHDSAParameters.sha2_128f_with_sha256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, SLHDSAParameters.sha2_192s_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, SLHDSAParameters.sha2_192f_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, SLHDSAParameters.sha2_256s_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, SLHDSAParameters.sha2_256f_with_sha512); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, SLHDSAParameters.shake_128s_with_shake128); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, SLHDSAParameters.shake_128f_with_shake128); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, SLHDSAParameters.shake_192s_with_shake256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, SLHDSAParameters.shake_192f_with_shake256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, SLHDSAParameters.shake_256s_with_shake256); + slhdsaParams.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, SLHDSAParameters.shake_256f_with_shake256); + + sphincsPlusOids.put(SLHDSAParameters.sha2_128s, BCObjectIdentifiers.sphincsPlus_sha2_128s); + sphincsPlusOids.put(SLHDSAParameters.sha2_128f, BCObjectIdentifiers.sphincsPlus_sha2_128f); + sphincsPlusOids.put(SLHDSAParameters.sha2_192s, BCObjectIdentifiers.sphincsPlus_sha2_192s); + sphincsPlusOids.put(SLHDSAParameters.sha2_192f, BCObjectIdentifiers.sphincsPlus_sha2_192f); + sphincsPlusOids.put(SLHDSAParameters.sha2_256s, BCObjectIdentifiers.sphincsPlus_sha2_256s); + sphincsPlusOids.put(SLHDSAParameters.sha2_256f, BCObjectIdentifiers.sphincsPlus_sha2_256f); + sphincsPlusOids.put(SLHDSAParameters.shake_128s, BCObjectIdentifiers.sphincsPlus_shake_128s); + sphincsPlusOids.put(SLHDSAParameters.shake_128f, BCObjectIdentifiers.sphincsPlus_shake_128f); + sphincsPlusOids.put(SLHDSAParameters.shake_192s, BCObjectIdentifiers.sphincsPlus_shake_192s); + sphincsPlusOids.put(SLHDSAParameters.shake_192f, BCObjectIdentifiers.sphincsPlus_shake_192f); + sphincsPlusOids.put(SLHDSAParameters.shake_256s, BCObjectIdentifiers.sphincsPlus_shake_256s); + sphincsPlusOids.put(SLHDSAParameters.shake_256f, BCObjectIdentifiers.sphincsPlus_shake_256f); + sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128s_robust, BCObjectIdentifiers.sphincsPlus_sha2_128s_r3); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128f_robust, BCObjectIdentifiers.sphincsPlus_sha2_128f_r3); sphincsPlusOids.put(SPHINCSPlusParameters.shake_128s_robust, BCObjectIdentifiers.sphincsPlus_shake_128s_r3); @@ -279,7 +376,6 @@ class Utils sphincsPlusOids.put(SPHINCSPlusParameters.shake_256f_robust, BCObjectIdentifiers.sphincsPlus_shake_256f_r3); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_256s, BCObjectIdentifiers.sphincsPlus_haraka_256s_r3); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_256f, BCObjectIdentifiers.sphincsPlus_haraka_256f_r3); - sphincsPlusOids.put(SPHINCSPlusParameters.haraka_128s_simple, BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_128f_simple, BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple); sphincsPlusOids.put(SPHINCSPlusParameters.haraka_192s_simple, BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple); @@ -289,14 +385,14 @@ class Utils sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128s, BCObjectIdentifiers.sphincsPlus_sha2_128s); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_128f, BCObjectIdentifiers.sphincsPlus_sha2_128f); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_128s, BCObjectIdentifiers.sphincsPlus_shake_128s); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_128f, BCObjectIdentifiers.sphincsPlus_shake_128f); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_192s, BCObjectIdentifiers.sphincsPlus_sha2_192s); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_192f, BCObjectIdentifiers.sphincsPlus_sha2_192f); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_192s, BCObjectIdentifiers.sphincsPlus_shake_192s); - sphincsPlusOids.put(SPHINCSPlusParameters.shake_192f, BCObjectIdentifiers.sphincsPlus_shake_192f); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_256s, BCObjectIdentifiers.sphincsPlus_sha2_256s); sphincsPlusOids.put(SPHINCSPlusParameters.sha2_256f, BCObjectIdentifiers.sphincsPlus_sha2_256f); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_128s, BCObjectIdentifiers.sphincsPlus_shake_128s); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_128f, BCObjectIdentifiers.sphincsPlus_shake_128f); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_192s, BCObjectIdentifiers.sphincsPlus_shake_192s); + sphincsPlusOids.put(SPHINCSPlusParameters.shake_192f, BCObjectIdentifiers.sphincsPlus_shake_192f); sphincsPlusOids.put(SPHINCSPlusParameters.shake_256s, BCObjectIdentifiers.sphincsPlus_shake_256s); sphincsPlusOids.put(SPHINCSPlusParameters.shake_256f, BCObjectIdentifiers.sphincsPlus_shake_256f); @@ -312,7 +408,6 @@ class Utils sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_256f, SPHINCSPlusParameters.sha2_256f); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256s, SPHINCSPlusParameters.shake_256s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256f, SPHINCSPlusParameters.shake_256f); - sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, SPHINCSPlusParameters.sha2_128s_robust); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, SPHINCSPlusParameters.sha2_128f_robust); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, SPHINCSPlusParameters.shake_128s_robust); @@ -331,7 +426,6 @@ class Utils sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, SPHINCSPlusParameters.shake_256f_robust); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3, SPHINCSPlusParameters.haraka_256s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3, SPHINCSPlusParameters.haraka_256f); - sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, SPHINCSPlusParameters.sha2_128s); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, SPHINCSPlusParameters.sha2_128f); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, SPHINCSPlusParameters.shake_128s); @@ -351,7 +445,17 @@ class Utils sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, SPHINCSPlusParameters.haraka_256s_simple); sphincsPlusParams.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, SPHINCSPlusParameters.haraka_256f_simple); } - + + static ASN1ObjectIdentifier slhdsaOidLookup(SLHDSAParameters params) + { + return (ASN1ObjectIdentifier)slhdsaOids.get(params); + } + + static SLHDSAParameters slhdsaParamsLookup(ASN1ObjectIdentifier oid) + { + return (SLHDSAParameters)slhdsaParams.get(oid); + } + static AlgorithmIdentifier sphincs256LookupTreeAlgID(String treeDigest) { if (treeDigest.equals(SPHINCSKeyParameters.SHA3_256)) @@ -530,14 +634,14 @@ static NTRUParameters ntruParamsLookup(ASN1ObjectIdentifier oid) return (NTRUParameters)ntruParams.get(oid); } - static ASN1ObjectIdentifier kyberOidLookup(KyberParameters params) + static ASN1ObjectIdentifier mlkemOidLookup(MLKEMParameters params) { - return (ASN1ObjectIdentifier)kyberOids.get(params); + return (ASN1ObjectIdentifier)mlkemOids.get(params); } - static KyberParameters kyberParamsLookup(ASN1ObjectIdentifier oid) + static MLKEMParameters mlkemParamsLookup(ASN1ObjectIdentifier oid) { - return (KyberParameters)kyberParams.get(oid); + return (MLKEMParameters)mlkemParams.get(oid); } static ASN1ObjectIdentifier ntrulprimeOidLookup(NTRULPRimeParameters params) @@ -560,6 +664,16 @@ static SNTRUPrimeParameters sntruprimeParamsLookup(ASN1ObjectIdentifier oid) return (SNTRUPrimeParameters)sntruprimeParams.get(oid); } + static ASN1ObjectIdentifier mldsaOidLookup(MLDSAParameters params) + { + return (ASN1ObjectIdentifier)mldsaOids.get(params); + } + + static MLDSAParameters mldsaParamsLookup(ASN1ObjectIdentifier oid) + { + return (MLDSAParameters)mldsaParams.get(oid); + } + static ASN1ObjectIdentifier dilithiumOidLookup(DilithiumParameters params) { return (ASN1ObjectIdentifier)dilithiumOids.get(params); @@ -589,4 +703,81 @@ static HQCParameters hqcParamsLookup(ASN1ObjectIdentifier oid) { return (HQCParameters)hqcParams.get(oid); } + + + private static boolean isRaw(byte[] data) + { + // check well-formed first + ByteArrayInputStream bIn = new ByteArrayInputStream(data); + + int tag = bIn.read(); + int len = readLen(bIn); + if (len != bIn.available()) + { + return true; + } + + return false; + } + + static ASN1OctetString parseOctetData(byte[] data) + { + // check well-formed first + if (!isRaw(data)) + { + if (data[0] == BERTags.OCTET_STRING) + { + return ASN1OctetString.getInstance(data); + } + } + + return null; + } + + static ASN1Primitive parseData(byte[] data) + { + // check well-formed first + if (!isRaw(data)) + { + if (data[0] == (BERTags.SEQUENCE | BERTags.CONSTRUCTED)) + { + return ASN1Sequence.getInstance(data); + } + + if (data[0] == BERTags.OCTET_STRING) + { + return ASN1OctetString.getInstance(data); + } + + if ((data[0] & 0xff) == BERTags.TAGGED) + { + return ASN1OctetString.getInstance(ASN1TaggedObject.getInstance(data), false); + } + } + + return null; + } + + /** + * ASN.1 length reader. + */ + static int readLen(ByteArrayInputStream bIn) + { + int length = bIn.read(); + if (length < 0) + { + return -1; + } + if (length != (length & 0x7f)) + { + int count = length & 0x7f; + length = 0; + while (count-- != 0) + { + length = (length << 8) + bIn.read(); + } + } + + return length; + } } diff --git a/core/src/main/jdk1.4/org/bouncycastle/util/Arrays.java b/core/src/main/jdk1.4/org/bouncycastle/util/Arrays.java index ef5d23662f..5adfcad624 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/util/Arrays.java +++ b/core/src/main/jdk1.4/org/bouncycastle/util/Arrays.java @@ -962,6 +962,14 @@ public static void clear(int[] data) } } + public static void clear(long[] data) + { + if (null != data) + { + java.util.Arrays.fill(data, 0); + } + } + public static boolean isNullOrContainsNull(Object[] array) { if (null == array) @@ -1137,6 +1145,28 @@ public static int hashCode(Object[] data) return hc; } + public static boolean segmentsOverlap(int aOff, int aLen, int bOff, int bLen) + { + return aLen > 0 + && bLen > 0 + && aOff - bOff < bLen + && bOff - aOff < aLen; + } + + public static void validateSegment(byte[] buf, int off, int len) + { + if (buf == null) + { + throw new NullPointerException("'buf' cannot be null"); + } + int available = buf.length - off; + int remaining = available - len; + if ((off | len | available | remaining) < 0) + { + throw new IndexOutOfBoundsException("buf.length: " + buf.length + ", off: " + off + ", len: " + len); + } + } + /** * Iterator backed by a specific array. */ diff --git a/core/src/main/jdk1.4/org/bouncycastle/util/Bytes.java b/core/src/main/jdk1.4/org/bouncycastle/util/Bytes.java index 526a27659e..25a9ce4431 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/util/Bytes.java +++ b/core/src/main/jdk1.4/org/bouncycastle/util/Bytes.java @@ -16,6 +16,14 @@ public static void xor(int len, byte[] x, byte[] y, byte[] z) } } + public static void xor(int len, byte[] x, int xOff, byte[] y, byte[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff++] = (byte)(x[xOff++] ^ y[i]); + } + } + public static void xor(int len, byte[] x, int xOff, byte[] y, int yOff, byte[] z, int zOff) { for (int i = 0; i < len; ++i) @@ -23,7 +31,23 @@ public static void xor(int len, byte[] x, int xOff, byte[] y, int yOff, byte[] z z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); } } - + + public static void xor(int len, byte[] x, byte[] y, byte[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff++] = (byte)(x[i] ^ y[i]); + } + } + + public static void xor(int len, byte[] x, byte[] y, int yOff, byte[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff++] = (byte)(x[i] ^ y[yOff++]); + } + } + public static void xorTo(int len, byte[] x, byte[] z) { for (int i = 0; i < len; ++i) @@ -32,6 +56,14 @@ public static void xorTo(int len, byte[] x, byte[] z) } } + public static void xorTo(int len, byte[] x, int xOff, byte[] z) + { + for (int i = 0; i < len; ++i) + { + z[i] ^= x[xOff++]; + } + } + public static void xorTo(int len, byte[] x, int xOff, byte[] z, int zOff) { for (int i = 0; i < len; ++i) diff --git a/core/src/main/jdk1.4/org/bouncycastle/util/Longs.java b/core/src/main/jdk1.4/org/bouncycastle/util/Longs.java index 5baea19a67..4e6d5f09a8 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/util/Longs.java +++ b/core/src/main/jdk1.4/org/bouncycastle/util/Longs.java @@ -77,4 +77,12 @@ public static Long valueOf(long value) { return new Long(value); } + + public static void xorTo(int len, long[] x, int xOff, long[] z, int zOff) + { + for (int i = 0; i < len; ++i) + { + z[zOff + i] ^= x[xOff + i]; + } + } } diff --git a/core/src/main/jdk1.4/org/bouncycastle/util/Properties.java b/core/src/main/jdk1.4/org/bouncycastle/util/Properties.java index efcf32cdb9..258ba9f2dc 100644 --- a/core/src/main/jdk1.4/org/bouncycastle/util/Properties.java +++ b/core/src/main/jdk1.4/org/bouncycastle/util/Properties.java @@ -48,6 +48,32 @@ public static boolean isOverrideSet(String propertyName) } } + /** + * Return whether a particular override has been set to true. + * + * @param propertyName the property name for the override. + * @return true if the property is set to "true", false otherwise. + */ + public static boolean isOverrideSet(String propertyName, boolean defIsTrue) + { + try + { + String value = getPropertyValue(propertyName); + if (value == null) + { + return defIsTrue; + } + else + { + return "true".equalsIgnoreCase(value); + } + } + catch (AccessControlException e) + { + return false; + } + } + /** * Enable the specified override property for the current thread only. * diff --git a/core/src/main/jdk1.5/org/bouncycastle/util/Exceptions.java b/core/src/main/jdk1.5/org/bouncycastle/util/Exceptions.java new file mode 100644 index 0000000000..af4f07eac4 --- /dev/null +++ b/core/src/main/jdk1.5/org/bouncycastle/util/Exceptions.java @@ -0,0 +1,22 @@ +package org.bouncycastle.util; + +import java.io.IOException; + +public class Exceptions +{ + public static IllegalArgumentException illegalArgumentException(String message, Throwable cause) + { + return new IllegalArgumentException(message, cause); + } + + public static IllegalStateException illegalStateException(String message, Throwable cause) + { + return new IllegalStateException(message, cause); + } + + public static IOException ioException(String message, Throwable cause) + { + return new IOException(message + "-" + cause.getMessage()); + } + +} diff --git a/core/src/test/java/org/bouncycastle/asn1/test/CertIDTest.java b/core/src/test/java/org/bouncycastle/asn1/test/CertIDTest.java new file mode 100644 index 0000000000..e162f0e9ac --- /dev/null +++ b/core/src/test/java/org/bouncycastle/asn1/test/CertIDTest.java @@ -0,0 +1,54 @@ +package org.bouncycastle.asn1.test; + +import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.DERNull; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.ocsp.CertID; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; +import org.bouncycastle.util.BigIntegers; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.test.SimpleTest; + +public class CertIDTest + extends SimpleTest +{ + public String getName() + { + return "CertID"; + } + + public void performTest() + throws Exception + { + DEROctetString issuerAHash = new DEROctetString(Strings.toByteArray("IssuerAHash")); + DEROctetString issuerBHash = new DEROctetString(Strings.toByteArray("IssuerBHash")); + DEROctetString issuerAKeyHash = new DEROctetString(Strings.toByteArray("IssuerAKeyHash")); + DEROctetString issuerBKeyHash = new DEROctetString(Strings.toByteArray("IssuerBKeyHash")); + + CertID a = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), issuerAHash, issuerAKeyHash, new ASN1Integer(BigIntegers.ONE)); + CertID b = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), issuerAHash, issuerAKeyHash, new ASN1Integer(BigIntegers.ONE)); + CertID c = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DEROctetString(new byte[1])), issuerAHash, issuerAKeyHash, new ASN1Integer(BigIntegers.ONE)); + + isTrue(a.equals(a)); + isTrue(a.equals(b)); + isTrue(a.hashCode() == b.hashCode()); + isTrue(!a.equals(c)); + isTrue(a.hashCode() != c.hashCode()); + + b = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), issuerAHash, issuerAKeyHash, new ASN1Integer(BigIntegers.TWO)); + isTrue(!a.equals(b)); + b = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm), issuerAHash, issuerAKeyHash, new ASN1Integer(BigIntegers.ONE)); + isTrue(!a.equals(b)); + b = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), issuerBHash, issuerAKeyHash, new ASN1Integer(BigIntegers.ONE)); + isTrue(!a.equals(b)); + b = new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), issuerAHash, issuerBKeyHash, new ASN1Integer(BigIntegers.ONE)); + isTrue(!a.equals(b)); + } + + public static void main( + String[] args) + { + runTest(new CertIDTest()); + } +} diff --git a/core/src/test/java/org/bouncycastle/asn1/test/GenerationTest.java b/core/src/test/java/org/bouncycastle/asn1/test/GenerationTest.java index a90f144ecb..86acbe2dcf 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/GenerationTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/GenerationTest.java @@ -412,7 +412,7 @@ public void testDuplicateExtensions() // ExtensionsGenerator genX = new ExtensionsGenerator(); - genX.addExtension(ext); + genX.addExtensions(ext); ext = Extensions.getInstance(ASN1Sequence.getInstance(genX.generate().getEncoded())); returnedExtension = ext.getExtension(Extension.subjectAlternativeName); diff --git a/core/src/test/java/org/bouncycastle/asn1/test/IssuingDistributionPointUnitTest.java b/core/src/test/java/org/bouncycastle/asn1/test/IssuingDistributionPointUnitTest.java index fa0af30aca..75eb9a2ef2 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/IssuingDistributionPointUnitTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/IssuingDistributionPointUnitTest.java @@ -27,7 +27,9 @@ public void performTest() new GeneralNames(new GeneralName(new X500Name("cn=test")))); ReasonFlags reasonFlags = new ReasonFlags(ReasonFlags.cACompromise); - checkPoint(6, name, true, true, reasonFlags, true, true); + checkOnlyException(name, true, true, reasonFlags, true, true); + checkOnlyException(name, true, true, reasonFlags, true, false); + checkOnlyException(name, true, false, reasonFlags, true, true); checkPoint(2, name, false, false, reasonFlags, false, false); @@ -45,6 +47,26 @@ public void performTest() } } + private void checkOnlyException( + DistributionPointName distributionPoint, + boolean onlyContainsUserCerts, + boolean onlyContainsCACerts, + ReasonFlags onlySomeReasons, + boolean indirectCRL, + boolean onlyContainsAttributeCerts) + throws IOException + { + try + { + new IssuingDistributionPoint(distributionPoint, onlyContainsUserCerts, onlyContainsCACerts, onlySomeReasons, indirectCRL, onlyContainsAttributeCerts); + fail("no exception"); + } + catch (IllegalArgumentException e) + { + isEquals("only one of onlyContainsCACerts, onlyContainsUserCerts, or onlyContainsAttributeCerts can be true", e.getMessage()); + } + } + private void checkPoint( int size, DistributionPointName distributionPoint, diff --git a/core/src/test/java/org/bouncycastle/asn1/test/LinkedCertificateTest.java b/core/src/test/java/org/bouncycastle/asn1/test/LinkedCertificateTest.java index 340e5f317d..72e9eb5294 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/LinkedCertificateTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/LinkedCertificateTest.java @@ -70,11 +70,7 @@ private void checkConstruction( checkValues(linked, digestInfo, certLocation, certIssuer, caCerts); - ASN1InputStream aIn = new ASN1InputStream(linked.toASN1Primitive().getEncoded()); - - ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); - - linked = LinkedCertificate.getInstance(seq); + linked = LinkedCertificate.getInstance(linked.getEncoded()); checkValues(linked, digestInfo, certLocation, certIssuer, caCerts); } diff --git a/core/src/test/java/org/bouncycastle/asn1/test/ObjectIdentifierTest.java b/core/src/test/java/org/bouncycastle/asn1/test/ObjectIdentifierTest.java index f5e00d2f9a..36b032ee02 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/ObjectIdentifierTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/ObjectIdentifierTest.java @@ -1,6 +1,7 @@ package org.bouncycastle.asn1.test; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestResult; @@ -24,7 +25,24 @@ public void performTest() { isEquals("invalid OID contents", e.getMessage()); } - + + byte[] faultyOID = Hex.decode("06092A864886FC6B048000"); + try + { + ASN1ObjectIdentifier.getInstance(faultyOID); + fail("no exception"); + } + catch (Exception e) + { + isEquals("failed to construct object identifier from byte[]: invalid OID contents", e.getMessage()); + } + + System.setProperty("org.bouncycastle.asn1.allow_wrong_oid_enc", "true"); + String oid = ASN1ObjectIdentifier.getInstance(faultyOID).getId(); + + System.setProperty("org.bouncycastle.asn1.allow_wrong_oid_enc", "false"); + isEquals("1.2.840.114283.4.0", oid); + // exercise the object cache for (int i = 0; i < 100; i++) { diff --git a/core/src/test/java/org/bouncycastle/asn1/test/RegressionTest.java b/core/src/test/java/org/bouncycastle/asn1/test/RegressionTest.java index b42a20f200..0cdcfbf37a 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/RegressionTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/RegressionTest.java @@ -55,7 +55,8 @@ public class RegressionTest new DLExternalTest(), new KMACParamsTest(), new DERPrivateTest(), - new X509AltTest() + new X509AltTest(), + new CertIDTest() }; public static void main(String[] args) diff --git a/core/src/test/java/org/bouncycastle/asn1/test/X500NameTest.java b/core/src/test/java/org/bouncycastle/asn1/test/X500NameTest.java index 4f79462665..8ddbdc87f4 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/X500NameTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/X500NameTest.java @@ -435,6 +435,8 @@ public void performTest() fail("strict comparison failed"); } + equalityTest(new X500Name(""), new X500Name("")); + // // inequality to sequences // @@ -663,6 +665,10 @@ public void performTest() { fail("padded equality test failed"); } + + isTrue(BCStyle.INSTANCE.attrNameToOID("jurisdictionCountry").equals(BCStyle.JURISDICTION_C)); + isTrue(BCStyle.INSTANCE.attrNameToOID("jurisdictionState").equals(BCStyle.JURISDICTION_ST)); + isTrue(BCStyle.INSTANCE.attrNameToOID("jurisdictionLocality").equals(BCStyle.JURISDICTION_L)); } private String getValue(RDN vl) diff --git a/core/src/test/java/org/bouncycastle/asn1/test/X509NameTest.java b/core/src/test/java/org/bouncycastle/asn1/test/X509NameTest.java index 9d5880cf28..0378c83e74 100644 --- a/core/src/test/java/org/bouncycastle/asn1/test/X509NameTest.java +++ b/core/src/test/java/org/bouncycastle/asn1/test/X509NameTest.java @@ -402,6 +402,8 @@ public void performTest() equalityTest(n1, n2); + equalityTest(new X509Name(""), new X509Name("")); + // // inequality to sequences // diff --git a/core/src/test/java/org/bouncycastle/crypto/agreement/test/AllTests.java b/core/src/test/java/org/bouncycastle/crypto/agreement/test/AllTests.java index 79e009227c..85f8a60131 100644 --- a/core/src/test/java/org/bouncycastle/crypto/agreement/test/AllTests.java +++ b/core/src/test/java/org/bouncycastle/crypto/agreement/test/AllTests.java @@ -22,6 +22,10 @@ public static Test suite() suite.addTestSuite(JPAKEPrimeOrderGroupTest.class); suite.addTestSuite(JPAKEUtilTest.class); + suite.addTestSuite(ECJPAKEParticipantTest.class); + suite.addTestSuite(ECJPAKECurveTest.class); + suite.addTestSuite(ECJPAKEUtilTest.class); + return new BCTestSetup(suite); } diff --git a/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKECurveTest.java b/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKECurveTest.java new file mode 100644 index 0000000000..45df15c442 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKECurveTest.java @@ -0,0 +1,107 @@ +package org.bouncycastle.crypto.agreement.test; + +import java.math.BigInteger; + +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurve; + +import junit.framework.TestCase; + + +public class ECJPAKECurveTest + extends TestCase +{ + + public void testConstruction() + throws CryptoException + { + //a + BigInteger a = new BigInteger("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", 16); + //b + BigInteger b = new BigInteger("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16); + //q + BigInteger q = new BigInteger("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", 16); + //n + BigInteger n = new BigInteger("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 16); + //h + BigInteger h = BigInteger.ONE; + //g_x + BigInteger g_x = new BigInteger("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", 16); + BigInteger g_y = new BigInteger("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", 16); + +// ECCurve.Fp curve = new ECCurve.Fp(q, a, b, n, h); +// ECPoint g = curve.createPoint( +// new BigInteger("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", 16), +// new BigInteger("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", 16) +// ); + + // q not prime + try + { + new ECJPAKECurve(BigInteger.valueOf(15), a, b, n, h, g_x, g_y); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // a is not in the field [0,q-1] + try + { + new ECJPAKECurve(q, BigInteger.valueOf(-1), b, n, h, g_x, g_y); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // b is not in the field [0,q-1] + try + { + new ECJPAKECurve(q, a, BigInteger.valueOf(-1), n, h, g_x, g_y); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // Discriminant is zero + try + { + new ECJPAKECurve(q, q.subtract(BigInteger.valueOf(3)), BigInteger.valueOf(2), n, h, g_x, g_y); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // n is not prime + try + { + new ECJPAKECurve(q, a, b, BigInteger.valueOf(15), h, g_x, g_y); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // G is not on the curve + try + { + new ECJPAKECurve(q, a, b, n, h, BigInteger.valueOf(2), BigInteger.valueOf(3)); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // should work + new ECJPAKECurve(q, a, b, n, h, g_x, g_y); + } +} diff --git a/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKEParticipantTest.java b/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKEParticipantTest.java new file mode 100644 index 0000000000..c8cbf97e22 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKEParticipantTest.java @@ -0,0 +1,540 @@ +package org.bouncycastle.crypto.agreement.test; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurve; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurves; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKEParticipant; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKERound1Payload; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKERound2Payload; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKERound3Payload; +import org.bouncycastle.crypto.digests.SHA256Digest; + +public class ECJPAKEParticipantTest + extends TestCase +{ + + public void testConstruction() + throws CryptoException + { + ECJPAKECurve curve = ECJPAKECurves.NIST_P256; + SecureRandom random = new SecureRandom(); + Digest digest = new SHA256Digest(); + String participantId = "participantId"; + char[] password = "password".toCharArray(); + + new ECJPAKEParticipant(participantId, password, curve, digest, random); + + // null participantID + try + { + new ECJPAKEParticipant(null, password, curve, digest, random); + fail(); + } + catch (NullPointerException e) + { + // pass + } + + // null password + try + { + new ECJPAKEParticipant(participantId, null, curve, digest, random); + fail(); + } + catch (NullPointerException e) + { + // pass + } + + // empty password + try + { + new ECJPAKEParticipant(participantId, "".toCharArray(), curve, digest, random); + fail(); + } + catch (IllegalArgumentException e) + { + // pass + } + + // null curve + try + { + new ECJPAKEParticipant(participantId, password, null, digest, random); + fail(); + } + catch (NullPointerException e) + { + // pass + } + + // null digest + try + { + new ECJPAKEParticipant(participantId, password, curve, null, random); + fail(); + } + catch (NullPointerException e) + { + // pass + } + + // null random + try + { + new ECJPAKEParticipant(participantId, password, curve, digest, null); + fail(); + } + catch (NullPointerException e) + { + // pass + } + } + + public void testSuccessfulExchange() + throws CryptoException + { + + ECJPAKEParticipant alice = createAlice(); + ECJPAKEParticipant bob = createBob(); + + ExchangeAfterRound2Creation exchange = runExchangeUntilRound2Creation(alice, bob); + + alice.validateRound2PayloadReceived(exchange.bobRound2Payload); + bob.validateRound2PayloadReceived(exchange.aliceRound2Payload); + + BigInteger aliceKeyingMaterial = alice.calculateKeyingMaterial(); + BigInteger bobKeyingMaterial = bob.calculateKeyingMaterial(); + + ECJPAKERound3Payload aliceRound3Payload = alice.createRound3PayloadToSend(aliceKeyingMaterial); + ECJPAKERound3Payload bobRound3Payload = bob.createRound3PayloadToSend(bobKeyingMaterial); + + alice.validateRound3PayloadReceived(bobRound3Payload, aliceKeyingMaterial); + bob.validateRound3PayloadReceived(aliceRound3Payload, bobKeyingMaterial); + + assertEquals(aliceKeyingMaterial, bobKeyingMaterial); + + } + + public void testIncorrectPassword() + throws CryptoException + { + ECJPAKEParticipant alice = createAlice(); + ECJPAKEParticipant bob = createBobWithWrongPassword(); + + ExchangeAfterRound2Creation exchange = runExchangeUntilRound2Creation(alice, bob); + + alice.validateRound2PayloadReceived(exchange.bobRound2Payload); + bob.validateRound2PayloadReceived(exchange.aliceRound2Payload); + + BigInteger aliceKeyingMaterial = alice.calculateKeyingMaterial(); + BigInteger bobKeyingMaterial = bob.calculateKeyingMaterial(); + + ECJPAKERound3Payload aliceRound3Payload = alice.createRound3PayloadToSend(aliceKeyingMaterial); + ECJPAKERound3Payload bobRound3Payload = bob.createRound3PayloadToSend(bobKeyingMaterial); + + // Validate incorrect passwords result in a CryptoException + try + { + alice.validateRound3PayloadReceived(bobRound3Payload, aliceKeyingMaterial); + fail(); + } + catch (CryptoException e) + { + // pass + } + + try + { + bob.validateRound3PayloadReceived(aliceRound3Payload, bobKeyingMaterial); + fail(); + } + catch (CryptoException e) + { + // pass + } + } + + public void testStateValidation() + throws CryptoException + { + + ECJPAKEParticipant alice = createAlice(); + ECJPAKEParticipant bob = createBob(); + + // We're testing alice here. Bob is just used for help. + + // START ROUND 1 CHECKS + + assertEquals(ECJPAKEParticipant.STATE_INITIALIZED, alice.getState()); + + // create round 2 before round 1 + try + { + alice.createRound2PayloadToSend(); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + ECJPAKERound1Payload aliceRound1Payload = alice.createRound1PayloadToSend(); + + assertEquals(ECJPAKEParticipant.STATE_ROUND_1_CREATED, alice.getState()); + + // create round 1 payload twice + try + { + alice.createRound1PayloadToSend(); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + // create round 2 before validating round 1 + try + { + alice.createRound2PayloadToSend(); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + // validate round 2 before validating round 1 + try + { + alice.validateRound2PayloadReceived(null); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + ECJPAKERound1Payload bobRound1Payload = bob.createRound1PayloadToSend(); + + alice.validateRound1PayloadReceived(bobRound1Payload); + + assertEquals(ECJPAKEParticipant.STATE_ROUND_1_VALIDATED, alice.getState()); + + // validate round 1 payload twice + try + { + alice.validateRound1PayloadReceived(bobRound1Payload); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + bob.validateRound1PayloadReceived(aliceRound1Payload); + + // START ROUND 2 CHECKS + + ECJPAKERound2Payload aliceRound2Payload = alice.createRound2PayloadToSend(); + + assertEquals(ECJPAKEParticipant.STATE_ROUND_2_CREATED, alice.getState()); + + // create round 2 payload twice + try + { + alice.createRound2PayloadToSend(); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + // create key before validating round 2 + try + { + alice.calculateKeyingMaterial(); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + // validate round 3 before validating round 2 + try + { + alice.validateRound3PayloadReceived(null, null); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + ECJPAKERound2Payload bobRound2Payload = bob.createRound2PayloadToSend(); + + alice.validateRound2PayloadReceived(bobRound2Payload); + + assertEquals(ECJPAKEParticipant.STATE_ROUND_2_VALIDATED, alice.getState()); + + // validate round 2 payload twice + try + { + alice.validateRound2PayloadReceived(bobRound2Payload); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + bob.validateRound2PayloadReceived(aliceRound2Payload); + + // create round 3 before calculating key + try + { + alice.createRound3PayloadToSend(BigInteger.ONE); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + // START KEY CALCULATION CHECKS + + BigInteger aliceKeyingMaterial = alice.calculateKeyingMaterial(); + + assertEquals(ECJPAKEParticipant.STATE_KEY_CALCULATED, alice.getState()); + + // calculate key twice + try + { + alice.calculateKeyingMaterial(); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + BigInteger bobKeyingMaterial = bob.calculateKeyingMaterial(); + + // START ROUND 3 CHECKS + + ECJPAKERound3Payload aliceRound3Payload = alice.createRound3PayloadToSend(aliceKeyingMaterial); + + assertEquals(ECJPAKEParticipant.STATE_ROUND_3_CREATED, alice.getState()); + + // create round 3 payload twice + try + { + alice.createRound3PayloadToSend(aliceKeyingMaterial); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + ECJPAKERound3Payload bobRound3Payload = bob.createRound3PayloadToSend(bobKeyingMaterial); + + alice.validateRound3PayloadReceived(bobRound3Payload, aliceKeyingMaterial); + + assertEquals(ECJPAKEParticipant.STATE_ROUND_3_VALIDATED, alice.getState()); + + // validate round 3 payload twice + try + { + alice.validateRound3PayloadReceived(bobRound3Payload, aliceKeyingMaterial); + fail(); + } + catch (IllegalStateException e) + { + // pass + } + + bob.validateRound3PayloadReceived(aliceRound3Payload, bobKeyingMaterial); + + + } + + public void testValidateRound1PayloadReceived() + throws CryptoException + { + + // We're testing alice here. Bob is just used for help. + ECJPAKERound1Payload bobRound1Payload = createBob().createRound1PayloadToSend(); + + // should succeed + createAlice().validateRound1PayloadReceived(bobRound1Payload); + + // alice verifies alice's payload + try + { + ECJPAKEParticipant alice = createAlice(); + alice.validateRound1PayloadReceived(alice.createRound1PayloadToSend()); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // g^x4 = infinity + ECJPAKECurve curve = ECJPAKECurves.NIST_P256; + try + { + createAlice().validateRound1PayloadReceived(new ECJPAKERound1Payload( + bobRound1Payload.getParticipantId(), + bobRound1Payload.getGx1(), + curve.getCurve().getInfinity(), + bobRound1Payload.getKnowledgeProofForX1(), + bobRound1Payload.getKnowledgeProofForX2())); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // zero knowledge proof for x3 fails + try + { + ECJPAKERound1Payload bobRound1Payload2 = createBob().createRound1PayloadToSend(); + createAlice().validateRound1PayloadReceived(new ECJPAKERound1Payload( + bobRound1Payload.getParticipantId(), + bobRound1Payload.getGx1(), + bobRound1Payload.getGx2(), + bobRound1Payload2.getKnowledgeProofForX1(), + bobRound1Payload.getKnowledgeProofForX2())); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // zero knowledge proof for x4 fails + try + { + ECJPAKERound1Payload bobRound1Payload2 = createBob().createRound1PayloadToSend(); + createAlice().validateRound1PayloadReceived(new ECJPAKERound1Payload( + bobRound1Payload.getParticipantId(), + bobRound1Payload.getGx1(), + bobRound1Payload.getGx2(), + bobRound1Payload.getKnowledgeProofForX1(), + bobRound1Payload2.getKnowledgeProofForX2())); + fail(); + } + catch (CryptoException e) + { + // pass + } + } + + public void testValidateRound2PayloadReceived() + throws CryptoException + { + + // We're testing alice here. Bob is just used for help. + + // should succeed + ExchangeAfterRound2Creation exchange1 = runExchangeUntilRound2Creation(createAlice(), createBob()); + exchange1.alice.validateRound2PayloadReceived(exchange1.bobRound2Payload); + + // alice verifies alice's payload + ExchangeAfterRound2Creation exchange2 = runExchangeUntilRound2Creation(createAlice(), createBob()); + try + { + exchange2.alice.validateRound2PayloadReceived(exchange2.aliceRound2Payload); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // wrong z + ExchangeAfterRound2Creation exchange3 = runExchangeUntilRound2Creation(createAlice(), createBob()); + ExchangeAfterRound2Creation exchange4 = runExchangeUntilRound2Creation(createAlice(), createBob()); + try + { + exchange3.alice.validateRound2PayloadReceived(exchange4.bobRound2Payload); + fail(); + } + catch (CryptoException e) + { + // pass + } + } + + private static class ExchangeAfterRound2Creation + { + + public ECJPAKEParticipant alice; + public ECJPAKERound2Payload aliceRound2Payload; + public ECJPAKERound2Payload bobRound2Payload; + + public ExchangeAfterRound2Creation( + ECJPAKEParticipant alice, + ECJPAKERound2Payload aliceRound2Payload, + ECJPAKERound2Payload bobRound2Payload) + { + this.alice = alice; + this.aliceRound2Payload = aliceRound2Payload; + this.bobRound2Payload = bobRound2Payload; + } + + } + + private ExchangeAfterRound2Creation runExchangeUntilRound2Creation(ECJPAKEParticipant alice, ECJPAKEParticipant bob) + throws CryptoException + { + + ECJPAKERound1Payload aliceRound1Payload = alice.createRound1PayloadToSend(); + ECJPAKERound1Payload bobRound1Payload = bob.createRound1PayloadToSend(); + + alice.validateRound1PayloadReceived(bobRound1Payload); + bob.validateRound1PayloadReceived(aliceRound1Payload); + + ECJPAKERound2Payload aliceRound2Payload = alice.createRound2PayloadToSend(); + ECJPAKERound2Payload bobRound2Payload = bob.createRound2PayloadToSend(); + + return new ExchangeAfterRound2Creation( + alice, + aliceRound2Payload, + bobRound2Payload); + } + + private ECJPAKEParticipant createAlice() + { + return createParticipant("alice", "password"); + } + + private ECJPAKEParticipant createBob() + { + return createParticipant("bob", "password"); + } + + private ECJPAKEParticipant createBobWithWrongPassword() + { + return createParticipant("bob", "wrong"); + } + + private ECJPAKEParticipant createParticipant(String participantId, String password) + { + return new ECJPAKEParticipant( + participantId, + password.toCharArray(), + ECJPAKECurves.NIST_P256); + } +} \ No newline at end of file diff --git a/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKEUtilTest.java b/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKEUtilTest.java new file mode 100644 index 0000000000..59e16d2fd9 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/agreement/test/ECJPAKEUtilTest.java @@ -0,0 +1,302 @@ +package org.bouncycastle.crypto.agreement.test; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurve; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKECurves; +import org.bouncycastle.crypto.agreement.ecjpake.ECJPAKEUtil; +import org.bouncycastle.crypto.agreement.ecjpake.ECSchnorrZKP; +import org.bouncycastle.crypto.digests.SHA1Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; + +public class ECJPAKEUtilTest + extends TestCase +{ + private static final BigInteger ONE = BigInteger.valueOf(1); + + public void testValidateParticipantIdsDiffer() + throws CryptoException + { + ECJPAKEUtil.validateParticipantIdsDiffer("a", "b"); + ECJPAKEUtil.validateParticipantIdsDiffer("a", "A"); + + try + { + ECJPAKEUtil.validateParticipantIdsDiffer("a", "a"); + fail(); + } + catch (CryptoException e) + { + // pass + } + } + + public void testValidateParticipantIdsEqual() + throws CryptoException + { + ECJPAKEUtil.validateParticipantIdsEqual("a", "a"); + + try + { + ECJPAKEUtil.validateParticipantIdsEqual("a", "b"); + fail(); + } + catch (CryptoException e) + { + // pass + } + } + + public void testValidateMacTag() + throws CryptoException + { + ECJPAKECurve curve1 = ECJPAKECurves.NIST_P256; + + SecureRandom random = new SecureRandom(); + Digest digest = SHA256Digest.newInstance(); + + BigInteger x1 = ECJPAKEUtil.generateX1(curve1.getN(), random); + BigInteger x2 = ECJPAKEUtil.generateX1(curve1.getN(), random); + BigInteger x3 = ECJPAKEUtil.generateX1(curve1.getN(), random); + BigInteger x4 = ECJPAKEUtil.generateX1(curve1.getN(), random); + + ECPoint gx1 = ECJPAKEUtil.calculateGx(curve1.getG(), x1); + ECPoint gx2 = ECJPAKEUtil.calculateGx(curve1.getG(), x2); + ECPoint gx3 = ECJPAKEUtil.calculateGx(curve1.getG(), x3); + ECPoint gx4 = ECJPAKEUtil.calculateGx(curve1.getG(), x4); + + ECPoint gB = ECJPAKEUtil.calculateGA(gx3, gx1, gx2); + + BigInteger s = ECJPAKEUtil.calculateS(curve1.getN(), "password".toCharArray()); + + BigInteger xs = ECJPAKEUtil.calculateX2s(curve1.getN(), x4, s); + + ECPoint B = ECJPAKEUtil.calculateA(gB, xs); + + BigInteger keyingMaterial = ECJPAKEUtil.calculateKeyingMaterial(curve1.getN(), gx4, x2, s, B); + + BigInteger macTag = ECJPAKEUtil.calculateMacTag("participantId", "partnerParticipantId", gx1, gx2, gx3, gx4, keyingMaterial, digest); + + ECJPAKEUtil.validateMacTag("partnerParticipantId", "participantId", gx3, gx4, gx1, gx2, keyingMaterial, digest, macTag); + + // validating own macTag (as opposed to the other party's mactag) + try + { + ECJPAKEUtil.validateMacTag("participantId", "partnerParticipantId", gx1, gx2, gx3, gx4, keyingMaterial, digest, macTag); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // participant ids switched + try + { + ECJPAKEUtil.validateMacTag("participantId", "partnerParticipantId", gx3, gx4, gx1, gx2, keyingMaterial, digest, macTag); + + fail(); + } + catch (CryptoException e) + { + // pass + } + } + + public void testValidateNotNull() + throws CryptoException + { + ECJPAKEUtil.validateNotNull("a", "description"); + + try + { + ECJPAKEUtil.validateNotNull(null, "description"); + fail(); + } + catch (NullPointerException e) + { + // pass + } + } + + public void testValidateZeroKnowledgeProof() + throws CryptoException + { + ECJPAKECurve curve1 = ECJPAKECurves.NIST_P256; + + SecureRandom random = new SecureRandom(); + Digest digest1 = SHA256Digest.newInstance(); + + BigInteger x1 = ECJPAKEUtil.generateX1(curve1.getN(), random); + ECPoint gx1 = ECJPAKEUtil.calculateGx(curve1.getG(), x1); + String participantId1 = "participant1"; + + ECSchnorrZKP zkp1 = ECJPAKEUtil.calculateZeroKnowledgeProof(curve1.getG(), curve1.getN(), x1, gx1, digest1, participantId1, random); + + // should succeed + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), gx1, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + + // wrong group + ECJPAKECurve curve2 = ECJPAKECurves.NIST_P384; + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve2.getG(), gx1, zkp1, curve2.getQ(), curve2.getN(), curve2.getCurve(), curve2.getH(), participantId1, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // wrong digest + Digest digest2 = new SHA1Digest(); + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), gx1, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest2); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // wrong participant + String participantId2 = "participant2"; + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), gx1, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId2, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // wrong gx + BigInteger x2 = ECJPAKEUtil.generateX1(curve1.getN(), random); + ECPoint gx2 = ECJPAKEUtil.calculateGx(curve1.getG(), x2); + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), gx2, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + + // wrong zkp, we need to change the zkp in some way to test if it catches it + ECSchnorrZKP zkp2 = ECJPAKEUtil.calculateZeroKnowledgeProof(curve1.getG(), curve1.getN(), x2, gx2, digest1, participantId1, random); + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), gx1, zkp2, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // gx <= Infinity + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), curve1.getCurve().getInfinity(), zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + // (x,y) elements for Gx are not in Fq ie: not in [0,q-1] + ECCurve.AbstractFp curve = curve1.getCurve(); + try + { + ECPoint invalidGx_1 = curve.createPoint(ONE.negate(), ONE); + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), invalidGx_1, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (Exception e) + { + // pass + } + try + { + + ECPoint invalidGx_2 = curve.createPoint(ONE, ONE.negate()); + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), invalidGx_2, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (Exception e) + { + // pass + } + try + { + + ECPoint invalidGx_3 = curve.createPoint(curve1.getQ(), ONE); + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), invalidGx_3, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (Exception e) + { + // pass + } + try + { + ECPoint invalidGx_4 = curve.createPoint(ONE, curve1.getQ()); + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), invalidGx_4, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId1, digest1); + fail(); + } + catch (Exception e) + { + // pass + } + + // gx is not on the curve + ECPoint invalidPoint = curve.createPoint(ONE, ONE);//Must come back and test this since (1,1) may exist on certain curves. Not for p256 though. + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), invalidPoint, zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId2, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + /* gx is such that n*gx == infinity + * Taking gx as any multiple of the generator G will create such a point + */ + + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), curve1.getG(), zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId2, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + + /* V is not a point on the curve + * i.e. V != G*r + X*h + */ + try + { + ECJPAKEUtil.validateZeroKnowledgeProof(curve1.getG(), curve.createPoint(ONE, ONE), zkp1, curve1.getQ(), curve1.getN(), curve1.getCurve(), curve1.getH(), participantId2, digest1); + fail(); + } + catch (CryptoException e) + { + // pass + } + } +} \ No newline at end of file diff --git a/core/src/test/java/org/bouncycastle/crypto/test/AESTest.java b/core/src/test/java/org/bouncycastle/crypto/test/AESTest.java index 7584ca42e4..5d56406fdb 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/AESTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/AESTest.java @@ -1,6 +1,7 @@ package org.bouncycastle.crypto.test; import java.security.SecureRandom; +import java.util.Random; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; @@ -16,6 +17,7 @@ import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; @@ -539,6 +541,59 @@ public void performTest() ctrCounterTest(); ctrFragmentedTest(); testLastByte(); + testCounter(); + } + + static byte[] fileBytes = new byte[0]; + static byte[] iv = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + private void testCounter() { + Random random = new Random(); + for (int i = 0; i < 255; i++) { + iv[iv.length - 1] += (byte) i; + + String inStr = " 1234567890jl字符串"; + for (int j = 1000; j > 0; j--) { + inStr += (char) ('a' + random.nextInt(26)); + verify(inStr); + fileBytes = new byte[0]; + } + } + } + + private void verify(String inStr) { + SICBlockCipher cipher = newCipher(); + byte[] bytes = Strings.toUTF8ByteArray(inStr); + + appendFile(bytes, cipher); + appendFile(bytes, cipher); + appendFile(bytes, cipher); + + byte[] out = new byte[fileBytes.length]; + newCipher().processBytes(fileBytes, 0, fileBytes.length, out, 0); + String outStr = Strings.fromUTF8ByteArray(out); + + if (!outStr.equals(inStr + inStr + inStr)) { + throw new RuntimeException("fail"); + } + } + + private void appendFile(byte[] bytes, SICBlockCipher cipher) { + cipher.seekTo(fileBytes.length); + byte[] out = new byte[bytes.length]; + cipher.processBytes(bytes, 0, bytes.length, out, 0); + + byte[] newFileBytes = Arrays.copyOf(fileBytes, fileBytes.length + out.length); + System.arraycopy(out, 0, newFileBytes, fileBytes.length, out.length); + fileBytes = newFileBytes; + } + + private static SICBlockCipher newCipher() { + SICBlockCipher sicBlockCipher = new SICBlockCipher(new AESEngine()); + byte[] key = "1234567890123456".getBytes(); + ParametersWithIV parametersWithIV = new ParametersWithIV(new KeyParameter(key), iv); + sicBlockCipher.init(true, parametersWithIV); + return sicBlockCipher; } public static void main( diff --git a/core/src/test/java/org/bouncycastle/crypto/test/AsconTest.java b/core/src/test/java/org/bouncycastle/crypto/test/AsconTest.java index cb6df6c288..cebd5f8f9a 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/AsconTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/AsconTest.java @@ -3,16 +3,24 @@ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; +import java.security.SecureRandom; import java.util.HashMap; import java.util.Random; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.ExtendedDigest; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.Xof; +import org.bouncycastle.crypto.digests.AsconCXof128; import org.bouncycastle.crypto.digests.AsconDigest; +import org.bouncycastle.crypto.digests.AsconHash256; import org.bouncycastle.crypto.digests.AsconXof; +import org.bouncycastle.crypto.digests.AsconXof128; +import org.bouncycastle.crypto.engines.AsconAEAD128; import org.bouncycastle.crypto.engines.AsconEngine; +import org.bouncycastle.crypto.modes.AEADCipher; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; @@ -28,7 +36,7 @@ public static void main(String[] args) { runTest(new AsconTest()); } - + public String getName() { return "Ascon"; @@ -37,27 +45,51 @@ public String getName() public void performTest() throws Exception { + testVectorsAsconCXof128_512(); + DigestTest.checkXof(new AsconXof128(), 1429, 317, new SecureRandom(), this); + DigestTest.checkXof(new AsconCXof128(), 1429, 317, new SecureRandom(), this); + DigestTest.checkXof(new AsconXof(AsconXof.AsconParameters.AsconXof), 1429, 317, new SecureRandom(), this); + DigestTest.checkXof(new AsconXof(AsconXof.AsconParameters.AsconXofA), 1429, 317, new SecureRandom(), this); + + testVectorsEngine_asconaead128(); + testVectorsDigest_AsconHash256(); + testVectorsXof_AsconXof128(); + + testBufferingEngine_asconaead128(); testBufferingEngine_ascon128(); testBufferingEngine_ascon128a(); testBufferingEngine_ascon80(); + testExceptionsDigest_AsconHash256(); testExceptionsDigest_AsconHash(); testExceptionsDigest_AsconHashA(); + testExceptionsEngine_asconaead128(); testExceptionsEngine_ascon128(); testExceptionsEngine_ascon128a(); testExceptionsEngine_ascon80pq(); + testExceptionsXof_AsconXof128(); + testExceptionsXof_AsconCXof128(); testExceptionsXof_AsconXof(); testExceptionsXof_AsconXofA(); + testOutputXof_AsconXof128(); + testOutputXof_AsconCXof128(); + testOutputXof_AsconXof(); + testOutputXof_AsconXofA(); + + testParametersDigest_AsconHash256(); testParametersDigest_AsconHash(); testParametersDigest_AsconHashA(); + testParametersEngine_asconaead128(); testParametersEngine_ascon128(); testParametersEngine_ascon128a(); testParametersEngine_ascon80pq(); + testParametersXof_AsconXof128(); + testParametersXof_AsconCXof128(); testParametersXof_AsconXof(); testParametersXof_AsconXofA(); @@ -70,126 +102,472 @@ public void performTest() testVectorsXof_AsconXof(); testVectorsXof_AsconXofA(); + + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new AsconAEAD128()); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new AsconEngine(AsconEngine.AsconParameters.ascon128)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new AsconEngine(AsconEngine.AsconParameters.ascon128a)); + CipherTest.checkAEADParemeter(this, 20, 16, 16, 16, new AsconEngine(AsconEngine.AsconParameters.ascon80pq)); + + CipherTest.testOverlapping(this,16, 16, 16, 16, new AsconAEAD128()); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new AsconEngine(AsconEngine.AsconParameters.ascon128)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new AsconEngine(AsconEngine.AsconParameters.ascon128a)); + CipherTest.testOverlapping(this, 20, 16, 16, 16, new AsconEngine(AsconEngine.AsconParameters.ascon80pq)); + + + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new AsconAEAD128(); + } + }); + + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128); + } + }); + + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128a); + } + }); + + CipherTest.checkCipher(32, 16, 100, 160, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon80pq); + } + }); + + DigestTest.checkDigestReset(this, new AsconHash256()); + DigestTest.checkDigestReset(this, new AsconXof128()); + DigestTest.checkDigestReset(this, new AsconCXof128()); + DigestTest.checkDigestReset(this, new AsconCXof128()); + DigestTest.checkDigestReset(this, new AsconXof(AsconXof.AsconParameters.AsconXof)); + DigestTest.checkDigestReset(this, new AsconXof(AsconXof.AsconParameters.AsconXofA)); + DigestTest.checkDigestReset(this, new AsconDigest(AsconDigest.AsconParameters.AsconHash)); + DigestTest.checkDigestReset(this, new AsconDigest(AsconDigest.AsconParameters.AsconHashA)); } - public void testBufferingEngine_ascon128() throws Exception + public void testBufferingEngine_ascon128() + throws Exception { - implTestBufferingEngine(AsconEngine.AsconParameters.ascon128); + implTestBufferingEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128); + } + }); } - public void testBufferingEngine_ascon128a() throws Exception + public void testBufferingEngine_ascon128a() + throws Exception { - implTestBufferingEngine(AsconEngine.AsconParameters.ascon128a); + implTestBufferingEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128a); + } + }); } - public void testBufferingEngine_ascon80() throws Exception + public void testBufferingEngine_ascon80() + throws Exception { - implTestBufferingEngine(AsconEngine.AsconParameters.ascon80pq); + implTestBufferingEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon80pq); + } + }); } - public void testExceptionsDigest_AsconHash() throws Exception + public void testBufferingEngine_asconaead128() + throws Exception { - implTestExceptionsDigest(AsconDigest.AsconParameters.AsconHash); + implTestBufferingEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconAEAD128(); + } + }); } - public void testExceptionsDigest_AsconHashA() throws Exception + public void testExceptionsDigest_AsconHash() + throws Exception { - implTestExceptionsDigest(AsconDigest.AsconParameters.AsconHashA); + implTestExceptionsDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconDigest(AsconDigest.AsconParameters.AsconHash); + } + }); } - public void testExceptionsEngine_ascon128() throws Exception + public void testExceptionsDigest_AsconHashA() + throws Exception { - implTestExceptionsEngine(AsconEngine.AsconParameters.ascon128); + implTestExceptionsDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconDigest(AsconDigest.AsconParameters.AsconHashA); + } + }); } - public void testExceptionsEngine_ascon128a() throws Exception + public void testExceptionsDigest_AsconHash256() + throws Exception { - implTestExceptionsEngine(AsconEngine.AsconParameters.ascon128a); + implTestExceptionsDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconHash256(); + } + }); } - public void testExceptionsEngine_ascon80pq() throws Exception + public void testExceptionsEngine_ascon128() + throws Exception { - implTestExceptionsEngine(AsconEngine.AsconParameters.ascon80pq); + implTestExceptionsEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128); + } + }); } - public void testExceptionsXof_AsconXof() throws Exception + public void testExceptionsEngine_ascon128a() + throws Exception { - implTestExceptionsXof(AsconXof.AsconParameters.AsconXof); + implTestExceptionsEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128a); + } + }); } - public void testExceptionsXof_AsconXofA() throws Exception + public void testExceptionsEngine_ascon80pq() + throws Exception { - implTestExceptionsXof(AsconXof.AsconParameters.AsconXofA); + implTestExceptionsEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon80pq); + } + }); } - public void testParametersDigest_AsconHash() throws Exception + public void testExceptionsEngine_asconaead128() + throws Exception { - implTestParametersDigest(AsconDigest.AsconParameters.AsconHash, 32); + implTestExceptionsEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconAEAD128(); + } + }); } - public void testParametersDigest_AsconHashA() throws Exception + public void testExceptionsXof_AsconXof() + throws Exception + { + implTestExceptionsXof(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconXof(AsconXof.AsconParameters.AsconXof); + } + }); + } + + public void testExceptionsXof_AsconXofA() + throws Exception + { + implTestExceptionsXof(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconXof(AsconXof.AsconParameters.AsconXofA); + } + }); + } + + public void testExceptionsXof_AsconXof128() + throws Exception + { + implTestExceptionsXof(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconXof128(); + } + }); + } + + public void testExceptionsXof_AsconCXof128() + throws Exception + { + implTestExceptionsXof(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconCXof128(); + } + }); + } + + public void testOutputXof_AsconXof() + { + implTestOutputXof(new AsconXof(AsconXof.AsconParameters.AsconXof)); + } + + public void testOutputXof_AsconXofA() + { + implTestOutputXof(new AsconXof(AsconXof.AsconParameters.AsconXofA)); + } + + public void testOutputXof_AsconXof128() { - implTestParametersDigest(AsconDigest.AsconParameters.AsconHashA, 32); + implTestOutputXof(new AsconXof128()); } - public void testParametersEngine_ascon128() throws Exception + public void testOutputXof_AsconCXof128() + { + implTestOutputXof(new AsconCXof128()); + } + + public void testParametersDigest_AsconHash() + throws Exception + { + implTestParametersDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconDigest(AsconDigest.AsconParameters.AsconHash); + } + }, 32); + } + + public void testParametersDigest_AsconHashA() + throws Exception + { + implTestParametersDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconDigest(AsconDigest.AsconParameters.AsconHashA); + } + }, 32); + } + + public void testParametersDigest_AsconHash256() + throws Exception + { + implTestParametersDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconHash256(); + } + }, 32); + } + + public void testParametersEngine_ascon128() + throws Exception + { + implTestParametersEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128); + } + }, 16, 16, 16); + } + + public void testParametersEngine_ascon128a() + throws Exception { - implTestParametersEngine(AsconEngine.AsconParameters.ascon128, 16, 16, 16); + implTestParametersEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon128a); + } + }, 16, 16, 16); } - public void testParametersEngine_ascon128a() throws Exception + public void testParametersEngine_ascon80pq() + throws Exception { - implTestParametersEngine(AsconEngine.AsconParameters.ascon128a, 16, 16, 16); + implTestParametersEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconEngine(AsconEngine.AsconParameters.ascon80pq); + } + }, 20, 16, 16); } - public void testParametersEngine_ascon80pq() throws Exception + public void testParametersEngine_asconaead128() + throws Exception { - implTestParametersEngine(AsconEngine.AsconParameters.ascon80pq, 20, 16, 16); + implTestParametersEngine(new CreateEngine() + { + @Override + public AEADCipher createEngine() + { + return new AsconAEAD128(); + } + }, 16, 16, 16); } - public void testParametersXof_AsconXof() throws Exception + public void testParametersXof_AsconXof() + throws Exception { implTestParametersXof(AsconXof.AsconParameters.AsconXof, 32); } - public void testParametersXof_AsconXofA() throws Exception + public void testParametersXof_AsconXofA() + throws Exception { implTestParametersXof(AsconXof.AsconParameters.AsconXofA, 32); } - public void testVectorsDigest_AsconHash() throws Exception + public void testParametersXof_AsconXof128() + throws Exception + { + implTestParametersDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconXof128(); + } + }, 32); + } + + public void testParametersXof_AsconCXof128() + throws Exception { - implTestVectorsDigest(AsconDigest.AsconParameters.AsconHash, "asconhash"); + implTestParametersDigest(new CreateDigest() + { + @Override + public ExtendedDigest createDigest() + { + return new AsconCXof128(); + } + }, 32); } - public void testVectorsDigest_AsconHashA() throws Exception + public void testVectorsDigest_AsconHash() + throws Exception { - implTestVectorsDigest(AsconDigest.AsconParameters.AsconHashA, "asconhasha"); + implTestVectorsDigest(createDigest(AsconDigest.AsconParameters.AsconHash), "crypto/ascon", "asconhash_LWC_HASH_KAT_256"); } - public void testVectorsEngine_ascon128() throws Exception + public void testVectorsDigest_AsconHashA() + throws Exception { - implTestVectorsEngine(AsconEngine.AsconParameters.ascon128, "128_128"); + implTestVectorsDigest(createDigest(AsconDigest.AsconParameters.AsconHashA), "crypto/ascon", "asconhasha_LWC_HASH_KAT_256"); } - public void testVectorsEngine_ascon128a() throws Exception + public void testVectorsEngine_ascon128() + throws Exception + { + implTestVectorsEngine(createEngine(AsconEngine.AsconParameters.ascon128), "crypto/ascon", "128_128"); + } + + public void testVectorsEngine_ascon128a() + throws Exception { - implTestVectorsEngine(AsconEngine.AsconParameters.ascon128a, "128_128_a"); + implTestVectorsEngine(createEngine(AsconEngine.AsconParameters.ascon128a), "crypto/ascon", "128_128_a"); } - public void testVectorsEngine_ascon80pq() throws Exception + public void testVectorsEngine_ascon80pq() + throws Exception { - implTestVectorsEngine(AsconEngine.AsconParameters.ascon80pq, "160_128"); + implTestVectorsEngine(createEngine(AsconEngine.AsconParameters.ascon80pq), "crypto/ascon", "160_128"); } - public void testVectorsXof_AsconXof() throws Exception + public void testVectorsEngine_asconaead128() + throws Exception { - implTestVectorsXof(AsconXof.AsconParameters.AsconXof, "asconxof"); + implTestVectorsEngine(new AsconAEAD128(), "crypto/ascon/asconaead128", "128_128"); } - public void testVectorsXof_AsconXofA() throws Exception + public void testVectorsDigest_AsconHash256() + throws Exception { - implTestVectorsXof(AsconXof.AsconParameters.AsconXofA, "asconxofa"); + implTestVectorsDigest(new AsconHash256(), "crypto/ascon/asconhash256", "LWC_HASH_KAT_256"); + } + + public void testVectorsXof_AsconXof128() + throws Exception + { + implTestVectorsXof(new AsconXof128(), "crypto/ascon/asconxof128", "LWC_HASH_KAT_256.txt"); + } + + public void testVectorsAsconCXof128_512() + throws Exception + { + implTestVectorsAsconCXof128(512 / 8, "crypto/ascon/asconcxof128", "LWC_CXOF_KAT_128_512.txt"); + } + + public void testVectorsXof_AsconXof() + throws Exception + { + implTestVectorsXof(createXof(AsconXof.AsconParameters.AsconXof), "crypto/ascon", "asconxof_LWC_HASH_KAT_256.txt"); + } + + public void testVectorsXof_AsconXofA() + throws Exception + { + implTestVectorsXof(createXof(AsconXof.AsconParameters.AsconXofA), "crypto/ascon", "asconxofa_LWC_HASH_KAT_256.txt"); } private static AsconDigest createDigest(AsconDigest.AsconParameters asconParameters) @@ -197,7 +575,17 @@ private static AsconDigest createDigest(AsconDigest.AsconParameters asconParamet return new AsconDigest(asconParameters); } - private static AsconEngine createEngine(AsconEngine.AsconParameters asconParameters) + private interface CreateDigest + { + ExtendedDigest createDigest(); + } + + private interface CreateEngine + { + AEADCipher createEngine(); + } + + private static AEADCipher createEngine(AsconEngine.AsconParameters asconParameters) { return new AsconEngine(asconParameters); } @@ -207,7 +595,7 @@ private static AsconXof createXof(AsconXof.AsconParameters asconParameters) return new AsconXof(asconParameters); } - private void implTestBufferingEngine(AsconEngine.AsconParameters asconParameters) + private void implTestBufferingEngine(CreateEngine operator) throws Exception { Random random = new Random(); @@ -216,7 +604,7 @@ private void implTestBufferingEngine(AsconEngine.AsconParameters asconParameters byte[] plaintext = new byte[plaintextLength]; random.nextBytes(plaintext); - AsconEngine ascon0 = createEngine(asconParameters); + AEADCipher ascon0 = operator.createEngine(); initEngine(ascon0, true); byte[] ciphertext = new byte[ascon0.getOutputSize(plaintextLength)]; @@ -230,7 +618,7 @@ private void implTestBufferingEngine(AsconEngine.AsconParameters asconParameters // Encryption for (int split = 1; split < plaintextLength; ++split) { - AsconEngine ascon = createEngine(asconParameters); + AEADCipher ascon = operator.createEngine(); initEngine(ascon, true); random.nextBytes(output); @@ -241,7 +629,7 @@ private void implTestBufferingEngine(AsconEngine.AsconParameters asconParameters { fail(""); } - + length += ascon.processBytes(plaintext, split, plaintextLength - split, output, length); length += ascon.doFinal(output, length); @@ -254,7 +642,7 @@ private void implTestBufferingEngine(AsconEngine.AsconParameters asconParameters // Decryption for (int split = 1; split < ciphertextLength; ++split) { - AsconEngine ascon = createEngine(asconParameters); + AEADCipher ascon = operator.createEngine(); initEngine(ascon, false); random.nextBytes(output); @@ -276,9 +664,9 @@ private void implTestBufferingEngine(AsconEngine.AsconParameters asconParameters } } - private void implTestExceptionsDigest(AsconDigest.AsconParameters asconParameters) + private void implTestExceptionsDigest(CreateDigest operator) { - AsconDigest ascon = createDigest(asconParameters); + ExtendedDigest ascon = operator.createDigest(); try { @@ -301,11 +689,23 @@ private void implTestExceptionsDigest(AsconDigest.AsconParameters asconParameter } } - private void implTestExceptionsEngine(AsconEngine.AsconParameters asconParameters) + private void implTestExceptionsEngine(CreateEngine operator) throws Exception { - AsconEngine ascon = createEngine(asconParameters); - int keySize = ascon.getKeyBytesSize(), ivSize = ascon.getIVBytesSize(); + AEADCipher ascon = operator.createEngine(); + + int keySize, ivSize; + if (ascon instanceof AsconEngine) + { + keySize = ((AsconEngine)ascon).getKeyBytesSize(); + ivSize = ((AsconEngine)ascon).getIVBytesSize(); + } + else + { + keySize = ((AsconAEAD128)ascon).getKeyBytesSize(); + ivSize = ((AsconAEAD128)ascon).getIVBytesSize(); + } + int offset; byte[] k = new byte[keySize]; byte[] iv = new byte[ivSize]; @@ -577,8 +977,8 @@ private void implTestExceptionsEngine(AsconEngine.AsconParameters asconParameter } } - private void implTestExceptionsGetUpdateOutputSize(AsconEngine ascon, boolean forEncryption, - CipherParameters parameters, int maxInputSize) + private void implTestExceptionsGetUpdateOutputSize(AEADCipher ascon, boolean forEncryption, + CipherParameters parameters, int maxInputSize) { ascon.init(forEncryption, parameters); @@ -611,9 +1011,9 @@ private void implTestExceptionsGetUpdateOutputSize(AsconEngine ascon, boolean fo } } - private void implTestExceptionsXof(AsconXof.AsconParameters asconParameters) + private void implTestExceptionsXof(CreateDigest operator) { - AsconXof ascon = createXof(asconParameters); + ExtendedDigest ascon = operator.createDigest(); try { @@ -636,9 +1036,38 @@ private void implTestExceptionsXof(AsconXof.AsconParameters asconParameters) } } - private void implTestParametersDigest(AsconDigest.AsconParameters asconParameters, int digestSize) + private void implTestOutputXof(Xof ascon) { - AsconDigest ascon = createDigest(asconParameters); + Random random = new Random(); + + byte[] expected = new byte[64]; + ascon.doFinal(expected, 0, expected.length); + + byte[] output = new byte[64]; + for (int i = 0; i < 64; ++i) + { + random.nextBytes(output); + + int pos = 0; + while (pos <= output.length - 16) + { + int len = random.nextInt(17); + ascon.doOutput(output, pos, len); + pos += len; + } + + ascon.doFinal(output, pos, output.length - pos); + + if (!areEqual(expected, output)) + { + fail(""); + } + } + } + + private void implTestParametersDigest(CreateDigest operator, int digestSize) + { + ExtendedDigest ascon = operator.createDigest(); if (ascon.getDigestSize() != digestSize) { @@ -646,16 +1075,26 @@ private void implTestParametersDigest(AsconDigest.AsconParameters asconParameter } } - private void implTestParametersEngine(AsconEngine.AsconParameters asconParameters, int keySize, int ivSize, - int macSize) + private void implTestParametersEngine(CreateEngine operator, int keySize, int ivSize, + int macSize) { - AsconEngine ascon = createEngine(asconParameters); - - if (ascon.getKeyBytesSize() != keySize) + AEADCipher ascon = operator.createEngine(); + int keySize2, ivSize2; + if (ascon instanceof AsconEngine) + { + keySize2 = ((AsconEngine)ascon).getKeyBytesSize(); + ivSize2 = ((AsconEngine)ascon).getIVBytesSize(); + } + else + { + keySize2 = ((AsconAEAD128)ascon).getKeyBytesSize(); + ivSize2 = ((AsconAEAD128)ascon).getIVBytesSize(); + } + if (keySize2 != keySize) { fail("key bytes of " + ascon.getAlgorithmName() + " is not correct"); } - if (ascon.getIVBytesSize() != ivSize) + if (ivSize2 != ivSize) { fail("iv bytes of " + ascon.getAlgorithmName() + " is not correct"); } @@ -685,12 +1124,11 @@ private void implTestParametersXof(AsconXof.AsconParameters asconParameters, int } } - private void implTestVectorsDigest(AsconDigest.AsconParameters asconParameters, String filename) + private void implTestVectorsDigest(ExtendedDigest ascon, String path, String filename) throws Exception { Random random = new Random(); - AsconDigest ascon = createDigest(asconParameters); - InputStream src = TestResourceFinder.findTestResource("crypto/ascon", filename + "_LWC_HASH_KAT_256.txt"); + InputStream src = TestResourceFinder.findTestResource(path, filename + ".txt"); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line; HashMap map = new HashMap(); @@ -732,12 +1170,11 @@ private void implTestVectorsDigest(AsconDigest.AsconParameters asconParameters, } } - private void implTestVectorsEngine(AsconEngine.AsconParameters asconParameters, String filename) + private void implTestVectorsEngine(AEADCipher ascon, String path, String filename) throws Exception { Random random = new Random(); - AsconEngine ascon = createEngine(asconParameters); - InputStream src = TestResourceFinder.findTestResource("crypto/ascon", "LWC_AEAD_KAT_" + filename + ".txt"); + InputStream src = TestResourceFinder.findTestResource(path, "LWC_AEAD_KAT_" + filename + ".txt"); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line; HashMap map = new HashMap(); @@ -746,6 +1183,11 @@ private void implTestVectorsEngine(AsconEngine.AsconParameters asconParameters, int a = line.indexOf('='); if (a < 0) { + int count = Integer.parseInt((String)map.get("Count")); +// if (count != 34) +// { +// continue; +// } byte[] key = Hex.decode((String)map.get("Key")); byte[] nonce = Hex.decode((String)map.get("Nonce")); byte[] ad = Hex.decode((String)map.get("AD")); @@ -787,7 +1229,7 @@ private void implTestVectorsEngine(AsconEngine.AsconParameters asconParameters, mismatch("Reccover Keystream " + map.get("Count"), (String)map.get("PT"), rv); } } - + //System.out.println("pass "+ count); map.clear(); } else @@ -797,12 +1239,60 @@ private void implTestVectorsEngine(AsconEngine.AsconParameters asconParameters, } } - private void implTestVectorsXof(AsconXof.AsconParameters asconParameters, String filename) + private void implTestVectorsAsconCXof128(int hash_length, String path, String filename) throws Exception { Random random = new Random(); - AsconXof ascon = createXof(asconParameters); - InputStream src = TestResourceFinder.findTestResource("crypto/ascon", filename + "_LWC_HASH_KAT_256.txt"); + + InputStream src = TestResourceFinder.findTestResource(path, filename); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + String line; + HashMap map = new HashMap(); + while ((line = bin.readLine()) != null) + { + int a = line.indexOf('='); + if (a < 0) + { + byte[] zByte = Hex.decode((String)map.get("Z")); + byte[] ptByte = Hex.decode((String)map.get("Msg")); + byte[] expected = Hex.decode((String)map.get("MD")); + + byte[] hash = new byte[hash_length]; + + AsconCXof128 ascon = new AsconCXof128(zByte); + ascon.update(ptByte, 0, ptByte.length); + ascon.doFinal(hash, 0, hash_length); + if (!areEqual(hash, expected)) + { + mismatch("Keystream " + map.get("Count"), (String)map.get("MD"), hash); + } + + if (ptByte.length > 1) + { + int split = random.nextInt(ptByte.length - 1) + 1; + ascon = new AsconCXof128(zByte); + ascon.update(ptByte, 0, split); + ascon.update(ptByte, split, ptByte.length - split); + ascon.doFinal(hash, 0, hash_length); + if (!areEqual(hash, expected)) + { + mismatch("Keystream " + map.get("Count"), (String)map.get("MD"), hash); + } + } + } + else + { + map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + private void implTestVectorsXof(Xof ascon, String path, String filename) + throws Exception + { + Random random = new Random(); + + InputStream src = TestResourceFinder.findTestResource(path, filename); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line; HashMap map = new HashMap(); @@ -847,10 +1337,19 @@ private void mismatch(String name, String expected, byte[] found) fail("mismatch on " + name, expected, new String(Hex.encode(found))); } - private static void initEngine(AsconEngine ascon, boolean forEncryption) + private static void initEngine(AEADCipher ascon, boolean forEncryption) { - int keySize = ascon.getKeyBytesSize(); - int ivSize = ascon.getIVBytesSize(); + int keySize, ivSize; + if (ascon instanceof AsconEngine) + { + keySize = ((AsconEngine)ascon).getKeyBytesSize(); + ivSize = ((AsconEngine)ascon).getIVBytesSize(); + } + else + { + keySize = ((AsconAEAD128)ascon).getKeyBytesSize(); + ivSize = ((AsconAEAD128)ascon).getIVBytesSize(); + } int macSize = ivSize * 8; AEADParameters parameters = new AEADParameters(new KeyParameter(new byte[keySize]), macSize, new byte[ivSize], null); diff --git a/core/src/test/java/org/bouncycastle/crypto/test/CTSTest.java b/core/src/test/java/org/bouncycastle/crypto/test/CTSTest.java index e59c95844b..5b61e8d2d2 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/CTSTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/CTSTest.java @@ -1,5 +1,7 @@ package org.bouncycastle.crypto.test; +import java.security.SecureRandom; + import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; @@ -14,6 +16,7 @@ import org.bouncycastle.crypto.modes.SICBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; @@ -23,22 +26,22 @@ public class CTSTest extends SimpleTest { - static byte[] in1 = Hex.decode("4e6f7720697320746865207420"); - static byte[] in2 = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f0aaa"); - static byte[] out1 = Hex.decode("9952f131588465033fa40e8a98"); - static byte[] out2 = Hex.decode("358f84d01eb42988dc34efb994"); - static byte[] out3 = Hex.decode("170171cfad3f04530c509b0c1f0be0aefbd45a8e3755a873bff5ea198504b71683c6"); - + static byte[] in1 = Hex.decode("4e6f7720697320746865207420"); + static byte[] in2 = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f0aaa"); + static byte[] out1 = Hex.decode("9952f131588465033fa40e8a98"); + static byte[] out2 = Hex.decode("358f84d01eb42988dc34efb994"); + static byte[] out3 = Hex.decode("170171cfad3f04530c509b0c1f0be0aefbd45a8e3755a873bff5ea198504b71683c6"); + private void testCTS( - int id, - BlockCipher cipher, - CipherParameters params, - byte[] input, - byte[] output) + int id, + BlockCipher cipher, + CipherParameters params, + byte[] input, + byte[] output) throws Exception { - byte[] out = new byte[input.length]; - BufferedBlockCipher engine = new CTSBlockCipher(cipher); + byte[] out = new byte[input.length]; + BufferedBlockCipher engine = new CTSBlockCipher(cipher); engine.init(true, params); @@ -64,15 +67,15 @@ private void testCTS( } private void testOldCTS( - int id, - BlockCipher cipher, - CipherParameters params, - byte[] input, - byte[] output) - throws Exception + int id, + BlockCipher cipher, + CipherParameters params, + byte[] input, + byte[] output) + throws Exception { - byte[] out = new byte[input.length]; - BufferedBlockCipher engine = new OldCTSBlockCipher(cipher); + byte[] out = new byte[input.length]; + BufferedBlockCipher engine = new OldCTSBlockCipher(cipher); engine.init(true, params); @@ -97,77 +100,159 @@ private void testOldCTS( } } - private void testExceptions() throws InvalidCipherTextException + private void testExceptions() + throws InvalidCipherTextException { BufferedBlockCipher engine = new CTSBlockCipher(new DESEngine()); CipherParameters params = new KeyParameter(new byte[engine.getBlockSize()]); engine.init(true, params); byte[] out = new byte[engine.getOutputSize(engine.getBlockSize())]; - + engine.processBytes(new byte[engine.getBlockSize() - 1], 0, engine.getBlockSize() - 1, out, 0); - try + try { engine.doFinal(out, 0); fail("Expected CTS encrypt error on < 1 block input"); - } catch(DataLengthException e) + } + catch (DataLengthException e) { // Expected } engine.init(true, params); engine.processBytes(new byte[engine.getBlockSize()], 0, engine.getBlockSize(), out, 0); - try + try { engine.doFinal(out, 0); - } catch(DataLengthException e) + } + catch (DataLengthException e) { fail("Unexpected CTS encrypt error on == 1 block input"); } engine.init(false, params); engine.processBytes(new byte[engine.getBlockSize() - 1], 0, engine.getBlockSize() - 1, out, 0); - try + try { engine.doFinal(out, 0); fail("Expected CTS decrypt error on < 1 block input"); - } catch(DataLengthException e) + } + catch (DataLengthException e) { // Expected } engine.init(false, params); engine.processBytes(new byte[engine.getBlockSize()], 0, engine.getBlockSize(), out, 0); - try + try { engine.doFinal(out, 0); - } catch(DataLengthException e) + } + catch (DataLengthException e) { fail("Unexpected CTS decrypt error on == 1 block input"); } - try + try { new CTSBlockCipher(SICBlockCipher.newInstance(AESEngine.newInstance())); fail("Expected CTS construction error - only ECB/CBC supported."); - } catch(IllegalArgumentException e) + } + catch (IllegalArgumentException e) { // Expected } } + private void testOverlapping() + throws Exception + { + //Skip the dofinal of the test + CTSBlockCipher bc = new CTSBlockCipher(AESEngine.newInstance()); + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[16]; + random.nextBytes(keyBytes); + KeyParameter key = new KeyParameter(keyBytes); + + int offset = 1 + random.nextInt(bc.getBlockSize() - 1) + bc.getBlockSize(); + byte[] data = new byte[bc.getBlockSize() * 4 + offset]; + byte[] expected = new byte[bc.getOutputSize(bc.getBlockSize() * 3)]; + random.nextBytes(data); + + bc.init(true, key); + int len = bc.processBytes(data, 0, expected.length, expected, 0); + bc.doFinal(expected, len); + bc.init(true, key); + len = bc.processBytes(data, 0, expected.length, data, offset); + bc.doFinal(data, offset + len); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping encryption"); + } + + bc.init(false, key); + bc.processBytes(data, 0, expected.length, expected, 0); + bc.init(false, key); + bc.processBytes(data, 0, expected.length, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping decryption"); + } + } + + private void testOverlapping2() + throws Exception + { + //Skip the dofinal of the test + OldCTSBlockCipher bc = new OldCTSBlockCipher(AESEngine.newInstance()); + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[16]; + random.nextBytes(keyBytes); + KeyParameter key = new KeyParameter(keyBytes); + + int offset = 1 + random.nextInt(bc.getBlockSize() - 1) + bc.getBlockSize(); + byte[] data = new byte[bc.getBlockSize() * 4 + offset]; + byte[] expected = new byte[bc.getOutputSize(bc.getBlockSize() * 3)]; + random.nextBytes(data); + + bc.init(true, key); + int len = bc.processBytes(data, 0, expected.length, expected, 0); + bc.doFinal(expected, len); + bc.init(true, key); + len = bc.processBytes(data, 0, expected.length, data, offset); + bc.doFinal(data, offset + len); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping encryption"); + } + + bc.init(false, key); + bc.processBytes(data, 0, expected.length, expected, 0); + bc.init(false, key); + bc.processBytes(data, 0, expected.length, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping decryption"); + } + } + public String getName() { return "CTS"; } - public void performTest() + public void performTest() throws Exception { - byte[] key1 = { (byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67, (byte)0x89, (byte)0xAB, (byte)0xCD, (byte)0xEF }; - byte[] key2 = { (byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67, (byte)0x89, (byte)0xAB, (byte)0xCD, (byte)0xEF, (byte)0xee, (byte)0xff }; - byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; + byte[] key1 = {(byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67, (byte)0x89, (byte)0xAB, (byte)0xCD, (byte)0xEF}; + byte[] key2 = {(byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67, (byte)0x89, (byte)0xAB, (byte)0xCD, (byte)0xEF, (byte)0xee, (byte)0xff}; + byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8}; testCTS(1, new DESEngine(), new KeyParameter(key1), in1, out1); testCTS(2, new CBCBlockCipher(new DESEngine()), new ParametersWithIV(new KeyParameter(key1), iv), in1, out2); @@ -177,11 +262,11 @@ public void performTest() // test vectors from rfc3962 // byte[] aes128 = Hex.decode("636869636b656e207465726979616b69"); - byte[] aesIn1 = Hex.decode("4920776f756c64206c696b652074686520"); + byte[] aesIn1 = Hex.decode("4920776f756c64206c696b652074686520"); byte[] aesOut1 = Hex.decode("c6353568f2bf8cb4d8a580362da7ff7f97"); - byte[] aesIn2 = Hex.decode("4920776f756c64206c696b65207468652047656e6572616c20476175277320"); + byte[] aesIn2 = Hex.decode("4920776f756c64206c696b65207468652047656e6572616c20476175277320"); byte[] aesOut2 = Hex.decode("fc00783e0efdb2c1d445d4c8eff7ed2297687268d6ecccc0c07b25e25ecfe5"); - byte[] aesIn3 = Hex.decode("4920776f756c64206c696b65207468652047656e6572616c2047617527732043"); + byte[] aesIn3 = Hex.decode("4920776f756c64206c696b65207468652047656e6572616c2047617527732043"); byte[] aesOut3 = Hex.decode("39312523a78662d5be7fcbcc98ebf5a897687268d6ecccc0c07b25e25ecfe584"); testCTS(4, new CBCBlockCipher(AESEngine.newInstance()), new ParametersWithIV(new KeyParameter(aes128), new byte[16]), aesIn1, aesOut1); @@ -202,16 +287,18 @@ public void performTest() testOldCTS(9, new CBCBlockCipher(AESEngine.newInstance()), new ParametersWithIV(new KeyParameter(aes128), new byte[16]), aes1Block, preErrata); byte[] aes128b = Hex.decode("aafd12f659cae63489b479e5076ddec2f06cb58faafd12f6"); - byte[] aesIn1b = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); + byte[] aesIn1b = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); byte[] aesOut1b = Hex.decode("6db2f802d99e1ef0a5940f306079e083cf87f4d8bb9d1abb36cdd9f44ead7d04"); testCTS(10, new CBCBlockCipher(AESEngine.newInstance()), new ParametersWithIV(new KeyParameter(aes128b), Hex.decode("aafd12f659cae63489b479e5076ddec2")), aesIn1b, aesOut1b); testExceptions(); + testOverlapping(); + testOverlapping2(); } public static void main( - String[] args) + String[] args) { runTest(new CTSTest()); } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/ChaCha20Poly1305Test.java b/core/src/test/java/org/bouncycastle/crypto/test/ChaCha20Poly1305Test.java index 042049f03b..b8dc6a5c29 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/ChaCha20Poly1305Test.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/ChaCha20Poly1305Test.java @@ -3,10 +3,13 @@ import java.security.SecureRandom; import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.macs.SipHash; +import org.bouncycastle.crypto.modes.CTSBlockCipher; import org.bouncycastle.crypto.modes.ChaCha20Poly1305; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; import org.bouncycastle.util.Times; import org.bouncycastle.util.encoders.Hex; @@ -48,6 +51,7 @@ public String getName() public void performTest() throws Exception { + testOverlapping(); for (int i = 0; i < TEST_VECTORS.length; ++i) { runTestCase(TEST_VECTORS[i]); @@ -439,6 +443,55 @@ private void testExceptions() throws InvalidCipherTextException } } + private void testOverlapping() + throws Exception + { + SecureRandom random = new SecureRandom(); + int kLength = 32; + byte[] K = new byte[kLength]; + random.nextBytes(K); + + int aLength = random.nextInt() >>> 24; + byte[] A = new byte[aLength]; + random.nextBytes(A); + + int nonceLength = 12; + byte[] nonce = new byte[nonceLength]; + random.nextBytes(nonce); + + AEADParameters parameters = new AEADParameters(new KeyParameter(K), 16 * 8, nonce, A); + + ChaCha20Poly1305 bc = initCipher(true, parameters); + + final int blockSize = 64; + int offset = 1 + random.nextInt(blockSize - 1) + blockSize; + byte[] data = new byte[blockSize * 4 + offset]; + byte[] expected = new byte[bc.getOutputSize(blockSize * 3)]; + random.nextBytes(data); + + + int len = bc.processBytes(data, 0, blockSize * 3, expected, 0); + bc.doFinal(expected, len); + bc = initCipher(true, parameters); + len = bc.processBytes(data, 0, blockSize * 3, data, offset); + bc.doFinal(data, offset + len); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping encryption"); + } + + bc = initCipher(false, parameters); + bc.processBytes(data, 0, expected.length, expected, 0); + bc = initCipher(false, parameters); + bc.processBytes(data, 0, expected.length, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping decryption"); + } + } + public static void main(String[] args) { runTest(new ChaCha20Poly1305Test()); diff --git a/core/src/test/java/org/bouncycastle/crypto/test/CipherTest.java b/core/src/test/java/org/bouncycastle/crypto/test/CipherTest.java index 407a044035..19ac878202 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/CipherTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/CipherTest.java @@ -1,14 +1,36 @@ package org.bouncycastle.crypto.test; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Random; + import org.bouncycastle.crypto.BlockCipher; +import org.bouncycastle.crypto.BufferedBlockCipher; +import org.bouncycastle.crypto.CipherKeyGenerator; +import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.DefaultBufferedBlockCipher; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; +import org.bouncycastle.util.test.SimpleTestResult; +import org.bouncycastle.util.test.TestFailedException; public abstract class CipherTest extends SimpleTest { - private SimpleTest[] _tests; + private SimpleTest[] _tests; private BlockCipher _engine; private KeyParameter _validKey; @@ -19,15 +41,15 @@ public abstract class CipherTest // } protected CipherTest( - SimpleTest[] tests, - BlockCipher engine, + SimpleTest[] tests, + BlockCipher engine, KeyParameter validKey) { _tests = tests; _engine = engine; _validKey = validKey; } - + public abstract String getName(); public void performTest() @@ -43,70 +65,70 @@ public void performTest() // // state tests // - byte[] buf = new byte[128]; - + byte[] buf = new byte[128]; + try - { + { _engine.processBlock(buf, 0, buf, 0); - + fail("failed initialisation check"); } catch (IllegalStateException e) { // expected } - + bufferSizeCheck((_engine)); } } - + private void bufferSizeCheck( BlockCipher engine) { byte[] correctBuf = new byte[engine.getBlockSize()]; byte[] shortBuf = new byte[correctBuf.length / 2]; - + engine.init(true, _validKey); - + try - { + { engine.processBlock(shortBuf, 0, correctBuf, 0); - + fail("failed short input check"); } catch (DataLengthException e) { // expected } - + try - { + { engine.processBlock(correctBuf, 0, shortBuf, 0); - + fail("failed short output check"); } catch (DataLengthException e) { // expected } - + engine.init(false, _validKey); - + try - { + { engine.processBlock(shortBuf, 0, correctBuf, 0); - + fail("failed short input check"); } catch (DataLengthException e) { // expected } - + try - { + { engine.processBlock(correctBuf, 0, shortBuf, 0); - + fail("failed short output check"); } catch (DataLengthException e) @@ -114,4 +136,811 @@ private void bufferSizeCheck( // expected } } + + interface Instance + { + AEADCipher createInstance(); + } + + static void checkCipher(int aeadLen, int ivLen, int msgLen, int strength, Instance instance) + { + AEADCipher pCipher = instance.createInstance(); + + try + { + /* Obtain some random data */ + final byte[] myData = new byte[msgLen]; + final SecureRandom myRandom = new SecureRandom(); + myRandom.nextBytes(myData); + + /* Obtain some random AEAD */ + final byte[] myAEAD = new byte[aeadLen]; + myRandom.nextBytes(myAEAD); + + /* Create the Key parameters */ + final CipherKeyGenerator myGenerator = new CipherKeyGenerator(); + final KeyGenerationParameters myGenParams = new KeyGenerationParameters(myRandom, strength); + myGenerator.init(myGenParams); + final byte[] myKey = myGenerator.generateKey(); + final KeyParameter myKeyParams = new KeyParameter(myKey); + + /* Create the nonce */ + final byte[] myNonce = new byte[ivLen]; + myRandom.nextBytes(myNonce); + final ParametersWithIV myParams = new ParametersWithIV(myKeyParams, myNonce); + + /* Initialise the cipher for encryption */ + pCipher.init(true, myParams); + final int myMaxOutLen = pCipher.getOutputSize(msgLen); + final byte[] myEncrypted = new byte[myMaxOutLen]; + pCipher.processAADBytes(myAEAD, 0, aeadLen); + int myOutLen = pCipher.processBytes(myData, 0, msgLen, myEncrypted, 0); + myOutLen += pCipher.doFinal(myEncrypted, myOutLen); + + /* Note that myOutLen is too large by DATALEN */ + pCipher = instance.createInstance(); + /* Initialise the cipher for decryption */ + pCipher.init(false, myParams); + final int myMaxClearLen = pCipher.getOutputSize(myOutLen); + final byte[] myDecrypted = new byte[myMaxClearLen]; + pCipher.processAADBytes(myAEAD, 0, aeadLen); + int myClearLen = pCipher.processBytes(myEncrypted, 0, myEncrypted.length, myDecrypted, 0); + myClearLen += pCipher.doFinal(myDecrypted, myClearLen); + final byte[] myResult = Arrays.copyOf(myDecrypted, msgLen); + + /* Check that we have the same result */ + if (!Arrays.areEqual(myData, myResult)) + { + System.out.println("Cipher " + pCipher.getAlgorithmName() + " failed"); + } + } + catch (InvalidCipherTextException e) + { + throw new RuntimeException(e); + } + } + + static void checkAEADCipherOutputSize(SimpleTest parent, int keySize, int ivSize, int blockSize, int tagSize, AEADCipher cipher) + throws InvalidCipherTextException + { + final SecureRandom random = new SecureRandom(); + int tmpLength = random.nextInt(blockSize - 1) + 1; + final byte[] plaintext = new byte[blockSize * 2 + tmpLength]; + byte[] key = new byte[keySize]; + byte[] iv = new byte[ivSize]; + random.nextBytes(key); + random.nextBytes(iv); + random.nextBytes(plaintext); + cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); + byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)]; + //before the encrypt + isEqualTo(parent, plaintext.length + tagSize, ciphertext.length); + isEqualTo(parent, plaintext.length, cipher.getUpdateOutputSize(plaintext.length) + tmpLength); + //during the encrypt process of the first block + int len = cipher.processBytes(plaintext, 0, tmpLength, ciphertext, 0); + isEqualTo(parent, plaintext.length + tagSize, len + cipher.getOutputSize(plaintext.length - tmpLength)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(plaintext.length - tmpLength) + tmpLength); + //during the encrypt process of the second block + len += cipher.processBytes(plaintext, tmpLength, blockSize, ciphertext, len); + isEqualTo(parent, plaintext.length + tagSize, len + cipher.getOutputSize(plaintext.length - tmpLength - blockSize)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(plaintext.length - tmpLength - blockSize) + tmpLength); + //process the remaining bytes + len += cipher.processBytes(plaintext, tmpLength + blockSize, blockSize, ciphertext, len); + isEqualTo(parent, plaintext.length + tagSize, len + cipher.getOutputSize(0)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(0) + tmpLength); + //process doFinal + len += cipher.doFinal(ciphertext, len); + isEqualTo(parent, len, ciphertext.length); + + cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv)); + //before the encrypt + isEqualTo(parent, plaintext.length, cipher.getOutputSize(ciphertext.length)); + isEqualTo(parent, plaintext.length, cipher.getUpdateOutputSize(ciphertext.length) + tmpLength); + //during the encrypt process of the first block + len = cipher.processBytes(ciphertext, 0, tmpLength, plaintext, 0); + isEqualTo(parent, plaintext.length, len + cipher.getOutputSize(ciphertext.length - tmpLength)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(ciphertext.length - tmpLength) + tmpLength); + //during the encrypt process of the second block + len += cipher.processBytes(ciphertext, tmpLength, blockSize, plaintext, len); + isEqualTo(parent, plaintext.length, len + cipher.getOutputSize(ciphertext.length - tmpLength - blockSize)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(ciphertext.length - tmpLength - blockSize) + tmpLength); + //process the remaining bytes + len += cipher.processBytes(ciphertext, tmpLength + blockSize, blockSize + tagSize, plaintext, len); + isEqualTo(parent, plaintext.length, len + cipher.getOutputSize(0)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(0) + tmpLength); + //process doFinal + len += cipher.doFinal(plaintext, len); + isEqualTo(parent, len, plaintext.length); + } + + static void isEqualTo( + SimpleTest parent, + int a, + int b) + { + if (a != b) + { + throw new TestFailedException(SimpleTestResult.failed(parent, "no message")); + } + } + + void checkCipher(final BlockCipher pCipher, final int datalen) + throws Exception + { + final SecureRandom random = new SecureRandom(); + /* Create the data */ + final byte[] myData = new byte[datalen]; + random.nextBytes(myData); + + /* Create the Key parameters */ + final CipherKeyGenerator myGenerator = new CipherKeyGenerator(); + final KeyGenerationParameters myGenParams = new KeyGenerationParameters(random, 256); + myGenerator.init(myGenParams); + final byte[] myKey = myGenerator.generateKey(); + final KeyParameter myKeyParams = new KeyParameter(myKey); + + /* Create the IV */ + final byte[] myIV = new byte[16]; + random.nextBytes(myIV); + + /* Create the initParams */ + final ParametersWithIV myParams = new ParametersWithIV(myKeyParams, myIV); + + /* Wrap Block Cipher with buffered BlockCipher */ + final BufferedBlockCipher myCipher = new DefaultBufferedBlockCipher(pCipher); + + /* Initialise the cipher for encryption */ + myCipher.init(true, myParams); + + /* Encipher the text */ + final byte[] myOutput = new byte[myCipher.getOutputSize(datalen)]; + int myOutLen = myCipher.processBytes(myData, 0, datalen, myOutput, 0); + myCipher.doFinal(myOutput, myOutLen); + + /* Re-Encipher the text (after implicit reset) */ + final byte[] myOutput2 = new byte[myCipher.getOutputSize(datalen)]; + myOutLen = myCipher.processBytes(myData, 0, datalen, myOutput2, 0); + myCipher.doFinal(myOutput2, myOutLen); + + myCipher.init(false, myParams); + final byte[] plaintext = new byte[myCipher.getOutputSize(myOutput.length)]; + myOutLen = myCipher.processBytes(myOutput2, 0, datalen, plaintext, 0); + myCipher.doFinal(plaintext, myOutLen); + + /* Check that the cipherTexts are identical */ + isTrue(areEqual(myOutput, myOutput2)); + isTrue(areEqual(myData, plaintext)); + } + + static void checkAEADParemeter(SimpleTest test, int keySize, int ivSize, final int macSize, int blockSize, final AEADCipher cipher) + throws Exception + { + final SecureRandom random = new SecureRandom(); + final byte[] key = new byte[keySize]; + final byte[] iv = new byte[ivSize]; + int tmpLength = random.nextInt(blockSize - 1) + 1; + final byte[] plaintext = new byte[blockSize * 2 + tmpLength]; + byte[] aad = new byte[random.nextInt(100) + 2]; + random.nextBytes(key); + random.nextBytes(iv); + random.nextBytes(plaintext); + random.nextBytes(aad); + cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); + byte[] ciphertext1 = new byte[cipher.getOutputSize(plaintext.length)]; + for (int i = 0; i < aad.length; ++i) + { + cipher.processAADByte(aad[i]); + } + int len = 0; + for (int i = 0; i < plaintext.length; ++i) + { + len += cipher.processByte(plaintext[i], ciphertext1, len); + } + len += cipher.doFinal(ciphertext1, len); + int aadSplit = random.nextInt(aad.length) + 1; + cipher.init(true, new AEADParameters(new KeyParameter(key), macSize * 8, iv, Arrays.copyOf(aad, aadSplit))); + cipher.processAADBytes(aad, aadSplit, aad.length - aadSplit); + byte[] ciphertext2 = new byte[cipher.getOutputSize(plaintext.length)]; + len = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext2, 0); + len += cipher.doFinal(ciphertext2, len); + cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); + byte[] ciphertext3 = new byte[cipher.getOutputSize(plaintext.length)]; + cipher.processAADBytes(aad, 0, aad.length); + len = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext3, 0); + len += cipher.doFinal(ciphertext3, len); + test.isTrue("cipher text check", Arrays.areEqual(ciphertext1, ciphertext2)); + cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv)); + for (int i = 0; i < aad.length; ++i) + { + cipher.processAADByte(aad[i]); + } + len = 0; + byte[] plaintext1 = new byte[plaintext.length]; + for (int i = 0; i < ciphertext1.length; ++i) + { + len += cipher.processByte(ciphertext1[i], plaintext1, len); + } + len += cipher.doFinal(plaintext1, len); + + test.testException("Invalid value for MAC size: ", "IllegalArgumentException", new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + int macSize2 = random.nextInt(); + while (macSize2 == macSize * 8) + { + macSize2 = random.nextInt(); + } + cipher.init(true, new AEADParameters(new KeyParameter(key), macSize2, iv, null)); + } + }); + } + + + /** + * @param DATALEN Data length + * @param PARTLEN Partial Data length. Must be greater than or equal to internal buffer length to exhibit problem. + * @param AEADLEN AEAD length. + * @param NONCELEN Nonce length. + */ + static void checkAEADCipherMultipleBlocks(SimpleTest test, int DATALEN, int PARTLEN, int AEADLEN, int strength, int NONCELEN, final AEADCipher pCipher) + throws InvalidCipherTextException + { + /* Obtain some random data */ + final byte[] myData = new byte[DATALEN]; + final SecureRandom myRandom = new SecureRandom(); + myRandom.nextBytes(myData); + + /* Obtain some random AEAD */ + final byte[] myAEAD = new byte[AEADLEN]; + myRandom.nextBytes(myAEAD); + + /* Create the Key parameters */ + final CipherKeyGenerator myGenerator = new CipherKeyGenerator(); + final KeyGenerationParameters myGenParams = new KeyGenerationParameters(myRandom, strength); + myGenerator.init(myGenParams); + final byte[] myKey = myGenerator.generateKey(); + final KeyParameter myKeyParams = new KeyParameter(myKey); + + /* Create the nonce */ + final byte[] myNonce = new byte[NONCELEN]; + myRandom.nextBytes(myNonce); + final ParametersWithIV myParams = new ParametersWithIV(myKeyParams, myNonce); + + /* Initialise the cipher for encryption */ + pCipher.init(true, myParams); + final int myExpectedOutLen = pCipher.getOutputSize(DATALEN); + final byte[] myEncrypted = new byte[myExpectedOutLen]; + pCipher.processAADBytes(myAEAD, 0, AEADLEN); + + /* Loop processing partial data */ + int myOutLen = 0; + for (int myPos = 0; myPos < DATALEN; myPos += PARTLEN) + { + final int myLen = Math.min(PARTLEN, DATALEN - myPos); + myOutLen += pCipher.processBytes(myData, myPos, myLen, myEncrypted, myOutLen); + } + + /* Finish the encryption */ + myOutLen += pCipher.doFinal(myEncrypted, myOutLen); + + /* Initialise the cipher for decryption */ + pCipher.init(false, myParams); + final int myExpectedClearLen = pCipher.getOutputSize(myOutLen); + final byte[] myDecrypted = new byte[myExpectedClearLen]; + pCipher.processAADBytes(myAEAD, 0, AEADLEN); + int myClearLen = 0; + for (int myPos = 0; myPos < myOutLen; myPos += PARTLEN) + { + final int myLen = Math.min(PARTLEN, myOutLen - myPos); + myClearLen += pCipher.processBytes(myEncrypted, myPos, myLen, myDecrypted, myClearLen); + } + myClearLen += pCipher.doFinal(myDecrypted, myClearLen); + final byte[] myResult = Arrays.copyOf(myDecrypted, myClearLen); + + /* Check that we have the same result */ + test.isTrue("cipher text check", Arrays.areEqual(myData, myResult)); + } + + static void implTestVectorsEngine(AEADCipher cipher, String path, String filename, SimpleTest test) + throws Exception + { + Random random = new Random(); + InputStream src = TestResourceFinder.findTestResource(path, filename); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + String line; + HashMap map = new HashMap(); + while ((line = bin.readLine()) != null) + { + int a = line.indexOf('='); + if (a < 0) + { + int count = Integer.parseInt((String)map.get("Count")); +// if (count != 67) +// { +// continue; +// } + byte[] key = Hex.decode((String)map.get("Key")); + byte[] nonce = Hex.decode((String)map.get("Nonce")); + byte[] ad = Hex.decode((String)map.get("AD")); + byte[] pt = Hex.decode((String)map.get("PT")); + byte[] ct = Hex.decode((String)map.get("CT")); + + CipherParameters parameters = new ParametersWithIV(new KeyParameter(key), nonce); + + // Encrypt + { + cipher.init(true, parameters); + + byte[] rv = new byte[cipher.getOutputSize(pt.length)]; + random.nextBytes(rv); // should overwrite any existing data + + cipher.processAADBytes(ad, 0, ad.length); + int len = cipher.processBytes(pt, 0, pt.length, rv, 0); + len += cipher.doFinal(rv, len); + + if (!test.areEqual(rv, 0, len, ct, 0, ct.length)) + { + mismatch("Keystream " + map.get("Count"), (String)map.get("CT"), rv, test); + } + } + + // Decrypt + { + cipher.init(false, parameters); + + byte[] rv = new byte[cipher.getOutputSize(ct.length)]; + random.nextBytes(rv); // should overwrite any existing data + + cipher.processAADBytes(ad, 0, ad.length); + int len = cipher.processBytes(ct, 0, ct.length, rv, 0); + len += cipher.doFinal(rv, len); + + if (!test.areEqual(rv, 0, len, pt, 0, pt.length)) + { + mismatch("Reccover Keystream " + map.get("Count"), (String)map.get("PT"), rv, test); + } + } + //System.out.println("pass " + count); + map.clear(); + } + else + { + map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + static void mismatch(String name, String expected, byte[] found, SimpleTest test) + throws Exception + { + test.fail("mismatch on " + name, expected, new String(Hex.encode(found))); + } + + static void implTestBufferingEngine(int keySize, int ivSize, final int macSize, SimpleTest test, Instance instance) + throws Exception + { + Random random = new Random(); + + int plaintextLength = 256; + byte[] plaintext = new byte[plaintextLength]; + random.nextBytes(plaintext); + + AEADCipher cipher0 = instance.createInstance(); + AEADParameters parameters = new AEADParameters(new KeyParameter(new byte[keySize]), macSize, new byte[ivSize], null); + cipher0.init(true, parameters); + + byte[] ciphertext = new byte[cipher0.getOutputSize(plaintextLength)]; + random.nextBytes(ciphertext); + + int ciphertextLength = cipher0.processBytes(plaintext, 0, plaintextLength, ciphertext, 0); + ciphertextLength += cipher0.doFinal(ciphertext, ciphertextLength); + + byte[] output = new byte[ciphertextLength]; + + // Encryption + for (int split = 1; split < plaintextLength; ++split) + { + AEADCipher cipher = instance.createInstance(); + cipher.init(true, parameters); + + random.nextBytes(output); + + int length = cipher.processBytes(plaintext, 0, split, output, 0); + + if (0 != cipher.getUpdateOutputSize(0)) + { + test.fail("fail in implTestBufferingEngine encryption"); + } + + length += cipher.processBytes(plaintext, split, plaintextLength - split, output, length); + length += cipher.doFinal(output, length); + + if (!Arrays.areEqual(ciphertext, 0, ciphertextLength, output, 0, length)) + { + test.fail("encryption failed with split: " + split); + } + } + + // Decryption + for (int split = 16; split < ciphertextLength; ++split) + { + AEADCipher cipher = instance.createInstance(); + cipher.init(false, parameters); + + random.nextBytes(output); + + int length = cipher.processBytes(ciphertext, 0, split, output, 0); + + if (0 != cipher.getUpdateOutputSize(0)) + { + test.fail("fail in implTestBufferingEngine decryption"); + } + + length += cipher.processBytes(ciphertext, split, ciphertextLength - split, output, length); + length += cipher.doFinal(output, length); + + if (!Arrays.areEqual(plaintext, 0, plaintextLength, output, 0, length)) + { + test.fail("decryption failed with split: " + split); + } + } + } + + static void implTestExceptionsEngine(int keysize, int ivsize, SimpleTest test, Instance instance) + throws Exception + { + AEADCipher cipher = instance.createInstance(); + + int offset; + byte[] k = new byte[keysize]; + byte[] iv = new byte[ivsize]; + byte[] m = new byte[0]; + CipherParameters params = new ParametersWithIV(new KeyParameter(k), iv); + try + { + cipher.processBytes(m, 0, m.length, null, 0); + test.fail(cipher.getAlgorithmName() + " need to be initialized before processBytes"); + } + catch (IllegalStateException e) + { + //expected + } + + try + { + cipher.processByte((byte)0, null, 0); + test.fail(cipher.getAlgorithmName() + " need to be initialized before processByte"); + } + catch (IllegalStateException e) + { + //expected + } + + try + { + cipher.reset(); + test.fail(cipher.getAlgorithmName() + " need to be initialized before reset"); + } + catch (IllegalStateException e) + { + //expected + } + + try + { + cipher.doFinal(null, m.length); + test.fail(cipher.getAlgorithmName() + " need to be initialized before dofinal"); + } + catch (IllegalStateException e) + { + //expected + } + + try + { + cipher.getMac(); + cipher.getOutputSize(0); + cipher.getUpdateOutputSize(0); + } + catch (IllegalStateException e) + { + //expected + test.fail(cipher.getAlgorithmName() + " functions can be called before initialization"); + } + + Random rand = new Random(); + int randomNum; + while ((randomNum = rand.nextInt(100)) == keysize) ; + byte[] k1 = new byte[randomNum]; + while ((randomNum = rand.nextInt(100)) == ivsize) ; + byte[] iv1 = new byte[randomNum]; + try + { + cipher.init(true, new ParametersWithIV(new KeyParameter(k1), iv)); + test.fail(cipher.getAlgorithmName() + " k size does not match"); + } + catch (IllegalArgumentException e) + { + //expected + } + try + { + cipher.init(true, new ParametersWithIV(new KeyParameter(k), iv1)); + test.fail(cipher.getAlgorithmName() + "iv size does not match"); + } + catch (IllegalArgumentException e) + { + //expected + } + + try + { + cipher.init(true, new AEADParameters(new KeyParameter(k), 0, iv)); + test.fail(cipher.getAlgorithmName() + " wrong type of CipherParameters"); + } + catch (IllegalArgumentException e) + { + //expected + } + + cipher.init(true, params); + byte[] c1 = new byte[cipher.getOutputSize(m.length)]; + try + { + cipher.doFinal(c1, m.length); + } + catch (Exception e) + { + test.fail(cipher.getAlgorithmName() + " allows no input for AAD and plaintext"); + } + byte[] mac2 = cipher.getMac(); + if (mac2 == null) + { + test.fail("mac should not be empty after dofinal"); + } + if (!Arrays.areEqual(mac2, c1)) + { + test.fail("mac should be equal when calling dofinal and getMac"); + } + cipher.init(true, params); + cipher.processAADByte((byte)0); + byte[] mac1 = new byte[cipher.getOutputSize(0)]; + cipher.doFinal(mac1, 0); + if (Arrays.areEqual(mac1, mac2)) + { + test.fail("mac should not match"); + } + cipher.init(true, params); + cipher.processByte((byte)0, new byte[1], 0); + try + { + cipher.processAADByte((byte)0); + // Romuls-M stores message into Stream, so the procssAADbyte(s) is allowed + if (!cipher.getAlgorithmName().equals("Romulus-M")) + { + test.fail("processAADByte(s) cannot be called after encryption/decryption"); + } + } + catch (IllegalStateException e) + { + //expected + } + try + { + cipher.processAADBytes(new byte[]{0}, 0, 1); + if (!cipher.getAlgorithmName().equals("Romulus-M")) + { + test.fail("processAADByte(s) cannot be called once only"); + } + } + catch (IllegalStateException e) + { + //expected + } + + cipher.reset(); + try + { + cipher.processAADBytes(new byte[]{0}, 1, 1); + test.fail("input for processAADBytes is too short"); + } + catch (DataLengthException e) + { + //expected + } + try + { + cipher.processBytes(new byte[]{0}, 1, 1, c1, 0); + test.fail("input for processBytes is too short"); + } + catch (DataLengthException e) + { + //expected + } + cipher.init(true, params); + try + { + int need = cipher.getUpdateOutputSize(64); + cipher.processBytes(new byte[64], 0, 64, new byte[need], 1); + if (!cipher.getAlgorithmName().equals("Romulus-M")) + { + test.fail("output for processBytes is too short"); + } + } + catch (OutputLengthException e) + { + //expected + } + try + { + cipher.doFinal(new byte[2], 2); + test.fail("output for dofinal is too short"); + } + catch (OutputLengthException e) + { + //expected + } + + implTestExceptionsGetUpdateOutputSize(cipher, false, params, 100, test); + implTestExceptionsGetUpdateOutputSize(cipher, true, params, 100, test); + + mac1 = new byte[cipher.getOutputSize(0)]; + mac2 = new byte[cipher.getOutputSize(0)]; + cipher.init(true, params); + cipher.processAADBytes(new byte[]{0, 0}, 0, 2); + cipher.doFinal(mac1, 0); + cipher.init(true, params); + cipher.processAADByte((byte)0); + cipher.processAADByte((byte)0); + cipher.doFinal(mac2, 0); + if (!Arrays.areEqual(mac1, mac2)) + { + test.fail("mac should match for the same AAD with different ways of inputing"); + } + + byte[] c2 = new byte[cipher.getOutputSize(10)]; + byte[] c3 = new byte[cipher.getOutputSize(10) + 2]; + + byte[] aad2 = {0, 1, 2, 3, 4}; + byte[] aad3 = {0, 0, 1, 2, 3, 4, 5}; + byte[] m2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + byte[] m3 = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + byte[] m4 = new byte[m2.length]; + cipher.init(true, params); + cipher.processAADBytes(aad2, 0, aad2.length); + offset = cipher.processBytes(m2, 0, m2.length, c2, 0); + cipher.doFinal(c2, offset); + cipher.init(true, params); + cipher.processAADBytes(aad3, 1, aad2.length); + offset = cipher.processBytes(m3, 1, m2.length, c3, 1); + cipher.doFinal(c3, offset + 1); + byte[] c3_partial = new byte[c2.length]; + System.arraycopy(c3, 1, c3_partial, 0, c2.length); + if (!Arrays.areEqual(c2, c3_partial)) + { + test.fail("mac should match for the same AAD and message with different offset for both input and output"); + } + cipher.init(false, params); + cipher.processAADBytes(aad2, 0, aad2.length); + offset = cipher.processBytes(c2, 0, c2.length, m4, 0); + cipher.doFinal(m4, offset); + if (!Arrays.areEqual(m2, m4)) + { + test.fail("The encryption and decryption does not recover the plaintext"); + } + c2[c2.length - 1] ^= 1; + cipher.init(false, params); + cipher.processAADBytes(aad2, 0, aad2.length); + offset = cipher.processBytes(c2, 0, c2.length, m4, 0); + try + { + cipher.doFinal(m4, offset); + test.fail("The decryption should fail"); + } + catch (InvalidCipherTextException e) + { + //expected; + } + + byte[] m7 = new byte[32 + rand.nextInt(32)]; + rand.nextBytes(m7); + + cipher.init(true, params); + byte[] c7 = new byte[cipher.getOutputSize(m7.length)]; + byte[] c8 = new byte[c7.length]; + byte[] c9 = new byte[c7.length]; + cipher.processAADBytes(aad2, 0, aad2.length); + offset = cipher.processBytes(m7, 0, m7.length, c7, 0); + cipher.doFinal(c7, offset); + + cipher.init(true, params); + cipher.processAADBytes(aad2, 0, aad2.length); + offset = cipher.processBytes(m7, 0, m7.length / 2, c8, 0); + offset += cipher.processBytes(m7, m7.length / 2, m7.length - m7.length / 2, c8, offset); + cipher.doFinal(c8, offset); + + cipher.init(true, params); + int split = rand.nextInt(m7.length - 1) + 1; + cipher.processAADBytes(aad2, 0, aad2.length); + offset = cipher.processBytes(m7, 0, split, c9, 0); + offset += cipher.processBytes(m7, split, m7.length - split, c9, offset); + cipher.doFinal(c9, offset); + + if (!Arrays.areEqual(c7, c8) || !Arrays.areEqual(c7, c9)) + { + test.fail("Splitting input of plaintext should output the same ciphertext"); + } + } + + static void implTestExceptionsGetUpdateOutputSize(AEADCipher cipher, boolean forEncryption, + CipherParameters parameters, int maxInputSize, SimpleTest test) + { + cipher.init(forEncryption, parameters); + + int maxOutputSize = cipher.getUpdateOutputSize(maxInputSize); + + byte[] input = new byte[maxInputSize]; + byte[] output = new byte[maxOutputSize]; + + for (int inputSize = 0; inputSize <= maxInputSize; ++inputSize) + { + cipher.init(forEncryption, parameters); + + int outputSize = cipher.getUpdateOutputSize(inputSize); + if (outputSize > 0) + { + try + { + cipher.processBytes(input, 0, inputSize, output, maxOutputSize - outputSize + 1); + test.fail("output for processBytes is too short"); + } + catch (OutputLengthException e) + { + //expected + } + } + else + { + cipher.processBytes(input, 0, inputSize, null, 0); + } + } + } + + static void testOverlapping(SimpleTest test, int keySize, int ivSize, int macSize, int blockSize, AEADCipher cipher) + throws Exception + { + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[keySize]; + byte[] ivBytes = new byte[ivSize]; + int offset = 1 + random.nextInt(blockSize - 1); + byte[] data = new byte[blockSize * 2 + offset + macSize]; + byte[] expected; + random.nextBytes(keyBytes); + random.nextBytes(ivBytes); + random.nextBytes(data); + AEADParameters parameters = new AEADParameters(new KeyParameter(new byte[keySize]), macSize * 8, new byte[ivSize], null); + cipher.init(true, parameters); + expected = new byte[cipher.getOutputSize(blockSize * 2)]; + int len = cipher.processBytes(data, 0, blockSize * 2, expected, 0); + cipher.doFinal(expected, len); + cipher.init(true, parameters); + len = cipher.processBytes(data, 0, blockSize * 2, data, offset); + cipher.doFinal(data, len + offset); + test.isTrue("fail on testing overlapping of encryption for " + cipher.getAlgorithmName(), + Arrays.areEqual(expected, 0, expected.length, data, offset, offset + expected.length)); + System.arraycopy(data, offset, data, 0, expected.length); + cipher.init(false, parameters); + expected = new byte[cipher.getOutputSize(data.length)]; + len = cipher.processBytes(data, 0, blockSize * 2 + macSize, expected, 0); + cipher.doFinal(expected, len); + cipher.init(false, parameters); + len = cipher.processBytes(data, 0, blockSize * 2 + macSize, data, offset); + cipher.doFinal(data, len + offset); + test.isTrue("fail on testing overlapping of decryption for " + cipher.getAlgorithmName(), + Arrays.areEqual(expected, 0, blockSize * 2, data, offset, offset + blockSize * 2)); + + } } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/DSTU7624Test.java b/core/src/test/java/org/bouncycastle/crypto/test/DSTU7624Test.java index 2af7f7978c..084f400862 100755 --- a/core/src/test/java/org/bouncycastle/crypto/test/DSTU7624Test.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/DSTU7624Test.java @@ -96,6 +96,7 @@ public void performTest() CCMModeTests(); XTSModeTests(); GCMModeTests(); + testOverlapping(); } public static void main( @@ -1464,4 +1465,41 @@ private void doFinalTest(AEADBlockCipher cipher, byte[] key, byte[] iv, byte[] a fail("Failed doFinal test - after: " + cipher.getAlgorithmName()); } } + + private void testOverlapping() + { + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[16]; + byte[] iv = new byte[16]; + random.nextBytes(keyBytes); + KXTSBlockCipher bc = new KXTSBlockCipher(new DSTU7624Engine(128)); + ParametersWithIV param = new ParametersWithIV(new KeyParameter(keyBytes), iv); + + int offset = 1 + random.nextInt(bc.getBlockSize() - 1) + bc.getBlockSize(); + byte[] data = new byte[bc.getBlockSize() * 4 + offset]; + byte[] expected = new byte[bc.getOutputSize(bc.getBlockSize() * 3)]; + random.nextBytes(data); + + bc.init(true, param); + int len = bc.processBytes(data, 0, expected.length, expected, 0); + bc.doFinal(expected, len); + bc.init(true, param); + len = bc.processBytes(data, 0, expected.length, data, offset); + bc.doFinal(data, offset + len); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping encryption"); + } + + bc.init(false, param); + bc.processBytes(data, 0, expected.length, expected, 0); + bc.init(false, param); + bc.processBytes(data, 0, expected.length, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping decryption"); + } + } } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/DigestTest.java b/core/src/test/java/org/bouncycastle/crypto/test/DigestTest.java index f2843515e8..a5d2cd82c7 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/DigestTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/DigestTest.java @@ -1,11 +1,25 @@ package org.bouncycastle.crypto.test; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Random; + +import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.ExtendedDigest; +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.Xof; import org.bouncycastle.crypto.digests.EncodableDigest; +import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Memoable; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; +import org.bouncycastle.util.test.SimpleTestResult; +import org.bouncycastle.util.test.TestFailedException; public abstract class DigestTest extends SimpleTest @@ -23,16 +37,16 @@ public abstract class DigestTest this.input = input; this.results = results; } - + public String getName() { return digest.getAlgorithmName(); } - + public void performTest() { byte[] resBuf = new byte[digest.getDigestSize()]; - + for (int i = 0; i < input.length - 1; i++) { byte[] m = toByteArray(input[i]); @@ -44,7 +58,7 @@ public void performTest() byte[] lastV = toByteArray(input[input.length - 1]); byte[] lastDigest = Hex.decode(results[input.length - 1]); - + vectorTest(digest, input.length - 1, resBuf, lastV, Hex.decode(results[input.length - 1])); testClone(resBuf, lastV, lastDigest); @@ -94,13 +108,13 @@ private void testMemo(byte[] resBuf, byte[] input, byte[] expected) { Memoable m = (Memoable)digest; - digest.update(input, 0, input.length/2); + digest.update(input, 0, input.length / 2); // copy the Digest Memoable copy1 = m.copy(); Memoable copy2 = copy1.copy(); - digest.update(input, input.length/2, input.length - input.length/2); + digest.update(input, input.length / 2, input.length - input.length / 2); digest.doFinal(resBuf, 0); if (!areEqual(expected, resBuf)) @@ -110,7 +124,7 @@ private void testMemo(byte[] resBuf, byte[] input, byte[] expected) m.reset(copy1); - digest.update(input, input.length/2, input.length - input.length/2); + digest.update(input, input.length / 2, input.length - input.length / 2); digest.doFinal(resBuf, 0); if (!areEqual(expected, resBuf)) @@ -120,7 +134,7 @@ private void testMemo(byte[] resBuf, byte[] input, byte[] expected) Digest md = (Digest)copy2; - md.update(input, input.length/2, input.length - input.length/2); + md.update(input, input.length / 2, input.length - input.length / 2); md.doFinal(resBuf, 0); if (!areEqual(expected, resBuf)) @@ -136,7 +150,7 @@ private void testClone(byte[] resBuf, byte[] input, byte[] expected) // clone the Digest Digest d = cloneDigest(digest); - digest.update(input, input.length/2, input.length - input.length/2); + digest.update(input, input.length / 2, input.length - input.length / 2); digest.doFinal(resBuf, 0); if (!areEqual(expected, resBuf)) @@ -144,7 +158,7 @@ private void testClone(byte[] resBuf, byte[] input, byte[] expected) fail("failing clone vector test", results[results.length - 1], new String(Hex.encode(resBuf))); } - d.update(input, input.length/2, input.length - input.length/2); + d.update(input, input.length / 2, input.length - input.length / 2); d.doFinal(resBuf, 0); if (!areEqual(expected, resBuf)) @@ -156,15 +170,15 @@ private void testClone(byte[] resBuf, byte[] input, byte[] expected) protected byte[] toByteArray(String input) { byte[] bytes = new byte[input.length()]; - + for (int i = 0; i != bytes.length; i++) { bytes[i] = (byte)input.charAt(i); } - + return bytes; } - + private void vectorTest( Digest digest, int count, @@ -212,12 +226,12 @@ protected void millionATest( String expected) { byte[] resBuf = new byte[digest.getDigestSize()]; - + for (int i = 0; i < 1000000; i++) { digest.update((byte)'a'); } - + digest.doFinal(resBuf, 0); if (!areEqual(resBuf, Hex.decode(expected))) @@ -225,17 +239,17 @@ protected void millionATest( fail("Million a's failed", expected, new String(Hex.encode(resBuf))); } } - + protected void sixtyFourKTest( String expected) { byte[] resBuf = new byte[digest.getDigestSize()]; - + for (int i = 0; i < 65536; i++) { digest.update((byte)(i & 0xff)); } - + digest.doFinal(resBuf, 0); if (!areEqual(resBuf, Hex.decode(expected))) @@ -243,4 +257,154 @@ protected void sixtyFourKTest( fail("64k test failed", expected, new String(Hex.encode(resBuf))); } } + + static void checkDigestReset(final SimpleTest test, final Digest pDigest) + { + int DATALEN = 100; + /* Obtain some random data */ + final byte[] myData = new byte[DATALEN]; + final SecureRandom myRandom = new SecureRandom(); + myRandom.nextBytes(myData); + + /* Update and finalise digest */ + final int myHashLen = pDigest.getDigestSize(); + final byte[] myFirst = new byte[myHashLen]; + pDigest.update(myData, 0, DATALEN); + pDigest.doFinal(myFirst, 0); + + + /* Reuse the digest */ + final byte[] mySecond = new byte[myHashLen]; + pDigest.update(myData, 0, DATALEN); + pDigest.doFinal(mySecond, 0); + + /* Check that we have the same result */ + if (!java.util.Arrays.equals(myFirst, mySecond)) + { + throw new TestFailedException(SimpleTestResult.failed(test, "Digest " + pDigest.getAlgorithmName() + " does not reset properly on doFinal()")); + } + } + + static void implTestExceptionsAndParametersDigest(final SimpleTest test, final Digest pDigest, final int digestsize) + { + if (pDigest.getDigestSize() != digestsize) + { + test.fail(pDigest.getAlgorithmName() + ": digest size is not correct"); + } + + try + { + pDigest.update(new byte[1], 1, 1); + test.fail(pDigest.getAlgorithmName() + ": input for update is too short"); + } + catch (DataLengthException e) + { + //expected + } + + try + { + pDigest.doFinal(new byte[pDigest.getDigestSize() - 1], 2); + test.fail(pDigest.getAlgorithmName() + ": output for dofinal is too short"); + } + catch (OutputLengthException e) + { + //expected + } + } + + static void implTestVectorsDigest(SimpleTest test, ExtendedDigest digest, String path, String filename) + throws Exception + { + Random random = new Random(); + InputStream src = TestResourceFinder.findTestResource(path, filename); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + String line; + HashMap map = new HashMap(); + while ((line = bin.readLine()) != null) + { + int a = line.indexOf('='); + if (a < 0) + { + int count = Integer.parseInt((String)map.get("Count")); + if (count != 21) + { + continue; + } + byte[] ptByte = Hex.decode((String)map.get("Msg")); + byte[] expected = Hex.decode((String)map.get("MD")); + + byte[] hash = new byte[digest.getDigestSize()]; + + digest.update(ptByte, 0, ptByte.length); + digest.doFinal(hash, 0); + if (!Arrays.areEqual(hash, expected)) + { + mismatch(test, "Keystream " + map.get("Count"), (String)map.get("MD"), hash); + } + + if (ptByte.length > 1) + { + int split = random.nextInt(ptByte.length - 1) + 1; + digest.update(ptByte, 0, split); + digest.update(ptByte, split, ptByte.length - split); + digest.doFinal(hash, 0); + if (!Arrays.areEqual(hash, expected)) + { + mismatch(test, "Keystream " + map.get("Count"), (String)map.get("MD"), hash); + } + } + + map.clear(); + } + else + { + map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + private static void mismatch(SimpleTest test, String name, String expected, byte[] found) + { + test.fail("mismatch on " + name, expected, new String(Hex.encode(found))); + } + + /** + * Check xof. + * + * @param pXof the xof + * @param DATALEN DataLength + * @param PARTIALLEN Partial length + */ + public static void checkXof(final Xof pXof, int DATALEN, int PARTIALLEN, SecureRandom random, SimpleTest test) + { + /* Create the data */ + final byte[] myData = new byte[DATALEN]; + random.nextBytes(myData); + + /* Update the Xof with the data */ + pXof.update(myData, 0, DATALEN); + + /* Extract Xof as single block */ + final byte[] myFull = new byte[DATALEN]; + pXof.doFinal(myFull, 0, DATALEN); + + /* Update the Xof with the data */ + pXof.update(myData, 0, DATALEN); + final byte[] myPart = new byte[DATALEN]; + + /* Create the xof as partial blocks */ + for (int myPos = 0; myPos < DATALEN; myPos += PARTIALLEN) + { + final int myLen = Math.min(PARTIALLEN, DATALEN - myPos); + pXof.doOutput(myPart, myPos, myLen); + } + pXof.doFinal(myPart, 0, 0); + + /* Check that they are identical */ + if (!Arrays.areEqual(myPart, myFull)) + { + test.fail(pXof.getAlgorithmName() + ": Mismatch on partial vs full xof"); + } + } } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/ECCSISignerTest.java b/core/src/test/java/org/bouncycastle/crypto/test/ECCSISignerTest.java new file mode 100644 index 0000000000..7559cf2a90 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/test/ECCSISignerTest.java @@ -0,0 +1,181 @@ +package org.bouncycastle.crypto.test; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.AsconHash256; +import org.bouncycastle.crypto.digests.MD5Digest; +import org.bouncycastle.crypto.digests.SHA224Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA3Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.ec.CustomNamedCurves; +import org.bouncycastle.crypto.generators.ECCSIKeyPairGenerator; +import org.bouncycastle.crypto.params.ECCSIKeyGenerationParameters; +import org.bouncycastle.crypto.params.ECCSIPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECCSIPublicKeyParameters; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.crypto.signers.ECCSISigner; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; +import org.bouncycastle.util.test.SimpleTest; + +public class ECCSISignerTest + extends SimpleTest +{ + String[] curveNames = { + "curve25519", + "secp128r1", + "secp160k1", + "secp160r1", + "secp160r2", + "secp192k1", + "secp192r1", + "secp224k1", + "secp224r1", + "secp256k1", + "secp256r1", + "secp384r1", + "secp521r1", + "sect113r1", + "sect113r2", + "sect131r1", + "sect131r2", + "sect163k1", + "sect163r1", + "sect163r2", + "sect193r1", + "sect193r2", + "sect233k1", + "sect233r1", + "sect239k1", + "sect283k1", + "sect283r1", + "sect409k1", + "sect409r1", + "sect571k1", + "sect571r1", + "sm2p256v1" + }; + + Digest[] digests = new Digest[]{ + new SHA256Digest(), + new SHA3Digest(), + new SHA3Digest(512), + new SHA224Digest(), + new SHA512Digest(), + new AsconHash256(), + new SHAKEDigest(256), + new SHAKEDigest(128), + new MD5Digest() + }; + + + public static void main(String[] args) + throws Exception + { + ECCSISignerTest test = new ECCSISignerTest(); + test.performTest(); + } + + @Override + public String getName() + { + return "ECCSISigner Test"; + } + + @Override + public void performTest() + throws Exception + { + testTestVector(); + for (int i = 0; i < curveNames.length; ++i) + { + for (int j = 0; j < digests.length; ++j) + { + testRandom(curveNames[i], digests[j]); + } + } + } + + private void testTestVector() + throws Exception + { + BigInteger ksak = BigInteger.valueOf(0x12345); + BigInteger v = BigInteger.valueOf(0x23456); + BigInteger j = BigInteger.valueOf(0x34567); + ECCSIKeyPairGenerator generator = new ECCSIKeyPairGenerator(); + SecureRandom random = new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(BigIntegers.asUnsignedByteArray(32, ksak)), + new FixedSecureRandom.Data(BigIntegers.asUnsignedByteArray(32, v)), + new FixedSecureRandom.Data(BigIntegers.asUnsignedByteArray(32, j))}); + ECCSIKeyGenerationParameters keyGenerationParameters = new ECCSIKeyGenerationParameters(random, + CustomNamedCurves.getByName("secP256r1"), new SHA256Digest(), "2011-02\0tel:+447700900123\0".getBytes()); + generator.init(keyGenerationParameters); + AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); + ECCSIPublicKeyParameters pub = (ECCSIPublicKeyParameters)keyPair.getPublic(); + ECCSIPrivateKeyParameters priv = (ECCSIPrivateKeyParameters)keyPair.getPrivate(); +// System.out.println(new String(Hex.encode(pub.getPVT().getXCoord().toBigInteger().toByteArray()))); +// System.out.println(new String(Hex.encode(pub.getPVT().getYCoord().toBigInteger().toByteArray()))); +// System.out.println(new String(Hex.encode(priv.getSSK().toByteArray()))); + + byte[] M = "message\0".getBytes(); + + ECCSISigner signer = new ECCSISigner(keyGenerationParameters.getKPAK(), CustomNamedCurves.getByName("secP256r1"), new SHA256Digest(), keyGenerationParameters.getId()); + signer.init(true, new ParametersWithRandom(priv, random)); + signer.update(M, 0, M.length); + byte[] sig = signer.generateSignature(); + isTrue(Arrays.areEqual(sig, Hex.decode("269D4C8F DEB66A74 E4EF8C0D 5DCC597D\n" + + " DFE6029C 2AFFC493 6008CD2C C1045D81\n" + + " E09B528D 0EF8D6DF 1AA3ECBF 80110CFC\n" + + " EC9FC682 52CEBB67 9F413484 6940CCFD\n" + + " 04\n" + + "\n" + + " 758A1427 79BE89E8 29E71984 CB40EF75\n" + + " 8CC4AD77 5FC5B9A3 E1C8ED52 F6FA36D9\n" + + " A79D2476 92F4EDA3 A6BDAB77 D6AA6474\n" + + " A464AE49 34663C52 65BA7018 BA091F79"))); +// System.out.println("sig: " + new String(Hex.encode(sig))); + + signer.init(false, pub); + signer.update(M, 0, M.length); + isTrue(signer.verifySignature(sig)); + } + + private void testRandom(String curveName, Digest digest) + throws Exception + { + SecureRandom random = new SecureRandom(); + ECCSIKeyPairGenerator generator = new ECCSIKeyPairGenerator(); + byte[] id = new byte[16]; + random.nextBytes(id); + X9ECParameters params = CustomNamedCurves.getByName(curveName); + ECCSIKeyGenerationParameters keyGenerationParameters = new ECCSIKeyGenerationParameters(random, + params, digest, id); + generator.init(keyGenerationParameters); + AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); + ECCSIPublicKeyParameters pub = (ECCSIPublicKeyParameters)keyPair.getPublic(); + ECCSIPrivateKeyParameters priv = (ECCSIPrivateKeyParameters)keyPair.getPrivate(); + + byte[] M = "message\0".getBytes(); + + ECCSISigner signer = new ECCSISigner(keyGenerationParameters.getKPAK(), params, digest, keyGenerationParameters.getId()); + signer.init(true, new ParametersWithRandom(priv, random)); + signer.update(M, 0, M.length); + signer.reset(); + signer.update(M, 0, M.length); + byte[] sig = signer.generateSignature(); + signer = new ECCSISigner(keyGenerationParameters.getKPAK(), params, digest, keyGenerationParameters.getId()); + signer.init(false, pub); + signer.update(M, 0, M.length); + signer.reset(); + signer.update(M, 0, M.length); + isTrue(signer.verifySignature(sig)); + } + +} diff --git a/core/src/test/java/org/bouncycastle/crypto/test/ElephantTest.java b/core/src/test/java/org/bouncycastle/crypto/test/ElephantTest.java index f9a4c388d0..5d2408a8d7 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/ElephantTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/ElephantTest.java @@ -8,9 +8,9 @@ import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.ElephantEngine; import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.test.TestResourceFinder; @@ -32,15 +32,53 @@ public void performTest() testVectors(ElephantEngine.ElephantParameters.elephant160, "v160"); testVectors(ElephantEngine.ElephantParameters.elephant176, "v176"); - ElephantEngine elephant = new ElephantEngine(ElephantEngine.ElephantParameters.elephant160); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 41, 10, 128, 12, new ElephantEngine(ElephantEngine.ElephantParameters.elephant160)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 41, 10, 128, 12, new ElephantEngine(ElephantEngine.ElephantParameters.elephant176)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 41, 10, 128, 12, new ElephantEngine(ElephantEngine.ElephantParameters.elephant200)); + CipherTest.checkAEADParemeter(this, 16, 12, 8, 20, new ElephantEngine(ElephantEngine.ElephantParameters.elephant160)); + CipherTest.checkAEADParemeter(this, 16, 12, 8, 22, new ElephantEngine(ElephantEngine.ElephantParameters.elephant176)); + CipherTest.checkAEADParemeter(this, 16, 12, 16, 25, new ElephantEngine(ElephantEngine.ElephantParameters.elephant200)); + CipherTest.testOverlapping(this, 16, 12, 8, 20, new ElephantEngine(ElephantEngine.ElephantParameters.elephant160)); + CipherTest.testOverlapping(this, 16, 12, 8, 22, new ElephantEngine(ElephantEngine.ElephantParameters.elephant176)); + CipherTest.testOverlapping(this, 16, 12, 16, 25, new ElephantEngine(ElephantEngine.ElephantParameters.elephant200)); + CipherTest.checkAEADCipherOutputSize(this, 16, 12, 20, 8, new ElephantEngine(ElephantEngine.ElephantParameters.elephant160)); + CipherTest.checkAEADCipherOutputSize(this, 16, 12, 22, 8, new ElephantEngine(ElephantEngine.ElephantParameters.elephant176)); + CipherTest.checkAEADCipherOutputSize(this, 16, 12, 25, 16, new ElephantEngine(ElephantEngine.ElephantParameters.elephant200)); +// //testVectors(ElephantEngine.ElephantParameters.elephant160, "v160_2"); + ElephantEngine elephant = new ElephantEngine(ElephantEngine.ElephantParameters.elephant200); testExceptions(elephant, elephant.getKeyBytesSize(), elephant.getIVBytesSize(), elephant.getBlockSize()); - testParameters(elephant, 16, 12, 8); - elephant = new ElephantEngine(ElephantEngine.ElephantParameters.elephant176); + implTestParametersEngine(elephant, 16, 12, 16); + CipherTest.checkCipher(10, 12, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new ElephantEngine(ElephantEngine.ElephantParameters.elephant160); + } + }); + CipherTest.checkCipher(10, 12, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new ElephantEngine(ElephantEngine.ElephantParameters.elephant176); + } + }); + CipherTest.checkCipher(10, 12, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new ElephantEngine(ElephantEngine.ElephantParameters.elephant200); + } + }); + + + + elephant = new ElephantEngine(ElephantEngine.ElephantParameters.elephant160); testExceptions(elephant, elephant.getKeyBytesSize(), elephant.getIVBytesSize(), elephant.getBlockSize()); - testParameters(elephant, 16, 12, 8); - elephant = new ElephantEngine(ElephantEngine.ElephantParameters.elephant200); + implTestParametersEngine(elephant, 16, 12, 8); + elephant = new ElephantEngine(ElephantEngine.ElephantParameters.elephant176); testExceptions(elephant, elephant.getKeyBytesSize(), elephant.getIVBytesSize(), elephant.getBlockSize()); - testParameters(elephant, 16, 12, 16); + implTestParametersEngine(elephant, 16, 12, 8); + } @@ -60,7 +98,7 @@ private void testVectors(ElephantEngine.ElephantParameters pbp, String filename) int a = line.indexOf('='); if (a < 0) { -// if (!map.get("Count").equals("859")) +// if (!map.get("Count").equals("689")) // { // continue; // } @@ -106,7 +144,7 @@ private void testVectors(ElephantEngine.ElephantParameters pbp, String filename) map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); } } - // System.out.println("Elephant AEAD pass"); + // System.out.println("Elephant AEAD pass"); } private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, int blocksize) @@ -153,7 +191,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(c1, m.length); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before dofinal"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -165,7 +203,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, // aeadBlockCipher.getOutputSize(0); // aeadBlockCipher.getUpdateOutputSize(0); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected fail(aeadBlockCipher.getAlgorithmName() + " functions can be called before initialisation"); @@ -195,17 +233,8 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, //expected } - try - { - aeadBlockCipher.init(true, new AEADParameters(new KeyParameter(k), 0, iv)); - fail(aeadBlockCipher.getAlgorithmName() + " wrong type of CipherParameters"); - } - catch (IllegalArgumentException e) - { - //expected - } - aeadBlockCipher.init(true, params); + c1 = new byte[aeadBlockCipher.getOutputSize(0)]; try { aeadBlockCipher.doFinal(c1, m.length); @@ -283,6 +312,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, // } try { + aeadBlockCipher.init(true, params); aeadBlockCipher.doFinal(new byte[2], 2); fail(aeadBlockCipher.getAlgorithmName() + ": output for dofinal is too short"); } @@ -305,15 +335,14 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, fail(aeadBlockCipher.getAlgorithmName() + ": mac should match for the same AAD with different ways of inputing"); } - byte[] c2 = new byte[aeadBlockCipher.getOutputSize(10)]; - byte[] c3 = new byte[aeadBlockCipher.getOutputSize(10) + 2]; - byte[] aad2 = {0, 1, 2, 3, 4}; byte[] aad3 = {0, 0, 1, 2, 3, 4, 5}; byte[] m2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] m3 = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; byte[] m4 = new byte[m2.length]; aeadBlockCipher.init(true, params); + byte[] c2 = new byte[aeadBlockCipher.getOutputSize(10)]; + byte[] c3 = new byte[aeadBlockCipher.getOutputSize(10) + 2]; aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); int offset = aeadBlockCipher.processBytes(m2, 0, m2.length, c2, 0); aeadBlockCipher.doFinal(c2, offset); @@ -347,12 +376,12 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(m4, offset); fail(aeadBlockCipher.getAlgorithmName() + ": The decryption should fail"); } - catch (IllegalArgumentException e) + catch (InvalidCipherTextException e) { //expected; } - byte[] m7 = new byte[blocksize * 2]; + byte[] m7 = new byte[blocksize * 3]; for (int i = 0; i < m7.length; ++i) { m7[i] = (byte)rand.nextInt(); @@ -370,34 +399,49 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, offset = aeadBlockCipher.processBytes(m7, 0, blocksize, c8, 0); offset += aeadBlockCipher.processBytes(m7, blocksize, m7.length - blocksize, c8, offset); aeadBlockCipher.doFinal(c8, offset); - aeadBlockCipher.init(true, params); - int split = rand.nextInt(blocksize * 2); - aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); - offset = aeadBlockCipher.processBytes(m7, 0, split, c9, 0); - offset += aeadBlockCipher.processBytes(m7, split, m7.length - split, c9, offset); - aeadBlockCipher.doFinal(c9, offset); - if (!areEqual(c7, c8) || !areEqual(c7, c9)) + + // random split for several times + for (int split = 0; split < blocksize * 3; ++split) { - fail(aeadBlockCipher.getAlgorithmName() + ": Splitting input of plaintext should output the same ciphertext"); + aeadBlockCipher.init(true, params); + aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); + offset = aeadBlockCipher.processBytes(m7, 0, split, c9, 0); + offset += aeadBlockCipher.processBytes(m7, split, m7.length - split, c9, offset); + aeadBlockCipher.doFinal(c9, offset); + if (!areEqual(c7, c8) || !areEqual(c7, c9)) + { + fail(aeadBlockCipher.getAlgorithmName() + ": Splitting input of plaintext should output the same ciphertext"); + } } - // System.out.println(aeadBlockCipher.getAlgorithmName() + " test Exceptions pass"); + + // System.out.println(aeadBlockCipher.getAlgorithmName() + " test Exceptions pass"); } - private void testParameters(ElephantEngine isap, int keySize, int ivSize, int macSize) + private void implTestParametersEngine(ElephantEngine cipher, int keySize, int ivSize, + int macSize) { - if (isap.getKeyBytesSize() != keySize) + if (cipher.getKeyBytesSize() != keySize) { - fail(isap.getAlgorithmName() + ": key bytes of " + isap.getAlgorithmName() + " is not correct"); + fail("key bytes of " + cipher.getAlgorithmName() + " is not correct"); } - if (isap.getIVBytesSize() != ivSize) + if (cipher.getIVBytesSize() != ivSize) { - fail(isap.getAlgorithmName() + ": iv bytes of " + isap.getAlgorithmName() + " is not correct"); + fail("iv bytes of " + cipher.getAlgorithmName() + " is not correct"); } - if (isap.getOutputSize(0) != macSize) + + CipherParameters parameters = new ParametersWithIV(new KeyParameter(new byte[keySize]), new byte[ivSize]); + + cipher.init(true, parameters); + if (cipher.getOutputSize(0) != macSize) { - fail(isap.getAlgorithmName() + ": mac bytes of " + isap.getAlgorithmName() + " is not correct"); + fail("getOutputSize of " + cipher.getAlgorithmName() + " is incorrect for encryption"); + } + + cipher.init(false, parameters); + if (cipher.getOutputSize(macSize) != 0) + { + fail("getOutputSize of " + cipher.getAlgorithmName() + " is incorrect for decryption"); } - // System.out.println(isap.getAlgorithmName() + " test Parameters pass"); } @@ -410,7 +454,5 @@ public static void main(String[] args) { runTest(new ElephantTest()); } - - } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/GOST28147Test.java b/core/src/test/java/org/bouncycastle/crypto/test/GOST28147Test.java index 74e78614b3..c656caa3e6 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/GOST28147Test.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/GOST28147Test.java @@ -4,9 +4,11 @@ import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.CryptoException; import org.bouncycastle.crypto.digests.GOST3411Digest; +import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.GOST28147Engine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.modes.CFBBlockCipher; +import org.bouncycastle.crypto.modes.GCFBBlockCipher; import org.bouncycastle.crypto.modes.GOFBBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; @@ -197,7 +199,8 @@ public void performTest() throws Exception { super.performTest(); - + checkCipher(new GCFBBlockCipher(new GOST28147Engine()), 2049); + checkCipher(new GCFBBlockCipher(AESEngine.newInstance()), 2049); //advanced tests with GOST28147KeyGenerator: //encrypt on hesh message; ECB mode: byte[] in = Hex.decode("4e6f77206973207468652074696d6520666f7220616c6c20"); diff --git a/core/src/test/java/org/bouncycastle/crypto/test/GiftCofbTest.java b/core/src/test/java/org/bouncycastle/crypto/test/GiftCofbTest.java new file mode 100644 index 0000000000..a7d18239f1 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/test/GiftCofbTest.java @@ -0,0 +1,84 @@ +package org.bouncycastle.crypto.test; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.engines.GiftCofbEngine; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.test.SimpleTest; + +public class GiftCofbTest + extends SimpleTest +{ + public String getName() + { + return "GiftCofb"; + } + + public void performTest() + throws Exception + { + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 16, 16, new GiftCofbEngine()); + CipherTest.implTestVectorsEngine(new GiftCofbEngine(), "crypto/giftcofb", "giftcofb_LWC_AEAD_KAT_128_128.txt", this); + CipherTest.implTestBufferingEngine(16, 16, 128, this, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new GiftCofbEngine(); + } + }); + CipherTest.implTestExceptionsEngine(16, 16, this, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new GiftCofbEngine(); + } + }); + implTestParametersEngine(new GiftCofbEngine(), 16, 16, 16); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new GiftCofbEngine()); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new GiftCofbEngine()); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new GiftCofbEngine()); + + CipherTest.checkCipher(16, 16, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new GiftCofbEngine(); + } + }); + } + + private void implTestParametersEngine(GiftCofbEngine cipher, int keySize, int ivSize, + int macSize) + { + if (cipher.getKeyBytesSize() != keySize) + { + fail("key bytes of " + cipher.getAlgorithmName() + " is not correct"); + } + if (cipher.getIVBytesSize() != ivSize) + { + fail("iv bytes of " + cipher.getAlgorithmName() + " is not correct"); + } + + CipherParameters parameters = new ParametersWithIV(new KeyParameter(new byte[keySize]), new byte[ivSize]); + + cipher.init(true, parameters); + if (cipher.getOutputSize(0) != macSize) + { + fail("getOutputSize of " + cipher.getAlgorithmName() + " is incorrect for encryption"); + } + + cipher.init(false, parameters); + if (cipher.getOutputSize(macSize) != 0) + { + fail("getOutputSize of " + cipher.getAlgorithmName() + " is incorrect for decryption"); + } + } + + public static void main(String[] args) + { + runTest(new GiftCofbTest()); + } +} diff --git a/core/src/test/java/org/bouncycastle/crypto/test/Grain128AEADTest.java b/core/src/test/java/org/bouncycastle/crypto/test/Grain128AEADTest.java index 161fcb68e4..5937166965 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/Grain128AEADTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/Grain128AEADTest.java @@ -1,19 +1,17 @@ package org.bouncycastle.crypto.test; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; +import java.security.SecureRandom; -import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.Grain128AEADEngine; +import org.bouncycastle.crypto.modes.AEADCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; -import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; +import org.bouncycastle.util.test.SimpleTestResult; +import org.bouncycastle.util.test.TestFailedException; public class Grain128AEADTest extends SimpleTest @@ -26,49 +24,27 @@ public String getName() public void performTest() throws Exception { - testVectors(); + CipherTest.testOverlapping(this, 16, 12, 8, 20, new Grain128AEADEngine()); + CipherTest.implTestVectorsEngine(new Grain128AEADEngine(), "crypto", "LWC_AEAD_KAT_128_96.txt", this); + checkAEADCipherOutputSize(this, 16, 12, 8, new Grain128AEADEngine()); + CipherTest.checkCipher(32, 12, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new Grain128AEADEngine(); + } + }); + CipherTest.checkAEADCipherMultipleBlocks(this, 1024, 7, 100, 128, 12, new Grain128AEADEngine()); + + + CipherTest.checkAEADParemeter(this, 16, 12, 8, 20, new Grain128AEADEngine()); + testSplitUpdate(); testExceptions(); testLongAEAD(); } - private void testVectors() - throws Exception - { - Grain128AEADEngine grain = new Grain128AEADEngine(); - CipherParameters params; - InputStream src = TestResourceFinder.findTestResource("crypto", "LWC_AEAD_KAT_128_96.txt"); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - String line; - byte[] ptByte, adByte; - byte[] rv; - HashMap map = new HashMap(); - while ((line = bin.readLine()) != null) - { - int a = line.indexOf('='); - if (a < 0) - { - params = new ParametersWithIV(new KeyParameter(Hex.decode((String)map.get("Key"))), Hex.decode((String)map.get("Nonce"))); - grain.init(true, params); - adByte = Hex.decode((String)map.get("AD")); - grain.processAADBytes(adByte, 0, adByte.length); - ptByte = Hex.decode((String)map.get("PT")); - rv = new byte[ptByte.length]; - grain.processBytes(ptByte, 0, ptByte.length, rv, 0); - byte[] mac = new byte[8]; - grain.doFinal(mac, 0); - if (!areEqual(Arrays.concatenate(rv, mac), Hex.decode((String)map.get("CT")))) - { - mismatch("Keystream " + map.get("Count"), (String)map.get("CT"), rv); - } - map.clear(); - } - else - { - map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); - } - } - } private void testSplitUpdate() throws InvalidCipherTextException @@ -95,7 +71,7 @@ private void testSplitUpdate() grain.doFinal(rv, len); isTrue(Arrays.areEqual(rv, CT)); - + grain.init(true, params); grain.processBytes(PT, 0, 10, rv, 0); try { @@ -104,7 +80,7 @@ private void testSplitUpdate() } catch (IllegalStateException e) { - isEquals("associated data must be added before plaintext/ciphertext", e.getMessage()); + isEquals("Grain-128 AEAD needs to be initialized", e.getMessage()); } try @@ -114,7 +90,7 @@ private void testSplitUpdate() } catch (IllegalStateException e) { - isEquals("associated data must be added before plaintext/ciphertext", e.getMessage()); + isEquals("Grain-128 AEAD needs to be initialized", e.getMessage()); } } @@ -127,11 +103,11 @@ private void testLongAEAD() byte[] AD = Hex.decode( // 186 bytes "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9"); byte[] CT = Hex.decode("731DAA8B1D15317A1CCB4E3DD320095FB27E5BB2A10F2C669F870538637D4F162298C70430A2B560"); - + Grain128AEADEngine grain = new Grain128AEADEngine(); ParametersWithIV params = new ParametersWithIV(new KeyParameter(Key), Nonce); grain.init(true, params); - + grain.processAADBytes(AD, 0, AD.length); byte[] rv = new byte[CT.length]; @@ -140,9 +116,9 @@ private void testLongAEAD() len += grain.processBytes(PT, 11, PT.length - 11, rv, len); grain.doFinal(rv, len); - - isTrue(Arrays.areEqual(rv, CT)); + isTrue(Arrays.areEqual(rv, CT)); + grain.init(true, params); grain.processBytes(PT, 0, 10, rv, 0); try { @@ -151,7 +127,7 @@ private void testLongAEAD() } catch (IllegalStateException e) { - isEquals("associated data must be added before plaintext/ciphertext", e.getMessage()); + isEquals("Grain-128 AEAD needs to be initialized", e.getMessage()); } try @@ -161,7 +137,7 @@ private void testLongAEAD() } catch (IllegalStateException e) { - isEquals("associated data must be added before plaintext/ciphertext", e.getMessage()); + isEquals("Grain-128 AEAD needs to be initialized", e.getMessage()); } } @@ -177,7 +153,7 @@ private void testExceptions() } catch (IllegalArgumentException e) { - isEquals("Grain-128AEAD init parameters must include an IV", e.getMessage()); + isEquals("invalid parameters passed to Grain-128 AEAD", e.getMessage()); } try @@ -189,7 +165,7 @@ private void testExceptions() } catch (IllegalArgumentException e) { - isEquals("Grain-128AEAD requires exactly 12 bytes of IV", e.getMessage()); + isEquals("Grain-128 AEAD requires exactly 12 bytes of IV", e.getMessage()); } try @@ -201,13 +177,57 @@ private void testExceptions() } catch (IllegalArgumentException e) { - isEquals("Grain-128AEAD key must be 128 bits long", e.getMessage()); + isEquals("Grain-128 AEAD key must be 16 bytes long", e.getMessage()); } } - private void mismatch(String name, String expected, byte[] found) + static void checkAEADCipherOutputSize(SimpleTest parent, int keySize, int ivSize, int tagSize, AEADCipher cipher) + throws InvalidCipherTextException { - fail("mismatch on " + name, expected, new String(Hex.encode(found))); + final SecureRandom random = new SecureRandom(); + int tmpLength = random.nextInt(tagSize - 1) + 1; + final byte[] plaintext = new byte[tmpLength]; + byte[] key = new byte[keySize]; + byte[] iv = new byte[ivSize]; + random.nextBytes(key); + random.nextBytes(iv); + random.nextBytes(plaintext); + cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); + byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)]; + //before the encrypt + isEqualTo(parent, plaintext.length + tagSize, ciphertext.length); + isEqualTo(parent, plaintext.length, cipher.getUpdateOutputSize(plaintext.length)); + //during the encrypt process of the first block + int len = cipher.processBytes(plaintext, 0, tmpLength, ciphertext, 0); + isEqualTo(parent, plaintext.length + tagSize, len + cipher.getOutputSize(plaintext.length - tmpLength)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(plaintext.length - tmpLength)); + //process doFinal + len += cipher.doFinal(ciphertext, len); + isEqualTo(parent, len, ciphertext.length); + + cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv)); + //before the encrypt + isEqualTo(parent, plaintext.length, cipher.getOutputSize(ciphertext.length)); + isEqualTo(parent, plaintext.length, cipher.getUpdateOutputSize(ciphertext.length)); + //during the encrypt process of the first block + len = cipher.processBytes(ciphertext, 0, tmpLength, plaintext, 0); + isEqualTo(parent, plaintext.length, len + cipher.getOutputSize(ciphertext.length - tmpLength)); + isEqualTo(parent, plaintext.length, len + cipher.getUpdateOutputSize(ciphertext.length - tmpLength)); + //process doFinal + len = cipher.processBytes(ciphertext, tmpLength, tagSize, plaintext, 0); + len += cipher.doFinal(plaintext, len); + isEqualTo(parent, len, plaintext.length); + } + + static void isEqualTo( + SimpleTest parent, + int a, + int b) + { + if (a != b) + { + throw new TestFailedException(SimpleTestResult.failed(parent, "no message")); + } } public static void main(String[] args) @@ -215,4 +235,3 @@ public static void main(String[] args) runTest(new Grain128AEADTest()); } } - diff --git a/core/src/test/java/org/bouncycastle/crypto/test/HPKETestVectors.java b/core/src/test/java/org/bouncycastle/crypto/test/HPKETestVectors.java index 7f3c12579b..830535a040 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/HPKETestVectors.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/HPKETestVectors.java @@ -8,7 +8,6 @@ import java.util.HashMap; import java.util.Iterator; -import junit.framework.TestCase; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.hpke.AEAD; @@ -16,10 +15,14 @@ import org.bouncycastle.crypto.hpke.HPKEContext; import org.bouncycastle.crypto.hpke.HPKEContextWithEncapsulation; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; +import junit.framework.TestCase; + public class HPKETestVectors extends TestCase { @@ -259,26 +262,50 @@ public void testVectors() // generate a private key from skRm and pkRm AsymmetricCipherKeyPair kp = hpke.deserializePrivateKey(skRm, pkRm); + byte[] skRm_serialized = Arrays.clone(skRm); + byte[] skSm_serialized = Arrays.clone(skSm); + byte[] skEm_serialized = Arrays.clone(skEm); + + switch (kem_id) + { + case HPKE.kem_X25519_SHA256: + X25519.clampPrivateKey(skRm_serialized); + if (mode == 2 || mode == 3) + { + X25519.clampPrivateKey(skSm_serialized); + } + X25519.clampPrivateKey(skEm_serialized); + break; + case HPKE.kem_X448_SHA512: + X448.clampPrivateKey(skRm_serialized); + if (mode == 2 || mode == 3) + { + X448.clampPrivateKey(skSm_serialized); + } + X448.clampPrivateKey(skEm_serialized); + break; + } + // tesing serialize assertTrue("serialize public key failed", Arrays.areEqual(pkRm, hpke.serializePublicKey(kp.getPublic()))); - assertTrue("serialize private key failed", Arrays.areEqual(skRm, hpke.serializePrivateKey(kp.getPrivate()))); + assertTrue("serialize private key failed", Arrays.areEqual(skRm_serialized, hpke.serializePrivateKey(kp.getPrivate()))); // testing receiver derive key pair assertTrue("receiver derived public key pair incorrect", Arrays.areEqual(pkRm, hpke.serializePublicKey(derivedKeyPairR.getPublic()))); - assertTrue("receiver derived secret key pair incorrect", Arrays.areEqual(skRm, hpke.serializePrivateKey(derivedKeyPairR.getPrivate()))); + assertTrue("receiver derived secret key pair incorrect", Arrays.areEqual(skRm_serialized, hpke.serializePrivateKey(derivedKeyPairR.getPrivate()))); // testing sender's derived key pair if (mode == 2 || mode == 3) { AsymmetricCipherKeyPair derivedSenderKeyPair = hpke.deriveKeyPair(ikmS); assertTrue("sender derived public key pair incorrect", Arrays.areEqual(pkSm, hpke.serializePublicKey(derivedSenderKeyPair.getPublic()))); - assertTrue("sender derived private key pair incorrect", Arrays.areEqual(skSm, hpke.serializePrivateKey(derivedSenderKeyPair.getPrivate()))); + assertTrue("sender derived private key pair incorrect", Arrays.areEqual(skSm_serialized, hpke.serializePrivateKey(derivedSenderKeyPair.getPrivate()))); } // testing ephemeral derived key pair AsymmetricCipherKeyPair derivedEKeyPair = hpke.deriveKeyPair(ikmE); assertTrue("ephemeral derived public key pair incorrect", Arrays.areEqual(pkEm, hpke.serializePublicKey(derivedEKeyPair.getPublic()))); - assertTrue("ephemeral derived private key pair incorrect", Arrays.areEqual(skEm, hpke.serializePrivateKey(derivedEKeyPair.getPrivate()))); + assertTrue("ephemeral derived private key pair incorrect", Arrays.areEqual(skEm_serialized, hpke.serializePrivateKey(derivedEKeyPair.getPrivate()))); // create a context with setupRecv // use pkEm as encap, private key from above, info as info diff --git a/core/src/test/java/org/bouncycastle/crypto/test/ISAPTest.java b/core/src/test/java/org/bouncycastle/crypto/test/ISAPTest.java index 88574af391..007fa98f90 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/ISAPTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/ISAPTest.java @@ -8,12 +8,11 @@ import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.digests.ISAPDigest; import org.bouncycastle.crypto.engines.ISAPEngine; import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.test.TestResourceFinder; @@ -33,6 +32,13 @@ public String getName() public void performTest() throws Exception { + DigestTest.implTestVectorsDigest(this, new ISAPDigest(), "crypto/isap", "LWC_HASH_KAT_256.txt"); + DigestTest.checkDigestReset(this, new ISAPDigest()); + DigestTest.implTestExceptionsAndParametersDigest(this, new ISAPDigest(), 32); + testVectors("isapa128av20", IsapType.ISAP_A_128A); + testVectors("isapa128v20", IsapType.ISAP_A_128); + testVectors("isapk128av20", IsapType.ISAP_K_128A); + testVectors("isapk128v20", IsapType.ISAP_K_128); ISAPEngine ISAP = new ISAPEngine(IsapType.ISAP_K_128A); testExceptions(ISAP, ISAP.getKeyBytesSize(), ISAP.getIVBytesSize(), ISAP.getBlockSize()); testParameters(ISAP, 16, 16, 16); @@ -45,12 +51,55 @@ public void performTest() ISAP = new ISAPEngine(IsapType.ISAP_A_128); testExceptions(ISAP, ISAP.getKeyBytesSize(), ISAP.getIVBytesSize(), ISAP.getBlockSize()); testParameters(ISAP, 16, 16, 16); - testExceptions(new ISAPDigest(), 32); - testVectors("isapa128av20", IsapType.ISAP_A_128A); - testVectors("isapa128v20", IsapType.ISAP_A_128); - testVectors("isapk128av20", IsapType.ISAP_K_128A); - testVectors("isapk128v20", IsapType.ISAP_K_128); - testVectors(); + + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new ISAPEngine(IsapType.ISAP_K_128A); + } + }); + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new ISAPEngine(IsapType.ISAP_K_128); + } + }); + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new ISAPEngine(IsapType.ISAP_A_128A); + } + }); + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new ISAPEngine(IsapType.ISAP_A_128); + } + }); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new ISAPEngine(IsapType.ISAP_K_128A)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new ISAPEngine(IsapType.ISAP_K_128)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 8, new ISAPEngine(IsapType.ISAP_A_128A)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 8, new ISAPEngine(IsapType.ISAP_A_128)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new ISAPEngine(IsapType.ISAP_K_128A)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new ISAPEngine(IsapType.ISAP_K_128)); + CipherTest.testOverlapping(this, 16, 16, 16, 8, new ISAPEngine(IsapType.ISAP_A_128A)); + CipherTest.testOverlapping(this, 16, 16, 16, 8, new ISAPEngine(IsapType.ISAP_A_128)); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 18, 16, new ISAPEngine(IsapType.ISAP_K_128A)); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 18, 16, new ISAPEngine(IsapType.ISAP_K_128)); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 8, 16, new ISAPEngine(IsapType.ISAP_A_128A)); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 8, 16, new ISAPEngine(IsapType.ISAP_A_128)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new ISAPEngine(IsapType.ISAP_K_128A)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new ISAPEngine(IsapType.ISAP_K_128)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new ISAPEngine(IsapType.ISAP_A_128A)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new ISAPEngine(IsapType.ISAP_A_128)); } private void testVectors(String filename, IsapType isapType) @@ -68,10 +117,10 @@ private void testVectors(String filename, IsapType isapType) int a = line.indexOf('='); if (a < 0) { -// if (!map.get("Count").equals("265")) -// { -// continue; -// } + if (!map.get("Count").equals("265")) + { + continue; + } byte[] key = Hex.decode(map.get("Key")); byte[] nonce = Hex.decode(map.get("Nonce")); byte[] ad = Hex.decode(map.get("AD")); @@ -104,6 +153,7 @@ private void testVectors(String filename, IsapType isapType) { mismatch("Reccover Keystream " + map.get("Count"), (String)map.get("PT"), pt_recovered); } + //System.out.println("Keystream " + map.get("Count") + " pass"); isap.reset(); map.clear(); @@ -116,74 +166,6 @@ private void testVectors(String filename, IsapType isapType) //System.out.print.println(filename + " pass"); } - private void testVectors() - throws Exception - { - ISAPDigest isap = new ISAPDigest(); - InputStream src = TestResourceFinder.findTestResource("crypto/isap", "LWC_HASH_KAT_256.txt"); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - String line; - byte[] ptByte; - HashMap map = new HashMap(); - while ((line = bin.readLine()) != null) - { - int a = line.indexOf('='); - if (a < 0) - { -// if (!map.get("Count").equals("10")) -// { -// continue; -// } - ptByte = Hex.decode((String)map.get("Msg")); - isap.update(ptByte, 0, ptByte.length); - byte[] hash = new byte[32]; - isap.doFinal(hash, 0); - if (!areEqual(hash, Hex.decode((String)map.get("MD")))) - { - mismatch("Keystream " + map.get("Count"), (String)map.get("MD"), hash); - } -// else -// { -// System.out.println(map.get("Count") + " pass"); -// } - map.clear(); - isap.reset(); - } - else - { - map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); - } - } - //System.out.print.println("ISAP Hash pass"); - } - - private void testExceptions(Digest digest, int digestsize) - { - if (digest.getDigestSize() != digestsize) - { - fail(digest.getAlgorithmName() + ": digest size is not correct"); - } - - try - { - digest.update(new byte[1], 1, 1); - fail(digest.getAlgorithmName() + ": input for update is too short"); - } - catch (DataLengthException e) - { - //expected - } - try - { - digest.doFinal(new byte[digest.getDigestSize() - 1], 2); - fail(digest.getAlgorithmName() + ": output for dofinal is too short"); - } - catch (DataLengthException e) - { - //expected - } - //System.out.print.println(digest.getAlgorithmName() + " test Exceptions pass"); - } private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, int blocksize) throws Exception @@ -199,7 +181,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.processBytes(m, 0, m.length, c1, 0); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before processBytes"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -209,7 +191,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.processByte((byte)0, c1, 0); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before processByte"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -219,7 +201,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.reset(); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before reset"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -229,7 +211,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(c1, m.length); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before dofinal"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -241,7 +223,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.getOutputSize(0); aeadBlockCipher.getUpdateOutputSize(0); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected fail(aeadBlockCipher.getAlgorithmName() + " functions can be called before initialisation"); @@ -271,17 +253,8 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, //expected } - try - { - aeadBlockCipher.init(true, new AEADParameters(new KeyParameter(k), 0, iv)); - fail(aeadBlockCipher.getAlgorithmName() + " wrong type of CipherParameters"); - } - catch (IllegalArgumentException e) - { - //expected - } - aeadBlockCipher.init(true, params); + c1 = new byte[aeadBlockCipher.getOutputSize(m.length)]; try { aeadBlockCipher.doFinal(c1, m.length); @@ -299,6 +272,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, { fail(aeadBlockCipher.getAlgorithmName() + ": mac should be equal when calling dofinal and getMac"); } + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADByte((byte)0); byte[] mac1 = new byte[aeadBlockCipher.getOutputSize(0)]; aeadBlockCipher.doFinal(mac1, 0); @@ -307,6 +281,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, fail(aeadBlockCipher.getAlgorithmName() + ": mac should not match"); } aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processBytes(new byte[16], 0, 16, new byte[16], 0); // try // { @@ -348,7 +323,8 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } try { - aeadBlockCipher.processBytes(new byte[blocksize], 0, blocksize, new byte[blocksize], blocksize >> 1); + aeadBlockCipher.init(true, params); + aeadBlockCipher.processBytes(new byte[blocksize + 1], 0, blocksize + 1, new byte[blocksize], blocksize >> 1); fail(aeadBlockCipher.getAlgorithmName() + ": output for processBytes is too short"); } catch (OutputLengthException e) @@ -368,9 +344,11 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, mac1 = new byte[aeadBlockCipher.getOutputSize(0)]; mac2 = new byte[aeadBlockCipher.getOutputSize(0)]; aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(new byte[]{0, 0}, 0, 2); aeadBlockCipher.doFinal(mac1, 0); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADByte((byte)0); aeadBlockCipher.processAADByte((byte)0); aeadBlockCipher.doFinal(mac2, 0); @@ -388,10 +366,12 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, byte[] m3 = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; byte[] m4 = new byte[m2.length]; aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); int offset = aeadBlockCipher.processBytes(m2, 0, m2.length, c2, 0); aeadBlockCipher.doFinal(c2, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad3, 1, aad2.length); offset = aeadBlockCipher.processBytes(m3, 1, m2.length, c3, 1); aeadBlockCipher.doFinal(c3, offset + 1); @@ -421,7 +401,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(m4, offset); fail(aeadBlockCipher.getAlgorithmName() + ": The decryption should fail"); } - catch (IllegalArgumentException e) + catch (InvalidCipherTextException e) { //expected; } @@ -431,20 +411,23 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, { m7[i] = (byte)rand.nextInt(); } + + aeadBlockCipher.init(true, params); byte[] c7 = new byte[aeadBlockCipher.getOutputSize(m7.length)]; byte[] c8 = new byte[c7.length]; byte[] c9 = new byte[c7.length]; - aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, m7.length, c7, 0); aeadBlockCipher.doFinal(c7, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, blocksize, c8, 0); offset += aeadBlockCipher.processBytes(m7, blocksize, m7.length - blocksize, c8, offset); aeadBlockCipher.doFinal(c8, offset); aeadBlockCipher.reset(); int split = rand.nextInt(blocksize * 2); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, split, c9, 0); offset += aeadBlockCipher.processBytes(m7, split, m7.length - split, c9, offset); diff --git a/core/src/test/java/org/bouncycastle/crypto/test/NISTCTSTest.java b/core/src/test/java/org/bouncycastle/crypto/test/NISTCTSTest.java index b1febcd4ca..11d1009a86 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/NISTCTSTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/NISTCTSTest.java @@ -1,14 +1,19 @@ package org.bouncycastle.crypto.test; +import java.security.SecureRandom; + import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.engines.DSTU7624Engine; +import org.bouncycastle.crypto.modes.KXTSBlockCipher; import org.bouncycastle.crypto.modes.NISTCTSBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; @@ -36,23 +41,23 @@ public class NISTCTSTest private static byte[] cs2NotQuiteTwoBlockOut = Hex.decode("f098097ca69b72e3a46e9ca21bb5ebbc22ecf2ac77"); private static byte[] cs3NotQuiteTwoBlockOut = Hex.decode("f098097ca69b72e3a46e9ca21bb5ebbc22ecf2ac77"); - static byte[] in1 = Hex.decode("4e6f7720697320746865207420"); - static byte[] in2 = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f0aaa"); - static byte[] out1 = Hex.decode("9952f131588465033fa40e8a98"); - static byte[] out2 = Hex.decode("358f84d01eb42988dc34efb994"); - static byte[] out3 = Hex.decode("170171cfad3f04530c509b0c1f0be0aefbd45a8e3755a873bff5ea198504b71683c6"); - + static byte[] in1 = Hex.decode("4e6f7720697320746865207420"); + static byte[] in2 = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f0aaa"); + static byte[] out1 = Hex.decode("9952f131588465033fa40e8a98"); + static byte[] out2 = Hex.decode("358f84d01eb42988dc34efb994"); + static byte[] out3 = Hex.decode("170171cfad3f04530c509b0c1f0be0aefbd45a8e3755a873bff5ea198504b71683c6"); + private void testCTS( - int id, - int type, - BlockCipher cipher, - CipherParameters params, - byte[] input, - byte[] output) + int id, + int type, + BlockCipher cipher, + CipherParameters params, + byte[] input, + byte[] output) throws Exception { - byte[] out = new byte[input.length]; - BufferedBlockCipher engine = new NISTCTSBlockCipher(type, cipher); + byte[] out = new byte[input.length]; + BufferedBlockCipher engine = new NISTCTSBlockCipher(type, cipher); engine.init(true, params); @@ -77,63 +82,106 @@ private void testCTS( } } - private void testExceptions() throws InvalidCipherTextException + private void testExceptions() + throws InvalidCipherTextException { BufferedBlockCipher engine = new NISTCTSBlockCipher(NISTCTSBlockCipher.CS1, AESEngine.newInstance()); CipherParameters params = new KeyParameter(new byte[engine.getBlockSize()]); engine.init(true, params); byte[] out = new byte[engine.getOutputSize(engine.getBlockSize())]; - + engine.processBytes(new byte[engine.getBlockSize() - 1], 0, engine.getBlockSize() - 1, out, 0); - try + try { engine.doFinal(out, 0); fail("Expected CTS encrypt error on < 1 block input"); - } catch(DataLengthException e) + } + catch (DataLengthException e) { // Expected } engine.init(true, params); engine.processBytes(new byte[engine.getBlockSize()], 0, engine.getBlockSize(), out, 0); - try + try { engine.doFinal(out, 0); - } catch(DataLengthException e) + } + catch (DataLengthException e) { fail("Unexpected CTS encrypt error on == 1 block input"); } engine.init(false, params); engine.processBytes(new byte[engine.getBlockSize() - 1], 0, engine.getBlockSize() - 1, out, 0); - try + try { engine.doFinal(out, 0); fail("Expected CTS decrypt error on < 1 block input"); - } catch(DataLengthException e) + } + catch (DataLengthException e) { // Expected } engine.init(false, params); engine.processBytes(new byte[engine.getBlockSize()], 0, engine.getBlockSize(), out, 0); - try + try { engine.doFinal(out, 0); - } catch(DataLengthException e) + } + catch (DataLengthException e) { fail("Unexpected CTS decrypt error on == 1 block input"); } } + private void testOverlapping() + throws Exception + { + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[16]; + byte[] iv = new byte[16]; + random.nextBytes(keyBytes); + BufferedBlockCipher bc = new NISTCTSBlockCipher(NISTCTSBlockCipher.CS1, AESEngine.newInstance()); + ParametersWithIV param = new ParametersWithIV(new KeyParameter(keyBytes), iv); + + int offset = 1 + random.nextInt(bc.getBlockSize() - 1) + bc.getBlockSize(); + byte[] data = new byte[bc.getBlockSize() * 4 + offset]; + byte[] expected = new byte[bc.getOutputSize(bc.getBlockSize() * 3)]; + random.nextBytes(data); + + bc.init(true, param); + int len = bc.processBytes(data, 0, expected.length, expected, 0); + bc.doFinal(expected, len); + bc.init(true, param); + len = bc.processBytes(data, 0, expected.length, data, offset); + bc.doFinal(data, offset + len); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping encryption"); + } + + bc.init(false, param); + bc.processBytes(data, 0, expected.length, expected, 0); + bc.init(false, param); + bc.processBytes(data, 0, expected.length, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + expected.length))) + { + fail("failed for overlapping decryption"); + } + } + public String getName() { return "NISTCTS"; } - public void performTest() + public void performTest() throws Exception { testCTS(1, NISTCTSBlockCipher.CS1, AESEngine.newInstance(), new ParametersWithIV(key, iv), singleBlock, singleOut); @@ -149,7 +197,7 @@ public void performTest() testCTS(9, NISTCTSBlockCipher.CS3, AESEngine.newInstance(), new ParametersWithIV(key, iv), notQuiteTwo, cs3NotQuiteTwoBlockOut); byte[] aes128b = Hex.decode("aafd12f659cae63489b479e5076ddec2f06cb58faafd12f6"); - byte[] aesIn1b = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); + byte[] aesIn1b = Hex.decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); byte[] aesOut1b = Hex.decode("6db2f802d99e1ef0a5940f306079e083cf87f4d8bb9d1abb36cdd9f44ead7d04"); testCTS(10, NISTCTSBlockCipher.CS3, AESEngine.newInstance(), new ParametersWithIV(new KeyParameter(aes128b), Hex.decode("aafd12f659cae63489b479e5076ddec2")), aesIn1b, aesOut1b); @@ -160,10 +208,11 @@ public void performTest() testCTS(11, NISTCTSBlockCipher.CS3, AESEngine.newInstance(), new ParametersWithIV(new KeyParameter(aes128c), Hex.decode("aafd12f659cae63489b479e5076ddec2")), aesIn1b, aesOut1c); testExceptions(); + testOverlapping(); } public static void main( - String[] args) + String[] args) { runTest(new NISTCTSTest()); } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/OpenSSHKeyParsingTests.java b/core/src/test/java/org/bouncycastle/crypto/test/OpenSSHKeyParsingTests.java index 4de35bc6ee..40e4b26b4f 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/OpenSSHKeyParsingTests.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/OpenSSHKeyParsingTests.java @@ -294,7 +294,6 @@ public void testECDSA_curvesFromSSHKeyGen() doECSigTest(new ECPublicKeyParameters(q, privKey.getParameters()), privKey); } - for (int i = 0; i != pairs.length; i++) { String[] pair = pairs[i]; @@ -335,6 +334,14 @@ public void testECDSA_curvesFromSSHKeyGen() } + private void testFido2Keys() + { + // P-256 ECDSA Key + byte[] decode = Base64.decode("AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBPnfX2RzzEvD5CEX/0G3LLXrDWjrir9jZ2omSoxNyNT44cSiOP2v/WodnYpQdJsLIZn5bGNI0UxzxTuFzdizrWkAAAAEc3NoOg=="); + + CipherParameters xpubSpec = OpenSSHPublicKeyUtil.parsePublicKey(decode); + } + private void doECSigTest(CipherParameters pubSpec, CipherParameters privSpec) { ECDSASigner signer = new ECDSASigner(); @@ -470,6 +477,7 @@ public void performTest() testRSA(); testED25519(); testFailures(); + testFido2Keys(); } public void testRSA() diff --git a/core/src/test/java/org/bouncycastle/crypto/test/PKCS12Test.java b/core/src/test/java/org/bouncycastle/crypto/test/PKCS12Test.java index a5402aeae0..e158379013 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/PKCS12Test.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/PKCS12Test.java @@ -6,6 +6,7 @@ import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; @@ -22,26 +23,6 @@ public class PKCS12Test char[] password1 = { 's', 'm', 'e', 'g' }; char[] password2 = { 'q', 'u', 'e', 'e', 'g' }; - private boolean isEqual( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - private TestResult run1( int id, char[] password, @@ -59,7 +40,7 @@ private TestResult run1( CipherParameters key = generator.generateDerivedParameters(24 * 8); - if (isEqual(result, ((KeyParameter)key).getKey())) + if (Arrays.areEqual(result, ((KeyParameter)key).getKey())) { return new SimpleTestResult(true, "PKCS12Test: Okay"); } @@ -87,7 +68,7 @@ private TestResult run2( ParametersWithIV params = (ParametersWithIV)generator.generateDerivedParameters(64, 64); - if (isEqual(result, params.getIV())) + if (Arrays.areEqual(result, params.getIV())) { return new SimpleTestResult(true, "PKCS12Test: Okay"); } @@ -115,7 +96,7 @@ private TestResult run3( CipherParameters key = generator.generateDerivedMacParameters(160); - if (isEqual(result, ((KeyParameter)key).getKey())) + if (Arrays.areEqual(result, ((KeyParameter)key).getKey())) { return new SimpleTestResult(true, "PKCS12Test: Okay"); } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/PaddingTest.java b/core/src/test/java/org/bouncycastle/crypto/test/PaddingTest.java index c963b26e4f..3c6f6fd24f 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/PaddingTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/PaddingTest.java @@ -13,6 +13,7 @@ import org.bouncycastle.crypto.paddings.ZeroBytePadding; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; @@ -27,28 +28,28 @@ public PaddingTest() } private void blockCheck( - PaddedBufferedBlockCipher cipher, - BlockCipherPadding padding, - KeyParameter key, - byte[] data) + PaddedBufferedBlockCipher cipher, + BlockCipherPadding padding, + KeyParameter key, + byte[] data) { - byte[] out = new byte[data.length + 8]; - byte[] dec = new byte[data.length]; - + byte[] out = new byte[data.length + 8]; + byte[] dec = new byte[data.length]; + try - { + { cipher.init(true, key); - - int len = cipher.processBytes(data, 0, data.length, out, 0); - + + int len = cipher.processBytes(data, 0, data.length, out, 0); + len += cipher.doFinal(out, len); - + cipher.init(false, key); - - int decLen = cipher.processBytes(out, 0, len, dec, 0); - + + int decLen = cipher.processBytes(out, 0, len, dec, 0); + decLen += cipher.doFinal(dec, decLen); - + if (!areEqual(data, dec)) { fail("failed to decrypt - i = " + data.length + ", padding = " + padding.getPaddingName()); @@ -59,31 +60,31 @@ private void blockCheck( fail("Exception - " + e.toString(), e); } } - + public void testPadding( - BlockCipherPadding padding, - SecureRandom rand, - byte[] ffVector, - byte[] ZeroVector) + BlockCipherPadding padding, + SecureRandom rand, + byte[] ffVector, + byte[] ZeroVector) { - PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new DESEngine(), padding); - KeyParameter key = new KeyParameter(Hex.decode("0011223344556677")); - + PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new DESEngine(), padding); + KeyParameter key = new KeyParameter(Hex.decode("0011223344556677")); + // // ff test // - byte[] data = { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0 }; - + byte[] data = {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0}; + if (ffVector != null) { padding.addPadding(data, 3); - + if (!areEqual(data, ffVector)) { fail("failed ff test for " + padding.getPaddingName()); } } - + // // zero test // @@ -91,23 +92,23 @@ public void testPadding( { data = new byte[8]; padding.addPadding(data, 4); - + if (!areEqual(data, ZeroVector)) { fail("failed zero test for " + padding.getPaddingName()); } } - + for (int i = 1; i != 200; i++) { data = new byte[i]; - + rand.nextBytes(data); blockCheck(cipher, padding, key, data); } } - + private void testOutputSizes() { PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(new DESEngine(), new PKCS7Padding()); @@ -138,15 +139,51 @@ private void testOutputSizes() } } + private void testOverlapping() + { + //Skip the dofinal of the test + PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(new DESEngine(), new PKCS7Padding()); + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[8]; + random.nextBytes(keyBytes); + KeyParameter key = new KeyParameter(keyBytes); + + int offset = 2 + random.nextInt(bc.getBlockSize() - 1); + byte[] data = new byte[bc.getBlockSize() * 2 + offset]; + byte[] expected = new byte[bc.getOutputSize(bc.getBlockSize() * 2)]; + random.nextBytes(data); + + bc.init(true, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, expected, 0); + bc.init(true, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + bc.getBlockSize() * 2))) + { + fail("failed for overlapping encryption"); + } + + bc.init(false, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, expected, 0); + bc.init(false, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + bc.getBlockSize() * 2))) + { + fail("failed for overlapping decryption"); + } + } + public void performTest() { - SecureRandom rand = new SecureRandom(new byte[20]); - + testOverlapping(); + SecureRandom rand = new SecureRandom(new byte[20]); + rand.setSeed(System.currentTimeMillis()); - + testPadding(new PKCS7Padding(), rand, - Hex.decode("ffffff0505050505"), - Hex.decode("0000000004040404")); + Hex.decode("ffffff0505050505"), + Hex.decode("0000000004040404")); PKCS7Padding padder = new PKCS7Padding(); try @@ -161,27 +198,27 @@ public void performTest() { fail("wrong exception for corrupt padding: " + e); } - } + } testPadding(new ISO10126d2Padding(), rand, - null, - null); - + null, + null); + testPadding(new X923Padding(), rand, - null, - null); + null, + null); testPadding(new TBCPadding(), rand, - Hex.decode("ffffff0000000000"), - Hex.decode("00000000ffffffff")); + Hex.decode("ffffff0000000000"), + Hex.decode("00000000ffffffff")); testPadding(new ZeroBytePadding(), rand, - Hex.decode("ffffff0000000000"), - null); - + Hex.decode("ffffff0000000000"), + null); + testPadding(new ISO7816d4Padding(), rand, - Hex.decode("ffffff8000000000"), - Hex.decode("0000000080000000")); + Hex.decode("ffffff8000000000"), + Hex.decode("0000000080000000")); testOutputSizes(); @@ -193,7 +230,7 @@ public String getName() } public static void main( - String[] args) + String[] args) { runTest(new PaddingTest()); } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/ParallelHashTest.java b/core/src/test/java/org/bouncycastle/crypto/test/ParallelHashTest.java index 05080caf2d..5d825cf705 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/ParallelHashTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/ParallelHashTest.java @@ -1,5 +1,6 @@ package org.bouncycastle.crypto.test; + import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.ParallelHash; import org.bouncycastle.util.Arrays; @@ -23,6 +24,7 @@ public String getName() public void performTest() throws Exception { + testException(); ParallelHash pHash = new ParallelHash(128, new byte[0], 8); byte[] data = Hex.decode("00 01 02 03 04 05 06 07 10 11 12 13 14 15 16 17 20 21 22 23 24 25 26 27"); @@ -164,6 +166,19 @@ private void testClone() } } + private void testException() + { + testException("block size should be greater than 0", "IllegalArgumentException", new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + Digest digest = new ParallelHash(128, null, 0); + } + }); + } + public static void main( String[] args) { diff --git a/core/src/test/java/org/bouncycastle/crypto/test/PhotonBeetleTest.java b/core/src/test/java/org/bouncycastle/crypto/test/PhotonBeetleTest.java index c6c9b53f62..3e223b93c5 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/PhotonBeetleTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/PhotonBeetleTest.java @@ -9,6 +9,7 @@ import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.digests.PhotonBeetleDigest; import org.bouncycastle.crypto.engines.PhotonBeetleEngine; import org.bouncycastle.crypto.modes.AEADCipher; @@ -30,60 +31,29 @@ public String getName() public void performTest() throws Exception { - testVectorsHash(); + DigestTest.implTestVectorsDigest(this, new PhotonBeetleDigest(), "crypto/photonbeetle", "LWC_HASH_KAT_256.txt"); + DigestTest.checkDigestReset(this, new PhotonBeetleDigest()); + DigestTest.implTestExceptionsAndParametersDigest(this, new PhotonBeetleDigest(), 32); + CipherTest.checkAEADCipherMultipleBlocks(this, 1024, 19, 100, 128, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb128)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1024, 19, 100, 128, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb32)); + testVectors(PhotonBeetleEngine.PhotonBeetleParameters.pb32, "v32"); + testVectors(PhotonBeetleEngine.PhotonBeetleParameters.pb128, "v128"); + DigestTest.checkDigestReset(this, new PhotonBeetleDigest()); + PhotonBeetleEngine pb = new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb32); testExceptions(pb, pb.getKeyBytesSize(), pb.getIVBytesSize(), pb.getBlockSize()); testParameters(pb, 16, 16, 16); pb = new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb128); testExceptions(pb, pb.getKeyBytesSize(), pb.getIVBytesSize(), pb.getBlockSize()); testParameters(pb, 16, 16, 16); - testVectors(PhotonBeetleEngine.PhotonBeetleParameters.pb32, "v32"); - testVectors(PhotonBeetleEngine.PhotonBeetleParameters.pb128, "v128"); - testExceptions(new PhotonBeetleDigest(), 32); - } - private void testVectorsHash() - throws Exception - { - PhotonBeetleDigest PhotonBeetle = new PhotonBeetleDigest(); - CipherParameters params; - InputStream src = TestResourceFinder.findTestResource("crypto/photonbeetle", "LWC_HASH_KAT_256.txt"); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - String line; - byte[] ptByte, adByte; - byte[] rv; - HashMap map = new HashMap(); - while ((line = bin.readLine()) != null) - { - int a = line.indexOf('='); - if (a < 0) - { -// if (!map.get("Count").equals("3")) -// { -// continue; -// } - PhotonBeetle.reset(); - ptByte = Hex.decode((String)map.get("Msg")); - PhotonBeetle.update(ptByte, 0, ptByte.length); - byte[] hash = new byte[32]; - PhotonBeetle.doFinal(hash, 0); - if (!areEqual(hash, Hex.decode((String)map.get("MD")))) - { - mismatch("Keystream " + map.get("Count"), (String)map.get("MD"), hash); - } -// else -// { -// System.out.println("Keystream " + map.get("Count") + " pass"); -// } - map.clear(); - PhotonBeetle.reset(); - } - else - { - map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); - } - } - //System.out.print.println("PhotonBeetle Hash pass"); + testExceptions(new PhotonBeetleDigest(), 32); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb128)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb32)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb128)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb32)); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 16, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb128)); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 4, 16, new PhotonBeetleEngine(PhotonBeetleEngine.PhotonBeetleParameters.pb32)); } private void testVectors(PhotonBeetleEngine.PhotonBeetleParameters pbp, String filename) @@ -94,7 +64,6 @@ private void testVectors(PhotonBeetleEngine.PhotonBeetleParameters pbp, String f InputStream src = TestResourceFinder.findTestResource("crypto/photonbeetle", filename + "_LWC_AEAD_KAT_128_128.txt"); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line; - byte[] ptByte, adByte; byte[] rv; HashMap map = new HashMap(); while ((line = bin.readLine()) != null) @@ -102,9 +71,9 @@ private void testVectors(PhotonBeetleEngine.PhotonBeetleParameters pbp, String f int a = line.indexOf('='); if (a < 0) { -// if (!map.get("Count").equals("133")) +// if (map.get("Count").equals("298")) // { -// continue; +// System.out.println("test"); // } byte[] key = Hex.decode(map.get("Key")); byte[] nonce = Hex.decode(map.get("Nonce")); @@ -121,10 +90,6 @@ private void testVectors(PhotonBeetleEngine.PhotonBeetleParameters pbp, String f { mismatch("Keystream " + map.get("Count"), (String)map.get("CT"), rv); } -// else -// { -// System.out.println("Keystream " + map.get("Count") + " pass"); -// } PhotonBeetle.reset(); PhotonBeetle.init(false, params); //Decrypt @@ -139,6 +104,7 @@ private void testVectors(PhotonBeetleEngine.PhotonBeetleParameters pbp, String f mismatch("Reccover Keystream " + map.get("Count"), (String)map.get("PT"), pt_recovered); } PhotonBeetle.reset(); + //System.out.println(map.get("Count") + " pass"); map.clear(); } @@ -184,7 +150,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.reset(); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before reset"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -194,7 +160,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(c1, m.length); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before dofinal"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -247,6 +213,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } aeadBlockCipher.init(true, params); + c1 = new byte[aeadBlockCipher.getOutputSize(m.length)]; try { aeadBlockCipher.doFinal(c1, m.length); @@ -266,6 +233,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADByte((byte)0); byte[] mac1 = new byte[aeadBlockCipher.getOutputSize(0)]; aeadBlockCipher.doFinal(mac1, 0); @@ -306,6 +274,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } try { + aeadBlockCipher.init(true, params); aeadBlockCipher.processBytes(new byte[]{0}, 1, 1, c1, 0); fail(aeadBlockCipher.getAlgorithmName() + ": input for processBytes is too short"); } @@ -335,9 +304,11 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, mac1 = new byte[aeadBlockCipher.getOutputSize(0)]; mac2 = new byte[aeadBlockCipher.getOutputSize(0)]; aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(new byte[]{0, 0}, 0, 2); aeadBlockCipher.doFinal(mac1, 0); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADByte((byte)0); aeadBlockCipher.processAADByte((byte)0); aeadBlockCipher.doFinal(mac2, 0); @@ -355,10 +326,12 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, byte[] m3 = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; byte[] m4 = new byte[m2.length]; aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); int offset = aeadBlockCipher.processBytes(m2, 0, m2.length, c2, 0); aeadBlockCipher.doFinal(c2, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad3, 1, aad2.length); offset = aeadBlockCipher.processBytes(m3, 1, m2.length, c3, 1); aeadBlockCipher.doFinal(c3, offset + 1); @@ -388,7 +361,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(m4, offset); fail(aeadBlockCipher.getAlgorithmName() + ": The decryption should fail"); } - catch (IllegalArgumentException e) + catch (InvalidCipherTextException e) { //expected; } @@ -398,20 +371,22 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, { m7[i] = (byte)rand.nextInt(); } + aeadBlockCipher.init(true, params); byte[] c7 = new byte[aeadBlockCipher.getOutputSize(m7.length)]; byte[] c8 = new byte[c7.length]; byte[] c9 = new byte[c7.length]; - aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, m7.length, c7, 0); aeadBlockCipher.doFinal(c7, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, blocksize, c8, 0); offset += aeadBlockCipher.processBytes(m7, blocksize, m7.length - blocksize, c8, offset); aeadBlockCipher.doFinal(c8, offset); aeadBlockCipher.reset(); - int split = rand.nextInt(blocksize * 2); + aeadBlockCipher.init(true, params); + int split = 7;//rand.nextInt(blocksize * 2); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, split, c9, 0); offset += aeadBlockCipher.processBytes(m7, split, m7.length - split, c9, offset); diff --git a/core/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java b/core/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java index c945e3154a..ea18403483 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java @@ -195,6 +195,9 @@ public class RegressionTest new SparkleTest(), new ISAPTest(), new ConcatenationKDFTest(), + new GiftCofbTest(), + new RomulusTest(), + new SAKKEKEMSTest(), }; public static void main(String[] args) diff --git a/core/src/test/java/org/bouncycastle/crypto/test/RomulusTest.java b/core/src/test/java/org/bouncycastle/crypto/test/RomulusTest.java new file mode 100644 index 0000000000..4b0bf9c3e8 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/test/RomulusTest.java @@ -0,0 +1,163 @@ +package org.bouncycastle.crypto.test; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.digests.RomulusDigest; +import org.bouncycastle.crypto.engines.RomulusEngine; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.test.SimpleTest; + +public class RomulusTest + extends SimpleTest +{ + public String getName() + { + return "Romulus"; + } + + public void performTest() + throws Exception + { + DigestTest.implTestVectorsDigest(this, new RomulusDigest(), "crypto/romulus", "LWC_HASH_KAT_256.txt"); + DigestTest.checkDigestReset(this, new RomulusDigest()); + DigestTest.implTestExceptionsAndParametersDigest(this, new RomulusDigest(), 32); + + CipherTest.implTestVectorsEngine(new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM), "crypto/romulus", "m_LWC_AEAD_KAT_128_128.txt", this); + CipherTest.implTestVectorsEngine(new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT), "crypto/romulus", "t_LWC_AEAD_KAT_128_128.txt", this); + CipherTest.implTestVectorsEngine(new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN), "crypto/romulus", "n_LWC_AEAD_KAT_128_128.txt", this); + + //TODO: StreamDataOperator does not suit for implTestBufferingEngine +// CipherTest.implTestBufferingEngine(16, 16, 128, this, new CipherTest.Instance() +// { +// @Override +// public AEADCipher createInstance() +// { +// return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM); +// } +// }); + CipherTest.implTestBufferingEngine(16, 16, 128, this, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT); + } + }); + CipherTest.implTestBufferingEngine(16, 16, 128, this, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN); + } + }); + //TODO: StreamDataOperator does not suit for implTestExceptionsEngine +// CipherTest.implTestExceptionsEngine(16, 16, this, new CipherTest.Instance() +// { +// @Override +// public AEADCipher createInstance() +// { +// return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM); +// } +// }); + CipherTest.implTestExceptionsEngine(16, 16, this, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT); + } + }); + CipherTest.implTestExceptionsEngine(16, 16, this, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN); + } + }); + implTestParametersEngine(new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM), 16, 16, 16); + implTestParametersEngine(new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT), 16, 16, 16); + implTestParametersEngine(new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN), 16, 16, 16); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT)); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT)); + CipherTest.testOverlapping(this, 16, 16, 16, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN)); + + CipherTest.checkCipher(16, 16, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM); + } + }); + CipherTest.checkCipher(16, 16, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT); + } + }); + + CipherTest.checkCipher(16, 16, 40, 128, new CipherTest.Instance() + { + public AEADCipher createInstance() + { + return new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN); + } + }); + +// RomulusEngine romulus = new RomulusEngine(RomulusEngine.RomulusParameters.RomulusT); +// testExceptions(romulus, romulus.getKeyBytesSize(), romulus.getIVBytesSize(), romulus.getBlockSize()); +// romulus = new RomulusEngine(RomulusEngine.RomulusParameters.RomulusM); +// testExceptions(romulus, romulus.getKeyBytesSize(), romulus.getIVBytesSize(), romulus.getBlockSize()); +// romulus = new RomulusEngine(RomulusEngine.RomulusParameters.RomulusN); +// testExceptions(romulus, romulus.getKeyBytesSize(), romulus.getIVBytesSize(), romulus.getBlockSize()); +// testExceptions(new RomulusDigest(), 32); +// //testVectorsHash(); +// testVectors(RomulusEngine.RomulusParameters.RomulusT, "t"); +// testVectors(RomulusEngine.RomulusParameters.RomulusM, "m"); +// testVectors(RomulusEngine.RomulusParameters.RomulusN, "n"); + } + + private void implTestParametersEngine(RomulusEngine cipher, int keySize, int ivSize, + int macSize) + { + if (cipher.getKeyBytesSize() != keySize) + { + fail("key bytes of " + cipher.getAlgorithmName() + " is not correct"); + } + if (cipher.getIVBytesSize() != ivSize) + { + fail("iv bytes of " + cipher.getAlgorithmName() + " is not correct"); + } + + CipherParameters parameters = new ParametersWithIV(new KeyParameter(new byte[keySize]), new byte[ivSize]); + + cipher.init(true, parameters); + if (cipher.getOutputSize(0) != macSize) + { + fail("getOutputSize of " + cipher.getAlgorithmName() + " is incorrect for encryption"); + } + + cipher.init(false, parameters); + if (cipher.getOutputSize(macSize) != 0) + { + fail("getOutputSize of " + cipher.getAlgorithmName() + " is incorrect for decryption"); + } + } + + public static void main(String[] args) + { + runTest(new RomulusTest()); + } +} + + + diff --git a/core/src/test/java/org/bouncycastle/crypto/test/SAKKEKEMSTest.java b/core/src/test/java/org/bouncycastle/crypto/test/SAKKEKEMSTest.java new file mode 100644 index 0000000000..d21555274d --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/test/SAKKEKEMSTest.java @@ -0,0 +1,175 @@ +package org.bouncycastle.crypto.test; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.crypto.kems.SAKKEKEMExtractor; +import org.bouncycastle.crypto.kems.SAKKEKEMSGenerator; +import org.bouncycastle.crypto.params.SAKKEPrivateKeyParameters; +import org.bouncycastle.crypto.params.SAKKEPublicKeyParameters; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; +import org.bouncycastle.util.test.SimpleTest; + +public class SAKKEKEMSTest + extends SimpleTest +{ + public static void main(String[] args) + throws Exception + { + SAKKEKEMSTest test = new SAKKEKEMSTest(); + test.performTest(); + } + + + @Override + public String getName() + { + return "SAKKE-KEMS Test"; + } + + @Override + public void performTest() + throws Exception + { + testTestVector(); + for (int i = 0; i < 1; ++i) + { + testRandom(); + } + } + + private void testTestVector() + { + final BigInteger Px = new BigInteger( + "53FC09EE332C29AD0A7990053ED9B52A2B1A2FD60AEC69C698B2F204B6FF7CBF" + + "B5EDB6C0F6CE2308AB10DB9030B09E1043D5F22CDB9DFA55718BD9E7406CE890" + + "9760AF765DD5BCCB337C86548B72F2E1A702C3397A60DE74A7C1514DBA66910D" + + "D5CFB4CC80728D87EE9163A5B63F73EC80EC46C4967E0979880DC8ABEAE63895", 16 + ); + + final BigInteger Py = new BigInteger( + "0A8249063F6009F1F9F1F0533634A135D3E82016029906963D778D821E141178" + + "F5EA69F4654EC2B9E7F7F5E5F0DE55F66B598CCF9A140B2E416CFF0CA9E032B9" + + "70DAE117AD547C6CCAD696B5B7652FE0AC6F1E80164AA989492D979FC5A4D5F2" + + "13515AD7E9CB99A980BDAD5AD5BB4636ADB9B5706A67DCDE75573FD71BEF16D7", 16 + ); + BigInteger g = new BigInteger(Hex.decode("66FC2A43 2B6EA392 148F1586 7D623068" + + " C6A87BD1 FB94C41E 27FABE65 8E015A87" + + " 371E9474 4C96FEDA 449AE956 3F8BC446" + + " CBFDA85D 5D00EF57 7072DA8F 541721BE" + + " EE0FAED1 828EAB90 B99DFB01 38C78433" + + " 55DF0460 B4A9FD74 B4F1A32B CAFA1FFA" + + " D682C033 A7942BCC E3720F20 B9B7B040" + + " 3C8CAE87 B7A0042A CDE0FAB3 6461EA46")); + BigInteger z = new BigInteger("AFF429D35F84B110D094803B3595A6E2998BC99F", 16); + BigInteger Zx = new BigInteger(Hex.decode("5958EF1B1679BF099B3A030DF255AA6A23C1D8F143D4D23F753E69BD27A832F38CB4AD53DDEF" + + "4260B0FE8BB45C4C1FF510EFFE300367A37B61F701D914AEF09724825FA0707D61A6DFF4FBD7273566CDDE352A0B04B7C16A78309BE" + + "640697DE747613A5FC195E8B9F328852A579DB8F99B1D0034479EA9C5595F47C4B2F54FF2")); + BigInteger Zy = new BigInteger(Hex.decode("1508D37514DCF7A8E143A6058C09A6BF2C9858CA37C258065AE6BF7532BC8B5B63383866E075" + + "3C5AC0E72709F8445F2E6178E065857E0EDA10F68206B63505ED87E534FB2831FF957FB7DC619DAE61301EEACC2FDA3680EA499925" + + "8A833CEA8FC67C6D19487FB449059F26CC8AAB655AB58B7CC796E24E9A394095754F5F8BAE")); + BigInteger q = new BigInteger(Hex.decode("265EAEC7 C2958FF6 99718466 36B4195E" + + " 905B0338 672D2098 6FA6B8D6 2CF8068B" + + " BD02AAC9 F8BF03C6 C8A1CC35 4C69672C" + + " 39E46CE7 FDF22286 4D5B49FD 2999A9B4" + + " 389B1921 CC9AD335 144AB173 595A0738" + + " 6DABFD2A 0C614AA0 A9F3CF14 870F026A" + + " A7E535AB D5A5C7C7 FF38FA08 E2615F6C" + + " 203177C4 2B1EB3A1 D99B601E BFAA17FB")); +// + byte[] b = Hex.decode("323031312D30320074656C3A2B34343737303039303031323300"); + + byte[] ssv = Hex.decode("123456789ABCDEF0123456789ABCDEF0"); + byte[] expectedR = Hex.decode("13EE3E1B8DAC5DB168B1CEB32F0566A4C273693F78BAFFA2A2EE6A686E6BD90F8206CCAB84E7F" + + "42ED39BD4FB131012ECCA2ECD2119414560C17CAB46B956A80F58A3302EB3E2C9A228FBA7ED34D8ACA2392DA1FFB0B17B2320AE09AAEDF" + + "D0235F6FE0EB65337A63F9CC97728B8E5AD0460FADE144369AA5B2166213247712096"); + + BigInteger kbx = new BigInteger("93AF67E5007BA6E6A80DA793DA300FA4" + + "B52D0A74E25E6E7B2B3D6EE9D18A9B5C" + + "5023597BD82D8062D34019563BA1D25C" + + "0DC56B7B979D74AA50F29FBF11CC2C93" + + "F5DFCA615E609279F6175CEADB00B58C" + + "6BEE1E7A2A47C4F0C456F05259A6FA94" + + "A634A40DAE1DF593D4FECF688D5FC678" + + "BE7EFC6DF3D6835325B83B2C6E69036B", 16); + + BigInteger kby = new BigInteger("155F0A27241094B04BFB0BDFAC6C670A" + + "65C325D39A069F03659D44CA27D3BE8D" + + "F311172B554160181CBE94A2A783320C" + + "ED590BC42644702CF371271E496BF20F" + + "588B78A1BC01ECBB6559934BDD2FB65D" + + "2884318A33D1A42ADF5E33CC5800280B" + + "28356497F87135BAB9612A1726042440" + + "9AC15FEE996B744C332151235DECB0F5", 16); +// BigInteger w = new BigInteger(Hex.decode("7D2A8438 E6291C64 9B6579EB 3B79EAE9" + +// "48B1DE9E 5F7D1F40 70A08F8D B6B3C515" + +// "6F2201AF FBB5CB9D 82AA3EC0 D0398B89" + +// "ABC78A13 A760C0BF 3F77E63D 0DF3F1A3" + +// "41A41B88 11DF197F D6CD0F00 3125606F" + +// "4F109F40 0F7292A1 0D255E3C 0EBCCB42" + +// "53FB182C 68F09CF6 CD9C4A53 DA6C74AD" + +// "007AF36B 8BCA979D 5895E282 F483FCD6")); +// BigInteger Rbx = new BigInteger(Hex.decode("44E8AD44 AB8592A6 A5A3DDCA 5CF896C7" + +// "18043606 A01D650D EF37A01F 37C228C3" + +// "32FC3173 54E2C274 D4DAF8AD 001054C7" + +// "6CE57971 C6F4486D 57230432 61C506EB" + +// "F5BE438F 53DE04F0 67C776E0 DD3B71A6" + +// "29013328 3725A532 F21AF145 126DC1D7" + +// "77ECC27B E50835BD 28098B8A 73D9F801" + +// "D893793A 41FF5C49 B87E79F2 BE4D56CE")); +// BigInteger Rby = new BigInteger(Hex.decode("557E134A D85BB1D4 B9CE4F8B E4B08A12" + +// "BABF55B1 D6F1D7A6 38019EA2 8E15AB1C" + +// "9F76375F DD1210D4 F4351B9A 009486B7" + +// "F3ED46C9 65DED2D8 0DADE4F3 8C6721D5" + +// "2C3AD103 A10EBD29 59248B4E F006836B" + +// "F097448E 6107C9ED EE9FB704 823DF199" + +// "F832C905 AE45F8A2 47A072D8 EF729EAB" + +// "C5E27574 B07739B3 4BE74A53 2F747B86")); + BigInteger p = new BigInteger( + "997ABB1F0A563FDA65C61198DAD0657A416C0CE19CB48261BE9AE358B3E01A2E" + + "F40AAB27E2FC0F1B228730D531A59CB0E791B39FF7C88A19356D27F4A666A6D0" + + "E26C6487326B4CD4512AC5CD65681CE1B6AFF4A831852A82A7CF3C521C3C09AA" + + "9F94D6AF56971F1FFCE3E82389857DB080C5DF10AC7ACE87666D807AFEA85FEB", 16 + ); + ECCurve.Fp curve = new ECCurve.Fp( + p, // Prime p + BigInteger.valueOf(-3).mod(p), // a = -3 + BigInteger.ZERO, // , + g,// Order of the subgroup (from RFC 6509) + BigInteger.ONE // Cofactor = 1 + ); + ECPoint P = curve.createPoint(Px, Py); + + ECPoint computed_Z = P.multiply(z).normalize(); + isTrue(computed_Z.equals(curve.createPoint(Zx, Zy))); + + SecureRandom random = new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(ssv)}); + SAKKEPublicKeyParameters b_publicKey = new SAKKEPublicKeyParameters(new BigInteger(b), curve.createPoint(Zx, Zy)); + SAKKEKEMSGenerator generator = new SAKKEKEMSGenerator(random); + SecretWithEncapsulation rlt = generator.generateEncapsulated(b_publicKey); + + + SAKKEKEMExtractor extractor = new SAKKEKEMExtractor(new SAKKEPrivateKeyParameters(z, b_publicKey)); + byte[] test = extractor.extractSecret(rlt.getEncapsulation()); + isTrue(Arrays.areEqual(test, ssv)); + } + + private void testRandom() + { + SecureRandom random = new SecureRandom(); + byte[] ssv = new byte[16]; + random.nextBytes(ssv); + SAKKEPrivateKeyParameters b_priv = new SAKKEPrivateKeyParameters(random); + SAKKEPublicKeyParameters b_pub = b_priv.getPublicParams(); + SAKKEKEMSGenerator generator = new SAKKEKEMSGenerator(new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(ssv)})); + SecretWithEncapsulation rlt = generator.generateEncapsulated(b_pub); + SAKKEKEMExtractor extractor = new SAKKEKEMExtractor(b_priv); + byte[] test = extractor.extractSecret(rlt.getEncapsulation()); + isTrue(Arrays.areEqual(test, ssv)); + } +} diff --git a/core/src/test/java/org/bouncycastle/crypto/test/SimpleTestTest.java b/core/src/test/java/org/bouncycastle/crypto/test/SimpleTestTest.java index 701b2a0797..cc5a3074d1 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/SimpleTestTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/SimpleTestTest.java @@ -20,9 +20,15 @@ public void testCrypto() { result.getException().printStackTrace(); } - fail(i+" -> "+ result.toString()); + fail(i + " -> " + result.toString()); } } } + + public static void main(String[] args) + { + SimpleTestTest test = new SimpleTestTest(); + test.testCrypto(); + } } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/SparkleTest.java b/core/src/test/java/org/bouncycastle/crypto/test/SparkleTest.java index 76ead9d8fe..ab76af8a2a 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/SparkleTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/SparkleTest.java @@ -36,14 +36,19 @@ public String getName() public void performTest() throws Exception { + testVectorsEngine_SCHWAEMM128_128(); + testVectorsEngine_SCHWAEMM192_192(); + testVectorsEngine_SCHWAEMM256_128(); + testVectorsEngine_SCHWAEMM256_256(); + testBufferingEngine_SCHWAEMM128_128(); testBufferingEngine_SCHWAEMM192_192(); testBufferingEngine_SCHWAEMM256_128(); testBufferingEngine_SCHWAEMM256_256(); testExceptionsDigest_ESCH256(); - testExceptionsDigest_ESCH384();; - + testExceptionsDigest_ESCH384(); + ; testExceptionsEngine_SCHWAEMM128_128(); testExceptionsEngine_SCHWAEMM192_192(); testExceptionsEngine_SCHWAEMM256_128(); @@ -60,118 +65,150 @@ public void performTest() testVectorsDigest_ESCH256(); testVectorsDigest_ESCH384(); - testVectorsEngine_SCHWAEMM128_128(); - testVectorsEngine_SCHWAEMM192_192(); - testVectorsEngine_SCHWAEMM256_128(); - testVectorsEngine_SCHWAEMM256_256(); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 16, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128)); + CipherTest.checkAEADParemeter(this, 24, 24, 24, 24, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192)); + CipherTest.checkAEADParemeter(this, 16, 32, 16, 16, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128)); + CipherTest.checkAEADParemeter(this, 32, 32, 32, 32, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256)); + + CipherTest.testOverlapping(this, 16, 16, 16, 16, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128)); + CipherTest.testOverlapping(this, 24, 24, 24, 24, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192)); + CipherTest.testOverlapping(this, 16, 32, 16, 16, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128)); + CipherTest.testOverlapping(this, 32, 32, 32, 32, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256)); + + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 16, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 24, 192, 24, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 16, 128, 32, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128)); + CipherTest.checkAEADCipherMultipleBlocks(this, 1025, 33, 32, 256, 32, new SparkleEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256)); } - public void testBufferingEngine_SCHWAEMM128_128() throws Exception + public void testBufferingEngine_SCHWAEMM128_128() + throws Exception { implTestBufferingEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128); } - public void testBufferingEngine_SCHWAEMM192_192() throws Exception + public void testBufferingEngine_SCHWAEMM192_192() + throws Exception { implTestBufferingEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192); } - public void testBufferingEngine_SCHWAEMM256_128() throws Exception + public void testBufferingEngine_SCHWAEMM256_128() + throws Exception { implTestBufferingEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128); } - public void testBufferingEngine_SCHWAEMM256_256() throws Exception + public void testBufferingEngine_SCHWAEMM256_256() + throws Exception { implTestBufferingEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256); } - public void testExceptionsDigest_ESCH256() throws Exception + public void testExceptionsDigest_ESCH256() + throws Exception { implTestExceptionsDigest(SparkleDigest.SparkleParameters.ESCH256); } - public void testExceptionsDigest_ESCH384() throws Exception + public void testExceptionsDigest_ESCH384() + throws Exception { implTestExceptionsDigest(SparkleDigest.SparkleParameters.ESCH384); } - public void testExceptionsEngine_SCHWAEMM128_128() throws Exception + public void testExceptionsEngine_SCHWAEMM128_128() + throws Exception { implTestExceptionsEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128); } - public void testExceptionsEngine_SCHWAEMM192_192() throws Exception + public void testExceptionsEngine_SCHWAEMM192_192() + throws Exception { implTestExceptionsEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192); } - public void testExceptionsEngine_SCHWAEMM256_128() throws Exception + public void testExceptionsEngine_SCHWAEMM256_128() + throws Exception { implTestExceptionsEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128); } - public void testExceptionsEngine_SCHWAEMM256_256() throws Exception + public void testExceptionsEngine_SCHWAEMM256_256() + throws Exception { implTestExceptionsEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256); } - public void testParametersDigest_ESCH256() throws Exception + public void testParametersDigest_ESCH256() + throws Exception { implTestParametersDigest(SparkleDigest.SparkleParameters.ESCH256, 32); } - public void testParametersDigest_ESCH384() throws Exception + public void testParametersDigest_ESCH384() + throws Exception { implTestParametersDigest(SparkleDigest.SparkleParameters.ESCH384, 48); } - public void testParametersEngine_SCHWAEMM128_128() throws Exception + public void testParametersEngine_SCHWAEMM128_128() + throws Exception { implTestParametersEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128, 16, 16, 16); } - public void testParametersEngine_SCHWAEMM192_192() throws Exception + public void testParametersEngine_SCHWAEMM192_192() + throws Exception { implTestParametersEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192, 24, 24, 24); } - public void testParametersEngine_SCHWAEMM256_128() throws Exception + public void testParametersEngine_SCHWAEMM256_128() + throws Exception { implTestParametersEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128, 16, 32, 16); } - public void testParametersEngine_SCHWAEMM256_256() throws Exception + public void testParametersEngine_SCHWAEMM256_256() + throws Exception { implTestParametersEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256, 32, 32, 32); } - public void testVectorsDigest_ESCH256() throws Exception + public void testVectorsDigest_ESCH256() + throws Exception { implTestVectorsDigest(SparkleDigest.SparkleParameters.ESCH256, "256"); } - public void testVectorsDigest_ESCH384() throws Exception + public void testVectorsDigest_ESCH384() + throws Exception { implTestVectorsDigest(SparkleDigest.SparkleParameters.ESCH384, "384"); } - public void testVectorsEngine_SCHWAEMM128_128() throws Exception + public void testVectorsEngine_SCHWAEMM128_128() + throws Exception { implTestVectorsEngine(SparkleEngine.SparkleParameters.SCHWAEMM128_128, "128_128"); } - public void testVectorsEngine_SCHWAEMM192_192() throws Exception + public void testVectorsEngine_SCHWAEMM192_192() + throws Exception { implTestVectorsEngine(SparkleEngine.SparkleParameters.SCHWAEMM192_192, "192_192"); } - public void testVectorsEngine_SCHWAEMM256_128() throws Exception + public void testVectorsEngine_SCHWAEMM256_128() + throws Exception { implTestVectorsEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_128, "128_256"); } - public void testVectorsEngine_SCHWAEMM256_256() throws Exception + public void testVectorsEngine_SCHWAEMM256_256() + throws Exception { implTestVectorsEngine(SparkleEngine.SparkleParameters.SCHWAEMM256_256, "256_256"); } @@ -347,7 +384,10 @@ private void implTestVectorsEngine(SparkleEngine.SparkleParameters pbp, String f byte[] ad = Hex.decode(map.get("AD")); byte[] pt = Hex.decode(map.get("PT")); byte[] ct = Hex.decode(map.get("CT")); - +// if (!map.get("Count").equals("17")) +// { +// continue; +// } CipherParameters parameters = new ParametersWithIV(new KeyParameter(key), nonce); // Encrypt @@ -383,7 +423,7 @@ private void implTestVectorsEngine(SparkleEngine.SparkleParameters pbp, String f mismatch("Reccover Keystream " + map.get("Count"), (String)map.get("PT"), rv); } } - + //System.out.println(map.get("Count") + " pass"); map.clear(); } else @@ -519,7 +559,7 @@ private void implTestExceptionsEngine(SparkleEngine.SparkleParameters sparklePar fail("mac should not match"); } sparkle.init(true, params); - sparkle.processByte((byte)0, null, 0); + sparkle.processByte((byte)0, new byte[1], 0); try { sparkle.processAADByte((byte)0); @@ -671,7 +711,7 @@ private void implTestExceptionsEngine(SparkleEngine.SparkleParameters sparklePar } private void implTestExceptionsGetUpdateOutputSize(SparkleEngine sparkle, boolean forEncryption, - CipherParameters parameters, int maxInputSize) + CipherParameters parameters, int maxInputSize) { sparkle.init(forEncryption, parameters); @@ -715,7 +755,7 @@ private void implTestParametersDigest(SparkleDigest.SparkleParameters sparklePar } private void implTestParametersEngine(SparkleEngine.SparkleParameters sparkleParameters, int keySize, int ivSize, - int macSize) + int macSize) { SparkleEngine sparkle = createEngine(sparkleParameters); diff --git a/core/src/test/java/org/bouncycastle/crypto/test/XoodyakTest.java b/core/src/test/java/org/bouncycastle/crypto/test/XoodyakTest.java index 268f417830..37bb098399 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/XoodyakTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/XoodyakTest.java @@ -9,6 +9,7 @@ import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.digests.XoodyakDigest; import org.bouncycastle.crypto.engines.XoodyakEngine; @@ -32,53 +33,27 @@ public String getName() public void performTest() throws Exception { - testVectorsHash(); + DigestTest.implTestVectorsDigest(this, new XoodyakDigest(), "crypto/xoodyak", "LWC_HASH_KAT_256.txt"); + DigestTest.checkDigestReset(this, new XoodyakDigest()); + DigestTest.implTestExceptionsAndParametersDigest(this, new XoodyakDigest(), 32); + CipherTest.checkAEADCipherMultipleBlocks(this, 1024, 18, 100, 128, 16, new XoodyakEngine()); testVectors(); + CipherTest.checkCipher(32, 16, 100, 128, new CipherTest.Instance() + { + @Override + public AEADCipher createInstance() + { + return new XoodyakEngine(); + } + }); + XoodyakEngine xoodyak = new XoodyakEngine(); testExceptions(xoodyak, xoodyak.getKeyBytesSize(), xoodyak.getIVBytesSize(), xoodyak.getBlockSize()); testParameters(xoodyak, 16, 16, 16); testExceptions(new XoodyakDigest(), 32); - } - - private void testVectorsHash() - throws Exception - { - XoodyakDigest xoodyak = new XoodyakDigest(); - InputStream src = TestResourceFinder.findTestResource("crypto/xoodyak", "LWC_HASH_KAT_256.txt"); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - String line; - byte[] ptByte; - HashMap map = new HashMap(); - while ((line = bin.readLine()) != null) - { - int a = line.indexOf('='); - if (a < 0) - { -// if (!map.get("Count").equals("18")) -// { -// continue; -// } - xoodyak.reset(); - ptByte = Hex.decode((String)map.get("Msg")); - xoodyak.update(ptByte, 0, ptByte.length); - byte[] hash = new byte[32]; - xoodyak.doFinal(hash, 0); - if (!areEqual(hash, Hex.decode((String)map.get("MD")))) - { - mismatch("Keystream " + map.get("Count"), (String)map.get("MD"), hash); - } -// else -// { -// System.out.println("Keystream " + map.get("Count") + " pass"); -// } - map.clear(); - } - else - { - map.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); - } - } -// System.out.println("Xoodyak Hash pass"); + CipherTest.checkAEADCipherOutputSize(this, 16, 16, 24, 16, new XoodyakEngine()); + CipherTest.checkAEADParemeter(this, 16, 16, 16, 24, new XoodyakEngine()); + CipherTest.testOverlapping(this, 16, 16, 16, 24, new XoodyakEngine()); } private void testVectors() @@ -96,8 +71,7 @@ private void testVectors() int a = line.indexOf('='); if (a < 0) { -// if (!map.get("Count").equals("826")) -// { +// if(!map.get("Count").equals("793")){ // continue; // } byte[] key = Hex.decode(map.get("Key")); @@ -115,10 +89,6 @@ private void testVectors() { mismatch("Keystream " + map.get("Count"), (String)map.get("CT"), rv); } -// else -// { -// System.out.println("Keystream " + map.get("Count") + " pass"); -// } xoodyak.reset(); xoodyak.init(false, params); //Decrypt @@ -133,6 +103,7 @@ private void testVectors() mismatch("Reccover Keystream " + map.get("Count"), (String)map.get("PT"), pt_recovered); } xoodyak.reset(); + //System.out.println(map.get("Count") +" pass"); map.clear(); } else @@ -157,7 +128,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.processBytes(m, 0, m.length, c1, 0); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before processBytes"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -167,7 +138,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.processByte((byte)0, c1, 0); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before processByte"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -177,7 +148,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.reset(); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before reset"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -187,7 +158,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(c1, m.length); fail(aeadBlockCipher.getAlgorithmName() + " need to be initialed before dofinal"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -240,6 +211,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } aeadBlockCipher.init(true, params); + c1 = new byte[aeadBlockCipher.getOutputSize(m.length)]; try { aeadBlockCipher.doFinal(c1, m.length); @@ -259,6 +231,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADByte((byte)0); byte[] mac1 = new byte[aeadBlockCipher.getOutputSize(0)]; aeadBlockCipher.doFinal(mac1, 0); @@ -267,13 +240,14 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, fail(aeadBlockCipher.getAlgorithmName() + ": mac should not match"); } aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processBytes(new byte[blocksize], 0, blocksize, new byte[blocksize], 0); try { aeadBlockCipher.processAADByte((byte)0); fail(aeadBlockCipher.getAlgorithmName() + ": processAADByte(s) cannot be called after encryption/decryption"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } @@ -282,12 +256,13 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.processAADBytes(new byte[]{0}, 0, 1); fail(aeadBlockCipher.getAlgorithmName() + ": processAADByte(s) cannot be called once only"); } - catch (IllegalArgumentException e) + catch (IllegalStateException e) { //expected } aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); try { aeadBlockCipher.processAADBytes(new byte[]{0}, 1, 1); @@ -308,7 +283,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, } try { - aeadBlockCipher.processBytes(new byte[blocksize], 0, blocksize, new byte[blocksize], blocksize >> 1); + aeadBlockCipher.processBytes(new byte[blocksize + 1], 0, blocksize + 1, new byte[blocksize], blocksize >> 1); fail(aeadBlockCipher.getAlgorithmName() + ": output for processBytes is too short"); } catch (OutputLengthException e) @@ -328,9 +303,11 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, mac1 = new byte[aeadBlockCipher.getOutputSize(0)]; mac2 = new byte[aeadBlockCipher.getOutputSize(0)]; aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(new byte[]{0, 0}, 0, 2); aeadBlockCipher.doFinal(mac1, 0); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADByte((byte)0); aeadBlockCipher.processAADByte((byte)0); aeadBlockCipher.doFinal(mac2, 0); @@ -348,10 +325,12 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, byte[] m3 = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; byte[] m4 = new byte[m2.length]; aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); int offset = aeadBlockCipher.processBytes(m2, 0, m2.length, c2, 0); aeadBlockCipher.doFinal(c2, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad3, 1, aad2.length); offset = aeadBlockCipher.processBytes(m3, 1, m2.length, c3, 1); aeadBlockCipher.doFinal(c3, offset + 1); @@ -381,7 +360,7 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, aeadBlockCipher.doFinal(m4, offset); fail(aeadBlockCipher.getAlgorithmName() + ": The decryption should fail"); } - catch (IllegalArgumentException e) + catch (InvalidCipherTextException e) { //expected; } @@ -391,19 +370,22 @@ private void testExceptions(AEADCipher aeadBlockCipher, int keysize, int ivsize, { m7[i] = (byte)rand.nextInt(); } + + aeadBlockCipher.init(true, params); byte[] c7 = new byte[aeadBlockCipher.getOutputSize(m7.length)]; byte[] c8 = new byte[c7.length]; byte[] c9 = new byte[c7.length]; - aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, m7.length, c7, 0); aeadBlockCipher.doFinal(c7, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, blocksize, c8, 0); offset += aeadBlockCipher.processBytes(m7, blocksize, m7.length - blocksize, c8, offset); aeadBlockCipher.doFinal(c8, offset); aeadBlockCipher.reset(); + aeadBlockCipher.init(true, params); int split = rand.nextInt(blocksize * 2); aeadBlockCipher.processAADBytes(aad2, 0, aad2.length); offset = aeadBlockCipher.processBytes(m7, 0, split, c9, 0); diff --git a/core/src/test/java/org/bouncycastle/crypto/threshold/test/AllTests.java b/core/src/test/java/org/bouncycastle/crypto/threshold/test/AllTests.java new file mode 100644 index 0000000000..d1adc46477 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/threshold/test/AllTests.java @@ -0,0 +1,42 @@ +package org.bouncycastle.crypto.threshold.test; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.test.PrintTestResult; + +public class AllTests + extends TestCase +{ + public static void main(String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("Secret Sharing Tests"); + suite.addTestSuite(ShamirSecretSplitterTest.class); + return new AllTests.BCTestSetup(suite); + } + + static class BCTestSetup + extends TestSetup + { + public BCTestSetup(Test test) + { + super(test); + } + + protected void setUp() + { + + } + + protected void tearDown() + { + + } + } +} diff --git a/core/src/test/java/org/bouncycastle/crypto/threshold/test/ShamirSecretSplitterTest.java b/core/src/test/java/org/bouncycastle/crypto/threshold/test/ShamirSecretSplitterTest.java new file mode 100644 index 0000000000..ae13341922 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/crypto/threshold/test/ShamirSecretSplitterTest.java @@ -0,0 +1,1114 @@ +package org.bouncycastle.crypto.threshold.test; + +import java.io.IOException; +import java.security.SecureRandom; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.threshold.SecretShare; +import org.bouncycastle.crypto.threshold.ShamirSecretSplitter; +import org.bouncycastle.crypto.threshold.ShamirSplitSecret; +import org.bouncycastle.crypto.threshold.ShamirSplitSecretShare; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; + +public class ShamirSecretSplitterTest + extends TestCase +{ + public static void main(String[] args) + throws IOException + { + ShamirSecretSplitterTest test = new ShamirSecretSplitterTest(); + for (int i = 0; i < 1000; ++i) + { + test.testShamirSecretMultipleDivide(); + } + test.performTest(); + System.out.println("OK"); + } + + public void performTest() + throws IOException + { + testShamirSecretResplit(); + testShamirSecretMultipleDivide(); + testShamirSecretSplitterSplitAround(); + testPolynomial(); + testShamirSecretSplitter(); + } + + public void testShamirSecretResplit() + throws IOException + { + int l = 9, m = 3, n = 9; + SecureRandom random = new SecureRandom(); + ShamirSecretSplitter.Algorithm algorithm = ShamirSecretSplitter.Algorithm.AES; + ShamirSecretSplitter.Mode mode = ShamirSecretSplitter.Mode.Table; + ShamirSecretSplitter splitter = new ShamirSecretSplitter(algorithm, mode, l, random); + + ShamirSplitSecret splitSecret = (ShamirSplitSecret)splitter.split(m, n); + ShamirSplitSecretShare[] secretShares = (ShamirSplitSecretShare[])splitSecret.getSecretShares(); + + ShamirSplitSecretShare[] secretShares1 = new ShamirSplitSecretShare[]{secretShares[0], secretShares[1], secretShares[2]}; + ShamirSplitSecret splitSecret1 = new ShamirSplitSecret(algorithm, mode, secretShares1); + byte[] secret1 = splitSecret1.getSecret(); + + + ShamirSplitSecret splitSecret2 = (ShamirSplitSecret)splitter.resplit(secret1, m, n); + ShamirSplitSecretShare[] secretShares2 = (ShamirSplitSecretShare[])splitSecret2.getSecretShares(); + ShamirSplitSecretShare[] secretShares3 = new ShamirSplitSecretShare[]{secretShares2[0], secretShares2[1], secretShares2[2]}; + ShamirSplitSecret splitSecret3 = new ShamirSplitSecret(algorithm, mode, secretShares3); + byte[] secret3 = splitSecret3.getSecret(); + + + assertTrue(Arrays.areEqual(secret1, secret3)); + assertFalse(Arrays.areEqual(Arrays.concatenate(secretShares[0].getEncoded(), secretShares[1].getEncoded(), secretShares[2].getEncoded()), + Arrays.concatenate(secretShares2[0].getEncoded(), secretShares2[1].getEncoded(), secretShares2[2].getEncoded()))); + } + + public void testShamirSecretMultipleDivide() + throws IOException + { + int l = 9, m = 3, n = 9; + SecureRandom random = new SecureRandom(); + ShamirSecretSplitter.Algorithm algorithm = ShamirSecretSplitter.Algorithm.AES; + ShamirSecretSplitter.Mode mode = ShamirSecretSplitter.Mode.Table; + ShamirSecretSplitter splitter = new ShamirSecretSplitter(algorithm, mode, l, random); + + ShamirSplitSecret splitSecret = (ShamirSplitSecret)splitter.split(m, n); + ShamirSplitSecretShare[] secretShares = (ShamirSplitSecretShare[])splitSecret.getSecretShares(); + + ShamirSplitSecretShare[] secretShares1 = new ShamirSplitSecretShare[]{secretShares[0], secretShares[1], secretShares[2]}; + ShamirSplitSecret splitSecret1 = new ShamirSplitSecret(algorithm, mode, secretShares1); + byte[] secret1 = splitSecret1.getSecret(); + + int mul = random.nextInt(254) + 1; + splitSecret.multiple(mul); + secretShares = (ShamirSplitSecretShare[])splitSecret.getSecretShares(); + ShamirSplitSecretShare[] secretShares4 = new ShamirSplitSecretShare[]{secretShares[1], secretShares[2], secretShares[5]}; + ShamirSplitSecret splitSecret4 = new ShamirSplitSecret(algorithm, mode, secretShares4); + byte[] secret4 = splitSecret4.getSecret(); + + splitSecret.divide(mul); + secretShares = (ShamirSplitSecretShare[])splitSecret.getSecretShares(); + ShamirSplitSecretShare[] secretShares2 = new ShamirSplitSecretShare[]{secretShares[4], secretShares[7], secretShares[8]}; + ShamirSplitSecret splitSecret2 = new ShamirSplitSecret(algorithm, mode, secretShares2); + byte[] secret2 = splitSecret2.getSecret(); + assertTrue(Arrays.areEqual(secret1, secret2)); + + + // not enough secret shares cannot correctly recover the secret + ShamirSplitSecretShare[] secretShares3 = new ShamirSplitSecretShare[]{secretShares[3], secretShares[6]}; + ShamirSplitSecret splitSecret3 = new ShamirSplitSecret(algorithm, mode, secretShares3); + byte[] secret3 = splitSecret3.getSecret(); + assertFalse(Arrays.areEqual(secret1, secret3)); + } + + public void testShamirSecretSplitterSplitAround() + throws IOException + { + int l = 9, m = 3, n = 9; + ShamirSecretSplitter.Algorithm algorithm = ShamirSecretSplitter.Algorithm.AES; + ShamirSecretSplitter.Mode mode = ShamirSecretSplitter.Mode.Table; + ShamirSecretSplitter splitter = new ShamirSecretSplitter(algorithm, mode, l, new SecureRandom()); + byte[] seed = Hex.decode("010203040506070809"); + //SecureRandom random = new SecureRandom(); + + //random.nextBytes(seed); + //System.out.println(Hex.decode(seed)); + ShamirSplitSecretShare ss = new ShamirSplitSecretShare(seed); + ShamirSplitSecret splitSecret = (ShamirSplitSecret)splitter.splitAround(ss, m, n); + ShamirSplitSecretShare[] secretShares = (ShamirSplitSecretShare[])splitSecret.getSecretShares(); + assertTrue(Arrays.areEqual(secretShares[0].getEncoded(), seed)); + + ShamirSplitSecretShare[] secretShares1 = new ShamirSplitSecretShare[]{secretShares[0], secretShares[1], secretShares[2]}; + ShamirSplitSecret splitSecret1 = new ShamirSplitSecret(algorithm, mode, secretShares1); + byte[] secret1 = splitSecret1.getSecret(); + + ShamirSplitSecretShare[] secretShares4 = new ShamirSplitSecretShare[]{secretShares[1], secretShares[2], secretShares[5]}; + ShamirSplitSecret splitSecret4 = new ShamirSplitSecret(algorithm, mode, secretShares4); + byte[] secret4 = splitSecret4.getSecret(); + + ShamirSplitSecretShare[] secretShares2 = new ShamirSplitSecretShare[]{secretShares[4], secretShares[7], secretShares[8]}; + ShamirSplitSecret splitSecret2 = new ShamirSplitSecret(algorithm, mode, secretShares2); + byte[] secret2 = splitSecret2.getSecret(); + + assertTrue(Arrays.areEqual(secret1, secret2)); + assertTrue(Arrays.areEqual(secret1, secret4)); + + // not enough secret shares cannot correctly recover the secret + ShamirSplitSecretShare[] secretShares3 = new ShamirSplitSecretShare[]{secretShares[3], secretShares[6]}; + ShamirSplitSecret splitSecret3 = new ShamirSplitSecret(algorithm, mode, secretShares3); + byte[] secret3 = splitSecret3.getSecret(); + assertFalse(Arrays.areEqual(secret1, secret3)); + + secretShares3 = new ShamirSplitSecretShare[]{secretShares[0], secretShares[1]}; + splitSecret3 = new ShamirSplitSecret(algorithm, mode, secretShares3); + secret3 = splitSecret3.getSecret(); + assertFalse(Arrays.areEqual(secret1, secret3)); + } + + public void testShamirSecretSplitter() + throws IOException + { + int l = 9, m = 3, n = 9; + ShamirSecretSplitter.Algorithm algorithm = ShamirSecretSplitter.Algorithm.AES; + ShamirSecretSplitter.Mode mode = ShamirSecretSplitter.Mode.Table; + ShamirSecretSplitter splitter = new ShamirSecretSplitter(algorithm, mode, l, new SecureRandom());//, secretshare); + ShamirSplitSecret splitSecret = (ShamirSplitSecret)splitter.split(m, n); //integers multiply/ divide + ShamirSplitSecretShare[] secretShares = (ShamirSplitSecretShare[])splitSecret.getSecretShares(); + + ShamirSplitSecretShare[] secretShares1 = new ShamirSplitSecretShare[]{secretShares[0], secretShares[1], secretShares[2]}; + ShamirSplitSecret splitSecret1 = new ShamirSplitSecret(algorithm, mode, secretShares1); + byte[] secret1 = splitSecret1.getSecret(); + + ShamirSplitSecretShare[] secretShares2 = new ShamirSplitSecretShare[]{secretShares[4], secretShares[7], secretShares[8]}; + ShamirSplitSecret splitSecret2 = new ShamirSplitSecret(algorithm, mode, secretShares2); + byte[] secret2 = splitSecret2.getSecret(); + + assertTrue(Arrays.areEqual(secret1, secret2)); + + // not enough secret shares cannot correctly recover the secret + ShamirSplitSecretShare[] secretShares3 = new ShamirSplitSecretShare[]{secretShares[3], secretShares[6]}; + ShamirSplitSecret splitSecret3 = new ShamirSplitSecret(algorithm, mode, secretShares3); + byte[] secret3 = splitSecret3.getSecret(); + assertFalse(Arrays.areEqual(secret1, secret3)); + } +// private static Polynomial polynomial1 = new PolynomialTable(Polynomial.AES); +// private static Polynomial polynomial2 = new PolynomialTable(Polynomial.RSA); + // Test test vectors for Polynomial 1 (x^^8 + x^^4 + x^^3 + x + 1) + + /* + * Test vector TV011B_1 + * secret = 74 65 73 74 00 + * random = A8 7B 34 91 B5 + * + * l = 5 + * m = 2 + * n = 2 + * + * split1 = DC 1E 47 E5 B5 + * split2 = 3F 93 1B 4D 71 + */ +// byte[][] TV011B_TV1_P = { +// {polynomial1.gfPow(0x01, (byte)0x00), polynomial1.gfPow(0x01, (byte)0x01)}, +// {polynomial1.gfPow(0x02, (byte)0x00), polynomial1.gfPow(0x02, (byte)0x01)} +// }; + + byte[][] TV011B_TV1_SR = { + {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x00}, + {(byte)0xA8, (byte)0x7B, (byte)0x34, (byte)0x91, (byte)0xB5} + }; + + byte[][] TV011B_TV1_SPLITS = { + {(byte)0xDC, (byte)0x1E, (byte)0x47, (byte)0xE5, (byte)0xB5}, + {(byte)0x3F, (byte)0x93, (byte)0x1B, (byte)0x4D, (byte)0x71} + }; + +// byte[][] TV011B_TV1_1_2_R = { +// {polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x01)), polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02))} +// }; + + byte[][] TV011B_TV1_1_2_SPLITS = { + {(byte)0xDC, (byte)0x1E, (byte)0x47, (byte)0xE5, (byte)0xB5}, + {(byte)0x3F, (byte)0x93, (byte)0x1B, (byte)0x4D, (byte)0x71} + }; + + byte[] TV011B_TV1_SECRET = {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x00}; + + /* + * Test vector TV011B_2 + * secret = 53 41 4D 54 43 + * random = 39 5D 39 6C 87 + * + * l = 5 + * m = 2 + * n = 4 + * + * split1 = 6A 1C 74 38 C4 + * split2 = 21 FB 3F 8C 56 + * split3 = 18 A6 06 E0 D1 + * split4 = B7 2E A9 FF 69 + */ +// byte[][] TV011B_TV2_P = { +// {polynomial1.gfPow(0x01, (byte)0x00), polynomial1.gfPow(0x01, (byte)0x01)}, +// {polynomial1.gfPow(0x02, (byte)0x00), polynomial1.gfPow(0x02, (byte)0x01)}, +// {polynomial1.gfPow(0x03, (byte)0x00), polynomial1.gfPow(0x03, (byte)0x01)}, +// {polynomial1.gfPow(0x04, (byte)0x00), polynomial1.gfPow(0x04, (byte)0x01)} +// }; + + byte[][] TV011B_TV2_SR = { + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}, + {(byte)0x39, (byte)0x5D, (byte)0x39, (byte)0x6C, (byte)0x87} + }; + + byte[][] TV011B_TV2_SPLITS = { + {(byte)0x6A, (byte)0x1C, (byte)0x74, (byte)0x38, (byte)0xC4}, + {(byte)0x21, (byte)0xFB, (byte)0x3F, (byte)0x8C, (byte)0x56}, + {(byte)0x18, (byte)0xA6, (byte)0x06, (byte)0xE0, (byte)0xD1}, + {(byte)0xB7, (byte)0x2E, (byte)0xA9, (byte)0xFF, (byte)0x69} + }; + +// byte[][] TV011B_TV2_1_2_R = { +// {polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02))} +// }; +// +// byte[][] TV011B_TV2_1_4_R = { +// {polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x01, (byte)0x04)), polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x04))} +// }; +// +// byte[][] TV011B_TV2_3_4_R = { +// {polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x03, (byte)0x04)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x03, (byte)0x04))} +// }; + + byte[][] TV011B_TV2_1_2_SPLITS = { + {(byte)0x6A, (byte)0x1C, (byte)0x74, (byte)0x38, (byte)0xC4}, + {(byte)0x21, (byte)0xFB, (byte)0x3F, (byte)0x8C, (byte)0x56} + }; + + byte[][] TV011B_TV2_1_4_SPLITS = { + {(byte)0x6A, (byte)0x1C, (byte)0x74, (byte)0x38, (byte)0xC4}, + {(byte)0xB7, (byte)0x2E, (byte)0xA9, (byte)0xFF, (byte)0x69} + }; + + byte[][] TV011B_TV2_3_4_SPLITS = { + {(byte)0x18, (byte)0xA6, (byte)0x06, (byte)0xE0, (byte)0xD1}, + {(byte)0xB7, (byte)0x2E, (byte)0xA9, (byte)0xFF, (byte)0x69} + }; + + byte[] TV011B_TV2_SECRET = {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}; + +// byte[][] TV011B_TV3_P = { +// {polynomial1.gfPow(0x01, (byte)0x00), polynomial1.gfPow(0x01, (byte)0x01), polynomial1.gfPow(0x01, (byte)0x02)}, +// {polynomial1.gfPow(0x02, (byte)0x00), polynomial1.gfPow(0x02, (byte)0x01), polynomial1.gfPow(0x02, (byte)0x02)}, +// {polynomial1.gfPow(0x03, (byte)0x00), polynomial1.gfPow(0x03, (byte)0x01), polynomial1.gfPow(0x03, (byte)0x02)}, +// {polynomial1.gfPow(0x04, (byte)0x00), polynomial1.gfPow(0x04, (byte)0x01), polynomial1.gfPow(0x04, (byte)0x02)} +// }; + + byte[][] TV011B_TV3_SR = { + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}, + {(byte)0x27, (byte)0x1A, (byte)0xAB, (byte)0x79, (byte)0x06}, + {(byte)0x3A, (byte)0x28, (byte)0x99, (byte)0xBC, (byte)0x37} + }; + + byte[][] TV011B_TV3_SPLITS = { + {(byte)0x4E, (byte)0x73, (byte)0x7F, (byte)0x91, (byte)0x72}, + {(byte)0xF5, (byte)0xD5, (byte)0x52, (byte)0x60, (byte)0x93}, + {(byte)0xE8, (byte)0xE7, (byte)0x60, (byte)0xA5, (byte)0xA2}, + {(byte)0x42, (byte)0x9F, (byte)0x84, (byte)0x9E, (byte)0x06} + }; + + /* + * Test vector TV011B_3 + * secret = 53 41 4D 54 43 + * random = 27 3A 1A 28 AB 99 79 BC 06 37 + * + * l = 5 + * m = 3 + * n = 4 + * + * split1 = 4E 73 7F 91 72 + * split2 = F5 D5 52 60 93 + * split3 = E8 E7 60 A5 A2 + * split4 = 42 9F 84 9E 06 + */ + +// byte[][] TV011B_TV3_1_2_3_R = { +// { +// polynomial1.gfMul(polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x01, (byte)0x03))), +// polynomial1.gfMul(polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x02, (byte)0x03))), +// polynomial1.gfMul(polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x03)), polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x03))) +// } +// }; +// +// byte[][] TV011B_TV3_1_2_4_R = { +// { +// polynomial1.gfMul(polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x01, (byte)0x04))), +// polynomial1.gfMul(polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x02, (byte)0x04))), +// polynomial1.gfMul(polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x04)), polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x04))) +// } +// }; +// +// byte[][] TV011B_TV3_1_3_4_R = { +// { +// polynomial1.gfMul(polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x01, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x01, (byte)0x04))), +// polynomial1.gfMul(polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x03, (byte)0x04))), +// polynomial1.gfMul(polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x04)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x03, (byte)0x04))) +// } +// }; + + byte[][] TV011B_TV3_1_2_3_SPLITS = { + {(byte)0x4E, (byte)0x73, (byte)0x7F, (byte)0x91, (byte)0x72}, + {(byte)0xF5, (byte)0xD5, (byte)0x52, (byte)0x60, (byte)0x93}, + {(byte)0xE8, (byte)0xE7, (byte)0x60, (byte)0xA5, (byte)0xA2} + }; + + byte[][] TV011B_TV3_1_2_4_SPLITS = { + {(byte)0x4E, (byte)0x73, (byte)0x7F, (byte)0x91, (byte)0x72}, + {(byte)0xF5, (byte)0xD5, (byte)0x52, (byte)0x60, (byte)0x93}, + {(byte)0x42, (byte)0x9F, (byte)0x84, (byte)0x9E, (byte)0x06} + }; + + byte[][] TV011B_TV3_1_3_4_SPLITS = { + {(byte)0x4E, (byte)0x73, (byte)0x7F, (byte)0x91, (byte)0x72}, + {(byte)0xE8, (byte)0xE7, (byte)0x60, (byte)0xA5, (byte)0xA2}, + {(byte)0x42, (byte)0x9F, (byte)0x84, (byte)0x9E, (byte)0x06} + }; + + byte[] TV011B_TV3_SECRET = {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}; + + /* + * Test vector TV011B_4 + * secret = 53 41 4D 54 43 + * random = 1A 22 4C 1E E9 76 0A 73 A0 9D 05 77 44 34 67 + * + * l = 5 + * m = 4 + * n = 4 + * + * split1 = 27 C0 94 BB 54 + * split2 = B9 69 F9 F4 0E + * split3 = 7E C7 CD 32 50 + * split4 = AB AF 81 82 8D + */ + +// byte[][] TV011B_TV4_P = { +// {polynomial1.gfPow(0x01, (byte)0x00), polynomial1.gfPow(0x01, (byte)0x01), polynomial1.gfPow(0x01, (byte)0x02), polynomial1.gfPow(0x01, (byte)0x03)}, +// {polynomial1.gfPow(0x02, (byte)0x00), polynomial1.gfPow(0x02, (byte)0x01), polynomial1.gfPow(0x02, (byte)0x02), polynomial1.gfPow(0x02, (byte)0x03)}, +// {polynomial1.gfPow(0x03, (byte)0x00), polynomial1.gfPow(0x03, (byte)0x01), polynomial1.gfPow(0x03, (byte)0x02), polynomial1.gfPow(0x03, (byte)0x03)}, +// {polynomial1.gfPow(0x04, (byte)0x00), polynomial1.gfPow(0x04, (byte)0x01), polynomial1.gfPow(0x04, (byte)0x02), polynomial1.gfPow(0x04, (byte)0x03)} +// }; + + byte[][] TV011B_TV4_SR = { + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}, + {(byte)0x1A, (byte)0x1E, (byte)0x0A, (byte)0x9D, (byte)0x44}, + {(byte)0x22, (byte)0xE9, (byte)0x73, (byte)0x05, (byte)0x34}, + {(byte)0x4C, (byte)0x76, (byte)0xA0, (byte)0x77, (byte)0x67} + }; + + byte[][] TV011B_TV4_SPLITS = { + {(byte)0x27, (byte)0xC0, (byte)0x94, (byte)0xBB, (byte)0x54}, + {(byte)0xB9, (byte)0x69, (byte)0xF9, (byte)0xF4, (byte)0x0E}, + {(byte)0x7E, (byte)0xC7, (byte)0xCD, (byte)0x32, (byte)0x50}, + {(byte)0xAB, (byte)0xAF, (byte)0x81, (byte)0x82, (byte)0x8D} + }; + +// byte[][] TV011B_TV4_1_2_3_4_R = { +// {polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x01, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x01, (byte)0x04))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x02, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x02, (byte)0x04))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x03)), polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x03, (byte)0x04))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x04)), polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x04)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x03, (byte)0x04))}) +// } +// }; + + byte[][] TV011B_TV4_1_2_3_4_SPLITS = { + {(byte)0x27, (byte)0xC0, (byte)0x94, (byte)0xBB, (byte)0x54}, + {(byte)0xB9, (byte)0x69, (byte)0xF9, (byte)0xF4, (byte)0x0E}, + {(byte)0x7E, (byte)0xC7, (byte)0xCD, (byte)0x32, (byte)0x50}, + {(byte)0xAB, (byte)0xAF, (byte)0x81, (byte)0x82, (byte)0x8D} + }; + + byte[] TV011B_TV4_SECRET = {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}; + + /* + * Test vector TV011B_5 + * secret = 54 65 73 74 20 44 61 74 61 + * random = 7F B4 E8 58 1E B7 5D C9 45 + * + * l = 9 + * m = 2 + * n = 9 + * + * split1 = 2B D1 9B 2C 3E F3 3C BD 24 + * split2 = AA 16 B8 C4 1C 31 DB FD EB + * split3 = D5 A2 50 9C 02 86 86 34 AE + * split4 = B3 83 FE 0F 58 AE 0E 7D 6E + * split5 = CC 37 16 57 46 19 53 B4 2B + * split6 = 4D F0 35 BF 64 DB B4 F4 E4 + * split7 = 32 44 DD E7 7A 6C E9 3D A1 + * split8 = 81 B2 72 82 D0 8B BF 66 7F + * split9 = FE 06 9A DA CE 3C E2 AF 3A + */ +// private static final byte[][] TV011B_TV5_P = { +// {polynomial1.gfPow(0x01, (byte)0x00), polynomial1.gfPow(0x01, (byte)0x01)}, +// {polynomial1.gfPow(0x02, (byte)0x00), polynomial1.gfPow(0x02, (byte)0x01)}, +// {polynomial1.gfPow(0x03, (byte)0x00), polynomial1.gfPow(0x03, (byte)0x01)}, +// {polynomial1.gfPow(0x04, (byte)0x00), polynomial1.gfPow(0x04, (byte)0x01)}, +// {polynomial1.gfPow(0x05, (byte)0x00), polynomial1.gfPow(0x05, (byte)0x01)}, +// {polynomial1.gfPow(0x06, (byte)0x00), polynomial1.gfPow(0x06, (byte)0x01)}, +// {polynomial1.gfPow(0x07, (byte)0x00), polynomial1.gfPow(0x07, (byte)0x01)}, +// {polynomial1.gfPow(0x08, (byte)0x00), polynomial1.gfPow(0x08, (byte)0x01)}, +// {polynomial1.gfPow(0x09, (byte)0x00), polynomial1.gfPow(0x09, (byte)0x01)} +// }; + + private static final byte[][] TV011B_TV5_SR = { + {(byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x44, (byte)0x61, (byte)0x74, (byte)0x61}, + {(byte)0x7F, (byte)0xB4, (byte)0xE8, (byte)0x58, (byte)0x1E, (byte)0xB7, (byte)0x5D, (byte)0xC9, (byte)0x45} + }; + + private static final byte[][] TV011B_TV5_SPLITS = { + {(byte)0x2B, (byte)0xD1, (byte)0x9B, (byte)0x2C, (byte)0x3E, (byte)0xF3, (byte)0x3C, (byte)0xBD, (byte)0x24}, + {(byte)0xAA, (byte)0x16, (byte)0xB8, (byte)0xC4, (byte)0x1C, (byte)0x31, (byte)0xDB, (byte)0xFD, (byte)0xEB}, + {(byte)0xD5, (byte)0xA2, (byte)0x50, (byte)0x9C, (byte)0x02, (byte)0x86, (byte)0x86, (byte)0x34, (byte)0xAE}, + {(byte)0xB3, (byte)0x83, (byte)0xFE, (byte)0x0F, (byte)0x58, (byte)0xAE, (byte)0x0E, (byte)0x7D, (byte)0x6E}, + {(byte)0xCC, (byte)0x37, (byte)0x16, (byte)0x57, (byte)0x46, (byte)0x19, (byte)0x53, (byte)0xB4, (byte)0x2B}, + {(byte)0x4D, (byte)0xF0, (byte)0x35, (byte)0xBF, (byte)0x64, (byte)0xDB, (byte)0xB4, (byte)0xF4, (byte)0xE4}, + {(byte)0x32, (byte)0x44, (byte)0xDD, (byte)0xE7, (byte)0x7A, (byte)0x6C, (byte)0xE9, (byte)0x3D, (byte)0xA1}, + {(byte)0x81, (byte)0xB2, (byte)0x72, (byte)0x82, (byte)0xD0, (byte)0x8B, (byte)0xBF, (byte)0x66, (byte)0x7F}, + {(byte)0xFE, (byte)0x06, (byte)0x9A, (byte)0xDA, (byte)0xCE, (byte)0x3C, (byte)0xE2, (byte)0xAF, (byte)0x3A} + }; +// +// private static final byte[][] TV011B_TV5_1_2_R = { +// {polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02))} +// }; +// +// private static final byte[][] TV011B_TV5_8_9_R = { +// {polynomial1.gfDiv(0x09, polynomial1.gfAdd(0x08, (byte)0x09)), polynomial1.gfDiv(0x08, polynomial1.gfAdd(0x08, (byte)0x09))} +// }; + + private static final byte[][] TV011B_TV5_1_2_SPLITS = { + {(byte)0x2B, (byte)0xD1, (byte)0x9B, (byte)0x2C, (byte)0x3E, (byte)0xF3, (byte)0x3C, (byte)0xBD, (byte)0x24}, + {(byte)0xAA, (byte)0x16, (byte)0xB8, (byte)0xC4, (byte)0x1C, (byte)0x31, (byte)0xDB, (byte)0xFD, (byte)0xEB} + }; + + private static final byte[][] TV011B_TV5_8_9_SPLITS = { + {(byte)0x81, (byte)0xB2, (byte)0x72, (byte)0x82, (byte)0xD0, (byte)0x8B, (byte)0xBF, (byte)0x66, (byte)0x7F}, + {(byte)0xFE, (byte)0x06, (byte)0x9A, (byte)0xDA, (byte)0xCE, (byte)0x3C, (byte)0xE2, (byte)0xAF, (byte)0x3A} + }; + + private static final byte[] TV011B_TV5_SECRET = + {(byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x44, (byte)0x61, (byte)0x74, (byte)0x61}; + + /* + * Test vector TV011B_6 + * secret = 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F + * random = EC 96 74 05 40 B3 E1 FC 9A 91 4F 6E 5F 7C CA 51 DB 72 32 02 C9 B8 81 00 4F 66 A2 80 71 97 + * + * l = 15 + * m = 3 + * n = 5 + * + * split1 = 7B 73 F0 19 0E 27 24 93 A0 3A 7A 8D 24 2C E9 + * split2 = AC FE 79 00 58 3B 52 D8 77 66 54 15 10 67 87 + * split3 = D6 8F 8A 1D 53 1A 71 43 DE 56 25 94 39 45 61 + * split4 = 3F 99 DD F4 88 9B E1 6A 29 E2 77 3E 10 68 63 + * split5 = 45 E8 2E E9 83 BA C2 F1 80 D2 06 BF 39 4A 85 + */ +// private static final byte[][] TV011B_TV6_P = { +// {polynomial1.gfPow(0x01, (byte)0x00), polynomial1.gfPow(0x01, (byte)0x01), polynomial1.gfPow(0x01, (byte)0x02)}, +// {polynomial1.gfPow(0x02, (byte)0x00), polynomial1.gfPow(0x02, (byte)0x01), polynomial1.gfPow(0x02, (byte)0x02)}, +// {polynomial1.gfPow(0x03, (byte)0x00), polynomial1.gfPow(0x03, (byte)0x01), polynomial1.gfPow(0x03, (byte)0x02)}, +// {polynomial1.gfPow(0x04, (byte)0x00), polynomial1.gfPow(0x04, (byte)0x01), polynomial1.gfPow(0x04, (byte)0x02)}, +// {polynomial1.gfPow(0x05, (byte)0x00), polynomial1.gfPow(0x05, (byte)0x01), polynomial1.gfPow(0x05, (byte)0x02)} +// }; + + private static final byte[][] TV011B_TV6_SR = { + {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B, (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F}, + {(byte)0xEC, (byte)0x74, (byte)0x40, (byte)0xE1, (byte)0x9A, (byte)0x4F, (byte)0x5F, (byte)0xCA, (byte)0xDB, (byte)0x32, (byte)0xC9, (byte)0x81, (byte)0x4F, (byte)0xA2, (byte)0x71}, + {(byte)0x96, (byte)0x05, (byte)0xB3, (byte)0xFC, (byte)0x91, (byte)0x6E, (byte)0x7C, (byte)0x51, (byte)0x72, (byte)0x02, (byte)0xB8, (byte)0x00, (byte)0x66, (byte)0x80, (byte)0x97} + }; + + private static final byte[][] TV011B_TV6_SPLITS = { + {(byte)0x7B, (byte)0x73, (byte)0xF0, (byte)0x19, (byte)0x0E, (byte)0x27, (byte)0x24, (byte)0x93, (byte)0xA0, (byte)0x3A, (byte)0x7A, (byte)0x8D, (byte)0x24, (byte)0x2C, (byte)0xE9}, + {(byte)0xAC, (byte)0xFE, (byte)0x79, (byte)0x00, (byte)0x58, (byte)0x3B, (byte)0x52, (byte)0xD8, (byte)0x77, (byte)0x66, (byte)0x54, (byte)0x15, (byte)0x10, (byte)0x67, (byte)0x87}, + {(byte)0xD6, (byte)0x8F, (byte)0x8A, (byte)0x1D, (byte)0x53, (byte)0x1A, (byte)0x71, (byte)0x43, (byte)0xDE, (byte)0x56, (byte)0x25, (byte)0x94, (byte)0x39, (byte)0x45, (byte)0x61}, + {(byte)0x3F, (byte)0x99, (byte)0xDD, (byte)0xF4, (byte)0x88, (byte)0x9B, (byte)0xE1, (byte)0x6A, (byte)0x29, (byte)0xE2, (byte)0x77, (byte)0x3E, (byte)0x10, (byte)0x68, (byte)0x63}, + {(byte)0x45, (byte)0xE8, (byte)0x2E, (byte)0xE9, (byte)0x83, (byte)0xBA, (byte)0xC2, (byte)0xF1, (byte)0x80, (byte)0xD2, (byte)0x06, (byte)0xBF, (byte)0x39, (byte)0x4A, (byte)0x85} + }; + +// private static final byte[][] TV011B_TV6_1_2_3_R = { +// {polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x01, (byte)0x03))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x02)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x02, (byte)0x03))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x01, polynomial1.gfAdd(0x01, (byte)0x03)), polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x03))})} +// }; +// +// private static final byte[][] TV011B_TV6_2_3_4_R = { +// {polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x02, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x02, (byte)0x04))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x03)), polynomial1.gfDiv(0x04, polynomial1.gfAdd(0x03, (byte)0x04))}), +// polynomial1.gfProd(new byte[]{polynomial1.gfDiv(0x02, polynomial1.gfAdd(0x02, (byte)0x04)), polynomial1.gfDiv(0x03, polynomial1.gfAdd(0x03, (byte)0x04))})} +// }; + + private static final byte[][] TV011B_TV6_1_2_3_SPLITS = { + {(byte)0x7B, (byte)0x73, (byte)0xF0, (byte)0x19, (byte)0x0E, (byte)0x27, (byte)0x24, (byte)0x93, (byte)0xA0, (byte)0x3A, (byte)0x7A, (byte)0x8D, (byte)0x24, (byte)0x2C, (byte)0xE9}, + {(byte)0xAC, (byte)0xFE, (byte)0x79, (byte)0x00, (byte)0x58, (byte)0x3B, (byte)0x52, (byte)0xD8, (byte)0x77, (byte)0x66, (byte)0x54, (byte)0x15, (byte)0x10, (byte)0x67, (byte)0x87}, + {(byte)0xD6, (byte)0x8F, (byte)0x8A, (byte)0x1D, (byte)0x53, (byte)0x1A, (byte)0x71, (byte)0x43, (byte)0xDE, (byte)0x56, (byte)0x25, (byte)0x94, (byte)0x39, (byte)0x45, (byte)0x61} + }; + + private static final byte[][] TV011B_TV6_2_3_4_SPLITS = { + {(byte)0xAC, (byte)0xFE, (byte)0x79, (byte)0x00, (byte)0x58, (byte)0x3B, (byte)0x52, (byte)0xD8, (byte)0x77, (byte)0x66, (byte)0x54, (byte)0x15, (byte)0x10, (byte)0x67, (byte)0x87}, + {(byte)0xD6, (byte)0x8F, (byte)0x8A, (byte)0x1D, (byte)0x53, (byte)0x1A, (byte)0x71, (byte)0x43, (byte)0xDE, (byte)0x56, (byte)0x25, (byte)0x94, (byte)0x39, (byte)0x45, (byte)0x61}, + {(byte)0x3F, (byte)0x99, (byte)0xDD, (byte)0xF4, (byte)0x88, (byte)0x9B, (byte)0xE1, (byte)0x6A, (byte)0x29, (byte)0xE2, (byte)0x77, (byte)0x3E, (byte)0x10, (byte)0x68, (byte)0x63} + }; + + private static final byte[] TV011B_TV6_SECRET = + {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B, (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F}; + + // Test test vectors for Polynomial 1 (x^^8 + x^^4 + x^^3 + x + 1) + + /* + * Test vector TV011D_1 + * secret = 74 65 73 74 00 + * random = A8 7B 34 91 B5 + * + * l = 5 + * m = 2 + * n = 2 + * + * split1 = DC 1E 47 E5 B5 + * split2 = 3F 93 1B 4D 71 + */ + + + // Constants for testing +// public static final byte[][] TV011D_TV1_P = { +// {polynomial2.gfPow(0x01, (byte)0x00), polynomial2.gfPow(0x01, (byte)0x01)}, +// {polynomial2.gfPow(0x02, (byte)0x00), polynomial2.gfPow(0x02, (byte)0x01)} +// }; + + public static final byte[][] TV011D_TV1_SR = { + {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x00}, + {(byte)0xF3, (byte)0xC2, (byte)0x33, (byte)0x81, (byte)0xF5} + }; + + public static final byte[][] TV011D_TV1_SPLITS = { + {(byte)0x87, (byte)0xA7, (byte)0x40, (byte)0xF5, (byte)0xF5}, + {(byte)0x8F, (byte)0xFC, (byte)0x15, (byte)0x6B, (byte)0xF7} + }; + +// public static final byte[][] TV011D_TV1_1_2_R = { +// {polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x01)), polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02))} +// }; + + public static final byte[][] TV011D_TV1_1_2_SPLITS = { + {(byte)0x87, (byte)0xA7, (byte)0x40, (byte)0xF5, (byte)0xF5}, + {(byte)0x8F, (byte)0xFC, (byte)0x15, (byte)0x6B, (byte)0xF7} + }; + + public static final byte[] TV011D_TV1_SECRET = + {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x00}; + + /* + * Test vector TV011D_2 + * secret = 53 41 4D 54 43 + * random = 39 5D 39 6C 87 + * + * l = 5 + * m = 2 + * n = 4 + * + * split1 = 6A 1C 74 38 C4 + * split2 = 21 FB 3F 8C 56 + * split3 = 18 A6 06 E0 D1 + * split4 = B7 2E A9 FF 69 + */ +// public static final byte[][] TV011D_TV2_P = { +// {polynomial2.gfPow(0x01, (byte)0x00), polynomial2.gfPow(0x01, (byte)0x01)}, +// {polynomial2.gfPow(0x02, (byte)0x00), polynomial2.gfPow(0x02, (byte)0x01)}, +// {polynomial2.gfPow(0x03, (byte)0x00), polynomial2.gfPow(0x03, (byte)0x01)}, +// {polynomial2.gfPow(0x04, (byte)0x00), polynomial2.gfPow(0x04, (byte)0x01)} +// }; + + public static final byte[][] TV011D_TV2_SR = { + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}, + {(byte)0x20, (byte)0x76, (byte)0x08, (byte)0x93, (byte)0x0C} + }; + + public static final byte[][] TV011D_TV2_SPLITS = { + {(byte)0x73, (byte)0x37, (byte)0x45, (byte)0xC7, (byte)0x4F}, + {(byte)0x13, (byte)0xAD, (byte)0x5D, (byte)0x6F, (byte)0x5B}, + {(byte)0x33, (byte)0xDB, (byte)0x55, (byte)0xFC, (byte)0x57}, + {(byte)0xD3, (byte)0x84, (byte)0x6D, (byte)0x22, (byte)0x73} + }; + + // Matrices for recombination +// public static final byte[][] TV011D_TV2_1_2_R = { +// {polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02))} +// }; +// +// public static final byte[][] TV011D_TV2_1_4_R = { +// {polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x01, (byte)0x04)), polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x04))} +// }; +// +// public static final byte[][] TV011D_TV2_3_4_R = { +// {polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x03, (byte)0x04)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x03, (byte)0x04))} +// }; + + // Split shares + public static final byte[][] TV011D_TV2_1_2_SPLITS = { + {(byte)0x73, (byte)0x37, (byte)0x45, (byte)0xC7, (byte)0x4F}, + {(byte)0x13, (byte)0xAD, (byte)0x5D, (byte)0x6F, (byte)0x5B} + }; + + public static final byte[][] TV011D_TV2_1_4_SPLITS = { + {(byte)0x73, (byte)0x37, (byte)0x45, (byte)0xC7, (byte)0x4F}, + {(byte)0xD3, (byte)0x84, (byte)0x6D, (byte)0x22, (byte)0x73} + }; + + public static final byte[][] TV011D_TV2_3_4_SPLITS = { + {(byte)0x33, (byte)0xDB, (byte)0x55, (byte)0xFC, (byte)0x57}, + {(byte)0xD3, (byte)0x84, (byte)0x6D, (byte)0x22, (byte)0x73} + }; + + public static final byte[] TV011D_TV2_SECRET = + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}; + /* + * Test vector TV011D_3 + * secret = 53 41 4D 54 43 + * random = 8C 15 92 62 5C 4A AF 53 41 45 + * + * l = 5 + * m = 3 + * n = 4 + * + * split1 = CA B1 5B A8 47 + * split2 = 02 ED C0 46 C8 + * split3 = 9B 1D D6 BA CC + * split4 = 14 5D F4 8B 7E + */ + + // Constants for TV3 +// public static final byte[][] TV011D_TV3_P = { +// {polynomial2.gfPow(0x01, (byte)0x00), polynomial2.gfPow(0x01, (byte)0x01), polynomial2.gfPow(0x01, (byte)0x02)}, +// {polynomial2.gfPow(0x02, (byte)0x00), polynomial2.gfPow(0x02, (byte)0x01), polynomial2.gfPow(0x02, (byte)0x02)}, +// {polynomial2.gfPow(0x03, (byte)0x00), polynomial2.gfPow(0x03, (byte)0x01), polynomial2.gfPow(0x03, (byte)0x02)}, +// {polynomial2.gfPow(0x04, (byte)0x00), polynomial2.gfPow(0x04, (byte)0x01), polynomial2.gfPow(0x04, (byte)0x02)} +// }; + + public static final byte[][] TV011D_TV3_SR = { + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}, + {(byte)0x8C, (byte)0x92, (byte)0x5C, (byte)0xAF, (byte)0x41}, + {(byte)0x15, (byte)0x62, (byte)0x4A, (byte)0x53, (byte)0x45} + }; + + public static final byte[][] TV011D_TV3_SPLITS = { + {(byte)0xCA, (byte)0xB1, (byte)0x5B, (byte)0xA8, (byte)0x47}, + {(byte)0x02, (byte)0xED, (byte)0xC0, (byte)0x46, (byte)0xC8}, + {(byte)0x9B, (byte)0x1D, (byte)0xD6, (byte)0xBA, (byte)0xCC}, + {(byte)0x14, (byte)0x5D, (byte)0xF4, (byte)0x8B, (byte)0x7E} + }; + + // Matrices for recombination +// public static final byte[][] TV011D_TV3_1_2_3_R = { +// { +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x01, (byte)0x03))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x02, (byte)0x03))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x03)), polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x03))}) +// } +// }; +// +// public static final byte[][] TV011D_TV3_1_2_4_R = { +// { +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x01, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x02, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x04)), polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x04))}) +// } +// }; +// +// public static final byte[][] TV011D_TV3_1_3_4_R = { +// { +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x01, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x01, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x03, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x04)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x03, (byte)0x04))}) +// } +// }; + + // Split shares + public static final byte[][] TV011D_TV3_1_2_3_SPLITS = { + {(byte)0xCA, (byte)0xB1, (byte)0x5B, (byte)0xA8, (byte)0x47}, + {(byte)0x02, (byte)0xED, (byte)0xC0, (byte)0x46, (byte)0xC8}, + {(byte)0x9B, (byte)0x1D, (byte)0xD6, (byte)0xBA, (byte)0xCC} + }; + + public static final byte[][] TV011D_TV3_1_2_4_SPLITS = { + {(byte)0xCA, (byte)0xB1, (byte)0x5B, (byte)0xA8, (byte)0x47}, + {(byte)0x02, (byte)0xED, (byte)0xC0, (byte)0x46, (byte)0xC8}, + {(byte)0x14, (byte)0x5D, (byte)0xF4, (byte)0x8B, (byte)0x7E} + }; + + public static final byte[][] TV011D_TV3_1_3_4_SPLITS = { + {(byte)0xCA, (byte)0xB1, (byte)0x5B, (byte)0xA8, (byte)0x47}, + {(byte)0x9B, (byte)0x1D, (byte)0xD6, (byte)0xBA, (byte)0xCC}, + {(byte)0x14, (byte)0x5D, (byte)0xF4, (byte)0x8B, (byte)0x7E} + }; + + // Secret to recover + public static final byte[] TV011D_TV3_SECRET = + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}; + + /* + * Test vector TV011D_4 + * secret = 53 41 4D 54 43 + * random = 72 B0 88 3C 96 B9 CB B9 CB B2 82 66 F3 79 FA + * + * l = 5 + * m = 4 + * n = 4 + * + * split1 = 19 52 F4 02 33 + * split2 = 79 FA 0E 08 C2 + * split3 = 24 58 37 17 94 + * split4 = F4 45 A9 D6 07 + */ + // Constants for TV4 +// public static final byte[][] TV011D_TV4_P = { +// {polynomial2.gfPow(0x01, (byte)0x00), polynomial2.gfPow(0x01, (byte)0x01), polynomial2.gfPow(0x01, (byte)0x02), polynomial2.gfPow(0x01, (byte)0x03)}, +// {polynomial2.gfPow(0x02, (byte)0x00), polynomial2.gfPow(0x02, (byte)0x01), polynomial2.gfPow(0x02, (byte)0x02), polynomial2.gfPow(0x02, (byte)0x03)}, +// {polynomial2.gfPow(0x03, (byte)0x00), polynomial2.gfPow(0x03, (byte)0x01), polynomial2.gfPow(0x03, (byte)0x02), polynomial2.gfPow(0x03, (byte)0x03)}, +// {polynomial2.gfPow(0x04, (byte)0x00), polynomial2.gfPow(0x04, (byte)0x01), polynomial2.gfPow(0x04, (byte)0x02), polynomial2.gfPow(0x04, (byte)0x03)} +// }; + + public static final byte[][] TV011D_TV4_SR = { + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}, + {(byte)0x72, (byte)0x3C, (byte)0xCB, (byte)0xB2, (byte)0xF3}, + {(byte)0xB0, (byte)0x96, (byte)0xB9, (byte)0x82, (byte)0x79}, + {(byte)0x88, (byte)0xB9, (byte)0xCB, (byte)0x66, (byte)0xFA} + }; + + public static final byte[][] TV011D_TV4_SPLITS = { + {(byte)0x19, (byte)0x52, (byte)0xF4, (byte)0x02, (byte)0x33}, + {(byte)0x79, (byte)0xFA, (byte)0x0E, (byte)0x08, (byte)0xC2}, + {(byte)0x24, (byte)0x58, (byte)0x37, (byte)0x17, (byte)0x94}, + {(byte)0xF4, (byte)0x45, (byte)0xA9, (byte)0xD6, (byte)0x07} + }; + + // Matrices for recombination +// public static final byte[][] TV011D_TV4_1_2_3_4_R = { +// { +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x01, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x01, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x02, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x02, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x03)), polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x03, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x04)), polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x04)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x03, (byte)0x04))}) +// } +// }; + + public static final byte[][] TV011D_TV4_1_2_3_4_SPLITS = { + {(byte)0x19, (byte)0x52, (byte)0xF4, (byte)0x02, (byte)0x33}, + {(byte)0x79, (byte)0xFA, (byte)0x0E, (byte)0x08, (byte)0xC2}, + {(byte)0x24, (byte)0x58, (byte)0x37, (byte)0x17, (byte)0x94}, + {(byte)0xF4, (byte)0x45, (byte)0xA9, (byte)0xD6, (byte)0x07} + }; + + // Secret to recover + public static final byte[] TV011D_TV4_SECRET = + {(byte)0x53, (byte)0x41, (byte)0x4D, (byte)0x54, (byte)0x43}; + + + /* + * Test vector TV011D_5 + * secret = 54 65 73 74 20 44 61 74 61 + * random = AF FD 2B 0B FA 34 33 63 9C + * + * l = 9 + * m = 2 + * n = 9 + * + * split1 = FB 98 58 7F DA 70 52 17 FD + * split2 = 17 82 25 62 C9 2C 07 B2 44 + * split3 = B8 7F 0E 69 33 18 34 D1 D8 + * split4 = D2 B6 DF 58 EF 94 AD E5 2B + * split5 = 7D 4B F4 53 15 A0 9E 86 B7 + * split6 = 91 51 89 4E 06 FC CB 23 0E + * split7 = 3E AC A2 45 FC C8 F8 40 92 + * split8 = 45 DE 36 2C A3 F9 E4 4B F5 + * split9 = EA 23 1D 27 59 CD D7 28 69 + */ + // Constants for TV5 +// public static final byte[][] TV011D_TV5_P = { +// {polynomial2.gfPow(0x01, (byte)0x00), polynomial2.gfPow(0x01, (byte)0x01)}, +// {polynomial2.gfPow(0x02, (byte)0x00), polynomial2.gfPow(0x02, (byte)0x01)}, +// {polynomial2.gfPow(0x03, (byte)0x00), polynomial2.gfPow(0x03, (byte)0x01)}, +// {polynomial2.gfPow(0x04, (byte)0x00), polynomial2.gfPow(0x04, (byte)0x01)}, +// {polynomial2.gfPow(0x05, (byte)0x00), polynomial2.gfPow(0x05, (byte)0x01)}, +// {polynomial2.gfPow(0x06, (byte)0x00), polynomial2.gfPow(0x06, (byte)0x01)}, +// {polynomial2.gfPow(0x07, (byte)0x00), polynomial2.gfPow(0x07, (byte)0x01)}, +// {polynomial2.gfPow(0x08, (byte)0x00), polynomial2.gfPow(0x08, (byte)0x01)}, +// {polynomial2.gfPow(0x09, (byte)0x00), polynomial2.gfPow(0x09, (byte)0x01)} +// }; + + public static final byte[][] TV011D_TV5_SR = { + {(byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x44, (byte)0x61, (byte)0x74, (byte)0x61}, + {(byte)0xAF, (byte)0xFD, (byte)0x2B, (byte)0x0B, (byte)0xFA, (byte)0x34, (byte)0x33, (byte)0x63, (byte)0x9C} + }; + + public static final byte[][] TV011D_TV5_SPLITS = { + {(byte)0xFB, (byte)0x98, (byte)0x58, (byte)0x7F, (byte)0xDA, (byte)0x70, (byte)0x52, (byte)0x17, (byte)0xFD}, + {(byte)0x17, (byte)0x82, (byte)0x25, (byte)0x62, (byte)0xC9, (byte)0x2C, (byte)0x07, (byte)0xB2, (byte)0x44}, + {(byte)0xB8, (byte)0x7F, (byte)0x0E, (byte)0x69, (byte)0x33, (byte)0x18, (byte)0x34, (byte)0xD1, (byte)0xD8}, + {(byte)0xD2, (byte)0xB6, (byte)0xDF, (byte)0x58, (byte)0xEF, (byte)0x94, (byte)0xAD, (byte)0xE5, (byte)0x2B}, + {(byte)0x7D, (byte)0x4B, (byte)0xF4, (byte)0x53, (byte)0x15, (byte)0xA0, (byte)0x9E, (byte)0x86, (byte)0xB7}, + {(byte)0x91, (byte)0x51, (byte)0x89, (byte)0x4E, (byte)0x06, (byte)0xFC, (byte)0xCB, (byte)0x23, (byte)0x0E}, + {(byte)0x3E, (byte)0xAC, (byte)0xA2, (byte)0x45, (byte)0xFC, (byte)0xC8, (byte)0xF8, (byte)0x40, (byte)0x92}, + {(byte)0x45, (byte)0xDE, (byte)0x36, (byte)0x2C, (byte)0xA3, (byte)0xF9, (byte)0xE4, (byte)0x4B, (byte)0xF5}, + {(byte)0xEA, (byte)0x23, (byte)0x1D, (byte)0x27, (byte)0x59, (byte)0xCD, (byte)0xD7, (byte)0x28, (byte)0x69} + }; + + // Matrices for recombination +// public static final byte[][] TV011D_TV5_1_2_R = { +// {polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02))} +// }; +// +// public static final byte[][] TV011D_TV5_8_9_R = { +// {polynomial2.gfDiv(0x09, polynomial2.gfAdd(0x08, (byte)0x09)), polynomial2.gfDiv(0x08, polynomial2.gfAdd(0x08, (byte)0x09))} +// }; + + public static final byte[][] TV011D_TV5_1_2_SPLITS = { + {(byte)0xFB, (byte)0x98, (byte)0x58, (byte)0x7F, (byte)0xDA, (byte)0x70, (byte)0x52, (byte)0x17, (byte)0xFD}, + {(byte)0x17, (byte)0x82, (byte)0x25, (byte)0x62, (byte)0xC9, (byte)0x2C, (byte)0x07, (byte)0xB2, (byte)0x44} + }; + + public static final byte[][] TV011D_TV5_8_9_SPLITS = { + {(byte)0x45, (byte)0xDE, (byte)0x36, (byte)0x2C, (byte)0xA3, (byte)0xF9, (byte)0xE4, (byte)0x4B, (byte)0xF5}, + {(byte)0xEA, (byte)0x23, (byte)0x1D, (byte)0x27, (byte)0x59, (byte)0xCD, (byte)0xD7, (byte)0x28, (byte)0x69} + }; + + // Secret to recover + public static final byte[] TV011D_TV5_SECRET = + {(byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x44, (byte)0x61, (byte)0x74, (byte)0x61}; + + + /* + * Test vector TV011D_6 + * secret = 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F + * random = 02 4A 89 AC 96 8C 98 65 77 FE B0 24 11 6B 94 F6 54 DD DE 20 9C 3C C3 E4 48 88 4D 31 F8 C8 + * + * l = 15 + * m = 3 + * n = 5 + * + * split1 = 49 27 19 F9 8C 92 7D 6A 80 F4 AB 2B CD 72 3F + * split2 = 30 87 38 A0 34 EB 94 C2 F2 2B DE 20 87 50 E5 + * split3 = 78 A2 22 5D BD 7F EE A0 7B D5 7E 07 47 2C D5 + * split4 = DD 0E 49 40 9F 86 BD B9 15 6F A6 C1 58 10 D4 + * split5 = 95 2B 53 BD 16 12 C7 DB 9C 91 06 E6 98 6C E4 + */ +// private static final byte[][] TV011D_TV6_P = { +// {polynomial2.gfPow(0x01, (byte)0x00), polynomial2.gfPow(0x01, (byte)0x01), polynomial2.gfPow(0x01, (byte)0x02)}, +// {polynomial2.gfPow(0x02, (byte)0x00), polynomial2.gfPow(0x02, (byte)0x01), polynomial2.gfPow(0x02, (byte)0x02)}, +// {polynomial2.gfPow(0x03, (byte)0x00), polynomial2.gfPow(0x03, (byte)0x01), polynomial2.gfPow(0x03, (byte)0x02)}, +// {polynomial2.gfPow(0x04, (byte)0x00), polynomial2.gfPow(0x04, (byte)0x01), polynomial2.gfPow(0x04, (byte)0x02)}, +// {polynomial2.gfPow(0x05, (byte)0x00), polynomial2.gfPow(0x05, (byte)0x01), polynomial2.gfPow(0x05, (byte)0x02)} +// }; + + private static final byte[][] TV011D_TV6_SR = { + {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B, (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F}, + {(byte)0x02, (byte)0x89, (byte)0x96, (byte)0x98, (byte)0x77, (byte)0xB0, (byte)0x11, (byte)0x94, (byte)0x54, (byte)0xDE, (byte)0x9C, (byte)0xC3, (byte)0x48, (byte)0x4D, (byte)0xF8}, + {(byte)0x4A, (byte)0xAC, (byte)0x8C, (byte)0x65, (byte)0xFE, (byte)0x24, (byte)0x6B, (byte)0xF6, (byte)0xDD, (byte)0x20, (byte)0x3C, (byte)0xE4, (byte)0x88, (byte)0x31, (byte)0xC8} + }; + + private static final byte[][] TV011D_TV6_SPLITS = { + {(byte)0x49, (byte)0x27, (byte)0x19, (byte)0xF9, (byte)0x8C, (byte)0x92, (byte)0x7D, (byte)0x6A, (byte)0x80, (byte)0xF4, (byte)0xAB, (byte)0x2B, (byte)0xCD, (byte)0x72, (byte)0x3F}, + {(byte)0x30, (byte)0x87, (byte)0x38, (byte)0xA0, (byte)0x34, (byte)0xEB, (byte)0x94, (byte)0xC2, (byte)0xF2, (byte)0x2B, (byte)0xDE, (byte)0x20, (byte)0x87, (byte)0x50, (byte)0xE5}, + {(byte)0x78, (byte)0xA2, (byte)0x22, (byte)0x5D, (byte)0xBD, (byte)0x7F, (byte)0xEE, (byte)0xA0, (byte)0x7B, (byte)0xD5, (byte)0x7E, (byte)0x07, (byte)0x47, (byte)0x2C, (byte)0xD5}, + {(byte)0xDD, (byte)0x0E, (byte)0x49, (byte)0x40, (byte)0x9F, (byte)0x86, (byte)0xBD, (byte)0xB9, (byte)0x15, (byte)0x6F, (byte)0xA6, (byte)0xC1, (byte)0x58, (byte)0x10, (byte)0xD4}, + {(byte)0x95, (byte)0x2B, (byte)0x53, (byte)0xBD, (byte)0x16, (byte)0x12, (byte)0xC7, (byte)0xDB, (byte)0x9C, (byte)0x91, (byte)0x06, (byte)0xE6, (byte)0x98, (byte)0x6C, (byte)0xE4} + }; + +// private static final byte[][] TV011D_TV6_1_2_3_R = { +// { +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x01, (byte)0x03))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x02)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x02, (byte)0x03))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x01, polynomial2.gfAdd(0x01, (byte)0x03)), polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x03))}) +// } +// }; +// +// private static final byte[][] TV011D_TV6_2_3_4_R = { +// { +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x02, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x02, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x03)), polynomial2.gfDiv(0x04, polynomial2.gfAdd(0x03, (byte)0x04))}), +// polynomial2.gfProd(new byte[]{polynomial2.gfDiv(0x02, polynomial2.gfAdd(0x02, (byte)0x04)), polynomial2.gfDiv(0x03, polynomial2.gfAdd(0x03, (byte)0x04))}) +// } +// }; + + private static final byte[][] TV011D_TV6_1_2_3_SPLITS = { + {(byte)0x49, (byte)0x27, (byte)0x19, (byte)0xF9, (byte)0x8C, (byte)0x92, (byte)0x7D, (byte)0x6A, (byte)0x80, (byte)0xF4, (byte)0xAB, (byte)0x2B, (byte)0xCD, (byte)0x72, (byte)0x3F}, + {(byte)0x30, (byte)0x87, (byte)0x38, (byte)0xA0, (byte)0x34, (byte)0xEB, (byte)0x94, (byte)0xC2, (byte)0xF2, (byte)0x2B, (byte)0xDE, (byte)0x20, (byte)0x87, (byte)0x50, (byte)0xE5}, + {(byte)0x78, (byte)0xA2, (byte)0x22, (byte)0x5D, (byte)0xBD, (byte)0x7F, (byte)0xEE, (byte)0xA0, (byte)0x7B, (byte)0xD5, (byte)0x7E, (byte)0x07, (byte)0x47, (byte)0x2C, (byte)0xD5} + }; + + private static final byte[][] TV011D_TV6_2_3_4_SPLITS = { + {(byte)0x30, (byte)0x87, (byte)0x38, (byte)0xA0, (byte)0x34, (byte)0xEB, (byte)0x94, (byte)0xC2, (byte)0xF2, (byte)0x2B, (byte)0xDE, (byte)0x20, (byte)0x87, (byte)0x50, (byte)0xE5}, + {(byte)0x78, (byte)0xA2, (byte)0x22, (byte)0x5D, (byte)0xBD, (byte)0x7F, (byte)0xEE, (byte)0xA0, (byte)0x7B, (byte)0xD5, (byte)0x7E, (byte)0x07, (byte)0x47, (byte)0x2C, (byte)0xD5}, + {(byte)0xDD, (byte)0x0E, (byte)0x49, (byte)0x40, (byte)0x9F, (byte)0x86, (byte)0xBD, (byte)0xB9, (byte)0x15, (byte)0x6F, (byte)0xA6, (byte)0xC1, (byte)0x58, (byte)0x10, (byte)0xD4} + }; + + private static final byte[] TV011D_TV6_SECRET = + {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B, (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F}; + + private interface PolynomialFactory + { + ShamirSecretSplitter newInstance(int l, int m, int n, SecureRandom random); + + ShamirSplitSecret newInstance(ShamirSplitSecretShare[] secretShares); + } + + @Override + public String getName() + { + return "Polynomial Test"; + } + + public void testPolynomial() + throws IOException + { + testPolynoimial1(new PolynomialFactory() + { + @Override + public ShamirSecretSplitter newInstance(int l, int m, int n, SecureRandom random) + { + return new ShamirSecretSplitter(ShamirSecretSplitter.Algorithm.AES, ShamirSecretSplitter.Mode.Native, l, random); + } + + @Override + public ShamirSplitSecret newInstance(ShamirSplitSecretShare[] secretShares) + { + return new ShamirSplitSecret(ShamirSecretSplitter.Algorithm.AES, ShamirSecretSplitter.Mode.Native, secretShares); + } + + }); + testPolynoimial1(new PolynomialFactory() + { + @Override + public ShamirSecretSplitter newInstance(int l, int m, int n, SecureRandom random) + { + return new ShamirSecretSplitter(ShamirSecretSplitter.Algorithm.AES, ShamirSecretSplitter.Mode.Table, l, random); + } + + @Override + public ShamirSplitSecret newInstance(ShamirSplitSecretShare[] secretShares) + { + return new ShamirSplitSecret(ShamirSecretSplitter.Algorithm.AES, ShamirSecretSplitter.Mode.Table, secretShares); + } + }); + + testPolynoimial2(new PolynomialFactory() + { + @Override + public ShamirSecretSplitter newInstance(int l, int m, int n, SecureRandom random) + { + return new ShamirSecretSplitter(ShamirSecretSplitter.Algorithm.RSA, ShamirSecretSplitter.Mode.Native, l, random); + } + + @Override + public ShamirSplitSecret newInstance(ShamirSplitSecretShare[] secretShares) + { + return new ShamirSplitSecret(ShamirSecretSplitter.Algorithm.RSA, ShamirSecretSplitter.Mode.Native, secretShares); + } + }); + + testPolynoimial2(new PolynomialFactory() + { + @Override + public ShamirSecretSplitter newInstance(int l, int m, int n, SecureRandom random) + { + return new ShamirSecretSplitter(ShamirSecretSplitter.Algorithm.RSA, ShamirSecretSplitter.Mode.Table, l, random); + } + + @Override + public ShamirSplitSecret newInstance(ShamirSplitSecretShare[] secretShares) + { + return new ShamirSplitSecret(ShamirSecretSplitter.Algorithm.RSA, ShamirSecretSplitter.Mode.Table, secretShares); + } + }); + } + + private void testPolynoimial1(PolynomialFactory polynomialFactory) + throws IOException + { + ShamirSecretSplitter splitter = polynomialFactory.newInstance(5, 2, 2, getSecureRandom(TV011B_TV1_SR)); + testMatrixMultiplication(splitter, TV011B_TV1_SPLITS, 2, 2); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2}, TV011B_TV1_1_2_SPLITS)), TV011B_TV1_SECRET); + splitter = polynomialFactory.newInstance(5, 2, 4, getSecureRandom(TV011B_TV2_SR)); + testMatrixMultiplication(splitter, TV011B_TV2_SPLITS, 2, 4); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2}, TV011B_TV2_1_2_SPLITS)), TV011B_TV2_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 4}, TV011B_TV2_1_4_SPLITS)), TV011B_TV2_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{3, 4}, TV011B_TV2_3_4_SPLITS)), TV011B_TV2_SECRET); + splitter = polynomialFactory.newInstance(5, 3, 4, getSecureRandom(TV011B_TV3_SR)); + testMatrixMultiplication(splitter, TV011B_TV3_SPLITS, 3, 4); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 3}, TV011B_TV3_1_2_3_SPLITS)), TV011B_TV3_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 4}, TV011B_TV3_1_2_4_SPLITS)), TV011B_TV3_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 3, 4}, TV011B_TV3_1_3_4_SPLITS)), TV011B_TV3_SECRET); + splitter = polynomialFactory.newInstance(5, 4, 4, getSecureRandom(TV011B_TV4_SR)); + testMatrixMultiplication(splitter, TV011B_TV4_SPLITS, 4, 4); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 3, 4}, TV011B_TV4_1_2_3_4_SPLITS)), TV011B_TV4_SECRET); + splitter = polynomialFactory.newInstance(9, 2, 9, getSecureRandom(TV011B_TV5_SR)); + testMatrixMultiplication(splitter, TV011B_TV5_SPLITS, 2, 9); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2}, TV011B_TV5_1_2_SPLITS)), TV011B_TV5_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{8, 9}, TV011B_TV5_8_9_SPLITS)), TV011B_TV5_SECRET); + splitter = polynomialFactory.newInstance(15, 3, 5, getSecureRandom(TV011B_TV6_SR)); + testMatrixMultiplication(splitter, TV011B_TV6_SPLITS, 3, 5); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 3}, TV011B_TV6_1_2_3_SPLITS)), TV011B_TV6_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{2, 3, 4}, TV011B_TV6_2_3_4_SPLITS)), TV011B_TV6_SECRET); + } + + private void testPolynoimial2(PolynomialFactory polynomialFactory) + throws IOException + { + ShamirSecretSplitter poly = polynomialFactory.newInstance(5, 2, 2, getSecureRandom(TV011D_TV1_SR)); + testMatrixMultiplication(poly, TV011D_TV1_SPLITS, 2, 2); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2}, TV011D_TV1_1_2_SPLITS)), TV011D_TV1_SECRET); + poly = polynomialFactory.newInstance(5, 2, 4, getSecureRandom(TV011D_TV2_SR)); + testMatrixMultiplication(poly, TV011D_TV2_SPLITS, 2, 4); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2}, TV011D_TV2_1_2_SPLITS)), TV011D_TV2_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 4}, TV011D_TV2_1_4_SPLITS)), TV011D_TV2_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{3, 4}, TV011D_TV2_3_4_SPLITS)), TV011D_TV2_SECRET); + poly = polynomialFactory.newInstance(5, 3, 4, getSecureRandom(TV011D_TV3_SR)); + testMatrixMultiplication(poly, TV011D_TV3_SPLITS, 3, 4); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 3}, TV011D_TV3_1_2_3_SPLITS)), TV011D_TV3_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 4}, TV011D_TV3_1_2_4_SPLITS)), TV011D_TV3_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 3, 4}, TV011D_TV3_1_3_4_SPLITS)), TV011D_TV3_SECRET); + poly = polynomialFactory.newInstance(5, 4, 4, getSecureRandom(TV011D_TV4_SR)); + testMatrixMultiplication(poly, TV011D_TV4_SPLITS, 4, 4); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 3, 4}, TV011D_TV4_1_2_3_4_SPLITS)), TV011D_TV4_SECRET); + poly = polynomialFactory.newInstance(9, 2, 9, getSecureRandom(TV011D_TV5_SR)); + testMatrixMultiplication(poly, TV011D_TV5_SPLITS, 2, 9); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2}, TV011D_TV5_1_2_SPLITS)), TV011D_TV5_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{8, 9}, TV011D_TV5_8_9_SPLITS)), TV011D_TV5_SECRET); + poly = polynomialFactory.newInstance(15, 3, 5, getSecureRandom(TV011D_TV6_SR)); + testMatrixMultiplication(poly, TV011D_TV6_SPLITS, 3, 5); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{1, 2, 3}, TV011D_TV6_1_2_3_SPLITS)), TV011D_TV6_SECRET); + testRecombine(polynomialFactory.newInstance(getShamirSplitSecretShareArray(new int[]{2, 3, 4}, TV011D_TV6_2_3_4_SPLITS)), TV011D_TV6_SECRET); + } + + static SecureRandom getSecureRandom(byte[][] sr) + { + byte[] source = new byte[sr.length * sr[0].length]; + int currentIndex = 0; + + for (int i = 0; i != sr.length; i++) + { + byte[] subArray = sr[i]; + System.arraycopy(subArray, 0, source, currentIndex, subArray.length); + currentIndex += subArray.length; + } + return new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(source)}); + } + + static ShamirSplitSecretShare[] getShamirSplitSecretShareArray(int[] rr, byte[][] splits) + { + ShamirSplitSecretShare[] secretShares = new ShamirSplitSecretShare[rr.length]; + for (int i = 0; i < secretShares.length; ++i) + { + secretShares[i] = new ShamirSplitSecretShare(splits[i], rr[i]); + } + return secretShares; + } + + static void testMatrixMultiplication(ShamirSecretSplitter poly, byte[][] splits, int m, int n) + throws IOException + { + SecretShare[] secretShares = poly.split(m, n).getSecretShares(); + byte[][] result = new byte[splits.length][splits[0].length]; + for (int i = 0; i < result.length; ++i) + { + result[i] = secretShares[i].getEncoded(); + assertTrue(Arrays.areEqual(splits[i], result[i])); + } + } + + public void testRecombine(ShamirSplitSecret splitSecret, byte[] secret) + throws IOException + { + byte[] result = splitSecret.getSecret(); + assertTrue(Arrays.areEqual(secret, result)); + } +} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/lms/HSSTests.java b/core/src/test/java/org/bouncycastle/pqc/crypto/lms/HSSTests.java index b262701d99..2ececd90d2 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/lms/HSSTests.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/lms/HSSTests.java @@ -543,6 +543,7 @@ else if (line.startsWith("Signature:")) assertEquals(1024, keyPair.getUsagesRemaining()); assertEquals(1024, keyPair.getIndexLimit()); + assertEquals(0, keyPair.getIndex()); // // Split the space up with a shard. @@ -555,7 +556,6 @@ else if (line.startsWith("Signature:")) HSSPrivateKeyParameters pair = shard1; int c = 0; - String exhaustionMessage = null; for (int i = 0; i < keyPair.getIndexLimit(); i++) { if (i == 500) @@ -640,6 +640,7 @@ public void testRemaining() HSSPrivateKeyParameters shard = keyPair.extractKeyShard(10); + assertEquals(10, shard.getUsagesRemaining()); assertEquals(15, shard.getIndexLimit()); assertEquals(5, shard.getIndex()); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/AllTests.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/AllTests.java index e89dbf1088..221427954b 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/AllTests.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/AllTests.java @@ -4,6 +4,7 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; + import org.bouncycastle.test.PrintTestResult; import org.bouncycastle.util.test.SimpleTestResult; @@ -19,6 +20,8 @@ public static Test suite() { TestSuite suite = new TestSuite("Lightweight PQ Crypto Tests"); + suite.addTestSuite(LMSTest.class); + suite.addTestSuite(HSSTest.class); suite.addTestSuite(XMSSMTPrivateKeyTest.class); suite.addTestSuite(XMSSMTPublicKeyTest.class); suite.addTestSuite(XMSSMTSignatureTest.class); @@ -37,17 +40,18 @@ public static Test suite() suite.addTestSuite(NTRUTest.class); suite.addTestSuite(NTRUParametersTest.class); suite.addTestSuite(FalconTest.class); - suite.addTestSuite(CrystalsKyberTest.class); + suite.addTestSuite(MLKEMTest.class); suite.addTestSuite(CrystalsDilithiumTest.class); + suite.addTestSuite(MLDSATest.class); suite.addTestSuite(NTRULPRimeTest.class); suite.addTestSuite(SNTRUPrimeTest.class); suite.addTestSuite(BIKETest.class); suite.addTestSuite(HQCTest.class); - suite.addTestSuite(RainbowVectorTest.class); - suite.addTestSuite(GeMSSTest.class); suite.addTestSuite(XWingTest.class); suite.addTestSuite(AllTests.SimpleTestTest.class); - + suite.addTestSuite(SLHDSATest.class); + suite.addTestSuite(MayoTest.class); + suite.addTestSuite(SnovaTest.class); return new BCTestSetup(suite); } diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/BIKETest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/BIKETest.java index f1ca00279a..f5f433eda6 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/BIKETest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/BIKETest.java @@ -4,7 +4,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; -import java.util.Random; import junit.framework.TestCase; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; @@ -52,7 +51,6 @@ public void testVectors() BIKEParameters.bike256 }; - TestSampler sampler = new TestSampler(); for (int fileIndex = 0; fileIndex < files.length; fileIndex++) { String name = files[fileIndex]; @@ -62,8 +60,7 @@ public void testVectors() String line = null; HashMap buf = new HashMap(); - Random rnd = new Random(System.currentTimeMillis()); - + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/CMCEVectorTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/CMCEVectorTest.java index b5f4ef3480..92f6525b74 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/CMCEVectorTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/CMCEVectorTest.java @@ -71,16 +71,16 @@ public void testVectors() CMCEParameters.mceliece8192128fr3 }; - TestSampler sampler = new TestSampler(); for (int fileIndex = 0; fileIndex != files.length; fileIndex++) { String name = files[fileIndex]; - // System.out.println("testing: " + name); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/cmce", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsDilithiumTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsDilithiumTest.java index 5eaac65d08..c50a69b206 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsDilithiumTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsDilithiumTest.java @@ -1,6 +1,7 @@ package org.bouncycastle.pqc.crypto.test; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.SecureRandom; @@ -27,75 +28,103 @@ public class CrystalsDilithiumTest extends TestCase { - /* -count = 0 -seed = 061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1 -mlen = 33 -msg = D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8 -pk = 1C0EE1111B08003F28E65E8B3BDEB037CF8F221DFCDAF5950EDB38D506D85BEFD9FDE3A496F75819F0A20D0441DC7830B4AA1CB8ECFC91BA0EEC3AFB6744E477B4E6EC3FDAE75048FFEBAABEA8E822117D5787F79070EA88287CE3CD5011FD8D93AB7E8B51F26116BF9B6D21C03F88BFEC488876F4D075A142D4E784D734407511F992069353F1DB67ACF73034A468A118588062111D320E00BCFF6DC63573FCED1E96AAEBA6452E3C7ACD19181F9B814BA19D39B4BAB5496DC055426E7EA461AF55D5B9FE97F9DF7E253203C1F9E152E96D75F9D9A84F5C263EC8C250440ADC986F4E36414C703B3E05426B28B7065950DA6D0E0B2C60AC3672DB6F3C78447DB7C20915770EA6FCE81DAB5339C1D5AF82A5D3324099DF56516A07DB7C0FC64383805C65F2B02FBCFCE63E93C4BF09409F9F0F77E73DA3B0019F2057E4CD7CFF0E5745EF18C3FD766E01747A64D415FC9789ABFA62284E11C7FF05D0548D973F679559A6A3AAD77ED5132D0150C014C3EC3A395F017E7ACFE3EABFCA44910CA06FF33542ECCE6241974742357D37F5C284BF0FE1A74B50C073551372133AF2DD41E21BAFC9C590EE6EBC4ACE731EF566156CA03755DC493C137028AF3B3DE5B00BD6CB3D9A87D0151F887C6768BC6CA02A94FB2086551A0F89BA26154E9D4506AD9FAF39F5723E234E06CFDED69D4EE4146B73E5DC1E4152A2A3159D73DBC833D3D417CD5CF7FB3DC7745CEED4DC0F5B1C6D6B69C1764157EA43DF9DBB442EFA39D1D0162E87C2D30C5012FD16D869C8A1FCBB45EDCC8E1813B2B190A961F9FC86591D3ABC5388AF678FF03DA78B7CC0F6185721C0DF33CC906435225DF2611002DF120E83566532292DEA3D8ACD109A0DFFAB3B0B43012796DB5B50683FB4C2D250DAB76AAE35A48E8C8D4A5CC154759745F0A1230F6CA9DD9C99E2F80EDC83304CE01E98F6C9489529A822F90033C228315EB2FCC8DBA382ED4301E07607A5B076C725F124994F18A997D2C5BBF9A324605265108ACBF4610FA1C3374408850A0864E2B61017EBEC1FBAB89DE3AB1B93CE4918B9E2C9E3FE456758062A9F882B283318271F4B9552FCF32624A9FDAA44C65C60E2B3648BEF1F17D0B7C74869EE0B53C4A62A24845DCEA5BCBF93B92E4C26648584E33479282E6C8B1D8FE21181BD9CF75F8A961724D4C4309779F1F1B775D254F70BD1769CC7C0EDD2A95FE5C9D84B16F7C54D85CCE4C8A182810809ED81E97D074884EEDF401CCACDAEAD82C14D06B68AEA6CE14B861B0CFD16090CBBF469C5E084314C0D8D3960EA06A3426D8B3FE762E00D09BDA374F3AE2CBEDE2838FF89D81DEB3013090E44199AED604963EAF919914CE04F207AC82CD4351FEF7B2D94393066FE4D44E3CC5952E75EB6F3714058915DE0EE184D8C55300F576A8B82A863E81AF33417BD4CFC94E7A61263B39F01F6E2E70748B6E5E59CF6CA01B0028C93BBBCEBC548F987F10755BF33CA585CB41CF578DF5FFE37924E3C2C072ED1DAC9162176972971E79B62FB208F1A73BF0361E2993DCCCD3110C34D839D18DD43A5E8F0D941E99ADCF441405F32107671B2D8B2244F7BA92DCED587A210FE8FF43C616ACB5E766E6AF2CEB03599BA3DE376EB5735EF16143953D1FDDB7E9F2874B0D6083DD7EC4386AE003F51CCF2D21EF6059163C5152174423F57119D0FCE627D763D81C10AA1329F74C8D445437BA6718A33DB6E79375172B2AE3591821978D520824E2D2FF898B7F4C867FF462722BC07EADAD389A910B6F65429DA129735FE049E3ECB3889F6047CF2BD2A88D50A651B3235D2480E1DA5A35247FA76C831736399D37E8D033C1D051C9B6A99AB80B1313FA24C5C59766E6C51A38FE9F1186A767EEBD0D88001AE0246CD4EBE2C979DE82C30BBDB98B4744F11F9E639EDDD8C194D7911201A8FA745991B4D8A5709B62A21B63B9762913D36CE995C2D6B79151E8D83838CD1F38840A9417255DD166B7A3584499003FB625611404C95B960DF0DB1BCF1574B0965DBD834EE148117D5E05A7CC7CC1A865618A2BE4854DB8935CDA1E68BD8D09E72F0AC9053C882C4ABA4004A614D10505300B6176CA1F324E22E7824299F9C40755B71D82B679547F06AD48BE66D68072C9390233C933F80A14F8D4A6B0B4E1970E1ACC1BEA7F5D3BE224448F857BAB68AEFA6D8CB819B64294A12997916CDBF56E9A8D002DD065F12C61823F4FC214508232E431F0B6898475BB5DD0D7D528E840C22809AF7E15363724A613ACCFBE2B37438C159CE14CB0C98BFD499C08DAC0CF45D821CC2FA47319B6FB4CED7E5985EC8274DE09071D3C10DA5BF9E522B01CE91D66B91795D3D22C00483454275DD2BBDD7C2DCC4A167E5D7FCDBB9F6208CD4C9A485FAAEB809A7711DAC2865CED4306474B22B4448F85DF33417F3FACE1C05D42703ED313042A05DE0362740130188ECB445BB255DC76EE8443F733117F8351F17603175554FEB00B7FF54D80786F305CDE18CD5EC56EC0962A3E04482DCE3622D040D24C40F2E8A14A447659D6C561F2FFEE68F8D3DE511B23E8B172A01A3EDA4D3780E74C677244330E9AEFF019FE07BE3D33F322F9CE2214B9D9CFF99D05A59E47551432AE76F4CD4F8DD51520FFE811B4B93CD6219C81B63B1D627785C2A0FC22E3AEA86CEEE1F7FBC4EFCB46DDFBCD88A02F3B4E67C5FF2E8DC68BF16C74699BBB628902F72C3DEBC8BF5DF706D47A605A107DAA0014139CE40F0D46D8D6DC7 -sk = 1C0EE1111B08003F28E65E8B3BDEB037CF8F221DFCDAF5950EDB38D506D85BEF394D1695059DFF40AE256C5D5EDABFB69F5F40F37A588F50532CA408A8168AB1E64F146427543D8C36B3B65226769A22911A5A313EAC17C4ABA25284514FC6131F20FE945B7F3690C56BD99E99376378FAE71A374A7158EDB50F116DC284686535780833022316433765807578714524810173154483652641333022302614737052210781265061858507754618580548533018706647518267737733500270312878821580714026734320616250617371010311453681523024650348143708371825508406086017625831312827001718481667317861073723557447151010112110662742120835462285131388164886833510476026118315742500742440642515861365613777118478050862437064068527631150135623216841417724084830878575438508636854268450568437024007161784543800612705826206765211121483880678147555021222855231084503701364318005376837650246531507600625331251200541606324235241507731457033476564312318033365167587141304111715546812605373423882432783371222817481812013632764751028032268650876553563338104474858543012431808386438538308412704646463346461068070602375516825741152882201577858333134315582840316360106481480464368461757213631657465221517713205106646831646714728313555147332818260731554368708032843262416053205202367725828181085426785155280007282271831120868377244420548647205350861738627124677510852763340373432115424065402345080041772846273616868078152467106825545816362764180571244255708045106636115858630465207053275021822428371023852752844203300172311140215768838476231851352521084382555567411445467278546586170430758800684551353478138120800843156221466031560016368563673618080045554337312584031148042036733018271556065603440514434554851122376451064337325382338062451617081541167173200853260404371068037376070864087000352457148262203505356660372180137103710365278432824642320476423840000674364565226217665212413887347650843121701647146540387244177741376785521641117316050482604148474663803351558017351262133622227106345601657207785483272483156167834564057686734583525352081556548103205334016607423715016325334667270811118243732131154424082613775046710080261386850712837526672242308021005015520483744377116420123167107823808071011246825824018158518742085382583106675131252852765256031478162138153470422610571556744682005455051484113038302414747156272021653210303873603486751766527214217262576653612111216874845403342683544406813605031081743567506346184755758586544840762318670343367586667732075171036052737241220173887544032263062135418368155773200100365185741860214443341023755635875026188641851762415850711803541515742425854563545155707638677240017678386862588177508612360606507333506605275024724336451354552554148604216431563331655676070342677080760553063501337707701374572745128728364747780273036442310552415431163146533631211846312638837626748351386351783125814478856084801427164775364735466055660523700464031105550453648423406611175526158521573573156158778744503872054561166220446141461830006866406004737442250560104577350748702663748684802632852635811304428683261106188260700733862552715534532142573231221878655672567467472814454641577410780605613161540446347533077616250133841474266705206708125431777701522218250013173169DB8086B122701706AE49B99305EE6D016F16F9FACC1F835298B41E21664206005CEB981A35F18651CDB90E68C1F950B059F73D6D3143A1F47AA21D80A05FAF5D3A40F67148D3A89A9FDA80364D57C7B8F68058A25D08498D9A9C378C98185DB13259159CAC4769C34A08023A3388C3505406FB21C69EEC12DAC95A3C9BA61185237F0FF1E0E05F1A6F5A0C09090100665A1AD3AFB1076847B232EEEA78409BD9055DB57C1B31E28A01D09999035BDFC657A61040103ECEBDC793409733734D9342CC5A069E070C2421DDE11C49E172DBE7FEAF9DEDDFB3DA5DAA6B3DD13200B09042E144EEA951B43DA48153C1F1D5C07FCF473FA7F321E72534577C895151B46E48331DDE61DA45F8609AC59581814666E1658B49114524BA3840C6BC5596551AEF42412C8AACCDD8EF69E46380E6DEF60FD91228B99CB511D68EF6631748A0548083A215445EC54693471A831042CF41D09AF898119B0FC646E484539C8C32D5DC24F9439D33EEEA033A4081550FDB0B08923DBA5D44A1A876FE7EE4320BF02F9BE26F418F309FA11FCD0C864A7AA34115083C1EA775345AC0548C877C685EA8C91B924AF4F607EF37A0208E21309AB6D0F2F8A4EAA0451FF4A47E6F482958D81A166A6A08A6A10FC8F9ADA42B64A12B9357D598A3664E9DF13755C10FFD7177E594DFCBCFB5D11B6ADB1607445479A5DB1AD8CA6D915F89795D240CBEDFAD2539D10518E53CC450D6FC5385AD6D76B7830F13828120645E3A0A5DCDEAF15F1968E64B3B1CEAF536CAA2953D161C75528C3FA8493E0C177AE807CED37648A82C9BE8BA970296D543F6FBD6724A99A68D2F68C1FD333F9DEF8526DB7836455B313E6BC366178C9C57721601EC0335054F067B78E663A058DBDA1C12D80A392F89C0AD9E2A3B2EA17E9C9A3B14D176822EEAC5FB5FF7D4C87D76080D2D42D9AA4C951F4CAF11A244EDA711D120A2EA321D1551D86CA9265E9CD5FA9591D880E403B6844F051DC04879972C863B97C72B409C19D5EBEE8AB58C6E7B3938A68A9CAD75D80C6FFC4F22254FF4420C606AD120CC20346A7E7324E78C862E0DEE161A64F44917DB0C38C1F79C969220D202F8802D0F9D7ABFB2DE434B1C53DABB57575EEBBBF31CFB2924872FA01473B3976AEADC99699B13820FA0868F2C9FD0D352E2593273CD621B1974FFA6187FA05C4118D4517C934151C1FA34BEC3ED3639598CBA24E28229CE9FD3B1DB4969C12EE49E18B36CE2B9145AAC75428DFFA145302F41D9E3394F38D3F3C0334C4774F1E94296DE36DC6E430E4C0A537E68BDD41AF0421193B16AB1891FA836CBC367B403705ABA5D2F9F2A4C2F275EC010B2EAB84095A569DBAE4457CC2AC1CFEB1EDA43C3E2819273C487ACBEBFA0A0ED1CC4667A6F577F62DFB1BC8FEAFD86D90108E16B8B0E6C2678686C928A668BB9857FFB28DE90545CD4437DD32CCCCC6ED58FB46FBF85E0AEC0C814E536245252B8029F0A2AB44B9027A7E35A941FA113C8D82974EA22DF02D84E5328CEA83D12D399C7F0259055F4B3AD707E7B3E537B93DEA1A066BDC775FC7D1A6F0FE29DDAFA9A7DA630A467EF6CBF5CCDFFD79F1C8BB6BB3882035C73CDF7ECFFB53C712A7C7EAA59765EFA960BF21E25A6703FB304F07739FEBC63F496B13CCAA077338A0B9A976A9F0FC5742D85C4AF401A4CE341B47BE2594FF7E3019A0E064535F9D9395CC74A6A6F00E0C4E3530A7FE9310CE30B6922D04FDE0AA749CC3FDEDB4D8708C1F6968BBEDDDD5833B299D79D61428180099B0A946A5D79085DF7F872CBDD219E6B8EF8B8AB5C1A149E6E15EF2828654FABEC249AFAAC4DC0B3B542334162FB09800B6C36CC90F2A106558BAE2198FA7D1E2D730DE46E355AEA93248E53AB21B518EC99D5F3B021196A0F614A46B9475621234733A28A465CC5A7FD432C3625812AABBB42D2D9CBEF16CBED9367202B02894D06BB801BDA8472B9918B7D724E36557DBE6B7633A5FD22D0E336E5557AFC018C812E9E6A35BFD8C60AB382E14FF51142B2D2C75A767F32413BA38487558F9345CBE6FD1D6B78C2E622F3B976230F99D6CBAF0BBD14949510A52644EF3F3078865037A1C10F47B59546699E1BD539C7DDCC03F71A0158EA9F0178E187BB6D49440DF2B10630FBE2FEB5097E47F285711CA6F835A10D3AA75C03C4184C03EF3075D49DCB2177ABD53AD7399D290EA691D647329056340E8C836E9750FD881DCE309D309A95B82492D4BDC15ECF8C7F5D3B9DD275548512DB5EF80CD409ED32B5148B82BF240A7DC72A18523D808B7A4F9E254799E17278FA88DAEBC944632E83F8609D681AB463513023D67CD51B153F0962912DD64AB8F6529DC22AA89E572A7F89CB97A8F4509319D223BB29974951716FD3177140A31EA20048BAF0FCA230CEF21967ABD83309A4FF7E35E88784DCA77AC079020EC0CA6DDEFBCBB7E317329314665D7C51F631F681B600364E47574F252BAD6396B3F5B17ADC220966A93CE8F315A2F83068D2EA06952E6EBD802473A2264EFA405B3E491BE776C50406E1150C56B894CF864546B0C7A65E3F1A2BEFEF2A9990BAFE70B6CA9F91A8F3DD21307A39A2AFBDFBDE9B7CA3D7828B13F49DECD729C0039E94EBB7B4BDA09B3505529A12CB1E2FD79B9E5087CD7C3BC05F7CFFBBA932A7BFF8E67555FEE0304D890313F86E1892569E2D6F14A89938717AAA3A32AD1167150299C21820ABD70FF902B004C6DE91C1C0B40706442AF531EC490B012750BCB4877935A7E54031702BB988EB3F92914CDBD42979AD7D27B2233EC1279D05493B12D3F5FBB7757536021B5F4CD932B480E40CBAE50D232E0A2EFFE0E8CB58808669199F0830872F369738682F846F6DEAD095BFFCD670A4A9CD142396C58506EA7A68B21ABDCC19CCC06F6DA55C885A855C456680CD4477BCA2BBA9153DCAEE682655B74ECA6F7E44C3BFE1E2D457491ED1BC64E1CF6CE18CF44A0166D1B244480882C1B35CEA703158E18C7EC6E0CF827D5504A45AE61152309BC8A18A52C0E7699A87C4E31C6911A8305351555B2971C94602B70E670AA30B90734EC1DAAD03A30A96F5847C5C3F7973CF4572D166C51D1E94A50A4C1C894A205F8ECB34E80F84CA8DC31A429D5600596179D1093E2A389CCFE9C0402EE49551710FFC25BDBE478F39F2063F31F75D7432ECA1C59EBD8F46D86A092DB12F810FA911C20D4CC1E425C543DC64577E44D84F422D9661E3D35921350D6F7099C5425E509E1458A0500AE5EB4CC6BB50626D0130F09361717A95919AED35592FA4ABE7B2BD4F999422151E63D4ED00CC751A5867977F15E482EFA01E5CCC44064F5B9FFE29AFFE626C4D5170ADA1DF027AB4179608C4093CCE2C409308CD898371A49FBEA2A2F2BA13BDEBAC1F4159F4B0368FB21D70A9D7931D7EFF934E6C544E13B7B73D465576C6E81FD6D5FD94393E80242F9420ACC0ED353EF18CA070F5E9A285AC4BCBAB19A38356F557B070E17AE5CF1F1BED42601E89C8C4C -smlen = 3326 -sm = 81FF8025E2D7DFC0F8D47C16041E54A2E124898A711A500D2A743986782155E933A9617C0612773F455F556B9A0D5A5F50CC090D4D36FB5D79B09DE4459FF9C76DBFA2F9B0B68676CFE2906789BA89F584B3A6D00D6ABE266A20B4EB1568D85E6F511E469162F3D602435795C0F9249F712DC5FD1D8F5AAC3B767447FF8875E7FE699A6C398130587846F694741DD1DA76D78EB22BA9CFAB920F700C603224067C8B2FA619D6787AA7FAF6D715E34968D923D7965F7F5E6244965F27E5DF0114CCF90E26700B9EE54769D9D713FDA7B753A8A5A0CEC9C7D41EB6967DAF74A0A286079B8AF6093C712D0E605E3856E8E690A1B90D9D17BB091E44C018A7BD6AB6EE8FA0DCC220DB244001AB640325084677B67325A2B0C83D0CD118D454E45A105FBC7C8BE060FD0FA8244C846042092183364447C83381E3E1DB0582B14FC388098E472AEC5DF99B74487D4837EFBF8BFB08EAD95EC732F5EA1B347BBD79805B3CE88FD1686F6202DDBE0386D9E72AF31BDEF979FE7C3672A3E4395C72E0E2F9500883ED0669C407DFF2AAB19D6D44FA1728B63B1C2E4755AFBCBFD8290777C7619772669F0591D5045418D558C1D8A460FE26A9944A7B8CAED1E1D299D35D57166E8F27A1EC7462FEAE5A551EBE853D9A9B85670F3C07D31714C92246A61E3C3B54D7FE758640A3D88E532449EEDBFB7C71CC102EDD043226BACCFCEF21147DD6204BBDDCC1110C16F8FC6CF62E424224E0E40212A932E8329199240A4F382A54B4FCEE4A899FE12B188091D61F4598E2649DFF1A091556D116C098B9ABCB0C20DB9516CD643ADB131842D9B37D4D7B17E5F7813623F5C43D668E78B4EE22CC96914DB45A27877F26D68395AAE2EDBF0A1EF0C48520D05E0DDA411578C7D4B8957AC48C58621BD5CCE25A718B5ABEAA6739768F44C73836BCA0AFD86491E15C49F40CAFE24B5FACB52B948B7C93A7C081C21961924D3D696FE23B1BBB63F4525F037B3648AAD3E04D8778EF4333573AED76AC0A607F783E8C228ECF85E093DF7A8E16C8955C4622C9DFAB726821908849CD117C30617404E4571CCA3C16291160E8A56CF8279F53CA31B03DFD87863E765D262589652EE032E020DA9D92102878534C64E882F76F98569FE77357DFEF2FD6C37E4FE9BA64F0CA92B5B40D318A994EEA264209C08B81BB42447E8295930160330101F0BF4FC4B77BEB74281C7761A8FC4A82582688ED3C8FD4B8464F87FBA1BA59BF77B2CC51D261591307924E3CA46EF4058458930A5B1486C9C4FFB4D90172250CC1D6C0ADC64EA7C494EE44E5E4749ECBB0A7E5F18C4CE82058DC7DD34DE5B05CA9812AB75FEF610D572E859213109050EEE46E7569531223CA029A42BA840C51423F419DF37A3822A9F77A3B2012B851FF539F1D370029461980A7373CF9B61FD954E98A338456EA3F14D5C501CE0593D268C98EACEFEA2BC591D466E23FCAF2381BDB656670B91D06F5E7853F0E7FC239D54FC3CA9A448E2868C61BA1410CA9C65DC53C30FD00534EB591DE952D940514EE0E7E20C795F86FE571786A40EB6F4CC2ACED893B30839F05DA96744B776670F91637CC6CE7451E0AA19021453EF1294585CB7A6E44AB9C313983DDBD4D6FA54DBA87FE5A5F5DEEED7CE9E52CC402FF6C2C1C41DDF9B245BC5CB1122FE0343CADB0B40D4BC8A558199B892A08F7D07F7735BC10C45A547DB0DA4904F415C5D832AB1EB3762126675C8A69240436D98FF96D9067DAAB72816287D167FAF475B43BCAFF5EF584B5E2579B101E388C6E40603AD4F3B5A8D15B4D3BBE4862BDE60AB825B80D2ED437176C8A86F050BAAD75687D7B83E8F3FBA6404DCBFB84521A67681AF0AE5297A9C6DCE2B409C3CC179068A06BD088D0B47592C3447EE980E35D7AD8CEF4352096D1168119D275CE9B289AD0B5512FFCDB9B521BD07A0F6F35C274BDE925F3A970EC6C320FEB2D6A5A8128C62848AC16D2971C136A3B7ED2FB324AFFAA200C29FECE5E388E989C3240EA39189D91B8CA6DAFCDEFC5D152A6A7BB2D67FCD3C1014218E9A9E8107D7BCD5F026B5DA99238F33C914918377EAB40C776047276156F83609A1D9D872757F0B35DB5044174C6C2567EB5EA9AFBEF6C051FFED8894445843205CEDFDEA788F429789FF87AFE5CA85C6E4F5B6E0D262B700C494195D7741C6702029483C8B0ACCB9B8014CC76DCB33245B45BB496B05A1641D8FEAD0ABCD53F9D551A716364E24B36E2F001521F76965BE160EB420C7FABAF97EDE20C4A2747CEF0D7639896AF7C5ED115816BD0B69E6B7D67A2E17CBC7314F1C673AE1C6197B8A3BE07B528EC053B8402104A34CF665BF7F2B3CAB84C6303538273880A8F6CEEC959C251C576A10A30A1081421D5EE0D4B2AE501B814A77A6137AF16B5DCE81039AEF9DA6E6BFBB79522427A0EDD2F1E8E2AAC8D28F9DDA4BE6E91D1649A9305D560EFED5C0A29B6452FB47EAA41CB50859CAC2B6BC4158D2D1AA9136CECE1FB380EAF63A8F1ED37AA34C5B7628B9BF972213A79020AFA21E81FF0FBFC9705502E5BBC6AD63DA058365B46E3D8F8B3A8E5D80BD8FA7EB92C9113DEEE6F76DE250360C2752A93886957AC33657F646A5734D961D82FAE897F1889E843F8CB897EDE7B68156FF6011228B006BE5A670B8913C21500734FD6D799B691B41E02DCAD4D3498F1FB5D2CA960E295FBB764808D296BB1C1C6C16E0BB61829ED7C7D56EC7F530653A86E3F4AACBEB6296D8456B0A80B430325B2CB142EB34BF6AE4FC9B619760C6386ED045C57455A2425F76EF25E76F0563AD2CE3B858B5087C9AC27AB2700C87E8839B3EA9653C147BE9C859A38F2A5BD23C689895CFFCC1F8EBA87CF79751A990F6C69A65674339F21492228A8A67F80188D97BE3A5F526068025A98A3B6831EEFBE2A5E43A6AE0150C0C88B2A3C05923D82BFDEFE4BC9D70A317F364E2C6108EE1047EF2C845F84EF3D5909B7A07EB8714A984ED41EAE3AEBAF52CEEE9C5A0FD19EDF819376D859F9F00894E6DD425BF126DD6205E528D7E91B75A1AFA0059E5C480225C1BE725494BF3BB136897501089038E9E9CB68B0BDA2EBA88EE58187C8E12D8DF598C0DF6C5084A8000E31AC98DFDB258C7E93A338BF6DE0B9F060DBA0AE14577DC6902A6F104DCDAA4BAE9E558F02F93797F38948C24B07C830747C3376FDDE0089847709298F609EB30DAB744F801B60AAFCB4DDEE347972ABB7DF496B1B4080B1BAD521E1A8658EB3FB4BA29EEAA9FDA969B3A2555286CC6ECA1616A2364A5D6CE810FAB0C829447E785FF3E7BFD41CC8E37D52D9217C10701C7B02C584C262BC5F3B6382066D89F4D1B95DF5255381F7A4CBDA53F75CA6701D4823CCE072ACFFEC65E56D8A2111C0FADF73972914B8658B9EB91F61BF391F17E7CF1107894861264F75398B4E9192CADD9003FAF5EA22BE0525CE89383BF4A7E85C8CD7706B092CB1251000C527A25C1425B7C5C84FDF6EB162540D5709D3E647562FE9387A169A21FC6D6D58A88297D7588E617F0D85EFC4A476BEC19E0A64588190230C36B93A517BECE6E8256A3C8CF494C281F2318C4FD046876399013EFD98D6023F4257EAB14B2A62EBB74733DAC5D41809BD97989D755D6A410B5805508F172F7C1B933D2DA5617E5B03EC189E41B512DAC7DDB49F90E1873F3F5FFBB7888E9B1A0C2EA73DBC063C72BC08D1211063C71FEC37CC1B28E05AA41A3EC4BACA7750FB55314C5B12AE161AB0413D58281C8F82B77158B17FA9A08EB0ABF4BBB869B06529C321150388DAAC8BA1C2EF640944DE22BC4E47D99C3E746605E7EF79D8621E155592CEE4E21A4A02FC80983106C84872C0CF6EAB309F28540F68EE9BFF5659446BDD6BA368D40C50855F7140FCF6D6ABEF14F8A1DB771E9FE513680670B2C5B19968D8F2F60B81750E7CD04AA4C2783AE8B1B4C2DE7DF7C3B4B4D071F91575DEEAFDA32D9CE54FCA612B98AA71F235530EB5893948A55BF7A4F1016D29DDEC21DDBBD62E1920075A23C91FC7BB7B935D883435B51608982C4ACF4CA24D76BD0C514DD4012A9CBF67AACD87B72DA97A78FD598614A9A49DFA8A5FCC45DFB5990116D05F6898544E87A209C5D51A62BD206770721737995246BFFB8A25EA0630C62C0039A858BF6A0862F33154703CFF3C404C5EC5EABAF86E917EEF82F18848CC382E8082EDB3A878AF584EE1D9C70C051DA1F3D48912DA4FAEB8078E1DF45FF3C24C85ACC5AFD12526B6A82C943EF3F0CDC60EA7BC7602130C747B11B28B47C8A22FFCA4F8161096F42360C93140D867113BB0B380288D20C6CAA9FA06C861E0AD9AE81A183466034EE3F148E337E3B441104F6B22FDF2C2F8A4B065AA00A389CA4ABAF4A0AD148E16A8FBEC244B2AB0FCDA9C06679FC9FFCA3F600F362613BAC8E2B64AB9939A841093F19F3B803A61183C5A0DD4D106CFA0EB19927321601010FE1C66461C7AEF33CB823FCD2690F0DE9D9BBCB657BA398222C30C14850D6CDF14303D8480A3B5A9F38AC7F8030BA314226D4DE58C66CFE33D0DC66004AF4D96AC0CD6AE0B6ED7142657616A6D87B5C8F5191C2C364849C9F408324195EA1D50AAD714334A596B773B4C8D8EAFF7FC0000000000000000000000000000000A12171B2128D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8 - */ - public void testDilithium() + public void testKeyGen() throws IOException { - String seed = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; - String pk = "1C0EE1111B08003F28E65E8B3BDEB037CF8F221DFCDAF5950EDB38D506D85BEFD9FDE3A496F75819F0A20D0441DC7830B4AA1CB8ECFC91BA0EEC3AFB6744E477B4E6EC3FDAE75048FFEBAABEA8E822117D5787F79070EA88287CE3CD5011FD8D93AB7E8B51F26116BF9B6D21C03F88BFEC488876F4D075A142D4E784D734407511F992069353F1DB67ACF73034A468A118588062111D320E00BCFF6DC63573FCED1E96AAEBA6452E3C7ACD19181F9B814BA19D39B4BAB5496DC055426E7EA461AF55D5B9FE97F9DF7E253203C1F9E152E96D75F9D9A84F5C263EC8C250440ADC986F4E36414C703B3E05426B28B7065950DA6D0E0B2C60AC3672DB6F3C78447DB7C20915770EA6FCE81DAB5339C1D5AF82A5D3324099DF56516A07DB7C0FC64383805C65F2B02FBCFCE63E93C4BF09409F9F0F77E73DA3B0019F2057E4CD7CFF0E5745EF18C3FD766E01747A64D415FC9789ABFA62284E11C7FF05D0548D973F679559A6A3AAD77ED5132D0150C014C3EC3A395F017E7ACFE3EABFCA44910CA06FF33542ECCE6241974742357D37F5C284BF0FE1A74B50C073551372133AF2DD41E21BAFC9C590EE6EBC4ACE731EF566156CA03755DC493C137028AF3B3DE5B00BD6CB3D9A87D0151F887C6768BC6CA02A94FB2086551A0F89BA26154E9D4506AD9FAF39F5723E234E06CFDED69D4EE4146B73E5DC1E4152A2A3159D73DBC833D3D417CD5CF7FB3DC7745CEED4DC0F5B1C6D6B69C1764157EA43DF9DBB442EFA39D1D0162E87C2D30C5012FD16D869C8A1FCBB45EDCC8E1813B2B190A961F9FC86591D3ABC5388AF678FF03DA78B7CC0F6185721C0DF33CC906435225DF2611002DF120E83566532292DEA3D8ACD109A0DFFAB3B0B43012796DB5B50683FB4C2D250DAB76AAE35A48E8C8D4A5CC154759745F0A1230F6CA9DD9C99E2F80EDC83304CE01E98F6C9489529A822F90033C228315EB2FCC8DBA382ED4301E07607A5B076C725F124994F18A997D2C5BBF9A324605265108ACBF4610FA1C3374408850A0864E2B61017EBEC1FBAB89DE3AB1B93CE4918B9E2C9E3FE456758062A9F882B283318271F4B9552FCF32624A9FDAA44C65C60E2B3648BEF1F17D0B7C74869EE0B53C4A62A24845DCEA5BCBF93B92E4C26648584E33479282E6C8B1D8FE21181BD9CF75F8A961724D4C4309779F1F1B775D254F70BD1769CC7C0EDD2A95FE5C9D84B16F7C54D85CCE4C8A182810809ED81E97D074884EEDF401CCACDAEAD82C14D06B68AEA6CE14B861B0CFD16090CBBF469C5E084314C0D8D3960EA06A3426D8B3FE762E00D09BDA374F3AE2CBEDE2838FF89D81DEB3013090E44199AED604963EAF919914CE04F207AC82CD4351FEF7B2D94393066FE4D44E3CC5952E75EB6F3714058915DE0EE184D8C55300F576A8B82A863E81AF33417BD4CFC94E7A61263B39F01F6E2E70748B6E5E59CF6CA01B0028C93BBBCEBC548F987F10755BF33CA585CB41CF578DF5FFE37924E3C2C072ED1DAC9162176972971E79B62FB208F1A73BF0361E2993DCCCD3110C34D839D18DD43A5E8F0D941E99ADCF441405F32107671B2D8B2244F7BA92DCED587A210FE8FF43C616ACB5E766E6AF2CEB03599BA3DE376EB5735EF16143953D1FDDB7E9F2874B0D6083DD7EC4386AE003F51CCF2D21EF6059163C5152174423F57119D0FCE627D763D81C10AA1329F74C8D445437BA6718A33DB6E79375172B2AE3591821978D520824E2D2FF898B7F4C867FF462722BC07EADAD389A910B6F65429DA129735FE049E3ECB3889F6047CF2BD2A88D50A651B3235D2480E1DA5A35247FA76C831736399D37E8D033C1D051C9B6A99AB80B1313FA24C5C59766E6C51A38FE9F1186A767EEBD0D88001AE0246CD4EBE2C979DE82C30BBDB98B4744F11F9E639EDDD8C194D7911201A8FA745991B4D8A5709B62A21B63B9762913D36CE995C2D6B79151E8D83838CD1F38840A9417255DD166B7A3584499003FB625611404C95B960DF0DB1BCF1574B0965DBD834EE148117D5E05A7CC7CC1A865618A2BE4854DB8935CDA1E68BD8D09E72F0AC9053C882C4ABA4004A614D10505300B6176CA1F324E22E7824299F9C40755B71D82B679547F06AD48BE66D68072C9390233C933F80A14F8D4A6B0B4E1970E1ACC1BEA7F5D3BE224448F857BAB68AEFA6D8CB819B64294A12997916CDBF56E9A8D002DD065F12C61823F4FC214508232E431F0B6898475BB5DD0D7D528E840C22809AF7E15363724A613ACCFBE2B37438C159CE14CB0C98BFD499C08DAC0CF45D821CC2FA47319B6FB4CED7E5985EC8274DE09071D3C10DA5BF9E522B01CE91D66B91795D3D22C00483454275DD2BBDD7C2DCC4A167E5D7FCDBB9F6208CD4C9A485FAAEB809A7711DAC2865CED4306474B22B4448F85DF33417F3FACE1C05D42703ED313042A05DE0362740130188ECB445BB255DC76EE8443F733117F8351F17603175554FEB00B7FF54D80786F305CDE18CD5EC56EC0962A3E04482DCE3622D040D24C40F2E8A14A447659D6C561F2FFEE68F8D3DE511B23E8B172A01A3EDA4D3780E74C677244330E9AEFF019FE07BE3D33F322F9CE2214B9D9CFF99D05A59E47551432AE76F4CD4F8DD51520FFE811B4B93CD6219C81B63B1D627785C2A0FC22E3AEA86CEEE1F7FBC4EFCB46DDFBCD88A02F3B4E67C5FF2E8DC68BF16C74699BBB628902F72C3DEBC8BF5DF706D47A605A107DAA0014139CE40F0D46D8D6DC7"; - String sk = "1C0EE1111B08003F28E65E8B3BDEB037CF8F221DFCDAF5950EDB38D506D85BEF394D1695059DFF40AE256C5D5EDABFB69F5F40F37A588F50532CA408A8168AB1E64F146427543D8C36B3B65226769A22911A5A313EAC17C4ABA25284514FC6131F20FE945B7F3690C56BD99E99376378FAE71A374A7158EDB50F116DC284686535780833022316433765807578714524810173154483652641333022302614737052210781265061858507754618580548533018706647518267737733500270312878821580714026734320616250617371010311453681523024650348143708371825508406086017625831312827001718481667317861073723557447151010112110662742120835462285131388164886833510476026118315742500742440642515861365613777118478050862437064068527631150135623216841417724084830878575438508636854268450568437024007161784543800612705826206765211121483880678147555021222855231084503701364318005376837650246531507600625331251200541606324235241507731457033476564312318033365167587141304111715546812605373423882432783371222817481812013632764751028032268650876553563338104474858543012431808386438538308412704646463346461068070602375516825741152882201577858333134315582840316360106481480464368461757213631657465221517713205106646831646714728313555147332818260731554368708032843262416053205202367725828181085426785155280007282271831120868377244420548647205350861738627124677510852763340373432115424065402345080041772846273616868078152467106825545816362764180571244255708045106636115858630465207053275021822428371023852752844203300172311140215768838476231851352521084382555567411445467278546586170430758800684551353478138120800843156221466031560016368563673618080045554337312584031148042036733018271556065603440514434554851122376451064337325382338062451617081541167173200853260404371068037376070864087000352457148262203505356660372180137103710365278432824642320476423840000674364565226217665212413887347650843121701647146540387244177741376785521641117316050482604148474663803351558017351262133622227106345601657207785483272483156167834564057686734583525352081556548103205334016607423715016325334667270811118243732131154424082613775046710080261386850712837526672242308021005015520483744377116420123167107823808071011246825824018158518742085382583106675131252852765256031478162138153470422610571556744682005455051484113038302414747156272021653210303873603486751766527214217262576653612111216874845403342683544406813605031081743567506346184755758586544840762318670343367586667732075171036052737241220173887544032263062135418368155773200100365185741860214443341023755635875026188641851762415850711803541515742425854563545155707638677240017678386862588177508612360606507333506605275024724336451354552554148604216431563331655676070342677080760553063501337707701374572745128728364747780273036442310552415431163146533631211846312638837626748351386351783125814478856084801427164775364735466055660523700464031105550453648423406611175526158521573573156158778744503872054561166220446141461830006866406004737442250560104577350748702663748684802632852635811304428683261106188260700733862552715534532142573231221878655672567467472814454641577410780605613161540446347533077616250133841474266705206708125431777701522218250013173169DB8086B122701706AE49B99305EE6D016F16F9FACC1F835298B41E21664206005CEB981A35F18651CDB90E68C1F950B059F73D6D3143A1F47AA21D80A05FAF5D3A40F67148D3A89A9FDA80364D57C7B8F68058A25D08498D9A9C378C98185DB13259159CAC4769C34A08023A3388C3505406FB21C69EEC12DAC95A3C9BA61185237F0FF1E0E05F1A6F5A0C09090100665A1AD3AFB1076847B232EEEA78409BD9055DB57C1B31E28A01D09999035BDFC657A61040103ECEBDC793409733734D9342CC5A069E070C2421DDE11C49E172DBE7FEAF9DEDDFB3DA5DAA6B3DD13200B09042E144EEA951B43DA48153C1F1D5C07FCF473FA7F321E72534577C895151B46E48331DDE61DA45F8609AC59581814666E1658B49114524BA3840C6BC5596551AEF42412C8AACCDD8EF69E46380E6DEF60FD91228B99CB511D68EF6631748A0548083A215445EC54693471A831042CF41D09AF898119B0FC646E484539C8C32D5DC24F9439D33EEEA033A4081550FDB0B08923DBA5D44A1A876FE7EE4320BF02F9BE26F418F309FA11FCD0C864A7AA34115083C1EA775345AC0548C877C685EA8C91B924AF4F607EF37A0208E21309AB6D0F2F8A4EAA0451FF4A47E6F482958D81A166A6A08A6A10FC8F9ADA42B64A12B9357D598A3664E9DF13755C10FFD7177E594DFCBCFB5D11B6ADB1607445479A5DB1AD8CA6D915F89795D240CBEDFAD2539D10518E53CC450D6FC5385AD6D76B7830F13828120645E3A0A5DCDEAF15F1968E64B3B1CEAF536CAA2953D161C75528C3FA8493E0C177AE807CED37648A82C9BE8BA970296D543F6FBD6724A99A68D2F68C1FD333F9DEF8526DB7836455B313E6BC366178C9C57721601EC0335054F067B78E663A058DBDA1C12D80A392F89C0AD9E2A3B2EA17E9C9A3B14D176822EEAC5FB5FF7D4C87D76080D2D42D9AA4C951F4CAF11A244EDA711D120A2EA321D1551D86CA9265E9CD5FA9591D880E403B6844F051DC04879972C863B97C72B409C19D5EBEE8AB58C6E7B3938A68A9CAD75D80C6FFC4F22254FF4420C606AD120CC20346A7E7324E78C862E0DEE161A64F44917DB0C38C1F79C969220D202F8802D0F9D7ABFB2DE434B1C53DABB57575EEBBBF31CFB2924872FA01473B3976AEADC99699B13820FA0868F2C9FD0D352E2593273CD621B1974FFA6187FA05C4118D4517C934151C1FA34BEC3ED3639598CBA24E28229CE9FD3B1DB4969C12EE49E18B36CE2B9145AAC75428DFFA145302F41D9E3394F38D3F3C0334C4774F1E94296DE36DC6E430E4C0A537E68BDD41AF0421193B16AB1891FA836CBC367B403705ABA5D2F9F2A4C2F275EC010B2EAB84095A569DBAE4457CC2AC1CFEB1EDA43C3E2819273C487ACBEBFA0A0ED1CC4667A6F577F62DFB1BC8FEAFD86D90108E16B8B0E6C2678686C928A668BB9857FFB28DE90545CD4437DD32CCCCC6ED58FB46FBF85E0AEC0C814E536245252B8029F0A2AB44B9027A7E35A941FA113C8D82974EA22DF02D84E5328CEA83D12D399C7F0259055F4B3AD707E7B3E537B93DEA1A066BDC775FC7D1A6F0FE29DDAFA9A7DA630A467EF6CBF5CCDFFD79F1C8BB6BB3882035C73CDF7ECFFB53C712A7C7EAA59765EFA960BF21E25A6703FB304F07739FEBC63F496B13CCAA077338A0B9A976A9F0FC5742D85C4AF401A4CE341B47BE2594FF7E3019A0E064535F9D9395CC74A6A6F00E0C4E3530A7FE9310CE30B6922D04FDE0AA749CC3FDEDB4D8708C1F6968BBEDDDD5833B299D79D61428180099B0A946A5D79085DF7F872CBDD219E6B8EF8B8AB5C1A149E6E15EF2828654FABEC249AFAAC4DC0B3B542334162FB09800B6C36CC90F2A106558BAE2198FA7D1E2D730DE46E355AEA93248E53AB21B518EC99D5F3B021196A0F614A46B9475621234733A28A465CC5A7FD432C3625812AABBB42D2D9CBEF16CBED9367202B02894D06BB801BDA8472B9918B7D724E36557DBE6B7633A5FD22D0E336E5557AFC018C812E9E6A35BFD8C60AB382E14FF51142B2D2C75A767F32413BA38487558F9345CBE6FD1D6B78C2E622F3B976230F99D6CBAF0BBD14949510A52644EF3F3078865037A1C10F47B59546699E1BD539C7DDCC03F71A0158EA9F0178E187BB6D49440DF2B10630FBE2FEB5097E47F285711CA6F835A10D3AA75C03C4184C03EF3075D49DCB2177ABD53AD7399D290EA691D647329056340E8C836E9750FD881DCE309D309A95B82492D4BDC15ECF8C7F5D3B9DD275548512DB5EF80CD409ED32B5148B82BF240A7DC72A18523D808B7A4F9E254799E17278FA88DAEBC944632E83F8609D681AB463513023D67CD51B153F0962912DD64AB8F6529DC22AA89E572A7F89CB97A8F4509319D223BB29974951716FD3177140A31EA20048BAF0FCA230CEF21967ABD83309A4FF7E35E88784DCA77AC079020EC0CA6DDEFBCBB7E317329314665D7C51F631F681B600364E47574F252BAD6396B3F5B17ADC220966A93CE8F315A2F83068D2EA06952E6EBD802473A2264EFA405B3E491BE776C50406E1150C56B894CF864546B0C7A65E3F1A2BEFEF2A9990BAFE70B6CA9F91A8F3DD21307A39A2AFBDFBDE9B7CA3D7828B13F49DECD729C0039E94EBB7B4BDA09B3505529A12CB1E2FD79B9E5087CD7C3BC05F7CFFBBA932A7BFF8E67555FEE0304D890313F86E1892569E2D6F14A89938717AAA3A32AD1167150299C21820ABD70FF902B004C6DE91C1C0B40706442AF531EC490B012750BCB4877935A7E54031702BB988EB3F92914CDBD42979AD7D27B2233EC1279D05493B12D3F5FBB7757536021B5F4CD932B480E40CBAE50D232E0A2EFFE0E8CB58808669199F0830872F369738682F846F6DEAD095BFFCD670A4A9CD142396C58506EA7A68B21ABDCC19CCC06F6DA55C885A855C456680CD4477BCA2BBA9153DCAEE682655B74ECA6F7E44C3BFE1E2D457491ED1BC64E1CF6CE18CF44A0166D1B244480882C1B35CEA703158E18C7EC6E0CF827D5504A45AE61152309BC8A18A52C0E7699A87C4E31C6911A8305351555B2971C94602B70E670AA30B90734EC1DAAD03A30A96F5847C5C3F7973CF4572D166C51D1E94A50A4C1C894A205F8ECB34E80F84CA8DC31A429D5600596179D1093E2A389CCFE9C0402EE49551710FFC25BDBE478F39F2063F31F75D7432ECA1C59EBD8F46D86A092DB12F810FA911C20D4CC1E425C543DC64577E44D84F422D9661E3D35921350D6F7099C5425E509E1458A0500AE5EB4CC6BB50626D0130F09361717A95919AED35592FA4ABE7B2BD4F999422151E63D4ED00CC751A5867977F15E482EFA01E5CCC44064F5B9FFE29AFFE626C4D5170ADA1DF027AB4179608C4093CCE2C409308CD898371A49FBEA2A2F2BA13BDEBAC1F4159F4B0368FB21D70A9D7931D7EFF934E6C544E13B7B73D465576C6E81FD6D5FD94393E80242F9420ACC0ED353EF18CA070F5E9A285AC4BCBAB19A38356F557B070E17AE5CF1F1BED42601E89C8C4C"; + String[] files = new String[]{ + "keyGen_ML-DSA-44.txt", + "keyGen_ML-DSA-65.txt", + "keyGen_ML-DSA-87.txt", + }; - NISTSecureRandom random = new NISTSecureRandom(Hex.decode(seed), null); + DilithiumParameters[] params = new DilithiumParameters[]{ + DilithiumParameters.dilithium2, + DilithiumParameters.dilithium3, + DilithiumParameters.dilithium5, + }; - DilithiumKeyPairGenerator keyGen = new DilithiumKeyPairGenerator(); + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; - keyGen.init(new DilithiumKeyGenerationParameters(random, DilithiumParameters.dilithium3)); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); + String line = null; + HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); - assertTrue(Arrays.areEqual(Hex.decode(sk), ((DilithiumPrivateKeyParameters)keyPair.getPrivate()).getEncoded())); - DilithiumPublicKeyParameters dPub = (DilithiumPublicKeyParameters)keyPair.getPublic(); - assertTrue(Arrays.areEqual(Hex.decode(pk), dPub.getEncoded())); - } + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] seed = Hex.decode((String)buf.get("seed")); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); - public void testRNG() - { - String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; - byte[] seed = Hex.decode(temp); + DilithiumParameters parameters = params[fileIndex]; - NISTSecureRandom r = new NISTSecureRandom(seed, null); + DilithiumKeyPairGenerator kpGen = new DilithiumKeyPairGenerator(); + DilithiumKeyGenerationParameters genParam = new DilithiumKeyGenerationParameters(new SecureRandom(), parameters); + // + // Generate keys and test. + // + kpGen.init(genParam); + AsymmetricCipherKeyPair kp = kpGen.internalGenerateKeyPair(seed); - String testBytesString = "7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2D"; - byte[] testBytes = Hex.decode(testBytesString); + DilithiumPublicKeyParameters pubParams = (DilithiumPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((DilithiumPublicKeyParameters)kp.getPublic())); + DilithiumPrivateKeyParameters privParams = (DilithiumPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((DilithiumPrivateKeyParameters)kp.getPrivate())); - byte[] randBytes = new byte[testBytes.length]; - r.nextBytes(randBytes); + assertTrue(name + ": public key", Arrays.areEqual(pk, pubParams.getEncoded())); + assertTrue(name + ": secret key", Arrays.areEqual(sk, privParams.getEncoded())); - assertTrue(Arrays.areEqual(randBytes, testBytes)); - } + } + buf.clear(); - public void testVectors() - throws Exception + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + // System.out.println("testing successful!"); + } + } + public void testSigGen() throws IOException { String[] files = new String[]{ - "PQCsignKAT_Dilithium2.rsp", - "PQCsignKAT_Dilithium3.rsp", - "PQCsignKAT_Dilithium5.rsp", + "sigGen_ML-DSA-44.txt", + "sigGen_ML-DSA-65.txt", + "sigGen_ML-DSA-87.txt", }; - DilithiumParameters[] parameters = new DilithiumParameters[]{ - DilithiumParameters.dilithium2, - DilithiumParameters.dilithium3, - DilithiumParameters.dilithium5, + DilithiumParameters[] params = new DilithiumParameters[]{ + DilithiumParameters.dilithium2, + DilithiumParameters.dilithium3, + DilithiumParameters.dilithium5, }; - TestSampler sampler = new TestSampler(); - for (int fileindex = 0; fileindex < files.length; fileindex++) + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) { - String name = files[fileindex]; - // System.out.println("testing: " + name); - InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium", name); + String name = files[fileIndex]; + + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium/acvp", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); @@ -108,110 +137,103 @@ public void testVectors() { if (buf.size() > 0) { - String count = (String)buf.get("count"); - if (sampler.skipTest(count)) + boolean deterministic = !buf.containsKey("rnd"); + byte[] sk = Hex.decode((String)buf.get("sk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + byte[] rnd = null; + if(!deterministic) { - continue; + rnd = Hex.decode((String)buf.get("rnd")); } - // System.out.println("test case: " + count); - byte[] seed = Hex.decode((String)buf.get("seed")); // seed for Dilithium secure random - byte[] pk = Hex.decode((String)buf.get("pk")); // public key - byte[] sk = Hex.decode((String)buf.get("sk")); // private key - byte[] sm = Hex.decode((String)buf.get("sm")); // signed message - int sm_len = Integer.parseInt((String)buf.get("smlen")); - byte[] msg = Hex.decode((String)buf.get("msg")); // message - int m_len = Integer.parseInt((String)buf.get("mlen")); + DilithiumParameters parameters = params[fileIndex]; - NISTSecureRandom random = new NISTSecureRandom(seed, null); + DilithiumPrivateKeyParameters privParams = new DilithiumPrivateKeyParameters(parameters, sk, null); - // keygen - DilithiumKeyGenerationParameters kparam = new DilithiumKeyGenerationParameters(random, parameters[fileindex]); - DilithiumKeyPairGenerator kpg = new DilithiumKeyPairGenerator(); - kpg.init(kparam); + // sign + DilithiumSigner signer = new DilithiumSigner(); - AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); + signer.init(true, privParams); + byte[] sigGenerated; + if(!deterministic) + { + sigGenerated = signer.internalGenerateSignature(message, rnd); + } + else + { + sigGenerated = signer.generateSignature(message); + } + assertTrue(Arrays.areEqual(sigGenerated, signature)); + } + buf.clear(); - DilithiumPublicKeyParameters pubParams = (DilithiumPublicKeyParameters)PublicKeyFactory.createKey( - SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((DilithiumPublicKeyParameters)kp.getPublic())); - DilithiumPrivateKeyParameters privParams = (DilithiumPrivateKeyParameters)PrivateKeyFactory.createKey( - PrivateKeyInfoFactory.createPrivateKeyInfo((DilithiumPrivateKeyParameters)kp.getPrivate())); + continue; + } - assertTrue(name + " " + count + " public key", Arrays.areEqual(pk, pubParams.getEncoded())); - assertTrue(name + " " + count + " secret key", Arrays.areEqual(sk, privParams.getEncoded())); + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + // System.out.println("testing successful!"); + } + } + public void testSigVer() throws IOException + { + String[] files = new String[]{ + "sigVer_ML-DSA-44.txt", + "sigVer_ML-DSA-65.txt", + "sigVer_ML-DSA-87.txt", + }; - // sign - DilithiumSigner signer = new DilithiumSigner(); - DilithiumPrivateKeyParameters skparam = (DilithiumPrivateKeyParameters)kp.getPrivate(); + DilithiumParameters[] params = new DilithiumParameters[]{ + DilithiumParameters.dilithium2, + DilithiumParameters.dilithium3, + DilithiumParameters.dilithium5, + }; - signer.init(true, skparam); + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean testPassed = TestUtils.parseBoolean((String)buf.get("testPassed")); + String reason = (String)buf.get("reason"); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + + DilithiumParameters parameters = params[fileIndex]; + + DilithiumPublicKeyParameters pubParams = new DilithiumPublicKeyParameters(parameters, pk); + DilithiumPrivateKeyParameters privParams = new DilithiumPrivateKeyParameters(parameters, sk, null); - byte[] sigGenerated = signer.generateSignature(msg); - byte[] attachedSig = Arrays.concatenate(sigGenerated, msg); - // verify DilithiumSigner verifier = new DilithiumSigner(); - DilithiumPublicKeyParameters pkparam = pubParams; - verifier.init(false, pkparam); - - boolean vrfyrespass = verifier.verifySignature(msg, sigGenerated); - sigGenerated[3]++; // changing the signature by 1 byte should cause it to fail - boolean vrfyresfail = verifier.verifySignature(msg, sigGenerated); - - // print results - /* - // System.out.println("--Keygen"); - boolean kgenpass = true; - if (!Arrays.areEqual(respk, pk)) { - // System.out.println(" == Keygen: pk do not match"); - kgenpass = false; - } - if (!Arrays.areEqual(ressk, sk)) { - // System.out.println(" == Keygen: sk do not match"); - kgenpass = false; - } - if (kgenpass) { - // System.out.println(" ++ Keygen pass"); - } else { - // System.out.println(" == Keygen failed"); - return; - } - - // System.out.println("--Sign"); - boolean spass = true; - if (!Arrays.areEqual(ressm, sm)) { - // System.out.println(" == Sign: signature do not match"); - spass = false; - } - if (spass) { - // System.out.println(" ++ Sign pass"); - } else { - // System.out.println(" == Sign failed"); - return; - } - - // System.out.println("--Verify"); - if (vrfyrespass && !vrfyresfail) { - // System.out.println(" ++ Verify pass"); - } else { - // System.out.println(" == Verify failed"); - return; - } - */ - // AssertTrue - - //sign - // // System.out.println("attached Sig = "); - // Helper.printByteArray(attachedSig); - // // System.out.println("sm = "); - // Helper.printByteArray(sm); - - assertTrue(name + " " + count + " signature", Arrays.areEqual(attachedSig, sm)); - - //verify - assertTrue(name + " " + count + " verify failed when should pass", vrfyrespass); - assertFalse(name + " " + count + " verify passed when should fail", vrfyresfail); + verifier.init(false, pubParams); + boolean ver = verifier.verifySignature(message, signature); + assertEquals("expected " + testPassed + " " + reason, ver, testPassed); } buf.clear(); @@ -223,13 +245,206 @@ public void testVectors() { buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); } - - } // System.out.println("testing successful!"); } } + public void testDilithium() + { + String seed = "70CEFB9AED5B68E018B079DA8284B9D5CAD5499ED9C265FF73588005D85C225C"; + String pk = "D2FD03F3A1B7F635AF9F34D580A98F524C735BD5BA2355DC6E035BD21765580CBB111923F194A7CC8A7BB2EBC5C0E71AA637CC800E6103B850A539B2A39E1B6D713E5DB8314C9AE1F8BF8A38F06AFB9D73B161B0FFE3A4891706AE26D54FFB496DF8DC0F1983509500C9ABBD28E59B3FCDABBDADABD45EC31499378BDE849E7C1F19B7044D67E05106D7136D95380D5605D4465D877557065DF0A75D3C28542F40FEED42EC7E280637B083D988BCA5F6394E02396C4676184FB63318DAFAF5BBDDE00E308FE84019C2340A3F3E1C0865624970711283356AE14BD6B94D1C9AE188DE1A8A2CA824A8EAE2FE6AFB38D83A2D99996AB21FE3E84C0BE6B6DA08879B677374FA7C691B13D40FA9D4CC26B2288D5A8C9A43724381004D61B0D57FF400314C8E30EE796AF10F7EE21BF13D08180465ABC72EDDB080C6A07184E3EEDC47C19AA7F09D1F3309E183A2BD9B0573DDE474A81BA4F78D0C523D0C04F90060FD571A35C037E079C5E210D7390DF568F2E2F03CE44420C82F3FE69EB9B48EE90962D6B0F24440648F71EDB241EE6566FC1A64CABF66BE6FECBCB1387C82A7BC202D9E367998E2A291AF0CD1570677FE8D63A3285A2EA6EB29AF9DC1AEC1C36C4706B12BAA20839692F286A6E0321468F7479345C4D52FBDB2F06725B554B89E2492612681ACEBC6C7BADA9225818DBC35D64C22C48BFF80A730D0716DFAC99DFD5B8992611D0C93EE90BDB260022AFE25D913E06EFFB59CB1F8A60CBFA5AB2F459A16F467E989525E0A37EBE56E833FDE55DB9D1530ADCF45846DF281E47CAA1E0A27EFDE2107D354CEA0F6A454692F04CD838EBDD46E191E5D9C11839A2C3F488A4FC7CD265A7B5D32B08CBDBFAB9D2CCD76222C8EE37DDCBD2AA063ED861473A6454CAEA377850B1A2B9DDBBCB374FAB5B12F351C8E5888872E5CD1F60A4FAE1FF837D192C22BEB41EE6FA392FCDF4550FF46B5CE906D017EF3077DF132300D8BBFA9BB03C75E79E2F04C284AD06A44399649C3E2A2A8D1EFE9B7A4E0C271047AB75908BFF7DF9E30ECA547745BAE23A86FF9A8B58C2538B88B866401076902DC5F0BD761687B49EAFE36D350CBEDFDD36C121CF23786BFCF7E47076496EAB6BBDA774049C2EBABE2DE99C4C24F2DB73684015B373977496760CF9AC23D8B623133DB2DE10D73FA6AD1C6DAC8434F28C6E251CE7293CFF3F3B61EFCB5A435123670F29846A13DF3EE712604461F1BAB8F4EBC836DE058978AE734396A98081B35CC98188A86949C99270D4709854C5B35B17F48A373134C814CC8A0F3E2FA807F2A918530907864778282D75E03A41B2504EED816A417A3AC6BA16080C39B7310192002A728F7F20395009A9E16767CE1971F5DE7D229A50613369E4382045A8E81901F4DBA8102F3D413FE35B326A874F233B719A7137600D35D33AEB6B7259624083AA968730C8F78292AD28F14EEABE660835984FE69EF23DEC8C327C0EB0B882D587E1EC433DA85C9FD1E0A34994DEA240C854452D18C30F496E49EC904B602E0F5062EDCDA03280A53B4313574CC2C0D5471BC9613BDFD6641F5BD127BAB5B5EB3D499A33114048220E819F8EE12CA922C8F17D9C9F51AD5BD6883B10E6AA2483BA49DC547DA7686151344F4E9099B38E430B5226B059832CF03DB48FB02DBA4E61593DC4576360491890E53EC0E6AC73CF32B25D823B38456E286505A541E5AEEE96B1914F5F76687CE2B0160227ABED77993594BCD831366206D75714082F1C46F1F4439AC81A57AF31C81C555307A070FFA94E0479B784BBD88A60CD4C7CFD94E6AFE02F6B21F72AF0DCD6609D40C965C14E5F2389183E53DE930F7DE1D44215CF49144844E8B87F78A7F132AEFE22BE80B4E3A05EE3A68CCF609EF44047402E4493046E6F9C767FF8A75E28B3CE077FDE7E7EED313B5BF7E460127CA8182E9BC794C0DFA730FB920080575A751B5CAEC85A109B4422BA266743F0D032BDA8F1CA6248CDB917530DF1302A5F8C18DC642D52478C98C12A3F16EF2B62B4F59EA1BB58DE7B65B3C7153CE6DA5E4950746F80E087A0E3586D097791BF36DEF865D68591D39D0903773EEA962147F34704138B54DF7924CDD8C333DB5E1A409CCB2B34E2C3C8C7FDD3FD8D012CBF382AAA85E83A12F235A2D147D035B7B28B34B6F57949F322482A7D4D3B15045C420D5ADDC7F0E69B4DC1CBA58B01D872480B06A260D827D891B13C4C5CA50C748DE3C771BE61E9AA170165CB01F4BF5DA27A7791D3AD3F6267B4CB4E61B28FA1708418D932DFC4161880C5D3B17A9663A9061FA8F1804315850FE4E7306C882B38227E867F80872CDC1944D472615EA4900EF7D270B881D4130F56C5CC980D92A47ADA6657EB6F37A385D2D8CC993E1442EB05281853636991E34AADC68954D04E7ADEF76BF880F059B0CBB55D915A4B123E2F1339A073CBFBC409BEFF6400AE096D5AE18EC42CFFAD5B4980FA35BF03413ADB5D7E6876AC355D1C9ED70CA2B973954D12B3CDD76AC6835DB96003ED8C4E288B71FD77DBAA7635720E12AE0A317DE808C664E317F55275791F3245CA4FE5D4D41077FC150A6E403D5A208E46EADBE8F2CFB8AF472F4A0CEAC015219478E6B86C958CF86525B7485C1734C7EF00E90683FFF5DBD0A7D413A855021026A1B32013A4616CBCD3700ACBC705BE3EFBA625C69A025267BCE9D135E3F5B5CC8C43956407E84B6663103E29C242035551AE797F56C6374BE0C798C0CF398F1ED"; + String sk = "D2FD03F3A1B7F635AF9F34D580A98F524C735BD5BA2355DC6E035BD21765580CE38D1C14F6467C35A9F380D27DE61F7C75031569EA2EC8260EEE9105261B7FE160C91344B0C6764C204E5B8D424650BEC06B9E2E625AF07E23F4950CA24FB4D6EC2C8B3A717C9311EB87279FE25E311F48B8256501F6463412B50DBC89A869BA2241112648400738730212442544575483725033356258423201621183610245665648356120845260685045655512724747212125402221428117650306426152134325243382121135623332074786223150837084264345645148311486246686743371366726014707721161588558387183806701657870647785600288534846622583548804744012574371077544387121142208887223588746148553716773822822741403577328718380781434875207647401607561060861322146156542670820841073130361028650452612166833552584735354526517106000385777812426804146432667410603554128333725230677821516317300087526584634638808846451112405321011181864782241003855754210468343733880078343787413576232688065864853483551585074460588700772013100875488142084166115605685115808058863018286131417220168171786585310622852822615043142885431780580115045688233663636406515244767064536422686750635413347851217808387655142313887566205174085281417213812608124414575018287101002132557042172427861117005304772132030216744315771455710541665741524024371512055116783678252533566424613702232740007068187175780286801721004275522864253158176308640831143305382735303723568704541157314123164326663562151508210302338172127102314227577283771627506887214187313030150715862866288868603270146172271385381703388681378810486573016523140830756821032312850065081630675766511601417121255564811411328826207476424482324775326081758115637483551478685666681732021367522746683445700666477204722285687124702480702542301257137367536005268153335820613732408717615224260185343116457761761566876606554781033631421832160155580423842031312343625273082812547513544126735001001838574424013036127812626811887435120627127515610222281118141666638208675561240065461127440345858781007852572885722222550840041260836462878467805022820771360751443687864313877737355412700540708286880045383432281006435486766501775761275438162403343453887216614704841431466587845820225457315213203024880801371255432720568652468040616835054533737272220680825508472867422361680075518121784448115645071105815511010471621075861187800527264521743234076486730776364875131638468745363842354661048363385214842038251103357468016433402070353221275733465833387438517503660880258758088316360182132261568741110331413053416726535501334808710264868845271442358803557705484287055888683862521827261177885176773005771117851106563570287401340012653451205467518807033356622620070232687726311133333814170622861514731302546511761580741613737061400548877756777665316726666887643583104875706764700436358605203442736486123721610624208608323540355557300610365342714158662558016531018261135468246132583477050060156021168545303687336418886334252015833423288568177555148481201581385041471835707545554552827313602123268321382587028585344867273428418220883610214161712415748852510260736761266172132360325411011226660161632642605186351585131425384566627833354507646508025434157357825430282384745701567517747803152750000947BCA93C27D584E2C66EAC9C7640C1CA217EEF66DABBCB260B4C34300FA051357820F57392544982FD11057DE233E6D2DD84972A7E47D4DBA99BC30CF8F2AD5A2C0243195ED2730FFA92D227D153095972D4B3447FFAC45A23EB41CBC87CDD1250A8A478B0F7A1D5B39AA2206E48645584FE7BF7A13168F482765E57BB924AC6D9A11369F4A6AFFCD169B7D75129B35D5134A31761BB8355AEEED27E201A06313013E307A01A73AEA7955C0578C8C5E5A1A2D2FA4593FACD904C62040BDB9F329933536BF8D81C4256BAAE8723FD4DC66BB5E7F9CA49031A193ECECBB5DC390EC6D5513C79A052B3FD43612FB7375315D8091F79BAB1318F17854561BC93AE0E5CD6D131E562C8114810C939AE563AA10B47CE4484317F34ABD02D0CCAD58DD29BCF657BBD9254B01CA9726091938ED32054B37DD617240F4434C1A4A8711AA3A399A8A5388330B7059ECCBB6B1B9CF7187ADF10B0C9171D3C0F6E2D460A419247672E3B9FEA2C95910BF2FB6A5D61F257453B07AFB64B0BA2758BCD735751F2D53515E236FE8A5B4393B80BF06DF97BDC6380087E6AA8DDE6E098111A7343FCDD1E903708E637EBF28323CDA6B9405810EDCFB3691149ECF224C50F8DF92A94AA4770A0E91466194BB0E27BF1CABF16ADFD351220033F76F5925557BCF9634E9461359621D80B4BBAD7E2A6E432DC43B126CA42AB88AA88F0A84AF58029C99A0248F0C454071F35B831FED1254D6F4E2720485786215F7C7F0C4ED15FA853CD3AA07259B39240A82135C2923A72B876FABB3F0F2C09613DE39D459A07C14E7BA437D8041491FCEC1433404BAD1DA9EE9471E17CB691B2A353710C9FFA4E5178112027764EB7DE809C3E1F1FA4178A5D4DC9EE27857EFF26B91711FC144D5A775B8B50D5DB939BA3207680C242FC821947F934C8DAEE203563D28606BE624A32901932DAE85712AF6C8016026927E9B8129574BE3CB1E95332B052707AC8AA8F435E88B7E568D4987C6AC0E902B0609A02D91B3F5FD3FD901DDD0DB9873BD7C71ED921D4577A78C4FCC9BF075203D38F5E76E74F277484E057B6189004131B0C9B1A155294D1CD3D5208E266901D7D314FACCE7E2AA584583A11E4D7C21B94A32E508EDDBBD7A65AA86B4FDFA6BC285D4CFF53926C7173FBE1F89CC303234B878C6B8101F58AC8D3E5E1BF5AB6B26297CC97B95954AABDB25BE008A3F47E56487B00D3DEDA890D92C83957FEAC6B8291AF65959E1D1FCA3BD196E9FC9E67E0607094822E5B4191DB96824B9F03F2EF57F5238BA7E1E84ED55B7DFF3D6C2C1273692A9A19272166130DB89FC67DC94DB614E3E82BA3A3512B012D51FB486B5A3150B78E724E2A12DE07D8671FBA2DA7FD5D147208FC3AF653E6520FC40871AF2177E65CBD0EAF304217B367A665F224CAEDFE93006AC1E14BCD67A88D171F3D8F3E358A71926BA3E5C239A531263EC9437BF2A033B8B55B2C0CB6E7E97316E22DF77CAD910D20EECE1C50910A5CC32ADAB09377550F92D5BB1F4C07F4A2822338E2CFF5348DF77CF8EF8E6657DED1E0CE058E3CCFBF39B3F166E303D33C3556C9AC8ECB3DF7C74AB36D0F2794441BA9808827B578FB5C29E494E21539AD3AB2B41BF161D7F69589D4524C54C89B486F75D252F541CC63B9E706D64A1289A2306C595363CB6FBEF0A1B5B17AB5B1794BF27036F64EAF0BD430DD58D80010CCDADA4A5A3A1E41A6FBF129D73779A37AE5C8D6841A9993C51E364E04FAC8E25A4E6872F6C860FA265C1C4426AD9C21D26DA8C278546ADCD831F2B8B26D4E1F670623D95C8362DA662D1FF0AB687503F328DE095810EDE12B49EAD1533519558C1E940B46E4EDB027BE9DA2039B25DCF7357E19E5416AE268C14FB3A8BABCB3D23F70CC9D59681C5D833AC22E653D86E22CE822540755D8D243C15213D076C6B26436DDC07C7E001347B0CB8783DFEFEDF275FEC4792686734007F0FF8540811C2AFE6CA151420532FA5526A1074C3D789F2932DE42E3ACFBF94760F426D96CF033FA49E2F458F9A9C2E71DACFE009DD9C3F3C8AB3282D6F383B981C82D6364F0E4BDB2AF6A95BA61F474150CAD7233F8903DF972DBB0328C0CB9D0CCBEF883D2E6ADD180ECA1B662FC1D2DBBDDB3634219E1EFF38B1E52875356C03EADE942055F483504BBBCB4302A417CF6D328ED793B1A3C0969B7B3418F50AB39F83C5666C90E38356F7F9D494A6DCB63D67C34E3D14A4E15596497926C8568D8EC3DBD9C2E82C385BCFB8D9674863BD4FBF1757DB447BF804AE950147C91FBF9AA17891044CCAA73B45528597462CED751D015EBBA9E2B7CDCBE6DC05AA9EAE0C86848A3475BB1C5744F5903EE4A842A469CC181271F245AD70D02A4837863B296B4ADB4E8D03D82B64AA11DD31CDF21EDF1DFE3276C4DBC877E35B15FB2835EC3A1C453168A38CA8E563CF3E9A00736CD5CFBD2841D10F94AD55799C2927E5461B28BAC5174D0CE3F8F7CD7609FBC8DA0C38CC21695CEDAD12F8D2E64951A8996E510D6D52797C5BA0EB4AFA6BF2CC43DA09DE3179E899BD7188B32A98A499D372F3707CED479B0981CB50C0C0539CF7E3100B720E466652A4F499C2BA3A17F5232268730B962BC572C0DE96E8C9E28F7E3532C2224196AA9E27688DD050D7CB7854FB3C35F9C62EFB10DA84833F29BB1BE5EF3B533638EEF743D8119DDC290BDF08B6F0F9E4E1E13446C53ED69805DA26908A15DF1C48E009EC1253BD5A5898EBB5121CC24904C8B10E24E680E565985076FDA11D13FFDFA4DB28AC9F0AEA2F81FD7ED4DCA8D3B2E3848B4D6046F6E0DE3A4F683F25E0605E84B36F483C404EF899CB3FCCBE8CB2A6F0A7E10B1948CD4F93F181555F661D31D426808BBF9F66FD60D649269CA3FE991B22428C37AD2A08680F747CC0360CCD373DC6A9F43A66470E014E72B3D8C38E020442D8AAB974E6049374145B04CB7F3044AAC1EFDAB2A18BB464D4F2F2D8143974C95EEE856D59EC00288ED43FF5CC8803006C995514A2CC9CA622B61BCD75EC51C202A917105B4A4BED1B80146831DCED07EFD2ED25739F54096911B150D3077CCD731A0361682725D53803F8FCEAA83919291EDB4493EC84CCE1D0F82A679236EAD1002AE8018CAC9FDBD246FF093D803C0DE3326A57907B0DD6B01D081458C75728C600829928890A56AAAFEFCF7423B70A6D86B415B8358DD044ABEE00B9C9795FC8F61A64686DF5F876A8F33061599AE830F7EB4C4BFF875F4A936C403C5D160DE5D33CAEE40FB718DDA4478AC6F51C59C2155254BD77671118411E2609D000306FC9507004A31E8957EA40C2564B83C3ABB71A87C11BD18D7891C449DBBE79B4A4FB048307CE0E812B2C68ECAB77FD1111526AB0817306CEBCB0497C552431CE15E4AB52283F679480D69DDDE1F2579CFDBE0BCA95FC5B2DB0C5CC76A31950F5116AAE5F02D46710E4257A75FDEDF2F47CE37C203E7F24D3C9179713C5D807C296149A75CCB444F0C6F6ABDD2DBB2985FE267482858A1E"; + + SecureRandom random = new SecureRandom(); + + DilithiumKeyPairGenerator keyGen = new DilithiumKeyPairGenerator(); + + keyGen.init(new DilithiumKeyGenerationParameters(random, DilithiumParameters.dilithium3)); + + AsymmetricCipherKeyPair keyPair = keyGen.internalGenerateKeyPair(Hex.decode(seed)); + + assertTrue(Arrays.areEqual(Hex.decode(sk), ((DilithiumPrivateKeyParameters)keyPair.getPrivate()).getEncoded())); + DilithiumPublicKeyParameters dPub = (DilithiumPublicKeyParameters)keyPair.getPublic(); + assertTrue(Arrays.areEqual(Hex.decode(pk), dPub.getEncoded())); + } + + public void testRNG() + { + String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; + byte[] seed = Hex.decode(temp); + + NISTSecureRandom r = new NISTSecureRandom(seed, null); + + String testBytesString = "7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2D"; + byte[] testBytes = Hex.decode(testBytesString); + + byte[] randBytes = new byte[testBytes.length]; + r.nextBytes(randBytes); + + assertTrue(Arrays.areEqual(randBytes, testBytes)); + } + + public void testVectors() + throws Exception + { + //Disabled OLD KATs + +// String[] files = new String[]{ +// "PQCsignKAT_Dilithium2.rsp", +// "PQCsignKAT_Dilithium3.rsp", +// "PQCsignKAT_Dilithium5.rsp", +// }; +// +// DilithiumParameters[] parameters = new DilithiumParameters[]{ +// DilithiumParameters.dilithium2, +// DilithiumParameters.dilithium3, +// DilithiumParameters.dilithium5, +// }; +// +// TestSampler sampler = new TestSampler(); +// for (int fileindex = 0; fileindex < files.length; fileindex++) +// { +// String name = files[fileindex]; +// // System.out.println("testing: " + name); +// InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium", name); +// BufferedReader bin = new BufferedReader(new InputStreamReader(src)); +// String line = null; +// HashMap buf = new HashMap(); +// while ((line = bin.readLine()) != null) +// { +// line = line.trim(); +// +// if (line.startsWith("#")) +// { +// continue; +// } +// if (line.length() == 0) +// { +// if (buf.size() > 0) +// { +// String count = (String)buf.get("count"); +// if (sampler.skipTest(count)) +// { +// continue; +// } +// // System.out.println("test case: " + count); +// +// byte[] seed = Hex.decode((String)buf.get("seed")); // seed for Dilithium secure random +// byte[] pk = Hex.decode((String)buf.get("pk")); // public key +// byte[] sk = Hex.decode((String)buf.get("sk")); // private key +// byte[] sm = Hex.decode((String)buf.get("sm")); // signed message +// int sm_len = Integer.parseInt((String)buf.get("smlen")); +// byte[] msg = Hex.decode((String)buf.get("msg")); // message +// int m_len = Integer.parseInt((String)buf.get("mlen")); +// +// NISTSecureRandom random = new NISTSecureRandom(seed, null); +// +// // keygen +// DilithiumKeyGenerationParameters kparam = new DilithiumKeyGenerationParameters(random, parameters[fileindex]); +// DilithiumKeyPairGenerator kpg = new DilithiumKeyPairGenerator(); +// kpg.init(kparam); +// +// AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); +// +// DilithiumPublicKeyParameters pubParams = (DilithiumPublicKeyParameters)PublicKeyFactory.createKey( +// SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((DilithiumPublicKeyParameters)kp.getPublic())); +// DilithiumPrivateKeyParameters privParams = (DilithiumPrivateKeyParameters)PrivateKeyFactory.createKey( +// PrivateKeyInfoFactory.createPrivateKeyInfo((DilithiumPrivateKeyParameters)kp.getPrivate())); +// +// assertTrue(name + " " + count + " public key", Arrays.areEqual(pk, pubParams.getEncoded())); +// assertTrue(name + " " + count + " secret key", Arrays.areEqual(sk, privParams.getEncoded())); +// +// // sign +// DilithiumSigner signer = new DilithiumSigner(); +// DilithiumPrivateKeyParameters skparam = (DilithiumPrivateKeyParameters)kp.getPrivate(); +// +// signer.init(true, skparam); +// +// byte[] sigGenerated = signer.generateSignature(msg); +// byte[] attachedSig = Arrays.concatenate(sigGenerated, msg); +// +// // verify +// DilithiumSigner verifier = new DilithiumSigner(); +// DilithiumPublicKeyParameters pkparam = pubParams; +// verifier.init(false, pkparam); +// +// boolean vrfyrespass = verifier.verifySignature(msg, sigGenerated); +// sigGenerated[3]++; // changing the signature by 1 byte should cause it to fail +// boolean vrfyresfail = verifier.verifySignature(msg, sigGenerated); +// +// // print results +// /* +// // System.out.println("--Keygen"); +// boolean kgenpass = true; +// if (!Arrays.areEqual(respk, pk)) { +// // System.out.println(" == Keygen: pk do not match"); +// kgenpass = false; +// } +// if (!Arrays.areEqual(ressk, sk)) { +// // System.out.println(" == Keygen: sk do not match"); +// kgenpass = false; +// } +// if (kgenpass) { +// // System.out.println(" ++ Keygen pass"); +// } else { +// // System.out.println(" == Keygen failed"); +// return; +// } +// +// // System.out.println("--Sign"); +// boolean spass = true; +// if (!Arrays.areEqual(ressm, sm)) { +// // System.out.println(" == Sign: signature do not match"); +// spass = false; +// } +// if (spass) { +// // System.out.println(" ++ Sign pass"); +// } else { +// // System.out.println(" == Sign failed"); +// return; +// } +// +// // System.out.println("--Verify"); +// if (vrfyrespass && !vrfyresfail) { +// // System.out.println(" ++ Verify pass"); +// } else { +// // System.out.println(" == Verify failed"); +// return; +// } +// */ +// // AssertTrue +// +// //sign +// // // System.out.println("attached Sig = "); +// // Helper.printByteArray(attachedSig); +// // // System.out.println("sm = "); +// // Helper.printByteArray(sm); +// +// assertTrue(name + " " + count + " signature", Arrays.areEqual(attachedSig, sm)); +// +// //verify +// assertTrue(name + " " + count + " verify failed when should pass", vrfyrespass); +// assertFalse(name + " " + count + " verify passed when should fail", vrfyresfail); +// +// } +// buf.clear(); +// +// continue; +// } +// +// int a = line.indexOf("="); +// if (a > -1) +// { +// buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); +// } +// +// +// } +// // System.out.println("testing successful!"); +// } + } + public void testDilithiumRandom() { byte[] msg = Strings.toByteArray("Hello World!"); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsKyberTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsKyberTest.java deleted file mode 100644 index 11316a1172..0000000000 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/CrystalsKyberTest.java +++ /dev/null @@ -1,318 +0,0 @@ -package org.bouncycastle.pqc.crypto.test; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.SecureRandom; -import java.util.HashMap; - -import junit.framework.Assert; -import junit.framework.TestCase; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.SecretWithEncapsulation; -import org.bouncycastle.crypto.util.DEROtherInfo; -import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyPairGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; -import org.bouncycastle.pqc.crypto.util.PQCOtherInfoGenerator; -import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; -import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; -import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; -import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; -import org.bouncycastle.test.TestResourceFinder; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.test.FixedSecureRandom; - -public class CrystalsKyberTest - extends TestCase -{ - - public void testModulus() throws IOException - { - KyberParameters[] params = new KyberParameters[]{ - KyberParameters.kyber512, - KyberParameters.kyber768, - KyberParameters.kyber1024, - }; - - String[] files = new String[]{ - "ML-KEM-512.txt", - "ML-KEM-768.txt", - "ML-KEM-1024.txt", - }; - - TestSampler sampler = new TestSampler(); - for (int fileIndex = 0; fileIndex != files.length; fileIndex++) - { - String name = files[fileIndex]; - // System.out.println("testing: " + name); - InputStream src = TestResourceFinder.findTestResource("pqc/crypto/kyber/modulus", name); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - - String line = null; - while ((line = bin.readLine()) != null) - { - line = line.trim(); - line = line.trim(); - byte[] key = Hex.decode(line); - KyberParameters parameters = params[fileIndex]; - - - KyberPublicKeyParameters pubParams = (KyberPublicKeyParameters) PublicKeyFactory.createKey( - SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new KyberPublicKeyParameters(parameters, key))); - - // KEM Enc - SecureRandom random = new SecureRandom(); - KyberKEMGenerator KyberEncCipher = new KyberKEMGenerator(random); - try - { - SecretWithEncapsulation secWenc = KyberEncCipher.generateEncapsulated(pubParams); - byte[] generated_cipher_text = secWenc.getEncapsulation(); - fail(); - } - catch (Exception ignored) - { - } - } - } - } - - public void testPrivInfoGeneration() - throws IOException - { - SecureRandom random = new SecureRandom(); - PQCOtherInfoGenerator.PartyU partyU = new PQCOtherInfoGenerator.PartyU(KyberParameters.kyber512, new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), Hex.decode("beef"), Hex.decode("cafe"), random); - - byte[] partA = partyU.getSuppPrivInfoPartA(); - - PQCOtherInfoGenerator.PartyV partyV = new PQCOtherInfoGenerator.PartyV(KyberParameters.kyber512, new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), Hex.decode("beef"), Hex.decode("cafe"), random); - - byte[] partB = partyV.getSuppPrivInfoPartB(partA); - - DEROtherInfo otherInfoU = partyU.generate(partB); - - DEROtherInfo otherInfoV = partyV.generate(); - - Assert.assertTrue(Arrays.areEqual(otherInfoU.getEncoded(), otherInfoV.getEncoded())); - } - - public void testKyber() - { - /* -count = 0 -seed = 061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1 -pk = D22302CBD3399FACC630991FC8F28BDB4354762541527678BCF61F65C241146C426D23B9BFAA6B7DF18C97F20C1B6125BF874B1D89475852C448215DB0EB7737F91480E8CEBD9A0871574F5AB62D9020175EC6927CA0B54C09818E42CF92A383172422C7DC1831D63B0C295DE75159DB8034E9E07F7B0B910C3C1E5FB66B3DC523F1FA6EB4910CB89A6C17562C83AB4C18D0CD7E0796592A372AA409B1C557347CCACDC4644A119064D06DD474929D1C6FB4D686E5491CE4BC89A30BB4B8C41BCE5157DFC1360823B1AB618C14B10F98C25067398EA7018C278A4B3DF31334D603B2044EF187CD9BC6CE42725BD962C264983E9E18155A8B9C47143D70460A26A56FE7658C1F150348C6087EF758AD167887860A007A5FC37358D43B5EBEE820ACEA474F0AC07B76802866199C61231D5C747C93774D2C1E0C1C67E6C81B82752173E125BAF39B4FD19A4F453DC57976B1D97FE6996992BBB65B7CB25D077BBAA6A13322899AF659CF1B3558C1B5001154B625809ED89AEEBB89E6EA7D67F723D045AB05715C42355DA6A5C8DD39C8ABE3037751A01ED1C7374919F3121B5A52C53D1487316769F80721DEEAAAD3C90F76E7AE9E12BA92B32B5FD457E3C752C2650DFB885771CB77AC3C785A8C562E6A1C63C2A55EA47CF8B90EB8225C123C346452566235B2F31823A33521E087937A345D8D663EEAA05658917BBAA008C2E335F8850A90A326D0E66432F44CEB8289E4ECB2D12958E984072ECACB88E1348FF0B55654ACBA5B54971CBAEBA88EC4B91A94C37192FA982BECB9F3DA421603B61A51BC8E36CBD053851C77B1B926B17A272AA9023246B02B3ED47F66A00BD5684823634E7CE58CF8F306E35B1E5322824D904801F0A2FA7C2BC9C252B0A56B7BA2AB0F636021745A70A9A43E2B0A8D615970B65309624B5184BCC30B911679AEDD76025FE3908FD67897B0CF4BE5A6F5413D7DD98564B23E42A93E4AA8821CD45054C643EDC1158DB6B3DEB13FB5A51EBD1A8A78B87225A7338E101104C4A220D9BDEDD48C85A1C2DAE781A80C40E13B87EAC73A764201C9B760CCFB1AE392699C7039D27C39362B27B8FC6F07A8A3D4410F1547C48A9997F62C61074452EF1515F8A649EBCA9437205A4E8A61606B41DAF6834D671F4D852C0C9C4096611648C6A3170678B1537CC1828D93580C9E5849A9653175ACB753F2BE7437BE45F6C603E485F2EC301BB42B6C37C225D7495A584AE231890AB5C8C35C268CF4BBB0213C096019319561A8A6947637AA40D006B415BB2CFA2237E0890B6A3BC134ABF8F6585E108D15940F91F4BF5B0C818055B21DEA6E63B553988C47F4B94E7CF800A493B4734705EDC56A4B6021C629500675876804CF0B951F038A5C7FE58E89774EF2992FD7C63099D352A7D21560B788B405709861817E59A96B3A3A83CBA803B16934331071905BBEC6532900155D8AC88CB32E4E21A3BD3A03FDEC325A51CD2773964E6784FCF1853737AA64EB67564727272661ABF84313A57A44B123C65509CFB7A6F6641CDCC3B57FE628C7B8192DB44FFBF5796A8613B1FA126F6076883C783DC24E2A4464C40B3A41CA70AE87620866CF4FCB2BD204BF5C283812BA056AC0C345E379C4BA24D750901279BB2F3A16F612BFADB35703332C7C136F68EAB6755C66B6A4AD1AABA7B768A58ACAACC10A459A1CC8EF29377BC200E4D315A30A6BCC3256F9734D06E9779CAA5442A9A16069081377C76E75154368072DC446ED6C8B8E622A21E383CF9BA1FB434E2ECC81E7B78CEE986B8FF798AB18CF9634543546284EDA2A26B47F05B735BCDB1202220076DC8B4E4B9F853533C8F6C7FF38817BA49712835785F17F14CA01D0C1C1E98810FE0B36E5B427157B9418449CEDD641A4293C85C32700102ACEC22EBAD98ED160A5F027BD4CDA57F1F3720A12C134654DD5E73F829676495390D0E7929D6034E9C55F7D55BA658BC587988E8AF94960F6CFB8D5AF7A0021535A6E25E437D49A780698BE22AC9953949F571B85A685725F8207A2B0AE849B601AB91B159B3DF4A154C2041E776070AFC42969322380917C97510799F3149131477E16663D3174C7C1CAEA788535C6C005A64F2868631B31B66E205FD38C1D84542D0F1B578F58C9BF5A0FAEAB6AB6494893053165EAFD465FC64A0C5F8F3F9003489415899D59A543D8208C54A3166529B53922 -sk = 07638FB69868F3D320E5862BD96933FEB311B362093C9B5D50170BCED43F1B536D9A204BB1F22695950BA1F2A9E8EB828B284488760B3FC84FABA04275D5628E39C5B2471374283C503299C0AB49B66B8BBB56A4186624F919A2BA59BB08D8551880C2BEFC4F87F25F59AB587A79C327D792D54C974A69262FF8A78938289E9A87B688B083E0595FE218B6BB1505941CE2E81A5A64C5AAC60417256985349EE47A52420A5F97477B7236AC76BC70E8288729287EE3E34A3DBC3683C0B7B10029FC203418537E7466BA6385A8FF301EE12708F82AAA1E380FC7A88F8F205AB7E88D7E95952A55BA20D09B79A47141D62BF6EB7DD307B08ECA13A5BC5F6B68581C6865B27BBCDDAB142F4B2CBFF488C8A22705FAA98A2B9EEA3530C76662335CC7EA3A00777725EBCCCD2A4636B2D9122FF3AB77123CE0883C1911115E50C9E8A94194E48DD0D09CFFB3ADCD2C1E92430903D07ADBF00532031575AA7F9E7B5A1F3362DEC936D4043C05F2476C07578BC9CBAF2AB4E382727AD41686A96B2548820BB03B32F11B2811AD62F489E951632ABA0D1DF89680CC8A8B53B481D92A68D70B4EA1C3A6A561C0692882B5CA8CC942A8D495AFCB06DE89498FB935B775908FE7A03E324D54CC19D4E1AABD3593B38B19EE1388FE492B43127E5A504253786A0D69AD32601C28E2C88504A5BA599706023A61363E17C6B9BB59BDC697452CD059451983D738CA3FD034E3F5988854CA05031DB09611498988197C6B30D258DFE26265541C89A4B31D6864E9389B03CB74F7EC4323FB9421A4B9790A26D17B0398A26767350909F84D57B6694DF830664CA8B3C3C03ED2AE67B89006868A68527CCD666459AB7F056671000C6164D3A7F266A14D97CBD7004D6C92CACA770B844A4FA9B182E7B18CA885082AC5646FCB4A14E1685FEB0C9CE3372AB95365C04FD83084F80A23FF10A05BF15F7FA5ACC6C0CB462C33CA524FA6B8BB359043BA68609EAA2536E81D08463B19653B5435BA946C9ADDEB202B04B031CC960DCC12E4518D428B32B257A4FC7313D3A7980D80082E934F9D95C32B0A0191A23604384DD9E079BBBAA266D14C3F756B9F2133107433A4E83FA7187282A809203A4FAF841851833D121AC383843A5E55BC2381425E16C7DB4CC9AB5C1B0D91A47E2B8DE0E582C86B6B0D907BB360B97F40AB5D038F6B75C814B27D9B968D419832BC8C2BEE605EF6E5059D33100D90485D378450014221736C07407CAC260408AA64926619788B8601C2A752D1A6CBF820D7C7A04716203225B3895B9342D147A8185CFC1BB65BA06B4142339903C0AC4651385B45D98A8B19D28CD6BAB088787F7EE1B12461766B43CBCCB96434427D93C065550688F6948ED1B5475A425F1B85209D061C08B56C1CC069F6C0A7C6F29358CAB911087732A649D27C9B98F9A48879387D9B00C25959A71654D6F6A946164513E47A75D005986C2363C09F6B537ECA78B9303A5FA457608A586A653A347DB04DFCC19175B3A301172536062A658A95277570C8852CA8973F4AE123A334047DD711C8927A634A03388A527B034BF7A8170FA702C1F7C23EC32D18A2374890BE9C787A9409C82D192C4BB705A2F996CE405D85A4C1A1AB9B6AEB49CCE1C2F8A97C3516C72A00A46263BAA696BF25727719C3216423618FF33380934A6C10545C4C5C5155B12486181FC7A2319873978B6A2A67490F8256BD2196FE1792A4C00077B812EAE8BED3572499684AB3371876761E450C9F9D2768A36806D7AB2046C91F17599E9AC592990808DCD7B4D0919072F14EC361773B7252444C323C308326F4A30F8680D2F748F56A132B82674ED0184620B82AD2CB182C97B481626647491290A011CC73828685A8C367A5B9CF8D621B0D5C1EFF03172758BD004978C251CD51342228989CAE6332AC486437CB5C57D4307462865253BE217B3515C73DF405B7F28217AD0B8CF60C2FFFAA0A0048B1FB4ACDCDC38B5250CFEC356A6DE26CFA7A588FDC86F98C854AC64C7BFAA96F5A32CC0610934BAA6A586B9A2054F13BA274174AA0D2B3A81B96A940666F789B5A6BCDC0A6A0178A0C9A02578A493F6EEA0D2E6C13951C9F249A5E8DD71DD49A742D451F1ABBA19AF8C547855E0AFC728E90ABB499C9BEEB766F4729CDA22263E324D22302CBD3399FACC630991FC8F28BDB4354762541527678BCF61F65C241146C426D23B9BFAA6B7DF18C97F20C1B6125BF874B1D89475852C448215DB0EB7737F91480E8CEBD9A0871574F5AB62D9020175EC6927CA0B54C09818E42CF92A383172422C7DC1831D63B0C295DE75159DB8034E9E07F7B0B910C3C1E5FB66B3DC523F1FA6EB4910CB89A6C17562C83AB4C18D0CD7E0796592A372AA409B1C557347CCACDC4644A119064D06DD474929D1C6FB4D686E5491CE4BC89A30BB4B8C41BCE5157DFC1360823B1AB618C14B10F98C25067398EA7018C278A4B3DF31334D603B2044EF187CD9BC6CE42725BD962C264983E9E18155A8B9C47143D70460A26A56FE7658C1F150348C6087EF758AD167887860A007A5FC37358D43B5EBEE820ACEA474F0AC07B76802866199C61231D5C747C93774D2C1E0C1C67E6C81B82752173E125BAF39B4FD19A4F453DC57976B1D97FE6996992BBB65B7CB25D077BBAA6A13322899AF659CF1B3558C1B5001154B625809ED89AEEBB89E6EA7D67F723D045AB05715C42355DA6A5C8DD39C8ABE3037751A01ED1C7374919F3121B5A52C53D1487316769F80721DEEAAAD3C90F76E7AE9E12BA92B32B5FD457E3C752C2650DFB885771CB77AC3C785A8C562E6A1C63C2A55EA47CF8B90EB8225C123C346452566235B2F31823A33521E087937A345D8D663EEAA05658917BBAA008C2E335F8850A90A326D0E66432F44CEB8289E4ECB2D12958E984072ECACB88E1348FF0B55654ACBA5B54971CBAEBA88EC4B91A94C37192FA982BECB9F3DA421603B61A51BC8E36CBD053851C77B1B926B17A272AA9023246B02B3ED47F66A00BD5684823634E7CE58CF8F306E35B1E5322824D904801F0A2FA7C2BC9C252B0A56B7BA2AB0F636021745A70A9A43E2B0A8D615970B65309624B5184BCC30B911679AEDD76025FE3908FD67897B0CF4BE5A6F5413D7DD98564B23E42A93E4AA8821CD45054C643EDC1158DB6B3DEB13FB5A51EBD1A8A78B87225A7338E101104C4A220D9BDEDD48C85A1C2DAE781A80C40E13B87EAC73A764201C9B760CCFB1AE392699C7039D27C39362B27B8FC6F07A8A3D4410F1547C48A9997F62C61074452EF1515F8A649EBCA9437205A4E8A61606B41DAF6834D671F4D852C0C9C4096611648C6A3170678B1537CC1828D93580C9E5849A9653175ACB753F2BE7437BE45F6C603E485F2EC301BB42B6C37C225D7495A584AE231890AB5C8C35C268CF4BBB0213C096019319561A8A6947637AA40D006B415BB2CFA2237E0890B6A3BC134ABF8F6585E108D15940F91F4BF5B0C818055B21DEA6E63B553988C47F4B94E7CF800A493B4734705EDC56A4B6021C629500675876804CF0B951F038A5C7FE58E89774EF2992FD7C63099D352A7D21560B788B405709861817E59A96B3A3A83CBA803B16934331071905BBEC6532900155D8AC88CB32E4E21A3BD3A03FDEC325A51CD2773964E6784FCF1853737AA64EB67564727272661ABF84313A57A44B123C65509CFB7A6F6641CDCC3B57FE628C7B8192DB44FFBF5796A8613B1FA126F6076883C783DC24E2A4464C40B3A41CA70AE87620866CF4FCB2BD204BF5C283812BA056AC0C345E379C4BA24D750901279BB2F3A16F612BFADB35703332C7C136F68EAB6755C66B6A4AD1AABA7B768A58ACAACC10A459A1CC8EF29377BC200E4D315A30A6BCC3256F9734D06E9779CAA5442A9A16069081377C76E75154368072DC446ED6C8B8E622A21E383CF9BA1FB434E2ECC81E7B78CEE986B8FF798AB18CF9634543546284EDA2A26B47F05B735BCDB1202220076DC8B4E4B9F853533C8F6C7FF38817BA49712835785F17F14CA01D0C1C1E98810FE0B36E5B427157B9418449CEDD641A4293C85C32700102ACEC22EBAD98ED160A5F027BD4CDA57F1F3720A12C134654DD5E73F829676495390D0E7929D6034E9C55F7D55BA658BC587988E8AF94960F6CFB8D5AF7A0021535A6E25E437D49A780698BE22AC9953949F571B85A685725F8207A2B0AE849B601AB91B159B3DF4A154C2041E776070AFC42969322380917C97510799F3149131477E16663D3174C7C1CAEA788535C6C005A64F2868631B31B66E205FD38C1D84542D0F1B578F58C9BF5A0FAEAB6AB6494893053165EAFD465FC64A0C5F8F3F9003489415899D59A543D8208C54A3166529B539228A39E87D531F3527C207EDCC1DB7FADDCF9628391879B335C707839A0DB051A8B505D7CFAD1B497499323C8686325E4792F267AAFA3F87CA60D01CB54F29202A -ct = E97436B18AE42096AE6237C8E56E1B777A9C4CAF1B20D1C40F230B45DC38F1A68013EEE84F6F5633C39E7A5548092A23B46220934C698A6DBC88149D8EE666D427E697CBF464DB1A41BBC86F1C2EF998E46E51B5D94D560109E7319AD2316FD4C2EEACFBC01DC54D8A47E33C66A82094465D1FB1C6B7BD9331BA1CE5AF1C28ADBD130FEB1C35768D388D58444700643E70262889CBFED51AD328D0E3724E63B60253445A75A96B0FBF5B580DE3D2ACE22802DF3F1B009404575745F2F7A75CAE5E1E5AD414AD363CB5DFA48F7C6ED3587278EF58EE98B144438EAA66E5CD0BA800FB9799FBF63DE47D9904039AF5722E3D7E0A3C08A0A4B62F3743E179101EDBA93B081C79ED9A065BFFF65AD71D8548EAF76ADD4C32E3BC4D6C7551FB604CEB62CCF94C8A4EE41E7362B3E66ACB86C250E61BDC8AF162F1A2D9B29403D4976C37179C9A4927CDD6BF1ACACFE4A645EB5A59919FEFF17D86F5DCC77ABC52F56E70C41197E9B8328726C3D20C9D3ACE0CBFA0A7F50C5DDB2F1507D590071B6F1D17CA84DEA7A5930DC5B70F37AD7F447447481D4F14EA2718DB1CD8E096011DD617ED56BD0B2D0AE8C51BB0FF1B052CDC9D09BC6A772FD75877F762E72E6FC39F9A8E9EBF1E3ADEFA1ED897BF81BC6751DB4D637918BAD74C6A9D5D5E5F6E512A08C3D8165B0DE8DDEDEBC5066C2C44FC5A0C97531C0EEEEFED4C5565BEE4B33DD782C7178E91F8AE7AC30B3E010EEB25F7D558F7C953602EEE903C22C2D657EB32624B1B8F854232AD6F19C298830E6A8F6FEBCA91AEC693A08BA4294D0461F55A5AD25965BC81547036121E28A20DE2E658B358B9D17EB065B0A2D1D3BB029BCEC85FCE555728FAB7A77BAA183F92FD4430DD3F1E099F23BA59E1C737A9F56BBD0236AFA079CD7D37A15E407D47B745C891364D7DB99887C4C2816875A3FCC3B4B9FA646F7819871692434FED5588BC5AA53C7B33A12D163B584F11FB07535A84AE9DACDE81D8FC77B1368CAE470797069FC7C782FA96A7FEC30BC6F0ED7D4934C00B09A629029CC17E1BC433B2C7CF35E7895908848E417C184655C8E708F803C47B3C8BA45CFEBB9BCBB933C6CB72CCFC4C27863B8F9E0FE9A2FDB186359315BE6B46B50D19900D6E890B9FC4A87B517B24909B72A1ADE60ED549E2ED500CB60FDC7642F782AFC33133E1811613049F4229C00CC734969BF673E2690C3AB63DD0E064B9D2CAE9BD218A03808D7A4ED92D1F39ECDE7F102E8D47701AFCA94C788D7FF101BF8EB022BD25CD6CD12B2710FB0EEE09E467692E6D14BAAE47C771E4D2B10927CBDE8994B023210CAE0EFDA65306B4B30C6619DFB8A7937852D92759AAE5625AE717A1608B486AE3F25CB46B78F3D04B3410B41CE829CA6C29B7E6806740F8E818A72F3C082E24782BF63D4C3FC17C011D9AE0FA2DBA4EAD828158FB40C15E0C252924B77979F8068DAD4F8EE7A7DA07306293B25E507791906692C431F23592FAA77F4F6F9F5023413E0E812DE0681372D09B07CAE884DEDBB8AC2B80347D3511E4CFCA50CD752A16593858DF1A2E6A52887D5A2F81E70E57C65FA2753478A285C3896F6272133FA40A88DDB04D7985EF70C35D7413DBD32F49478694C509F2C97D21822F20740A86DD7ABDF66D0E632A254056DF5E0E7F013BCB7DFF01E38F881CFF77F1EDD48612A2677B7D1E4E62D5A6196340E26151EEA29D8EBD9786E38721B09EC974E336F2437505EAC34DE0270C0780C6B3A89520475481409864797DA4B6ACBE848225E25C7265A4E3BE16EE8CD8A225D2FDF4C498BA35332A553FE4066D73E758653F51A8A08913E469907DA5E7BF068E4C18486D1BE273BB4C674491BFE27F94453F64048086C93AE7F96FF7505B57CF3EDAC0AA5DE3A6B06470266DBC8945E952A2A73BD7CF8524E8EA00E1D0631DCA8F658145910F7248BE8266D0F98EF7152A112F3762F7B5356161E756D7EA4FCEFD3CBC44D4E59DCDA05ACC37F90B44C62431EB7610E15375984892B769D9417FCD6781B434F4C59191A020DADD81F0928E11C010617087015A968A5EA8B52DF8BB1706BF4AC7839FA80D52CC05C499091977B29B4AEABB7B1974D1B3BC097B23F3977CB0DF44E1A20318B4642D7A67D330F45A6FA5DEB96D8DDB9EAE323E61371BB6BEF4C13771D53BFA33B40408C813D3F539A29C4CF99C1D273E8561E2C53B505436CC3C -ss = C9786ED936508E178D55A1208C590A10F25CFBFEB50BE4207395A8B2F8AA192E - */ - String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; - String expectedPubKey = "D22302CBD3399FACC630991FC8F28BDB4354762541527678BCF61F65C241146C426D23B9BFAA6B7DF18C97F20C1B6125BF874B1D89475852C448215DB0EB7737F91480E8CEBD9A0871574F5AB62D9020175EC6927CA0B54C09818E42CF92A383172422C7DC1831D63B0C295DE75159DB8034E9E07F7B0B910C3C1E5FB66B3DC523F1FA6EB4910CB89A6C17562C83AB4C18D0CD7E0796592A372AA409B1C557347CCACDC4644A119064D06DD474929D1C6FB4D686E5491CE4BC89A30BB4B8C41BCE5157DFC1360823B1AB618C14B10F98C25067398EA7018C278A4B3DF31334D603B2044EF187CD9BC6CE42725BD962C264983E9E18155A8B9C47143D70460A26A56FE7658C1F150348C6087EF758AD167887860A007A5FC37358D43B5EBEE820ACEA474F0AC07B76802866199C61231D5C747C93774D2C1E0C1C67E6C81B82752173E125BAF39B4FD19A4F453DC57976B1D97FE6996992BBB65B7CB25D077BBAA6A13322899AF659CF1B3558C1B5001154B625809ED89AEEBB89E6EA7D67F723D045AB05715C42355DA6A5C8DD39C8ABE3037751A01ED1C7374919F3121B5A52C53D1487316769F80721DEEAAAD3C90F76E7AE9E12BA92B32B5FD457E3C752C2650DFB885771CB77AC3C785A8C562E6A1C63C2A55EA47CF8B90EB8225C123C346452566235B2F31823A33521E087937A345D8D663EEAA05658917BBAA008C2E335F8850A90A326D0E66432F44CEB8289E4ECB2D12958E984072ECACB88E1348FF0B55654ACBA5B54971CBAEBA88EC4B91A94C37192FA982BECB9F3DA421603B61A51BC8E36CBD053851C77B1B926B17A272AA9023246B02B3ED47F66A00BD5684823634E7CE58CF8F306E35B1E5322824D904801F0A2FA7C2BC9C252B0A56B7BA2AB0F636021745A70A9A43E2B0A8D615970B65309624B5184BCC30B911679AEDD76025FE3908FD67897B0CF4BE5A6F5413D7DD98564B23E42A93E4AA8821CD45054C643EDC1158DB6B3DEB13FB5A51EBD1A8A78B87225A7338E101104C4A220D9BDEDD48C85A1C2DAE781A80C40E13B87EAC73A764201C9B760CCFB1AE392699C7039D27C39362B27B8FC6F07A8A3D4410F1547C48A9997F62C61074452EF1515F8A649EBCA9437205A4E8A61606B41DAF6834D671F4D852C0C9C4096611648C6A3170678B1537CC1828D93580C9E5849A9653175ACB753F2BE7437BE45F6C603E485F2EC301BB42B6C37C225D7495A584AE231890AB5C8C35C268CF4BBB0213C096019319561A8A6947637AA40D006B415BB2CFA2237E0890B6A3BC134ABF8F6585E108D15940F91F4BF5B0C818055B21DEA6E63B553988C47F4B94E7CF800A493B4734705EDC56A4B6021C629500675876804CF0B951F038A5C7FE58E89774EF2992FD7C63099D352A7D21560B788B405709861817E59A96B3A3A83CBA803B16934331071905BBEC6532900155D8AC88CB32E4E21A3BD3A03FDEC325A51CD2773964E6784FCF1853737AA64EB67564727272661ABF84313A57A44B123C65509CFB7A6F6641CDCC3B57FE628C7B8192DB44FFBF5796A8613B1FA126F6076883C783DC24E2A4464C40B3A41CA70AE87620866CF4FCB2BD204BF5C283812BA056AC0C345E379C4BA24D750901279BB2F3A16F612BFADB35703332C7C136F68EAB6755C66B6A4AD1AABA7B768A58ACAACC10A459A1CC8EF29377BC200E4D315A30A6BCC3256F9734D06E9779CAA5442A9A16069081377C76E75154368072DC446ED6C8B8E622A21E383CF9BA1FB434E2ECC81E7B78CEE986B8FF798AB18CF9634543546284EDA2A26B47F05B735BCDB1202220076DC8B4E4B9F853533C8F6C7FF38817BA49712835785F17F14CA01D0C1C1E98810FE0B36E5B427157B9418449CEDD641A4293C85C32700102ACEC22EBAD98ED160A5F027BD4CDA57F1F3720A12C134654DD5E73F829676495390D0E7929D6034E9C55F7D55BA658BC587988E8AF94960F6CFB8D5AF7A0021535A6E25E437D49A780698BE22AC9953949F571B85A685725F8207A2B0AE849B601AB91B159B3DF4A154C2041E776070AFC42969322380917C97510799F3149131477E16663D3174C7C1CAEA788535C6C005A64F2868631B31B66E205FD38C1D84542D0F1B578F58C9BF5A0FAEAB6AB6494893053165EAFD465FC64A0C5F8F3F9003489415899D59A543D8208C54A3166529B53922"; - String expectedPrivKey = "07638FB69868F3D320E5862BD96933FEB311B362093C9B5D50170BCED43F1B536D9A204BB1F22695950BA1F2A9E8EB828B284488760B3FC84FABA04275D5628E39C5B2471374283C503299C0AB49B66B8BBB56A4186624F919A2BA59BB08D8551880C2BEFC4F87F25F59AB587A79C327D792D54C974A69262FF8A78938289E9A87B688B083E0595FE218B6BB1505941CE2E81A5A64C5AAC60417256985349EE47A52420A5F97477B7236AC76BC70E8288729287EE3E34A3DBC3683C0B7B10029FC203418537E7466BA6385A8FF301EE12708F82AAA1E380FC7A88F8F205AB7E88D7E95952A55BA20D09B79A47141D62BF6EB7DD307B08ECA13A5BC5F6B68581C6865B27BBCDDAB142F4B2CBFF488C8A22705FAA98A2B9EEA3530C76662335CC7EA3A00777725EBCCCD2A4636B2D9122FF3AB77123CE0883C1911115E50C9E8A94194E48DD0D09CFFB3ADCD2C1E92430903D07ADBF00532031575AA7F9E7B5A1F3362DEC936D4043C05F2476C07578BC9CBAF2AB4E382727AD41686A96B2548820BB03B32F11B2811AD62F489E951632ABA0D1DF89680CC8A8B53B481D92A68D70B4EA1C3A6A561C0692882B5CA8CC942A8D495AFCB06DE89498FB935B775908FE7A03E324D54CC19D4E1AABD3593B38B19EE1388FE492B43127E5A504253786A0D69AD32601C28E2C88504A5BA599706023A61363E17C6B9BB59BDC697452CD059451983D738CA3FD034E3F5988854CA05031DB09611498988197C6B30D258DFE26265541C89A4B31D6864E9389B03CB74F7EC4323FB9421A4B9790A26D17B0398A26767350909F84D57B6694DF830664CA8B3C3C03ED2AE67B89006868A68527CCD666459AB7F056671000C6164D3A7F266A14D97CBD7004D6C92CACA770B844A4FA9B182E7B18CA885082AC5646FCB4A14E1685FEB0C9CE3372AB95365C04FD83084F80A23FF10A05BF15F7FA5ACC6C0CB462C33CA524FA6B8BB359043BA68609EAA2536E81D08463B19653B5435BA946C9ADDEB202B04B031CC960DCC12E4518D428B32B257A4FC7313D3A7980D80082E934F9D95C32B0A0191A23604384DD9E079BBBAA266D14C3F756B9F2133107433A4E83FA7187282A809203A4FAF841851833D121AC383843A5E55BC2381425E16C7DB4CC9AB5C1B0D91A47E2B8DE0E582C86B6B0D907BB360B97F40AB5D038F6B75C814B27D9B968D419832BC8C2BEE605EF6E5059D33100D90485D378450014221736C07407CAC260408AA64926619788B8601C2A752D1A6CBF820D7C7A04716203225B3895B9342D147A8185CFC1BB65BA06B4142339903C0AC4651385B45D98A8B19D28CD6BAB088787F7EE1B12461766B43CBCCB96434427D93C065550688F6948ED1B5475A425F1B85209D061C08B56C1CC069F6C0A7C6F29358CAB911087732A649D27C9B98F9A48879387D9B00C25959A71654D6F6A946164513E47A75D005986C2363C09F6B537ECA78B9303A5FA457608A586A653A347DB04DFCC19175B3A301172536062A658A95277570C8852CA8973F4AE123A334047DD711C8927A634A03388A527B034BF7A8170FA702C1F7C23EC32D18A2374890BE9C787A9409C82D192C4BB705A2F996CE405D85A4C1A1AB9B6AEB49CCE1C2F8A97C3516C72A00A46263BAA696BF25727719C3216423618FF33380934A6C10545C4C5C5155B12486181FC7A2319873978B6A2A67490F8256BD2196FE1792A4C00077B812EAE8BED3572499684AB3371876761E450C9F9D2768A36806D7AB2046C91F17599E9AC592990808DCD7B4D0919072F14EC361773B7252444C323C308326F4A30F8680D2F748F56A132B82674ED0184620B82AD2CB182C97B481626647491290A011CC73828685A8C367A5B9CF8D621B0D5C1EFF03172758BD004978C251CD51342228989CAE6332AC486437CB5C57D4307462865253BE217B3515C73DF405B7F28217AD0B8CF60C2FFFAA0A0048B1FB4ACDCDC38B5250CFEC356A6DE26CFA7A588FDC86F98C854AC64C7BFAA96F5A32CC0610934BAA6A586B9A2054F13BA274174AA0D2B3A81B96A940666F789B5A6BCDC0A6A0178A0C9A02578A493F6EEA0D2E6C13951C9F249A5E8DD71DD49A742D451F1ABBA19AF8C547855E0AFC728E90ABB499C9BEEB766F4729CDA22263E324D22302CBD3399FACC630991FC8F28BDB4354762541527678BCF61F65C241146C426D23B9BFAA6B7DF18C97F20C1B6125BF874B1D89475852C448215DB0EB7737F91480E8CEBD9A0871574F5AB62D9020175EC6927CA0B54C09818E42CF92A383172422C7DC1831D63B0C295DE75159DB8034E9E07F7B0B910C3C1E5FB66B3DC523F1FA6EB4910CB89A6C17562C83AB4C18D0CD7E0796592A372AA409B1C557347CCACDC4644A119064D06DD474929D1C6FB4D686E5491CE4BC89A30BB4B8C41BCE5157DFC1360823B1AB618C14B10F98C25067398EA7018C278A4B3DF31334D603B2044EF187CD9BC6CE42725BD962C264983E9E18155A8B9C47143D70460A26A56FE7658C1F150348C6087EF758AD167887860A007A5FC37358D43B5EBEE820ACEA474F0AC07B76802866199C61231D5C747C93774D2C1E0C1C67E6C81B82752173E125BAF39B4FD19A4F453DC57976B1D97FE6996992BBB65B7CB25D077BBAA6A13322899AF659CF1B3558C1B5001154B625809ED89AEEBB89E6EA7D67F723D045AB05715C42355DA6A5C8DD39C8ABE3037751A01ED1C7374919F3121B5A52C53D1487316769F80721DEEAAAD3C90F76E7AE9E12BA92B32B5FD457E3C752C2650DFB885771CB77AC3C785A8C562E6A1C63C2A55EA47CF8B90EB8225C123C346452566235B2F31823A33521E087937A345D8D663EEAA05658917BBAA008C2E335F8850A90A326D0E66432F44CEB8289E4ECB2D12958E984072ECACB88E1348FF0B55654ACBA5B54971CBAEBA88EC4B91A94C37192FA982BECB9F3DA421603B61A51BC8E36CBD053851C77B1B926B17A272AA9023246B02B3ED47F66A00BD5684823634E7CE58CF8F306E35B1E5322824D904801F0A2FA7C2BC9C252B0A56B7BA2AB0F636021745A70A9A43E2B0A8D615970B65309624B5184BCC30B911679AEDD76025FE3908FD67897B0CF4BE5A6F5413D7DD98564B23E42A93E4AA8821CD45054C643EDC1158DB6B3DEB13FB5A51EBD1A8A78B87225A7338E101104C4A220D9BDEDD48C85A1C2DAE781A80C40E13B87EAC73A764201C9B760CCFB1AE392699C7039D27C39362B27B8FC6F07A8A3D4410F1547C48A9997F62C61074452EF1515F8A649EBCA9437205A4E8A61606B41DAF6834D671F4D852C0C9C4096611648C6A3170678B1537CC1828D93580C9E5849A9653175ACB753F2BE7437BE45F6C603E485F2EC301BB42B6C37C225D7495A584AE231890AB5C8C35C268CF4BBB0213C096019319561A8A6947637AA40D006B415BB2CFA2237E0890B6A3BC134ABF8F6585E108D15940F91F4BF5B0C818055B21DEA6E63B553988C47F4B94E7CF800A493B4734705EDC56A4B6021C629500675876804CF0B951F038A5C7FE58E89774EF2992FD7C63099D352A7D21560B788B405709861817E59A96B3A3A83CBA803B16934331071905BBEC6532900155D8AC88CB32E4E21A3BD3A03FDEC325A51CD2773964E6784FCF1853737AA64EB67564727272661ABF84313A57A44B123C65509CFB7A6F6641CDCC3B57FE628C7B8192DB44FFBF5796A8613B1FA126F6076883C783DC24E2A4464C40B3A41CA70AE87620866CF4FCB2BD204BF5C283812BA056AC0C345E379C4BA24D750901279BB2F3A16F612BFADB35703332C7C136F68EAB6755C66B6A4AD1AABA7B768A58ACAACC10A459A1CC8EF29377BC200E4D315A30A6BCC3256F9734D06E9779CAA5442A9A16069081377C76E75154368072DC446ED6C8B8E622A21E383CF9BA1FB434E2ECC81E7B78CEE986B8FF798AB18CF9634543546284EDA2A26B47F05B735BCDB1202220076DC8B4E4B9F853533C8F6C7FF38817BA49712835785F17F14CA01D0C1C1E98810FE0B36E5B427157B9418449CEDD641A4293C85C32700102ACEC22EBAD98ED160A5F027BD4CDA57F1F3720A12C134654DD5E73F829676495390D0E7929D6034E9C55F7D55BA658BC587988E8AF94960F6CFB8D5AF7A0021535A6E25E437D49A780698BE22AC9953949F571B85A685725F8207A2B0AE849B601AB91B159B3DF4A154C2041E776070AFC42969322380917C97510799F3149131477E16663D3174C7C1CAEA788535C6C005A64F2868631B31B66E205FD38C1D84542D0F1B578F58C9BF5A0FAEAB6AB6494893053165EAFD465FC64A0C5F8F3F9003489415899D59A543D8208C54A3166529B539228A39E87D531F3527C207EDCC1DB7FADDCF9628391879B335C707839A0DB051A8B505D7CFAD1B497499323C8686325E4792F267AAFA3F87CA60D01CB54F29202A"; - - byte[] seed = Hex.decode(temp); - - NISTSecureRandom random = new NISTSecureRandom(seed, null); - - byte[] coins = new byte[64]; - random.nextBytes(coins); - - KyberKeyPairGenerator keyGen = new KyberKeyPairGenerator(); - - keyGen.init(new KyberKeyGenerationParameters(new FixedSecureRandom(coins), KyberParameters.kyber1024)); - - AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); - // // System.out.print("public key = "); - // Helper.printByteArray(((KyberPublicKeyParameters) keyPair.getPublic()).getEncoded()); - assertTrue(Arrays.areEqual(Hex.decode(expectedPubKey), ((KyberPublicKeyParameters)keyPair.getPublic()).getEncoded())); - - // // System.out.print("secret Key = "); - // Helper.printByteArray(((KyberPrivateKeyParameters) keyPair.getPrivate()).getEncoded()); - assertTrue(Arrays.areEqual(Hex.decode(expectedPrivKey), ((KyberPrivateKeyParameters)keyPair.getPrivate()).getEncoded())); - - KyberKEMGenerator kemGen = new KyberKEMGenerator(random); - - SecretWithEncapsulation secretEncap = kemGen.generateEncapsulated(keyPair.getPublic()); - - String expectedSharedSecret = "C9786ED936508E178D55A1208C590A10F25CFBFEB50BE4207395A8B2F8AA192E"; - - // // System.out.print("Shared secret = "); - // Helper.printByteArray(secretEncap.getSecret()); - assertTrue(Arrays.areEqual(Hex.decode(expectedSharedSecret), secretEncap.getSecret())); - - String expectedCipherText = "E97436B18AE42096AE6237C8E56E1B777A9C4CAF1B20D1C40F230B45DC38F1A68013EEE84F6F5633C39E7A5548092A23B46220934C698A6DBC88149D8EE666D427E697CBF464DB1A41BBC86F1C2EF998E46E51B5D94D560109E7319AD2316FD4C2EEACFBC01DC54D8A47E33C66A82094465D1FB1C6B7BD9331BA1CE5AF1C28ADBD130FEB1C35768D388D58444700643E70262889CBFED51AD328D0E3724E63B60253445A75A96B0FBF5B580DE3D2ACE22802DF3F1B009404575745F2F7A75CAE5E1E5AD414AD363CB5DFA48F7C6ED3587278EF58EE98B144438EAA66E5CD0BA800FB9799FBF63DE47D9904039AF5722E3D7E0A3C08A0A4B62F3743E179101EDBA93B081C79ED9A065BFFF65AD71D8548EAF76ADD4C32E3BC4D6C7551FB604CEB62CCF94C8A4EE41E7362B3E66ACB86C250E61BDC8AF162F1A2D9B29403D4976C37179C9A4927CDD6BF1ACACFE4A645EB5A59919FEFF17D86F5DCC77ABC52F56E70C41197E9B8328726C3D20C9D3ACE0CBFA0A7F50C5DDB2F1507D590071B6F1D17CA84DEA7A5930DC5B70F37AD7F447447481D4F14EA2718DB1CD8E096011DD617ED56BD0B2D0AE8C51BB0FF1B052CDC9D09BC6A772FD75877F762E72E6FC39F9A8E9EBF1E3ADEFA1ED897BF81BC6751DB4D637918BAD74C6A9D5D5E5F6E512A08C3D8165B0DE8DDEDEBC5066C2C44FC5A0C97531C0EEEEFED4C5565BEE4B33DD782C7178E91F8AE7AC30B3E010EEB25F7D558F7C953602EEE903C22C2D657EB32624B1B8F854232AD6F19C298830E6A8F6FEBCA91AEC693A08BA4294D0461F55A5AD25965BC81547036121E28A20DE2E658B358B9D17EB065B0A2D1D3BB029BCEC85FCE555728FAB7A77BAA183F92FD4430DD3F1E099F23BA59E1C737A9F56BBD0236AFA079CD7D37A15E407D47B745C891364D7DB99887C4C2816875A3FCC3B4B9FA646F7819871692434FED5588BC5AA53C7B33A12D163B584F11FB07535A84AE9DACDE81D8FC77B1368CAE470797069FC7C782FA96A7FEC30BC6F0ED7D4934C00B09A629029CC17E1BC433B2C7CF35E7895908848E417C184655C8E708F803C47B3C8BA45CFEBB9BCBB933C6CB72CCFC4C27863B8F9E0FE9A2FDB186359315BE6B46B50D19900D6E890B9FC4A87B517B24909B72A1ADE60ED549E2ED500CB60FDC7642F782AFC33133E1811613049F4229C00CC734969BF673E2690C3AB63DD0E064B9D2CAE9BD218A03808D7A4ED92D1F39ECDE7F102E8D47701AFCA94C788D7FF101BF8EB022BD25CD6CD12B2710FB0EEE09E467692E6D14BAAE47C771E4D2B10927CBDE8994B023210CAE0EFDA65306B4B30C6619DFB8A7937852D92759AAE5625AE717A1608B486AE3F25CB46B78F3D04B3410B41CE829CA6C29B7E6806740F8E818A72F3C082E24782BF63D4C3FC17C011D9AE0FA2DBA4EAD828158FB40C15E0C252924B77979F8068DAD4F8EE7A7DA07306293B25E507791906692C431F23592FAA77F4F6F9F5023413E0E812DE0681372D09B07CAE884DEDBB8AC2B80347D3511E4CFCA50CD752A16593858DF1A2E6A52887D5A2F81E70E57C65FA2753478A285C3896F6272133FA40A88DDB04D7985EF70C35D7413DBD32F49478694C509F2C97D21822F20740A86DD7ABDF66D0E632A254056DF5E0E7F013BCB7DFF01E38F881CFF77F1EDD48612A2677B7D1E4E62D5A6196340E26151EEA29D8EBD9786E38721B09EC974E336F2437505EAC34DE0270C0780C6B3A89520475481409864797DA4B6ACBE848225E25C7265A4E3BE16EE8CD8A225D2FDF4C498BA35332A553FE4066D73E758653F51A8A08913E469907DA5E7BF068E4C18486D1BE273BB4C674491BFE27F94453F64048086C93AE7F96FF7505B57CF3EDAC0AA5DE3A6B06470266DBC8945E952A2A73BD7CF8524E8EA00E1D0631DCA8F658145910F7248BE8266D0F98EF7152A112F3762F7B5356161E756D7EA4FCEFD3CBC44D4E59DCDA05ACC37F90B44C62431EB7610E15375984892B769D9417FCD6781B434F4C59191A020DADD81F0928E11C010617087015A968A5EA8B52DF8BB1706BF4AC7839FA80D52CC05C499091977B29B4AEABB7B1974D1B3BC097B23F3977CB0DF44E1A20318B4642D7A67D330F45A6FA5DEB96D8DDB9EAE323E61371BB6BEF4C13771D53BFA33B40408C813D3F539A29C4CF99C1D273E8561E2C53B505436CC3C"; - - assertTrue(Arrays.areEqual(Hex.decode(expectedCipherText), secretEncap.getEncapsulation())); - - KyberKEMExtractor kemExtract = new KyberKEMExtractor((KyberPrivateKeyParameters)keyPair.getPrivate()); - - byte[] decryptedSharedSecret = kemExtract.extractSecret(secretEncap.getEncapsulation()); - - assertTrue(Arrays.areEqual(Hex.decode(expectedSharedSecret), decryptedSharedSecret)); - } - - public void testRNG() - { - String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; - byte[] seed = Hex.decode(temp); - NISTSecureRandom r = new NISTSecureRandom(seed, null); - byte[] testBytes = new byte[48]; - r.nextBytes(testBytes); - - String randBytesString = "7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E47"; - byte[] randBytes = Hex.decode(randBytesString); - - assertTrue(Arrays.areEqual(randBytes, testBytes)); - } - - public void testParameters() - throws Exception - { - assertEquals(256, KyberParameters.kyber512.getSessionKeySize()); - assertEquals(256, KyberParameters.kyber768.getSessionKeySize()); - assertEquals(256, KyberParameters.kyber1024.getSessionKeySize()); - } - - public void testVectors() - throws Exception - { - KyberParameters[] params = new KyberParameters[]{ - KyberParameters.kyber512, - KyberParameters.kyber768, - KyberParameters.kyber1024, - }; - - String[] files = new String[]{ - "kyber512.rsp", - "kyber768.rsp", - "kyber1024.rsp", - }; - - TestSampler sampler = new TestSampler(); - for (int fileIndex = 0; fileIndex != files.length; fileIndex++) - { - String name = files[fileIndex]; - // System.out.println("testing: " + name); - InputStream src = TestResourceFinder.findTestResource("pqc/crypto/kyber", name); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - - String line = null; - HashMap buf = new HashMap(); - while ((line = bin.readLine()) != null) - { - line = line.trim(); - - if (line.startsWith("#")) - { - continue; - } - if (line.length() == 0) - { - if (buf.size() > 0) - { - String count = (String)buf.get("count"); - if (sampler.skipTest(count)) - { - continue; - } - // System.out.println("test case: " + count); - - byte[] seed = Hex.decode((String)buf.get("seed")); // seed for Kyber secure random - byte[] pk = Hex.decode((String)buf.get("pk")); // public key - byte[] sk = Hex.decode((String)buf.get("sk")); // private key - byte[] ct = Hex.decode((String)buf.get("ct")); // ciphertext - byte[] ss = Hex.decode((String)buf.get("ss")); // session key - - NISTSecureRandom random = new NISTSecureRandom(seed, null); - KyberParameters parameters = params[fileIndex]; - - byte[] coins = new byte[64]; - random.nextBytes(coins); - KyberKeyPairGenerator kpGen = new KyberKeyPairGenerator(); - KyberKeyGenerationParameters genParam = new KyberKeyGenerationParameters(new FixedSecureRandom(coins), parameters); - // - // Generate keys and test. - // - kpGen.init(genParam); - AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); - - KyberPublicKeyParameters pubParams = (KyberPublicKeyParameters)PublicKeyFactory.createKey( - SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((KyberPublicKeyParameters)kp.getPublic())); - KyberPrivateKeyParameters privParams = (KyberPrivateKeyParameters)PrivateKeyFactory.createKey( - PrivateKeyInfoFactory.createPrivateKeyInfo((KyberPrivateKeyParameters)kp.getPrivate())); - - assertTrue(name + " " + count + ": public key", Arrays.areEqual(pk, pubParams.getEncoded())); - assertTrue(name + " " + count + ": secret key", Arrays.areEqual(sk, privParams.getEncoded())); - - // KEM Enc - KyberKEMGenerator KyberEncCipher = new KyberKEMGenerator(random); - SecretWithEncapsulation secWenc = KyberEncCipher.generateEncapsulated(pubParams); - byte[] generated_cipher_text = secWenc.getEncapsulation(); - - //assertTrue(name + " " + count + ": kem_enc cipher text", Arrays.areEqual(ct, generated_cipher_text)); - byte[] secret = secWenc.getSecret(); - assertTrue(name + " " + count + ": kem_enc key", Arrays.areEqual(ss, 0, secret.length, secret, 0, secret.length)); - - // KEM Dec - KyberKEMExtractor KyberDecCipher = new KyberKEMExtractor(privParams); - - byte[] dec_key = KyberDecCipher.extractSecret(generated_cipher_text); - - assertTrue(name + " " + count + ": kem_dec ss", Arrays.areEqual(ss, 0, dec_key.length, dec_key, 0, dec_key.length)); - assertTrue(name + " " + count + ": kem_dec key", Arrays.areEqual(dec_key, secret)); - // } - // catch (AssertionError e) { - // // System.out.println("Failed assertion error."); - // // System.out.println(); - - // // System.out.println(); - // continue; - // } - } - buf.clear(); - - continue; - } - - int a = line.indexOf("="); - if (a > -1) - { - buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); - } - } - // System.out.println("testing successful!"); - } - } - - public void testKyberRandom() - { - SecureRandom random = new SecureRandom(); - KyberKeyPairGenerator keyGen = new KyberKeyPairGenerator(); - - keyGen.init(new KyberKeyGenerationParameters(random, KyberParameters.kyber1024)); - - for (int i = 0; i != 1000; i++) - { - AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); - - KyberKEMGenerator kemGen = new KyberKEMGenerator(random); - - SecretWithEncapsulation secretEncap = kemGen.generateEncapsulated(keyPair.getPublic()); - - KyberKEMExtractor kemExtract = new KyberKEMExtractor((KyberPrivateKeyParameters)keyPair.getPrivate()); - - byte[] decryptedSharedSecret = kemExtract.extractSecret(secretEncap.getEncapsulation()); - - assertTrue(Arrays.areEqual(secretEncap.getSecret(), decryptedSharedSecret)); - } - } -} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/FalconTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/FalconTest.java index 5126132033..efc6335926 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/FalconTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/FalconTest.java @@ -39,16 +39,16 @@ public void testVectors() FalconParameters.falcon_1024 }; - TestSampler sampler = new TestSampler(); - for (int fileindex = 0; fileindex < files.length; fileindex++) { String name = files[fileindex]; - // System.out.println("testing: " + name); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/falcon", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); @@ -141,34 +141,42 @@ public void testVectors() // System.out.println("testing successful!"); } } - - public void testFalconRandom() - { - byte[] msg = Strings.toByteArray("Hello World!"); - FalconKeyPairGenerator keyGen = new FalconKeyPairGenerator(); + public void testRandom() + throws Exception + { SecureRandom random = new SecureRandom(); + byte[] msg = Strings.toByteArray("Hello World!"); + FalconKeyPairGenerator keyGen = new FalconKeyPairGenerator(); keyGen.init(new FalconKeyGenerationParameters(random, FalconParameters.falcon_512)); - for (int i = 0; i != 100; i++) + for (int i = 0; i < 10; ++i) { AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); - // sign - FalconSigner signer = new FalconSigner(); - FalconPrivateKeyParameters skparam = (FalconPrivateKeyParameters)keyPair.getPrivate(); - ParametersWithRandom skwrand = new ParametersWithRandom(skparam, random); - signer.init(true, skwrand); - - byte[] sigGenerated = signer.generateSignature(msg); + FalconPrivateKeyParameters privParams = (FalconPrivateKeyParameters)keyPair.getPrivate(); + FalconPublicKeyParameters pubParams = (FalconPublicKeyParameters)keyPair.getPublic(); - // verify - FalconSigner verifier = new FalconSigner(); - FalconPublicKeyParameters pkparam = (FalconPublicKeyParameters)keyPair.getPublic(); - verifier.init(false, pkparam); + privParams = (FalconPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo(privParams)); + pubParams = (FalconPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubParams)); + + for (int j = 0; j < 10; ++j) + { + // sign + FalconSigner signer = new FalconSigner(); + signer.init(true, new ParametersWithRandom(privParams, random)); + byte[] signature = signer.generateSignature(msg); + + // verify + FalconSigner verifier = new FalconSigner(); + verifier.init(false, pubParams); + boolean verified = verifier.verifySignature(msg, signature); - assertTrue("count = " + i, verifier.verifySignature(msg, sigGenerated)); + assertTrue("count = " + i, verified); + } } } } diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/FrodoVectorTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/FrodoVectorTest.java index 1e6c6d7ef6..3d0b7031b6 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/FrodoVectorTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/FrodoVectorTest.java @@ -58,16 +58,16 @@ public void testVectors() FrodoParameters.frodokem1344shake }; - TestSampler sampler = new TestSampler(); for (int fileIndex = 0; fileIndex != files.length; fileIndex++) { String name = files[fileIndex]; - // System.out.println("testing: " + name); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/frodo", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/HQCTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/HQCTest.java index bb4fd1b538..b133b888b3 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/HQCTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/HQCTest.java @@ -4,7 +4,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; -import java.util.Random; import junit.framework.TestCase; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; @@ -42,9 +41,9 @@ public void testVectors() String[] files; // test cases files = new String[]{ - "hqc-128_kat.rsp", - "hqc-192_kat.rsp", - "hqc-256_kat.rsp", + "HQC-128.rsp", + "HQC-192.rsp", + "HQC-256.rsp", }; HQCParameters[] listParams = new HQCParameters[]{ @@ -53,19 +52,16 @@ public void testVectors() HQCParameters.hqc256 }; - TestSampler sampler = new TestSampler(); for (int fileIndex = 0; fileIndex < files.length; fileIndex++) { - // System.out.println("Working Directory = " + System.getProperty("user.dir")); String name = files[fileIndex]; - // System.out.println("testing: " + name); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/hqc", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line = null; HashMap buf = new HashMap(); - Random rnd = new Random(System.currentTimeMillis()); - + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/LMSTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/LMSTest.java index 3a6484a5c0..27091be9c5 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/LMSTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/LMSTest.java @@ -8,6 +8,7 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.pqc.crypto.ExhaustedPrivateKeyException; +import org.bouncycastle.pqc.crypto.lms.HSSPrivateKeyParameters; import org.bouncycastle.pqc.crypto.lms.LMOtsParameters; import org.bouncycastle.pqc.crypto.lms.LMSKeyGenerationParameters; import org.bouncycastle.pqc.crypto.lms.LMSKeyPairGenerator; @@ -111,6 +112,7 @@ public void testKeyGenAndSignTwoSigsWithShard() LMSSigner signer = new LMSSigner(); assertEquals(2, privKey.getUsagesRemaining()); + assertEquals(2, privKey.getIndexLimit()); assertEquals(0, privKey.getIndex()); signer.init(true, privKey); @@ -158,7 +160,7 @@ public void testKeyGenAndSignTwoSigsWithShard() PrivateKeyInfo pInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(kp.getPrivate()); AsymmetricKeyParameter pKey = PrivateKeyFactory.createKey(pInfo.getEncoded()); - signer.init(false, ((LMSPrivateKeyParameters)pKey).getPublicKey()); + signer.init(false, ((HSSPrivateKeyParameters)pKey).getPublicKey()); assertTrue(signer.verifySignature(msg1, sig1)); } diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/MLDSATest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/MLDSATest.java new file mode 100644 index 0000000000..d3e5a14588 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/MLDSATest.java @@ -0,0 +1,761 @@ +package org.bouncycastle.pqc.crypto.test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.mldsa.HashMLDSASigner; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSASigner; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; + +public class MLDSATest + extends TestCase +{ + private static final Map PARAMETERS_MAP = new HashMap() + { + { + put("ML-DSA-44", MLDSAParameters.ml_dsa_44); + put("ML-DSA-65", MLDSAParameters.ml_dsa_65); + put("ML-DSA-87", MLDSAParameters.ml_dsa_87); + } + }; + + private static final MLDSAParameters[] PARAMETER_SETS = new MLDSAParameters[] + { + MLDSAParameters.ml_dsa_44, + MLDSAParameters.ml_dsa_65, + MLDSAParameters.ml_dsa_87, + }; + + public void testConsistency() + throws Exception + { + SecureRandom random = new SecureRandom(); + + MLDSAKeyPairGenerator kpg = new MLDSAKeyPairGenerator(); + + for (int idx = 0; idx != PARAMETER_SETS.length; idx++) + { + MLDSAParameters parameters = PARAMETER_SETS[idx]; + kpg.init(new MLDSAKeyGenerationParameters(random, parameters)); + + int msgSize = 0; + do + { + byte[] msg = new byte[msgSize]; + + for (int i = 0; i < 2; ++i) + { + AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); + + MLDSASigner signer = new MLDSASigner(); + + for (int j = 0; j < 2; ++j) + { + random.nextBytes(msg); + + // sign + signer.init(true, new ParametersWithRandom(kp.getPrivate(), random)); + signer.update(msg, 0, msg.length); + byte[] signature = signer.generateSignature(); + + // verify + signer.init(false, kp.getPublic()); + signer.update(msg, 0, msg.length); + boolean shouldVerify = signer.verifySignature(signature); + + assertTrue("count = " + i, shouldVerify); + } + } + + msgSize += msgSize < 128 ? 1 : 17; + } + while (msgSize <= 2048); + } + } + + public void testKeyGen() + throws IOException + { + String[] files = new String[]{ + "keyGen_ML-DSA-44.txt", + "keyGen_ML-DSA-65.txt", + "keyGen_ML-DSA-87.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] seed = Hex.decode((String)buf.get("seed")); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); + + FixedSecureRandom random = new FixedSecureRandom(seed); + MLDSAParameters parameters = PARAMETER_SETS[fileIndex]; + + MLDSAKeyPairGenerator kpGen = new MLDSAKeyPairGenerator(); + kpGen.init(new MLDSAKeyGenerationParameters(random, parameters)); + + // + // Generate keys and test. + // + AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); + + MLDSAPublicKeyParameters pubParams = (MLDSAPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(kp.getPublic())); + MLDSAPrivateKeyParameters privParams = (MLDSAPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo(kp.getPrivate())); + + assertTrue(name + ": public key", Arrays.areEqual(pk, pubParams.getEncoded())); + assertTrue(name + ": secret key", Arrays.areEqual(sk, privParams.getEncoded())); + } + buf.clear(); + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testSigGen() + throws IOException + { + String[] files = new String[]{ + "sigGen_ML-DSA-44.txt", + "sigGen_ML-DSA-65.txt", + "sigGen_ML-DSA-87.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean deterministic = !buf.containsKey("rnd"); + byte[] sk = Hex.decode((String)buf.get("sk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + byte[] rnd = new byte[32]; + if (!deterministic) + { + rnd = Hex.decode((String)buf.get("rnd")); + } + + MLDSAParameters parameters = PARAMETER_SETS[fileIndex]; + + MLDSAPrivateKeyParameters privParams = new MLDSAPrivateKeyParameters(parameters, sk, null); + + // sign + InternalMLDSASigner signer = new InternalMLDSASigner(); + + signer.init(true, privParams); + + byte[] sigGenerated = signer.internalGenerateSignature(message, rnd); + + assertTrue(Arrays.areEqual(sigGenerated, signature)); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testSigVer() + throws IOException + { + String[] files = new String[]{ + "sigVer_ML-DSA-44.txt", + "sigVer_ML-DSA-65.txt", + "sigVer_ML-DSA-87.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/dilithium/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean testPassed = TestUtils.parseBoolean((String)buf.get("testPassed")); + String reason = (String)buf.get("reason"); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + + MLDSAParameters parameters = PARAMETER_SETS[fileIndex]; + + MLDSAPublicKeyParameters pubParams = new MLDSAPublicKeyParameters(parameters, pk); + + InternalMLDSASigner verifier = new InternalMLDSASigner(); + verifier.init(false, pubParams); + + boolean ver = verifier.internalVerifySignature(message, signature); + assertEquals("expected " + testPassed + " " + reason, testPassed, ver); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testRNG() + { + String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; + byte[] seed = Hex.decode(temp); + + NISTSecureRandom r = new NISTSecureRandom(seed, null); + + String testBytesString = "7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2D"; + byte[] testBytes = Hex.decode(testBytesString); + + byte[] randBytes = new byte[testBytes.length]; + r.nextBytes(randBytes); + + assertTrue(Arrays.areEqual(randBytes, testBytes)); + } + + public void testKeyGenCombinedVectorSet() + throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/mldsa", "ML-DSA-keyGen.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] seed = Hex.decode((String)buf.get("seed")); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); + + FixedSecureRandom random = new FixedSecureRandom(seed); + MLDSAParameters parameters = (MLDSAParameters)PARAMETERS_MAP.get((String)buf.get("parameterSet")); + + MLDSAKeyPairGenerator kpGen = new MLDSAKeyPairGenerator(); + kpGen.init(new MLDSAKeyGenerationParameters(random, parameters)); + + // + // Generate keys and test. + // + AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); + + MLDSAPublicKeyParameters pubParams = (MLDSAPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(kp.getPublic())); + MLDSAPrivateKeyParameters privParams = (MLDSAPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo(kp.getPrivate())); + + assertTrue(Arrays.areEqual(pk, pubParams.getEncoded())); + assertTrue(Arrays.areEqual(sk, privParams.getEncoded())); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testSigGenCombinedVectorSet() + throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/mldsa", "ML-DSA-sigGen.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean deterministic = TestUtils.parseBoolean((String)buf.get("deterministic")); + byte[] sk = Hex.decode((String)buf.get("sk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + byte[] rnd = null; + if (!deterministic) + { + rnd = Hex.decode((String)buf.get("rnd")); + } + else + { + rnd = new byte[32]; + } + + MLDSAParameters parameters = (MLDSAParameters)PARAMETERS_MAP.get((String)buf.get("parameterSet")); + MLDSAPrivateKeyParameters privParams = new MLDSAPrivateKeyParameters(parameters, sk, null); + + // sign + InternalMLDSASigner signer = new InternalMLDSASigner(); + + signer.init(true, privParams); + byte[] sigGenerated; + + sigGenerated = signer.internalGenerateSignature(message, rnd); + assertTrue(Arrays.areEqual(sigGenerated, signature)); + + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testSigVerCombinedVectorSet() + throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/mldsa", "ML-DSA-sigVer.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (!buf.isEmpty()) + { + boolean expectedResult = TestUtils.parseBoolean((String)buf.get("testPassed")); + + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + + MLDSAParameters parameters = (MLDSAParameters)PARAMETERS_MAP.get((String)buf.get("parameterSet")); + + MLDSAPublicKeyParameters pubParams = new MLDSAPublicKeyParameters(parameters, pk); + + InternalMLDSASigner verifier = new InternalMLDSASigner(); + verifier.init(false, pubParams); + + boolean verifyResult = verifier.internalVerifySignature(message, signature); + assertEquals(expectedResult, verifyResult); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testMLDSARejection() + throws Exception + { + rejectionExternalMuTest(MLDSAParameters.ml_dsa_44, "dilithium_external_mu_rejection_vectors_44.h"); + rejectionExternalMuTest(MLDSAParameters.ml_dsa_65, "dilithium_external_mu_rejection_vectors_65.h"); + rejectionExternalMuTest(MLDSAParameters.ml_dsa_87, "dilithium_external_mu_rejection_vectors_87.h"); + rejectionPrehashTest(MLDSAParameters.ml_dsa_44, "dilithium_prehash_rejection_vectors_44.h"); + rejectionPrehashTest(MLDSAParameters.ml_dsa_65, "dilithium_prehash_rejection_vectors_65.h"); + rejectionPrehashTest(MLDSAParameters.ml_dsa_87, "dilithium_prehash_rejection_vectors_87.h"); + rejectionTest(MLDSAParameters.ml_dsa_44, "dilithium_pure_rejection_vectors_44.h"); + rejectionTest(MLDSAParameters.ml_dsa_65, "dilithium_pure_rejection_vectors_65.h"); + rejectionTest(MLDSAParameters.ml_dsa_87, "dilithium_pure_rejection_vectors_87.h"); + rejectionUpStreamTest(MLDSAParameters.ml_dsa_44, "dilithium_rejection_upstream_vectors_44.h"); + rejectionUpStreamTest(MLDSAParameters.ml_dsa_65, "dilithium_rejection_upstream_vectors_65.h"); + rejectionUpStreamTest(MLDSAParameters.ml_dsa_87, "dilithium_rejection_upstream_vectors_87.h"); + rejectionUpStreamTest(MLDSAParameters.ml_dsa_44, "dilithium_rejection_vectors_44.h"); + rejectionUpStreamTest(MLDSAParameters.ml_dsa_65, "dilithium_rejection_vectors_65.h"); + rejectionUpStreamTest(MLDSAParameters.ml_dsa_87, "dilithium_rejection_vectors_87.h"); + } + + private interface RejectionOperation + { + byte[] processSign(MLDSAPrivateKeyParameters privParams, byte[] msg) + throws CryptoException; + boolean processVerify(MLDSAPublicKeyParameters pubParams, byte[] msg, byte[] sig); + } + + private void rejectionTest(MLDSAParameters parameters, String filename, RejectionOperation operation) + throws Exception + { + List testVectors = parseTestVectors(TestResourceFinder.findTestResource("pqc/crypto/mldsa", filename)); + for (int i = 0; i < testVectors.size(); ++i) + { + TestVector t = (TestVector)testVectors.get(i); + FixedSecureRandom random = new FixedSecureRandom(t.seed); + + MLDSAKeyPairGenerator kpGen = new MLDSAKeyPairGenerator(); + kpGen.init(new MLDSAKeyGenerationParameters(random, parameters)); + + // + // Generate keys and test. + // + AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); + + MLDSAPublicKeyParameters pubParams = (MLDSAPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(kp.getPublic())); + MLDSAPrivateKeyParameters privParams = (MLDSAPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo(kp.getPrivate())); + + if (t.pk.length != 0) + { + assertTrue(Arrays.areEqual(t.pk, pubParams.getEncoded())); + } + if (t.sk.length != 0) + { + assertTrue(Arrays.areEqual(t.sk, privParams.getEncoded())); + } + byte[] signature = operation.processSign(privParams, t.msg); + if (t.sig.length != 0) + { + assertTrue(Arrays.areEqual(t.sig, signature)); + } + boolean shouldVerify = operation.processVerify(pubParams, t.msg, signature); + assertTrue(shouldVerify); + } + } + + private void rejectionExternalMuTest(MLDSAParameters parameters, String filename) + throws Exception + { + rejectionTest(parameters, filename, new RejectionOperation() + { + public byte[] processSign(MLDSAPrivateKeyParameters privParams, byte[] msg) + throws CryptoException + { + InternalMLDSASigner signer = new InternalMLDSASigner(); + signer.init(true, privParams); + return signer.generateMuSignature(msg); + } + + public boolean processVerify(MLDSAPublicKeyParameters pubParams, byte[] msg, byte[] sig) + { + InternalMLDSASigner signer = new InternalMLDSASigner(); + signer.init(false, pubParams); + return signer.verifyMuSignature(msg, sig); + } + }); + } + + private void rejectionPrehashTest(MLDSAParameters parameters, String filename) + throws Exception + { + rejectionTest(parameters, filename, new RejectionOperation() + { + public byte[] processSign(MLDSAPrivateKeyParameters privParams, byte[] msg) + throws CryptoException + { + HashMLDSASigner signer = new HashMLDSASigner(); + signer.init(true, privParams); + signer.update(msg, 0, msg.length); + return signer.generateSignature(); + } + + public boolean processVerify(MLDSAPublicKeyParameters pubParams, byte[] msg, byte[] sig) + { + HashMLDSASigner signer = new HashMLDSASigner(); + signer.init(false, pubParams); + signer.update(msg, 0, msg.length); + return signer.verifySignature(sig); + } + }); + } + + private void rejectionTest(MLDSAParameters parameters, String filename) + throws Exception + { + rejectionTest(parameters, filename, new RejectionOperation() + { + public byte[] processSign(MLDSAPrivateKeyParameters privParams, byte[] msg) + throws CryptoException + { + InternalMLDSASigner signer = new InternalMLDSASigner(); + + signer.init(true, privParams); + signer.update(msg, 0, msg.length); + return signer.generateSignature(); + } + + public boolean processVerify(MLDSAPublicKeyParameters pubParams, byte[] msg, byte[] sig) + { + InternalMLDSASigner signer = new InternalMLDSASigner(); + signer.init(false, pubParams); + signer.update(msg, 0, msg.length); + return signer.verifySignature(sig); + } + }); + } + + private void rejectionUpStreamTest(MLDSAParameters parameters, String filename) + throws Exception + { + rejectionTest(parameters, filename, new RejectionOperation() + { + public byte[] processSign(MLDSAPrivateKeyParameters privParams, byte[] msg) + throws CryptoException + { + InternalMLDSASigner signer = new InternalMLDSASigner(); + signer.init(true, privParams); + return signer.internalGenerateSignature(msg, new byte[32]); + } + + public boolean processVerify(MLDSAPublicKeyParameters pubParams, byte[] msg, byte[] sig) + { + InternalMLDSASigner signer = new InternalMLDSASigner(); + signer.init(false, pubParams); + signer.update(msg, 0, msg.length); + return signer.internalVerifySignature(msg, sig); + } + }); + } + + private static List parseTestVectors(InputStream src) + throws IOException + { + List vectors = new ArrayList(); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + TestVector currentVector = null; + String currentField = null; + List currentBytes = null; + Pattern fieldPattern = Pattern.compile("\\.(seed|pk|sk|msg|sig|key_hash|sig_hash)\\s*=\\s*\\{"); + Pattern hexPattern = Pattern.compile("0x([0-9a-fA-F]{2})"); + + String line; + while ((line = bin.readLine()) != null) + { + // Skip comments and empty lines + line = line.split("//")[0].trim(); + if (line.length() == 0) + { + continue; + } + + // Look for test vector array start + if (line.indexOf("dilithium_rejection_testvectors[] = ") >= 0) + { + continue; + } + + // Start new test vector + if (line.startsWith("{") && currentVector == null) + { + currentVector = new TestVector(); + continue; + } + + // Detect field start + Matcher fieldMatcher = fieldPattern.matcher(line); + if (fieldMatcher.find()) + { + currentField = fieldMatcher.group(1); + currentBytes = new ArrayList(); + line = line.substring(fieldMatcher.end()).trim(); + } + + // Collect hex values if in field + if (currentField != null) + { + Matcher hexMatcher = hexPattern.matcher(line); + while (hexMatcher.find()) + { + String hex = hexMatcher.group(1); + currentBytes.add(new Byte((byte)Integer.parseInt(hex, 16))); + } + + // Check for field end + if (line.indexOf("},") >= 0) + { + setField(currentVector, currentField, currentBytes); + currentField = null; + currentBytes = null; + } + continue; + } + + // End of test vector + if (line.startsWith("},") && currentVector != null) + { + vectors.add(currentVector); + currentVector = null; + } + } + + return vectors; + } + + private static void setField(TestVector vector, String field, List bytes) + { + byte[] byteArray = new byte[bytes.size()]; + for (int i = 0; i < bytes.size(); i++) + { + byteArray[i] = ((Byte)bytes.get(i)).byteValue(); + } + + if ("seed".equals(field)) + { + vector.seed = byteArray; + } + else if ("pk".equals(field)) + { + vector.pk = byteArray; + } + else if ("sk".equals(field)) + { + vector.sk = byteArray; + } + else if ("msg".equals(field)) + { + vector.msg = byteArray; + } + else if ("sig".equals(field)) + { + vector.sig = byteArray; + } + // else ignore + } + + static class TestVector + { + byte[] seed = new byte[0]; + byte[] pk = new byte[0]; + byte[] sk = new byte[0]; + byte[] msg = new byte[0]; + byte[] sig = new byte[0]; + } + + private static class InternalMLDSASigner + extends MLDSASigner + { + public byte[] internalGenerateSignature(byte[] message, byte[] rnd) + { + return super.internalGenerateSignature(message, rnd); + } + + public boolean internalVerifySignature(byte[] message, byte[] signature) + { + return super.internalVerifySignature(message, signature); + } + } +} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/MLKEMTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/MLKEMTest.java new file mode 100644 index 0000000000..beb3537abf --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/MLKEMTest.java @@ -0,0 +1,539 @@ +package org.bouncycastle.pqc.crypto.test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.crypto.util.DEROtherInfo; +import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PQCOtherInfoGenerator; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; + +public class MLKEMTest + extends TestCase +{ + private static final Map parametersMap = new HashMap() + { + { + put("ML-KEM-512", MLKEMParameters.ml_kem_512); + put("ML-KEM-768", MLKEMParameters.ml_kem_768); + put("ML-KEM-1024", MLKEMParameters.ml_kem_1024); + } + }; + + public void testKeyGen() throws IOException + { + MLKEMParameters[] params = new MLKEMParameters[]{ + MLKEMParameters.ml_kem_512, + MLKEMParameters.ml_kem_768, + MLKEMParameters.ml_kem_1024, + }; + + String[] files = new String[]{ + "keyGen_ML-KEM-512.txt", + "keyGen_ML-KEM-768.txt", + "keyGen_ML-KEM-1024.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/kyber/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] z = Hex.decode((String)buf.get("z")); + byte[] d = Hex.decode((String)buf.get("d")); + byte[] ek = Hex.decode((String)buf.get("ek")); + byte[] dk = Hex.decode((String)buf.get("dk")); + + MLKEMParameters parameters = params[fileIndex]; + + MLKEMKeyPairGenerator kpGen = new MLKEMKeyPairGenerator(); + MLKEMKeyGenerationParameters genParam = new MLKEMKeyGenerationParameters(new SecureRandom(), parameters); + + // + // Generate keys and test. + // + kpGen.init(genParam); + AsymmetricCipherKeyPair kp = kpGen.internalGenerateKeyPair(d, z); + + MLKEMPublicKeyParameters pubParams = (MLKEMPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((MLKEMPublicKeyParameters)kp.getPublic())); + MLKEMPrivateKeyParameters privParams = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((MLKEMPrivateKeyParameters)kp.getPrivate())); + + assertTrue(name + ": public key", Arrays.areEqual(ek, pubParams.getEncoded())); + assertTrue(name + ": secret key", Arrays.areEqual(dk, privParams.getEncoded())); + + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testKeyGenCombinedVectorSet() throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/mlkem", "ML-KEM-keyGen.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] z = Hex.decode((String)buf.get("z")); + byte[] d = Hex.decode((String)buf.get("d")); + byte[] ek = Hex.decode((String)buf.get("ek")); + byte[] dk = Hex.decode((String)buf.get("dk")); + + MLKEMParameters parameters = (MLKEMParameters)parametersMap.get((String)buf.get("parameterSet")); + + MLKEMKeyPairGenerator kpGen = new MLKEMKeyPairGenerator(); + MLKEMKeyGenerationParameters genParam = new MLKEMKeyGenerationParameters(new SecureRandom(), parameters); + + // + // Generate keys and test. + // + kpGen.init(genParam); + AsymmetricCipherKeyPair kp = kpGen.internalGenerateKeyPair(d, z); + + MLKEMPublicKeyParameters pubParams = (MLKEMPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((MLKEMPublicKeyParameters)kp.getPublic())); + MLKEMPrivateKeyParameters privParams = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((MLKEMPrivateKeyParameters)kp.getPrivate())); + + assertTrue("public key", Arrays.areEqual(ek, pubParams.getEncoded())); + assertTrue("secret key", Arrays.areEqual(dk, privParams.getEncoded())); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testEncapDecap_encapsulation() throws IOException + { + MLKEMParameters[] params = new MLKEMParameters[]{ + MLKEMParameters.ml_kem_512, + MLKEMParameters.ml_kem_768, + MLKEMParameters.ml_kem_1024, + }; + + String[] files = new String[]{ + "encapDecap_encapsulation_ML-KEM-512.txt", + "encapDecap_encapsulation_ML-KEM-768.txt", + "encapDecap_encapsulation_ML-KEM-1024.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/kyber/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] m = Hex.decode((String)buf.get("m")); + byte[] c = Hex.decode((String)buf.get("c")); + byte[] k = Hex.decode((String)buf.get("k")); +// String reason = (String)buf.get("reason"); + byte[] ek = Hex.decode((String)buf.get("ek")); +// byte[] dk = Hex.decode((String)buf.get("dk")); + + MLKEMParameters parameters = params[fileIndex]; + + MLKEMPublicKeyParameters pubKey = new MLKEMPublicKeyParameters(parameters, ek); +// MLKEMPrivateKeyParameters privKey = new MLKEMPrivateKeyParameters(parameters, dk); + + MLKEMPublicKeyParameters pubParams = (MLKEMPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((MLKEMPublicKeyParameters)pubKey)); +// MLKEMPrivateKeyParameters privParams = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey( +// PrivateKeyInfoFactory.createPrivateKeyInfo((MLKEMPrivateKeyParameters)privKey)); + + // KEM Enc + MLKEMGenerator generator = new MLKEMGenerator(new SecureRandom()); + SecretWithEncapsulation secWenc = generator.internalGenerateEncapsulated(pubParams, m); + byte[] generated_cipher_text = secWenc.getEncapsulation(); + + byte[] secret = secWenc.getSecret(); + assertTrue(name + ": c", Arrays.areEqual(c, generated_cipher_text)); + assertTrue(name + ": k", Arrays.areEqual(k, 0, secret.length, secret, 0, secret.length)); + + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testEncapDecap_decapsulation() throws IOException + { + MLKEMParameters[] params = new MLKEMParameters[]{ + MLKEMParameters.ml_kem_512, + MLKEMParameters.ml_kem_768, + MLKEMParameters.ml_kem_1024, + }; + + String[] files = new String[]{ + "encapDecap_decapsulation_ML-KEM-512.txt", + "encapDecap_decapsulation_ML-KEM-768.txt", + "encapDecap_decapsulation_ML-KEM-1024.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/kyber/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] c = Hex.decode((String)buf.get("c")); + byte[] k = Hex.decode((String)buf.get("k")); +// String reason = (String)buf.get("reason"); +// byte[] ek = Hex.decode((String)buf.get("ek")); + byte[] dk = Hex.decode((String)buf.get("dk")); + + MLKEMParameters parameters = params[fileIndex]; + +// MLKEMPublicKeyParameters pubKey = new MLKEMPublicKeyParameters(parameters, ek); + MLKEMPrivateKeyParameters privKey = new MLKEMPrivateKeyParameters(parameters, dk); + +// MLKEMPublicKeyParameters pubParams = (MLKEMPublicKeyParameters)PublicKeyFactory.createKey( +// SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((MLKEMPublicKeyParameters)pubKey)); + MLKEMPrivateKeyParameters privParams = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((MLKEMPrivateKeyParameters)privKey)); + + MLKEMExtractor extractor = new MLKEMExtractor(privParams); + + byte[] dec_key = extractor.extractSecret(c); + + assertTrue(name + ": dk", Arrays.areEqual(dec_key, k)); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testEncapDecapCombinedVectorSet() throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/mlkem", "ML-KEM-encapDecap.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] c = Hex.decode((String)buf.get("c")); + byte[] k = Hex.decode((String)buf.get("k")); + + MLKEMParameters parameters = (MLKEMParameters)parametersMap.get((String)buf.get("parameterSet")); + + String function = (String)buf.get("function"); + if ("encapsulation".equals(function)) + { + byte[] m = Hex.decode((String)buf.get("m")); + byte[] ek = Hex.decode((String)buf.get("ek")); + + MLKEMPublicKeyParameters pubKey = new MLKEMPublicKeyParameters(parameters, ek); + + MLKEMPublicKeyParameters pubParams = (MLKEMPublicKeyParameters)PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((MLKEMPublicKeyParameters)pubKey)); + + MLKEMGenerator generator = new MLKEMGenerator(new SecureRandom()); + SecretWithEncapsulation secWenc = generator.internalGenerateEncapsulated(pubParams, m); + byte[] generated_cipher_text = secWenc.getEncapsulation(); + byte[] secret = secWenc.getSecret(); + + assertTrue("encap: c", Arrays.areEqual(c, generated_cipher_text)); + assertTrue("encap: k", Arrays.areEqual(k, 0, secret.length, secret, 0, secret.length)); + } + else + { + byte[] dk = Hex.decode((String)buf.get("dk")); + + MLKEMPrivateKeyParameters privKey = new MLKEMPrivateKeyParameters(parameters, dk); + + MLKEMPrivateKeyParameters privParams = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((MLKEMPrivateKeyParameters)privKey)); + + MLKEMExtractor extractor = new MLKEMExtractor(privParams); + byte[] dec_key = extractor.extractSecret(c); + + assertTrue("decap: dk", Arrays.areEqual(dec_key, k)); + } + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testModulus() throws IOException + { + MLKEMParameters[] params = new MLKEMParameters[]{ + MLKEMParameters.ml_kem_512, + MLKEMParameters.ml_kem_768, + MLKEMParameters.ml_kem_1024, + }; + + String[] files = new String[]{ + "ML-KEM-512.txt", + "ML-KEM-768.txt", + "ML-KEM-1024.txt", + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/kyber/modulus", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + while ((line = bin.readLine()) != null) + { + line = line.trim(); + byte[] key = Hex.decode(line); + MLKEMParameters parameters = params[fileIndex]; + + MLKEMPublicKeyParameters pubParams = (MLKEMPublicKeyParameters) PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new MLKEMPublicKeyParameters(parameters, key))); + + // KEM Enc + SecureRandom random = new SecureRandom(); + MLKEMGenerator generator = new MLKEMGenerator(random); + try + { + SecretWithEncapsulation secWenc = generator.generateEncapsulated(pubParams); + byte[] generated_cipher_text = secWenc.getEncapsulation(); + fail(); + } + catch (Exception ignored) + { + } + } + } + } + + public void testPrivInfoGeneration() + throws IOException + { + SecureRandom random = new SecureRandom(); + PQCOtherInfoGenerator.PartyU partyU = new PQCOtherInfoGenerator.PartyU(MLKEMParameters.ml_kem_512, + new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), Hex.decode("beef"), Hex.decode("cafe"), random); + + byte[] partA = partyU.getSuppPrivInfoPartA(); + + PQCOtherInfoGenerator.PartyV partyV = new PQCOtherInfoGenerator.PartyV(MLKEMParameters.ml_kem_512, + new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), Hex.decode("beef"), Hex.decode("cafe"), random); + + byte[] partB = partyV.getSuppPrivInfoPartB(partA); + + DEROtherInfo otherInfoU = partyU.generate(partB); + + DEROtherInfo otherInfoV = partyV.generate(); + + assertTrue(Arrays.areEqual(otherInfoU.getEncoded(), otherInfoV.getEncoded())); + } + + public void testMLKEM() + { + byte[] z = Hex.decode("99E3246884181F8E1DD44E0C7629093330221FD67D9B7D6E1510B2DBAD8762F7"); + byte[] d = Hex.decode("49AC8B99BB1E6A8EA818261F8BE68BDEAA52897E7EC6C40B530BC760AB77DCE3"); + String expectedPubKey = "A04184D4BC7B532A0F70A54D7757CDE6175A6843B861CB2BC4830C0012554CFC5D2C8A2027AA3CD967130E9B96241B11C4320C7649CC23A71BAFE691AFC08E680BCEF42907000718E4EACE8DA28214197BE1C269DA9CB541E1A3CE97CFADF9C6058780FE6793DBFA8218A2760B802B8DA2AA271A38772523A76736A7A31B9D3037AD21CEBB11A472B8792EB17558B940E70883F264592C689B240BB43D5408BF446432F412F4B9A5F6865CC252A43CF40A320391555591D67561FDD05353AB6B019B3A08A73353D51B6113AB2FA51D975648EE254AF89A230504A236A4658257740BDCBBE1708AB022C3C588A410DB3B9C308A06275BDF5B4859D3A2617A295E1A22F90198BAD0166F4A943417C5B831736CB2C8580ABFDE5714B586ABEEC0A175A08BC710C7A2895DE93AC438061BF7765D0D21CD418167CAF89D1EFC3448BCBB96D69B3E010C82D15CAB6CACC6799D3639669A5B21A633C865F8593B5B7BC800262BB837A924A6C5440E4FC73B41B23092C3912F4C6BEBB4C7B4C62908B03775666C22220DF9C88823E344C7308332345C8B795D34E8C051F21F5A21C214B69841358709B1C305B32CC2C3806AE9CCD3819FFF4507FE520FBFC27199BC23BE6B9B2D2AC1717579AC769279E2A7AAC68A371A47BA3A7DBE016F14E1A727333663C4A5CD1A0F8836CF7B5C49AC51485CA60345C990E06888720003731322C5B8CD5E6907FDA1157F468FD3FC20FA8175EEC95C291A262BA8C5BE990872418930852339D88A19B37FEFA3CFE82175C224407CA414BAEB37923B4D2D83134AE154E490A9B45A0563B06C953C3301450A2176A07C614A74E3478E48509F9A60AE945A8EBC7815121D90A3B0E07091A096CF02C57B25BCA58126AD0C629CE166A7EDB4B33221A0D3F72B85D562EC698B7D0A913D73806F1C5C87B38EC003CB303A3DC51B4B35356A67826D6EDAA8FEB93B98493B2D1C11B676A6AD9506A1AAAE13A824C7C08D1C6C2C4DBA9642C76EA7F6C8264B64A23CCCA9A74635FCBF03E00F1B5722B214376790793B2C4F0A13B5C40760B4218E1D2594DCB30A70D9C1782A5DD30576FA4144BFC8416EDA8118FC6472F56A979586F33BB070FB0F1B0B10BC4897EBE01BCA3893D4E16ADB25093A7417D0708C83A26322E22E6330091E30152BF823597C04CCF4CFC7331578F43A2726CCB428289A90C863259DD180C5FF142BEF41C7717094BE07856DA2B140FA67710967356AA47DFBC8D255B4722AB86D439B7E0A6090251D2D4C1ED5F20BBE6807BF65A90B7CB2EC0102AF02809DC9AC7D0A3ABC69C18365BCFF59185F33996887746185906C0191AED4407E139446459BE29C6822717644353D24AB6339156A9C424909F0A9025BB74720779BE43F16D81C8CC666E99710D8C68BB5CC4E12F314E925A551F09CC59003A1F88103C254BB978D75F394D3540E31E771CDA36E39EC54A62B5832664D821A72F1E6AFBBA27F84295B2694C498498E812BC8E9378FE541CEC5891B25062901CB7212E3CDC46179EC5BCEC10BC0B9311DE05074290687FD6A5392671654284CD9C8CC3EBA80EB3B662EB53EB75116704A1FEB5C2D056338532868DDF24EB8992AB8565D9E490CADF14804360DAA90718EAB616BAB0765D33987B47EFB6599C5563235E61E4BE670E97955AB292D9732CB8930948AC82DF230AC72297A23679D6B94C17F1359483254FEDC2F05819F0D069A443B78E3FC6C3EF4714B05A3FCA81CBBA60242A7060CD885D8F39981BB18092B23DAA59FD9578388688A09BBA079BC809A54843A60385E2310BBCBCC0213CE3DFAAB33B47F9D6305BC95C6107813C585C4B657BF30542833B14949F573C0612AD524BAAE69590C1277B86C286571BF66B3CFF46A3858C09906A794DF4A06E9D4B0A2E43F10F72A6C6C47E5646E2C799B71C33ED2F01EEB45938EB7A4E2E2908C53558A540D350369FA189C616943F7981D7618CF02A5B0A2BCC422E857D1A47871253D08293C1C179BCDC0437069107418205FDB9856623B8CA6B694C96C084B17F13BB6DF12B2CFBBC2B0E0C34B00D0FCD0AECFB27924F6984E747BE2A09D83A8664590A8077331491A4F7D720843F23E652C6FA840308DB4020337AAD37967034A9FB523B67CA70330F02D9EA20C1E84CB8E5757C9E1896B60581441ED618AA5B26DA56C0A5A73C4DCFD755E610B4FC81FF84E21"; + String expectedPrivKey = "8C8B3722A82E550565521611EBBC63079944C9B1ABB3B0020FF12F631891A9C468D3A67BF6271280DA58D03CB042B3A461441637F929C273469AD15311E910DE18CB9537BA1BE42E98BB59E498A13FD440D0E69EE832B45CD95C382177D67096A18C07F1781663651BDCAC90DEDA3DDD143485864181C91FA2080F6DAB3F86204CEB64A7B4446895C03987A031CB4B6D9E0462FDA829172B6C012C638B29B5CD75A2C930A5596A3181C33A22D574D30261196BC350738D4FD9183A763336243ACED99B3221C71D8866895C4E52C119BF3280DAF80A95E15209A795C4435FBB3570FDB8AA9BF9AEFD43B094B781D5A81136DAB88B8799696556FEC6AE14B0BB8BE4695E9A124C2AB8FF4AB1229B8AAA8C6F41A60C34C7B56182C55C2C685E737C6CA00A23FB8A68C1CD61F30D3993A1653C1675AC5F0901A7160A73966408B8876B715396CFA4903FC69D60491F8146808C97CD5C533E71017909E97B835B86FF847B42A696375435E006061CF7A479463272114A89EB3EAF2246F0F8C104A14986828E0AD20420C9B37EA23F5C514949E77AD9E9AD12290DD1215E11DA274457AC86B1CE6864B122677F3718AA31B02580E64317178D38F25F609BC6C55BC374A1BF78EA8ECC219B30B74CBB3272A599238C93985170048F176775FB19962AC3B135AA59DB104F7114DBC2C2D42949ADECA6A85B323EE2B2B23A77D9DB235979A8E2D67CF7D2136BBBA71F269574B38888E1541340C19284074F9B7C8CF37EB01384E6E3822EC4882DFBBEC4E6098EF2B2FC177A1F0BCB65A57FDAA89315461BEB7885FB68B3CD096EDA596AC0E61DD7A9C507BC6345E0827DFCC8A3AC2DCE51AD731AA0EB932A6D0983992347CBEB3CD0D9C9719797CC21CF0062B0AD94CAD734C63E6B5D859CBE19F0368245351BF464D7505569790D2BB724D8659A9FEB1C7C473DC4D061E29863A2714BAC42ADCD1A8372776556F7928A7A44E94B6A25322D03C0A1622A7FD261522B7358F085BDFB60758762CB901031901B5EECF4920C81020A9B1781BCB9DD19A9DFB66458E7757C52CEC75B4BA740A24099CB56BB60A76B6901AA3E0169C9E83496D73C4C99435A28D613E97A1177F58B6CC595D3B2331E9CA7B57B74DC2C5277D26F2FE19240A55C35D6CFCA26C73E9A2D7C980D97960AE1A04698C16B398A5F20C35A0914145CE1674B71ABC6066A909A3E4B911E69D5A849430361F731B07246A6329B52361904225082D0AAC5B21D6B34862481A890C3C360766F04263603A6B73E802B1F70B2EB00046836B8F493BF10B90B8737C6C548449B294C47253BE26CA72336A632063AD3D0B48C8B0F4A34447EF13B764020DE739EB79ABA20E2BE1951825F293BEDD1089FCB0A91F560C8E17CDF52541DC2B81F972A7375B201F10C08D9B5BC8B95100054A3D0AAFF89BD08D6A0E7F2115A435231290460C9AD435A3B3CF35E52091EDD1890047BCC0AABB1ACEBC75F4A32BC1451ACC4969940788E89412188946C9143C5046BD1B458DF617C5DF533B052CD6038B7754034A23C2F7720134C7B4EACE01FAC0A2853A9285847ABBD06A3343A778AC6062E458BC5E61ECE1C0DE0206E6FE8A84034A7C5F1B005FB0A584051D3229B86C909AC5647B3D75569E05A88279D80E5C30F574DC327512C6BBE8101239EC62861F4BE67B05B9CDA9C545C13E7EB53CFF260AD9870199C21F8C63D64F0458A7141285023FEB829290872389644B0C3B73AC2C8E121A29BB1C43C19A233D56BED82740EB021C97B8EBBA40FF328B541760FCC372B52D3BC4FCBC06F424EAF253804D4CB46F41FF254C0C5BA483B44A87C219654555EC7C163C79B9CB760A2AD9BB722B93E0C28BD4B1685949C496EAB1AFF90919E3761B346838ABB2F01A91E554375AFDAAAF3826E6DB79FE7353A7A578A7C0598CE28B6D9915214236BBFFA6D45B6376A07924A39A7BE818286715C8A3C110CD76C02E0417AF138BDB95C3CCA798AC809ED69CFB672B6FDDC24D89C06A6558814AB0C21C62B2F84C0E3E0803DB337A4E0C7127A6B4C8C08B1D1A76BF07EB6E5B5BB47A16C74BC548375FB29CD789A5CFF91BDBD071859F4846E355BB0D29484E264DFF36C9177A7ACA78908879695CA87F25436BC12630724BB22F0CB64897FE5C41195280DA04184D4BC7B532A0F70A54D7757CDE6175A6843B861CB2BC4830C0012554CFC5D2C8A2027AA3CD967130E9B96241B11C4320C7649CC23A71BAFE691AFC08E680BCEF42907000718E4EACE8DA28214197BE1C269DA9CB541E1A3CE97CFADF9C6058780FE6793DBFA8218A2760B802B8DA2AA271A38772523A76736A7A31B9D3037AD21CEBB11A472B8792EB17558B940E70883F264592C689B240BB43D5408BF446432F412F4B9A5F6865CC252A43CF40A320391555591D67561FDD05353AB6B019B3A08A73353D51B6113AB2FA51D975648EE254AF89A230504A236A4658257740BDCBBE1708AB022C3C588A410DB3B9C308A06275BDF5B4859D3A2617A295E1A22F90198BAD0166F4A943417C5B831736CB2C8580ABFDE5714B586ABEEC0A175A08BC710C7A2895DE93AC438061BF7765D0D21CD418167CAF89D1EFC3448BCBB96D69B3E010C82D15CAB6CACC6799D3639669A5B21A633C865F8593B5B7BC800262BB837A924A6C5440E4FC73B41B23092C3912F4C6BEBB4C7B4C62908B03775666C22220DF9C88823E344C7308332345C8B795D34E8C051F21F5A21C214B69841358709B1C305B32CC2C3806AE9CCD3819FFF4507FE520FBFC27199BC23BE6B9B2D2AC1717579AC769279E2A7AAC68A371A47BA3A7DBE016F14E1A727333663C4A5CD1A0F8836CF7B5C49AC51485CA60345C990E06888720003731322C5B8CD5E6907FDA1157F468FD3FC20FA8175EEC95C291A262BA8C5BE990872418930852339D88A19B37FEFA3CFE82175C224407CA414BAEB37923B4D2D83134AE154E490A9B45A0563B06C953C3301450A2176A07C614A74E3478E48509F9A60AE945A8EBC7815121D90A3B0E07091A096CF02C57B25BCA58126AD0C629CE166A7EDB4B33221A0D3F72B85D562EC698B7D0A913D73806F1C5C87B38EC003CB303A3DC51B4B35356A67826D6EDAA8FEB93B98493B2D1C11B676A6AD9506A1AAAE13A824C7C08D1C6C2C4DBA9642C76EA7F6C8264B64A23CCCA9A74635FCBF03E00F1B5722B214376790793B2C4F0A13B5C40760B4218E1D2594DCB30A70D9C1782A5DD30576FA4144BFC8416EDA8118FC6472F56A979586F33BB070FB0F1B0B10BC4897EBE01BCA3893D4E16ADB25093A7417D0708C83A26322E22E6330091E30152BF823597C04CCF4CFC7331578F43A2726CCB428289A90C863259DD180C5FF142BEF41C7717094BE07856DA2B140FA67710967356AA47DFBC8D255B4722AB86D439B7E0A6090251D2D4C1ED5F20BBE6807BF65A90B7CB2EC0102AF02809DC9AC7D0A3ABC69C18365BCFF59185F33996887746185906C0191AED4407E139446459BE29C6822717644353D24AB6339156A9C424909F0A9025BB74720779BE43F16D81C8CC666E99710D8C68BB5CC4E12F314E925A551F09CC59003A1F88103C254BB978D75F394D3540E31E771CDA36E39EC54A62B5832664D821A72F1E6AFBBA27F84295B2694C498498E812BC8E9378FE541CEC5891B25062901CB7212E3CDC46179EC5BCEC10BC0B9311DE05074290687FD6A5392671654284CD9C8CC3EBA80EB3B662EB53EB75116704A1FEB5C2D056338532868DDF24EB8992AB8565D9E490CADF14804360DAA90718EAB616BAB0765D33987B47EFB6599C5563235E61E4BE670E97955AB292D9732CB8930948AC82DF230AC72297A23679D6B94C17F1359483254FEDC2F05819F0D069A443B78E3FC6C3EF4714B05A3FCA81CBBA60242A7060CD885D8F39981BB18092B23DAA59FD9578388688A09BBA079BC809A54843A60385E2310BBCBCC0213CE3DFAAB33B47F9D6305BC95C6107813C585C4B657BF30542833B14949F573C0612AD524BAAE69590C1277B86C286571BF66B3CFF46A3858C09906A794DF4A06E9D4B0A2E43F10F72A6C6C47E5646E2C799B71C33ED2F01EEB45938EB7A4E2E2908C53558A540D350369FA189C616943F7981D7618CF02A5B0A2BCC422E857D1A47871253D08293C1C179BCDC0437069107418205FDB9856623B8CA6B694C96C084B17F13BB6DF12B2CFBBC2B0E0C34B00D0FCD0AECFB27924F6984E747BE2A09D83A8664590A8077331491A4F7D720843F23E652C6FA840308DB4020337AAD37967034A9FB523B67CA70330F02D9EA20C1E84CB8E5757C9E1896B60581441ED618AA5B26DA56C0A5A73C4DCFD755E610B4FC81FF84E21D2E574DFD8CD0AE893AA7E125B44B924F45223EC09F2AD1141EA93A68050DBF699E3246884181F8E1DD44E0C7629093330221FD67D9B7D6E1510B2DBAD8762F7"; + + SecureRandom random = new SecureRandom(); + MLKEMKeyPairGenerator keyGen = new MLKEMKeyPairGenerator(); + + keyGen.init(new MLKEMKeyGenerationParameters(random, MLKEMParameters.ml_kem_1024)); + + AsymmetricCipherKeyPair keyPair = keyGen.internalGenerateKeyPair(d, z); + assertTrue(Arrays.areEqual(Hex.decode(expectedPubKey), ((MLKEMPublicKeyParameters)keyPair.getPublic()).getEncoded())); + + assertTrue(Arrays.areEqual(Hex.decode(expectedPrivKey), ((MLKEMPrivateKeyParameters)keyPair.getPrivate()).getEncoded())); + + MLKEMGenerator kemGen = new MLKEMGenerator(random); + + byte[] message = Hex.decode("59C5154C04AE43AAFF32700F081700389D54BEC4C37C088B1C53F66212B12C72"); + + SecretWithEncapsulation secretEncap = kemGen.internalGenerateEncapsulated(keyPair.getPublic(), message); + + String expectedSharedSecret = "5CF38F578AC4AE95FBFED574B3D8EBF7CB1DC9074F22277360E36D775347C058"; + + assertTrue(Arrays.areEqual(Hex.decode(expectedSharedSecret), secretEncap.getSecret())); + + String expectedCipherText = "8B9FE419250C5FB0463C8181FCF7CEC777136B738E015EBA31067AA4A8C378BBAC0121B88214F1AEB866E4F33C277099E09B4BF7E21CDDA30B5B32C18B0E9660C30601D85DAEC07AAF4B343EC5516FA501DD63088B999FB9A414C6CA593806C08CD4C775139BF0F0BF3676D773EDD56E616A13830D5F5FE35E515DBC84E43AAD0167D57E60A9DE30886ACD3F7F2006CAC26A7A07B4DADBEDFBED7F305764386AAD726D5B2BF14A376BAD8B4896688491733FB34E6EDEA10BFD5E448541CB6E69E3D87DF190AFA7FF62577775BAACEA444A6128A20200251D8FA759DC60FDA6A9730CFFE4997FE7EBCDD1644AE2D55290A4074CDD2CE53C18D22BC33671E68727A9B5A2FEAFB114A8045D96A56981E200A09661375987625ACC233EDE817AF1DEEAA21C7C4377423E73C5AF9BFF58A49DE6DAFD07A3E3BABD891F62BBA41D1856B8BC502CC86EE115A3598431E2B54AB0C5EACC3CE6A03090925C1FD5A251B00576763A963994A7A23EE12EBFC1B994F93C6144178F0BEF88245CE77CD32EF651826A6090AF561A5864DEC2A51D846F1F48F88B4B55F58C2373E0F67BDC95DC23A43E8546232A7B234E49F5226A3A63BDBCED7240FC81C2DB68AAEB2671A2FD231997BF8839C63A7F41F15E7242821D42E80BBC0F43FA9E353DE8B25ED8FFC242EB512C6A5260919AAE89A11176532BCCC762A520A37AEC4E7209AA81CEE0DD4ADD932C47EB8100BE98AA1DEEA9EA698115ADCED950A6C536D19AEB325CEA8C5245C0A2281533FB90809DC2BE90567EBE6AE229FE09B44DA2182585EA694D8A9AB33EBC24B44E09BD510F34B4140E1FB41162F9415F2D9106A0CEA00A26ED0920021F4E5BCFB3DABF5850DAB22B2E889D9611FBE06D0C899708EB5E5FAD2FBBE0D5C0BDE080F8E760EDFA037D55DA77F0F39591BF5B050C905FA538B7228E238A290DF340778DCBD6BE40A3B1DD455FB27ADBE176AEF6CC295BEA570BDC221BA14002E3B113B0EF237452FBC9F1AEC42E0D2B33F19832DB0A6171CAEB0B30EEAD3A54B704B761C7D4AFEA8F6AFC15156666A081C43AEB2E04FEECEF8AABA4049BD78B120B9ABA86A60342A0CF806411C473C26C4BE1540E3312388BCBC8523BA73F40EA28D5564274F3661D7ACAA0F1E8D0F28DCF6B501329963E6857FDB2AAE873A7D9D6C14821F6C0B6AA50AC449075CD6F2A256C5A05959DAB5A5912CC8E8F8B9F59941BFCCE6A28CBA74A20382B1FD3382D056547D5BC5EF4AAE62F96F038C595A4F901D6AE790F8978292AD1CC3A1E800B71A5BBE84533646655E3752FBD6B02B97B204E75D28A34C2F990FB8E8CD31CE6E683FA7E67DA03367E8D47DC626F060FBA2D0425004CAC2A61D982D2E3D85008624B45DB022CF51BA265B5E974712A9372EECAC0EA272B2FC56EBED0D32105521BA2C4A8FE0C678CE4E45902C7BA9D510BD47B2B5F931DD732F27DE9B42FD4AA39EAC765283A9965EE97C0D88E23EFA6F718242C67770B87BF8832858C1D13FC520870BD34F2B9C6FBFD1A528B744F814C93F4F4E87108316FE2AB06E02292DEA7FCF6FEFB17BF5AA7376A4A9BDB7C49BF709EB1E05D60EF14CD85A75239B97BCA9A6A3CC1B28F28979D612431BAAC1ACEE5EF62776B4D51B7EB0F63DF507760097223CA903E16E02DEB7FCABFBEC26DAEDC0ED4CC55726BDC31D1775112EF3C35D1DF928C6EB7830D8CA6570CB5CE348E3F26DDE864F20E5BE7B99E264EBC0E9D8DE9C6E4B7FE3CFBE673833CF7E8B3081529062CB6815C7C0766822B3B31E56BA1FC73FE3DED4B5D435BFCE2F2997C1D4B9CE293220DD461103BE084BF12076372668A69836769C1F6D8C32E2C7BC2E7D66714C814793A2970C90DD94DF14C89C60DD35B52A14778E137E750CE83AC3AAB667FCBDCBA38B7FA6D1C6BF7B99D957078176D9779A09F84B75FBC2A11769EF65532B09ACA4C9A3766B4A1FC717F94648FB8B8D9363E54F1C4201C075C18B1EAE098B83598089585ED9DC06B96E2D1C96DC738086EBBC26C3193B64139E1FC1DFB22A17893506EF7B35792B4EB00196693686EB5DEB3CEB436DD16D2D92A0FD31F468AF8662040F5257BFA0F14991C0D560999EEF775178D14955ADF091DD797AC1FDCEC7776055271C0F130562D0B0A6749B159DD0DB9AC69271AC719B83B683CE8B32342AC4AB257B0F8083C8CC86338AFA4D386C9848F413ED0"; + + assertTrue(Arrays.areEqual(Hex.decode(expectedCipherText), secretEncap.getEncapsulation())); + + MLKEMExtractor kemExtract = new MLKEMExtractor((MLKEMPrivateKeyParameters)keyPair.getPrivate()); + + byte[] decryptedSharedSecret = kemExtract.extractSecret(secretEncap.getEncapsulation()); + + assertTrue(Arrays.areEqual(Hex.decode(expectedSharedSecret), decryptedSharedSecret)); + } + + public void testRNG() + { + String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; + byte[] seed = Hex.decode(temp); + NISTSecureRandom r = new NISTSecureRandom(seed, null); + byte[] testBytes = new byte[48]; + r.nextBytes(testBytes); + + String randBytesString = "7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E47"; + byte[] randBytes = Hex.decode(randBytesString); + + assertTrue(Arrays.areEqual(randBytes, testBytes)); + } + + public void testParameters() + throws Exception + { + assertEquals(256, MLKEMParameters.ml_kem_512.getSessionKeySize()); + assertEquals(256, MLKEMParameters.ml_kem_768.getSessionKeySize()); + assertEquals(256, MLKEMParameters.ml_kem_1024.getSessionKeySize()); + } + + public void testMLKEMRandom() + { + SecureRandom random = new SecureRandom(); + MLKEMKeyPairGenerator keyGen = new MLKEMKeyPairGenerator(); + + keyGen.init(new MLKEMKeyGenerationParameters(random, MLKEMParameters.ml_kem_1024)); + + for (int i = 0; i != 1000; i++) + { + AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); + + MLKEMGenerator kemGen = new MLKEMGenerator(random); + + SecretWithEncapsulation secretEncap = kemGen.generateEncapsulated(keyPair.getPublic()); + + MLKEMExtractor kemExtract = new MLKEMExtractor((MLKEMPrivateKeyParameters)keyPair.getPrivate()); + + byte[] decryptedSharedSecret = kemExtract.extractSecret(secretEncap.getEncapsulation()); + + assertTrue(Arrays.areEqual(secretEncap.getSecret(), decryptedSharedSecret)); + } + } +} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/MayoTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/MayoTest.java new file mode 100644 index 0000000000..e275ecf2de --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/MayoTest.java @@ -0,0 +1,94 @@ +package org.bouncycastle.pqc.crypto.test; + +import java.security.SecureRandom; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.pqc.crypto.MessageSigner; +import org.bouncycastle.pqc.crypto.mayo.MayoKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoSigner; + +public class MayoTest + extends TestCase +{ + public static void main(String[] args) + throws Exception + { + MayoTest test = new MayoTest(); + test.testTestVectors(); + //test.testKeyGen(); + } + + private static final MayoParameters[] PARAMETER_SETS = new MayoParameters[] + { + MayoParameters.mayo1, + MayoParameters.mayo2, + MayoParameters.mayo3, + MayoParameters.mayo5 + }; + + private static final String[] files = new String[]{ + "PQCsignKAT_24_MAYO_1.rsp", + "PQCsignKAT_24_MAYO_2.rsp", + "PQCsignKAT_32_MAYO_3.rsp", + "PQCsignKAT_40_MAYO_5.rsp", + }; + + + public void testTestVectors() + throws Exception + { + long start = System.currentTimeMillis(); + TestUtils.testTestVector(false, true, false, "pqc/crypto/mayo", files, new TestUtils.KeyGenerationOperation() + { + @Override + public SecureRandom getSecureRandom(byte[] seed) + { + return new NISTSecureRandom(seed, null); + } + + @Override + public AsymmetricCipherKeyPairGenerator getAsymmetricCipherKeyPairGenerator(int fileIndex, SecureRandom random) + { + MayoParameters parameters = PARAMETER_SETS[fileIndex]; + + MayoKeyPairGenerator kpGen = new MayoKeyPairGenerator(); + kpGen.init(new MayoKeyGenerationParameters(random, parameters)); + return kpGen; + } + + @Override + public byte[] getPublicKeyEncoded(AsymmetricKeyParameter pubParams) + { + return ((MayoPublicKeyParameters)pubParams).getEncoded(); + } + + @Override + public byte[] getPrivateKeyEncoded(CipherParameters privParams) + { + return ((MayoPrivateKeyParameters)privParams).getEncoded(); + } + + @Override + public Signer getSigner() + { + return null; + } + + @Override + public MessageSigner getMessageSigner() + { + return new MayoSigner(); + } + }); + long end = System.currentTimeMillis(); + System.out.println("time cost: " + (end - start) +"\n"); + } +} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUKAT.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUKAT.java index e6888c3951..f400db2f59 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUKAT.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUKAT.java @@ -31,13 +31,12 @@ public class NTRUKAT */ public byte[] ss; - private static final TestSampler sampler = new TestSampler(); - public static List getKAT(InputStream src) { List kats = new ArrayList(); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); try { for (String line = bin.readLine(); line != null; line = bin.readLine()) diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRULPRimeTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRULPRimeTest.java index 774c6e59f1..13e2d4afd3 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRULPRimeTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRULPRimeTest.java @@ -37,8 +37,6 @@ public void testKEM() NTRULPRimeParameters.ntrulpr1277 }; - TestSampler sampler = new TestSampler(); - for (int i = 0; i != paramList.length; i++) { NTRULPRimeParameters paramSpec = paramList[i]; @@ -47,6 +45,7 @@ public void testKEM() BufferedReader resourceReader = new BufferedReader(new InputStreamReader(resource)); String line; + TestSampler sampler = new TestSampler(); while ((line = resourceReader.readLine()) != null) { if (! line.startsWith("count")) diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUTest.java index 7624329cca..e7c5957976 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/NTRUTest.java @@ -31,7 +31,6 @@ public class NTRUTest extends TestCase { - private final String KAT_ROOT = "/org/bouncycastle/pqc/crypto/test/ntru/"; private final NTRUParameters[] params = { NTRUParameters.ntruhps2048509, NTRUParameters.ntruhps2048677, @@ -59,6 +58,16 @@ public class NTRUTest "PQCkemKAT_2983.rsp" }; + public void testParameters() + { + assertEquals(256, NTRUParameters.ntruhps2048509.getSessionKeySize()); + assertEquals(256, NTRUParameters.ntruhps2048677.getSessionKeySize()); + assertEquals(256, NTRUParameters.ntruhps4096821 .getSessionKeySize()); + assertEquals(256, NTRUParameters.ntruhps40961229.getSessionKeySize()); + assertEquals(256, NTRUParameters.ntruhrss701.getSessionKeySize()); + assertEquals(256, NTRUParameters.ntruhrss1373.getSessionKeySize()); + } + public void testPrivInfoGeneration() throws IOException { diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/PicnicVectorTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/PicnicVectorTest.java index 5d048aff09..765e592c0e 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/PicnicVectorTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/PicnicVectorTest.java @@ -90,17 +90,16 @@ public void testVectors() }; } - TestSampler sampler = new TestSampler(); - for (int fileIndex = 0; fileIndex != files.length; fileIndex++) { String name = files[fileIndex]; - // System.out.println("testing: " + name); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/picnic", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/RainbowTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/RainbowTest.java deleted file mode 100644 index e3c6458c8f..0000000000 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/RainbowTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.bouncycastle.pqc.crypto.test; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.pqc.crypto.MessageSigner; -import org.bouncycastle.pqc.crypto.rainbow.RainbowKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowKeyPairGenerator; -import org.bouncycastle.pqc.crypto.rainbow.RainbowParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowSigner; -import org.bouncycastle.util.BigIntegers; -import org.bouncycastle.util.test.SimpleTest; - -public class RainbowTest - extends SimpleTest -{ - private RainbowParameters params; - - public RainbowTest(RainbowParameters params) - { - this.params = params; - } - - public String getName() - { - return params.getName(); - } - - public void performTest() - { - byte[] seed = new byte[64]; - SecureRandom sr = new SecureRandom(); - sr.nextBytes(seed); - NISTSecureRandom random = new NISTSecureRandom(seed, null); - - RainbowKeyPairGenerator rainbowKeyGen = new RainbowKeyPairGenerator(); - RainbowKeyGenerationParameters genParam = new RainbowKeyGenerationParameters(random, params); - - rainbowKeyGen.init(genParam); - - AsymmetricCipherKeyPair pair = rainbowKeyGen.generateKeyPair(); - - ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), random); - - MessageSigner rainbowSigner = new RainbowSigner(); - - rainbowSigner.init(true, param); - - byte[] message = BigIntegers.asUnsignedByteArray(new BigInteger("968236873715988614170569073515315707566766479517")); - - byte[] sig = rainbowSigner.generateSignature(message); - - rainbowSigner.init(false, pair.getPublic()); - - if (!rainbowSigner.verifySignature(message, sig)) - { - fail("verification fails"); - } - } - - public static void main(String[] args) - { - runTest(new RainbowTest(RainbowParameters.rainbowIIIclassic)); - runTest(new RainbowTest(RainbowParameters.rainbowIIIcircumzenithal)); - runTest(new RainbowTest(RainbowParameters.rainbowIIIcompressed)); - runTest(new RainbowTest(RainbowParameters.rainbowVclassic)); - runTest(new RainbowTest(RainbowParameters.rainbowVcircumzenithal)); - runTest(new RainbowTest(RainbowParameters.rainbowVcompressed)); - } -} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/RainbowVectorTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/RainbowVectorTest.java deleted file mode 100644 index 8de315b7a1..0000000000 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/RainbowVectorTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.bouncycastle.pqc.crypto.test; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; - -import junit.framework.TestCase; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.pqc.crypto.MessageSigner; -import org.bouncycastle.pqc.crypto.rainbow.RainbowKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowKeyPairGenerator; -import org.bouncycastle.pqc.crypto.rainbow.RainbowParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowSigner; -import org.bouncycastle.test.TestResourceFinder; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.encoders.Hex; - -public class RainbowVectorTest - extends TestCase -{ - public void testVectors() - throws Exception - { - String[] files = new String[]{ - "rainbowIIIclassic.rsp", - "rainbowIIIcircumzenithal.rsp", - "rainbowIIIcompressed.rsp", - "rainbowVclassic.rsp", - "rainbowVcircumzenithal.rsp", - "rainbowVcompressed.rsp" - }; - RainbowParameters[] params = new RainbowParameters[]{ - RainbowParameters.rainbowIIIclassic, - RainbowParameters.rainbowIIIcircumzenithal, - RainbowParameters.rainbowIIIcompressed, - RainbowParameters.rainbowVclassic, - RainbowParameters.rainbowVcircumzenithal, - RainbowParameters.rainbowVcompressed - }; - - TestSampler sampler = new TestSampler(); - - for (int fileIndex = 0; fileIndex != files.length; fileIndex++) - { - String name = files[fileIndex]; - // System.out.println("testing: " + name); - InputStream src = TestResourceFinder.findTestResource("pqc/crypto/rainbow", name); - BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - - String line = null; - HashMap buf = new HashMap(); - while ((line = bin.readLine()) != null) - { - line = line.trim(); - - if (line.startsWith("#")) - { - continue; - } - if (line.length() == 0) - { - if (buf.size() > 0) - { - String count = (String)buf.get("count"); - if (sampler.skipTest(count)) - { - continue; - } - - // System.out.println("test case: " + count); - byte[] seed = Hex.decode((String)buf.get("seed")); // seed for Rainbow secure random - int mlen = Integer.parseInt((String)buf.get("mlen")); // message length - byte[] msg = Hex.decode((String)buf.get("msg")); // message - byte[] pk = Hex.decode((String)buf.get("pk")); // public key - byte[] sk = Hex.decode((String)buf.get("sk")); // private key - int smlen = Integer.parseInt((String)buf.get("smlen")); // signature length - byte[] sigExpected = Hex.decode((String)buf.get("sm")); // signature - - NISTSecureRandom random = new NISTSecureRandom(seed, null); - - RainbowParameters parameters = params[fileIndex]; - - RainbowKeyPairGenerator kpGen = new RainbowKeyPairGenerator(); - RainbowKeyGenerationParameters genParams = new RainbowKeyGenerationParameters(random, parameters); - // - // Generate keys and test. - // - kpGen.init(genParams); - AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); - - RainbowPublicKeyParameters pubParams = (RainbowPublicKeyParameters)kp.getPublic(); - RainbowPrivateKeyParameters privParams = (RainbowPrivateKeyParameters)kp.getPrivate(); - assertTrue(name + " " + count + ": public key", Arrays.areEqual(pk, pubParams.getEncoded())); - assertTrue(name + " " + count + ": secret key", Arrays.areEqual(sk, privParams.getPrivateKey())); - - // - // Signature test - // - ParametersWithRandom param = new ParametersWithRandom(kp.getPrivate(), random); - MessageSigner signer = new RainbowSigner(); - - signer.init(true, param); - - byte[] sigGenerated = signer.generateSignature(msg); - byte[] attachedSig = Arrays.concatenate(msg, sigGenerated); - - //// System.out.println("expected:\t" + Hex.toHexString(sigExpected).toUpperCase().substring(msg.length*2, sigExpected.length*2)); - //// System.out.println("generated:\t" + Hex.toHexString(sigGenerated).toUpperCase()); - //// System.out.println("attached:\t" + Hex.toHexString(attachedSig).toUpperCase()); - - signer.init(false, kp.getPublic()); - - assertTrue(name + " " + count + ": signature verify", signer.verifySignature(msg, sigGenerated)); - assertTrue(name + " " + count + ": signature gen match", Arrays.areEqual(sigExpected, attachedSig)); - } - buf.clear(); - - continue; - } - - int a = line.indexOf("="); - if (a > -1) - { - buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); - } - } - // System.out.println("testing successful!"); - } - } - -} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SABERVectorTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SABERVectorTest.java index ce5f0d1ea7..d63527e933 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SABERVectorTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SABERVectorTest.java @@ -79,17 +79,16 @@ public void testVectors() "ufiresaber-90s.rsp", }; - TestSampler sampler = new TestSampler(); - for (int fileIndex = 0; fileIndex != files.length; fileIndex++) { String name = files[fileIndex]; - // System.out.println("testing: " + name); + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/saber", name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SLHDSATest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SLHDSATest.java new file mode 100644 index 0000000000..99ba397db4 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SLHDSATest.java @@ -0,0 +1,755 @@ +package org.bouncycastle.pqc.crypto.test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAKeyPairGenerator; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSASigner; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; + +public class SLHDSATest + extends TestCase +{ + private static final Map parametersMap = new HashMap() + { + { + put("SLH-DSA-SHA2-128s", SLHDSAParameters.sha2_128s); + put("SLH-DSA-SHA2-128f", SLHDSAParameters.sha2_128f); + put("SLH-DSA-SHA2-192s", SLHDSAParameters.sha2_192s); + put("SLH-DSA-SHA2-192f", SLHDSAParameters.sha2_192f); + put("SLH-DSA-SHA2-256s", SLHDSAParameters.sha2_256s); + put("SLH-DSA-SHA2-256f", SLHDSAParameters.sha2_256f); + + put("SLH-DSA-SHAKE-128s", SLHDSAParameters.shake_128s); + put("SLH-DSA-SHAKE-128f", SLHDSAParameters.shake_128f); + put("SLH-DSA-SHAKE-192s", SLHDSAParameters.shake_192s); + put("SLH-DSA-SHAKE-192f", SLHDSAParameters.shake_192f); + put("SLH-DSA-SHAKE-256s", SLHDSAParameters.shake_256s); + put("SLH-DSA-SHAKE-256f", SLHDSAParameters.shake_256f); + } + }; + + SLHDSAParameters[] PARAMETER_SETS = new SLHDSAParameters[] + { + SLHDSAParameters.sha2_128f, + SLHDSAParameters.sha2_128s, + SLHDSAParameters.sha2_192f, + SLHDSAParameters.sha2_192s, + SLHDSAParameters.sha2_256f, + SLHDSAParameters.sha2_256s, + SLHDSAParameters.shake_128f, + SLHDSAParameters.shake_128s, + SLHDSAParameters.shake_192f, + SLHDSAParameters.shake_192s, + SLHDSAParameters.shake_256f, + SLHDSAParameters.shake_256s, + }; + + public void testConsistency() + { + SecureRandom random = new SecureRandom(); + + SLHDSAKeyPairGenerator kpg = new SLHDSAKeyPairGenerator(); + + for (int idx = 0; idx != PARAMETER_SETS.length; idx++) + { + SLHDSAParameters parameters = PARAMETER_SETS[idx]; + kpg.init(new SLHDSAKeyGenerationParameters(random, parameters)); + + { + AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); + + SLHDSASigner signer = new SLHDSASigner(); + + { + int msgLen = random.nextInt(257); + byte[] msg = new byte[msgLen]; + random.nextBytes(msg); + + // sign + signer.init(true, new ParametersWithRandom(kp.getPrivate(), random)); + byte[] signature = signer.generateSignature(msg); + + // verify + signer.init(false, kp.getPublic()); + boolean shouldVerify = signer.verifySignature(msg, signature); + + assertTrue(shouldVerify); + } + } + } + } + + public void testKeyGenSingleFile() throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa/", "SLH-DSA-keyGen.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] skSeed = Hex.decode((String)buf.get("skSeed")); + byte[] skPrf = Hex.decode((String)buf.get("skPrf")); + byte[] pkSeed = Hex.decode((String)buf.get("pkSeed")); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); + + SLHDSAParameters parameters = (SLHDSAParameters)parametersMap.get((String)buf.get("parameterSet")); + + SLHDSAKeyPairGenerator kpGen = new SLHDSAKeyPairGenerator(); + SLHDSAKeyGenerationParameters genParam = new SLHDSAKeyGenerationParameters(new SecureRandom(), parameters); + + // + // Generate keys and test. + // + kpGen.init(genParam); + AsymmetricCipherKeyPair kp = kpGen.internalGenerateKeyPair(skSeed, skPrf, pkSeed); + + SLHDSAPublicKeyParameters pubParams = (SLHDSAPublicKeyParameters) PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((SLHDSAPublicKeyParameters) kp.getPublic())); + SLHDSAPrivateKeyParameters privParams = (SLHDSAPrivateKeyParameters) PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((SLHDSAPrivateKeyParameters) kp.getPrivate())); + + assertTrue("public key", Arrays.areEqual(pk, pubParams.getEncoded())); + assertTrue("secret key", Arrays.areEqual(sk, privParams.getEncoded())); + + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testSigGenSingleFile() throws IOException + { + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa", "SLH-DSA-sigGen.txt"); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean deterministic = !buf.containsKey("additionalRandomness"); + byte[] sk = Hex.decode((String)buf.get("sk")); +// int messageLength = Integer.parseInt((String)buf.get("messageLength")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + byte[] rnd = null; + + SLHDSAParameters parameters = (SLHDSAParameters)parametersMap.get((String)buf.get("parameterSet")); + + SLHDSAPrivateKeyParameters privParams = new SLHDSAPrivateKeyParameters(parameters, sk); + + if (!deterministic) + { + rnd = Hex.decode((String)buf.get("additionalRandomness")); + } + else + { + rnd = privParams.getPublicSeed(); + } + + // sign + InternalSLHDSASigner signer = new InternalSLHDSASigner(); + + signer.init(true, privParams); + byte[] sigGenerated = signer.internalGenerateSignature(message, rnd); + assertTrue(Arrays.areEqual(sigGenerated, signature)); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testSigVerSingleFile() throws IOException + { + String name ="SLH-DSA-sigVer.txt"; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean testPassed = TestUtils.parseBoolean((String)buf.get("testPassed")); +// boolean deterministic = !buf.containsKey("additionalRandomness"); + String reason = (String)buf.get("reason"); + + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + +// byte[] rnd = null; +// if (!deterministic) +// { +// rnd = Hex.decode((String)buf.get("additionalRandomness")); +// } + + SLHDSAParameters parameters = (SLHDSAParameters)parametersMap.get((String)buf.get("parameterSet")); + + SLHDSAPublicKeyParameters pubParams = new SLHDSAPublicKeyParameters(parameters, pk); + + InternalSLHDSASigner verifier = new InternalSLHDSASigner(); + verifier.init(false, pubParams); + boolean ver = verifier.internalVerifySignature(message, signature); + assertEquals("expected " + testPassed + " " + reason, ver, testPassed); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + + public void testKeyGen() throws IOException + { + String[] files = new String[]{ + "keyGen_SLH-DSA-SHA2-128s.txt", + "keyGen_SLH-DSA-SHA2-192f.txt", + "keyGen_SLH-DSA-SHAKE-192s.txt", + "keyGen_SLH-DSA-SHAKE-256f.txt", + }; + + SLHDSAParameters[] params = new SLHDSAParameters[]{ + SLHDSAParameters.sha2_128s, + SLHDSAParameters.sha2_192f, + SLHDSAParameters.shake_192s, + SLHDSAParameters.shake_256f, + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + byte[] skSeed = Hex.decode((String)buf.get("skSeed")); + byte[] skPrf = Hex.decode((String)buf.get("skPrf")); + byte[] pkSeed = Hex.decode((String)buf.get("pkSeed")); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); + + SLHDSAParameters parameters = params[fileIndex]; + + SLHDSAKeyPairGenerator kpGen = new SLHDSAKeyPairGenerator(); + SLHDSAKeyGenerationParameters genParam = new SLHDSAKeyGenerationParameters(new SecureRandom(), parameters); + // + // Generate keys and test. + // + kpGen.init(genParam); + AsymmetricCipherKeyPair kp = kpGen.internalGenerateKeyPair(skSeed, skPrf, pkSeed); + + SLHDSAPublicKeyParameters pubParams = (SLHDSAPublicKeyParameters) PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo((SLHDSAPublicKeyParameters) kp.getPublic())); + SLHDSAPrivateKeyParameters privParams = (SLHDSAPrivateKeyParameters) PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo((SLHDSAPrivateKeyParameters) kp.getPrivate())); + + assertTrue(name + ": public key", Arrays.areEqual(pk, pubParams.getEncoded())); + assertTrue(name + ": secret key", Arrays.areEqual(sk, privParams.getEncoded())); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testSigGen() throws IOException + { + String[] files = new String[]{ + "sigGen_SLH-DSA-SHA2-192s.txt", + "sigGen_SLH-DSA-SHA2-256f.txt", + "sigGen_SLH-DSA-SHAKE-128f.txt", + "sigGen_SLH-DSA-SHAKE-192s.txt", + "sigGen_SLH-DSA-SHAKE-256f.txt", + }; + + SLHDSAParameters[] params = new SLHDSAParameters[]{ + SLHDSAParameters.sha2_192s, + SLHDSAParameters.sha2_256f, + SLHDSAParameters.shake_128f, + SLHDSAParameters.shake_192s, + SLHDSAParameters.shake_256f, + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean deterministic = !buf.containsKey("additionalRandomness"); + byte[] sk = Hex.decode((String)buf.get("sk")); +// int messageLength = Integer.parseInt((String)buf.get("messageLength")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + byte[] rnd = null; + + SLHDSAParameters parameters = params[fileIndex]; + + SLHDSAPrivateKeyParameters privParams = new SLHDSAPrivateKeyParameters(parameters, sk); + + if (!deterministic) + { + rnd = Hex.decode((String)buf.get("additionalRandomness")); + } + else + { + rnd = privParams.getPublicSeed(); + } + + // sign + InternalSLHDSASigner signer = new InternalSLHDSASigner(); + + signer.init(true, privParams); + byte[] sigGenerated = signer.internalGenerateSignature(message, rnd); + assertTrue(Arrays.areEqual(sigGenerated, signature)); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + + public void testSigVer() throws IOException + { + String[] files = new String[]{ + "sigVer_SLH-DSA-SHA2-192s.txt", + "sigVer_SLH-DSA-SHA2-256f.txt", + "sigVer_SLH-DSA-SHAKE-128f.txt", + "sigVer_SLH-DSA-SHAKE-192s.txt", + "sigVer_SLH-DSA-SHAKE-256f.txt", + }; + + SLHDSAParameters[] params = new SLHDSAParameters[]{ + SLHDSAParameters.sha2_192s, + SLHDSAParameters.sha2_256f, + SLHDSAParameters.shake_128f, + SLHDSAParameters.shake_192s, + SLHDSAParameters.shake_256f, + }; + + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa/acvp", name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line = null; + HashMap buf = new HashMap(); + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + boolean testPassed = TestUtils.parseBoolean((String)buf.get("testPassed")); +// boolean deterministic = !buf.containsKey("additionalRandomness"); + String reason = (String)buf.get("reason"); + + byte[] pk = Hex.decode((String)buf.get("pk")); +// byte[] sk = Hex.decode((String)buf.get("sk")); + byte[] message = Hex.decode((String)buf.get("message")); + byte[] signature = Hex.decode((String)buf.get("signature")); + +// byte[] rnd = null; +// if (!deterministic) +// { +// rnd = Hex.decode((String)buf.get("additionalRandomness")); +// } + + SLHDSAParameters parameters = params[fileIndex]; + + SLHDSAPublicKeyParameters pubParams = new SLHDSAPublicKeyParameters(parameters, pk); +// SLHDSAPrivateKeyParameters privParams = new SLHDSAPrivateKeyParameters(parameters, sk); + + InternalSLHDSASigner verifier = new InternalSLHDSASigner(); + verifier.init(false, pubParams); + boolean ver = verifier.internalVerifySignature(message, signature); + assertEquals("expected " + testPassed + " " + reason, ver, testPassed); + } + buf.clear(); + + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } + +// public void testVectors() +// throws Exception +// { +// String files = +// " sha2-128f-simple.rsp sha2-192f-simple.rsp sha2-256f-simple.rsp shake-128f-simple.rsp" + +// " shake-192f-simple.rsp shake-256f-simple.rsp " + +// " sha2-128s-simple.rsp sha2-192s-simple.rsp" + +// " sha2-256s-simple.rsp shake-128s-simple.rsp shake-192s-simple.rsp shake-256s-simple.rsp"; +// +// TestSampler sampler = new TestSampler(); +// +// String[] fileList = splitOn(files, ' '); +// for (int i = 0; i != fileList.length; i++) +// { +// String name = fileList[i]; +// InputStream src = TestResourceFinder.findTestResource("pqc/crypto/slhdsa", "subset_" + name); +// BufferedReader bin = new BufferedReader(new InputStreamReader(src)); +// String line = null; +// HashMap buf = new HashMap(); +// while ((line = bin.readLine()) != null) +// { +// line = line.trim(); +// +// if (line.startsWith("#")) +// { +// continue; +// } +// if (line.length() == 0) +// { +// if (buf.size() > 0) +// { +// String count = (String)buf.get("count"); +// byte[] sk = Hex.decode((String)buf.get("sk")); +// byte[] pk = Hex.decode((String)buf.get("pk")); +// byte[] msg = Hex.decode((String)buf.get("msg")); +// byte[] sigExpected = Hex.decode((String)buf.get("sm")); +// byte[] oprR = Hex.decode((String)buf.get("optrand")); +// +// if (sampler.skipTest(count)) +// { +// continue; +// } +// +// SLHDSAKeyPairGenerator kpGen = new SLHDSAKeyPairGenerator(); +// SecureRandom random = new FixedSecureRandom(sk); +// +// SLHDSAParameters parameters; +// +// String[] nameParts = splitOn(name, '-'); +// boolean sha2 = nameParts[0].equals("sha2"); +// boolean shake = nameParts[0].equals("shake"); +// boolean haraka = nameParts[0].equals("haraka"); +// int size = Integer.parseInt(nameParts[1].substring(0, 3)); +// boolean fast = nameParts[1].endsWith("f"); +// boolean slow = nameParts[1].endsWith("s"); +// boolean simple = nameParts[2].equals("simple.rsp"); +// boolean robust = nameParts[2].equals("robust.rsp"); +// if (robust) +// { +// continue; +// } +// if (haraka) +// { +// continue; +// } +// +// StringBuffer b = new StringBuffer(); +// if (sha2) +// { +// b.append("sha2"); +// } +// else if (shake) +// { +// b.append("shake"); +// } +// else +// { +// throw new IllegalArgumentException("unknown digest"); +// } +// +// b.append("_"); +// b.append(size); +// +// if (fast) +// { +// b.append("f"); +// } +// else if (slow) +// { +// b.append("s"); +// } +// else +// { +// throw new IllegalArgumentException("unknown speed"); +// } +// +// if (robust) +// { +// if (b.indexOf("haraka") < 0) +// { +// b.append("_robust"); +// } +// } +// else if (simple) +// { +// if (b.indexOf("haraka") >= 0) +// { +// b.append("_simple"); +// } +// } +// else +// { +// throw new IllegalArgumentException("unknown complexity"); +// } +// +// +// parameters = (SLHDSAParameters)SLHDSAParameters.class.getField(b.toString()).get(null); +// +// // +// // Generate keys and test. +// // +// kpGen.init(new SLHDSAKeyGenerationParameters(random, parameters)); +// AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); +// +// SLHDSAPublicKeyParameters pubParams = (SLHDSAPublicKeyParameters)kp.getPublic(); +// SLHDSAPrivateKeyParameters privParams = (SLHDSAPrivateKeyParameters)kp.getPrivate(); +// +// // FIXME No OIDs for simple variants of SPHINCS+ +// if (name.indexOf("-simple") < 0) +// { +// pubParams = (SLHDSAPublicKeyParameters)PublicKeyFactory.createKey( +// SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubParams)); +// privParams = (SLHDSAPrivateKeyParameters)PrivateKeyFactory.createKey( +// PrivateKeyInfoFactory.createPrivateKeyInfo(privParams)); +// } +// +// assertTrue(name + " " + count + ": public key", Arrays.areEqual(pk, pubParams.getEncoded())); +// assertTrue(name + " " + count + ": secret key", Arrays.areEqual(sk, privParams.getEncoded())); +// +// // +// // Signature test +// // +// +// SLHDSASigner signer = new SLHDSASigner(); +// +// signer.init(true, new ParametersWithRandom(privParams, new FixedSecureRandom(oprR))); +// +// byte[] sigGenerated = signer.generateSignature(msg); +// byte[] attachedSig = Arrays.concatenate(sigGenerated, msg); +// +// +// signer.init(false, pubParams); +// +// assertTrue(name + " " + count + ": signature verify", signer.verifySignature(msg, Arrays.copyOfRange(sigExpected, 0, sigGenerated.length))); +// +// assertTrue(name + " " + count + ": signature gen match", Arrays.areEqual(sigExpected, attachedSig)); +// +// } +// buf.clear(); +// +// continue; +// } +// +// int a = line.indexOf("="); +// if (a > -1) +// { +// buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); +// } +// } +// src.close(); +// } +// } + + public void testBasicKeyGenerationSha2128sSimple() + { + byte[] skSeed = Hex.decode("2F896D61D9CD9038CA303394FADAA22A"); + byte[] skPrf = Hex.decode("24AC5EC1D86A989CA2196C3C8632419C"); + byte[] pkSeed = Hex.decode("1A05A42FE300E87B16AEE116CB2E2363"); + byte[] pk = Hex.decode("1A05A42FE300E87B16AEE116CB2E236358E2C3E62632C9DE03D08A535A0EB7E7"); + byte[] sk = Hex.decode("2F896D61D9CD9038CA303394FADAA22A24AC5EC1D86A989CA2196C3C8632419C1A05A42FE300E87B16AEE116CB2E236358E2C3E62632C9DE03D08A535A0EB7E7"); + + SLHDSAParameters parameters = SLHDSAParameters.sha2_128s; + + SLHDSAKeyPairGenerator kpGen = new SLHDSAKeyPairGenerator(); + SLHDSAKeyGenerationParameters genParam = new SLHDSAKeyGenerationParameters(new SecureRandom(), parameters); + // + // Generate keys and test. + // + kpGen.init(genParam); + AsymmetricCipherKeyPair kp = kpGen.internalGenerateKeyPair(skSeed, skPrf, pkSeed); + + SLHDSAPublicKeyParameters pubParams = (SLHDSAPublicKeyParameters) kp.getPublic(); + SLHDSAPrivateKeyParameters privParams = (SLHDSAPrivateKeyParameters) kp.getPrivate(); + + assertTrue("public key", Arrays.areEqual(pk, pubParams.getEncoded())); + assertTrue("secret key", Arrays.areEqual(sk, privParams.getEncoded())); + } + + public void testBasicKeyGenerationShake256128fSimpleSign() + { + byte[] sk = Hex.decode("DADB023900B157BAEDFF38B4BDE4B308C83A26A11170274E7E35CD3935AEAF07119231DA3849A12477373395D264043DA6CECC80D20A2E15A3622ABFFC221FC8"); + byte[] message = Hex.decode("3048BDE7F28C0414CC318C90048F23AFECF079866C34858521192E1684F37F0BC5D2C8585E9BF753626F6E853779D41C15BDA83DEF79DBF8A11B82EAE066833AB6C409D8AC386C942D69FF482D26A1A4030F7C082E36CFCEAA7491CB2F25BD61B79BACD91DD72C91C5D673BE48866D33E6B20F9DC83BD5639D27B0D8CA326AA1"); + byte[] signature = Hex.decode("EA52B3F889F36866D485BE712C5A7EE6FB696EFA6F5BBCB9E4FF1820FE0C580BE5786FE8A773E1AFCD353B106EECD84D65C3BF4259089B54DCC0557911FDCA8323AF0839686975D2D6AD148572D173E8D8EE8DE5E8A709D11B29E84C8ADD4E373985310F4C09F346086765B90888B94704014171AE30F65CCEE69DBC2603C0FF3D662DD0E18E0B0C69A457C5B46B3062B1A5F690EA5AA84D33C92C571D5C4156C2A96F07E66816F8453697381C93571BF7072F697152F191482CD1C73C41F2C190B59C06EFF4F4E806E832FE18F3D298F8CFBFC5E7529D3E35187289DAC000EAC6C563E456A6CFF491D90778E577476B34ECEB3193BDCEAF720E368E4D56A88634AD6FA3FA25CC09194D53AA00F9044B087727F99B4FFE61C6171CBCB424AF6DF373C58F73FF229D8DC557CBED5C6E8EF908A9DC07D2D62FFBF791B689D5356ECF67F3658A8EF845A4E8F6275B7FE44555742C2BAD4ED740D10186DE0E6CE9FC75144599F070C8F8704ECB99CA9DA9ECAC449E0170A8FD1B48DA791DE2D376CCD3C13B99FDBDE0495AAD3B4D3D6F955D51917A649262810E80467D177B29CA85FC96B93CEBC78A4E318DAA1EF00CE6D5B73BF41196CC7AA8B4D247CD1B0CA2C494DCC8591EFBFD18F5FACFC765CDA4EF6990AA7FD26696A440F992774DD952E144D3E349CDA3312E2D4A60AAE010743023AFFB20C0CAF9F4DF9697D20341B46EEB60F3C5993794E8D443C3457DA31E6F37DB4C7CCBEE86C491250AF781F81F3247CF94EE61B6EC9C493B6501AFAF2A1A41F776D4C74F2ED7F17DA149B540322D38EDF6214BF9D1575957A2ED1D0C54A20F661BA39CE2658223422A8AA5A8B6078A226C9E68C5A43674918A067A1103CAD71A9899B53B398358FD076DCA90251CC28977827FBFBBE71D9CCF0D333D95BA1F270CED5676648F5E19800622E1A0E893F9FCFE9065F216C7ED9A17F6320F866F3A95979DE3285E294987BC65D3A099E978E29C9F72ECC14020A228E587D3569D8454F3BCC8E5DBE8EA6062D4A24B1A9DCC20BB34BE1EF6C25F77E9EED6334CF6F4763CBAF5819C145D8326E558447768B7895A7F4C4CA5647A112AF1292F6F46DF796573AD3B76C2062921C252B7979119BE9309E104BAD3F643DC1433DCA48E3FF43C49B95ACC4E9941448892BB2BFC61A22F7EE5D29C9789F69612B1B3503CB324587D4CF882F40F20A46598C636D75327DD35E7132C88B91EBDD44F511E360EF6D086613F383CA4F70914E09CDFA544413A95159B3AE724FB2017F2F3ABE8AD4E64926AE797533931AF66C91DAAA46AA9AA9B331EE116EBFC57E7AF4D4466AEC4785FB72D1692E149C8EBB35140F1BD61A78495D85E5DF64EA74134E941310C59E51506408F74F1435B67701A7A76F472309A6F0B0097C8BAE4F86368CC7A93B66B8CDDF893EF10201A246D1C6E4F386FE727E27495A9735B667FFC5752818030E51250D1646AD69EC8D46628BDCF450F1165CC60211A439C8CACB48F9309FC1C992385343D821FE68BED569A972676128D338956578DF73A9186238F3FB8B1DFCC2357C3444EE25756DFC2B39135117B63D6CA4113FAD133913DB7924A7BDBD417F42D3B61BE442C451BE0B6B7BC58AB8A2A2738D1679E3B6E0F25DE923B242EADC95525D71672D527BE64BFE88956DDBAE1EE124056332AB20F8806C2F3A3F1292B099C7502CE94AEE45BFC85410CF68EF739A34565E6D337F4240C265A006CE8FE77FA10FB795155B31CBDBB22647E3F71D1EE798C3D7713652EDE11C9425E5EC06BA430A58FE95C14F08A87D0DC5E654F69A306FDA04FEE8B8162190517CAA7DDD644B6F5BD55F3670678E0CC8232F436A965EBD4FE7487E58CBD61E38DB2A31A95A9605DD40371D3D4F4C3F056E86145061B91A98F20C57EA2D38C9B332538B3E0F9C2BB204FCE003A79F09B71BF9B51D18D566C47B6A4150B974138C440DFB2F994E138A0F41F3BD3D4F2CB61A27CA36531E858968A851513946C00287C1369024AC4E3C46888EB97F7208FFB0CF0B7EE6D808AA09D7BC21300F300CCC2D75592F331A97DD69DBF3B58AFD9ACAD269C3829D8E77A4ABB0020FDD37A2CAA2BAF71584B1AD79BF8DEAE8D2ED1BFB38D04C437A83BDA779C2ECB3D2FB2DEEBBE1D6FFA1F7C524642997F482A3AE472EA925D11E7A06DEEBD272F3D16658B810124DC45DFAD77C3350901E571FE138869883716A4D1EC4A44CCA76EA6A5C1A72972751992C39A5A3EEC5C0E148FC0130C104F7B5DAC8340A88E6D371023237B64B203EB03DE0F91DA7EB0612D2C185C3F33D6678B25C39FD459DFA0B3B96D7BADFA2984B73E164AC507C898FAA55ECC3D086FA6FD28D9C93EEB053F5AF51A6A261EBF50ED3729FEEABA7178313FBD39EC1D010F4A831D088214D50262AC5975F1F34DBF791E9C72C48B6C7E9FB841579211007C336DAA46DE84954CD99E1B97CBE5CE34889ACC6861EBF2A63FB7745DAC42E0EAB5A7C7AB95B1C9D1BAB6D7AE20037988D65F973884E0816151392691405D5E52197438C39AFDA66532C7279F5B9B58B85112BF2C03A76FB54FE5EACFC5F12C3C47820E99647CDCDBBACEBC200B28B4D707EA257F37F1CE5047D2AB0E02948E1BDF126866D76EC48DD6271A2ECFB68040B31BFE6563AC34456BC66C10CEACDA74F3F92983AC1F8250B87D2D925592E3280C46A71CF16E4FEEEDBD53C240164943794F9D9471EAC03D15A5EE0DC1914A9D5C50E3D2AA165513C9BFA1560F04E06EBDE94C22E62932588A68C7A8B65223BC55B6FE75DA29874E4673AA3CA66217B1284AE0CD9C1C605556CB68156B833549146E98D76E0725A41F44B13F8249A19C169FC6F396F0152129A2C2ECC6609653644C4731E92B4AFA4516676D22A5BF0F263CB8430D40015046C41444380F80C2371E4F6EC825E19E5EB0FD2D2F07975687ED64C16684AC969D446F925689D468347DC3B96A6C5F715B8A69D60705E22ED45FF8598D3185DDAAF0F0E611A9337CA54B5C822F785E06A2BBB48ED9EBA9B39B7BB91482F27CF22781695754733278058E682D0BA140C0830902E7A12D6AE7C2FE603816DD1AF08CADB1D18C2FB3BBE22121F74898AEB1D55B04F300E8396519A41DA60259DDEB533E8EC3712B8FD07DA650E819E8EE0CB165863175E3FC70E81EF729F839769BC34727F5354395A479886B1B2D446DCB48EC2384EAEDFB9023B5C29FB8ADDB416EDF03DA9BF50CE8397DFF31EE52EAC25F482CD28C84A4B430654590BBB9401539302F23B914C62203BBB7AB7C709A08F8C707D2F9ADC49EAD6A0C6A1997F2818534248AF1FC0BFBBA33729675EDA0B0709CC1F6187EAE1F599E025966905F1D357FF7ABF118B1E7FF2186AA724869535AFA8AED869FD0F929C8AD3B73F01571C614E4CFEB80A9132F8ED8F65C67A6DF8685F1D2F457A9E40D0CDF005D7A6BF4560308A342E933B05549E40BA87E2A4559D4123C45E3238F40A91726B3018A59DE1CB116BF1B99E56FC42EA720A9276D42078F18C98BBBC2DB597B852542C8ABBB14CFCAC2E56D82BC403F321FEA9F60DF76B0FD5CC2F49AA3FF99DC46432EFD2DFE33DC6287BB140AEA5C3C582B9E4A7DA0A1FEF384A568AB86FF624086BD22CAE972580208B73AC88DE300A5792DFDB9516C113D42996DBA0A925B67774CE060D334239605F4E9F616619959568C7325AEBC8BB0CD5A60D312E130C33372760C2820192D87FC2AF2FB151FF63D2819FE51916916A13B883C478FBF6A33D1EAFEF08402F80E6E6D2F88001F96FF84E5CB81E4CB61AC804D733179175706FDD637925B6764001ADB6616A1F8D83262CDD40B505679699D85EC960E136D3D0DB3EA6FE22D38994D3ECCCC974982EC868066D98798551EB7E42825684AFB2AF7190E81BAD9F6CB426DBBBC0BE7231DCC9D3BFF065AF0BE5772FEB8A9FB1AC87AAC2EE9B0ADC2E86EF239E208D58B36DCA7A6F13B79363B5E5891A11927C5B7925F4157D28F27E59AF3F24373734EB10EC734F57624810B81E8A77C48546E8485E08274451AFB84A58F1B0F13B5DCA38DB9037F37870657E1379C26F47D4D45C80513069F0C08585F9778700F88D8EEADA57B4D3EF3DB100D889CCCD9433561F7A05FCCE05220509253C42E1710F08ECDE1AD49584B07F9A1FD17B11ED48E8900BF00FFCC1822A68336914F223DD80449DD980D74DD1BF5EA269A4725D549E249ED5604BE51F7369EE3366C65EF5F0311683CD5652583B5B9552472F1146BDD2DE068BA5D4C1702185CD34450F3B015C5952C8458C4D5345C9081CB1044B76EC63EBD725D38FAB0E111A11FC7CC130CBF3E9BC97FAE14F78BA4C97F60879660788DAE01A394372B2CFF17C93F3DA92B213C4BD00084602E7AFB11CAB263979B4CE9EAE5BB03C89EE41D546266BC371BE33E28AC3E43C52F66F823BB31DF5C97EAB4584B31D9CC2F662B78DD387811B90D3577CAB2DF90CA1AE12C20B8DFA7958C8FDA63AA6EBCF5E27492FD2219CA016ECEAE59095C9ED097BBFE985E3A6AAD24A0A8BC1D5D1E85FBB3F87944F6BC3010F39ED5062290FC826DBD5EF8592EFC084B7B45C17BE0A22792E48577D14335DD17F88BAD9D50F3B83D4373F37BDC88ED5D39FBF2B807AB33A05B229DECACA01269CDCA999AE5E5ECF4E6D18B5AE41201FEF3B83EB64358670C981F8B1D0F33930CF62F907C761103C6A5B0AB19524EF0EFC74837A1EDF14657E31929BC63DCC07EEE1581B47A790C86542EBB3D04A091C59E5636ED8CFDFBC3631819CE9915245815E2D3E127EBABECC5E4DA38F4CEA5CC9968A3D23A95970FEB49FC74C4B0C1B85BADBCA2827F55A556D6EFA23B5DE174567456984690CE9235012D13355F2CA9C43CD5E59A84400321E299D6507B90496C52D8DC48A2166B00E2726AD75090B74F288B2704C52E7A197DF10A3D4AC8292694C83DB9DA54415A98AF542C7C299572661EBF426DF387473B877CA2A71993F3F682AE25C13901B048395E66F09C69C43E3990668682EC4424497422D38E79B617F806F22B0E393007D9586D3CCA274F750E2D5ACBF5245972AC34A40787730FAF2BF004BE36AB098C5486EFD95A977A8675A9A904FE79CE8810A3D1A629BE0B51CD8ED3C72019081988FB22FC8B2311D0F91C37883378EFF1D8786846931D96EBC29CE0D2DE42EBCF20AB46CE9259C83BB86997B5E7275B8A9A5A81E65E4D6BC19D6E9C7806E2D15E5EC7BC6026295D52AC66D183099D8543CDD50FB5614BBFFD99ECAC7B5019C4D94F8EDB1BEB4343D1A22C898CF2132C897A669F255DB9884374451D4A29F0F92791D2229BC29230906120A98EF5484D55440243E1DBE547AA96BC0F578444FEB41620935E276B58A46B2A96049BCBE2AAAEC8C23578C8A0903BDFAB0EE272CBB59315E06201C3D633AB6F974E779D68AC4F35BE9C1F02624EEB780681BECD1BEC79F9480D1FEC5780DF79DB98FC392403AA4BDC47FD71DC3E76FDEBF58CD3B0472A96927F25922138C7C5DBC56CBD16744BA9FF8046BAD134AD90416263B52C3B61C3781981E35AE6E5000FC715093A34DF7C4A06987F87B4304E98222613BB5812DF652C0CFD8421B21567ADC5FDE09D3FE88AE109CFA32647680A6EEE3B5E2DA4054B61FA7ECBA7F94322514F71432BFDDD4ACB92E578BC2656AC7C0C8BCE6FD9C88144842545A6C56EF91DEE1EE62A70996CE2090F8D1665A9AE4DE52BB1E803FFFF708F551BAF664A6AB44DB8ACAF1740AF077A34EB02401286B67F31D89B17D40A1FD2CA38E197276039A64FBA2F5833108D587715ADD5285EC0914EE382042402B2C2E884873EE1DE429025683D512545047DA3AE7B36B4D1E96EE93DC1544B25A8AA7319697A653258642D22151AA37CE86D88CA85644A42457794DB0012A851194B94D58681261BF84819DD7CD3B71D85A0A407C8385A4A854610D882793C93C30526D67420B28B17E998473C3769E442D13B9B664DEC623AAD0DB5BDBB606F8E123B4B8AE037242EEAFEE8D94594761A85851AF740E3F4DAC75FD35D5FDA1B50D591BCF7C22FFB190497AF417F6A0E406EC22CCAFF1D1369F54B8193C93182A738ED6EF261779B785258F65BF093DB76190DD01C5D9A5F59BE7B1F93A34E86EB44B664F6063B7B08D53CA0B0D5CA926D449E1895D576F9955E215413456B5A02AFB7C14D56666298A2EA581576B8D275C3D02BB57D8C4FB3C71AEA31786E3948D0039DF67473A1135B94AEEAFA47FED3590AFBFE67854113D396A577C01128E91EB55028FD0C46724A6BE94F2472A37417A9DC44EBE7A5859E3FAB39AD38BD8BB5C462A0E57CEB14D3C8499B343B2ACF2AE1D003A32E99328D0689D787D4E067660A16E6A2C3022BECFC5885F85757230641AF0428006C1B2EC617DF866487022B356474959F2771C3053D9B6F56FFAEC6D970EEF014B427D5CB4F3F852BE64F8F54364DD82FFF47B13763ED931949731D6757EC1AC30C004A343EDBD6C5E48A7F311E40AC9FF9BB3DECB12F7AA5396EF949EF98275E624CB4ACEE6184D13D80A96D535B21FC59C9616E0E9E34E6858DD8DCCE39ACF505836462A255E2D58B0534BBD5B0A8BCD45226C178A70909C7A1EE44A003C733469103E6A114581250E8B823DE56FC9A08B4A54A28F572E3AAF59E6FDB3E6DBDB59553CC5B5E2E3094BDA6C8C97A58DCDE2B5AB6C1318AC6C796F31CE5CC1427F245572B730C26C993D8E3550F954869D82871DC8A3E903B7747ACC6D476EA7501D7973171DFFE8EFEA2345D7C9ED011F09BA6D2E8B992EE3D67439154699597627ACE5CB65B471F24D38673DC452E909D855C803C6923E0EC11E1F2A06C2A975C4B539FEF387AF7AF427B5A9501162EAAC8D2B55760FCD9FAAD2A4642BB42B85E7C58971B7F1DFE2B82D794DDE694C094B31717D90ACF61060B8B5F293B7CE68EC0CD2EB10FA43AEC8E604FDF3B0465A79F007D9DA481BF9590840EE0EE30D1A1687150E799459D1B8DE5A7FF92F43E0A298529797C4EBC7AB4320A87BAA208CC6E0A622AB9B67F9014F132B2D4A59E2729F218A8DBDF9147335336FB7A973A506133DEF843AD600533B325F5BF06095E49B00CFB078096E2D931F9541F18CF7F5B4AA716BF40F870AFFCC4EC2C64A073C6A7F8BE0A1969DA10173085384A484253AE426C46D42A14FDD8A0D555204A05A44845F6066715EFE2BA1C7B30CF95C60179986952DFB8094289C0977C7B737C7A1FA3945DC457EFF5961768E61D745F9CA4AB78FE5ADF254521B3149FE985D869E2AD7724D2AD9861175138E6853881A39A8EC1673849059F30A4DDAF671C537F296729ADA9CF7D86171C6C797FA6EB4D23F659BAB36D67F9FAA8505F26DE850FB97445C5670863BCFDE31F466E61ECF2FFE9E6314688F91D9F97D6641414A7908925EB4DF057E96133CB8E2C49E055E5137442A8F87AAF32E7F77034F438F1EC849A1549BF4E22155EACB038BBF3F6458EDDBEFEE5BF3D89975BF1A329B975F6E8CB9ED8020A19CFC57D527589219F4344E1619A1C85DD6E67DE3DF935E6FEE20FDC4579BD303E5D95EE5B509B58A3D6899B7397C2AF3E45D52FBFED35D8AD82B1FCC5EF76264453F64D8153994B05DA5B0AE4D428335F34AFA2C5AE108ACA9D50E78DB42D972A7C87EC8FE8BF524806232C1559596539C9416DCE518F96DF5649F7807448C53D927E0B02F880BFC9714C4C0438B95AE79645B209A2EC117387B83BC429EFDCD4BD41EDABE0E1D2B1BBA7B0932C234B3D3FE30E948684049CB197D82C035ED3A1D60579C3F9DB849A68CBC2968D7114D7F7CBF58E7E02D6C1633BBEDFC53C960E52B6136AD5620C25D2F898FE5F367B00720FD3D718EBA657666787F50CFF06725D4545C8E9C5686A57C0B6AD672088CCA2F4864951B164514082D5BBBDD3390C26206B4403BFD98365D4912751EEE910B75FAE27C4D5334B69E3C4618165CB68E45DC92F8906052FBE511EBD577B30FFFD48E1E9522D10C9D4C2B796F66363C621456A168866517E55A077833844DBFB1D6AEF0DED29BF88F9F76D22E71703F193057DE08C4A3DD711324CD6F886845E730C55E6829BCFEA1F97BF3CAE94D1552044F11ACCBACDA4A34941E012E0C67D4348B25C20474D04BBAC4B6396CA3DAAFD45D00A8905F9124DD0729BE16864A6DB768A28893F4EC57683C4A49173D0049FC915A8577DB9EABBC7172469775478A2E973F90086E363986703692BB416CBE0B422A9BD4E21DF8B105C97FA01EDF7E735A56C5928301D4EEC1C85A59A0DB6AB6886E1726B7AA4884A807230B4CA2DBB45EA7F1512AE9F53FBFAED6930D3A38F430E3115E277F41D4AA0F4DBBE84B0412C3C962C8AE43D74C07E1F35527DC8431CF67098527317A4F205FDCDD2C5B6F8462A93455310EB5C8B5E6FCFCFD4E6AFD0D4A7381B955CAFA1CE2CC87FAFD939B4C87B75EFFC1EA171EA07A275DC23327E1EB972AE3A42EEAE319595F3DEC76F097FB91EDCEEA10CE82554FA69E4D72BC5C408056018CC421DBF252905B89DAC81E4827F1EECDE696C465201CA1E7FCB6E84F645128A743552647D1E524E79EE09CC9806C027048C7BDAF7C5D033D1AF1F2F832520E4599FFFDE257E46F606B6A96D762E93CE9F29ADFD0067CBD454C170224BC19E164972A08D6BFD3EABBD92A9ACD009E13E70F194FE8E16761DDA54F7B2319335F7B11513159CC13D699A256A236431D02F19A554E24635928AEB0C06AAA03DC40C863D6D9483A6CDD22CBB79F82A78E581941D143AA02F8316B06A3526CF62BDB5B0084AFB00642DB9EF335C32D90709440631DA39AB38193EFC4A091AFE7EEE2A3AD4C7284388553B4A388B8BEE6144C1C32190F1BA3E5181B029036BA23D632C90E0662438CFB26696BFE0DE8517A77E3321818CD97F8B89C0F52646EA58A17E044BE611D7A8378083B8D5EBBA5D4DAA8114F0673FF60388FBCD98F3D302385E760073B5E30AD141504CCC9CBCB91304BF02917FD1B5B0EB68D1D85B559A26F9A585B16A0E8FED0C000272E2487D8D21332F55B5FDA26D35C34C8E702410728139FA558A79D4FB2841509890B73AF96B993D4873D0121053AA2208A22DEDFEE805C4EAB14DF41489A74E42E1B6DC4693AD13553B3993731DB74188C50CEC97C488410E6355733F17CD0F611D6EA991C69F53AA65B43EDE46447669E630F9AD8B643BE8020949554A2C04844D9CB085981FAFAEDA58402359C10CCB103C6662C6DFF41C451EDBE3DC741DC46846AAB0A3FD27D92425D41B5305ECD8D7BC8F623710A43372515BFBD02F1805F96C3492D8744DA31B00F8C4277E2F65AC664C926D6DB00ADE6DB114DBF7CD580FDC371921ACA774B284AE968836056609199F38EA68C626C07CFE19B7BA2397D863083FAFE9E81BA5E4CEAFCB4B283CD1B4982B98791AAAEF031C9FB8D65DC242050D9A133B64DB5E57C3BD8842D3ECB1B50019D3FEF411613C1D5199F2A00990A3C6AAF0A343F0F30A5AAAFA0E1DDD37CB684288DF1410112174B0B137A4B9B6026F0BE67B8ECE5A7D4344C7C333A60405978710A2F95E34FC4C2FD4ECDE5422D5392512E7B04F27D8A5BA2DA7FF837484BEC3C17E26E5DC3DC6C9D16A03141F41C1E87F358AD555E50A366FE7F6A661ECBA6405CD82744A5F658A31D88C3D73303F0541CB2014622CEC76543BB292D07A9FE683158D2D6251FAB3B6A43F7F34BADDD285EF76B2EB51E80A6BCF6ACC767695FD3E1A4F33BADCF8F09D9F205D2555BC3D4333CB16B0FDA573A390E78C05E7ECF0170204099F8E8A0DE58F9EBFF7ACBE5339C7FB01803CF1ECC3C023D6DA93DAE2C0307A7055CE5570A6A1E76D24E4313CFE81C7EECB6746544AC159241D464747502D6347D8553FC39485FD027659EFDC34AE3420C6F55F6E8A58F97703241F42EF87F9C8C3C26C46F97F50B9AD368439B2AA7EA6F92241601253E792A9F4F9869D3F66812F920C8090975398D723DFDF12075743146694C54A65EA381161C6712082E4D9107B7DC74A3AA02A3851B2285595F637CB65FC613086831A0F526FDC793F675693E225CCF3FBEE7F483E85ECD8FF9A5D290FDD24294F6A113D4070FDA80C4E05DEF2DAD2888699A6B091075D9DDF1DDE3D8E02A22651FD829582CA3B69098ED42A81BACD9AD5FE12177B52A165E72D85F4E1AE5D5A8F3337039E8CAE5FDDFEFF0247F8ED66FC8D54B05ACC5B11E4988A0C9A98FD41C34D64B3D2DEDBEF8D8435411F81DA7CD8BEEE8845417F5608B78E017800EFAFD22D38B60E133616DEBC47386D8B64A3D5D72530CA31B8B28C78FEBD37107BA9E9B15E1DCFB6B31A38BF9687C094E3C9937080DA337DC12A60CFABBEE179F8C0D19780CBE6DFC7A205F42096589E851BFADCBAAF020E569D0BD56282B5F6E1B776E66FEFCF11A29363F6A32B8E11BA54F044FFC450F24C14FA6CCB4656AD8C82B8D105B83E31EA8D5C9F0FAD6B82554EBDCECDA6D8BD7D7B6B00D28E8E4D16849490A446880D4DBE7BC709C7CF034C72F3CB1A8DCD11CDD18C1C58DF373C10F30AF7C8B3496C455A68E89223FEEDE94427EA777741C5240035F8C94633438BC020495012F414A3D61F69C4CD0184A70D199F761EA9C6CA86275C4BBB635477D420A49F516182E21ECCC927D68D3BA8C2C1BF0857426F217A5CAE3838858D80EE875FC381EEC855AD6741DF673F487A960CCF8B9522B2A85C696E63904078FE2B37D0AF5DD2FEADC37F71206AF58D3A2F5831EB78B48049A0BB69913D8F2F1BC1D1684CFFD088ABE0B87405612F98BC085FBA626C553187ED83D9758F68C4E8D122AFE832CB1BF75F4B9E5705A68A5AE91C5C78C61E4BDF607D933312AC3DF74E01D5A9E2AAFF3043AACD7EE898B2149B758CC2323CABA9A976E65DCCD56F7C39B13AEBED82AE2F93C1478AB1C649041E2DD32ECD8A8D0FBA92AF72A6A9B9749D13CF534A539311CB7E10A93F065CF4880526129F01034A962FFD20FB76245F79088B015ABABB0AE7E29A222CE2AFC046AC1EDDFE0AFA5983A4A3688ACA58D9B333493328BA4E093617ABD338954205B2D067770B91D18D64821E87D8781D52F20E096B44505E4F2823C364BEB696FCD6CF8A5F607862DF370FDBF502801984FAE20CB0AD4C2844E6E6EF5BF6DC33918810A30E10072BA5F51F933ED174E20FC1D810958A4ABEC116265C0BEF2E5888EE43CBB34D2117848BCD07C08F5D4B09CA16212741F2D43D2558F19A3019519082B4DC39F37AAA278439C3E5C44894965CB34EA5B4D16C90A4291F5114488B5643F7A906B175D3C153620DC6126210C600A0974469573B891CEB02B374B71D3BA534006F9CB891C49EDD0CE2E311FDB9DE14B770AD5FCFC85681A0B3992EC20DC7F81E61DE318EBC66DB2EDD42B2B540F91EF0689C5E02C5E5A1E0F113E435F30B61CBED530E82B9B46F8F6A28F14E6D9C0BD17B3DB9AFD2273500EDA1531D854D88981FF88EC342DE7FCEE9B7206EB34213F42FD4C254F49C90E47EE413B698CCACD02882DCB955E0C08CA4936A3BA3CC07A03A29C9D5A1C43D8FC6840C53ECB80F17F3BCEA0B298B81806B732F917CD6A6135C0DB7848F0C2BF46EFA4FE7381BBC47A32F7CF02C46B02BC11BDE7F18FDDA7AC854994C4D8FB8F6FF4F8F4EBC1B4E4FA511F6C78AA5C367B91236B92F7AE47B85A6DD7CAE2826C26D79403B29921BDDABA218BF9331188C2D6212E8BDEAD88EB9797F5916D492F098C6B24AF4022EDF6DD12306EC8B2F9FAF6979DB1D805FF54B2DC161CA3E3A1DEC12A35D65DC055941A3F76CCAD59E5593C0A69F56EC3C34461D9BE3823CA52C3808AE4A0CF5A40B8B0E99E89893794AFC7E1A020DD3B7370655265BD601ADE1EAEA97F24DA21C8CEFFE3C270888C78A03CF5288943EA38927DBF090588E59D3A44E49D70E0634D8E70BA03CE28D0B234F07F3E0C94FB4F40129B1D2261ADCF2F001BDA749AEEA9D07A156E8DF29D734D17FEA92A6A6F13AC58C927EBA415F5794F24FA5540175F74D879A2E0F38F89B660BE5BB4FAE56C7E44494C7F69804DE20F48FC51DCED12C82143CF491117B7097E3F897AF4BAE2AD3C3E8A38DF9B9569DB4D67E3C20F4FB5BAC779414384E8D91341D8A23F75E93F9B635D095E60E6E9496CADC878A3A887D22032D712517995E5FE71FF804FAFC9C74FAA7E2412192CE27B25DA96926A17B844B32BFC59D17154C1032532CEA955CCD00208CD729B78223AFAF986E8D26DD99E2D59F27C81C9DC85E613CA934EC8B996FA214F94920E3FEB5C495F5C715C11FDD97A6A4DF73D4D99E1102F0A044E27A49489B910043FAA71EF985405A110869202682284216D86A1401EE029ECF0D85E4779D744E06974D989BD562593FF6DCB8A00F73ECA411D98C0ACADFA02EFEA493A0B80F09F0A727C2BB5186B84264C6FB60C59D37660F16FC4C721CD19CB81A3ED62CC73EA382CEE9ADCDB8AAEB6C1B95F0B536161A16FB41797BABBAB6186579CB8A10F7594A2E071232632619D290B40EF5000F5606A525E5E9DDA2FDFE0E660BC17DBD2E4936468DBD52EA7DC5A05BE1979D5CE884D7B0AF950E519A5BE92552A61601DD2913E01F6BE8D3D7BA8F586D7D1362B9CE757FE2F926C09A2EFB81B3E114905B0A0A20468204806208C3424E6AD9BAA8BA3371BFBE1BEECDD061E1E0A13934410A471B4B4BCBFB41C7871801CFD3463B8EA5ED697720A54DA04ED22F9248D74E3C110095698CB564D9F3CDE75A93359F52BEFE94E0A7FAF1FAED01AF84F4302007AE04835E326DADFABAF6235A8CBE1CF41E31D6D6D7D6D360516EF9795F2E03F3911A161CE3E8EB5E9E904671F00C8A3B852A4498CBEA83D6285A4FB414D628B123C84E95DA3DAB4BE232173065771F1647390AE3C5938E955F93562A9B7AF67E2F6E8754840D1649DA13C752887F26BC68E7B30C69F5BBC66B8D43F70B4C81BF678FE83E1E893B3B0A2363A86F808C85CDBAED1733A85132BFE5E175F87B4091578B08F980077E58DE792DF9005834359139FB085FB1BF92956B3A2D76D905599AE00CD1E97599A6D2F05C722BB5F13DC581DAB6A41899D68DD7A6B315DB21B6BB890EE26C45EF980C2AAA5D75D56A0EC0B73A77EFB883F4E62A6E5E7CF58ABF11C59D76E38B4ED61619007A9DC18F21CD977D2B157AE9B22481C586801BC3F92D1493E8C501A6555648D278B12ADA547263025FA95A93B34015F04EA8B37BD39783E1B9567FF484FF5E719D42904D0299D613B93DBC8B99218626BBF52C4E4D68E4F65125A8491E59A461331E1B404F7BF879B13B70FF726BB80E7832ABA8E072F1437EC4E5CA106C6863D063FA9B7BACFFB24BD32AA6D624F30A5A2943AC7A085069137D3F62BA22962D9D9AAE00D2BBFF35F723B3EA698A2AC3692C48A4130697952EF8691CCEBE20A9EE6B33648186B45C1E9EC5D26B456B78E37E18007C14478CB46AB05176FED3B6CAA8F129E5D92A15522AE226CDD335FBBC32C4F6E40B2CA71B4ADFBA1D62BD5ED5FBBA50E0D8F4EC21D22555CA7866A9E504147A802823CADFC900AA92A6B94DCEF9A32A868446D5567F331EC8D3B9B855794134D367A1EF978CD079FB7214DABCF8F78310F7A3145FD7374D5931858970830C350686E9C4BC93432E26A86A576B526CAF28BFFEDA36A4A5B016BAC3FF4B68D09B881F4E6BE62FDDE77517FCAB64DA19339AD97BC7082F037697660D25BDA758E6B3911F830C1EAA8577445948431A0B4F055CC3EBA94C8B6B4E1178FF80FACFD5D949304D56F3ACCD35DECE845C824833BE7E3CB2403F3C74602CC90396542A0269127DFB739A318C606258D943C5DEC6B1F1CE3ACF0CD948D9F17AA2C0C3C7542ABFFA36C3CC46FA44397646C468737955B3EF20436CA9103E7D0FEBDD42133A1E0CA779E9A90C61009324B2480DA8C2ADB1D031D6A1E916F115B6125F7E6D0EC1C0DA7A18ADB8328F492E05C081FA9D423E962C1154A430196B22D155005CBB3C915B5A8909902E09BC1A7229AC7A901E032033BCF8F482D3128F1D55363234AB6840110D3F755995F428D97A4FEE849537AF2F8026489010FBAD6892561DDC452C15420AEF20998CD6FF379646AB6A2C0A0302ABB294EF252D6CD051CDDBD15514A98B576FEE4BAD5ECF207B99198ABE05563A4BE3693CA7A87C3468666FF174C55E82D8EE5266E51B6AAEDF06AEFE78CDC6DB7F2332E0749FC23E2BB08F975A63A404592F88CA0B4D988A30CBA49B323CAB8C1059DCCCBFE5422C8E68889762C1ED645891AFDD3150DFE89E13BF851008ED32F356B97CF846C86FA52D16293A6CDDEC8923D5D4E9F6CC0B311147BF18A5C612D4B318AEC20F6C4686D7930E932C758ECE9051021AAD99085758459DFED5CD9C1DB2E531B6E6265BC4463A96E56E275AB466BF5E13CA5B3470AE225AE8FB2CAD575F3753CB248DD2F06F7D22A50CF52F351138B1C08E9BFD71FDF1D576C2BE12C7C6143DEB38121E76883CB63AAA310EA3D82F5B221C3EBCEDE0EF870569FF52FDF1EAD73068DB36C1888D98AC03D085CAEF954DA724AA94DC4091BC90C014D5AD24580B8FE4B0FF16E8D21B17441B1395A15D7C18855F5778F448E0C87F83FE55282629754186BA12E6352B7BC9BD3AF81896BDD768EDA2BF8CE5FA3B265434BC56B76833386E0D1ABEB6EBE505125771D52632CE44A1B75D0069E864F806E2D94C60FDD78E518F1764E5F5CEC2F42CA796B88834B0C66C683529371D307DCFF220C27DCE8D38B94DE7EA17C80B66946F18160E5CBAC59594A8FE4542B7F06121810E3D06C468D167F93D698A5763B242B14A5B2DCA11AF7292E1D061B5C444BD34158125440314E11FCE408704F408C73D3B16D2FF57A7D4F975EC8F1C4D0709CB670FE42D075E6DAB45C00BB7C39CADDB4809BCDE731AB578A6EDC4E896D409FE3FF067DB341615B82A786516DC6CAB0AA5DD259946B40F00B865333D6AE0FAC263F32E947180942E2282A5868CC297BF0079632DBD2886795162ABDD153F1DD2F4B411BA2EC90FC968BDD73DBEAECB3FBBA04ACC9E6FD3FE9DB8654076A0450A0EE05479F82C8A82F5034D0D36D634292C6904AFC589ACF55F9A4B2837234156D9DD4E33AF4C93EC34C73F97E9AE1D6FB6386A55DA95916D8AA7461FAA2C90D512A168E19F99CF22438F0513EE97761AC759FFE5F739E2048DBA4C39E63365B1FA95904F78EF9175EAB9696316B153D1B98AE51442C05500AE2B9B6C82729D06398B39EF7A0101AD4D606E713AEC004EA270FE6519EA9472B9EC6D7FE5DCA5B34C233D12057FA7715BE8AF1C7AE4D929E1766B25928989057524898469D55A368F4B1004784382F17BA0720F56AC818C8DEAF6DF2BEBFC5BAF51B5FAE1DC77FBCFCE778E63820E029C48DF80FE6D8942874C82597750FD8BA00868E317DC40FBF6894935154C566526FA5E4BC6B2BBEA71C7494A50389A33DDCBBB890FFB878B887DA1F0F17848AD4CB0C68E95D7A4A66F22511CBFE54E2DE4D7DFC1129F4808BC155A7FD6A8011B2C43A89CDE183EC441D631A9EAD43460B2B69FA6BDD5AB32B5FDAF128567AC5BD4807F610637CFA667E375D912F26911C3B586AA2866B150EE05B93566EB4EE2E853504D18F023706D038618A341812FAE1634B70BAA33C9040BB877F4CF07BA7A49D6D96E9ABC0D1C9E8DC9F4946B008355737D7DDA12EC6C8E1A9CB45CA66DF94B61BDCD12C49E6E6BA51516D875C49911A231EEC5BE6EAEB4244359D4B7C9447964B2053658E916CD9538B21A3EA00F287A985ADC5114A0CCB15ABC46C854CEF0BCE191CB525C3C282391F2E9149636D602EBBF884E097F9BB90C5331D12DB7F0FD40CB699D89FECCDC7410C7E2B6C7AE95C119A0CDF8AF8F384BE13C23DEB2598A06B054394267D61D891C02BA6612959A0EA3D1A28F85312E379A0367C95F0E24615154227FA2500BA3548BBBA46F81A740D23944213F4F48D654C6F6AF41ECF4796515AE92CEA08D80CF2DA7C70B3413C451825E2F7B83D0EA99C3A4979688E223971D8C8B9A8F8228520B113D9F6137C0DE9CA060B3189E699E088FB8AE9FBCA602FDE791347F5E29A71D3BD5FB290EA42F5AC8F0528C65D53A0EE7EBCDB93DE18C6CF427BE8DD392AB146CC46E04028507D9F666903A836947E6F2B0206AF6E4E618F133683E977EEC6D929798A3ABF18C38E6A28FC1581DA524D5F6EA9BF7BE47AA785090979A12D4E965F40E2D3A568E768D7AC02879DF2B0B0176ECBDED2D2F3227355C125CDECDD61C91282FBB2F5B76404E8D73AE05F74B9B7B9FCAF8020AA53688FB99727A64A39292B06F4115DD64AC8BB2DD8584B4A42CFC94A13D4592180621D89855318FB9C47E7B556EC6DEFEF1D6D7A86607F2AB676BDFA8B8C03D0A892E5A9898FA94FA5B2386649EE75491414455A0FF1078320593CE6CCC8F087ED6EFD0997698852804AC62647DB4E01881453C056A91AB77439DEF983574DB19C96CD404FF23ED0D87DE78452FFBDEA9DD0648FE7A32EB3CA85122FCBC8D309E0B6AE349A56AAF04314373D870DF994D733D9137BCDF3517314E7F282A709C4CE8893C695832BE19AD83779C0622EF4E525A991E8E1F0F1FB339E6314318FCFBDE16A1EF5BFC32B51D8EC9F7071C83EEBE4E6081DC20441DA02F718976B4B5DDDAB192D6962CF92DC3F31EF59FAD3EB803CE2F875457A4496D0896DC385811540E44230EC05BF2B3E33BB88EB4BDE7D3FC7EB1F62FB54D3C642E2D1E8308A24C2324C18F27C0E00BECB195A1CBF15A32C4172D6A48DD7A72677BBC0695583E12AF7A4E6499A43904715CCEDD7761C6E999F422C88753671C355A9EDF273D3EF9149C64B5109A551476174C6EE74D1FC43C511FB5DE28CBB13FDAC58AB50DC98A9A0EC0F373BC381F5A6226DFE4C56F68063B59C7F3A36EE2EDE311A0ADBA653A51313A06C3B78C36EF0E82CEE7DBE2C68397E3A1F9DFF85E7DD89C95FF300C8951351DB52E17F3E449D2236D6687BEF754948E50845B05D033684663A432734807D594C080ADD589832CA0D6E51BBFB624A903D13B68703831238C94464F5E1C1D9720F0E56DC2358763C3191EC86C97357A4FD94CD5C0BAA6D144090DE4D37D1A89CD8BBB7B1BE9AB0F774F1024E64C46943BEDEA1B5D6403F2324158B158614C33B277D92277DF64E45F4896B5C880B91B3371F679257A0FD29B583FBCC758B77902A8A97E245B57FF05C1DEB84D17F49447958BF92202710B8F3AF33D39EE01784F6B7757D321CC8F4951231FB0A435958494B7869C5F387F3EF17807F90706D20A194C5F69C3783678B92BFBE92F52093BB2E88C04DCCBE300E78F0C8730E12A1EC5C44BFF9D1DEEA05C33DC80BE1669CD4C8E65891641258F61D390140724DE13C62B1C8660D070EA7C2BE929489D0B3260EE359E3D346745862B565CF03FA43A85B49A1D0A1A9EA43BD6D1A3F4495442504D4249195CCDD107769ACC5D73FA0299D4E0873A15596E5D01DF624BFC9C11166148C727AA2B1CD50C497E085858AD6BE8E3CBE9D11859CF70B237D90B2231D47A55485ECBBD5FF2C32F1FF8636452B1774C068C7AC5C891A671E6686B29B696CECA78A261F20CD88EB41F7E8F64EFAF7E108EBAE4EFDF02EABB7D6C0ADBDBAB27E3180EC19B95015F362DB1FE92BEB5F225D632B92006719900B7EA8C4C75DB970ADE06906C0BABCE5E1955CCABA581F96B870A5F05D4A8CCE7F620F79EFF9B7FEB471688F571D059B36B93F0C74CCF67948326B14160830F5C402108067D7B5A02C23EA2DCB4A42DA29DED563384EE91A22F364D4E49B58A08570B7C9D20F380349005968D8CBD8FE1208F124AFCE3BC0540994AA8ABB777C4F8FFC80B22FEEB888F9D089178D71F836E0253CB75A3575031A098ADA28597F597C8DF5C7C57F1654606C043C7654CD8621BA14BA09E71EAAD10FE8BA1DE3E7AC177BBB0CF48169E02FC84A4BBC4BC3DA9033C3B54AEFDC2F85B437B631E0CF2642EECAC95617F1EBBF4B5DA1CE90F4D8DC28B09A06970749A20E8248AFFB376D1F9AF7C0319C8A3C141BBFD3EB002A66F5A5869A0B8F371AFC89320A9F34F3FBE2B523D347D257B7DDA78C27479D2E297FD0D79D4DD0B59001C1D3460D7E2EEF2394A6CD98116FFE326BA575732DF12497249B3D43FAB93D145B41F2A5C557C0BB66BF9D5B50DD44CAA61EBE2C6BDDC15E1677B43F472501E8210E6DCE0292746E2AE2CD299F75CB222C39193588862332F77831943D9609857241F5722E52E55CB64AE57FD2C4DAB0A40BB23B28E8607AABFDF43328F7C91C1E205D41B0E6C9798A4F491F94E056D324A19ADEE1FEEDFFA68F49CC33AB97985CF9CC56EB88538943580338022EBD5341D4B7BA131B29B5E6A1348598F3983000D32EACF6354AC20D9E6E5FD3219AAE1B79585F9C1150DCDC97D1E42D493D167E7A31581C01CDCB237ECC1317FFF8EC02414FF29980C2943611FC5F64F0B797DFC0B3C000B0C25A28E6A1882F45892C3428196E5195EF6CF44446E921C6619A4494FE00FF96CBC83B048691D288362DFED850B01AC3B2651EEFC45EBFB741C87A98EAD95F1A3281EB20B52EFC5EF26CC38361D9F078B4DA27FF711342DF984B1F932A67819580051A6DEB3B55CFF0835C4648B8EA22B8962D22D1D5F2F72B77BB39312C0AD0381BBB81F6BF874D6A34F1FE0B01AD1D5D8BBA8EB537DBBBB14E9650A414AB0E0C7AD9526880E2127898FFD626C14E0F3DF32D111CA19133E3675DF7E8B96A6D8FB50AC32400AA6AB8148E92D4EC5FA01EB53049084AB73F0F47814738CE60400CB9F4CAA4E20427B791EB3EAF976053DA0958E10DEF7499D58A1337AC6318A3B969EFA175FD88C8F9E18BCC6C489A09B8FFF8035E8B2A4152CD464A5DF52EC0595D2A51B466DADBD444974B96075D954DA46885890DA5F182120B9F8A80F43AB072A3FDE7270E1A2050B6676139EE1110E73834AC98CC3E83964281B25526BD2D58A2BE80FB4872B4851128CF2DA8BA9464C353109194ED0CF7BDC851C06AF96E7DCA691C84FDFB86971DDCBB8E7C4CD2DD3AAB23B5D324926DA586E63DD8E830E86B2F13E054CA0A1BBE5527C233F0B5FE597659919157826D2456A1153C97B9C4B75A8EA8255609BE21FE12CBD4B71E5AB6DB9E233EB8D38139857C5F46E9C593B0E976152A6F5E8AD838028E5960A4A80B284DDFD83E9A4ABCA646DDFAA7F2D40C5DBA2B1EE5167A7D1603FCA615C2EA96AF6E3FD35F8901CF7E0DB719AEC247AE020F380B5114EA497141CB91E46F666EB3495F89F255FA2025B42FDC9A6962611D97C23EB46BDA45F2688FCCDED26AD52ECC6F0EF31AECDE9BE3B8B0CB7891B28083DB4B1640B9B9FDE964E766806554E19AF0CBF4BB81AB2E867C5B3686AD5DEFA1A7416054681F5D721BC0EB26CA87DB7BDB36FC132411EC385224FB22CF781D9E2A98C8C376FC543C87A0A052528D7C015AB320A46FC8036F8DE22AC778A9367A8157DC5C0B6D33562A01A427D1AEF7936BDF5FB44E6DCA3418FC5A3F335C784C856C6DC9FF9990C04C506E33EA2DDA0B38331A38DEF0B8DE5FC81E426736E5D1D27B5203EB8FE4FF13F037BB9C19133E1D530DF0CDF661AE7E0572F0EE8624DC00C5C75BE6E7C62F459378F9E598D6C79B825796FF90E3B900F1508583161EA030212591A60F6D12F6B0B4DBF0FFB772FFD6B79B9EDB5FB80404E7504766B8AE5E6C373D7490932F4FBBB94CAB3B30521A4E3C9FA2FF600343CFE3FC718978383A0511DE4B63BFC6037440AC11A90D0B4B8DCB30472975695BCC3BADAA4DF99D2182A76C87EE3895408BC29E528D1D970915950B1DC068000AE2519758C0C1908463D60A531B6855AFFFFFDE6DEAF67DE484C582773C542C08EC75D87A29208AD23722709D6F3BB61477FD1651E064A4CBB8EDFB5C1C2F15B31E770B99CDEE5D0EC1B4EBE79DBAFB96B8B3136C17B0211CAE9829A49EDD689FB39D986D5B5C35021EB5E36241FC3AA3C8AD0B67090C05819C2FB5AA74E6C2745E989EAFB9F64519ED4C77A3117F5ABC2C8FD5288EE3D55AD5136A6FD9D38EA12BAA4C576BB87C15AD0E238ADFA626CBAED74B40A5FC81988134B28E190E5C04977A02A9FED86BA505984A19C61BE03A49AB2AD28572A9A196611E03D21F445A6F690DC8358F5D4CEC7E42FE9BEBD071FC198F61A8F7E85349DBCA130EAF138787FFBF92844C1D8CD736760C54886B3781E8C683F54FCD7C1CA75C0567A9FDED4D64EC98AE9FABF0D41DD3094CF714F4F8D0F3CE6F1B0ED651784B18FC0BDC87AEDF24CE6B9702A3F78BE6A2CD2E5010108BCF5C7FBACAFE05D9A0407FCA1D95C6CE262CE70FE3923D35D59B29E27EF412DB81976234BA75BF5BFF81471A69839AD6D2B6CDB1470DD4A90E6798F4E464606B777C506B5B74348CE957F878D8985C24D64DE28088DEC4ED9DE68B01D7786539973AB526EAC403AEA89D2E400CDE608669B4CAA6005F56FB07D9E95FFCEDAD0FF933759D8386082B9499BB9FC10537856B51D747355637C6D29E6DFC8F223A007314F1183D7F9D0516FF4B1BF6DC9A2C6F20D7772392D83E9795B6CD82A45DE10C952D684EBAA828046437A814470044E139BF505E76CBE98C1623E15B9A28944474AD07932F057E22B3F1B2A98BE4A101D082886C4D2B757C6A62D26340662812A4C690B11AACB3F09F358815F1E977A1A24A575A76EDD235129F97917A70D26BCC2A61F5262374F647D913DDBD14C3AA1840C42AB2F562F5CE944D2CDE53F9482F5620360DAC190CB763F434548C51D9510C640927E89C461C9E7BBB0B55510BA4593F059182A7FB391E1E417413E54ED632002B5D8C05CEBB142EE6D31C88BA2B0F87E61462393EC3D568B1B6B3661FB8F610E694AB324387CBAD03AF8EB2A353042F5B97838EB1313939D319566CBD33B721559747407B7F6EB1CB60083D22AFA548A2C3843D3952905FADE717348DE4A32B8A004AF6396B1D4E1187527AB259775EB17E142C40A326474953C135799C5DA28D683F7BB328D101706862B50407A0651C21A1F07A7D79D275B3D8D46B32AAF28ABF5E92829ED713F004702C91BA035D369AA860892E54D01AFBCB86B23C01636648828A9D3C42FDF699CAA8AED7A87606FA31FAE021AA8CD6213FD331A6492A57F790F8C4D8652BC097C868A61685232C1FD00BA3230D1C19C0773C7BF9C1FA22DE0F8E036923F58403BED7E9E8CC209166C1CC53FB8D147E17E384808AF2C9E9BF91398EFBAA83BB6A40BF41D1BD8938684E804845D00B8F031D02F00717C6AC9EE7D56F3233C2CA3F096C88F13A87ECB67D406A8A99443EF8CCB1C9E1FE15A0AF367B95D89E7F71520BBF9BA4AAA530CAC03A1148D3EE7168E4E91AA9E6D12FC53C0BE2C3B9396A5A386F8ECEBC4C6C16384CF89F1E934D9FC17553638C3DB09486AC7600054A4A227C0FBE8C1D26A9347253447B9A982BC842F7D6DA56F296BECE64D2DEB4ED2F2DE79E19D44429A7EEB0B6B2C8E9CB90ADA3A569F75A74F91A0C4E5242020F03F372BCB5CCFB555BDAEFD2B34657F45FD24C9E062113C9E9D6290799EE2ABAFB9243F6EF4F548DB65B223508CA4A7C54EB81D9C49539A1BCC9589490B5421F0FACD38B8EC0F529556A292A4D608B28306DC465804DF6E8D7A7EE5BCD5561B068951F156F3C0D7015493EABD1B32B917D16FED4352DEB23F9BAAC0E3576550C347178C95BC5362E0657F80E36E5BFB4A416E4D6B8E6BEFD285B21C44C6F1EAD2DD59BE34F7AA479014BA1903732EAF7361BADFD2FA49BEB13F43D209778D5A1DF220B6029D038BB971497D89C205C25188C79D4A96ADA64B84929EEFD221B75908CFBC8D55696B0EC64BC154CFFC3361E68F0AC5918DA9B4F61D411CDC1282F64E2B6CA6FF86DB7492B18FABC2DB37F8DAD83C2B68E884A862B0F925E92FFD7937C404BFB60B16728DBD494059A4757759F452BACB4AF094B4EDC3057DCC214DD6482D44859383A5A2A878C72E60EC22BDFB07F84E735C56571F13258FE26AFB2C62014183ECCC7593B62069D129FD00EE94207BF14A18EE1CE2F736DE6C5EBA8D520EAC681156CFEBE3BED052DFCBBCB42D7A51D5C2A172E2EE3925EC94D59374BF4B0AAB6629745BDF27568F5DFF954B36FE9232BCB75A59B67D11E37BA87A6F7FF346A446C3AD3060D2CF299F05D3D52ABAFE61C1F4D1FB1B912F784ECC290CFB371F19E5D647A7A62C16D7412875B346322D30969945E6A215AB1F62D6998D1A3724D725ADB797EF5CA441F5E2BAC539D35AB3E645720105D8B565CD0CE83AEA6D60016A61141FF30938F24682A74961C9119FBBEB6C7CA95DA9163A3331B29AE63D76A22584449732FEDCA022C5A2AA87AE66F67AEAD257D4DC8F7F37881872211E97EE4A42BAD633F56E31EC3BF7C94011ECE846D804EA1AC7B3121960DC84C6A42D921A2A2DFE9FDDFA7A70F241412AAC4066747FCD008B21A9127075C256EF29658D2DBDBE8C0DF52C82B34992F8B49391DEA0A18B4DFE8CAAAD9C99CBD06FC60DD990402F2F4B07BA2FAABDC135B866E5E3BD32D3E0EB104E4A757142F43A80847FB563BB80FB84DBA2CC3BDC0393AAE483AC6A2A5E4E0CB19A1D3C8E49077045B0622F671D6E70717BF15BF4E915C7650F95CF15B524E1CA071A2A51D8801BF75A805CC04A724092E2BE55F9D8039CFB2E6D6AF800CDDBF7F8CCB9938F927086A7625D6903364A2B84F37D85BF6AD16559A3C8B187239B13030442287EC2A1AC3A0D2DA3AB0EBF37D62E00C42D98270DFC43E917A74BC201C60D94DE904F8A625D0178359EBE711556F3670806F8D07D8D05129748C28CBF4F117AD30094197527E00320D325DD4CB3C351A4BF33E5D8576B744AD59E722606D38509B395F2B6A2A03792551C1C0F9E5F26116C2D4268B1DBB750DC114787BDE9E1174D8C3F8999C4EFAF84F253D1B9AACCA6CBE1DAD25C861208180836FA572F324A899DDE228BCCADB545B644FB288717954EFF6CCD0260162101047564F6BEF5BB2843FEB8C280C5CD99C7D951052B102CEF3F136868809BC1E634DCE9F67D8CF6A6E86A0690696C3096858395CB10143579E35B81E18BA7D712E3D4A398BF14E534087142FCDD39773402D0943B97E9F8C4E214D53DC37A9D5F25DFF856BF9165C964619F278E591E67C418A6785FB9EBB5D19C67156520F5D6636B47D3F83808829AEB2A02CCFCEB0EC4B4D7DAD2A84D7028A926856CDAA9D6111BBB53EA997D023B1E019268E9D9D9BB1BBCC352D86DB733387683F383B6FF3E45357C49CF5013EDEB94A950923FFF3177B82BDFABBC6959E590020654E1A71918E14B490E18495FA6C86AE5BA8D4B148A34B5158531B4EF78BE7F8509EB008A6B1DE3C69D90BE27471D1D57272152EE892B28114A6A80BDAE2F3683C0A842D2DD12335BCD72F4C63CF89C787D4F8A676AC91E27E19E20F01CFA02274E7EEE466558974F0691BA1B17C8D8EE210CBC309595E5A6BF2E289016AC4672D320C81EC79C35E8C20A93C95F09D9FEEC643F040E044784248238E081A48DC56A5BD7F64D1875976897F058157D70BEE8DAE543FD8F354D9C8DF1F9DE9FC519039892A88F7D3833C45086CB726F979E9728F82AC196E3790F3F6B8D4F251E6934603DFCE34159EEBE64BA6D30BF1B58F213ECF55775A9FE4E17E67A4295D567DEDDEA81CD775014E4D503ACE722FF885DDE34CDA4944CF9E035586B3F2C5A00BFA26FD640CAF364D32FBBE37814F808C0D727D85DC444388BE6DD1181B952DE85D8F2EF4B147631CA55740A20FE7E4BDB5DCBB141C29D6DE17F0B67F42BF8C14F13E2B7E51234EBF26091627CB4E8F65D536CCC98A08121C770DDFEB41C08FEFDEEC559815732A586AB079D43343D8BF7706B7F86A48A6AFEF04F72DADB42FAD88FFE9A02183532758AE2309892E93F699C6C2B0AE17E7EA414BE39FCF3C9CF20275F408486815F7F47811B4561D094F10057C8D2F56C73BE80530B72E2C4F1D9C3E21E35EB5FC7FBEBD2F8C0CE722A3E010B39EFB3C62730C6C7FDCA0B310716E0B39312621147C1CE9FF21E80A8E696AA0283A6159D29B6CADDB903FAA63B0E067F87C66609D06DCCA80DEBB814AC211748D5C7C4"); + byte[] rnd = Hex.decode("934CEDC78C6F657E3BF6120E38EBB228"); + + SLHDSAParameters parameters = SLHDSAParameters.shake_128f; + + SLHDSAPrivateKeyParameters privParams = new SLHDSAPrivateKeyParameters(parameters, sk); + + // sign + InternalSLHDSASigner signer = new InternalSLHDSASigner(); + + signer.init(true, privParams); + byte[] sigGenerated = signer.internalGenerateSignature(message, rnd); + assertTrue(Arrays.areEqual(sigGenerated, signature)); + } + +// private static String[] splitOn(String input, char c) +// { +// String s = input.trim(); +// List l = new ArrayList(); +// +// int idx = s.indexOf(c); +// while (idx > 0) +// { +// l.add(s.substring(0, idx)); +// s = s.substring(idx + 1).trim(); +// idx = s.indexOf(c); +// } +// +// if (s.length() > 0) +// { +// l.add(s); +// } +// +// return (String[]) l.toArray(new String[0]); +// } + + private class InternalSLHDSASigner + extends SLHDSASigner + { + public byte[] internalGenerateSignature(byte[] message, byte[] optRand) + { + return super.internalGenerateSignature(message, optRand); + } + + public boolean internalVerifySignature(byte[] message, byte[] signature) + { + return super.internalVerifySignature(message, signature); + } + } +} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SNTRUPrimeTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SNTRUPrimeTest.java index f10d8dd235..865a5d460f 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SNTRUPrimeTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SNTRUPrimeTest.java @@ -37,7 +37,6 @@ public void testKEM() SNTRUPrimeParameters.sntrup1277 }; - TestSampler sampler = new TestSampler(); for (int i = 0; i != paramList.length; i++) { SNTRUPrimeParameters paramSpec = paramList[i]; @@ -46,6 +45,7 @@ public void testKEM() BufferedReader resourceReader = new BufferedReader(new InputStreamReader(resource)); String line; + TestSampler sampler = new TestSampler(); while ((line = resourceReader.readLine()) != null) { if (! line.startsWith("count")) diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SnovaTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SnovaTest.java new file mode 100644 index 0000000000..2800c307b5 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SnovaTest.java @@ -0,0 +1,175 @@ +package org.bouncycastle.pqc.crypto.test; + +import java.security.SecureRandom; + +import junit.framework.TestCase; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.pqc.crypto.MessageSigner; +import org.bouncycastle.pqc.crypto.snova.SnovaKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaKeyPairGenerator; +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPublicKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaSigner; + + +public class SnovaTest + extends TestCase +{ + public static void main(String[] args) + throws Exception + { + SnovaTest test = new SnovaTest(); + test.testTestVectors(); + } + + private static final SnovaParameters[] PARAMETER_SETS = new SnovaParameters[] + { + SnovaParameters.SNOVA_24_5_4_ESK, + SnovaParameters.SNOVA_24_5_4_SHAKE_ESK, + SnovaParameters.SNOVA_24_5_4_SHAKE_SSK, + SnovaParameters.SNOVA_24_5_4_SSK, + SnovaParameters.SNOVA_24_5_5_ESK, + SnovaParameters.SNOVA_24_5_5_SHAKE_ESK, + SnovaParameters.SNOVA_24_5_5_SHAKE_SSK, + SnovaParameters.SNOVA_24_5_5_SSK, + SnovaParameters.SNOVA_25_8_3_ESK, + SnovaParameters.SNOVA_25_8_3_SHAKE_ESK, + SnovaParameters.SNOVA_25_8_3_SHAKE_SSK, + SnovaParameters.SNOVA_25_8_3_SSK, + SnovaParameters.SNOVA_29_6_5_ESK, + SnovaParameters.SNOVA_29_6_5_SHAKE_ESK, + SnovaParameters.SNOVA_29_6_5_SHAKE_SSK, + SnovaParameters.SNOVA_29_6_5_SSK, + SnovaParameters.SNOVA_37_8_4_ESK, + SnovaParameters.SNOVA_37_8_4_SHAKE_ESK, + SnovaParameters.SNOVA_37_8_4_SHAKE_SSK, + SnovaParameters.SNOVA_37_8_4_SSK, + SnovaParameters.SNOVA_37_17_2_ESK, + SnovaParameters.SNOVA_37_17_2_SHAKE_ESK, + SnovaParameters.SNOVA_37_17_2_SHAKE_SSK, + SnovaParameters.SNOVA_37_17_2_SSK, + SnovaParameters.SNOVA_49_11_3_ESK, + SnovaParameters.SNOVA_49_11_3_SHAKE_ESK, + SnovaParameters.SNOVA_49_11_3_SHAKE_SSK, + SnovaParameters.SNOVA_49_11_3_SSK, + SnovaParameters.SNOVA_56_25_2_ESK, + SnovaParameters.SNOVA_56_25_2_SHAKE_ESK, + SnovaParameters.SNOVA_56_25_2_SHAKE_SSK, + SnovaParameters.SNOVA_56_25_2_SSK, + SnovaParameters.SNOVA_60_10_4_ESK, + SnovaParameters.SNOVA_60_10_4_SHAKE_ESK, + SnovaParameters.SNOVA_60_10_4_SHAKE_SSK, + SnovaParameters.SNOVA_60_10_4_SSK, + SnovaParameters.SNOVA_66_15_3_ESK, + SnovaParameters.SNOVA_66_15_3_SHAKE_ESK, + SnovaParameters.SNOVA_66_15_3_SHAKE_SSK, + SnovaParameters.SNOVA_66_15_3_SSK, + SnovaParameters.SNOVA_75_33_2_ESK, + SnovaParameters.SNOVA_75_33_2_SHAKE_ESK, + SnovaParameters.SNOVA_75_33_2_SHAKE_SSK, + SnovaParameters.SNOVA_75_33_2_SSK, + }; + + private static final String[] files = new String[]{ + "PQCsignKAT_SNOVA_24_5_4_ESK.rsp", + "PQCsignKAT_SNOVA_24_5_4_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_24_5_4_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_24_5_4_SSK.rsp", + "PQCsignKAT_SNOVA_24_5_5_ESK.rsp", + "PQCsignKAT_SNOVA_24_5_5_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_24_5_5_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_24_5_5_SSK.rsp", + "PQCsignKAT_SNOVA_25_8_3_ESK.rsp", + "PQCsignKAT_SNOVA_25_8_3_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_25_8_3_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_25_8_3_SSK.rsp", + "PQCsignKAT_SNOVA_29_6_5_ESK.rsp", + "PQCsignKAT_SNOVA_29_6_5_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_29_6_5_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_29_6_5_SSK.rsp", + "PQCsignKAT_SNOVA_37_8_4_ESK.rsp", + "PQCsignKAT_SNOVA_37_8_4_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_37_8_4_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_37_8_4_SSK.rsp", + "PQCsignKAT_SNOVA_37_17_2_ESK.rsp", + "PQCsignKAT_SNOVA_37_17_2_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_37_17_2_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_37_17_2_SSK.rsp", + "PQCsignKAT_SNOVA_49_11_3_ESK.rsp", + "PQCsignKAT_SNOVA_49_11_3_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_49_11_3_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_49_11_3_SSK.rsp", + "PQCsignKAT_SNOVA_56_25_2_ESK.rsp", + "PQCsignKAT_SNOVA_56_25_2_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_56_25_2_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_56_25_2_SSK.rsp", + "PQCsignKAT_SNOVA_60_10_4_ESK.rsp", + "PQCsignKAT_SNOVA_60_10_4_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_60_10_4_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_60_10_4_SSK.rsp", + "PQCsignKAT_SNOVA_66_15_3_ESK.rsp", + "PQCsignKAT_SNOVA_66_15_3_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_66_15_3_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_66_15_3_SSK.rsp", + "PQCsignKAT_SNOVA_75_33_2_ESK.rsp", + "PQCsignKAT_SNOVA_75_33_2_SHAKE_ESK.rsp", + "PQCsignKAT_SNOVA_75_33_2_SHAKE_SSK.rsp", + "PQCsignKAT_SNOVA_75_33_2_SSK.rsp", + }; + + + public void testTestVectors() + throws Exception + { + long start = System.currentTimeMillis(); + TestUtils.testTestVector(true, true, false, "pqc/crypto/snova", files, new TestUtils.KeyGenerationOperation() + { + @Override + public SecureRandom getSecureRandom(byte[] seed) + { + return new NISTSecureRandom(seed, null); + } + + @Override + public AsymmetricCipherKeyPairGenerator getAsymmetricCipherKeyPairGenerator(int fileIndex, SecureRandom random) + { + SnovaParameters parameters = PARAMETER_SETS[fileIndex]; + + SnovaKeyPairGenerator kpGen = new SnovaKeyPairGenerator(); + kpGen.init(new SnovaKeyGenerationParameters(random, parameters)); + return kpGen; + } + + @Override + public byte[] getPublicKeyEncoded(AsymmetricKeyParameter pubParams) + { + return ((SnovaPublicKeyParameters)pubParams).getEncoded(); + } + + @Override + public byte[] getPrivateKeyEncoded(CipherParameters privParams) + { + return ((SnovaPrivateKeyParameters)privParams).getEncoded(); + } + + @Override + public Signer getSigner() + { + return null; + } + + @Override + public MessageSigner getMessageSigner() + { + return new SnovaSigner(); + } + }); + long end = System.currentTimeMillis(); + System.out.println("time cost: " + (end - start) + "\n"); + } +} + diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SphincsPlusTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SphincsPlusTest.java index 4ad3b88542..5fea355d8f 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/SphincsPlusTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/SphincsPlusTest.java @@ -44,18 +44,18 @@ public void testVectors() " haraka-128s-simple.rsp haraka-256f-simple.rsp" + " haraka-192f-simple.rsp haraka-256s-simple.rsp"; - TestSampler sampler = new TestSampler(); - String[] fileList = splitOn(files, ' '); - //long startTime = System.currentTimeMillis(); + for (int i = 0; i != fileList.length; i++) { String name = fileList[i]; + InputStream src = TestResourceFinder.findTestResource("pqc/crypto/sphincs_plus", "subset_" + name); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); - // System.out.println(name); + String line = null; HashMap buf = new HashMap(); + TestSampler sampler = new TestSampler(); while ((line = bin.readLine()) != null) { line = line.trim(); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestSampler.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestSampler.java index 054663747f..75ff701b15 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestSampler.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestSampler.java @@ -20,12 +20,16 @@ class TestSampler boolean skipTest(String count) { - int c = Integer.parseInt(count); - return !isFull && c != 0 && ((c + offSet) % 9 != 0); + return !isFull && shouldSkip(Integer.parseInt(count)); } boolean skipTest(int count) { - return !isFull && count != 0 && ((count + offSet) % 9 != 0); + return !isFull && shouldSkip(count); + } + + private boolean shouldSkip(int count) + { + return count != 0 && ((count + offSet) % 9 != 0); } } diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestUtils.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestUtils.java new file mode 100644 index 0000000000..32072717f1 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/TestUtils.java @@ -0,0 +1,156 @@ +package org.bouncycastle.pqc.crypto.test; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.SecureRandom; +import java.util.HashMap; + +import junit.framework.Assert; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.MessageSigner; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; + +class TestUtils +{ + static boolean parseBoolean(String value) + { + return "true".equalsIgnoreCase(value); + } + + public interface KeyGenerationOperation + { + SecureRandom getSecureRandom(byte[] seed); + + AsymmetricCipherKeyPairGenerator getAsymmetricCipherKeyPairGenerator(int fileIndex, SecureRandom random); + + byte[] getPublicKeyEncoded(AsymmetricKeyParameter pubParams); + + byte[] getPrivateKeyEncoded(CipherParameters privParams); + + Signer getSigner(); + + MessageSigner getMessageSigner(); + } + + public static void testTestVector(boolean sampleOnly, boolean enableFactory, boolean isSigner, String homeDir, String[] files, KeyGenerationOperation operation) + throws Exception + { + for (int fileIndex = 0; fileIndex != files.length; fileIndex++) + { + String name = files[fileIndex]; + + InputStream src = TestResourceFinder.findTestResource(homeDir, name); + BufferedReader bin = new BufferedReader(new InputStreamReader(src)); + + String line; + HashMap buf = new HashMap(); + TestSampler sampler = sampleOnly ? new TestSampler() : null; + while ((line = bin.readLine()) != null) + { + line = line.trim(); + + if (line.startsWith("#")) + { + continue; + } + if (line.length() == 0) + { + if (buf.size() > 0) + { + String count = (String)buf.get("count"); + if (sampler != null && sampler.skipTest(count)) + { + continue; + } + + byte[] seed = Hex.decode((String)buf.get("seed")); + byte[] pk = Hex.decode((String)buf.get("pk")); + byte[] sk = Hex.decode((String)buf.get("sk")); + byte[] message = Hex.decode((String)buf.get("msg")); + byte[] signature = Hex.decode((String)buf.get("sm")); + + SecureRandom random = operation.getSecureRandom(seed); + + AsymmetricCipherKeyPairGenerator kpGen = operation.getAsymmetricCipherKeyPairGenerator(fileIndex, random); + + // + // Generate keys and test. + // + AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); + AsymmetricKeyParameter pubParams; + CipherParameters privParams; + if (enableFactory) + { + pubParams = PublicKeyFactory.createKey( + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(kp.getPublic())); + privParams = PrivateKeyFactory.createKey( + PrivateKeyInfoFactory.createPrivateKeyInfo(kp.getPrivate())); + } + else + { + pubParams = kp.getPublic(); + privParams = kp.getPrivate(); + } + + Assert.assertTrue(name + ": public key", Arrays.areEqual(pk, operation.getPublicKeyEncoded(pubParams))); + Assert.assertTrue(name + ": secret key", Arrays.areEqual(sk, operation.getPrivateKeyEncoded(privParams))); + + byte[] sigGenerated; + privParams = new ParametersWithRandom(privParams, random); + if (isSigner) + { + Signer signer = operation.getSigner(); + signer.init(true, privParams); + signer.update(message, 0, message.length); + sigGenerated = signer.generateSignature(); + } + else + { + MessageSigner signer = operation.getMessageSigner(); + signer.init(true, privParams); + sigGenerated = signer.generateSignature(message); + } + + Assert.assertTrue(Arrays.areEqual(sigGenerated, signature)); + + if (isSigner) + { + Signer signer = operation.getSigner(); + signer.init(false, pubParams); + signer.update(message, 0, message.length); + Assert.assertTrue(signer.verifySignature(sigGenerated)); + } + else + { + MessageSigner signer = operation.getMessageSigner(); + signer.init(false, pubParams); + Assert.assertTrue(signer.verifySignature(message, sigGenerated)); + } + System.out.println("Count " + count + " pass"); + } + buf.clear(); + continue; + } + + int a = line.indexOf("="); + if (a > -1) + { + buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim()); + } + } + } + } +} diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/XMSSPrivateKeyTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/XMSSPrivateKeyTest.java index 7118bada5e..5f18de9089 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/XMSSPrivateKeyTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/XMSSPrivateKeyTest.java @@ -4,7 +4,6 @@ import junit.framework.TestCase; import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.Xof; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.digests.SHAKEDigest; diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/XWingTest.java b/core/src/test/java/org/bouncycastle/pqc/crypto/test/XWingTest.java index 60c287322f..a65a316210 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/XWingTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/crypto/test/XWingTest.java @@ -1,5 +1,7 @@ package org.bouncycastle.pqc.crypto.test; +import java.security.SecureRandom; + import junit.framework.TestCase; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.SecretWithEncapsulation; @@ -16,70 +18,261 @@ public class XWingTest extends TestCase { - public void testKEM() + public static void main(String[] args) throws Exception { - String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; - String expectedSecret = "e5015e7e9b71e3a0436b159a042b14cb5b63435eee3b8db95f1e8fcce44632a8"; - - byte[] seed = Hex.decode(temp); - - NISTSecureRandom random = new NISTSecureRandom(seed, null); - - byte[] coins = new byte[96]; - random.nextBytes(coins); - - XWingKeyPairGenerator keyGen = new XWingKeyPairGenerator(); - - keyGen.init(new XWingKeyGenerationParameters(new FixedSecureRandom(coins))); - - AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); - - XWingKEMGenerator kemGen = new XWingKEMGenerator(random); - - SecretWithEncapsulation secretEncap = kemGen.generateEncapsulated(keyPair.getPublic()); - - byte[] sharedSecret = secretEncap.getSecret(); + XWingTest test = new XWingTest(); + test.testKEM(); + } - assertTrue(Arrays.areEqual(Hex.decode(expectedSecret), sharedSecret)); + static byte[] seed1 = Hex.decode("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26"); + static byte[] eseed1 = Hex.decode("3cb1eea988004b93103cfb0aeefd2a686e01fa4a58e8a3639ca8a1e3f9ae57e235b8cc87\n" + + " 3c23dc62b8d260169afa2f75ab916a58d974918835d25e6a435085b2"); + static byte[] pubEnc1 = Hex.decode("e2236b35a8c24b39b10aa1323a96a919a2ced88400633a7b07131713fc14b2b5b19cfc3d\n" + + " a5fa1a92c49f25513e0fd30d6b1611c9ab9635d7086727a4b7d21d34244e66969cf15b3b\n" + + " 2a785329f61b096b277ea037383479a6b556de7231fe4b7fa9c9ac24c0699a0018a52534\n" + + " 01bacfa905ca816573e56a2d2e067e9b7287533ba13a937dedb31fa44baced4076992361\n" + + " 0034ae31e619a170245199b3c5c39864859fe1b4c9717a07c30495bdfb98a0a002ccf56c\n" + + " 1286cef5041dede3c44cf16bf562c7448518026b3d8b9940680abd38a1575fd27b58da06\n" + + " 3bfac32c39c30869374c05c1aeb1898b6b303cc68be455346ee0af699636224a148ca2ae\n" + + " a10463111c709f69b69c70ce8538746698c4c60a9aef0030c7924ceec42a5d36816f545e\n" + + " ae13293460b3acb37ea0e13d70e4aa78686da398a8397c08eaf96882113fe4f7bad4da40\n" + + " b0501e1c753efe73053c87014e8661c33099afe8bede414a5b1aa27d8392b3e131e9a70c\n" + + " 1055878240cad0f40d5fe3cdf85236ead97e2a97448363b2808caafd516cd25052c5c362\n" + + " 543c2517e4acd0e60ec07163009b6425fc32277acee71c24bab53ed9f29e74c66a0a3564\n" + + " 955998d76b96a9a8b50d1635a4d7a67eb42df5644d330457293a8042f53cc7a69288f17e\n" + + " d55827e82b28e82665a86a14fbd96645eca8172c044f83bc0d8c0b4c8626985631ca87af\n" + + " 829068f1358963cb333664ca482763ba3b3bb208577f9ba6ac62c25f76592743b64be519\n" + + " 317714cb4102cb7b2f9a25b2b4f0615de31decd9ca55026d6da0b65111b16fe52feed8a4\n" + + " 87e144462a6dba93728f500b6ffc49e515569ef25fed17aff520507368253525860f58be\n" + + " 3be61c964604a6ac814e6935596402a520a4670b3d284318866593d15a4bb01c35e3e587\n" + + " ee0c67d2880d6f2407fb7a70712b838deb96c5d7bf2b44bcf6038ccbe33fbcf51a54a584\n" + + " fe90083c91c7a6d43d4fb15f48c60c2fd66e0a8aad4ad64e5c42bb8877c0ebec2b5e387c\n" + + " 8a988fdc23beb9e16c8757781e0a1499c61e138c21f216c29d076979871caa6942bafc09\n" + + " 0544bee99b54b16cb9a9a364d6246d9f42cce53c66b59c45c8f9ae9299a75d15180c3c95\n" + + " 2151a91b7a10772429dc4cbae6fcc622fa8018c63439f890630b9928db6bb7f9438ae406\n" + + " 5ed34d73d486f3f52f90f0807dc88dfdd8c728e954f1ac35c06c000ce41a0582580e3bb5\n" + + " 7b672972890ac5e7988e7850657116f1b57d0809aaedec0bede1ae148148311c6f7e3173\n" + + " 46e5189fb8cd635b986f8c0bdd27641c584b778b3a911a80be1c9692ab8e1bbb12839573\n" + + " cce19df183b45835bbb55052f9fc66a1678ef2a36dea78411e6c8d60501b4e60592d1369\n" + + " 8a943b509185db912e2ea10be06171236b327c71716094c964a68b03377f513a05bcd99c\n" + + " 1f346583bb052977a10a12adfc758034e5617da4c1276585e5774e1f3b9978b09d0e9c44\n" + + " d3bc86151c43aad185712717340223ac381d21150a04294e97bb13bbda21b5a182b6da96\n" + + " 9e19a7fd072737fa8e880a53c2428e3d049b7d2197405296ddb361912a7bcf4827ced611\n" + + " d0c7a7da104dde4322095339f64a61d5bb108ff0bf4d780cae509fb22c256914193ff734\n" + + " 9042581237d522828824ee3bdfd07fb03f1f942d2ea179fe722f06cc03de5b69859edb06\n" + + " eff389b27dce59844570216223593d4ba32d9abac8cd049040ef6534"); + static byte[] privEnc1 = Hex.decode("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26"); + static byte[] ss1 = Hex.decode("d2df0522128f09dd8e2c92b1e905c793d8f57a54c3da25861f10bf4ca613e384"); + static byte[] ct1 = Hex.decode("b83aa828d4d62b9a83ceffe1d3d3bb1ef31264643c070c5798927e41fb07914a273f8f96\n" + + " e7826cd5375a283d7da885304c5de0516a0f0654243dc5b97f8bfeb831f68251219aabdd\n" + + " 723bc6512041acbaef8af44265524942b902e68ffd23221cda70b1b55d776a92d1143ea3\n" + + " a0c475f63ee6890157c7116dae3f62bf72f60acd2bb8cc31ce2ba0de364f52b8ed38c79d\n" + + " 719715963a5dd3842d8e8b43ab704e4759b5327bf027c63c8fa857c4908d5a8a7b88ac7f\n" + + " 2be394d93c3706ddd4e698cc6ce370101f4d0213254238b4a2e8821b6e414a1cf20f6c12\n" + + " 44b699046f5a01caa0a1a55516300b40d2048c77cc73afba79afeea9d2c0118bdf2adb88\n" + + " 70dc328c5516cc45b1a2058141039e2c90a110a9e16b318dfb53bd49a126d6b73f215787\n" + + " 517b8917cc01cabd107d06859854ee8b4f9861c226d3764c87339ab16c3667d2f49384e5\n" + + " 5456dd40414b70a6af841585f4c90c68725d57704ee8ee7ce6e2f9be582dbee985e038ff\n" + + " c346ebfb4e22158b6c84374a9ab4a44e1f91de5aac5197f89bc5e5442f51f9a5937b102b\n" + + " a3beaebf6e1c58380a4a5fedce4a4e5026f88f528f59ffd2db41752b3a3d90efabe46389\n" + + " 9b7d40870c530c8841e8712b733668ed033adbfafb2d49d37a44d4064e5863eb0af0a08d\n" + + " 47b3cc888373bc05f7a33b841bc2587c57eb69554e8a3767b7506917b6b70498727f16ea\n" + + " c1a36ec8d8cfaf751549f2277db277e8a55a9a5106b23a0206b4721fa9b3048552c5bd5b\n" + + " 594d6e247f38c18c591aea7f56249c72ce7b117afcc3a8621582f9cf71787e183dee0936\n" + + " 7976e98409ad9217a497df888042384d7707a6b78f5f7fb8409e3b535175373461b77600\n" + + " 2d799cbad62860be70573ecbe13b246e0da7e93a52168e0fb6a9756b895ef7f0147a0dc8\n" + + " 1bfa644b088a9228160c0f9acf1379a2941cd28c06ebc80e44e17aa2f8177010afd78a97\n" + + " ce0868d1629ebb294c5151812c583daeb88685220f4da9118112e07041fcc24d5564a99f\n" + + " dbde28869fe0722387d7a9a4d16e1cc8555917e09944aa5ebaaaec2cf62693afad42a3f5\n" + + " 18fce67d273cc6c9fb5472b380e8573ec7de06a3ba2fd5f931d725b493026cb0acbd3fe6\n" + + " 2d00e4c790d965d7a03a3c0b4222ba8c2a9a16e2ac658f572ae0e746eafc4feba023576f\n" + + " 08942278a041fb82a70a595d5bacbf297ce2029898a71e5c3b0d1c6228b485b1ade509b3\n" + + " 5fbca7eca97b2132e7cb6bc465375146b7dceac969308ac0c2ac89e7863eb8943015b243\n" + + " 14cafb9c7c0e85fe543d56658c213632599efabfc1ec49dd8c88547bb2cc40c9d38cbd30\n" + + " 99b4547840560531d0188cd1e9c23a0ebee0a03d5577d66b1d2bcb4baaf21cc7fef1e038\n" + + " 06ca96299df0dfbc56e1b2b43e4fc20c37f834c4af62127e7dae86c3c25a2f696ac8b589\n" + + " dec71d595bfbe94b5ed4bc07d800b330796fda89edb77be0294136139354eb8cd3759157\n" + + " 8f9c600dd9be8ec6219fdd507adf3397ed4d68707b8d13b24ce4cd8fb22851bfe9d63240\n" + + " 7f31ed6f7cb1600de56f17576740ce2a32fc5145030145cfb97e63e0e41d354274a079d3\n" + + " e6fb2e15"); - XWingKEMExtractor kemExtract = new XWingKEMExtractor((XWingPrivateKeyParameters)keyPair.getPrivate()); + static byte[] seed2 = Hex.decode("badfd6dfaac359a5efbb7bcc4b59d538df9a04302e10c8bc1cbf1a0b3a5120ea"); + static byte[] eseed2 = Hex.decode("17cda7cfad765f5623474d368ccca8af0007cd9f5e4c849f167a580b14aabdefaee7eef4\n" + + " 7cb0fca9767be1fda69419dfb927e9df07348b196691abaeb580b32d"); + static byte[] pubEnc2 = Hex.decode("0333285fa253661508c9fb444852caa4061636cb060e69943b431400134ae1fbc0228724\n" + + " 7cb38068bbb89e6714af10a3fcda6613acc4b5e4b0d6eb960c302a0253b1f507b596f088\n" + + " 4d351da89b01c35543214c8e542390b2bc497967961ef10286879c34316e6483b644fc27\n" + + " e8019d73024ba1d1cc83650bb068a5431b33d1221b3d122dc1239010a55cb13782140893\n" + + " f30aca7c09380255a0c621602ffbb6a9db064c1406d12723ab3bbe2950a21fe521b160b3\n" + + " 0b16724cc359754b4c88342651333ea9412d5137791cf75558ebc5c54c520dd6c622a059\n" + + " f6b332ccebb9f24103e59a297cd69e4a48a3bfe53a5958559e840db5c023f66c10ce2308\n" + + " 1c2c8261d744799ba078285cfa71ac51f44708d0a6212c3993340724b3ac38f63e82a889\n" + + " a4fc581f6b8353cc6233ac8f5394b6cca292f892360570a3031c90c4da3f02a895677390\n" + + " e60c24684a405f69ccf1a7b95312a47c844a4f9c2c4a37696dc10072a87bf41a2717d45b\n" + + " 2a99ce09a4898d5a3f6b67085f9a626646bcf369982d483972b9cd7d244c4f49970f766a\n" + + " 22507925eca7df99a491d80c27723e84c7b49b633a46b46785a16a41e02c538251622117\n" + + " 364615d9c2cdaa1687a860c18bfc9ce8690efb2a524cb97cdfd1a4ea661fa7d08817998a\n" + + " f838679b07c9db8455e2167a67c14d6a347522e89e8971270bec858364b1c1023b82c483\n" + + " cf8a8b76f040fe41c24dec2d49f6376170660605b80383391c4abad1136d874a77ef73b4\n" + + " 40758b6e7059add20873192e6e372e069c22c5425188e5c240cb3a6e29197ad17e87ec41\n" + + " a813af68531f262a6db25bbdb8a15d2ed9c9f35b9f2063890bd26ef09426f225aa1e6008\n" + + " d31600a29bcdf3b10d0bc72788d35e25f4976b3ca6ac7cbf0b442ae399b225d9714d0638\n" + + " a864bda7018d3b7c793bd2ace6ac68f4284d10977cc029cf203c5698f15a06b162d6c8b4\n" + + " fd40c6af40824f9c6101bb94e9327869ab7efd835dfc805367160d6c8571e3643ac70cba\n" + + " d5b96a1ad99352793f5af71705f95126cb4787392e94d808491a2245064ba5a7a30c0663\n" + + " 01392a6c315336e10dbc9c2177c7af382765b6c88eeab51588d01d6a95747f3652dc5b5c\n" + + " 401a23863c7a0343737c737c99287a40a90896d4594730b552b910d23244684206f0eb84\n" + + " 2fb9aa316ab182282a75fb72b6806cea4774b822169c386a58773c3edc8229d85905abb8\n" + + " 7ac228f0f7a2ce9a497bb5325e17a6a82777a997c036c3b862d29c14682ad325a9600872\n" + + " f3913029a1588648ba590a7157809ff740b5138380015c40e9fb90f0311107946f28e596\n" + + " 2e21666ad65092a3a60480cd16e61ff7fb5b44b70cf12201878428ef8067fceb1e1dcb49\n" + + " d66c773d312c7e53238cb620e126187009472d41036b702032411dc96cb750631df9d994\n" + + " 52e495deb4300df660c8d35f32b424e98c7ed14b12d8ab11a289ac63c50a24d52925950e\n" + + " 49ba6bf4c2c38953c92d60b6cd034e575c711ac41bfa66951f62b9392828d7b45aed377a\n" + + " c69c35f1c6b80f388f34e0bb9ce8167eb2bc630382825c396a407e905108081b444ac8a0\n" + + " 7c2507376a750d18248ee0a81c4318d9a38fc44c3b41e8681f87c34138442659512c4127\n" + + " 6e1cc8fc4eb66e12727bcb5a9e0e405cdea21538d6ea885ab169050e6b91e1b69f7ed34b\n" + + " cbb48fd4c562a576549f85b528c953926d96ea8a160b8843f1c89c62"); + static byte[] privEnc2 = Hex.decode("badfd6dfaac359a5efbb7bcc4b59d538df9a04302e10c8bc1cbf1a0b3a5120ea"); + static byte[] ss2 = Hex.decode("f2e86241c64d60f6649fbc6c5b7d17180b780a3f34355e64a85749949c45f150"); + static byte[] ct2 = Hex.decode("c93beb22326705699bbc3d1d0aa6339be7a405debe61a7c337e1a91453c097a6f77c1306\n" + + " 39d1aaeb193175f1a987aa1fd789a63c9cd487ebd6965f5d8389c8d7c8cfacbba4b44d2f\n" + + " be0ae84de9e96fb11215d9b76acd51887b752329c1a3e0468ccc49392c1e0f1aad61a73c\n" + + " 10831e60a9798cb2e7ec07596b5803db3e243ecbb94166feade0c9197378700f8eb65a43\n" + + " 502bbac4605992e2de2b906ab30ba401d7e1ff3c98f42cfc4b30b974d3316f331461ac05\n" + + " f43e0db7b41d3da702a4f567b6ee7295199c7be92f6b4a47e7307d34278e03c872fb4864\n" + + " 7c446a64a3937dccd7c6d8de4d34b9dea45a0b065ef15b9e94d1b6df6dca7174d9bc9d14\n" + + " c6225e3a78a58785c3fe4e2fe6a0706f3365389e4258fbb61ecf1a1957715982b3f18444\n" + + " 24e03acd83da7eee50573f6cd3ff396841e9a00ad679da92274129da277833d0524674fe\n" + + " ea09a98d25b888616f338412d8e65e151e65736c8c6fb448c9260fa20e7b2712148bcd3a\n" + + " 0853865f50c1fc9e4f201aee3757120e034fd509d954b7a749ff776561382c4cb64cebcb\n" + + " b6aa82d04cd5c2b40395ecaf231bde8334ecfd955d09efa8c6e7935b1cb0298fb8b6740b\n" + + " e4593360eed5f129d59d98822a6cea37c57674e919e84d6b90f695fca58e7d29092bd70f\n" + + " 7c97c6dfb021b9f87216a6271d8b144a364d03b6bf084f972dc59800b14a2c008bbd0992\n" + + " b5b82801020978f2bdddb3ca3367d876cffb3548dab695a29882cae2eb5ba7c847c3c71b\n" + + " d0150fa9c33aac8e6240e0c269b8e295ddb7b77e9c17bd310be65e28c0802136d086777b\n" + + " e5652d6f1ac879d3263e9c712d1af736eac048fe848a577d6afaea1428dc71db8c430edd\n" + + " 7b584ae6e6aeaf7257aff0fd8fe25c30840e30ccfa1d95118ef0f6657367e9070f3d97a2\n" + + " e9a7bae19957bd707b00e31b6b0ebb9d7df4bd22e44c060830a194b5b8288353255b5295\n" + + " 4ff5905ab2b126d9aa049e44599368c27d6cb033eae5182c2e1504ee4e3745f51488997b\n" + + " 8f958f0209064f6f44a7e4de5226d5594d1ad9b42ac59a2d100a2f190df873a2e141552f\n" + + " 33c923b4c927e8747c6f830c441a8bd3c5b371f6b3ab8103ebcfb18543aefc1beb6f776b\n" + + " bfd5344779f4aa23daaf395f69ec31dc046b491f0e5cc9c651dfc306bd8f2105be7bc7a4\n" + + " f4e21957f87278c771528a8740a92e2daefa76a3525f1fae17ec4362a2700988001d8600\n" + + " 11d6ca3a95f79a0205bcf634cef373a8ea273ff0f4250eb8617d0fb92102a6aa09cf0c3e\n" + + " e2cad1ad96438c8e4dfd6ee0fcc85833c3103dd6c1600cd305bc2df4cda89b55ca237a3f\n" + + " 9c3f82390074ff30825fc750130ebaf13d0cf7556d2c52a98a4bad39ca5d44aaadeaef77\n" + + " 5c695e64d06e966acfcd552a14e2df6c63ae541f0fa88fc48263089685704506a21a0385\n" + + " 6ce65d4f06d54f3157eeabd62491cb4ac7bf029e79f9fbd4c77e2a3588790c710e611da8\n" + + " b2040c76a61507a8020758dcc30894ad018fef98e401cc54106e20d94bd544a8f0e1fd05\n" + + " 00342d123f618aa8c91bdf6e0e03200693c9651e469aee6f91c98bea4127ae66312f4ae3\n" + + " ea155b67"); - byte[] decryptedSharedSecret = kemExtract.extractSecret(secretEncap.getEncapsulation()); + static byte[] seed3 = Hex.decode("ef58538b8d23f87732ea63b02b4fa0f4873360e2841928cd60dd4cee8cc0d4c9"); + static byte[] eseed3 = Hex.decode("22a96188d032675c8ac850933c7aff1533b94c834adbb69c6115bad4692d8619f90b0cdf\n" + + " 8a7b9c264029ac185b70b83f2801f2f4b3f70c593ea3aeeb613a7f1b"); + static byte[] pubEnc3 = Hex.decode("36244278824f77c621c660892c1c3886a9560caa52a97c461fd3958a598e749bbc8c7798\n" + + " ac8870bac7318ac2b863000ca3b0bdcbbc1ccfcb1a30875df9a76976763247083e646ccb\n" + + " 2499a4e4f0c9f4125378ba3da1999538b86f99f2328332c177d1192b849413e655101289\n" + + " 73f679d23253850bb6c347ba7ca81b5e6ac4c574565c731740b3cd8c9756caac39fba7ac\n" + + " 422acc60c6c1a645b94e3b6d21485ebad9c4fe5bb4ea0853670c5246652bff65ce8381cb\n" + + " 473c40c1a0cd06b54dcec11872b351397c0eaf995bebdb6573000cbe2496600ba76c8cb0\n" + + " 23ec260f0571e3ec12a9c82d9db3c57b3a99e8701f78db4fabc1cc58b1bae02745073a81\n" + + " fc8045439ba3b885581a283a1ba64e103610aabb4ddfe9959e7241011b2638b56ba6a982\n" + + " ef610c514a57212555db9a98fb6bcf0e91660ec15dfa66a67408596e9ccb97489a09a073\n" + + " ffd1a0a7ebbe71aa5ff793cb91964160703b4b6c9c5390842c2c905d4a9f88111fed5787\n" + + " 4ba9b03cf611e70486edf539767c7485189d5f1b08e32a274dc24a39c918fd2a4dfa946a\n" + + " 8c897486f2c974031b2804aabc81749db430b85311372a3b8478868200b40e043f7bf4a1\n" + + " c3a08b0771b431e342ee277410bca034a0c77086c8f702b3aed2b4108bbd3af471633373\n" + + " a1ac74b128b148d1b9412aa66948cac6dc6614681fda02ca86675d2a756003c49c50f06e\n" + + " 13c63ce4bc9f321c860b202ee931834930011f485c9af86b9f642f0c353ad305c66996b9\n" + + " a136b753973929495f0d8048db75529edcb4935904797ac66605490f66329c3bb36b8573\n" + + " a3e00f817b3082162ff106674d11b261baae0506cde7e69fdce93c6c7b59b9d4c759758a\n" + + " cf287c2e4c4bfab5170a9236daf21bdb6005e92464ee8863f845cf37978ef19969264a51\n" + + " 6fe992c93b5f7ae7cb6718ac69257d630379e4aac6029cb906f98d91c92d118c36a6d161\n" + + " 15d4c8f16066078badd161a65ba51e0252bc358c67cd2c4beab2537e42956e08a39cfccf\n" + + " 0cd875b5499ee952c83a162c68084f6d35cf92f71ec66baec74ab87e2243160b64df54af\n" + + " b5a07f78ec0f5c5759e5a4322bca2643425748a1a97c62108510c44fd9089c5a7c14e57b\n" + + " 1b77532800013027cff91922d7c935b4202bb507aa47598a6a5a030117210d4c49c17470\n" + + " 0550ad6f82ad40e965598b86bc575448eb19d70380d465c1f870824c026d74a2522a799b\n" + + " 7b122d06c83aa64c0974635897261433914fdfb14106c230425a83dc8467ad8234f086c7\n" + + " 2a47418be9cfb582b1dcfa3d9aa45299b79fff265356d8286a1ca2f3c2184b2a70d15289\n" + + " e5b202d03b64c735a867b1154c55533ff61d6c296277011848143bc85a4b823040ae025a\n" + + " 29293ab77747d85310078682e0ba0ac236548d905a79494324574d417c7a3457bd5fb525\n" + + " 3c4876679034ae844d0d05010fec722db5621e3a67a2d58e2ff33b432269169b51f9dcc0\n" + + " 95b8406dc1864cf0aeb6a2132661a38d641877594b3c51892b9364d25c63d637140a2018\n" + + " d10931b0daa5a2f2a405017688c991e586b522f94b1132bc7e87a63246475816c8be9c62\n" + + " b731691ab912eb656ce2619225663364701a014b7d0337212caa2ecc731f34438289e0ca\n" + + " 4590a276802d980056b5d0d316cae2ecfea6d86696a9f161aa90ad47eaad8cadd31ae3cb\n" + + " c1c013747dfee80fb35b5299f555dcc2b787ea4f6f16ffdf66952461"); + static byte[] privEnc3 = Hex.decode("ef58538b8d23f87732ea63b02b4fa0f4873360e2841928cd60dd4cee8cc0d4c9"); + static byte[] ss3 = Hex.decode("953f7f4e8c5b5049bdc771d1dffada0dd961477d1a2ae0988baa7ea6898d893f"); + static byte[] ct3 = Hex.decode("0d2e38cbf17a2e2e4e0c87a94ca1e7701ae1552e02509b3b00f9c82c39e3fd435b05b912\n" + + " 75f47abc9f1021429a26a346598cd6cd9efdc8adc1dbc35036d0290bf89733c835309202\n" + + " 232f9bf652ea82f3d49280d6e8a3bd3135fb883445ab5b074d949c5350c7c7d6ac59905b\n" + + " dbfce6639da8a9d4b390ecc1dd05522d2956f2d37a05593996e5cb3fd8d5a9eb52417732\n" + + " e1ebf545588713b4760227115aab7ada178dadbca583b26cfedba2888a0c95b950bf07f7\n" + + " 50d7aa8103798aa3470a042c0105c6a037de2f9ebc396021b2ba2c16aba696fbac3454dc\n" + + " 8e053b8fa55edd45215eeb57a1eab9106fb426b375a9b9e5c3419efc7610977e72640f9f\n" + + " d1b2ec337de33c35e5a7581b2aae4d8ee86d2e0ebf82a1350714de50d2d788687878a196\n" + + " 44ae4e3175e8d59dc90171b3badeff65aeaf600e5e5483a3595fdeb40cbafcbd040c29a2\n" + + " f6900533ae999d24f54dfcef748c30313ca447cdddfa57ad78eaa890e90f3f7bf8d11696\n" + + " 8a5713cc75fd0408f36364fa265c5617039304eaeac4cbee6fc49b9fe2276768cdbec2d7\n" + + " 3a507b543cc028dc1b154b7c2b0412254c466a94a8d6ea3a47e1743469bd45c08f54cf96\n" + + " 5884be3696e961741ede16e3b1bc4feb93faaef31d911dc0cb3fa90bcda991959a9d2cbc\n" + + " 817a5564c5c01177a59e9577589ea344d60cf5b0aa39f31863febd54603ca87ad2363c76\n" + + " 6642a3f52557bcd9e4c05a87665842ba336b83156a677030f0bad531a8387a1486a599ca\n" + + " a748fcea7bdc1eb63f3cdb97173551ab7c1c36b69acbbdb2ff7a1e7bc70439632ddc67b9\n" + + " 7f3da1f59b3c1588515957cb8a2f86ab635ce0a78b7cdf24eac3445e8fc8b79ba04da9e9\n" + + " 03f49a7d912c197a84b4cfabc779b97d24788419bcf58035db99717edb9fd1c1df8c4005\n" + + " f700eabba528ddfcbaeda6dd30754f795948a34c9319ab653524b19931c7900c4167988a\n" + + " f52292fe902e746b524d20ceffb4339e8f5535f41cf35f0f8ea8b4a7b949c5d2381116b1\n" + + " 46e9b913a83a3fa1c65ff9468c835fe4114554a6c66a80e1c9a6bb064b380be3c95e5595\n" + + " ec979bf1c85aa938938e3f10e72b0c87811969e8ab0d83de0b0604c4016ac3a015e19514\n" + + " 089271bdc6ebf2ec56fab6018e44de749b4c36cc235e370da8466dbdc253542a2d704eb3\n" + + " 316fd70d5d238cb7eaaf05966d973f62c7ef43b9a806f4ed213ac8099ea15d61a9024441\n" + + " 60883f6bf441a3e1469945c9b79489ea18390f1ebc83caca10bdb8f2429877b52bd44c94\n" + + " a228ef91c392ef5398c5c83982701318ccedab92f7a279c4fddebaa7fe5e986c48b7d813\n" + + " 5b3fe4cd15be2004ce73ff86b1e55f8ecd6ba5b8114315f8e716ef3ab0a64564a4644651\n" + + " 166ebd68b1f783e2e443dbccadfe189368647629f1a12215840b7f1d026de2f665c2eb02\n" + + " 3ff51a6df160912811ee03444ae4227fb941dc9ec4f31b445006fd384de5e60e0a5061b5\n" + + " 0cb1202f863090fc05eb814e2d42a03586c0b56f533847ac7b8184ce9690bc8dece32a88\n" + + " ca934f541d4cc520fa64de6b6e1c3c8e03db5971a445992227c825590688d203523f5271\n" + + " 61137334"); - assertTrue(Arrays.areEqual(Hex.decode(expectedSecret), decryptedSharedSecret)); + public void testKEM() + { + kemTest(seed1, eseed1, pubEnc1, privEnc1, ss1, ct1); + kemTest(seed2, eseed2, pubEnc2, privEnc2, ss2, ct2); + kemTest(seed3, eseed3, pubEnc3, privEnc3, ss3, ct3); } - public void testKeyEncoding() - throws Exception + private void kemTest(byte[] seed, byte[] eseed, byte[] pubEnc, byte[] privEnc, byte[] ss, byte[] ct) { - byte[] pubEnc = Hex.decode("a72c2d9c843ee9f8313ecc7f86d6294d59159d9a879a542e260922adf999051cc45200c9ffdb60449c49465979272367c083a7d6267a3ed7a7fd47957c219327f7ca73a4007e1627f00b11cc80573c15aee6640fb8562dfa6b240ca0ad351ac4ac155b96c14c8ab13dd262cdfd51c4bb5572fd616553d17bdd430acbea3e95f0b698d66990ab51e5d03783a8b3d278a5720454cf9695cfdca08485ba099c51cd92a7ea7587c1d15c28e609a81852601b0604010679aa482d51261ec36e36b8719676217fd74c54786488f4b4969c05a8ba27ca3a77cce73b965923ca554e422b9b61f4754641608ac16c9b8587a32c1c5dd788f88b36b717a46965635deb67f45b129b99070909c93eb80b42c2b3f3f70343a7cf37e8520e7bcfc416aca4f18c7981262ba2bfc756ae03278f0ec66dc2057696824ba6769865a601d7148ef6f54e5af5686aa2906f994ce38a5e0b938f239007003022c03392df3401b1e4a3a7ebc6161449f73374c8b0140369343d9295fdf511845c4a46ebaab6ca5492f6800b98c0cc803653a4b1d6e6aaed1932bacc5fefaa818ba502859ba5494c5f5402c8536a9c4c1888150617f80098f6b2a99c39bc5dc7cf3b5900a21329ab59053abaa64ed163e859a8b3b3ca3359b750ccc3e710c7ac43c8191cb5d68870c06391c0cb8aec72b897ac6be7fbaacc676ed66314c83630e89448c88a1df04aceb23abf2e409ef333c622289c18a2134e650c45257e47475fa33aa537a5a8f7680214716c50d470e3284963ca64f54677aec54b5272162bf52bc8142e1d4183fc017454a6b5a496831759064024745978cbd51a6cedc8955de4cc6d363670a47466e82be5c23603a17bf22acdb7cc984af08c87e14e27753cf587a8ec3447e62c649e887a67c36c9ce98721b697213275646b194f36758673a8ed11284455afc7a8529f69c97a3c2d7b8c636c0ba55614b768e624e712930f776169b01715725351bc74b47395ed52b25a1313c95164814c34c979cbdfab85954662cab485e75087a98cc74bb82ca2d1b5bf2803238480638c40e90b43c7460e7aa917f010151fab1169987b372abb59271f7006c24e60236b84b9ddd600623704254617fb498d89e58b0368bcb2103e79353eb587860c1422e476162e425bc2381db82c6592737e1dd602864b0167a71ec1f223305c02fe25052af2b3b5a55a0d7a2022d9a798dc0c5874a98702aaf4054c5d80338a5248b5b7bd09c53b5e2a084b047d277a861b1a73bb51488de04ef573c85230a0470b73175c9fa50594f66a5f50b4150054c93b68186f8b5cbc49316c8548a642b2b36a1d454c7489ac33b2d2ce6668096782a2c1e0866d21a65e16b585e7af8618bdf3184c1986878508917277b93e10706b1614972b2a94c7310fe9c708c231a1a8ac8d9314a529a97f469bf64962d820648443099a076d55d4cea824a58304844f99497c10a25148618a315d72ca857d1b04d575b94f85c01d19bef211bf0aa3362e7041fd16596d808e867b44c4c00d1cda3418967717f147d0eb21b42aaee74ac35d0b92414b958531aadf463ec6305ae5ecaf79174002f26ddecc813bf32672e8529d95a4e730a7ab4a3e8f8a8af979a665eafd465fc64a0c5f8f3f9003489415899d59a543d8208c54a3166529b539227001e4f285d5113a537f141fa23cb2770845ac28fc9d70df557415f3bc00e735"); - byte[] privEnc = Hex.decode("07638fb69868f3d320e5862bd96933feb311b362093c9b5d50170bced43f1b536d9a204bb1f22695950ba1f2a9e8eb828b284488760b3fc84faba04275d5628e39c5b2471374283c503299c0ab49b66b8bbb56a4186624f919a2ba59bb08d8551880c2befc4f87f25f59ab587a79c327d792d54c974a69262ff8a78938289e9a87b688b083e0595fe218b6bb1505941ce2e81a5a64c5aac60417256985349ee47a52420a5f97477b7236ac76bc70e8288729287ee3e34a3dbc3683c0b7b10029fc203418537e7466ba6385a8ff301ee12708f82aaa1e380fc7a88f8f205ab7e88d7e95952a55ba20d09b79a47141d62bf6eb7dd307b08eca13a5bc5f6b68581c6865b27bbcddab142f4b2cbff488c8a22705faa98a2b9eea3530c76662335cc7ea3a00777725ebcccd2a4636b2d9122ff3ab77123ce0883c1911115e50c9e8a94194e48dd0d09cffb3adcd2c1e92430903d07adbf00532031575aa7f9e7b5a1f3362dec936d4043c05f2476c07578bc9cbaf2ab4e382727ad41686a96b2548820bb03b32f11b2811ad62f489e951632aba0d1df89680cc8a8b53b481d92a68d70b4ea1c3a6a561c0692882b5ca8cc942a8d495afcb06de89498fb935b775908fe7a03e324d54cc19d4e1aabd3593b38b19ee1388fe492b43127e5a504253786a0d69ad32601c28e2c88504a5ba599706023a61363e17c6b9bb59bdc697452cd059451983d738ca3fd034e3f5988854ca05031db09611498988197c6b30d258dfe26265541c89a4b31d6864e9389b03cb74f7ec4323fb9421a4b9790a26d17b0398a26767350909f84d57b6694df830664ca8b3c3c03ed2ae67b89006868a68527ccd666459ab7f056671000c6164d3a7f266a14d97cbd7004d6c92caca770b844a4fa9b182e7b18ca885082ac5646fcb4a14e1685feb0c9ce3372ab95365c04fd83084f80a23ff10a05bf15f7fa5acc6c0cb462c33ca524fa6b8bb359043ba68609eaa2536e81d08463b19653b5435ba946c9addeb202b04b031cc960dcc12e4518d428b32b257a4fc7313d3a7980d80082e934f9d95c32b0a0191a23604384dd9e079bbbaa266d14c3f756b9f2133107433a4e83fa7187282a809203a4faf841851833d121ac383843a5e55bc2381425e16c7db4cc9ab5c1b0d91a47e2b8de0e582c86b6b0d907bb360b97f40ab5d038f6b75c814b27d9b968d419832bc8c2bee605ef6e5059d33100d90485d378450014221736c07407cac260408aa64926619788b8601c2a752d1a6cbf820d7c7a04716203225b3895b9342d147a8185cfc1bb65ba06b4142339903c0ac4651385b45d98a8b19d28cd6bab088787f7ee1b12461766b43cbccb96434427d93c065550688f6948ed1b5475a425f1b85209d061c08b56c1cc069f6c0a7c6f29358cab911087732a649d27c9b98f9a48879387d9b00c25959a71654d6f6a946164513e47a75d005986c2363c09f6b537eca78b9303a5fa457608a586a653a347db04dfcc19175b3a301172536062a658a95277570c8852ca8973f4ae123a334047dd711c8927a634a03388a527b034bf7a8170fa702c1f7c23ec32d18a2374890be9c787a9409c82d192c4bb705a2f996ce405da72c2d9c843ee9f8313ecc7f86d6294d59159d9a879a542e260922adf999051cc45200c9ffdb60449c49465979272367c083a7d6267a3ed7a7fd47957c219327f7ca73a4007e1627f00b11cc80573c15aee6640fb8562dfa6b240ca0ad351ac4ac155b96c14c8ab13dd262cdfd51c4bb5572fd616553d17bdd430acbea3e95f0b698d66990ab51e5d03783a8b3d278a5720454cf9695cfdca08485ba099c51cd92a7ea7587c1d15c28e609a81852601b0604010679aa482d51261ec36e36b8719676217fd74c54786488f4b4969c05a8ba27ca3a77cce73b965923ca554e422b9b61f4754641608ac16c9b8587a32c1c5dd788f88b36b717a46965635deb67f45b129b99070909c93eb80b42c2b3f3f70343a7cf37e8520e7bcfc416aca4f18c7981262ba2bfc756ae03278f0ec66dc2057696824ba6769865a601d7148ef6f54e5af5686aa2906f994ce38a5e0b938f239007003022c03392df3401b1e4a3a7ebc6161449f73374c8b0140369343d9295fdf511845c4a46ebaab6ca5492f6800b98c0cc803653a4b1d6e6aaed1932bacc5fefaa818ba502859ba5494c5f5402c8536a9c4c1888150617f80098f6b2a99c39bc5dc7cf3b5900a21329ab59053abaa64ed163e859a8b3b3ca3359b750ccc3e710c7ac43c8191cb5d68870c06391c0cb8aec72b897ac6be7fbaacc676ed66314c83630e89448c88a1df04aceb23abf2e409ef333c622289c18a2134e650c45257e47475fa33aa537a5a8f7680214716c50d470e3284963ca64f54677aec54b5272162bf52bc8142e1d4183fc017454a6b5a496831759064024745978cbd51a6cedc8955de4cc6d363670a47466e82be5c23603a17bf22acdb7cc984af08c87e14e27753cf587a8ec3447e62c649e887a67c36c9ce98721b697213275646b194f36758673a8ed11284455afc7a8529f69c97a3c2d7b8c636c0ba55614b768e624e712930f776169b01715725351bc74b47395ed52b25a1313c95164814c34c979cbdfab85954662cab485e75087a98cc74bb82ca2d1b5bf2803238480638c40e90b43c7460e7aa917f010151fab1169987b372abb59271f7006c24e60236b84b9ddd600623704254617fb498d89e58b0368bcb2103e79353eb587860c1422e476162e425bc2381db82c6592737e1dd602864b0167a71ec1f223305c02fe25052af2b3b5a55a0d7a2022d9a798dc0c5874a98702aaf4054c5d80338a5248b5b7bd09c53b5e2a084b047d277a861b1a73bb51488de04ef573c85230a0470b73175c9fa50594f66a5f50b4150054c93b68186f8b5cbc49316c8548a642b2b36a1d454c7489ac33b2d2ce6668096782a2c1e0866d21a65e16b585e7af8618bdf3184c1986878508917277b93e10706b1614972b2a94c7310fe9c708c231a1a8ac8d9314a529a97f469bf64962d820648443099a076d55d4cea824a58304844f99497c10a25148618a315d72ca857d1b04d575b94f85c01d19bef211bf0aa3362e7041fd16596d808e867b44c4c00d1cda3418967717f147d0eb21b42aaee74ac35d0b92414b958531aadf463ec6305ae5ecaf79174002f26ddecc813bf32672e8529d95a4e730a7ab4a3e8f8a8af979a665eafd465fc64a0c5f8f3f9003489415899d59a543d8208c54a3166529b53922d4ec143b50f01423b177895edee22bb739f647ecf85f50bc25ef7b5a725dee86b505d7cfad1b497499323c8686325e4792f267aafa3f87ca60d01cb54f29202a38784ccb7ebcdcfd45542b7f6af778742e0f4479175084aa488b3b743406786a"); - String temp = "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"; - String expectedSecret = "e5015e7e9b71e3a0436b159a042b14cb5b63435eee3b8db95f1e8fcce44632a8"; - - byte[] seed = Hex.decode(temp); - - NISTSecureRandom random = new NISTSecureRandom(seed, null); + SecureRandom random = new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(seed)}); + XWingKeyPairGenerator keyGen = new XWingKeyPairGenerator(); + keyGen.init(new XWingKeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair(); - byte[] coins = new byte[96]; - random.nextBytes(coins); XWingPublicKeyParameters publicKey = new XWingPublicKeyParameters(pubEnc); + assertTrue(Arrays.areEqual(((XWingPublicKeyParameters)keyPair.getPublic()).getEncoded(), pubEnc)); + assertTrue(Arrays.areEqual(((XWingPrivateKeyParameters)keyPair.getPrivate()).getEncoded(), privEnc)); XWingPrivateKeyParameters privKey = new XWingPrivateKeyParameters(privEnc); - + random = new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(eseed)}); XWingKEMGenerator kemGen = new XWingKEMGenerator(random); SecretWithEncapsulation secretEncap = kemGen.generateEncapsulated(publicKey); byte[] sharedSecret = secretEncap.getSecret(); - - assertTrue(Arrays.areEqual(Hex.decode(expectedSecret), sharedSecret)); - + byte[] encapsulation = secretEncap.getEncapsulation(); + assertTrue(Arrays.areEqual(ss, sharedSecret)); + assertTrue(Arrays.areEqual(encapsulation, ct)); XWingKEMExtractor kemExtract = new XWingKEMExtractor(privKey); - byte[] decryptedSharedSecret = kemExtract.extractSecret(secretEncap.getEncapsulation()); + byte[] decryptedSharedSecret = kemExtract.extractSecret(encapsulation); - assertTrue(Arrays.areEqual(Hex.decode(expectedSecret), decryptedSharedSecret)); + assertTrue(Arrays.areEqual(ss, decryptedSharedSecret)); } } diff --git a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/AllTests.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/AllTests.java index f85072288a..7d2bdd4ddf 100644 --- a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/AllTests.java +++ b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/AllTests.java @@ -29,6 +29,7 @@ public static Test suite() suite.addTestSuite(NTRUSignerTest.class); suite.addTestSuite(NTRUSigningParametersTest.class); suite.addTestSuite(QTESLATest.class); + suite.addTestSuite(GeMSSTest.class); suite.addTestSuite(SimpleTestTest.class); return new BCTestSetup(suite); diff --git a/core/src/test/java/org/bouncycastle/pqc/crypto/test/GeMSSTest.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/GeMSSTest.java similarity index 89% rename from core/src/test/java/org/bouncycastle/pqc/crypto/test/GeMSSTest.java rename to core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/GeMSSTest.java index 83f9ab196b..bbaa20111a 100644 --- a/core/src/test/java/org/bouncycastle/pqc/crypto/test/GeMSSTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/GeMSSTest.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.crypto.test; +package org.bouncycastle.pqc.legacy.crypto.test; import java.io.BufferedReader; import java.io.InputStream; @@ -7,16 +7,18 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Random; import junit.framework.TestCase; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.pqc.crypto.gemss.GeMSSKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.gemss.GeMSSKeyPairGenerator; -import org.bouncycastle.pqc.crypto.gemss.GeMSSParameters; -import org.bouncycastle.pqc.crypto.gemss.GeMSSPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.gemss.GeMSSPublicKeyParameters; -import org.bouncycastle.pqc.crypto.gemss.GeMSSSigner; +import org.bouncycastle.pqc.crypto.test.NISTSecureRandom; +import org.bouncycastle.pqc.legacy.crypto.gemss.GeMSSKeyGenerationParameters; +import org.bouncycastle.pqc.legacy.crypto.gemss.GeMSSKeyPairGenerator; +import org.bouncycastle.pqc.legacy.crypto.gemss.GeMSSParameters; +import org.bouncycastle.pqc.legacy.crypto.gemss.GeMSSPrivateKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.gemss.GeMSSPublicKeyParameters; +import org.bouncycastle.pqc.legacy.crypto.gemss.GeMSSSigner; import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; @@ -36,6 +38,10 @@ public void testVectors() TestSampler sampler = new TestSampler(); + Random rd = new Random(System.currentTimeMillis()); + + int offSet = rd.nextInt(10); + String[] fileList = splitOn(files, ' '); for (int i = 0; i < fileList.length; i++) { @@ -65,10 +71,14 @@ public void testVectors() byte[] sigExpected = Hex.decode((String)buf.get("sm")); byte[] seed = Hex.decode((String)buf.get("seed")); - if (sampler.skipTest(count)) + if (Integer.parseInt(count) != offSet) { continue; } +// if (sampler.skipTest(count)) +// { +// continue; +// } GeMSSKeyPairGenerator kpGen = new GeMSSKeyPairGenerator(); SecureRandom random = new NISTSecureRandom(seed, null); diff --git a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/McElieceKobaraImaiCipherTest.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/McElieceKobaraImaiCipherTest.java index 35ffc0ecf2..3c013f6b76 100644 --- a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/McElieceKobaraImaiCipherTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/McElieceKobaraImaiCipherTest.java @@ -129,13 +129,7 @@ public void performTest() // XXX write in McElieceFujisakiDigestCipher? - boolean verified = true; - for (int i = 0; i < hash.length; i++) - { - verified = verified && hash[i] == constructedmessage[i]; - } - - if (!verified) + if (!Arrays.areEqual(hash, constructedmessage)) { fail("en/decryption fails"); } diff --git a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/QTESLASecureRandomFactory.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/QTESLASecureRandomFactory.java index df8b71a433..02db7b3ca6 100644 --- a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/QTESLASecureRandomFactory.java +++ b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/QTESLASecureRandomFactory.java @@ -1,8 +1,9 @@ package org.bouncycastle.pqc.legacy.crypto.test; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - +import org.bouncycastle.crypto.BufferedBlockCipher; +import org.bouncycastle.crypto.DefaultBufferedBlockCipher; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.util.test.FixedSecureRandom; /** @@ -113,11 +114,13 @@ private void AES256_ECB(byte[] key, byte[] ctr, byte[] buffer, int startPosition { try { - Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); + BufferedBlockCipher bufferedBlockCipher = new DefaultBufferedBlockCipher(AESEngine.newInstance()); + + bufferedBlockCipher.init(true, new KeyParameter(key)); - cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); + int len = bufferedBlockCipher.processBytes(ctr, 0, ctr.length, buffer, startPosition); - cipher.doFinal(ctr, 0, ctr.length, buffer, startPosition); + bufferedBlockCipher.doFinal(buffer, len); } catch (Throwable ex) { diff --git a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RainbowSignerTest.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RainbowSignerTest.java deleted file mode 100644 index 00eed90fc2..0000000000 --- a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RainbowSignerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bouncycastle.pqc.legacy.crypto.test; - - -import java.math.BigInteger; -import java.security.SecureRandom; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.digests.SHA224Digest; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.pqc.crypto.DigestingMessageSigner; -import org.bouncycastle.pqc.legacy.crypto.rainbow.RainbowKeyGenerationParameters; -import org.bouncycastle.pqc.legacy.crypto.rainbow.RainbowKeyPairGenerator; -import org.bouncycastle.pqc.legacy.crypto.rainbow.RainbowParameters; -import org.bouncycastle.pqc.legacy.crypto.rainbow.RainbowSigner; -import org.bouncycastle.util.BigIntegers; -import org.bouncycastle.util.test.SimpleTest; - - -public class RainbowSignerTest -extends SimpleTest -{ - public String getName() - { - return "Rainbow"; - } - - public void performTest() - { - RainbowParameters params = new RainbowParameters(); - - RainbowKeyPairGenerator rainbowKeyGen = new RainbowKeyPairGenerator(); - RainbowKeyGenerationParameters genParam = new RainbowKeyGenerationParameters(new SecureRandom(), params); - - rainbowKeyGen.init(genParam); - - AsymmetricCipherKeyPair pair = rainbowKeyGen.generateKeyPair(); - - ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), new SecureRandom()); - - DigestingMessageSigner rainbowSigner = new DigestingMessageSigner(new RainbowSigner() , new SHA224Digest()); - - rainbowSigner.init(true, param); - - byte[] message = BigIntegers.asUnsignedByteArray(new BigInteger("968236873715988614170569073515315707566766479517")); - rainbowSigner.update(message, 0, message.length); - byte[] sig = rainbowSigner.generateSignature(); - - rainbowSigner.init(false, pair.getPublic()); - rainbowSigner.update(message, 0, message.length); - - if (!rainbowSigner.verifySignature(sig)) - { - fail("verification fails"); - } - } - - public static void main( - String[] args) - { - runTest(new RainbowSignerTest()); - } -} diff --git a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RegressionTest.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RegressionTest.java index d60a243c62..ce9fc8ab90 100644 --- a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RegressionTest.java +++ b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/RegressionTest.java @@ -10,8 +10,7 @@ public class RegressionTest new McElieceFujisakiCipherTest(), new McElieceKobaraImaiCipherTest(), new McElieceCipherTest(), - new McEliecePointchevalCipherTest(), - new RainbowSignerTest() , + new McEliecePointchevalCipherTest() }; public static void main(String[] args) diff --git a/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/TestSampler.java b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/TestSampler.java new file mode 100644 index 0000000000..de2fb053e1 --- /dev/null +++ b/core/src/test/java/org/bouncycastle/pqc/legacy/crypto/test/TestSampler.java @@ -0,0 +1,31 @@ +package org.bouncycastle.pqc.legacy.crypto.test; + +import java.util.Random; + +import org.bouncycastle.util.Properties; + +class TestSampler +{ + private final boolean isFull; + private final int offSet; + + TestSampler() + { + isFull = Properties.isOverrideSet("test.full"); + + Random random = new Random(System.currentTimeMillis()); + + this.offSet = random.nextInt(10); + } + + boolean skipTest(String count) + { + int c = Integer.parseInt(count); + return !isFull && c != 0 && ((c + offSet) % 9 != 0); + } + + boolean skipTest(int count) + { + return !isFull && count != 0 && ((count + offSet) % 9 != 0); + } +} diff --git a/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java b/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java index 189d829b0f..a10aa56924 100644 --- a/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java +++ b/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java @@ -122,6 +122,34 @@ public void testRegularBlobEndFault() } } + public void testRegularBlobEndLaxParsing() + throws IOException + { + String original = System.setProperty(PemReader.LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME, "true"); + PemReader rd = new PemReader(new StringReader(blob4)); + + PemObject obj; + try + { + obj = rd.readPemObject(); + } + finally + { + if (original != null) + { + System.setProperty(PemReader.LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME, original); + } + else + { + System.setProperty(PemReader.LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME, ""); + } + } + + assertEquals("BLOB", obj.getType()); + assertTrue(Arrays.areEqual(new byte[64], obj.getContent())); + + } + private void lengthTest(String type, List headers, byte[] data) throws IOException { diff --git a/core/src/test/jdk1.3/org/bouncycastle/crypto/test/CipherTest.java b/core/src/test/jdk1.3/org/bouncycastle/crypto/test/CipherTest.java new file mode 100644 index 0000000000..377ea7ce8c --- /dev/null +++ b/core/src/test/jdk1.3/org/bouncycastle/crypto/test/CipherTest.java @@ -0,0 +1,188 @@ +package org.bouncycastle.crypto.test; + +import java.security.SecureRandom; + +import org.bouncycastle.crypto.BlockCipher; +import org.bouncycastle.crypto.CipherKeyGenerator; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.KeyGenerationParameters; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.test.SimpleTest; + +public abstract class CipherTest + extends SimpleTest +{ + private SimpleTest[] _tests; + private BlockCipher _engine; + private KeyParameter _validKey; + +// protected CipherTest( +// SimpleTest[] tests) +// { +// _tests = tests; +// } + + protected CipherTest( + SimpleTest[] tests, + BlockCipher engine, + KeyParameter validKey) + { + _tests = tests; + _engine = engine; + _validKey = validKey; + } + + public abstract String getName(); + + public void performTest() + throws Exception + { + for (int i = 0; i != _tests.length; i++) + { + _tests[i].performTest(); + } + + if (_engine != null) + { + // + // state tests + // + byte[] buf = new byte[128]; + + try + { + _engine.processBlock(buf, 0, buf, 0); + + fail("failed initialisation check"); + } + catch (IllegalStateException e) + { + // expected + } + + bufferSizeCheck((_engine)); + } + } + + private void bufferSizeCheck( + BlockCipher engine) + { + byte[] correctBuf = new byte[engine.getBlockSize()]; + byte[] shortBuf = new byte[correctBuf.length / 2]; + + engine.init(true, _validKey); + + try + { + engine.processBlock(shortBuf, 0, correctBuf, 0); + + fail("failed short input check"); + } + catch (DataLengthException e) + { + // expected + } + + try + { + engine.processBlock(correctBuf, 0, shortBuf, 0); + + fail("failed short output check"); + } + catch (DataLengthException e) + { + // expected + } + + engine.init(false, _validKey); + + try + { + engine.processBlock(shortBuf, 0, correctBuf, 0); + + fail("failed short input check"); + } + catch (DataLengthException e) + { + // expected + } + + try + { + engine.processBlock(correctBuf, 0, shortBuf, 0); + + fail("failed short output check"); + } + catch (DataLengthException e) + { + // expected + } + } + + interface Instace + { + AEADCipher CreateInstace(); + } + + static void checkCipher(int aeadLen, int ivLen, int msgLen, Instace instace) + { + AEADCipher pCipher = instace.CreateInstace(); + + try + { + /* Obtain some random data */ + final byte[] myData = new byte[msgLen]; + final SecureRandom myRandom = new SecureRandom(); + myRandom.nextBytes(myData); + + /* Obtain some random AEAD */ + final byte[] myAEAD = new byte[aeadLen]; + myRandom.nextBytes(myAEAD); + + /* Create the Key parameters */ + final CipherKeyGenerator myGenerator = new CipherKeyGenerator(); + final KeyGenerationParameters myGenParams = new KeyGenerationParameters(myRandom, 128); + myGenerator.init(myGenParams); + final byte[] myKey = myGenerator.generateKey(); + final KeyParameter myKeyParams = new KeyParameter(myKey); + + /* Create the nonce */ + final byte[] myNonce = new byte[ivLen]; + myRandom.nextBytes(myNonce); + final ParametersWithIV myParams = new ParametersWithIV(myKeyParams, myNonce); + + /* Initialise the cipher for encryption */ + pCipher.init(true, myParams); + final int myMaxOutLen = pCipher.getOutputSize(msgLen); + final byte[] myEncrypted = new byte[myMaxOutLen]; + pCipher.processAADBytes(myAEAD, 0, aeadLen); + int myOutLen = pCipher.processBytes(myData, 0, msgLen, myEncrypted, 0); + myOutLen += pCipher.doFinal(myEncrypted, myOutLen); + + /* Note that myOutLen is too large by DATALEN */ + pCipher = instace.CreateInstace(); + /* Initialise the cipher for decryption */ + pCipher.init(false, myParams); + final int myMaxClearLen = pCipher.getOutputSize(myOutLen); + final byte[] myDecrypted = new byte[myMaxClearLen]; + pCipher.processAADBytes(myAEAD, 0, aeadLen); + int myClearLen = pCipher.processBytes(myEncrypted, 0, myEncrypted.length, myDecrypted, 0); + myClearLen += pCipher.doFinal(myDecrypted, myClearLen); + final byte[] myResult = Arrays.copyOf(myDecrypted, msgLen); + + /* Check that we have the same result */ + if (!Arrays.areEqual(myData, myResult)) + { + System.out.println("Cipher " + pCipher.getAlgorithmName() + " failed"); + } + } + catch (InvalidCipherTextException e) + { + throw new RuntimeException(e.toString()); + } + } +} diff --git a/docs/releasenotes.html b/docs/releasenotes.html index 495c876314..1b23f26112 100644 --- a/docs/releasenotes.html +++ b/docs/releasenotes.html @@ -18,20 +18,133 @@

    1.0 Introduction

    2.0 Release History

    -

    2.1.1 Version

    -Date:      2024, 18th April. +

    2.1.1 Version

    +Release: 1.81
    +Date:      2025, 4th June.

    2.1.2 Defects Fixed

      +
    • A potention NullPointerException in the KEM KDF KemUtil class has been removed.
    • +
    • Overlapping input/output buffers in doFinal could result in data corruption. This has been fixed.
    • +
    • Fixed Grain-128AEAD decryption incorrectly handle MAC verification.
    • +
    • Add configurable header validation to prevent malicious header injection in PGP cleartext signed messages; Fix signature packet encoding issues in PGPSignature.join() and embedded signatures while phasing out legacy format.
    • +
    • Fixed ParallelHash initialization stall when using block size B=0.
    • +
    • The PRF from the PBKDF2 function was been lost when PBMAC1 was initialized from protectionAlgorithm. This has been fixed.
    • +
    • The lowlevel DigestFactory was cloning MD5 when being asked to clone SHA1. This has been fixed.
    • +
    +

    2.1.3 Additional Features and Functionality

    +
      +
    • XWing implementation updated to draft-connolly-cfrg-xwing-kem/07/
    • +
    • Further support has been added for generation and use of PGP V6 keys
    • +
    • Additional validation has been added for armored headers in Cleartext Signed Messages.
    • +
    • The PQC signature algorithm proposal Mayo has been added to the low-level API and the BCPQC provider.
    • +
    • The PQC signature algorithm proposal Snova has been added to the low-level API and the BCPQC provider.
    • +
    • Support for ChaCha20-Poly1305 has been added to the CMS/SMIME APIs.
    • +
    • The Falcon implementation has been updated to the latest draft.
    • +
    • Support has been added for generating keys which encode as seed-only and expanded-key-only for ML-KEM and ML-DSA private keys.
    • +
    • Private key encoding of ML-DSA and ML-KEM private keys now follows the latest IETF draft.
    • +
    • The Ascon family of algorithms has been updated to the initial draft of SP 800-232. Some additional optimisation work has been done.
    • +
    • Support for ML-DSA's external-mu calculation and signing has been added to the BC provider.
    • +
    • CMS now supports ML-DSA for SignedData generation.
    • +
    • Introduce high-level OpenPGP API for message creation/consumption and certificate evaluation.
    • +
    • Added JDK21 KEM API implementation for HQC algorithm.
    • +
    • BCJSSE: Strip trailing dot from hostname for SNI, endpointID checks.
    • +
    • BCJSSE: Draft support for ML-KEM updated (draft-connolly-tls-mlkem-key-agreement-05).
    • +
    • BCJSSE: Draft support for hybrid ECDHE-MLKEM (draft-ietf-tls-ecdhe-mlkem-00).
    • +
    • BCJSSE: Optionally prefer TLS 1.3 server's supported_groups order (BCSSLParameters.useNamedGroupsOrder).
    • +
    + +

    2.2.1 Version

    +Release: 1.80
    +Date:      2025, 14th January. +

    2.2.2 Defects Fixed

    +
      +
    • A splitting issue for ML-KEM lead to an incorrect size for kemct in KEMRecipientInfos. This has been fixed.
    • +
    • The PKCS12 KeyStore has been adjusted to prevent accidental doubling of the Oracle trusted certificate attribute (results in an IOException when used with the JVM PKCS12 implementation).
    • +
    • The SignerInfoGenerator copy constructor was ignoring the certHolder field. This has been fixed.
    • +
    • The getAlgorithm() method return value for a CompositePrivateKey was not consistent with the corresponding getAlgorithm() return value for the CompositePrivateKey. This has been fixed.
    • +
    • The international property files were missing from the bcjmail distribution. This has been fixed.
    • +
    • Issues with ElephantEngine failing on processing large/multi-block messages have been addressed.
    • +
    • GCFB mode now fully resets on a reset.
    • +
    • The lightweight algorithm contestants: Elephant, ISAP, PhotonBeetle, Xoodyak now support the use of the AEADParameters class and provide accurate update/doFinal output lengths.
    • +
    • An unnecessary downcast in CertPathValidatorUtilities was resulting in the ignoring of URLs for FTP based CRLs. This has been fixed.
    • +
    • A regression in the OpenPGP API could cause NoSuchAlgorithmException to be thrown when attempting to use SHA-256 in some contexts. This has been fixed.
    • +
    • EtsiTs1029411TypesAuthorization was missing an extension field. This has been added.
    • +
    • Interoperability issues with single depth LMS keys have been addressed.
    • +
    +

    2.2.3 Additional Features and Functionality

    +
      +
    • CompositeSignatures now updated to draft-ietf-lamps-pq-composite-sigs-03.
    • +
    • ML-KEM, ML-DSA, SLH-DSA, and Composite private keys now use raw encodings as per the latest drafts from IETF 121: draft-ietf-lamps-kyber-certificates-06, draft-ietf-lamps-dilithium-certificates-05, and draft-ietf-lamps-x509-slhdsa.
    • +
    • Initial support has been added for RFC 9579 PBMAC1 in the PKCS API.
    • +
    • Support has been added for EC-JPAKE to the lightweight API.
    • +
    • Support has been added for the direct construction of S/MIME AuthEnvelopedData objects, via the SMIMEAuthEnvelopedData class.
    • +
    • An override "org.bouncycastle.asn1.allow_wrong_oid_enc" property has been added to disable new OID encoding checks (use with caution).
    • +
    • Support has been added for the PBEParemeterSpec.getParameterSpec() method where supported by the JVM.
    • +
    • ML-DSA/SLH-DSA now return null for Signature.getParameters() if no context is provided. This allows the algorithms to be used with the existing Java key tool.
    • +
    • HQC has been updated to reflect the reference implementation released on 2024-10-30.
    • +
    • Support has been added to the low-level APIs for the OASIS Shamir Secret Splitting algorithms.
    • +
    • BCJSSE: System property "org.bouncycastle.jsse.fips.allowGCMCiphersIn12" no longer used. FIPS TLS 1.2 GCM suites can now be enabled according to JcaTlsCrypto#getFipsGCMNonceGeneratorFactory (see JavaDoc for details) if done in alignment with FIPS requirements.
    • +
    • Support has been added for OpenPGP V6 PKESK and message encryption.
    • +
    • PGPSecretKey.copyWithNewPassword() now includes AEAD support.
    • +
    • The ASCON family of algorithms have been updated in accordance with the published FIPS SP 800-232 draft.
    • +
    + +

    2.3.1 Version

    +Release: 1.79
    +Date:      2024, 30th October. +

    2.3.2 Defects Fixed

    +
      +
    • Leading zeroes were sometimes dropped from Ed25519 signatures leading to verification errors in the PGP API. This has been fixed.
    • +
    • Default version string for Armored Output is now set correctly in 18on build.
    • +
    • The Elephant cipher would fail on large messages. This has been fixed.
    • +
    • CMSSignedData.replaceSigners() would re-encode the digest algorithms block, occassionally dropping ones where NULL had been previously added as an algorithm parameter. The method now attempts to only use the original digest algorithm identifiers.
    • +
    • ERSInputStreamData would fail to generate the correct hash if called a second time with a different hash algorithm. This has been fixed.
    • +
    • A downcast in the CrlCache which would cause FTP based CRLs to fail to load has been removed.
    • +
    • ECUtil.getNamedCurveOid() now trims curve names of excess space before look up.
    • +
    • The PhotonBeetle and Xoodyak digests did not reset properly after a doFinal() call. This has been fixed.
    • +
    • Malformed AlgorithmIdentifiers in CertIDs could cause caching issues in the OCSP cache. This has been fixed.
    • +
    • With Java 21 a provider service class will now be returned with a null class name where previously a null would have been returned for a service. This can cause a NullPointerException to be thrown by the BC provider if a non-existant service is requested. This issue has now been worked around.
    • +
    • CMS: OtherKeyAttribute.keyAttr now treated as optional.
    • +
    • CMS: EnvelopedData and AuthEnvelopedData could calculate the wrong versions. This has been fixed.
    • +
    • The default version header for PGP armored output did not carry the correct version string. This has been fixed.
    • +
    • In some situations the algorithm lookup for creating PGPDigestCalculators would fail due to truncation of the algorithm name. This has been fixed.
    • +
    +

    2.3.3 Additional Features and Functionality

    +
      +
    • Object Identifiers have been added for ML-KEM, ML-DSA, and SLH-DSA.
    • +
    • The PQC algorithms, ML-KEM, ML-DSA (including pre-hash), and SLH-DSA (including pre-hash) have been added to the BC provider and the lightweight API.
    • +
    • A new spec, ContextParameterSpec, has been added to support signature contexts for ML-DSA and SLH-DSA.
    • +
    • BCJSSE: Added support for security property "jdk.tls.server.defaultDHEParameters" (disabled in FIPS mode).
    • +
    • BCJSSE: Added support for signature_algorithms_cert configuration via "org.bouncycastle.jsse.client.SignatureSchemesCert" and "org.bouncycastle.jsse.server.SignatureSchemesCert" system properties or BCSSLParameters property "SignatureSchemesCert".
    • +
    • BCJSSE: Added support for boolean system property "org.bouncycastle.jsse.fips.allowGCMCiphersIn12" (false by default).
    • +
    • (D)TLS: Remove redundant verification of self-generated RSA signatures.
    • +
    • CompositePrivateKeys now support the latest revision of the composite signature draft.
    • +
    • Delta Certificates now support the latest revision of the delta certificate extension draft.
    • +
    • A general KeyIdentifier class, encapsulating both PGP KeyID and the PGP key fingerprint has been added to the PGP API.
    • +
    • Support for the LibrePGP PreferredEncryptionModes signature subpacket has been added to the PGP API.
    • +
    • Support for Version 6 signatures, including salts, has been added to the PGP API.
    • +
    • Support for the PreferredKeyServer signature supacket has been added to the PGP API.
    • +
    • Support for RFC 9269, "Using KEMs in Cryptographic Message Syntax (CMS)", has been added to the CMS API.
    • +
    • Support for the Argon2 S2K has been added to the PGP API.
    • +
    • The system property "org.bouncycastle.pemreader.lax" has been introduced for situations where the BC PEM parsing is now too strict.
    • +
    • The system property "org.bouncycastle.ec.disable_f2m" has been introduced to allow F2m EC support to be disabled.
    • +
    + +

    2.4.1 Version

    +Release: 1.78.1
    +Date:      2024, 18th April. +

    2.4.2 Defects Fixed

    +
    • The new dependency of the the PGP API on the bcutil jar was missing from the module jar, the OSGi manifest, and the Maven POM. This has been fixed.
    • Missing exports and duplicate imports have been added/removed from the OSGi manifests.
    • -
    • The OSGi manifests now have the same bundle IDs as 1.77 and lock down dependencies to the equivalent variations
    • +
    • The OSGi manifests now have the same bundle IDs as 1.77 and lock down dependencies to the equivalent variations.
    • A check in the X.509 Extensions class preventing the parsing of empty extensions has been removed.
    -

    2.2.1 Version

    +

    2.5.1 Version

    Release: 1.78
    Date:      2024, 7th April. -

    2.2.2 Defects Fixed

    +

    2.5.2 Defects Fixed

    • Issues with a dangling weak reference causing intermittent NullPointerExceptions in the OcspCache have been fixed.
    • Issues with non-constant time RSA operations in TLS handshakes have been fixed.
    • @@ -47,8 +160,9 @@

      2.2.2 Defects Fixed

    • The missing module import of java.logging to the provider module has been added.
    • GOST ASN.1 public key alg parameters are now compliant with RFC 9215.
    • An off-by-one error in the encoding for EccP256CurvePoint for ITS has been fixed.
    • +
    • PEM Parser now enforces PEM headers to start at the beginning of the line to be meaningful.
    -

    2.2.3 Additional Features and Functionality

    +

    2.5.3 Additional Features and Functionality

    • An implementation of MLS (RFC 9420 - The Messaging Layer Security Protocol) has been added as a new module.
    • NTRU now supports NTRU-HPS4096-1229 and NTRU-HRSS-1373.
    • @@ -66,7 +180,7 @@

      2.2.3 Additional Features and Functionality

    • CertPathValidationContext and CertificatePoliciesValidation now include implementations of Memoable.
    • The Composite post-quantum signatures implementation has been updated to the latest draft draft-ounsworth-pq-composite-sigs.
    -

    2.2.4 Notes.

    +

    2.5.4 Notes.

    • Both versions of NTRUPrime have been updated to produce 256 bit secrets in line with Kyber. This should also bring them into line with other implementations such as those used in OpenSSH now.
    • BCJSSE: The boolean system property 'org.bouncycastle.jsse.fips.allowRSAKeyExchange" now defaults to false. All RSA @@ -77,7 +191,7 @@

      2.2.4 Notes.

    • The PKCS12 store using GCM does not include the PKCS#12 MAC so no longer includes use of the PKCS#12 PBE scheme and only uses PBKDF2.
    • In keeping with the current set of experimental OIDs for PQC algorithms, OIDs may have changed to reflect updated versions of the algorithms.
    -

    2.2.5 Security Advisories.

    +

    2.5.5 Security Advisories.

    Release 1.78 deals with the following CVEs:

    @@ -85,13 +199,13 @@

    2.2.5 Security Advisories.

  • CVE-2024-29857 - Importing an EC certificate with specially crafted F2m parameters can cause high CPU usage during parameter evaluation.
  • CVE-2024-30171 - Possible timing based leakage in RSA based handshakes due to exception processing eliminated.
  • CVE-2024-30172 - Crafted signature and public key can be used to trigger an infinite loop in the Ed25519 verification code.
  • -
  • CVE-2024-301XX - When endpoint identification is enabled in the BCJSSE and an SSL socket is not created with an explicit hostname (as happens with HttpsURLConnection), hostname verification could be performed against a DNS-resolved IP address. This has been fixed.
  • +
  • CVE-2024-34447 - When endpoint identification is enabled in the BCJSSE and an SSL socket is not created with an explicit hostname (as happens with HttpsURLConnection), hostname verification could be performed against a DNS-resolved IP address. This has been fixed.
  • -

    2.3.1 Version

    +

    2.6.1 Version

    Release: 1.77
    Date:      2023, November 13th -

    2.3.2 Defects Fixed

    +

    2.6.2 Defects Fixed

    • Using an unescaped '=' in an X.500 RDN would result in the RDN being truncated silently. The issue is now detected and an exception is thrown.
    • asn1.eac.CertificateBody was returning certificateEffectiveDate from getCertificateExpirationDate(). This has been fixed to return certificateExpirationDate.
    • @@ -107,7 +221,7 @@

      2.3.2 Defects Fixed

    • An internal method in Arrays was failing to construct its failure message correctly on an error. This has been fixed.
    • HSSKeyPublicParameters.generateLMSContext() would fail for a unit depth key. This has been fixed.
    -

    2.3.3 Additional Features and Functionality

    +

    2.6.3 Additional Features and Functionality

    • BCJSSE: Added org.bouncycastle.jsse.client.omitSigAlgsCertExtension and org.bouncycastle.jsse.server.omitSigAlgsCertExtension boolean system properties to control (for client and server resp.) whether the signature_algorithms_cert extension should be omitted if it would be identical to signature_algorithms. @@ -119,7 +233,7 @@

      2.3.3 Additional Features and Functionality

    • TLS: RSA key exchange cipher suites are now disabled by default.
    • Support has been added for PKCS#10 requests to allow certificates using the altSignature/altPublicKey extensions.
    -

    2.3.4 Notes.

    +

    2.6.4 Notes.

    • Kyber and Dilithium have been updated according to the latest draft of the standard. Dilithium-AES and Kyber-AES have now been removed. Kyber now produces 256 bit secrets for all parameter sets (in line with the draft standard).
    • NTRU has been updated to produce 256 bit secrets in line with Kyber.
    • @@ -128,10 +242,10 @@

      2.3.4 Notes.

    • PQC CMS SignedData now defaults to SHA-256 for signed attributes rather than SHAKE-256. This is also a compatibility change, but may change further again as the IETF standard for CMS is updated.
    -

    2.4.1 Version

    +

    2.7.1 Version

    Release: 1.76
    Date:      2023, July 29th -

    2.4.2 Defects Fixed

    +

    2.7.2 Defects Fixed

    • Service allocation in the provider could fail due to the lack of a permission block. This has been fixed.
    • JceKeyFingerPrintCalculator has been generalised for different providers by using "SHA-256" for the algorithm string.
    • @@ -140,7 +254,7 @@

      2.4.2 Defects Fixed

    • Cipher.unwrap() for HQC could fail due to a miscalculation of the length of the KEM packet. This has been fixed.
    • There was exposure to a Java 7 method in the Java 5 to Java 8 BCTLS jar which could cause issues with some TLS 1.2 cipher suites running on older JVMs. This is now fixed.
    -

    2.4.3 Additional Features and Functionality

    +

    2.7.3 Additional Features and Functionality

    • BCJSSE: Following OpenJDK, finalizers have been removed from SSLSocket subclasses. Applications should close sockets and not rely on garbage collection.
    • BCJSSE: Added support for boolean system property "jdk.tls.client.useCompatibilityMode" (default "true").
    • @@ -153,30 +267,30 @@

      2.4.3 Additional Features and Functionality

    • An UnknownPacket type has been added to the PGP APIs to allow for forwards compatibility with upcoming revisions to the standard.
    -

    2.5.1 Version

    +

    2.8.1 Version

    Release: 1.75
    Date:      2023, June 21st -

    2.5.2 Defects Fixed

    +

    2.8.2 Defects Fixed

    • Several Java 8 method calls were accidentally introduced in the Java 5 to Java 8 build. The affected classes have been refactored to remove this.
    • (D)TLS: renegotiation after resumption now fixed to avoid breaking connection.
    -

    2.5.3 Notes.

    +

    2.8.3 Notes.

    • The ASN.1 core package has had some dead and retired methods cleaned up and removed.
    -

    2.6.1 Version

    +

    2.9.1 Version

    Release: 1.74
    Date:      2023, June 12th -

    2.6.2 Defects Fixed

    +

    2.9.2 Defects Fixed

    • AsconEngine: Fixed a buffering bug when decrypting across multiple processBytes calls (ascon128a unaffected).
    • Context based sanity checking on PGP signatures has been added.
    • The ParallelHash clone constructor was not copying all fields. This is now fixed.
    • The maximimum number of blocks for CTR/SIC modes was 1 block less than it should have been. This is now fixed.
    -

    2.6.3 Additional Features and Functionality

    +

    2.9.3 Additional Features and Functionality

    • The PGP API now supports wildcard key IDs for public key based data encryption.
    • LMS now supports SHA256/192, SHAKE256/192, and SHAKE256/256 (the additional SP 8000-208 parameter sets).
    • @@ -195,22 +309,22 @@

      2.6.3 Additional Features and Functionality

    • The number of keys/sub-keys in a PGPKeyRing can now be found by calling PGPKeyRing.size().
    • The PQC algorithms LMS/HSS, SPHINCS+, Dilithium, Falcon, and NTRU are now supported directly by the BC provider.
    -

    2.6.4 Notes.

    +

    2.9.4 Notes.

    • The now defunct PQC SIKE algorithm has been removed, this has also meant the removal of its resource files so the provider is now quite a bit smaller.
    • As a precaution, HC128 now enforces a 128 bit IV, previous behaviour for shorter IVs can be supported where required by padding the IV to the 128 bits with zero.
    • PGP encrypted data generation now uses integrity protection by default. Previous behaviour for encrypted data can be supported where required by calling PGPDataEncryptorBuilder.setWithIntegrityPacket(false) when data encryption is set up.
    • There are now additional sanity checks in place to prevent accidental mis-use of PGPSignature objects. If this change causes any issues, you might want to check what your code is up to as there is probably a bug.
    -

    2.6.5 Security Advisories.

    +

    2.9.5 Security Advisories.

    • CVE-2023-33201 - this release fixes an issue with the X509LDAPCertStoreSpi where a specially crafted certificate subject could be used to try and extract extra information out of an LDAP server with wild-card matching enabled.
    -

    2.7.1 Version

    +

    2.10.1 Version

    Release: 1.73
    Date:      2023, April 8th -

    2.7.2 Defects Fixed

    +

    2.10.2 Defects Fixed

    • BCJSSE: Instantiating a JSSE provider in some contexts could cause an AccessControl exception. This has been fixed.
    • The EC key pair generator can generate out of range private keys when used with SM2. A specific SM2KeyPairGenerator has been added to the low-level API and is used by KeyPairGenerator.getInstance("SM2", "BC"). The SM2 signer has been updated to check for out of range keys as well..
    • @@ -231,7 +345,7 @@

      2.7.2 Defects Fixed

    • IPAddress has been written to provide stricter checking and avoid the use of Integer.parseInt().
    • A Java 7 class snuck into the Java 5 to Java 8 build. This has been addressed.
    -

    2.7.3 Additional Features and Functionality

    +

    2.10.3 Additional Features and Functionality

    • The Rainbow NIST Post Quantum Round-3 Candidate has been added to the low-level API and the BCPQC provider (level 3 and level 5 parameter sets only).
    • The GeMSS NIST Post Quantum Round-3 Candidate has been added to the low-level API.
    • @@ -258,38 +372,38 @@

      2.7.3 Additional Features and Functionality

    • A general purpose PQCOtherInfoGenerator has been added which supports all Kyber and NTRU.
    • An implementation of HPKE (RFC 9180 - Hybrid Public Key Encryption) has been added to the light-weight cryptography API.
    -

    2.7.4 Security Advisories.

    +

    2.10.4 Security Advisories.

    • The PQC implementations have now been subject to formal review for secret leakage and side channels, there were issues in BIKE, Falcon, Frodo, HQC which have now been fixed. Some weak positives also showed up in Rainbow, Picnic, SIKE, and GeMSS - for now this last set has been ignored as the algorithms will either be updated if they reappear in the Signature Round, or deleted, as is already the case for SIKE (it is now in the legacy package). Details on the group responsible for the testing can be found in the CONTRIBUTORS file.
    • For at least some ECIES variants (e.g. when using CBC) there is an issue with potential malleability of a nonce (implying silent malleability of the plaintext) that must be sent alongside the ciphertext but is outside the IES integrity check. For this reason the automatic generation of nonces with IED is now disabled and they have to be passed in using an IESParameterSpec. The current advice is to agree on a nonce between parties and then rely on the use of the ephemeral key component to allow the nonce (rather the so called nonce) usage to be extended.
    -

    2.7.5 Notes.

    +

    2.10.5 Notes.

    • Most test data files have now been migrated to a separate project bc-test-data which is also available on github. If you clone bc-test-data at the same level as the bc-java project the tests will find the test data they require.
    • There has been further work to make entropy collection more friendly in container environments. See DRBG.java for details. We would welcome any further feedback on this as we clearly cannot try all situations first hand.
    -

    2.8.1 Version

    +

    2.11.1 Version

    Release: 1.72.2, 1.72.3
    Date:      2022, November 20th -

    2.8.2 Defects Fixed

    +

    2.11.2 Defects Fixed

    • PGP patch release - fix for OSGI and version header in 1.72.1 jar file.
    -

    2.9.1 Version

    +

    2.12.1 Version

    Release: 1.72.1
    Date:      2022, October 25th -

    2.9.2 Defects Fixed

    +

    2.12.2 Defects Fixed

    • PGP patch release - fix for regression in OpenPGP PGPEncryptedData.java which could result in checksum failures on correct files.
    -

    2.10.1 Version

    +

    2.13.1 Version

    Release: 1.72
    Date:      2022, September 25th -

    2.10.2 Defects Fixed

    +

    2.13.2 Defects Fixed

    • There were parameter errors in XMSS^MT OIDs for XMSSMT_SHA2_40/4_256 and XMSSMT_SHA2_60/3_256. These have been fixed.
    • There was an error in Merkle tree construction for the Evidence Records (ERS) implementation which could result in invalid roots been timestamped. ERS now produces an ArchiveTimeStamp for each data object/group with an associated reduced hash tree. The reduced hash tree is now calculated as a simple path to the root of the tree for each record.
    • @@ -297,7 +411,7 @@

      2.10.2 Defects Fixed

    • A tagging calculation error in GCMSIV which could result in incorrect tags has been fixed.
    • Issues around Java 17 which could result in failing tests have been addressed.
    -

    2.10.3 Additional Features and Functionality

    +

    2.13.3 Additional Features and Functionality

    • BCJSSE: TLS 1.3 is now enabled by default where no explicit protocols are supplied (e.g. "TLS" or "Default" SSLContext algorithms, or SSLContext.getDefault() method).
    • BCJSSE: Rewrite SSLEngine implementation to improve compatibility with SunJSSE.
    • @@ -327,22 +441,22 @@

      2.10.3 Additional Features and Functionality

    • Support has been added to the PKCS#12 implementation for the Oracle trusted certificate attribute.
    • Performance of our BZIP2 classes has been improved.
    -

    2.10.4 Notes

    +

    2.13.4 Notes

    Keep in mind the PQC algorithms are still under development and we are still at least a year and a half away from published standards. This means the algorithms may still change so by all means experiment, but do not use the PQC algoritms for anything long term.

    The legacy "Rainbow" and "McEliece" implementations have been removed from the BCPQC provider. The underlying classes are still present if required. Other legacy algorithm implementations can be found under the org.bouncycastle.pqc.legacy package.

    -

    2.10.5 Security Notes

    +

    2.13.5 Security Notes

    The PQC SIKE algorithm is provided for research purposes only. It should now be regarded as broken. The SIKE implementation will be withdrawn in BC 1.73.

    -

    2.11.1 Version

    +

    2.14.1 Version

    Release: 1.71
    Date:      2022, March 31st. -

    2.11.2 Defects Fixed

    +

    2.14.2 Defects Fixed

    • In line with GPG the PGP API now attempts to preserve comments containing non-ascii UTF-8 characters.
    • An accidental partial dependency on Java 1.7 has been removed from the TLS API.
    • @@ -356,7 +470,7 @@

      2.11.2 Defects Fixed

    • An accidental regression introduced by a fix for another issue in PKIXCertPathReviewer around use of the AuthorityKeyIdentifier extension and it failing to match a certificate uniquely when the serial number field is missing has been fixed.
    • An error was found in the creation of TLS 1.3 Export Keying Material which could cause compatibility issues. This has been fixed.
    -

    2.11.3 Additional Features and Functionality

    +

    2.14.3 Additional Features and Functionality

    • Support has been added for OpenPGP regular expression signature packets.
    • Support has been added for OpenPGP PolicyURI signature packets.
    • @@ -386,16 +500,16 @@

      2.11.3 Additional Features and Functionality

    • ASN.1 object support has been added for the Lightweight Certificate Management Protocol (CMP), currently in draft.
    • A HybridValueParamterSpec class has been added for use with KeyAgreement to support SP 800-56C hybrid (so classical/post-quantum) key agreement.
    -

    2.11.4 Notes

    +

    2.14.4 Notes

    • The deprecated QTESLA implementation has been removed from the BCPQC provider.
    • The submission update to SPHINCS+ has been added. This changes the generation of signatures - particularly deterministic ones.
    -

    2.12.1 Version

    +

    2.15.1 Version

    Release: 1.70
    Date:      2021, November 29th. -

    2.12.2 Defects Fixed

    +

    2.15.2 Defects Fixed

    • Blake 3 output limit is enforced.
    • The PKCS12 KeyStore was relying on default precedence for its key Cipher implementation so was sometimes failing if used from the keytool. The KeyStore class now makes sure it uses the correct Cipher implementation.
    • @@ -409,7 +523,7 @@

      2.12.2 Defects Fixed

    • The lack of close() in the ASN.1 Dump command line utility was triggering false positives in some code analysis tools. A close() call has been added.
    • PGPPublicKey.getBitStrength() now properly recognises EdDSA keys.
    -

    2.12.3 Additional Features and Functionality

    +

    2.15.3 Additional Features and Functionality

    • Missing PGP CRC checksums can now be optionally ignored using setDetectMissingCRC() (default false) on ArmoredInputStream.
    • PGPSecretKey.copyWithNewPassword() now has a variant which uses USAGE_SHA1 for key protection if a PGPDigestCalculator is passed in.
    • @@ -448,15 +562,15 @@

      2.12.3 Additional Features and Functionality

    • The JcePKCSPBEOutputEncryptorBuilder now supports SCRYPT with ciphers that do not have algorithm parameters (e.g. AESKWP).
    • Support is now added for certificates using ETSI TS 103 097, "Intelligent Transport Systems (ITS)" in the bcpkix package.
    -

    2.12.4 Notes.

    +

    2.15.4 Notes.

    • While this release should maintain source code compatibility, developers making use of some parts of the ASN.1 library will find that some classes need recompiling. Apologies for the inconvenience.
    -

    2.13.1 Version

    +

    2.16.1 Version

    Release: 1.69
    Date:      2021, June 7th. -

    2.13.2 Defects Fixed

    +

    2.16.2 Defects Fixed

    • Lightweight and JCA conversion of Ed25519 keys in the PGP API could drop the leading byte as it was zero. This has been fixed.
    • Marker packets appearing at the start of PGP public key rings could cause parsing failure. This has been fixed.
    • @@ -476,7 +590,7 @@

      2.13.2 Defects Fixed

    • Fix various conversions and interoperability for XDH and EdDSA between BC and SunEC providers.
    • TLS: Prevent attempts to use KeyUpdate mechanism in versions before TLS 1.3.
    -

    2.13.3 Additional Features and Functionality

    +

    2.16.3 Additional Features and Functionality

    • GCM-SIV has been added to the lightweight API and the provider.
    • Blake3 has been added to the lightweight API.
    • @@ -517,24 +631,24 @@

      2.13.3 Additional Features and Functionality

    • BCJSSE: Key managers now support EC credentials for use with TLS 1.3 ECDSA signature schemes (including brainpool).
    • TLS: Add TLS 1.3 support for brainpool curves per RFC 8734.
    -

    2.13.4 Notes

    +

    2.16.4 Notes

    • There is a small API change in the PKIX package to the DigestAlgorithmIdentifierFinder interface as a find() method that takes an ASN1ObjectIdentifier has been added to it. For people wishing to extend their own implementations, see DefaultDigestAlgorithmIdentifierFinder for a sample implementation.
    • A version of the bcmail API supporting Jakarta Mail has now been added (see bcjmail jar).
    • Some work has been done on moving out code that does not need to be in the provider jar. This has reduced the size of the provider jar and should also make it easier for developers to patch the classes involved as they no longer need to be signed. bcpkix and bctls are both dependent on the new bcutil jar.
    -

    2.14.1 Version

    +

    2.17.1 Version

    Release: 1.68
    Date:      2020, December 21st. -

    2.14.2 Defects Fixed

    +

    2.17.2 Defects Fixed

    • Some BigIntegers utility methods would fail for BigInteger.ZERO. This has been fixed.
    • PGPUtil.isKeyRing() was not detecting secret sub-keys in its input. This has been fixed.
    • The ASN.1 class, ArchiveTimeStamp was insisting on a value for the optional reducedHashTree field. This has been fixed.
    • BCJSSE: Lock against multiple writers - a possible synchronization issue has been removed.
    -

    2.14.3 Additional Features and Functionality

    +

    2.17.3 Additional Features and Functionality

    • BCJSSE: Added support for system property com.sun.net.ssl.requireCloseNotify. Note that we are using a default value of 'true'.
    • BCJSSE: 'TLSv1.3' is now a supported protocol for both client and server. For this release it is only enabled by default for the 'TLSv1.3' SSLContext, but can be explicitly enabled using 'setEnabledProtocols' on an SSLSocket or SSLEngine, or via SSLParameters.
    • @@ -545,10 +659,10 @@

      2.14.3 Additional Features and Functionality

    -

    2.15.1 Version

    +

    2.18.1 Version

    Release: 1.67
    Date:      2020, November 1st. -

    2.15.2 Defects Fixed

    +

    2.18.2 Defects Fixed

    • BCJSSE: SunJSSE compatibility fix - override of getChannel() removed and 'urgent data' behaviour should now conform to what the SunJSSE expects.
    • Nested BER data could sometimes cause issues in octet strings. This has been fixed.
    • @@ -560,7 +674,7 @@

      2.15.2 Defects Fixed

    • Zero length data would cause an unexpected exception from RFC5649WrapEngine. This has been fixed.
    • OpenBSDBcrypt was failing to handle some valid prefixes. This has been fixed.
    -

    2.15.3 Additional Features and Functionality

    +

    2.18.3 Additional Features and Functionality

    • Performance of Argon2 has been improved.
    • Performance of Noekeon has been improved.
    • @@ -578,15 +692,15 @@

      2.15.3 Additional Features and Functionality

    • Mode name checks in Cipher strings should now make sure an improper mode name always results in a NoSuchAlgorithmException.
    • In line with changes in OpenSSL, the OpenSSLPBKDF now uses UTF-8 encoding.
    -

    2.15.4 Security Advisory

    +

    2.18.4 Security Advisory

    • As described in CVE-2020-28052, the OpenBSDBCrypt.checkPassword() method had a flaw in it due to a change for BC 1.65. BC 1.66 is also affected. The issue is fixed in BC 1.67. If you are using OpenBSDBCrypt.checkPassword() and you are using BC 1.65 or BC 1.66 we strongly advise moving to BC 1.67 or later.
    -

    2.16.1 Version

    +

    2.19.1 Version

    Release: 1.66
    Date:      2020, July 4th. -

    2.16.2 Defects Fixed

    +

    2.19.2 Defects Fixed

    • EdDSA verifiers now reset correctly after rejecting overly long signatures.
    • BCJSSE: SSLSession.getPeerCertificateChain could throw NullPointerException. This has been fixed.
    • @@ -603,7 +717,7 @@

      2.16.2 Defects Fixed

    • For a few values the cSHAKE implementation would add unnecessary pad bytes where the N and S strings produced encoded data that was block aligned. This has been fixed.
    • There were a few circumstances where Argon2BytesGenerator might hit an unexpected null. These have been removed.
    -

    2.16.3 Additional Features and Functionality

    +

    2.19.3 Additional Features and Functionality

    • The qTESLA signature algorithm has been updated to v2.8 (20191108).
    • BCJSSE: Client-side OCSP stapling now supports status_request_v2 extension.
    • @@ -622,15 +736,15 @@

      2.16.3 Additional Features and Functionality

    • Performance of the Base64 encoder has been improved.
    • The PGPPublicKey class will now include direct key sigantures when checking for key expiry times.
    -

    2.16.4 Notes

    +

    2.19.4 Notes

    The qTESLA update breaks compatibility with previous versions. Private keys now include a hash of the public key at the end, and signatures are no longer interoperable with previous versions.

    -

    2.17.1 Version

    +

    2.20.1 Version

    Release: 1.65
    Date:      2020, March 31st. -

    2.17.2 Defects Fixed

    +

    2.20.2 Defects Fixed

    • DLExternal would encode using DER encoding for tagged SETs. This has been fixed.
    • ChaCha20Poly1305 could fail for large (>~2GB) files. This has been fixed.
    • @@ -642,7 +756,7 @@

      2.17.2 Defects Fixed

    • BCJSSE: Choice of credentials and signing algorithm now respect the peer's signature_algorithms extension properly.
    • BCJSSE: KeyManager for KeyStoreBuilderParameters no longer leaks memory.
    -

    2.17.3 Additional Features and Functionality

    +

    2.20.3 Additional Features and Functionality

    • LMS and HSS (RFC 8554) support has been added to the low level library and the PQC provider.
    • SipHash128 support has been added to the low level library and the JCE provider.
    • @@ -656,10 +770,10 @@

      2.17.3 Additional Features and Functionality

    • TLS: DSA in JcaTlsCrypto now falls back to stream signing to work around NoneWithDSA limitations in default provider.
    -

    2.18.1 Version

    +

    2.21.1 Version

    Release: 1.64
    Date:      2019, October 7th. -

    2.18.2 Defects Fixed

    +

    2.21.2 Defects Fixed

    • OpenSSH: Fixed padding in generated Ed25519 private keys.
    • Validation of headers in PemReader now looks for tailing dashes in header.
    • @@ -667,7 +781,7 @@

      2.18.2 Defects Fixed

    • Some compatibility issues around the signature encryption algorithm field in CMS SignedData and the GOST algorithms have been addressed.
    • GOST3410-2012-512 now uses the GOST3411-2012-256 as its KDF digest.
    -

    2.18.3 Additional Features and Functionality

    +

    2.21.3 Additional Features and Functionality

    • PKCS12: key stores containing only certificates can now be created without the need to provide passwords.
    • BCJSSE: Initial support for AlgorithmConstraints; protocol versions and cipher suites.
    • @@ -680,20 +794,20 @@

      2.18.3 Additional Features and Functionality

    • Support for Java 11's NamedParameterSpec class has been added (using reflection) to the EC and EdEC KeyPairGenerator implementations.
    -

    2.18.4 Removed Features and Functionality

    +

    2.21.4 Removed Features and Functionality

    • Deprecated ECPoint 'withCompression' tracking has been removed.
    -

    2.18.5 Security Advisory

    +

    2.21.5 Security Advisory

    • A change to the ASN.1 parser in 1.63 introduced a regression that can cause an OutOfMemoryError to occur on parsing ASN.1 data. We recommend upgrading to 1.64, particularly where an application might be parsing untrusted ASN.1 data from third parties.
    -

    2.19.1 Version

    +

    2.22.1 Version

    Release: 1.63
    Date:      2019, September 10th. -

    2.19.2 Defects Fixed

    +

    2.22.2 Defects Fixed

    • The ASN.1 parser would throw a large object exception for some objects which could be safely parsed. This has been fixed.
    • GOST3412-2015 CTR mode was unusable at the JCE level. This has been fixed.
    • @@ -712,7 +826,7 @@

      2.19.2 Defects Fixed

    • It is now possible to specify different S-Box parameters for the GOST 28147-89 MAC.
    -

    2.19.3 Additional Features and Functionality

    +

    2.22.3 Additional Features and Functionality

    • QTESLA is now updated with the round 2 changes. Note: the security catergories, and in some cases key generation and signatures, have changed. For people interested in comparison, the round 1 version is now moved to org.bouncycastle.pqc.crypto.qteslarnd1 - this package will be deleted in 1.64. Please keep in mind that QTESLA may continue to evolve.
    • Support has been added for generating Ed25519/Ed448 signed certificates.
    • @@ -725,10 +839,10 @@

      2.19.3 Additional Features and Functionality

    • The valid path for EST services has been updated to cope with the characters used in the Aruba clearpass EST implementation.
    -

    2.20.1 Version

    +

    2.23.1 Version

    Release: 1.62
    Date:      2019, June 3rd. -

    2.20.2 Defects Fixed

    +

    2.23.2 Defects Fixed

    • DTLS: Fixed infinite loop on IO exceptions.
    • DTLS: Retransmission timers now properly apply to flights monolithically.
    • @@ -745,7 +859,7 @@

      2.20.2 Defects Fixed

    • CertificateFactory now enforces presence of PEM headers when required.
    • A performance issue with RSA key pair generation that was introduced in 1.61 has been mostly eliminated.
    -

    2.20.3 Additional Features and Functionality

    +

    2.23.3 Additional Features and Functionality

    • Builders for X509 certificates and CRLs now support replace and remove extension methods.
    • DTLS: Added server-side support for HelloVerifyRequest.
    • @@ -766,10 +880,10 @@

      2.20.3 Additional Features and Functionality

    • Support for the Ethereum flavor of IES has been added to the lightweight API.
    -

    2.21.1 Version

    +

    2.24.1 Version

    Release: 1.61
    Date:      2019, February 4th. -

    2.21.2 Defects Fixed

    +

    2.24.2 Defects Fixed

    • Use of EC named curves could be lost if keys were constructed via a key factory and algorithm parameters. This has been fixed.
    • RFC3211WrapEngine would not properly handle messages longer than 127 bytes. This has been fixed.
    • @@ -790,7 +904,7 @@

      2.21.2 Defects Fixed

    • Several parsing issues related to the processing of CMP PKIPublicationInfo have been fixed.
    • The ECGOST curves for id-tc26-gost-3410-12-256-paramSetA and id-tc26-gost-3410-12-512-paramSetC had incorrect co-factors. These have been fixed.
    -

    2.21.3 Additional Features and Functionality

    +

    2.24.3 Additional Features and Functionality

    • The qTESLA signature algorithm has been added to PQC light-weight API and the PQC provider.
    • The password hashing function, Argon2 has been added to the lightweight API.
    • @@ -814,15 +928,15 @@

      2.21.3 Additional Features and Functionality

    • SM2 in public key cipher mode has been added to the provider API.
    • The BCFKSLoadStoreParameter has been extended to allow the use of certificates and digital signatures for verifying the integrity of BCFKS key stores.
    -

    2.21.4 Removed Features and Functionality

    +

    2.24.4 Removed Features and Functionality

    • Deprecated methods for EC point construction independent of curves have been removed.
    -

    2.22.1 Version

    +

    2.25.1 Version

    Release: 1.60
    Date:      2018, June 30 -

    2.22.2 Defects Fixed

    +

    2.25.2 Defects Fixed

    • Base64/UrlBase64 would throw an exception on a zero length string. This has been fixed.
    • Base64/UrlBase64 would throw an exception if there was whitespace in the last 4 characters. This has been fixed.
    • @@ -843,7 +957,7 @@

      2.22.2 Defects Fixed

    • In some situations the use of sm2p256v1 would result in "unknown curve name". This has been fixed.
    • CMP PollReqContent now supports multiple certificate request IDs.
    -

    2.22.3 Additional Features and Functionality

    +

    2.25.3 Additional Features and Functionality

    • TLS: Extended CBC padding is now optional (and disabled by default).
    • TLS: Now supports channel binding 'tls-server-end-point'.
    • @@ -871,16 +985,16 @@

      2.22.3 Additional Features and Functionality

    • Support has been added for the German BSI KAEG Elliptic Curve key agreement algorithm with X9.63 as the KDF to the JCE.
    • Support has been added for the German BSI KAEG Elliptic Curve session key KDF to the lightweight API.
    -

    2.22.4 Security Related Changes and CVE's Addressed by this Release

    +

    2.25.4 Security Related Changes and CVE's Addressed by this Release

    • CVE-2018-1000180: issue around primality tests for RSA key pair generation if done using only the low-level API.
    • CVE-2018-1000613: lack of class checking in deserialization of XMSS/XMSS^MT private keys with BDS state information.
    -

    2.23.1 Version

    +

    2.26.1 Version

    Release: 1.59
    Date:      2017, December 28 -

    2.23.2 Defects Fixed

    +

    2.26.2 Defects Fixed

    • Issues with using PQC based keys with the provided BC KeyStores have now been fixed.
    • ECGOST-2012 public keys were being encoded with the wrong OID for the digest parameter in the algorithm parameter set. This has been fixed.
    • @@ -894,7 +1008,7 @@

      2.23.2 Defects Fixed

    • An off-by-one error for the max N check for SCRYPT has been fixed. SCRYPT should now be compliant with RFC 7914.
    • ASN1GeneralizedTime will now accept a broader range of input strings.
    -

    2.23.3 Additional Features and Functionality

    +

    2.26.3 Additional Features and Functionality

    • GOST3410-94 private keys encoded using ASN.1 INTEGER are now accepted in private key info objects.
    • SCRYPT is now supported as a SecretKeyFactory in the provider and in the PKCS8 APIs
    • @@ -913,15 +1027,15 @@

      2.23.3 Additional Features and Functionality

    • A DEROtherInfo generator for key agreement using NewHope as the source of the shared private info has been added that can be used in conjunction with regular key agreement algorithms.
    • RFC 7748: Added low-level implementations of X25519 and X448.
    -

    2.23.4 Security Related Changes and CVE's Addressed by this Release

    +

    2.26.4 Security Related Changes and CVE's Addressed by this Release

    • CVE-2017-13098 ("ROBOT"), a Bleichenbacher oracle in TLS when RSA key exchange is negotiated. This potentially affected BCJSSE servers and any other TLS servers configured to use JCE for the underlying crypto - note the two TLS implementations using the BC lightweight APIs are not affected by this.
    -

    2.24.1 Version

    +

    2.27.1 Version

    Release: 1.58
    Date:      2017, August 18 -

    2.24.2 Defects Fixed

    +

    2.27.2 Defects Fixed

    • NewHope and SPHINCS keys are now correctly created off certificates by the BC provider.
    • Use of the seeded constructor with SecureRandom() and the BC provider in first position could cause a stack overflow error. This has been fixed.
    • @@ -935,7 +1049,7 @@

      2.24.2 Defects Fixed

    • A race condition that could occur inside the HybridSecureRandom on reseed and result in an exception has been fixed.
    • DTLS now supports records containing multiple handshake messages.
    -

    2.24.3 Additional Features and Functionality

    +

    2.27.3 Additional Features and Functionality

    • An implementation of GOST3410-2012 has been added to light weight API and the JCA provider.
    • Support for ECDH GOST3410-2012 and GOST3410-2001 have been added. The CMS API can also handle reading ECDH GOST3410 key transport messages.
    • @@ -955,16 +1069,16 @@

      2.24.3 Additional Features and Functionality

    • The new TLS API now supports RFC 7633 - X.509v3 TLS Feature Extension (e.g. "must staple"), enabled in default clients.
    • TLS exceptions have been made more directly informative.
    -

    2.24.4 Removed Features and Functionality

    +

    2.27.4 Removed Features and Functionality

    • Per RFC 7465, removed support for RC4 in the new TLS API.
    • Per RFC 7568, removed support for SSLv3 in the new TLS API.
    -

    2.25.1 Version

    +

    2.28.1 Version

    Release: 1.57
    Date:      2017, May 11 -

    2.25.2 Defects Fixed

    +

    2.28.2 Defects Fixed

    • A class cast exception for master certification removal in PGPPublicKey.removeCertification() by certification has been fixed.
    • GOST GOFB 28147-89 mode had an edge condition concerning the incorrect calculation of N4 (see section 6.1 of RFC 5830) affecting about 1% of IVs. This has been fixed.
    • @@ -981,7 +1095,7 @@

      2.25.2 Defects Fixed

    • EC FixedPointCombMultiplier avoids 'infinity' point in lookup tables, reducing timing side-channels.
    • Reuse of a Blake2b digest with a call to reset() rather than doFinal() could result in incorrect padding being introduced and the wrong digest result produced. This has been fixed.
    -

    2.25.3 Additional Features and Functionality

    +

    2.28.3 Additional Features and Functionality

    • ARIA (RFC 5794) is now supported by the provider and the lightweight API.
    • ARIA Key Wrapping (RFC 5649 style) is now supported by the provider and the lightweight API.
    • @@ -991,23 +1105,23 @@

      2.25.3 Additional Features and Functionality

    • A test client for EST which will interop with the 7030 test server at http://testrfc7030.com/ has been added to the general test module in the current source tree.
    • The BCJSSE provider now supports SSLContext.getDefault(), with very similar behaviour to the SunJSSE provider, including checks of the relevant javax.net.ssl.* system properties and auto-loading of jssecacerts or cacerts as the default trust store.
    -

    2.25.4 Security Related Changes

    +

    2.28.4 Security Related Changes

    • The default parameter sizes for DH and DSA are now 2048. If you have been relying on key pair generation without passing in parameters generated keys will now be larger.
    • Further work has been done on preventing accidental re-use of a GCM cipher without first changing its key or iv.
    -

    2.26.1 Version

    +

    2.29.1 Version

    Release: 1.56
    Date:      2016, December 23 -

    2.26.2 Defects Fixed

    +

    2.29.2 Defects Fixed

    • See section 2.15.4 for Security Defects.
    • Using unknown status with the ASN.1 CertStatus primitive could result in an IllegalArgumentException on construction. This has been fixed.
    • A potentional NullPointerException in a precomputation in WNafUtil has been removed.
    • PGPUtil.getDecoderStream() would throw something other than an IOException for empty and very small data. This has been fixed.
    -

    2.26.3 Additional Features and Functionality

    +

    2.29.3 Additional Features and Functionality

    • Support for the explicit setting of AlgorithmParameters has been added to the JceCMSContentEncryptorBuilder and the JceCMSMacCaculatorBuilder classes to allow configuration of the session cipher/MAC used.
    • EC, ECGOST3410, and DSTU4145 Public keys are now validated on construction in the JCA/JCE and the light weight API.
    • @@ -1023,7 +1137,7 @@

      2.26.3 Additional Features and Functionality

    • SHA-3 support has been added to BcDefaultDigestProvider.
    • A higher level TLS API and JSSE provider have been added to the project.
    -

    2.26.4 Security Related Changes and CVE's Addressed by this Release

    +

    2.29.4 Security Related Changes and CVE's Addressed by this Release

    • It is now possible to configure the provider to only import keys for specific named curves.
    • Work has been done to improve the "constant time" behaviour of the RSA padding mechanisms.
    • @@ -1042,15 +1156,15 @@

      2.26.3 Additional Features and Functionality

    • CVE-2016-1000346: Other party DH public key not fully validated. This can cause issues as invalid keys can be used to reveal details about the other party's private key where static Diffie-Hellman is in use. As of this release the key parameters are checked on agreement calculation.
    • CVE-2016-1000352: ECIES allows the use of unsafe ECB mode. This algorithm is now removed from the provider.
    -

    2.26.5 Security Advisory

    +

    2.29.5 Security Advisory

    • We consider the carry propagation bugs fixed in this release to have been exploitable in previous releases (1.51-1.55), for static ECDH, to reveal the long-term key, per "Practical realisation and elimination of an ECC-related software bug attack", Brumley et.al.. The most common case of this would be the non-ephemeral ECDH ciphersuites in TLS. These are not enabled by default in our TLS implementations, but they can be enabled explicitly by users. We recommend that users DO NOT enable static ECDH ciphersuites for TLS.
    -

    2.27.1 Version

    +

    2.30.1 Version

    Release: 1.55
    Date:      2016, August 18 -

    2.27.2 Defects Fixed

    +

    2.30.2 Defects Fixed

    • Issues with cloning of blake digests with salts and personalisation strings have been fixed.
    • The JceAsymmetricValueDecryptor in the CRMF package now attempts to recognise a wider range of parameters for the key wrapping algorithm, rather than relying on a default.
    • @@ -1071,7 +1185,7 @@

      2.27.2 Defects Fixed

    • Trying to use of non-default parameters for OAEP in CRMF would resort to the default parameter set. This has been fixed.
    • If the BC provider was not registered, creating a CertificateFactory would cause a new provider object to be created. This has been fixed.
    -

    2.27.3 Additional Features and Functionality

    +

    2.30.3 Additional Features and Functionality

    • The DANE API has been updated to reflect the latest standard changes.
    • The signature algorithm SPHINCS-256 has been added to the post-quantum provider (BCPQC). Support is in place for SHA-512 and SHA3-512 (using trees based around SHA512_256 and SHA3_256 respectively).
    • @@ -1089,10 +1203,10 @@

      2.27.3 Additional Features and Functionality

    • Additional search methods have been added to PGP public and secret key rings.
    -

    2.28.1 Version

    +

    2.31.1 Version

    Release: 1.54
    Date:      2015, December 29 -

    2.28.2 Defects Fixed

    +

    2.31.2 Defects Fixed

    • Blake2b-160, Blake2b-256, Blake2b-384, and Blake2b-512 are now actually in the provider and an issue with cloning Blake2b digests has been fixed.
    • PKCS#5 Scheme 2 using DESede CBC is now supported by the PKCS#12 implementation.
    • @@ -1101,7 +1215,7 @@

      2.28.2 Defects Fixed

    • It turns out, after advice one way and another that the NESSIE test vectors for Serpent are now what should be followed and that the vectors in the AES submission are regarded as an algorithm called Tnepres. The Serpent version now follows the NESSIE vectors, and the Tnepres cipher has been added to the provider and the lightweight API for compatibility.
    • Problems with DTLS record-layer version handling were resolved, making version negotiation work properly.
    -

    2.28.3 Additional Features and Functionality

    +

    2.31.3 Additional Features and Functionality

    • Camellia and SEED key wrapping are now supported for CMS key agreement
    • The BC TLS/DTLS code now includes a non-blocking API.
    • @@ -1111,19 +1225,19 @@

      2.28.3 Additional Features and Functionality

    • Support has been added to the CMS API for PKCS#7 ANY type encapsulated content where the encapsulated content is not an OCTET STRING.
    • PSSSigner in the lightweight API now supports fixed salts.
    -

    2.28.4 Security Advisory

    +

    2.31.4 Security Advisory

    • (D)TLS 1.2: Motivated by CVE-2015-7575, we have added validation that the signature algorithm received in DigitallySigned structures is actually one of those offered (in signature_algorithms extension or CertificateRequest). With our default TLS configuration, we do not believe there is an exploitable vulnerability in any earlier releases. Users that are customizing the signature_algorithms extension, or running a server supporting client authentication, are advised to double-check that they are not offering any signature algorithms involving MD5.
    -

    2.28.5 Notes

    +

    2.31.5 Notes

    If you have been using Serpent, you will need to either change to Tnepres, or take into account the fact that Serpent is now byte-swapped compared to what it was before.

    -

    2.29.1 Version

    +

    2.32.1 Version

    Release: 1.53
    Date:      2015, October 10 -

    2.29.2 Defects Fixed

    +

    2.32.2 Defects Fixed

    • The BC JCE cipher implementations could sometimes fail when used in conjunction with the JSSE and NIO. This has been fixed.
    • PGPPublicKey.getBitStrength() always returned 0 for EC keys. This has been fixed.
    • @@ -1148,7 +1262,7 @@

      2.29.2 Defects Fixed

    • Some decidedly odd argument casting in the PKIXCertPathValidator has been fixed to throw an InvalidAlgorithmParameterException.
    • Presenting an empty array of certificates to the PKIXCertPathValidator would cause an IndexOutOfRangeException instead of a CertPathValidatorException. This has been fixed.
    -

    2.29.3 Additional Features and Functionality

    +

    2.32.3 Additional Features and Functionality

    • It is now possible to specify that an unwrapped key must be usable by a software provider in the asymmetric unwrappers for CMS.
    • A Blake2b implementation has been added to the provider and lightweight API.
    • @@ -1164,15 +1278,15 @@

      2.29.3 Additional Features and Functionality

    • The PKCS#12 key store will now garbage collect orphaned certificates on saving.
    • Caching for ASN.1 ObjectIdentifiers has been rewritten to make use of an intern method. The "usual suspects" are now interned automatically, and the cache is used by the parser. Other OIDs can be added to the cache by calling ASN1ObjectIdentifier.intern().
    -

    2.29.4 Notes

    +

    2.32.4 Notes

    It turns out there was a similar, but different, issue in Crypto++ to the BC issue with ECIES. Crypto++ 6.0 now offers a corrected version of ECIES which is compatible with that which is now in BC.

    -

    2.30.1 Version

    +

    2.33.1 Version

    Release: 1.52
    Date:      2015, March 2 -

    2.30.2 Defects Fixed

    +

    2.33.2 Defects Fixed

    • GenericSigner in the lightweight API would fail if the digest started with a zero byte, occasionally causing a TLS negotiation to fail. This has been fixed.
    • Some BC internal classes expected the BC provider to be accessible within the provider. This has been fixed.
    • @@ -1189,7 +1303,7 @@

      2.30.2 Defects Fixed

    • A badly formed issuer in a X.509 certificate could cause a null pointer exception in X509CertificateHolder.toString(). This has been fixed.
    • CMSSignedData.verifySignatures() could fail on a correct counter signature due to a mismatch of the SID. This has been fixed.
    -

    2.30.3 Additional Features and Functionality

    +

    2.33.3 Additional Features and Functionality

    • The CMP support class CMPCertificate restricted the types of certificates that could be added. A more flexible method has been introduced to allow for other certificate types.
    • Support classes have be added for DNS-based Authentication of Named Entities (DANE) to the PKIX distribution.
    • @@ -1217,15 +1331,15 @@

      2.30.3 Additional Features and Functionality

    • Support for some JDK1.5+ language features has finally made its way into the repository.
    • A load store parameter, PKCS12StoreParameter, has been added to support DER only encoding of PKCS12 key stores.
    -

    2.30.4 Security Advisory

    +

    2.33.4 Security Advisory

    • The CTR DRBGs would not populate some bytes in the requested block of random bytes if the size of the block requested was not an exact multiple of the block size of the underlying cipher being used in the DRBG. If you are using the CTR DRBGs with "odd" keysizes, we strongly advise upgrading to this release, or contacting us for a work around.
    -

    2.31.1 Version

    +

    2.34.1 Version

    Release: 1.51
    Date:      2014, July 28 -

    2.31.2 Defects Fixed

    +

    2.34.2 Defects Fixed

    • The AEAD GCM AlgorithmParameters object was unable to return a GCMParameterSpec object. This has been fixed.
    • Cipher.getIV() was returning null for AEAD mode ciphers. This has been fixed.
    • @@ -1240,7 +1354,7 @@

      2.31.2 Defects Fixed

    • PKCS#12 files containing keys/certificates with empty attribute sets attached to them no longer cause an ArrayIndexOutOfBoundsException to be thrown.
    • Issues with certificate verification and server side DTLS/TLS 1.2 have now been fixed.
    -

    2.31.3 Additional Features and Functionality

    +

    2.34.3 Additional Features and Functionality

    • The range of key algorithm names that will be interpreted by KeyAgreement.generateSecret() has been expanded for ECDH derived algorithms in the provider. A KeyAgreement of ECDHwithSHA1KDF can now be explicitly created.
    • ECIES now supports the use of IVs with the underlying block cipher and CBC mode in both the lightweight and the JCE APIs.
    • @@ -1267,17 +1381,17 @@

      2.31.3 Additional Features and Functionality

    • Full support is now provided for client-side auth in the D/TLS server code.
    • Compatibility issues with some OSGI containers have been addressed.
    -

    2.31.4 Notes

    +

    2.34.4 Notes

    • Support for NTRUSigner has been deprecated as the algorithm has been withdrawn.
    • Some changes have affected the return values of some methods. If you are migrating from an earlier release, it is recommended to recompile before using this release.
    • There has been further clean out of deprecated methods in this release. If your code has previously been flagged as using a deprecated method you may need to change it. The OpenPGP API is the most heavily affected.
    -

    2.32.1 Version

    +

    2.35.1 Version

    Release: 1.50
    Date:      2013, December 3 -

    2.32.2 Defects Fixed

    +

    2.35.2 Defects Fixed

    • The DualECSP800DRBG sometimes truncated the last block in the generated stream incorrectly. This has been fixed.
    • Keys produced from RSA certificates with specialised parameters would lose the parameter settings. This has been fixed.
    • @@ -1291,7 +1405,7 @@

      2.32.2 Defects Fixed

    • Default RC2 parameters for 40 bit RC2 keys in CMSEnvelopedData were encoding incorrectly. This has been fixed.
    • In case of a long hash the DSTU4145 implementation would sometimes remove one bit too much during truncation. This has been fixed.
    -

    2.32.3 Additional Features and Functionality

    +

    2.35.3 Additional Features and Functionality

    • Additional work has been done on CMS recipient generation to simplify the generation of OAEP encrypted messages and allow for non-default parameters.
    • OCB implementation updated to account for changes in draft-irtf-cfrg-ocb-03.
    • @@ -1311,7 +1425,7 @@

      2.32.3 Additional Features and Functionality

    • The JDK 1.5+ provider will now recognise and use GCMParameterSpec if it is run in a 1.7 JVM.
    • Client side support and some server side support has been added for TLS/DTLS 1.2.
    -

    2.32.4 Notes

    +

    2.35.4 Notes

    • org.bouncycastle.crypto.DerivationFunction is now a base interface, the getDigest() method appears on DigestDerivationFunction.
    • Recent developments at NIST indicate the SHA-3 may be changed before final standardisation. Please bare this in mind if you are using it.
    • @@ -1321,10 +1435,10 @@

      2.32.4 Notes

    • ECDH support for OpenPGP should still be regarded as experimental. It is still possible there will be compliance issues with other implementations.
    -

    2.33.1 Version

    +

    2.36.1 Version

    Release: 1.49
    Date:      2013, May 31 -

    2.33.2 Defects Fixed

    +

    2.36.2 Defects Fixed

    • Occasional ArrayOutOfBounds exception in DSTU-4145 signature generation has been fixed.
    • The handling of escaped characters in X500 names is much improved.
    • @@ -1335,7 +1449,7 @@

      2.33.2 Defects Fixed

    • PEMParser would throw a NullPointerException if it ran into explicit EC curve parameters, it would also throw an Exception if the named curve was not already defined. The parser now returns X9ECParmameters for explicit parameters and returns an ASN1ObjectIdentifier for a named curve.
    • The V2TBSCertListGenerator was adding the wrong date type for CRL invalidity date extensions. This has been fixed.
    -

    2.33.3 Additional Features and Functionality

    +

    2.36.3 Additional Features and Functionality

    • A SecretKeyFactory has been added that enables use of PBKDF2WithHmacSHA.
    • Support has been added to PKCS12 KeyStores and PfxPdu to handle PKCS#5 encrypted private keys.
    • @@ -1364,16 +1478,16 @@

      2.33.3 Additional Features and Functionality

    • A basic commitment package has been introduced into the lightweight API containing a digest based commitment scheme.
    • It is now possible to set the NotAfter and NotBefore date in the CRMF CertificateRequestMessageBuilder class.
    -

    2.33.4 Notes

    +

    2.36.4 Notes

    • The NTRU implementation has been moved into the org.bouncycastle.pqc package hierarchy.
    • The change to PEMParser to support explicit EC curves is not backward compatible. If you run into a named curve you need to use org.bouncycastle.asn1.x9.ECNamedCurveTable.getByOID() to look the curve up if required.
    -

    2.34.1 Version

    +

    2.37.1 Version

    Release: 1.48
    Date:      2013, February 10 -

    2.34.2 Defects Fixed

    +

    2.37.2 Defects Fixed

    • Occasional key compatibility issues in IES due to variable length keys have been fixed.
    • PEMWriter now recognises the new PKCS10CertificationRequest object.
    • @@ -1384,7 +1498,7 @@

      2.34.2 Defects Fixed

    • The BC SSL implementation has been modified to deal with the "Lucky Thirteen" attack.
    • A regression in 1.47 which prevented key wrapping with regular symmetric PBE algorihtms has been fixed.
    -

    2.34.3 Additional Features and Functionality

    +

    2.37.3 Additional Features and Functionality

    • IES now supports auto generation of ephemeral keys in both the JCE and the lightweight APIs.
    • A new class PEMParser has been added to return the new CertificateHolder and Request objects introduced recently.
    • @@ -1399,10 +1513,10 @@

      2.34.3 Additional Features and Functionality

    • T61String now uses UTF-8 encoding by default rather than a simple 8 bit transform.
    -

    2.35.1 Version

    +

    2.38.1 Version

    Release: 1.47
    Date:      2012, March 30 -

    2.35.2 Defects Fixed

    +

    2.38.2 Defects Fixed

    • OpenPGP ID based certifications now support UTF-8. Note: this may mean that some old certifications no longer validate - if this happens a retry can be added using by converting the ID using Strings.fromByteArray(Strings.toByteArray(id)) - this will strip out the top byte in each character.
    • IPv4/IPv6 parsing in CIDR no longer assumes octet boundaries on a mask.
    • @@ -1419,7 +1533,7 @@

      2.35.2 Defects Fixed

    • Check of DH parameter L could reject some valid keys. This is now fixed.
    -

    2.35.3 Additional Features and Functionality

    +

    2.38.3 Additional Features and Functionality

    • Support is now provided via the RepeatedKey class to enable IV only re-initialisation in the JCE layer. The same effect can be acheived in the light weight API by using null as the key parameter when creating a ParametersWithIV object.
    • CRMF now supports empty poposkInput.
    • @@ -1439,15 +1553,15 @@

      2.35.3 Additional Features and Functionality

    • The J2ME lcrypto release now includes higher level classes for handling PKCS, CMS, CRMF, CMP, EAC, OpenPGP, and certificate generation.
    -

    2.35.4 Other notes

    +

    2.38.4 Other notes

    Okay, so we have had to do another release. The issue we have run into is that we probably didn't go far enough in 1.46, but we are now confident that moving from this release to 2.0 should be largely just getting rid of deprecated methods. While this release does change a lot it is relatively straight forward to do a port and we have a porting guide which explains the important ones. The area there has been the most change in is the ASN.1 library which was in bad need of a rewrite after 10 years of patching. On the bright side the rewrite did allow us to eliminate a few problems and bugs in the ASN.1 library, so we have some hope anyone porting to it will also have similar benefits. As with 1.46 the other point of emphasis has been making sure interface support is available for operations across the major APIs, so the lightweight API or some local role your own methods can be used instead for doing encryption and signing.

    -

    2.36.1 Version

    +

    2.39.1 Version

    Release: 1.46
    Date:      2011, February 23 -

    2.36.2 Defects Fixed

    +

    2.39.2 Defects Fixed

    • An edge condition in ECDSA which could result in an invalid signature has been fixed.
    • Exhaustive testing has been performed on the ASN.1 parser, eliminating another potential OutOfMemoryException and several escaping run time exceptions.
    • @@ -1456,7 +1570,7 @@

      2.36.2 Defects Fixed

    • DERGeneralizedTime.getDate() would produce incorrect results for fractional seconds. This has been fixed.
    • PSSSigner would produce incorrect results if the MGF digest and content digest were not the same. This has been fixed.
    -

    2.36.3 Additional Features and Functionality

    +

    2.39.3 Additional Features and Functionality

    • A null genTime can be passed to TimeStampResponseGenerator.generate() to generate timeNotAvailable error responses.
    • Support has been added for reading and writing of openssl PKCS#8 encrypted keys.
    • @@ -1473,7 +1587,7 @@

      2.36.3 Additional Features and Functionality

    • PGP public subkeys can now be separately decoded and encoded.
    • An IV can now be passed to an ISO9797Alg3Mac.
    -

    2.36.4 Other notes

    +

    2.39.4 Other notes

    Baring security patches we expect 1.46 will be the last of the 1.* releases. The next release of BC will be version 2.0. For this reason a lot of things in 1.46 that relate to CMS have been deprecated and @@ -1490,29 +1604,29 @@

    2.36.4 Other notes

  • The X509Name class will utlimately be replacde with the X500Name class, the getInstance() methods on both these classes allow conversion from one type to another.
  • The org.bouncycastle.cms.RecipientId class now has a collection of subclasses to allow for more specific recipient matching. If you are creating your own recipient ids you should use the constructors for the subclasses rather than relying on the set methods inherited from X509CertSelector. The dependencies on X509CertSelector and CertStore will be removed from the version 2 CMS API.
  • -

    2.37.1 Version

    +

    2.40.1 Version

    Release: 1.45
    Date:      2010, January 12 -

    2.37.2 Defects Fixed

    +

    2.40.2 Defects Fixed

    • OpenPGP now supports UTF-8 in file names for literal data.
    • The ASN.1 library was losing track of the stream limit in a couple of places, leading to the potential of an OutOfMemoryError on a badly corrupted stream. This has been fixed.
    • The provider now uses a privileged block for initialisation.
    • JCE/JCA EC keys are now serialisable.
    -

    2.37.3 Additional Features and Functionality

    +

    2.40.3 Additional Features and Functionality

    • Support for EC MQV has been added to the light weight API, provider, and the CMS/SMIME library.
    -

    2.37.4 Security Advisory

    +

    2.40.4 Security Advisory

    • This version of the provider has been specifically reviewed to eliminate possible timing attacks on algorithms such as GCM and CCM mode.
    -

    2.38.1 Version

    +

    2.41.1 Version

    Release: 1.44
    Date:      2009, October 9 -

    2.38.2 Defects Fixed

    +

    2.41.2 Defects Fixed

    • The reset() method in BufferedAsymmetricBlockCipher is now fully clearing the buffer.
    • Use of ImplicitlyCA with KeyFactory and Sun keyspec no longer causes NullPointerException.
    • @@ -1528,7 +1642,7 @@

      2.38.2 Defects Fixed

    • PKIXCertPathReviewer.getTrustAnchor() could occasionally cause a null pointer exception or an exception due to conflicting trust anchors. This has been fixed.
    • Handling of explicit CommandMap objects with the generation of S/MIME messages has been improved.
    -

    2.38.3 Additional Features and Functionality

    +

    2.41.3 Additional Features and Functionality

    • PEMReader/PEMWriter now support encrypted EC keys.
    • BC generated EC private keys now include optional fields required by OpenSSL.
    • @@ -1544,24 +1658,24 @@

      2.38.3 Additional Features and Functionality

    • Support for raw signatures has been extended to RSA and RSA-PSS in the provider. RSA support can be used in CMSSignedDataStreamGenerator to support signatures without signed attributes.
    -

    2.39.1 Version

    +

    2.42.1 Version

    Release: 1.43
    Date:      2009, April 13 -

    2.39.2 Defects Fixed

    +

    2.42.2 Defects Fixed

    • Multiple countersignature attributes are now correctly collected.
    • Two bugs in HC-128 and HC-256 related to sign extension and byte swapping have been fixed. The implementations now pass the latest ecrypt vector tests.
    • X509Name.hashCode() is now consistent with equals.
    -

    2.39.3 Security Advisory

    +

    2.42.3 Security Advisory

    • The effect of the sign extension bug was to decrease the key space the HC-128 and HC-256 ciphers were operating in and the byte swapping inverted every 32 bits of the generated stream. If you are using either HC-128 or HC-256 you must upgrade to this release.
    -

    2.40.1 Version

    +

    2.43.1 Version

    Release: 1.42
    Date:      2009, March 16 -

    2.40.2 Defects Fixed

    +

    2.43.2 Defects Fixed

    • A NullPointer exception which could be result from generating a diffie-hellman key has been fixed.
    • CertPath validation could occasionally mistakenly identify a delta CRL. This has been fixed.
    • @@ -1574,7 +1688,7 @@

      2.40.2 Defects Fixed

    • Multiplication by negative powers of two is fixed in BigInteger.
    • OptionalValidity now encodes correctly.
    -

    2.40.3 Additional Features and Functionality

    +

    2.43.3 Additional Features and Functionality

    • Support for NONEwithECDSA has been added.
    • Support for Grainv1 and Grain128 has been added.
    • @@ -1585,10 +1699,10 @@

      2.40.3 Additional Features and Functionality

    • Support for the SRP-6a protocol has been added to the lightweight API.
    -

    2.41.1 Version

    +

    2.44.1 Version

    Release: 1.41
    Date:      2008, October 1 -

    2.41.2 Defects Fixed

    +

    2.44.2 Defects Fixed

    • The GeneralName String constructor now supports IPv4 and IPv6 address parsing.
    • An issue with nested-multiparts with postamble for S/MIME that was causing signatures to fail verification has been fixed.
    • @@ -1599,7 +1713,7 @@

      2.41.2 Defects Fixed

    • Standard name "DiffieHellman" is now supported in the provider.
    • Better support for equality tests for '#' encoded entries has been added to X509Name.
    -

    2.41.3 Additional Features and Functionality

    +

    2.44.3 Additional Features and Functionality

    • Camellia is now 12.5% faster than previously.
    • A smaller version (around 8k compiled) of Camellia, CamelliaLightEngine has also been added.
    • @@ -1610,10 +1724,10 @@

      2.41.3 Additional Features and Functionality

    • Support for reading and extracting personalised certificates in PGP Secret Key rings has been added.
    -

    2.42.1 Version

    +

    2.45.1 Version

    Release: 1.40
    Date:      2008, July 12 -

    2.42.2 Defects Fixed

    +

    2.45.2 Defects Fixed

    • EAX mode ciphers were not resetting correctly after a doFinal/reset. This has been fixed.
    • The SMIME API was failing to verify doubly nested multipart objects in signatures correctly. This has been fixed.
    • @@ -1629,7 +1743,7 @@

      2.42.2 Defects Fixed

    • The '+' character can now be escaped or quoted in the constructor for X509Name, X509Prinicipal.
    • Fix to regression from 1.38: PKIXCertPathValidatorResult.getPublicKey was returning the wrong public key when the BC certificate path validator was used.
    -

    2.42.3 Additional Features and Functionality

    +

    2.45.3 Additional Features and Functionality

    • Galois/Counter Mode (GCM) has been added to the lightweight API and the JCE provider.
    • SignedPublicKeyAndChallenge and PKCS10CertificationRequest can now take null providers if you need to fall back to the default provider mechanism.
    • @@ -1637,15 +1751,15 @@

      2.42.3 Additional Features and Functionality

    • Unnecessary local ID attributes on certificates in PKCS12 files are now automatically removed.
    • The PKCS12 store types PKCS12-3DES-3DES and PKCS12-DEF-3DES-3DES have been added to support generation of PKCS12 files with both certificates and keys protected by 3DES.
    -

    2.42.4 Additional Notes

    +

    2.45.4 Additional Notes

    • Due to problems for some users caused by the presence of the IDEA algorithm, an implementation is no longer included in the default signed jars. Only the providers of the form bcprov-ext-*-*.jar now include IDEA.
    -

    2.43.1 Version

    +

    2.46.1 Version

    Release: 1.39
    Date:      2008, March 29 -

    2.43.2 Defects Fixed

    +

    2.46.2 Defects Fixed

    • A bug causing the odd NullPointerException has been removed from the LocalizedMessage class.
    • IV handling in CMS for the SEED and Camellia was incorrect. This has been fixed.
    • @@ -1659,7 +1773,7 @@

      2.43.2 Defects Fixed

    • A decoding issue with a mis-identified tagged object in CertRepMessage has been fixed.
    • \# is now properly recognised in the X509Name class.
    -

    2.43.3 Additional Features and Functionality

    +

    2.46.3 Additional Features and Functionality

    • Certifications associated with user attributes can now be created, verified and removed in OpenPGP.
    • API support now exists for CMS countersignature reading and production.
    • @@ -1674,10 +1788,10 @@

      2.43.3 Additional Features and Functionality

    • Support has been added to the provider for the VMPC MAC.
    -

    2.44.1 Version

    +

    2.47.1 Version

    Release: 1.38
    Date:      2007, November 7 -

    2.44.2 Defects Fixed

    +

    2.47.2 Defects Fixed

    • SMIME signatures containing non-standard quote-printable data could be altered by SMIME encryption. This has been fixed.
    • CMS signatures that do not use signed attributes were vulnerable to one of Bleichenbacher's RSA signature forgery attacks. This has been fixed.
    • @@ -1691,7 +1805,7 @@

      2.44.2 Defects Fixed

    • Overwriting entities in a PKCS#12 file was not fully compliant with the JavaDoc for KeyStore. This has been fixed.
    • TlsInputStream.read() could appear to return end of file when end of file had not been reached. This has been fixed.
    -

    2.44.3 Additional Features and Functionality

    +

    2.47.3 Additional Features and Functionality

    • Buffering in the streaming CMS has been reworked. Throughput is now usually higher and the behaviour is more predictable.
    • It's now possible to pass a table of hashes to a CMS detached signature rather than having to always pass the data.
    • @@ -1702,10 +1816,10 @@

      2.44.3 Additional Features and Functionality

    • CertPathReviewer has better handling for problem trust anchors.
    • Base64 encoder now does initial size calculations to try to improve resource usage.
    -

    2.45.1 Version

    +

    2.48.1 Version

    Release: 1.37
    Date:      2007, June 15 -

    2.45.2 Defects Fixed

    +

    2.48.2 Defects Fixed

    • The ClearSignedFileProcessor example for OpenPGP did not take into account trailing white space in the file to be signed. This has been fixed.
    • @@ -1719,7 +1833,7 @@

      2.45.2 Defects Fixed

    • The default private key length in the lightweght API for generated DiffieHellman parameters was absurdly small, this has been fixed.
    • Cipher.getParameters() for PBEwithSHAAndTwofish-CBC was returning null after intialisation. This has been fixed.
    -

    2.45.3 Additional Features and Functionality

    +

    2.48.3 Additional Features and Functionality

    • The block cipher mode CCM has been added to the provider and light weight API.
    • The block cipher mode EAX has been added to the provider and light weight API.
    • @@ -1738,10 +1852,10 @@

      2.45.3 Additional Features and Functionality

    • The JCE provider now supports RIPEMD160withECDSA.
    -

    2.46.1 Version

    +

    2.49.1 Version

    Release: 1.36
    Date:      2007, March 16 -

    2.46.2 Defects Fixed

    +

    2.49.2 Defects Fixed

    • DSA key generator now checks range and keysize.
    • Class loader issues with i18n classes should now be fixed.
    • @@ -1755,7 +1869,7 @@

      2.46.2 Defects Fixed

    • Some surrogate pairs were not assembled correctly by the UTF-8 decoder. This has been fixed.
    • Alias resolution in PKCS#12 is now case insensitive.
    -

    2.46.3 Additional Features and Functionality

    +

    2.49.3 Additional Features and Functionality

    • CMS/SMIME now supports basic EC KeyAgreement with X9.63.
    • CMS/SMIME now supports RFC 3211 password based encryption.
    • @@ -1771,10 +1885,10 @@

      2.46.3 Additional Features and Functionality

    • DSASigner now handles long messages. SHA2 family digest support for DSA has been added to the provider.
    -

    2.47.1 Version

    +

    2.50.1 Version

    Release: 1.35
    Date:      2006, December 16 -

    2.47.2 Defects Fixed

    +

    2.50.2 Defects Fixed

    • Test data files are no longer in the provider jars.
    • SMIMESignedParser now handles indefinite length data in SignerInfos.
    • @@ -1789,7 +1903,7 @@

      2.47.2 Defects Fixed

    • The IESEngine could incorrectly encrypt data when used in block cipher mode. This has been fixed.
    • An error in the encoding of the KEKRecipientInfo has been fixed. Compatability warning: this may mean that versions of BC mail prior to 1.35 will have trouble processing KEK messages produced by 1.35 or later.
    -

    2.47.3 Additional Features and Functionality

    +

    2.50.3 Additional Features and Functionality

    • Further optimisations to elliptic curve math libraries.
    • API now incorporates a CertStore which should be suitable for use with LDAP.
    • @@ -1811,10 +1925,10 @@

      2.47.3 Additional Features and Functionality

    • PGP packet streams can now be closed off using close() on the returned stream as well as closing the generator.
    -

    2.48.1 Version

    +

    2.51.1 Version

    Release: 1.34
    Date:      2006, October 2 -

    2.48.2 Defects Fixed

    +

    2.51.2 Defects Fixed

    • Endianess of integer conversion in KDF2BytesGenerator was incorrect. This has been fixed.
    • Generating critical signature subpackets in OpenPGP would result in a zero packet tag. This has been fixed. @@ -1826,7 +1940,7 @@

      2.48.2 Defects Fixed

    • PGP Identity strings were only being interpreted as ASCII rather than UTF-8. This has been fixed.
    • CertificateFactory.generateCRLs now returns a Collection rather than null.
    -

    2.48.3 Additional Features and Functionality

    +

    2.51.3 Additional Features and Functionality

    • An ISO18033KDFParameters class had been added to support ISO18033 KDF generators.
    • An implemention of the KDF1 bytes generator algorithm has been added. @@ -1846,16 +1960,16 @@

      2.48.3 Additional Features and Functionality

    • Performance of the prime number generation in the BigInteger library has been further improved.
    • In line with RFC 3280 section 4.1.2.4 DN's are now encoded using UTF8String by default rather than PrintableString.
    -

    2.48.4 Security Advisory

    +

    2.51.4 Security Advisory

    • If you are using public exponents with the value three you *must* upgrade to this release, otherwise it will be possible for attackers to exploit some of Bleichenbacher's RSA signature forgery attacks on your applications.
    -

    2.49.1 Version

    +

    2.52.1 Version

    Release: 1.33
    Date:      2006, May 3 -

    2.49.2 Defects Fixed

    +

    2.52.2 Defects Fixed

    • OCSPResponseData was including the default version in its encoding. This has been fixed.
    • BasicOCSPResp.getVersion() would throw a NullPointer exception if called on a default version response. This has been fixed. @@ -1864,7 +1978,7 @@

      2.49.2 Defects Fixed

    • ArmoredInputStream was not closing the underlying stream on close. This has been fixed.
    • Small base64 encoded strings with embedded white space could decode incorrectly using the Base64 class. This has been fixed.
    -

    2.49.3 Additional Features and Functionality

    +

    2.52.3 Additional Features and Functionality

    • The X509V2CRLGenerator now supports adding general extensions to CRL entries.
    • A RoleSyntax implementation has been added to the x509 ASN.1 package, and the AttributeCertificateHolder class now support the IssuerSerial option. @@ -1872,10 +1986,10 @@

      2.49.3 Additional Features and Functionality

    • DERUTF8String now supports surrogate pairs.
    -

    2.50.1 Version

    +

    2.53.1 Version

    Release: 1.32
    Date:      2006, March 27 -

    2.50.2 Defects Fixed

    +

    2.53.2 Defects Fixed

    • Further work has been done on RFC 3280 compliance.
    • The ASN1Sequence constructor for SemanticsInformation would sometimes throw a ClassCastException on reconstruction an object from a byte stream. This has been fixed. @@ -1892,7 +2006,7 @@

      2.50.2 Defects Fixed

    • OpenPGP clear text signatures containing '\r' as line separators were not being correctly canonicalized. This has been fixed.
    -

    2.50.3 Additional Features and Functionality

    +

    2.53.3 Additional Features and Functionality

    • The ASN.1 library now includes classes for the ICAO Electronic Passport.
    • Support has been added to CMS and S/MIME for ECDSA. @@ -1901,16 +2015,16 @@

      2.50.3 Additional Features and Functionality

    • Support has been added for repeated attributes in CMS and S/MIME messages.
    • A wider range of RSA-PSS signature types is now supported for CRL and Certificate verification.
    -

    2.50.4 Possible compatibility issue

    +

    2.53.4 Possible compatibility issue

    • Previously elliptic curve keys and points were generated with point compression enabled by default. Owing to patent issues in some jurisdictions, they are now generated with point compression disabled by default.
    -

    2.51.1 Version

    +

    2.54.1 Version

    Release: 1.31
    Date:      2005, December 29 -

    2.51.2 Defects Fixed

    +

    2.54.2 Defects Fixed

    • getCriticalExtensionOIDs on an X.509 attribute certificate was returning the non-critical set. This has been fixed.
    • Encoding uncompressed ECDSA keys could occasionally introduce an extra leading zero byte. This has been fixed. @@ -1923,7 +2037,7 @@

      2.51.2 Defects Fixed

      This has been fixed.
    • OIDs with extremely large components would sometimes reencode with unnecessary bytes in their encoding. The optimal DER encoding will now be produced instead.
    -

    2.51.3 Additional Features and Functionality

    +

    2.54.3 Additional Features and Functionality

    • The SMIME package now supports the large file streaming model as well.
    • Additional ASN.1 message support has been added for RFC 3739 in the org.bouncycastle.x509.qualified package. @@ -1932,10 +2046,10 @@

      2.51.3 Additional Features and Functionality

    • CertPathValidator has been updated to better support path validation as defined in RFC 3280.
    -

    2.52.1 Version

    +

    2.55.1 Version

    Release: 1.30
    Date:      2005, September 18 -

    2.52.2 Defects Fixed

    +

    2.55.2 Defects Fixed

    • Whirlpool was calculating the wrong digest for 31 byte data and could throw an exception for some other data lengths. This has been fixed.
    • AlgorithmParameters for IVs were returning a default of RAW encoding of the parameters when they should have been returning an @@ -1947,7 +2061,7 @@

      2.52.2 Defects Fixed

    • KEKIdentifier would not handle OtherKeyAttribute objects correctly. This has been fixed.
    • GetCertificateChain on a PKCS12 keystore would return a single certificate chain rather than null if the alias passed in represented a certificate not a key. This has been fixed.
    -

    2.52.3 Additional Features and Functionality

    +

    2.55.3 Additional Features and Functionality

    • RSAEngine no longer assumes keys are byte aligned when checking for out of range input.
    • PGPSecretKeyRing.removeSecretKey and PGPSecretKeyRing.insertSecretKey have been added. @@ -1958,10 +2072,10 @@

      2.52.3 Additional Features and Functionality

    • Both the lightweight API and the provider now support the Camellia encryption algorithm.
    -

    2.53.1 Version

    +

    2.56.1 Version

    Release: 1.29
    Date:      2005, June 27 -

    2.53.2 Defects Fixed

    +

    2.56.2 Defects Fixed

    • HMac-SHA384 and HMac-SHA512 were not IETF compliant. This has been fixed.
    • The equals() method on ElGamalKeyParameters and DHKeyParameters in the lightweight API would sometimes @@ -1972,7 +2086,7 @@

      2.53.2 Defects Fixed

    • ISO9796 signatures for full recovered messsages could incorrectly verify for similar messages in some circumstances. This has been fixed.
    • The occasional problem with decrypting PGP messages containing compressed streams now appears to be fixed.
    -

    2.53.3 Additional Features and Functionality

    +

    2.56.3 Additional Features and Functionality

    • Support has been added for the OIDs and key generation required for HMac-SHA224, HMac-SHA256, HMac-SHA384, and HMac-SHA512. @@ -1980,16 +2094,16 @@

      2.53.3 Additional Features and Functionality

    • The provider and the lightweight API now support the GOST-28147-94 MAC algorithm.
    • Headers are now settable for PGP armored output streams.
    -

    2.53.4 Notes

    +

    2.56.4 Notes

    • The old versions of HMac-SHA384 and HMac-SHA512 can be invoked as OldHMacSHA384 and OldHMacSHA512, or by using the OldHMac class in the lightweight API.
    -

    2.54.1 Version

    +

    2.57.1 Version

    Release: 1.28
    Date:      2005, April 20 -

    2.54.2 Defects Fixed

    +

    2.57.2 Defects Fixed

    • Signatures on binary encoded S/MIME messages could fail to validate when correct. This has been fixed.
    • getExtensionValue() on CRL Entries were returning the encoding of the inner object, rather than the octet string. This has been fixed. @@ -2003,7 +2117,7 @@

      2.54.2 Defects Fixed

    • Filetype for S/MIME compressed messages was incorrect. This has been fixed.
    • BigInteger class can now create negative numbers from byte arrays.
    -

    2.54.3 Additional Features and Functionality

    +

    2.57.3 Additional Features and Functionality

    • S/MIME now does canonicalization on non-binary input for signatures.
    • Micalgs for the new SHA schemes are now supported. @@ -2014,7 +2128,7 @@

      2.54.3 Additional Features and Functionality

    • Support has been added for the creation of ECDSA certificate requests.
    • The provider and the light weight API now support the WHIRLPOOL message digest.
    -

    2.54.4 Notes

    +

    2.57.4 Notes

    • Patches for S/MIME binary signatures and canonicalization were actually applied in 1.27, but a couple of days after the release - if the class CMSProcessableBodyPartOutbound is present in the package org.bouncycastle.mail.smime you have the patched 1.27. We would recommend upgrading to 1.28 in any case @@ -2022,10 +2136,10 @@

      2.54.4 Notes

    • GOST private keys are probably not encoding correctly and can be expected to change.
    -

    2.55.1 Version

    +

    2.58.1 Version

    Release: 1.27
    Date:      2005, February 20 -

    2.55.2 Defects Fixed

    +

    2.58.2 Defects Fixed

    • Typos in the provider which pointed Signature algorithms SHA256WithRSA, SHA256WithRSAEncryption, SHA384WithRSA, SHA384WithRSAEncryption, SHA512WithRSA, and SHA512WithRSAEncryption at the PSS versions of the algorithms have been fixed. The correct names for the PSS algorithms are SHA256withRSAandMGF1, SHA384withRSAandMGF1, and SHA512withRSAandMGF1.
    • X509CertificateFactory failed under some circumstances to reset properly if the input stream being passed @@ -2039,7 +2153,7 @@

      2.55.2 Defects Fixed

    • TSP TimeStampToken was failing to validate time stamp tokens with the issuerSerial field set in the ESSCertID structure. This has been fixed.
    • Path validation in environments with frequently updated CRLs could occasionally reject a valid path. This has been fixed.
    -

    2.55.3 Additional Features and Functionality

    +

    2.58.3 Additional Features and Functionality

    • Full support has been added for the OAEPParameterSpec class to the JDK 1.5 povider.
    • Full support has been added for the PSSParameterSpec class to the JDK 1.4 and JDK 1.5 providers. @@ -2050,7 +2164,7 @@

      2.55.3 Additional Features and Functionality

    • The CertPath support classes now support PKCS #7 encoding.
    • Point compression can now be turned off when encoding elliptic curve keys.
    -

    2.55.4 Changes that may affect compatibility

    +

    2.58.4 Changes that may affect compatibility

    • org.bouncycastle.jce.interfaces.ElGamalKey.getParams() has been changed to getParameters() to avoid clashes with a JCE interface with the same method signature. @@ -2060,10 +2174,10 @@

      2.55.4 Changes that may affect compatibility

      were using these previously you should use SHA256WithRSAAndMGF1, SHA384WithRSAAndMGF1, or SHA512WithRSAAndMGF1.
    -

    2.56.1 Version

    +

    2.59.1 Version

    Release: 1.26
    Date:      2005, January 15 -

    2.56.2 Defects Fixed

    +

    2.59.2 Defects Fixed

    • The X.509 class UserNotice assumed some of the optional fields were not optional. This has been fixed.
    • BCPGInputStream would break on input packets of 8274 bytes in length. This has been fixed. @@ -2072,7 +2186,7 @@

      2.56.2 Defects Fixed

    • ASN1Sets now properly sort their contents when created from scratch.
    • A bug introduced in the CertPath validation in the last release which meant some certificate paths would validate if they were invalid has been fixed.
    -

    2.56.3 Additional Features and Functionality

    +

    2.59.3 Additional Features and Functionality

    • Support for JDK 1.5 naming conventions for OAEP encryption and PSS signing has been added.
    • Support for Time Stamp Protocol (RFC 3161) has been added. @@ -2082,15 +2196,15 @@

      2.56.3 Additional Features and Functionality

    • PBEWithMD5AndRC2, PBEWithSHA1AndRC2 now generate keys rather than exceptions.
    • The BigInteger implementation has been further optimised to take more advantage of the Montgomery number capabilities.
    -

    2.56.4 JDK 1.5 Changes

    +

    2.59.4 JDK 1.5 Changes

    • The JDK 1.5 version of the provider now supports the new Elliptic Curve classes found in the java.security packages. Note: while we have tried to preserve some backwards compatibility people using Elliptic curve are likely to find some minor code changes are required when moving code from JDK 1.4 to JDK 1.5 as the java.security APIs have changed.
    -

    2.57.1 Version

    +

    2.60.1 Version

    Release: 1.25
    Date:      2004, October 1 -

    2.57.2 Defects Fixed

    +

    2.60.2 Defects Fixed

    • In some situations OpenPGP would overread when a stream had been broken up into partial blocks. This has been fixed. @@ -2112,7 +2226,7 @@

      2.57.2 Defects Fixed

    • Parsing a message with a zero length body with SMIMESigned would cause an exception. This has been fixed.
    • Some versions of PGP use zeros in the data stream rather than a replication of the last two bytes of the iv as specified in the RFC to determine if the correct decryption key has been found. The decryption classes will now cope with both.
    -

    2.57.3 Additional Features and Functionality

    +

    2.60.3 Additional Features and Functionality

    • Support for extracting signatures based on PGP user attributes has been added to PGPPublicKey. @@ -2132,10 +2246,10 @@

      2.57.3 Additional Features and Functionality

    • OID components of up to 2^63 bits are now supported.
    -

    2.58.1 Version

    +

    2.61.1 Version

    Release: 1.24
    Date:      2004, June 12 -

    2.58.2 Defects Fixed

    +

    2.61.2 Defects Fixed

    • OpenPGP Secret key rings now parse key rings with user attribute packets in them correctly.
    • OpenPGP Secret key rings now parse key rings with GPG comment packets in them. @@ -2152,17 +2266,17 @@

      2.58.2 Defects Fixed

    • An encoding error introduced in 1.23 which affected generation of the KeyUsage extension has been fixed.
    -

    2.58.3 Additional Features and Functionality

    +

    2.61.3 Additional Features and Functionality

    • PKCS12 keystore now handles single key/certificate files without any attributes present.
    • Support for creation of PGPKeyRings incorporating sub keys has been added.
    • ZeroPadding for encrypting ASCII data has been added.
    -

    2.59.1 Version

    +

    2.62.1 Version

    Release: 1.23
    Date:      2004, April 10 -

    2.59.2 Defects Fixed

    +

    2.62.2 Defects Fixed

    • Reading a PGP Secret key file would sometimes cause a class cast exception. This has been fixed.
    • PGP will now read SecretKeys which are encrypted with the null algorithm. @@ -2177,7 +2291,7 @@

      2.59.2 Defects Fixed

    • X509Name class will now print names with nested pairs in component sets correctly.
    • RC4 now resets correctly on doFinal.
    -

    2.59.3 Additional Features and Functionality

    +

    2.62.3 Additional Features and Functionality

    • PGP V3 keys and V3 signature generation is now supported.
    • Collection classes have been added for representing files of PGP public and secret keys. @@ -2196,10 +2310,10 @@

      2.59.3 Additional Features and Functionality

    • DERGeneralizedTime getTime() method now handles a broader range of input strings.
    -

    2.60.1 Version

    +

    2.63.1 Version

    Release: 1.22
    Date:      2004, February 7 -

    2.60.2 Defects Fixed

    +

    2.63.2 Defects Fixed

    • Generating DSA signatures with PGP would cause a class cast exception, this has been fixed.
    • PGP Data in the 192 to 8383 byte length would sometimes be written with the wrong length header. This has been fixed. @@ -2209,7 +2323,7 @@

      2.60.2 Defects Fixed

    • PSS signature verification would fail approximately 0.5 % of the time on correct signatures. This has been fixed.
    • Encoding of CRL Distribution Points now always works.
    -

    2.60.3 Additional Features and Functionality

    +

    2.63.3 Additional Features and Functionality

    • Additional methods for getting public key information have been added to the PGP package.
    • Some support for user attributes and the image attribute tag has been added. @@ -2217,10 +2331,10 @@

      2.60.3 Additional Features and Functionality

    • Support for ElGamal encryption/decryption has been added to the PGP package.
    -

    2.61.1 Version

    +

    2.64.1 Version

    Release: 1.21
    Date:      2003, December 6 -

    2.61.2 Defects Fixed

    +

    2.64.2 Defects Fixed

    • The CertPath validator would fail for some valid CRLs. This has been fixed.
    • AES OIDS for S/MIME were still incorrect, this has been fixed. @@ -2228,17 +2342,17 @@

      2.61.2 Defects Fixed

    • The J2ME BigInteger class would sometimes go into an infinite loop generating prime numbers. This has been fixed.
    • DERBMPString.equals() would throw a class cast exception. This has been fixed.
    -

    2.61.3 Additional Features and Functionality

    +

    2.64.3 Additional Features and Functionality

    • PEMReader now handles public keys.
    • OpenPGP/BCPG should now handle partial input streams. Additional methods for reading subpackets off signatures.
    • The ASN.1 library now supports policy qualifiers and policy info objects.
    -

    2.62.1 Version

    +

    2.65.1 Version

    Release: 1.20
    Date:      2003, October 8 -

    2.62.2 Defects Fixed

    +

    2.65.2 Defects Fixed

    • BigInteger toString() in J2ME/JDK1.0 now produces same output as the Sun one.
    • RSA would throw a NullPointer exception with doFinal without arguments. This has been fixed. @@ -2248,7 +2362,7 @@

      2.62.2 Defects Fixed

    • AES OIDS were incorrect, this has been fixed.
    • In some cases BC generated private keys would not work with the JSSE. This has been fixed.
    -

    2.62.3 Additional Features and Functionality

    +

    2.65.3 Additional Features and Functionality

    • Support for reading/writing OpenPGP public/private keys and OpenPGP signatures has been added.
    • Support for generating OpenPGP PBE messages and public key encrypted messages has been added. @@ -2256,10 +2370,10 @@

      2.62.3 Additional Features and Functionality

    • Addition of a Null block cipher to the light weight API.
    -

    2.63.1 Version

    +

    2.66.1 Version

    Release: 1.19
    Date:      2003, June 7 -

    2.63.2 Defects Fixed

    +

    2.66.2 Defects Fixed

    • The PKCS12 store would throw an exception reading PFX files that had attributes with no values. This has been fixed.
    • RSA Private Keys would not serialise if they had PKCS12 bag attributes attached to them, this has been fixed. @@ -2267,7 +2381,7 @@

      2.63.2 Defects Fixed

    • ASN1 parser would sometimes mistake an implicit null for an implicit empty sequence. This has been fixed.
    -

    2.63.3 Additional Features and Functionality

    +

    2.66.3 Additional Features and Functionality

    • S/MIME and CMS now support the draft standard for AES encryption.
    • S/MIME and CMS now support setable key sizes for the standard algorithms. @@ -2279,10 +2393,10 @@

      2.63.3 Additional Features and Functionality

      in order to find algorithms.
    -

    2.64.1 Version

    +

    2.67.1 Version

    Release: 1.18
    Date:      2003, February 8 -

    2.64.2 Defects Fixed

    +

    2.67.2 Defects Fixed

    • DESKeySpec.isParityAdjusted in the clean room JCE could go into an infinite loop. This has been fixed. @@ -2293,7 +2407,7 @@

      2.64.2 Defects Fixed

    • Seeding with longs in the SecureRandom for the J2ME and JDK 1.0, only used 4 bytes of the seed value. This has been fixed.
    -

    2.64.3 Additional Features and Functionality

    +

    2.67.3 Additional Features and Functionality

    • The X.509 OID for RSA is now recognised by the provider as is the OID for RSA/OAEP.
    • Default iv's for DES are now handled correctly in CMS. @@ -2305,10 +2419,10 @@

      2.64.3 Additional Features and Functionality

      Sun BigInteger library.
    -

    2.65.1 Version

    +

    2.68.1 Version

    Release: 1.17
    Date:      2003, January 8 -

    2.65.2 Defects Fixed

    +

    2.68.2 Defects Fixed

    • Reuse of an CMSSignedObject could occasionally result in a class cast exception. This has been fixed. @@ -2319,7 +2433,7 @@

      2.65.2 Defects Fixed

    • The DERObject constructor in OriginatorIdentifierOrKey was leaving the id field as null. This has been fixed.
    -

    2.65.3 Additional Functionality and Features

    +

    2.68.3 Additional Functionality and Features

    • RC2 now supports the full range of parameter versions and effective key sizes. @@ -2339,10 +2453,10 @@

      2.65.3 Additional Functionality and Features

      string to OID conversion.
    -

    2.66.1 Version

    +

    2.69.1 Version

    Release: 1.16
    Date:      2002, November 30 -

    2.66.2 Defects Fixed

    +

    2.69.2 Defects Fixed

    • CRLS were only working for UTC time constructed Time objects, this has been fixed. @@ -2356,7 +2470,7 @@

      2.66.2 Defects Fixed

      to throw a NullPointerException at the wrong time.
    • Macs now clone correctly in the clean room JCE.
    -

    2.66.3 Additional Functionality and Features

    +

    2.69.3 Additional Functionality and Features

    • PGPCFB support has been added to the provider and the lightweight API.
    • There are now three versions of the AESEngine, all faster than before, @@ -2374,10 +2488,10 @@

      2.66.3 Additional Functionality and Features

      and to support multiple recipients/signers.
    -

    2.67.1 Version

    +

    2.70.1 Version

    Release: 1.15
    Date:      2002, September 6 -

    2.67.2 Defects Fixed

    +

    2.70.2 Defects Fixed

    • The base string for the oids in asn1.x509.KeyPurposeId was incorrect. This has been fixed. @@ -2400,7 +2514,7 @@

      2.67.2 Defects Fixed

      The local name now takes precedence.
    • ReasonFlags now correctly encodes.
    -

    2.67.3 Additional Functionality and Features

    +

    2.70.3 Additional Functionality and Features

    • The PKCS12 key store now handles key bags in encryptedData bags.
    • The X509NameTokenizer now handles for '\' and '"' characters. @@ -2409,10 +2523,10 @@

      2.67.3 Additional Functionality and Features

    • Both the provider and the lightweight library now support a basic SIC mode for block ciphers.
    -

    2.68.1 Version

    +

    2.71.1 Version

    Release: 1.14
    Date:      2002, June 17 -

    2.68.2 Defects Fixed

    +

    2.71.2 Defects Fixed

    • there was a bug in the BigInteger right shifting for > 31 bit shifts. This has been fixed. @@ -2433,7 +2547,7 @@

      2.68.2 Defects Fixed

    • asn1.x509.ExtendedKeyUsage used to throw a null pointer exception on construction. This has been fixed.
    -

    2.68.3 Additional Functionality and Features

    +

    2.71.3 Additional Functionality and Features

    • The BigInteger library now uses Montgomery numbers for modPow and is substantially faster. @@ -2447,10 +2561,10 @@

      2.68.3 Additional Functionality and Features

      object identifiers.
    -

    2.69.1 Version

    +

    2.72.1 Version

    Release: 1.13
    Date:      2002, April 19 -

    2.69.2 Defects Fixed

    +

    2.72.2 Defects Fixed

    • The TBSCertificate object in the ASN.1 library now properly implements the Time object, rather returning UTC time. @@ -2459,7 +2573,7 @@

      2.69.2 Defects Fixed

    • toByteArray in the big integer class was not always producing correct results for negative numbers. This has been Fixed.
    -

    2.69.3 Additional Functionality and Features

    +

    2.72.3 Additional Functionality and Features

    • The key to keySpec handling of the secret key factories has been improved.
    • There is now a SMIME implementation and a more complete CMS @@ -2474,10 +2588,10 @@

      2.69.3 Additional Functionality and Features

      length certificate chains for signing keys.
    -

    2.70.1 Version

    +

    2.73.1 Version

    Release: 1.12
    Date:      2002, February 8 -

    2.70.2 Defects Fixed

    +

    2.73.2 Defects Fixed

    • The ASN.1 library was unable to read an empty set object. This has been fixed.
    • Returning sets of critical and non-critical extensions on X.509 certificates could result in a null pointer exception if the certificate had no extensions. This has been fixed. @@ -2496,7 +2610,7 @@

      2.70.2 Defects Fixed

    • the IV algorithm parameters class would improperly throw an exception on initialisation. This has been fixed.
    -

    2.70.3 Additional Functionality and Features

    +

    2.73.3 Additional Functionality and Features

    • The AESWrap ciphers will now take IV's.
    • The DES-EDEWrap algorithm described in https://www.ietf.org/internet-drafts/draft-ietf-smime-key-wrap-01.txt is now supported. @@ -2510,10 +2624,10 @@

      2.70.3 Additional Functionality and Features

      for details).
    -

    2.71.1 Version

    +

    2.74.1 Version

    Release: 1.11
    Date:      2001, December 10 -

    2.71.2 Defects Fixed

    +

    2.74.2 Defects Fixed

    • X9.23 padding of MACs now works correctly with block size aligned data.
    • Loading a corrupted "UBER" key store would occasionally cause the @@ -2539,7 +2653,7 @@

      2.71.2 Defects Fixed

      extensions. This has been fixed.
    • The NetscapeCert type bits were reversed! This has been fixed.
    -

    2.71.3 Additional Functionality and Features

    +

    2.74.3 Additional Functionality and Features

    • The lightweight API and the JCE provider now support ElGamal.
    • X509Principal, and X509Name now supports the "DC" attribute and the @@ -2553,7 +2667,7 @@

      2.71.3 Additional Functionality and Features

    • Elliptic curve routines now handle uncompressed points as well as the compressed ones.
    -

    2.71.4 Other changes

    +

    2.74.4 Other changes

    • As the range of public key types supported has expanded the getPublicKey method on the SubjectPublicKeyInfo class is not always going to work. The @@ -2561,10 +2675,10 @@

      2.71.4 Other changes

      throws an IOException if there is a problem.
    -

    2.72.1 Version

    +

    2.75.1 Version

    Release: 1.10
    Date:      2001, October 20 -

    2.72.2 Defects Fixed

    +

    2.75.2 Defects Fixed

    • The PKCS12 Key Store now interoperates with the JDK key tool. Note: this does mean the the key name passed to the setKeyEntry calls has become significant. @@ -2572,7 +2686,7 @@

      2.72.2 Defects Fixed

      has been fixed.
    • The ASN.1 input streams now handle zero-tagged zero length objects correctly.
    -

    2.72.3 Additional Functionality and Features

    +

    2.75.3 Additional Functionality and Features

    • The JCE Provider and the lightweight API now support Serpent, CAST5, and CAST6.
    • The JCE provider and the lightweight API now has an implementation of ECIES. @@ -2582,10 +2696,10 @@

      2.72.3 Additional Functionality and Features

    • Support for the generation of PKCS10 certification requests has been added.
    -

    2.73.1 Version

    +

    2.76.1 Version

    Release: 1.09
    Date:      2001, October 6 -

    2.73.2 Defects Fixed

    +

    2.76.2 Defects Fixed

    • failure to pass in an RC5 parameters object now results in an exception at the upper level of the JCE, rather than falling over in the lightweight @@ -2598,7 +2712,7 @@

      2.73.2 Defects Fixed

    • In some cases the ASN.1 library wouldn't handle implicit tagging properly. This has been fixed.
    -

    2.73.3 Additional Functionality and Features

    +

    2.76.3 Additional Functionality and Features

    • Support for RC5-64 has been added to the JCE.
    • ISO9796-2 signatures have been added to the JCE and lightweight API. @@ -2622,10 +2736,10 @@

      2.73.3 Additional Functionality and Features

      resource hungry and faster - whether it's fast enough remains to be seen!
    -

    2.74.1 Version

    +

    2.77.1 Version

    Release: 1.08
    Date:      2001, September 9 -

    2.74.2 Defects Fixed

    +

    2.77.2 Defects Fixed

    • It wasn't possible to specify an ordering for distinguished names in X509 certificates. This is now supported. @@ -2636,7 +2750,7 @@

      2.74.2 Defects Fixed

    • The netscape certificate request class wouldn't compile under JDK 1.1. This has been fixed.
    -

    2.74.3 Additional Functionality and Features

    +

    2.77.3 Additional Functionality and Features

    • ISO 9796-1 padding is now supported with RSA in the lightweight API and the JCE. @@ -2650,10 +2764,10 @@

      2.74.3 Additional Functionality and Features

      this is fixed.
    -

    2.75.1 Version

    +

    2.78.1 Version

    Release: 1.07
    Date:      2001, July 9 -

    2.75.2 Defects Fixed

    +

    2.78.2 Defects Fixed

    • It turned out that the setOddParity method in the DESParameter class was indeed doing something odd but not what was intended. This is now @@ -2664,10 +2778,10 @@

      2.75.2 Defects Fixed

      have a look in org.bouncycastle.jce.provider.JDKKeyStore lines 201-291.
    -

    2.76.1 Version

    +

    2.79.1 Version

    Release: 1.06
    Date:      2001, July 2 -

    2.76.2 Defects Fixed

    +

    2.79.2 Defects Fixed

    • Diffie-Hellman keys are now properly serialisable as well as encodable. @@ -2689,17 +2803,17 @@

      2.76.2 Defects Fixed

    • Resetting and resusing HMacs in the lightweight and heavyweight libraries caused a NullPointer exception. This has been fixed.
    -

    2.76.3 Additional Functionality

    +

    2.79.3 Additional Functionality

    • ISO10126Padding is now recognised explicitly for block ciphers as well.
    • The Blowfish implementation is now somewhat faster.
    -

    2.77.1 Version

    +

    2.80.1 Version

    Release: 1.05
    Date:      2001, April 17 -

    2.77.2 Defects Fixed

    +

    2.80.2 Defects Fixed

    • The DESEDE key generator can now be used to generate 2-Key-DESEDE keys as well as 3-Key-DESEDE keys. @@ -2710,22 +2824,22 @@

      2.77.2 Defects Fixed

    • The ASN.1 library was skipping explicitly tagged objects of zero length. This has been fixed.
    -

    2.77.3 Additional Functionality

    +

    2.80.3 Additional Functionality

    • There is now an org.bouncycastle.jce.netscape package which has a class in for dealing with Netscape Certificate Request objects.
    -

    2.77.4 Additional Notes

    +

    2.80.4 Additional Notes

    Concerning the PKCS12 fix: in a few cases this may cause some backward compatibility issues - if this happens to you, drop us a line at feedback-crypto@bouncycastle.org and we will help you get it sorted out.

    -

    2.78.1 Version

    +

    2.81.1 Version

    Release: 1.04
    Date:      2001, March 11 -

    2.78.2 Defects Fixed

    +

    2.81.2 Defects Fixed

    • Signatures generated by other providers that include optional null parameters in the AlgorithmIdentifier are now handled correctly by the @@ -2754,7 +2868,7 @@

      2.78.2 Defects Fixed

      hash table when the hash table constructor was called. This has been fixed.
    -

    2.78.3 Additional Functionality

    +

    2.81.3 Additional Functionality

    • Added Elliptic Curve DSA (X9.62) - ECDSA - to provider and lightweight library. @@ -2766,10 +2880,10 @@

      2.78.3 Additional Functionality

    • The certificate generators now support ECDSA and DSA certs as well.
    -

    2.79.1 Version

    +

    2.82.1 Version

    Release: 1.03
    Date:      2001, January 7 -

    2.79.2 Defects Fixed

    +

    2.82.2 Defects Fixed

    • CFB and OFB modes when specified without padding would insist on input being block aligned. When specified without padding CFB and OFB now behave in a compatible @@ -2779,29 +2893,29 @@

      2.79.2 Defects Fixed

      length as the plain text.
    -

    2.80.1 Version

    +

    2.83.1 Version

    Release: 1.02
    Date:      2000, November 7 -

    2.80.2 Defects Fixed

    +

    2.83.2 Defects Fixed

    • The RSA key pair generator occasionally produced keys 1 bit under the requested size. This is now fixed.
    -

    2.81.1 Version

    +

    2.84.1 Version

    Release: 1.01
    Date:      2000, October 15 -

    2.81.2 Defects Fixed

    +

    2.84.2 Defects Fixed

    • Buffered ciphers in lightweight library were not resetting correctly on a doFinal. This has been fixed.
    -

    2.82.1 Version

    +

    2.85.1 Version

    Release: 1.00
    Date:      2000, October 13 -

    2.82.2 Defects Fixed

    +

    2.85.2 Defects Fixed

    • JDK1.2 version now works with keytool for certificate generation. @@ -2816,7 +2930,7 @@

      2.82.2 Defects Fixed

    • Some DES PBE algorithms did not set the parity correctly in generated keys, this has been fixed.
    -

    2.82.3 Additional functionality

    +

    2.85.3 Additional functionality

    • Argument validation is much improved. diff --git a/docs/specifications.html b/docs/specifications.html index 3fa7536911..6b7c989165 100644 --- a/docs/specifications.html +++ b/docs/specifications.html @@ -468,7 +468,7 @@

      Key Encapsulation Mechanisms

      Classic McEliece128-256.CMCEKEMGenerator, CMCEKEMExtractorRound 4 FrodoKEM128-256.FrodoKEMGenerator, FrodoKEMExtractor HQC128-256.HQCKEMGenerator, HQCKEMExtractorRound 4 -Kyber128-256.KyberKEMGenerator, KyberKEMExtractorFinalist +ML-KEM128-256.MLKEMGenerator, MLKEMExtractorFinalist NTRU128-256.NTRUKEMGenerator, NTRUKEMExtractor NTRU Prime128-256.NTRULPRimeKEMGenerator, NTRULPRimeKEMExtractor
      SNTRUPrimeKEMGenerator, SNTRUPrimeKEMExtractor SABER128-256.SABERKEMGenerator, SABERKEMExtractor @@ -1008,10 +1008,10 @@

      Signature Algorithms

    • SHA256withSM2
    • SM3withSM2
    • LMS
    • -
    • Dilithium
    • +
    • ML-DSA
    • Falcon
    • Picnic
    • -
    • SPHINCS+
    • +
    • SLH-DSA
    • XMSS-SHA256
    • XMSS-SHA512
    • XMSS-SHAKE128
    • diff --git a/gradle.properties b/gradle.properties index 4e15dd08af..35de375e4f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ org.gradle.jvmargs=-Xmx2g -version=1.78.1 -maxVersion=1.79 +version=1.81 +maxVersion=1.82 org.gradle.java.installations.auto-detect=false org.gradle.java.installations.auto-download=false -org.gradle.java.installations.fromEnv=BC_JDK8,BC_JDK11,BC_JDK17,BC_JDK21 +org.gradle.java.installations.fromEnv=BC_JDK8,BC_JDK11,BC_JDK17 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index afba109285..d64cd49177 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3499ded5c1..a4413138c9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 65dcd68d65..1aa94a4269 100755 --- a/gradlew +++ b/gradlew @@ -83,10 +83,8 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,10 +131,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -144,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -197,11 +198,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/jmail/build.gradle b/jmail/build.gradle index 4f7c510e66..5a3bc6ef26 100644 --- a/jmail/build.gradle +++ b/jmail/build.gradle @@ -27,47 +27,43 @@ dependencies { implementation group: 'jakarta.mail', name: 'jakarta.mail-api', version: '2.0.1' implementation group: 'jakarta.activation', name: 'jakarta.activation-api', version: '2.0.0' - implementation files("$bc_prov") - implementation files("$bc_util") - implementation files("$bc_pkix") - implementation project(path: ':core') - - java9Implementation files("$bc_prov") - java9Implementation files("$bc_util") - java9Implementation files("$bc_pkix") + java9Implementation files(sourceSets.main.output.classesDirs) { builtBy compileJava } } +evaluationDependsOn(":prov") +evaluationDependsOn(":util") +evaluationDependsOn(":pkix") + task copyTask(type: Copy) { duplicatesStrategy = 'include' - from '../mail/src/main/java' - from 'src/main/java' - into 'build/src/main/java' + from '../mail/src/main' + from 'src/main' + into 'build/src/main' filter { String line -> (line.contains('javax.mail') || line.contains('javax.activation')) ? line.replace('javax.mail', 'jakarta.mail').replace('javax.activation', 'jakarta.activation') : line } } compileJava.dependsOn(copyTask) +processResources.dependsOn(copyTask) compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + options.release = 8 } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + + options.release = 9 + + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" + def util_jar="${project(":util").jar.outputs.files.getFiles().getAt(0)}" + def pkix_jar="${project(":pkix").jar.outputs.files.getFiles().getAt(0)}" + options.compilerArgs += [ - '--module-path', "$bc_prov${File.pathSeparator}$bc_util${File.pathSeparator}$bc_pkix${File.pathSeparator}${rootProject.projectDir}/libs/jakarta.mail-2.0.1.jar${File.pathSeparator}${rootProject.projectDir}/libs/jakarta.activation-api-2.0.0.jar" + '--module-path', "$prov_jar${File.pathSeparator}$util_jar${File.pathSeparator}$pkix_jar${File.pathSeparator}${rootProject.projectDir}/libs/jakarta.mail-2.0.1.jar${File.pathSeparator}${rootProject.projectDir}/libs/jakarta.activation-api-2.0.0.jar" ] options.sourcepath = files(['build/src/main/java', 'src/main/jdk1.9']) @@ -79,12 +75,14 @@ jar { into('META-INF/versions/9') { from sourceSets.java9.output } + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bcjmail') manifest.attributes('Bundle-SymbolicName': 'bcjmail') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': 'org.bouncycastle.mail.*') - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.mail.*,org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "org.bouncycastle.mail.*;version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,jakarta.*;resolution:=optional,!org.bouncycastle.mail.*,org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") } task sourcesJar(type: Jar) { @@ -114,3 +112,20 @@ test { forkEvery = 1; maxParallelForks = 8; } + +compileJava9Java.dependsOn([":prov:jar", ":util:jar",":pkix:jar"]) + +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcjmail-$vmrange" + from components.java + + + artifact(javadocJar) + artifact(sourcesJar) + } + + } +} diff --git a/jmail/src/main/resources/META-INF/mailcap b/jmail/src/main/resources/META-INF/mailcap new file mode 100644 index 0000000000..fcd430d137 --- /dev/null +++ b/jmail/src/main/resources/META-INF/mailcap @@ -0,0 +1,5 @@ +application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature +application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime +application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature +application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime +multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed diff --git a/jmail/src/main/resources/org/bouncycastle/mail/smime/validator/SignedMailValidatorMessages.properties b/jmail/src/main/resources/org/bouncycastle/mail/smime/validator/SignedMailValidatorMessages.properties new file mode 100644 index 0000000000..ccf8c96cdc --- /dev/null +++ b/jmail/src/main/resources/org/bouncycastle/mail/smime/validator/SignedMailValidatorMessages.properties @@ -0,0 +1,172 @@ +## constructor exception messages + +# Signature valid +SignedMailValidator.sigValid.title = Signature valid +SignedMailValidator.sigValid.text = Signature valid +SignedMailValidator.sigValid.summary = Signature valid +SignedMailValidator.sigValid.details = Signature valid + +# Signature invalid +SignedMailValidator.sigInvalid.title = Signature invalid +SignedMailValidator.sigInvalid.text = Signature invalid +SignedMailValidator.sigInvalid.summary = Signature invalid +SignedMailValidator.sigInvalid.details = Signature invalid + +# message is not signed +SignedMailValidator.noSignedMessage.title = Message is not signed +SignedMailValidator.noSignedMessage.text = SignedMailValidator: MimeMessage message is not a signed message. +SignedMailValidator.noSignedMessage.summary = SignedMailValidator: MimeMessage message is not a signed message. +SignedMailValidator.noSignedMessage.details = SignedMailValidator: MimeMessage message is not a signed message. + +# exception reading the Mime message +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionReadingMessage.title = Exception reading the MimeMessage +SignedMailValidator.exceptionReadingMessage.text = SignedMailValidator: there was a {2} reading the MimeMessage: {0}. +SignedMailValidator.exceptionReadingMessage.summary = SignedMailValidator: there was a {2} reading the MimeMessage: {0}. +SignedMailValidator.exceptionReadingMessage.details = SignedMailValidator: there was a {2} reading the MimeMessage: {0}. + +## exception messages + +# signer has not signed the mail message +SignedMailValidator.wrongSigner.title = Signer has not signed the message +SignedMailValidator.wrongSigner.text = The given signer did not sign the mail message. +SignedMailValidator.wrongSigner.summary = The given signer did not sign the mail message. +SignedMailValidator.wrongSigner.details = The given signer did not sign the mail message. + +## notifications messages + +# short signing key +# {0} the key length as Integer +SignedMailValidator.shortSigningKey.title = Careless short signing key +SignedMailValidator.shortSigningKey.text = Warning: The signing key is only {0} bits long. +SignedMailValidator.shortSigningKey.summary = Warning: The signing key is only {0} bits long. +SignedMailValidator.shortSigningKey.details = Warning: The signing key is only {0} bits long. + +# signing certificate has very long validity period +# {0} notBefore date +# {1} notAfter date +SignedMailValidator.longValidity.title = Very long validity period +SignedMailValidator.longValidity.text = Warning: The signing certificate has a very long validity period: from {0,date} {0,time,full} until {1,date} {1,time,full}. +SignedMailValidator.longValidity.summary = Warning: The signing certificate has a very long validity period: from {0,date} {0,time,full} until {1,date} {1,time,full}. +SignedMailValidator.longValidity.details = Warning: The signing certificate has a very long validity period: from {0,date} {0,time,full} until {1,date} {1,time,full}. + +# signed receipt requested +SignedMailValidator.signedReceiptRequest.title = Signed Receipt Request +SignedMailValidator.signedReceiptRequest.text = The signature contains a signed receipt request. +SignedMailValidator.signedReceiptRequest.summary = The signature contains a signed receipt request. +SignedMailValidator.signedReceiptRequest.details = The signature contains a signed receipt request as per RFC 2634. + +## error messages + +# no signer certificate found +SignedMailValidator.noSignerCert.title = No signer certificate found +SignedMailValidator.noSignerCert.text = Signature Validation failed: No signer certificate found. +SignedMailValidator.noSignerCert.summary = Signature Validation failed: No signer certificate found. +SignedMailValidator.noSignerCert.details = Signature Validation failed: No signer certificate found. + +# certificate contains no email address +SignedMailValidator.noEmailInCert.title = Certificate not usable for email signatures +SignedMailValidator.noEmailInCert.text = The signer certificate is not usable for email signatures: it contains no email address. +SignedMailValidator.noEmailInCert.summary = The signer certificate is not usable for email signatures: it contains no email address. +SignedMailValidator.noEmailInCert.details = The signer certificate is not usable for email signatures: it contains no email address. + +# certificate email address does not match from email address +# {0} from email addresses in the message +# {1} email addresses in the certificate +SignedMailValidator.emailFromCertMismatch.title = Email address mismatch +SignedMailValidator.emailFromCertMismatch.text = Email address in signer certificate does not match the sender address. Signer email: {1}. Sender email: {0}. +SignedMailValidator.emailFromCertMismatch.summary = Email address in signer certificate does not match the sender address. Signer email: {1}. Sender email: {0}. +SignedMailValidator.emailFromCertMismatch.details = Email address in signer certificate does not match the sender address. Signer email: {1}. Sender email: {0}. + +# exception extracting email addresses from certificate +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.certGetEmailError.title = Exception extracting email addresses from certificate +SignedMailValidator.certGetEmailError.text = There was a {2} extracting the email addresses from the certificate. Cause: {0}. +SignedMailValidator.certGetEmailError.summary = There was a {2} extracting the email addresses from the certificate. +SignedMailValidator.certGetEmailError.details = There was a {2} extracting the email addresses from the certificate. Cause: {0}. + +# no signing time found +SignedMailValidator.noSigningTime.title = No signing time +SignedMailValidator.noSigningTime.text = The signature contains no signing time. Using the current time for validating the certificate path. +SignedMailValidator.noSigningTime.summary = The signature contains no signing time. +SignedMailValidator.noSigningTime.details = The signature contains no signing time. Using the current time for validating the certificate path. + +# expired at signing time +# {0} signing time +# {1} not after date +SignedMailValidator.certExpired.title = Certificate expired at signing time +SignedMailValidator.certExpired.text = The message was signed at {0,date} {0,time,full}. But the certificate expired at {1,date} {1,time,full}. +SignedMailValidator.certExpired.summary = The message was signed at {0,date} {0,time,full}. But the certificate expired at {1,date} {1,time,full}. +SignedMailValidator.certExpired.details = The message was signed at {0,date} {0,time,full}. But the certificate expired at {1,date} {1,time,full}. + +# not yet valid at signing time +# {0} signing time +# {1} notBefore date +SignedMailValidator.certNotYetValid.title = Certificate not yet valid at signing time +SignedMailValidator.certNotYetValid.text = The message was signed at {0,date} {0,time,full}. But the certificate is not valid before {1,date} {1,time,full}. +SignedMailValidator.certNotYetValid.summary = The message was signed at {0,date} {0,time,full}. But the certificate is not valid before {1,date} {1,time,full}. +SignedMailValidator.certNotYetValid.details = The message was signed at {0,date} {0,time,full}. But the certificate is not valid before {1,date} {1,time,full}. + +# exception retrieving the signer certificate +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionRetrievingSignerCert.title = Exception retrieving the signer certificate +SignedMailValidator.exceptionRetrievingSignerCert.text = Signature Validation failed. There was a {2} retrieving the signer certificate: {0}. +SignedMailValidator.exceptionRetrievingSignerCert.summary = Signature Validation failed. There was a {2} retrieving the signer certificate. +SignedMailValidator.exceptionRetrievingSignerCert.details = Signature Validation failed There was a {2} retrieving the signer certificate: {0}. + +# exception verifying the signature +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionVerifyingSignature.title = Signature not verified +SignedMailValidator.exceptionVerifyingSignature.text = Signature not verified. There was a {2}. Cause: {0}. +SignedMailValidator.exceptionVerifyingSignature.summary = Signature not verified. There was a {2}. +SignedMailValidator.exceptionVerifyingSignature.details = Signature not verified. There was a {2}. Cause: {0}. + +# signature not verified +SignedMailValidator.signatureNotVerified.title = Signature not verified +SignedMailValidator.signatureNotVerified.text = Signature not verified. The public key of the signer does not correspond to the signature. +SignedMailValidator.signatureNotVerified.summary = Signature not verified. The public key of the signer does not correspond to the signature. +SignedMailValidator.signatureNotVerified.details = Signature not verified. The public key of the signer does not correspond to the signature. + +# certificate key usage does not permit digitalSignature or nonRepudiation +SignedMailValidator.signingNotPermitted.title = Key not usable for email signatures +SignedMailValidator.signingNotPermitted.text = The key usage extension of signer certificate does not permit using the key for email signatures. +SignedMailValidator.signingNotPermitted.summary = The signer key is not usable for email signatures. +SignedMailValidator.signingNotPermitted.details = The key usage extension of signer certificate does not permit using the key for email signatures. + +# certificate extended key usage does not permit emailProtection or anyExtendedKeyUsage +SignedMailValidator.extKeyUsageNotPermitted.title = Key not usable for email signatures +SignedMailValidator.extKeyUsageNotPermitted.text = The extended key usage extension of the signer certificate does not permit using the key for email signatures. +SignedMailValidator.extKeyUsageNotPermitted.summary = The signer key is not usable for email signatures. +SignedMailValidator.extKeyUsageNotPermitted.details = The extended key usage extension of the signer certificate does not permit using the key for email signatures. + +# exception processing the extended key usage extension +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.extKeyUsageError.title = Exception processing the extended key usage extension +SignedMailValidator.extKeyUsageError.text = There was a {2} processing the extended key usage extension. Cause: {0}. +SignedMailValidator.extKeyUsageError.summary = There was a {2} processing the extended key usage extension. +SignedMailValidator.extKeyUsageError.details = There was a {2} processing the extended key usage extension. Cause: {0}. + +# cannot create certificate path (exception) +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionCreateCertPath.title = Certificate path validation failed +SignedMailValidator.exceptionCreateCertPath.text = Certificate path validation failed. There was a {2} creating the CertPath: {0}. +SignedMailValidator.exceptionCreateCertPath.summary = Certificate path validation failed. There was a {2} creating the CertPath: {0}. +SignedMailValidator.exceptionCreateCertPath.details = Certificate path validation failed. There was a {2} creating the CertPath: {0}. + +# certificate path is invalid +SignedMailValidator.certPathInvalid.title = Certificate path invalid +SignedMailValidator.certPathInvalid.text = The certificate path is invalid. +SignedMailValidator.certPathInvalid.summary = The certificate path is invalid. +SignedMailValidator.certPathInvalid.details = The certificate path is invalid. diff --git a/jmail/src/main/resources/org/bouncycastle/mail/smime/validator/SignedMailValidatorMessages_de.properties b/jmail/src/main/resources/org/bouncycastle/mail/smime/validator/SignedMailValidatorMessages_de.properties new file mode 100644 index 0000000000..acdd3731a1 --- /dev/null +++ b/jmail/src/main/resources/org/bouncycastle/mail/smime/validator/SignedMailValidatorMessages_de.properties @@ -0,0 +1,172 @@ +## constructor exception messages + +# Signatur gltig +SignedMailValidator.sigValid.title = Signatur gltig +SignedMailValidator.sigValid.text = Signatur gltig +SignedMailValidator.sigValid.summary = Signatur gltig +SignedMailValidator.sigValid.details = Signatur gltig + +# Signatur ungltig +SignedMailValidator.sigInvalid.title = Signatur ungltig +SignedMailValidator.sigInvalid.text = Signatur ungltig +SignedMailValidator.sigInvalid.summary = Signatur ungltig +SignedMailValidator.sigInvalid.details = Signatur ungltig + +# message is not signed +SignedMailValidator.noSignedMessage.title = Die Nachricht ist nicht signiert +SignedMailValidator.noSignedMessage.text = SignedMailValidator: Die MimeMessage message ist nicht signiert. +SignedMailValidator.noSignedMessage.summary = SignedMailValidator: Die MimeMessage message ist nicht signiert. +SignedMailValidator.noSignedMessage.details = SignedMailValidator: Die MimeMessage message ist nicht signiert. + +# exception reading the Mime message +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionReadingMessage.title = Fehler beim lesen der MimeMessage +SignedMailValidator.exceptionReadingMessage.text = SignedMailValidator: Es gab eine {2} beim lesen der MimeMessage: {0}. +SignedMailValidator.exceptionReadingMessage.summary = SignedMailValidator: Es gab eine {2} beim lesen der MimeMessage. +SignedMailValidator.exceptionReadingMessage.details = SignedMailValidator: Es gab eine {2} beim lesen der MimeMessage: {0}. + +## exception messages + +# signer has not signed the mail message +SignedMailValidator.wrongSigner.title = Falscher Unterzeichner +SignedMailValidator.wrongSigner.text = Die Email enhlt keine Signatur vom gegebenen Unterzeichner. +SignedMailValidator.wrongSigner.summary = Die Email enhlt keine Signatur vom gegebenen Unterzeichner. +SignedMailValidator.wrongSigner.details = Die Email enhlt keine Signatur vom gegebenen Unterzeichner. + +## notifications messages + +# short signing key +# {0} the key length as Integer +SignedMailValidator.shortSigningKey.title = Fahrlssig kurzer Signaturschlssel +SignedMailValidator.shortSigningKey.text = Warnung: Der Signaturschlssel ist nur {0} bit lang. +SignedMailValidator.shortSigningKey.summary = Warnung: Der Signaturschlssel ist nur {0} bit lang. +SignedMailValidator.shortSigningKey.details = Warnung: Der Signaturschlssel ist nur {0} bit lang. + +# signing certificate has very long validity period +# {0} notBefore date +# {1} notAfter date +SignedMailValidator.longValidity.title = Sehr lange Gltigkeitsdauer +SignedMailValidator.longValidity.text = Warnung: Das Signierzertifikat hat eine sehr lange Gltigkeitsdauer: von {0,date} {0,time,full} bis {1,date} {1,time,full}. +SignedMailValidator.longValidity.summary = Warnung: Das Signierzertifikat hat eine sehr lange Gltigkeitsdauer: von {0,date} {0,time,full} bis {1,date} {1,time,full}. +SignedMailValidator.longValidity.details = Warnung: Das Signierzertifikat hat eine sehr lange Gltigkeitsdauer: von {0,date} {0,time,full} bis {1,date} {1,time,full}. + +# signed receipt requested +SignedMailValidator.signedReceiptRequest.title = Signed Receipt Request +SignedMailValidator.signedReceiptRequest.text = Die Signatur enthlt einen signed receipt request. +SignedMailValidator.signedReceiptRequest.summary = Die Signatur enthlt einen signed receipt request. +SignedMailValidator.signedReceiptRequest.details = Die Signatur enthlt einen signed receipt request gemss RFC 2634. + +## error messages + +# no signer certificate found +SignedMailValidator.noSignerCert.title = Kein Unterzeichner Zertifikat gefunden +SignedMailValidator.noSignerCert.text = Signatur Validierung fehlgeschlagen: Es wurde kein Unterzeichner Zertifikat gefunden. +SignedMailValidator.noSignerCert.summary = Signatur Validierung fehlgeschlagen: Es wurde kein Unterzeichner Zertifikat gefunden. +SignedMailValidator.noSignerCert.details = Signatur Validierung fehlgeschlagen: Es wurde kein Unterzeichner Zertifikat gefunden. + +# certificate contains no email address +SignedMailValidator.noEmailInCert.title = Zertifikat nicht fr Email Signaturen verwendbar +SignedMailValidator.noEmailInCert.text = Das Unterzeichner Zertifikat kann nicht fr Email Signaturen verwendet werden: Es enthlt keine Email Addresse. +SignedMailValidator.noEmailInCert.summary = Das Unterzeichner Zertifikat kann nicht fr Email Signaturen verwendet werden: Es enthlt keine Email Addresse. +SignedMailValidator.noEmailInCert.details = Das Unterzeichner Zertifikat kann nicht fr Email Signaturen verwendet werden: Es enthlt keine Email Addresse. + +# certificate email address does not match from email address +# {0} from email addresses in the message +# {1} email addresses in the certificate +SignedMailValidator.emailFromCertMismatch.title = Email Addressen stimmen nicht berein +SignedMailValidator.emailFromCertMismatch.text = Die Email Addresse im Unterzeichner Zertifikat stimmt nicht mit der Sender Addresse berein. Unterzeichner: {1}. Sender: {0}. +SignedMailValidator.emailFromCertMismatch.summary = Die Email Addresse im Unterzeichner Zertifikat stimmt nicht mit der Sender Addresse berein. Unterzeichner: {1}. Sender: {0}. +SignedMailValidator.emailFromCertMismatch.details = Die Email Addresse im Unterzeichner Zertifikat stimmt nicht mit der Sender Addresse berein. Unterzeichner: {1}. Sender: {0}. + +# exception extracting email addresses from certificate +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.certGetEmailError.title = Fehler bei extrahieren der Email Addresse vom Zertifikat +SignedMailValidator.certGetEmailError.text = Es gab eine {2} beim Extrahieren der Email Addresse vom Zertifikat. Grund: {0}. +SignedMailValidator.certGetEmailError.summary = Es gab eine {2} beim Extrahieren der Email Addresse vom Zertifikat. +SignedMailValidator.certGetEmailError.details = Es gab eine {2} beim Extrahieren der Email Addresse vom Zertifikat. Grund: {0}. + +# no signing time found +SignedMailValidator.noSigningTime.title = Keine Signierzeit +SignedMailValidator.noSigningTime.text = Die Signatur enthlt keine Signier Zeit. Benutze die aktuelle Zeit zur Zertifikationpfad Validierung. +SignedMailValidator.noSigningTime.summary = Die Signatur enthlt keine Signier Zeit. +SignedMailValidator.noSigningTime.details = Die Signatur enthlt keine Signier Zeit. Benutze die aktuelle Zeit zur Zertifikationpfad Validierung. + +# expired at signing time +# {0} signing time +# {1} not after date +SignedMailValidator.certExpired.title = Zertifikat zur Signierzeit abgelaufen +SignedMailValidator.certExpired.text = Die Nachricht wurde am {0,date} {0,time,full} signiert. Aber das Zertifikat ist am {1,date} {1,time,full} abgelaufen. +SignedMailValidator.certExpired.summary = Die Nachricht wurde am {0,date} {0,time,full} signiert. Aber das Zertifikat ist am {1,date} {1,time,full} abgelaufen. +SignedMailValidator.certExpired.details = Die Nachricht wurde am {0,date} {0,time,full} signiert. Aber das Zertifikat ist am {1,date} {1,time,full} abgelaufen. + +# not yet valid at signing time +# {0} signing time +# {1} notBefore date +SignedMailValidator.certNotYetValid.title = Zertifikat noch nicht gltig zur Signierzeit +SignedMailValidator.certNotYetValid.text = Die Nachricht wurde am {0,date} {0,time,full} signiert. Aber das Zertifikat ist erst gltig ab {1,date} {1,time,full}. +SignedMailValidator.certNotYetValid.summary = Die Nachricht wurde am {0,date} {0,time,full} signiert. Aber das Zertifikat ist erst gltig ab {1,date} {1,time,full}. +SignedMailValidator.certNotYetValid.details = Die Nachricht wurde am {0,date} {0,time,full} signiert. Aber das Zertifikat ist erst gltig ab {1,date} {1,time,full}. + +# exception retrieving the signer certificate +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionRetrievingSignerCert.title = Fehler beim Lesen des Signaturzertifikats +SignedMailValidator.exceptionRetrievingSignerCert.text = Signatur Validierung fehlgeschlagen. Es gab eine {2} beim Lesen des Signaturzertifikats: {0}. +SignedMailValidator.exceptionRetrievingSignerCert.summary = Signatur Validierung fehlgeschlagen. Es gab eine {2} beim Lesen des Signaturzertifikats. +SignedMailValidator.exceptionRetrievingSignerCert.details = Signatur Validierung fehlgeschlagen. Es gab eine {2} beim Lesen des Signaturzertifikats: {0}. + +# exception verifying the signature +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionVerifyingSignature.title = Signatur nicht verifiziert +SignedMailValidator.exceptionVerifyingSignature.text = Signatur nicht verifiziert. Es gab eine {2}. Grund: {0}. +SignedMailValidator.exceptionVerifyingSignature.summary = Signatur nicht verifiziert. Es gab eine {2}. +SignedMailValidator.exceptionVerifyingSignature.details = Signatur nicht verifiziert. Es gab eine {2}. Grund: {0}. + +# signature not verified +SignedMailValidator.signatureNotVerified.title = Signatur nicht verifiziert +SignedMailValidator.signatureNotVerified.text = Signatur nicht verifiziert. Der ffentliche Schlssel des Unterzeichners passt nicht zur Signatur. +SignedMailValidator.signatureNotVerified.summary = Signatur nicht verifiziert. Der ffentliche Schlssel des Unterzeichners passt nicht zur Signatur. +SignedMailValidator.signatureNotVerified.details = Signatur nicht verifiziert. Der ffentliche Schlssel des Unterzeichners passt nicht zur Signatur. + +# certificate key usage does not permit digitalSignature or nonRepudiation +SignedMailValidator.signingNotPermitted.title = Schlssel nicht verwendbar fr Email Signaturen +SignedMailValidator.signingNotPermitted.text = Der Schlssel des Unterzeichners darf nicht fr Email Signaturen verwendet werden. +SignedMailValidator.signingNotPermitted.summary = Der Schlssel des Unterzeichners darf nicht fr Email Signaturen verwendet werden. +SignedMailValidator.signingNotPermitted.details = Die Schlsselverwendung des Unterzeichner Zertifikats erlaubt keine Verwendung fr Email Signaturen. + +# certificate extended key usage does not permit emailProtection or anyExtendedKeyUsage +SignedMailValidator.extKeyUsageNotPermitted.title = Schlssel nicht verwendbar fr Email Signaturen +SignedMailValidator.extKeyUsageNotPermitted.text = Der Schlssel des Unterzeichners darf nicht fr Email Signaturen verwendet werden. +SignedMailValidator.extKeyUsageNotPermitted.summary = Der Schlssel des Unterzeichners darf nicht fr Email Signaturen verwendet werden. +SignedMailValidator.extKeyUsageNotPermitted.details = Die erweiterte Schlsselverwendung des Unterzeichner Zertifikats erlaubt keine Verwendung fr Email Signaturen. + +# exception processing the extended key usage extension +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.extKeyUsageError.title = Fehler bei der Verarbeitung der Extended key usage Erweiterung +SignedMailValidator.extKeyUsageError.text = Es gab eine {2} bei der Verarbeitung der Extended key usage Erweiterung. Grund: {0}. +SignedMailValidator.extKeyUsageError.summary = Es gab eine {2} bei der Verarbeitung der Extended key usage Erweiterung. +SignedMailValidator.extKeyUsageError.details = Es gab eine {2} bei der Verarbeitung der Extended key usage Erweiterung. Grund: {0}. + +# cannot create certificate path (exception) +# {0} message of the underlying exception +# {1} the underlying exception +# {2} the name of the exception +SignedMailValidator.exceptionCreateCertPath.title = Zertifizierungspfad Validierung fehlgeschlagen +SignedMailValidator.exceptionCreateCertPath.text = Die Zertifizierungspfad Validierung ist fehlgeschlagen. Es gab eine {2} beim erstellen des Zertifizierungspfad: {0}. +SignedMailValidator.exceptionCreateCertPath.summary = Die Zertifizierungspfad Validierung ist fehlgeschlagen. Es gab eine {2} beim erstellen des Zertifizierungspfad: {0}. +SignedMailValidator.exceptionCreateCertPath.details = Die Zertifizierungspfad Validierung ist fehlgeschlagen. Es gab eine {2} beim erstellen des Zertifizierungspfad: {0}. + +# certificate path is invalid +SignedMailValidator.certPathInvalid.title = Zertifikats-Pfad ungltig +SignedMailValidator.certPathInvalid.text = Der Zertifikats-Pfad ist ungltig. +SignedMailValidator.certPathInvalid.summary = Der Zertifikats-Pfad ist ungltig. +SignedMailValidator.certPathInvalid.details = Der Zertifikats-Pfad ist ungltig. diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/KMIPInputException.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/KMIPInputException.java new file mode 100644 index 0000000000..e3061bae8b --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/KMIPInputException.java @@ -0,0 +1,12 @@ +package org.bouncycastle.kmip.wire; + +import java.io.IOException; + +public class KMIPInputException + extends IOException +{ + public KMIPInputException(String msg) + { + super(msg); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/KMIPInputStream.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/KMIPInputStream.java new file mode 100644 index 0000000000..95dae660f3 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/KMIPInputStream.java @@ -0,0 +1,740 @@ +package org.bouncycastle.kmip.wire; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Attribute; +import javax.xml.stream.events.EndElement; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; + +import org.bouncycastle.kmip.wire.attribute.KMIPName; +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; +import org.bouncycastle.kmip.wire.attribute.KMIPVendorAttribute; +import org.bouncycastle.kmip.wire.enumeration.KMIPCryptographicAlgorithm; +import org.bouncycastle.kmip.wire.enumeration.KMIPCryptographicUsageMask; +import org.bouncycastle.kmip.wire.enumeration.KMIPEnumeration; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyFormatType; +import org.bouncycastle.kmip.wire.enumeration.KMIPNameType; +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; +import org.bouncycastle.kmip.wire.enumeration.KMIPOperation; +import org.bouncycastle.kmip.wire.enumeration.KMIPResultReason; +import org.bouncycastle.kmip.wire.enumeration.KMIPResultStatus; +import org.bouncycastle.kmip.wire.enumeration.KMIPSplitKeyMethod; +import org.bouncycastle.kmip.wire.message.KMIPBatchItem; +import org.bouncycastle.kmip.wire.message.KMIPHeader; +import org.bouncycastle.kmip.wire.message.KMIPMessage; +import org.bouncycastle.kmip.wire.message.KMIPPayload; +import org.bouncycastle.kmip.wire.message.KMIPProtocolVersion; +import org.bouncycastle.kmip.wire.message.KMIPRequestBatchItem; +import org.bouncycastle.kmip.wire.message.KMIPRequestHeader; +import org.bouncycastle.kmip.wire.message.KMIPRequestMessage; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayload; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayloadCreate; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayloadCreateSplitKey; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayloadDefault; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayloadGet; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayloadJoinSplitKey; +import org.bouncycastle.kmip.wire.message.KMIPRequestPayloadRegister; +import org.bouncycastle.kmip.wire.message.KMIPResponseBatchItem; +import org.bouncycastle.kmip.wire.message.KMIPResponseHeader; +import org.bouncycastle.kmip.wire.message.KMIPResponseMessage; +import org.bouncycastle.kmip.wire.message.KMIPResponsePayload; +import org.bouncycastle.kmip.wire.message.KMIPResponsePayloadCreate; +import org.bouncycastle.kmip.wire.message.KMIPResponsePayloadCreateSplitKey; +import org.bouncycastle.kmip.wire.message.KMIPResponsePayloadDefault; +import org.bouncycastle.kmip.wire.message.KMIPResponsePayloadGet; +import org.bouncycastle.kmip.wire.object.KMIPKeyBlock; +import org.bouncycastle.kmip.wire.object.KMIPObject; +import org.bouncycastle.kmip.wire.object.KMIPSplitKey; +import org.bouncycastle.kmip.wire.object.KMIPSymmetricKey; +import org.bouncycastle.util.encoders.Hex; + +public class KMIPInputStream +{ + private final XMLEventReader eventReader; + + public KMIPInputStream(InputStream stream) + throws XMLStreamException + { + this.eventReader = XMLInputFactory.newInstance().createXMLEventReader(stream); + } + + public KMIPMessage[] parse() + throws XMLStreamException, KMIPInputException + { + ArrayList messages = new ArrayList(); + // Get a list of elements + try + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + if (name.equals("RequestMessage") || name.equals("ResponseMessage")) + { + KMIPMessage message = parseMessage(); + messages.add(message); + } + } + } + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + + KMIPMessage[] rlt = new KMIPMessage[messages.size()]; + messages.toArray(rlt); + return rlt; + } + + + private KMIPMessage parseMessage() + throws KMIPInputException + { + KMIPHeader header = null; + boolean isRequest = true; + ArrayList batchItems = new ArrayList(); + try + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + switch (name) + { + case "RequestHeader": + isRequest = true; + header = parseHeader(true); + break; + case "ResponseHeader": + isRequest = false; + header = parseHeader(false); + break; + case "BatchItem": + KMIPBatchItem batchItem = parseBatchItem(isRequest); + batchItems.add(batchItem); + break; + } + } + + if (event.isEndElement()) + { + assertEndElement(event, isRequest ? "RequestMessage" : "ResponseMessage"); + break; + } + + } + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + if (isRequest) + { + KMIPRequestBatchItem[] items = new KMIPRequestBatchItem[batchItems.size()]; + batchItems.toArray(items); + return new KMIPRequestMessage((KMIPRequestHeader)header, items); + } + else + { + KMIPResponseBatchItem[] items = new KMIPResponseBatchItem[batchItems.size()]; + batchItems.toArray(items); + return new KMIPResponseMessage((KMIPResponseHeader)header, items); + } + } + + private KMIPHeader parseHeader(boolean isRequest) + throws KMIPInputException + { + KMIPProtocolVersion protocolVersion = null; + String clientCorrelationValue = null; + Date timestamp = null; + int batchCount = -1; + try + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + switch (name) + { + case "ProtocolVersion": + int marjorVersion, minorVersion; + startElement = assertStartElement("ProtocolVersionMajor"); + marjorVersion = parseInteger(startElement, "ProtocolVersionMajor"); + startElement = assertStartElement("ProtocolVersionMinor"); + minorVersion = parseInteger(startElement, "ProtocolVersionMinor"); + assertEndElement(eventReader.nextEvent(), "ProtocolVersion"); + protocolVersion = new KMIPProtocolVersion(marjorVersion, minorVersion); + break; + case "ClientCorrelationValue": + clientCorrelationValue = parseTextString(startElement, "ClientCorrelationValue"); + break; + case "BatchCount": + batchCount = parseInteger(startElement, "BatchCount"); + break; + case "TimeStamp": + timestamp = parseDateTime(startElement, "TimeStamp"); + break; + default: + throw new KMIPInputException("Add more code to support parseHeader"); + } + } + if (event.isEndElement()) + { + assertEndElement(event, isRequest ? "RequestHeader" : "ResponseHeader"); + break; + } + } + + if (protocolVersion == null || batchCount == -1) + { + throw new KMIPInputException("Request Header should contain Protocol Version and Batch Count"); + } + if (isRequest) + { + KMIPRequestHeader header = new KMIPRequestHeader(protocolVersion, batchCount); + header.setClientCorrelationValue(clientCorrelationValue); + return header; + } + else + { + return new KMIPResponseHeader(protocolVersion, timestamp, batchCount); + } + + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + } + + private KMIPBatchItem parseBatchItem(boolean isRequest) + throws KMIPInputException + { + KMIPOperation operation = null; + KMIPRequestPayload requestPayload = null; + KMIPResultStatus resultStatus = null; + KMIPResponsePayload responsePayload = null; + KMIPResultReason resultReason = null; + String resultMessage = null; + try + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + switch (name) + { + case "Operation": + operation = parseEnum(startElement, KMIPOperation.class, "Operation"); + break; + case "ResultStatus": + resultStatus = parseEnum(startElement, KMIPResultStatus.class, "ResultStatus"); + break; + case "RequestPayload": + requestPayload = (KMIPRequestPayload)parsePayload(operation, true); + break; + case "ResponsePayload": + responsePayload = (KMIPResponsePayload)parsePayload(operation, false); + break; + case "ResultReason": + resultReason = parseEnum(startElement, KMIPResultReason.class, "ResultReason"); + break; + case "ResultMessage": + resultMessage = parseTextString(startElement, "ResultMessage"); + break; + default: + throw new KMIPInputException("Add more code to support parseBatchItem"); + } + } + if (event.isEndElement()) + { + assertEndElement(event, "BatchItem"); + break; + } + } + + if (isRequest) + { + if (operation == null || requestPayload == null) + { + throw new KMIPInputException("Request Header should contain Protocol Version and Batch Count"); + } + + return new KMIPRequestBatchItem(operation, requestPayload); + } + else + { + if (operation == null || (responsePayload == null && resultStatus != KMIPResultStatus.OperationFailed)) + { + throw new KMIPInputException("Request Header should contain Protocol Version and Batch Count"); + } + KMIPResponseBatchItem batchItem = new KMIPResponseBatchItem(operation, resultStatus, responsePayload); + if (resultReason == null) + { + if (resultStatus == KMIPResultStatus.OperationFailed) + { + throw new KMIPInputException("Result Reason is REQUIRED if Result Status is Failure"); + } + } + else + { + batchItem.setResultReason(resultReason); + } + if (resultMessage != null) + { + batchItem.setResultMessage(resultMessage); + } + return batchItem; + } + + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + } + + private KMIPPayload parsePayload(KMIPOperation operation, boolean isRequest) + throws KMIPInputException + { + KMIPObjectType objectType = null; + Map attributes = null; + XMLEvent event; + KMIPUniqueIdentifier uniqueIdentifier = null; + ArrayList uniqueIdentifiers = new ArrayList(); + int splitKeyParts = 0, splitKeyThreshold = 0; + KMIPSplitKeyMethod splitKeyMethod = null; + KMIPObject object = null; + try + { + while (eventReader.hasNext()) + { + event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + switch (name) + { + case "ObjectType": + objectType = parseEnum(startElement, KMIPObjectType.class, "ObjectType"); + break; + case "Attributes": + attributes = parseAttributes(); + break; + case "UniqueIdentifier": + uniqueIdentifier = parseUniqueIdentifier(startElement, "UniqueIdentifier"); + uniqueIdentifiers.add(uniqueIdentifier); + break; + case "SplitKeyParts": + splitKeyParts = parseInteger(startElement, "SplitKeyParts"); + break; + case "SplitKeyThreshold": + splitKeyThreshold = parseInteger(startElement, "SplitKeyThreshold"); + break; + case "SplitKeyMethod": + splitKeyMethod = parseEnum(startElement, KMIPSplitKeyMethod.class, "SplitKeyMethod"); + break; + case "SymmetricKey": + assertStartElement("KeyBlock"); + KMIPKeyBlock keyBlock = parseKeyBlock(); + + object = new KMIPSymmetricKey(keyBlock); + assertEndElement(event, "SymmetricKey"); + break; + case "SplitKey": + object = parseSplitKey(event); + break; + default: + throw new KMIPInputException("Add more code to support parseRequestPayload"); + } + } + + if (event.isEndElement()) + { + assertEndElement(event, isRequest ? "RequestPayload" : "ResponsePayload"); + break; + } + } + if (isRequest) + { + switch (operation) + { + case Create: + return new KMIPRequestPayloadCreate(objectType, attributes); + case CreateSplitKey: + KMIPRequestPayloadCreateSplitKey splitkey = new KMIPRequestPayloadCreateSplitKey(objectType, splitKeyParts, + splitKeyThreshold, splitKeyMethod, attributes); + if (uniqueIdentifier != null) + { + splitkey.setUniqueIdentifier(uniqueIdentifier); + } + return splitkey; + case JoinSplitKey: + KMIPUniqueIdentifier[] kmipUniqueIdentifiers = new KMIPUniqueIdentifier[uniqueIdentifiers.size()]; + uniqueIdentifiers.toArray(kmipUniqueIdentifiers); + KMIPRequestPayloadJoinSplitKey joinSplitKey = new KMIPRequestPayloadJoinSplitKey(objectType, kmipUniqueIdentifiers); + if (attributes != null) + { + joinSplitKey.setAttributes(attributes); + } + return joinSplitKey; + case Destroy: + KMIPRequestPayloadDefault destroy = new KMIPRequestPayloadDefault(); + if (uniqueIdentifier != null) + { + destroy.setUniqueIdentifier(uniqueIdentifier); + } + return destroy; + case Register: + return new KMIPRequestPayloadRegister(objectType, attributes, object); + case Get: + KMIPRequestPayloadGet get = new KMIPRequestPayloadGet(); + if (uniqueIdentifier != null) + { + get.setUniqueIdentifier(uniqueIdentifier); + } + return get; + default: + throw new KMIPInputException("add more support for parseRequestPayload"); + } + } + else + { + switch (operation) + { + case Create: + return new KMIPResponsePayloadCreate(objectType, uniqueIdentifier); + case CreateSplitKey: + KMIPUniqueIdentifier[] kmipUniqueIdentifiers = new KMIPUniqueIdentifier[uniqueIdentifiers.size()]; + uniqueIdentifiers.toArray(kmipUniqueIdentifiers); + return new KMIPResponsePayloadCreateSplitKey(kmipUniqueIdentifiers); + case JoinSplitKey: + case Destroy: + case Register: + return new KMIPResponsePayloadDefault(uniqueIdentifier); + case Get: + return new KMIPResponsePayloadGet(objectType, uniqueIdentifier, object); + default: + throw new KMIPInputException("add more support for parseResponsePayload"); + } + } + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + } + + private KMIPSplitKey parseSplitKey(XMLEvent event) + throws XMLStreamException, KMIPInputException + { + StartElement startElement = assertStartElement("SplitKeyParts"); + int splitKeyParts = parseInteger(startElement, "SplitKeyParts"); + + startElement = assertStartElement("KeyPartIdentifier"); + int keyPartIdentifier = parseInteger(startElement, "KeyPartIdentifier"); + + startElement = assertStartElement("SplitKeyThreshold"); + int splitKeyThreshold = parseInteger(startElement, "SplitKeyThreshold"); + + startElement = assertStartElement("SplitKeyMethod"); + KMIPSplitKeyMethod splitKeyMethod = parseEnum(startElement, KMIPSplitKeyMethod.class, "SplitKeyMethod"); + assertStartElement("KeyBlock"); + KMIPKeyBlock keyBlock = parseKeyBlock(); + assertEndElement(event, "SplitKey"); + return new KMIPSplitKey(splitKeyParts, keyPartIdentifier, splitKeyThreshold, splitKeyMethod, null, keyBlock); + } + + private Map parseAttributes() + throws KMIPInputException + { + Map attributes = new HashMap(); + try + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + switch (name) + { + case "CryptographicAlgorithm": + KMIPEnumeration cryptographicAlgorithm = parseEnum(startElement, KMIPCryptographicAlgorithm.class, "CryptographicAlgorithm"); + attributes.put("CryptographicAlgorithm", cryptographicAlgorithm); + break; + case "CryptographicLength": + int cryptographicLength = parseInteger(startElement, "CryptographicLength"); + attributes.put("CryptographicLength", cryptographicLength); + break; + case "CryptographicUsageMask": + int cryptographicUsageMask = parseInteger(startElement, KMIPCryptographicUsageMask.class, "CryptographicUsageMask"); + attributes.put("CryptographicUsageMask", cryptographicUsageMask); + break; + case "Name": + startElement = assertStartElement("NameValue"); + String nameValue = parseTextString(startElement, "NameValue"); + startElement = assertStartElement("NameType"); + KMIPNameType nameType = parseEnum(startElement, KMIPNameType.class, "NameType"); + + assertEndElement(event, "Name"); + KMIPName kmipName = new KMIPName(nameValue, nameType); + attributes.put("Name", kmipName); + break; + case "Attribute": + startElement = assertStartElement("VendorIdentification"); + String vendorIdentification = parseTextString(startElement, "VendorIdentification"); + startElement = assertStartElement("AttributeName"); + String attributeName = parseTextString(startElement, "AttributeName"); + startElement = assertStartElement("AttributeValue"); + String attributeValue = parseTextString(startElement, "AttributeValue"); + assertEndElement(event, "Attribute"); + KMIPVendorAttribute vendorAttribute = new KMIPVendorAttribute(vendorIdentification, attributeName, attributeValue); + attributes.put("VendorAttribute", vendorAttribute); + break; + default: + throw new KMIPInputException("Add more code to support parseAttributes"); + } + } + + if (event.isEndElement()) + { + assertEndElement(event, "Attributes"); + return attributes; + } + } + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + return null; + } + + private KMIPKeyBlock parseKeyBlock() + throws KMIPInputException + { + KMIPKeyFormatType keyFormatType = null; + byte[] keyValue = null; + KMIPCryptographicAlgorithm cryptographicAlgorithm = null; + int cryptographicLength = 0; + try + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + String name = startElement.getName().getLocalPart(); + switch (name) + { + case "KeyFormatType": + keyFormatType = parseEnum(startElement, KMIPKeyFormatType.class, "KeyFormatType"); + break; + case "KeyValue": + startElement = assertStartElement("KeyMaterial"); + keyValue = parseByteString(startElement, "KeyMaterial"); + assertEndElement(event, "KeyValue"); + break; + case "CryptographicAlgorithm": + cryptographicAlgorithm = parseEnum(startElement, KMIPCryptographicAlgorithm.class, "CryptographicAlgorithm"); + break; + case "CryptographicLength": + cryptographicLength = parseInteger(startElement, "CryptographicLength"); + break; + default: + throw new KMIPInputException("Add more code to support parseKeyBlock"); + } + } + + if (event.isEndElement()) + { + assertEndElement(event, "KeyBlock"); + return new KMIPKeyBlock(keyFormatType, keyValue, cryptographicAlgorithm, cryptographicLength); + } + } + } + catch (XMLStreamException e) + { + throw new KMIPInputException("Error processing XML: " + e.getMessage()); + } + return null; + } + + private static void assertException(Attribute attribute, String value, String errorMessage) + throws KMIPInputException + { + if (!attribute.getName().getLocalPart().equals("type") || !attribute.getValue().equals(value)) + { + //parse error + throw new KMIPInputException(errorMessage); + } + } + + private static void assertException(boolean condition, String errorMessage) + throws KMIPInputException + { + if (condition) + { + throw new KMIPInputException(errorMessage); + } + } + + private StartElement assertStartElement(String name) + throws KMIPInputException, XMLStreamException + { + while (eventReader.hasNext()) + { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) + { + StartElement startElement = event.asStartElement(); + if (!startElement.getName().getLocalPart().equals(name)) + { + throw new KMIPInputException("Error in parsing" + name + ": Expected " + name + ", but got" + startElement.getName()); + } + return startElement; + } + } + throw new KMIPInputException("Error in parsing" + name + ": Expected Start Element for " + name); + } + + private void assertEndElement(XMLEvent event, String name) + throws KMIPInputException, XMLStreamException + { + do + { + if (event.isEndElement()) + { + EndElement endElement = event.asEndElement(); + if (!endElement.getName().getLocalPart().equals(name)) + { + throw new KMIPInputException("Error in parsing" + name + ": Expected " + name + "but got" + endElement.getName()); + } + return; + } + event = eventReader.nextEvent(); + } + while (eventReader.hasNext()); + throw new KMIPInputException("Error in parsing" + name + ": Expected End Element for " + name); + } + + private String parseElementAttribute(StartElement startElement, String className, String type) + throws KMIPInputException, XMLStreamException + { + String value; + if (startElement.getAttributes() != null) + { + Iterator it = startElement.getAttributes(); + Attribute attribute = (Attribute)it.next(); + assertException(attribute, type, "Error in parsing " + className + ": type should be " + type); + attribute = (Attribute)it.next(); + value = attribute.getValue(); + assertException(it.hasNext(), "Error in parsing " + className + ": There should be 2 attributes"); + assertEndElement(eventReader.nextEvent(), className); + } + else + { + throw new KMIPInputException("Error in parsing " + className + ": there should be 2 attributes"); + } + return value; + } + + private int parseInteger(StartElement startElement, String className) + throws KMIPInputException, XMLStreamException + { + return Integer.parseInt(parseElementAttribute(startElement, className, "Integer")); + } + + private String parseTextString(StartElement startElement, String className) + throws KMIPInputException, XMLStreamException + { + return parseElementAttribute(startElement, className, "TextString"); + } + + private byte[] parseByteString(StartElement startElement, String className) + throws KMIPInputException, XMLStreamException + { + return Hex.decode(parseElementAttribute(startElement, className, "ByteString")); + } + + private KMIPUniqueIdentifier parseUniqueIdentifier(StartElement startElement, String className) + throws KMIPInputException, XMLStreamException + { + //TODO: parse integer, enumeration + String value = parseElementAttribute(startElement, className, "TextString"); + return new KMIPUniqueIdentifier(value); + } + + private Date parseDateTime(StartElement startElement, String className) + throws KMIPInputException, XMLStreamException + { + String value = parseElementAttribute(startElement, className, "DateTime"); + if (value.equals("$NOW")) + { + return new Date(); + } + return new Date(value); + } + + public & KMIPEnumeration> T parseEnum(StartElement startElement, Class enumClass, String className) + throws KMIPInputException, XMLStreamException + { + String value = parseElementAttribute(startElement, className, "Enumeration"); + // Convert value string to corresponding enum constant + try + { + return Enum.valueOf(enumClass, value.replace("-", "_")); + } + catch (IllegalArgumentException e) + { + throw new KMIPInputException("Error in parsing " + className + ": Invalid value for enum: " + value); + } + } + + private & KMIPEnumeration> int parseInteger(StartElement startElement, Class enumClass, String className) + throws KMIPInputException, XMLStreamException + { + int result = 0; + String value = parseElementAttribute(startElement, className, "Integer"); + try + { + for (String v : value.split(" ")) + { + T enumConstant = Enum.valueOf(enumClass, v.replace("-", "_")); + result |= enumConstant.getValue(); + } + } + catch (IllegalArgumentException e) + { + throw new KMIPInputException(" Invalid value for enum: " + value); + } + return result; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPAttribute.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPAttribute.java new file mode 100644 index 0000000000..0f890e9595 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPAttribute.java @@ -0,0 +1,5 @@ +package org.bouncycastle.kmip.wire.attribute; + +public interface KMIPAttribute +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPCryptographicObject.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPCryptographicObject.java new file mode 100644 index 0000000000..7b0443f2d8 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPCryptographicObject.java @@ -0,0 +1,5 @@ +package org.bouncycastle.kmip.wire.attribute; + +public abstract class KMIPCryptographicObject +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPName.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPName.java new file mode 100644 index 0000000000..d03ce5fe15 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPName.java @@ -0,0 +1,64 @@ +package org.bouncycastle.kmip.wire.attribute; + +import org.bouncycastle.kmip.wire.enumeration.KMIPNameType; + +/** + * Represents the Name attribute used to identify and locate an object in the key management system. + */ +public class KMIPName + implements KMIPAttribute +{ + + private String nameValue; // Human-readable name to identify the object + private KMIPNameType nameType; // Enum representing the type of name + + /** + * Constructs a Name attribute with the given value and type. + * + * @param nameValue The value of the name (human-readable string). + * @param nameType The type of the name (an enumeration). + */ + public KMIPName(String nameValue, KMIPNameType nameType) + { + if (nameValue == null || nameValue.isEmpty()) + { + throw new IllegalArgumentException("Name value cannot be null or empty."); + } + if (nameType == null) + { + throw new IllegalArgumentException("Name type cannot be null."); + } + this.nameValue = nameValue; + this.nameType = nameType; + } + + // Getters and setters + public String getNameValue() + { + return nameValue; + } + + public void setNameValue(String nameValue) + { + if (nameValue == null || nameValue.isEmpty()) + { + throw new IllegalArgumentException("Name value cannot be null or empty."); + } + this.nameValue = nameValue; + } + + public KMIPNameType getNameType() + { + return nameType; + } + + public void setNameType(KMIPNameType nameType) + { + if (nameType == null) + { + throw new IllegalArgumentException("Name type cannot be null."); + } + this.nameType = nameType; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPSymmetricKeyAttribute.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPSymmetricKeyAttribute.java new file mode 100644 index 0000000000..4753cd2570 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPSymmetricKeyAttribute.java @@ -0,0 +1,89 @@ +package org.bouncycastle.kmip.wire.attribute; + +import org.bouncycastle.kmip.wire.enumeration.KMIPCryptographicAlgorithm; + +public class KMIPSymmetricKeyAttribute + extends KMIPCryptographicObject +{ + private KMIPCryptographicAlgorithm cryptographicAlgorithm; + private int cryptographicLength; + private int cryptographicUsageMask; + + /** + * Constructor to initialize all fields of SymmetricKeyAttribute. + * + * @param cryptographicAlgorithm The cryptographic algorithm used. + * @param cryptographicLength The length of the cryptographic key. + * @param cryptographicUsageMask The cryptographic usage mask. + */ + public KMIPSymmetricKeyAttribute(KMIPCryptographicAlgorithm cryptographicAlgorithm, int cryptographicLength, int cryptographicUsageMask) + { + this.cryptographicAlgorithm = cryptographicAlgorithm; + this.cryptographicLength = cryptographicLength; + this.cryptographicUsageMask = cryptographicUsageMask; + } + + // Getters + + /** + * Gets the cryptographic algorithm. + * + * @return The cryptographic algorithm. + */ + public KMIPCryptographicAlgorithm getCryptographicAlgorithm() + { + return cryptographicAlgorithm; + } + + /** + * Gets the cryptographic length. + * + * @return The length of the cryptographic key. + */ + public int getCryptographicLength() + { + return cryptographicLength; + } + + /** + * Gets the cryptographic usage mask. + * + * @return The cryptographic usage mask. + */ + public int getCryptographicUsageMask() + { + return cryptographicUsageMask; + } + + // Setters + + /** + * Sets the cryptographic algorithm. + * + * @param cryptographicAlgorithm The cryptographic algorithm to set. + */ + public void setCryptographicAlgorithm(KMIPCryptographicAlgorithm cryptographicAlgorithm) + { + this.cryptographicAlgorithm = cryptographicAlgorithm; + } + + /** + * Sets the cryptographic length. + * + * @param cryptographicLength The length of the cryptographic key to set. + */ + public void setCryptographicLength(int cryptographicLength) + { + this.cryptographicLength = cryptographicLength; + } + + /** + * Sets the cryptographic usage mask. + * + * @param cryptographicUsageMask The cryptographic usage mask to set. + */ + public void setCryptographicUsageMask(int cryptographicUsageMask) + { + this.cryptographicUsageMask = cryptographicUsageMask; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPUniqueIdentifier.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPUniqueIdentifier.java new file mode 100644 index 0000000000..986b8bd668 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPUniqueIdentifier.java @@ -0,0 +1,132 @@ +package org.bouncycastle.kmip.wire.attribute; + + +import org.bouncycastle.kmip.wire.enumeration.KMIPUniqueIdentifierEnum; + +public class KMIPUniqueIdentifier +{ + private String textValue; // Unique identifier as a text string + private KMIPUniqueIdentifierEnum enumValue; // Unique identifier as an enumeration + private int intValue; // Unique identifier as an integer + private Identifier flag = Identifier.Unknown; + + private enum Identifier + { + Unknown, String, Enum, Integer + } + + + /** + * Constructor for UniqueIdentifier using a String. + * + * @param textValue The text string identifier. + */ + public KMIPUniqueIdentifier(String textValue) + { + this.textValue = textValue; + flag = Identifier.String; + } + + /** + * Constructor for UniqueIdentifier using an Enumeration. + * + * @param enumValue The enumeration identifier. + */ + public KMIPUniqueIdentifier(KMIPUniqueIdentifierEnum enumValue) + { + this.enumValue = enumValue; + flag = Identifier.Enum; + } + + /** + * Constructor for UniqueIdentifier using an Integer. + * + * @param intValue The integer identifier. + */ + public KMIPUniqueIdentifier(int intValue) + { + this.intValue = intValue; + flag = Identifier.Integer; + } + + /** + * Get the text value of the unique identifier. + * + * @return The text value as a String. + */ + public String getTextValue() + { + return textValue; + } + + /** + * Set the text value of the unique identifier. + * + * @param textValue The text value to set. + */ + public void setTextValue(String textValue) + { + this.textValue = textValue; + } + + /** + * Get the enumeration value of the unique identifier. + * + * @return The enumeration value. + */ + public KMIPUniqueIdentifierEnum getEnumValue() + { + return enumValue; + } + + /** + * Set the enumeration value of the unique identifier. + * + * @param enumValue The enumeration value to set. + */ + public void setEnumValue(KMIPUniqueIdentifierEnum enumValue) + { + this.enumValue = enumValue; + } + + /** + * Get the integer value of the unique identifier. + * + * @return The integer value. + */ + public int getIntValue() + { + return intValue; + } + + /** + * Set the integer value of the unique identifier. + * + * @param intValue The integer value to set. + */ + public void setIntValue(int intValue) + { + this.intValue = intValue; + } + + /** + * Check which type of identifier is being used (Text, Enum, or int). + * + * @return The type of identifier. + */ + public String getIdentifierType() + { + switch (flag) + { + case String: + return "Text String"; + case Enum: + return "Enumeration"; + case Integer: + return "Integer"; + } + return "Unknown"; + } + +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPVendorAttribute.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPVendorAttribute.java new file mode 100644 index 0000000000..5317d640a2 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/attribute/KMIPVendorAttribute.java @@ -0,0 +1,72 @@ +package org.bouncycastle.kmip.wire.attribute; + + +/** + * Represents a vendor-specific attribute used for sending and receiving Managed Object attributes. + * Vendor Identification and Attribute Name are text strings used to identify the attribute, while Attribute Value + * varies depending on the specific attribute. + *

      + * Vendor Attributes created by the client with Vendor Identification “x” are not created (provided during + * object creation), set, added, adjusted, modified or deleted by the server. + *

      + * Vendor Attributes created by the server with Vendor Identification “y” are not created (provided during + * object creation), set, added, adjusted, modified or deleted by the client. + */ +public class KMIPVendorAttribute +{ + + // Vendor identification (alphanumeric, underscore, and period allowed). + private String vendorIdentification; + + // Attribute name (text string). + private String attributeName; + + // Attribute value can vary depending on the attribute type (could be primitive or structured). + private Object attributeValue; + + /** + * Constructor for VendorAttribute. + * + * @param vendorIdentification The vendor identification value. + * @param attributeName The attribute name. + * @param attributeValue The attribute value (could vary in type). + */ + public KMIPVendorAttribute(String vendorIdentification, String attributeName, Object attributeValue) + { + this.vendorIdentification = vendorIdentification; + this.attributeName = attributeName; + this.attributeValue = attributeValue; + } + + // Getters and Setters + + public String getVendorIdentification() + { + return vendorIdentification; + } + + public void setVendorIdentification(String vendorIdentification) + { + this.vendorIdentification = vendorIdentification; + } + + public String getAttributeName() + { + return attributeName; + } + + public void setAttributeName(String attributeName) + { + this.attributeName = attributeName; + } + + public Object getAttributeValue() + { + return attributeValue; + } + + public void setAttributeValue(Object attributeValue) + { + this.attributeValue = attributeValue; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPAttestationType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPAttestationType.java new file mode 100644 index 0000000000..78252795ee --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPAttestationType.java @@ -0,0 +1,50 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public enum KMIPAttestationType + implements KMIPEnumeration +{ + TPMQuote(0x00000001), // TPM Quote + TCGIntegrityReport(0x00000002), // TCG Integrity Report + SAMLAssertion(0x00000003); // SAML Assertion + + private final int value; + + /** + * Constructor for AttestationType. + * + * @param value The hex value corresponding to the attestation type. + */ + KMIPAttestationType(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the attestation type. + * + * @return The hex value as an int. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves an AttestationType based on the provided value. + * + * @param value The hex value of the attestation type. + * @return The corresponding AttestationType enum. + * @throws IllegalArgumentException if the value does not match any attestation type. + */ + public static KMIPAttestationType fromValue(int value) + { + for (KMIPAttestationType type : KMIPAttestationType.values()) + { + if (type.getValue() == value) + { + return type; + } + } + throw new IllegalArgumentException("Unknown attestation type value: " + value); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPBlockCipherMode.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPBlockCipherMode.java new file mode 100644 index 0000000000..a4953c0cdc --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPBlockCipherMode.java @@ -0,0 +1,71 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * The BlockCipherMode enum represents various block cipher modes that can be used + * in cryptographic operations. + */ +public enum KMIPBlockCipherMode +{ + + CBC(1), // Cipher Block Chaining + ECB(2), // Electronic Codebook + PCBC(3), // Propagating Cipher Block Chaining + CFB(4), // Cipher Feedback + OFB(5), // Output Feedback + CTR(6), // Counter + CMAC(7), // Cipher-based Message Authentication Code + CCM(8), // Counter with CBC-MAC + GCM(9), // Galois/Counter Mode + CBC_MAC(10), // Cipher Block Chaining - Message Authentication Code + XTS(11), // XEX-based Tweaked Codebook Mode with Ciphertext Stealing + AESKeyWrapPadding(12), // AES Key Wrap with Padding + NISTKeyWrap(13), // NIST Key Wrap + X9_102_AESKW(14), // X9.102 AES Key Wrap + X9_102_TDKW(15), // X9.102 Tweakable Block Cipher Key Wrap + X9_102_AKW1(16), // X9.102 AKW1 + X9_102_AKW2(17), // X9.102 AKW2 + AEAD(18); // Authenticated Encryption with Associated Data + //EXTENSIONS("8XXXXXXX"); // Extensions for future use + + private final int value; + + /** + * Constructor for BlockCipherMode. + * + * @param value The hex value corresponding to the block cipher mode. + */ + KMIPBlockCipherMode(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the block cipher mode. + * + * @return The hex value as a String. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a BlockCipherMode based on the provided value. + * + * @param value The hex value of the block cipher mode. + * @return The corresponding BlockCipherMode enum. + * @throws IllegalArgumentException if the value does not match any mode. + */ + public static KMIPBlockCipherMode fromValue(int value) + { + for (KMIPBlockCipherMode mode : KMIPBlockCipherMode.values()) + { + if (mode.value == value) + { + return mode; + } + } + throw new IllegalArgumentException("Unknown block cipher mode value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPCryptographicAlgorithm.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPCryptographicAlgorithm.java new file mode 100644 index 0000000000..7c498fbc45 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPCryptographicAlgorithm.java @@ -0,0 +1,108 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * The CryptographicAlgorithm enum represents various cryptographic algorithms and their corresponding values. + */ +public enum KMIPCryptographicAlgorithm + implements KMIPEnumeration +{ + DES(0x01), // DES + TRIPLE_DES(0x02), // 3DES + AES(0x03), // AES + RSA(0x04), // RSA + DSA(0x05), // DSA + ECDSA(0x06), // ECDSA + HMAC_SHA1(0x07), // HMAC-SHA1 + HMAC_SHA224(0x08), // HMAC-SHA224 + HMAC_SHA256(0x09), // HMAC-SHA256 + HMAC_SHA384(0x0A), // HMAC-SHA384 + HMAC_SHA512(0x0B), // HMAC-SHA512 + HMAC_MD5(0x0C), // HMAC-MD5 + DH(0x0D), // DH (Diffie-Hellman) + ECDH(0x0E), // ECDH (Elliptic Curve Diffie-Hellman) + ECMQV(0x0F), // ECMQV + Blowfish(0x10), // Blowfish + Camellia(0x11), // Camellia + CAST5(0x12), // CAST5 + IDEA(0x13), // IDEA + MARS(0x14), // MARS + RC2(0x15), // RC2 + RC4(0x16), // RC4 + RC5(0x17), // RC5 + SKIPJACK(0x18), // SKIPJACK + Twofish(0x19), // Twofish + EC(0x1A), // EC (Elliptic Curve) + OneTimePad(0x1B), // One Time Pad + ChaCha20(0x1C), // ChaCha20 + Poly1305(0x1D), // Poly1305 + ChaCha20Poly1305(0x1E), // ChaCha20Poly1305 + SHA3_224(0x1F), // SHA3-224 + SHA3_256(0x20), // SHA3-256 + SHA3_384(0x21), // SHA3-384 + SHA3_512(0x22), // SHA3-512 + HMAC_SHA3_224(0x23), // HMAC-SHA3-224 + HMAC_SHA3_256(0x24), // HMAC-SHA3-256 + HMAC_SHA3_384(0x25), // HMAC-SHA3-384 + HMAC_SHA3_512(0x26), // HMAC-SHA3-512 + SHAKE_128(0x27), // SHAKE-128 + SHAKE_256(0x28), // SHAKE-256 + ARIA(0x29), // ARIA + SEED(0x2A), // SEED + SM2(0x2B), // SM2 + SM3(0x2C), // SM3 + SM4(0x2D), // SM4 + GOST_R_34_10_2012(0x2E), // GOST R 34.10-2012 + GOST_R_34_11_2012(0x2F), // GOST R 34.11-2012 + GOST_R_34_13_2015(0x30), // GOST R 34.13-2015 + GOST_28147_89(0x31), // GOST 28147-89 + XMSS(0x32), // XMSS + SPHINCS_256(0x33), // SPHINCS-256 + McEliece(0x34), // McEliece + McEliece_6960119(0x35), // McEliece-6960119 + McEliece_8192128(0x36), // McEliece-8192128 + ED25519(0x37), // Ed25519 + ED448(0x38); // Ed448 + //EXTENSIONS("8XXXXXXX"); // Extensions for future use + + private final int value; + + /** + * Constructor for CryptographicAlgorithm. + * + * @param value The hex value corresponding to the cryptographic algorithm. + */ + KMIPCryptographicAlgorithm(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the cryptographic algorithm. + * + * @return The hex value as a String. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a CryptographicAlgorithm based on the provided value. + * + * @param value The hex value of the cryptographic algorithm. + * @return The corresponding CryptographicAlgorithm enum. + * @throws IllegalArgumentException if the value does not match any algorithm. + */ + public static KMIPCryptographicAlgorithm fromValue(int value) + { + for (KMIPCryptographicAlgorithm algorithm : KMIPCryptographicAlgorithm.values()) + { + if (algorithm.value == value) + { + return algorithm; + } + } + throw new IllegalArgumentException("Unknown cryptographic algorithm value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPCryptographicUsageMask.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPCryptographicUsageMask.java new file mode 100644 index 0000000000..1b23e991ce --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPCryptographicUsageMask.java @@ -0,0 +1,49 @@ +package org.bouncycastle.kmip.wire.enumeration; + + +// Enum representing cryptographic usage mask +public enum KMIPCryptographicUsageMask + implements KMIPEnumeration +{ + Sign(0x00000001), + Verify(0x00000002), + Encrypt(0x00000004), + Decrypt(0x00000008), + WrapKey(0x00000010), + UnwrapKey(0x00000020), + MacGenerate(0x00000080), + MacVerify(0x00000100), + DeriveKey(0x00000200), + KeyAgreement(0x00000800), + CertificateSign(0x00001000), + CrlSign(0x00002000), + Authenticate(0x00100000), + Unrestricted(0x00200000), + FpeEncrypt(0x00400000), + FpeDecrypt(0x00800000); + + private final int value; + + KMIPCryptographicUsageMask(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static KMIPCryptographicUsageMask fromValue(int value) + { + for (KMIPCryptographicUsageMask algorithm : KMIPCryptographicUsageMask.values()) + { + if (algorithm.value == value) + { + return algorithm; + } + } + throw new IllegalArgumentException("Unknown cryptographic algorithm value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPDigitalSignatureAlgorithm.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPDigitalSignatureAlgorithm.java new file mode 100644 index 0000000000..cce71701a3 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPDigitalSignatureAlgorithm.java @@ -0,0 +1,70 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * The DigitalSignatureAlgorithm enum represents various algorithms used for digital signatures. + */ +public enum KMIPDigitalSignatureAlgorithm +{ + MD2_WITH_RSA_ENCRYPTION(0x01), // MD2 with RSA Encryption + MD5_WITH_RSA_ENCRYPTION(0x02), // MD5 with RSA Encryption + SHA1_WITH_RSA_ENCRYPTION(0x03), // SHA-1 with RSA Encryption + SHA224_WITH_RSA_ENCRYPTION(0x04), // SHA-224 with RSA Encryption + SHA256_WITH_RSA_ENCRYPTION(0x05), // SHA-256 with RSA Encryption + SHA384_WITH_RSA_ENCRYPTION(0x06), // SHA-384 with RSA Encryption + SHA512_WITH_RSA_ENCRYPTION(0x07), // SHA-512 with RSA Encryption + RSASSA_PSS(0x08), // RSASSA-PSS + DSA_WITH_SHA1(0x09), // DSA with SHA-1 + DSA_WITH_SHA224(0x0A), // DSA with SHA-224 + DSA_WITH_SHA256(0x0B), // DSA with SHA-256 + ECDSA_WITH_SHA1(0x0C), // ECDSA with SHA-1 + ECDSA_WITH_SHA224(0x0D), // ECDSA with SHA-224 + ECDSA_WITH_SHA256(0x0E), // ECDSA with SHA-256 + ECDSA_WITH_SHA384(0x0F), // ECDSA with SHA-384 + ECDSA_WITH_SHA512(0x10), // ECDSA with SHA-512 + SHA3_256_WITH_RSA_ENCRYPTION(0x11), // SHA3-256 with RSA Encryption + SHA3_384_WITH_RSA_ENCRYPTION(0x12), // SHA3-384 with RSA Encryption + SHA3_512_WITH_RSA_ENCRYPTION(0x13); // SHA3-512 with RSA Encryption + //EXTENSIONS("8XXXXXXX"); // Extensions for future use + + private final int value; + + /** + * Constructor for DigitalSignatureAlgorithm. + * + * @param value The hex value corresponding to the digital signature algorithm. + */ + KMIPDigitalSignatureAlgorithm(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the digital signature algorithm. + * + * @return The hex value as a String. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a DigitalSignatureAlgorithm based on the provided value. + * + * @param value The hex value of the digital signature algorithm. + * @return The corresponding DigitalSignatureAlgorithm enum. + * @throws IllegalArgumentException if the value does not match any algorithm. + */ + public static KMIPDigitalSignatureAlgorithm fromValue(int value) + { + for (KMIPDigitalSignatureAlgorithm algorithm : KMIPDigitalSignatureAlgorithm.values()) + { + if (algorithm.value == value) + { + return algorithm; + } + } + throw new IllegalArgumentException("Unknown digital signature algorithm value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPEncodingOption.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPEncodingOption.java new file mode 100644 index 0000000000..cf8aa04533 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPEncodingOption.java @@ -0,0 +1,52 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enum representing the Encoding Option Enumeration. + *

      + * This enum defines the available encoding options for cryptographic key materials. + * Each option corresponds to a specific value that can be used in the context of + * key management operations. + *

      + */ +public enum KMIPEncodingOption +{ + + /** + * Represents no encoding, indicating that the wrapped + * un-encoded value of the Byte String Key Material field + * is to be used. + */ + NO_ENCODING(1), + + /** + * Represents TTLV encoding, indicating that the wrapped + * TTLV-encoded Key Value structure is to be used. + */ + NTTLV_ENCODING(2); + + //EXTENSIONS("8XXXXXXX"); + private final int value; + + KMIPEncodingOption(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static KMIPEncodingOption fromValue(int value) + { + for (KMIPEncodingOption algorithm : KMIPEncodingOption.values()) + { + if (algorithm.value == value) + { + return algorithm; + } + } + throw new IllegalArgumentException("Unknown encoding option value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPEnumeration.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPEnumeration.java new file mode 100644 index 0000000000..7fb5cc9a22 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPEnumeration.java @@ -0,0 +1,6 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public interface KMIPEnumeration +{ + int getValue(); +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPHashingAlgorithm.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPHashingAlgorithm.java new file mode 100644 index 0000000000..2ad916126b --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPHashingAlgorithm.java @@ -0,0 +1,71 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * The HashingAlgorithm enum represents various hashing algorithms + * used in cryptographic operations. + */ +public enum KMIPHashingAlgorithm +{ + + MD2(0x01), // MD2 hashing algorithm + MD4(0x02), // MD4 hashing algorithm + MD5(0x03), // MD5 hashing algorithm + SHA_1(0x04), // SHA-1 hashing algorithm + SHA_224(0x05), // SHA-224 hashing algorithm + SHA_256(0x06), // SHA-256 hashing algorithm + SHA_384(0x07), // SHA-384 hashing algorithm + SHA_512(0x08), // SHA-512 hashing algorithm + RIPEMD_160(0x09), // RIPEMD-160 hashing algorithm + TIGER(0x0A), // Tiger hashing algorithm + WHIRLPOOL(0x0B), // Whirlpool hashing algorithm + SHA_512_224(0x0C), // SHA-512/224 hashing algorithm + SHA_512_256(0x0D), // SHA-512/256 hashing algorithm + SHA3_224(0x0E), // SHA3-224 hashing algorithm + SHA3_256(0x0F), // SHA3-256 hashing algorithm + SHA3_384(0x10), // SHA3-384 hashing algorithm + SHA3_512(0x11); // SHA3-512 hashing algorithm + //EXTENSIONS("8XXXXXXX"); // Extensions for future use + + private final int value; + + /** + * Constructor for HashingAlgorithm. + * + * @param value The hex value corresponding to the hashing algorithm. + */ + KMIPHashingAlgorithm(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the hashing algorithm. + * + * @return The hex value as a String. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a HashingAlgorithm based on the provided value. + * + * @param value The hex value of the hashing algorithm. + * @return The corresponding HashingAlgorithm enum. + * @throws IllegalArgumentException if the value does not match any algorithm. + */ + public static KMIPHashingAlgorithm fromValue(int value) + { + for (KMIPHashingAlgorithm algorithm : KMIPHashingAlgorithm.values()) + { + if (algorithm.value == value) + { + return algorithm; + } + } + throw new IllegalArgumentException("Unknown hashing algorithm value: " + value); + } +} + + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyCompressionType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyCompressionType.java new file mode 100644 index 0000000000..432a5decd0 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyCompressionType.java @@ -0,0 +1,53 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enumeration representing the key compression types for elliptic curve public keys. + */ +public enum KMIPKeyCompressionType +{ + UNCOMPRESSED(0x01), + COMPRESSED_PRIME(0x02), + COMPRESSED_CHAR2(0x03), + HYBRID(0x04); + //EXTENSIONS("8XXXXXXX"); + + private final int value; + + /** + * Constructor to initialize the enumeration with its value. + * + * @param value the string value associated with the key compression type. + */ + KMIPKeyCompressionType(int value) + { + this.value = value; + } + + /** + * Returns the string value of the key compression type. + * + * @return the string value of the key compression type. + */ + public int getValue() + { + return value; + } + + /** + * Returns the KeyCompressionType constant corresponding to the given string value. + * + * @param value the string value to find the corresponding KeyCompressionType. + * @return the KeyCompressionType corresponding to the given value, or null if not found. + */ + public static KMIPKeyCompressionType fromValue(int value) + { + for (KMIPKeyCompressionType kct : KMIPKeyCompressionType.values()) + { + if (kct.getValue() == value) + { + return kct; + } + } + throw new IllegalArgumentException("Unknown key compression type value: " + value); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyFormatType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyFormatType.java new file mode 100644 index 0000000000..bbc03a52a5 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyFormatType.java @@ -0,0 +1,68 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enumeration representing the key format types for cryptographic keys. + */ +public enum KMIPKeyFormatType + implements KMIPEnumeration +{ + Raw(0x01), + Opaque(0x02), + PKCS1(0x03), + PKCS8(0x04), + X509(0x05), + ECPrivateKey(0x06), + TransparentSymmetricKey(0x07), + TransparentDSAPrivateKey(0x08), + TransparentDSAPublicKey(0x09), + TransparentRSAPrivateKey(0x0A), + TransparentRSAPublicKey(0x0B), + TransparentDHPrivateKey(0x0C), + TransparentDHPublicKey(0x0D), + TransparentECPrivateKey(0x14), + TransparentECPublicKey(0x15), + PKCS12(0x16), + PKCS10(0x17); + //EXTENSIONS("8XXXXXXX"); + + private final int value; + + /** + * Constructor to initialize the enumeration with its value. + * + * @param value the string value associated with the key format type. + */ + KMIPKeyFormatType(int value) + { + this.value = value; + } + + /** + * Returns the string value of the key format type. + * + * @return the string value of the key format type. + */ + public int getValue() + { + return value; + } + + /** + * Returns the KeyFormatType constant corresponding to the given string value. + * + * @param value the string value to find the corresponding KeyFormatType. + * @return the KeyFormatType corresponding to the given value, or null if not found. + */ + public static KMIPKeyFormatType fromValue(int value) + { + for (KMIPKeyFormatType kft : KMIPKeyFormatType.values()) + { + if (kft.getValue() == value) + { + return kft; + } + } + throw new IllegalArgumentException("Unknown key format type value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyRoleType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyRoleType.java new file mode 100644 index 0000000000..98b9381b49 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyRoleType.java @@ -0,0 +1,80 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * The KeyRoleType enum represents various roles a cryptographic key can take in cryptographic operations. + *

      + * Note that while the set and definitions of key role types are chosen to match [X9 TR-31](ANSI, X9 TR-31: Interoperable + * Secure Key Exchange Key Block Specification for Symmetric Algorithms, 2010.) there is no necessity to match binary + * representations. + */ +public enum KMIPKeyRoleType +{ + BDK(0x01), // Base Derivation Key + CVK(0x02), // Card Verification Key + DEK(0x03), // Data Encryption Key + MKAC(0x04), // Master Key Application Cryptogram + MKSMC(0x05), // Master Key Secure Messaging - Confidentiality + MKSMI(0x06), // Master Key Secure Messaging - Integrity + MKDAC(0x07), // Master Key Dynamic Authentication Cryptogram + MKDN(0x08), // Master Key Data Network + MKCP(0x09), // Master Key Common Platform + MKOTH(0x0A), // Master Key Other + KEK(0x0B), // Key Encryption Key + MAC16609(0x0C), // MAC Key for ANSI X9.24 Part 1: 2009 + MAC97971(0x0D), // MAC Key for ISO 9797-1: 2011 MAC Algorithm 1 + MAC97972(0x0E), // MAC Key for ISO 9797-1: 2011 MAC Algorithm 2 + MAC97973(0x0F), // MAC Key for ISO 9797-1: 2011 MAC Algorithm 3 + MAC97974(0x10), // MAC Key for ISO 9797-1: 2011 MAC Algorithm 4 + MAC97975(0x11), // MAC Key for ISO 9797-1: 2011 MAC Algorithm 5 + ZPK(0x12), // Zone PIN Key + PVKIBM(0x13), // PIN Verification Key - IBM + PVKPVV(0x14), // PIN Verification Key - PVV + PVKOTH(0x15), // PIN Verification Key - Other + DUKPT(0x16), // Derived Unique Key Per Transaction + IV(0x17), // Initialization Vector + TRKBK(0x18); // Track Block Key + //EXTENSIONS("8XXXXXXX"); // Extensions for future use + + private final int value; + + /** + * Constructor for KeyRoleType. + * + * @param value The hex value corresponding to the key role type. + */ + KMIPKeyRoleType(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the key role type. + * + * @return The hex value as a String. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a KeyRoleType based on the provided value. + * + * @param value The hex value of the key role type. + * @return The corresponding KeyRoleType enum. + * @throws IllegalArgumentException if the value does not match any role type. + */ + public static KMIPKeyRoleType fromValue(int value) + { + for (KMIPKeyRoleType role : KMIPKeyRoleType.values()) + { + if (role.value == value) + { + return role; + } + } + throw new IllegalArgumentException("Unknown key role type value: " + value); + } +} + + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyWrapType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyWrapType.java new file mode 100644 index 0000000000..fea24eb42c --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPKeyWrapType.java @@ -0,0 +1,48 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public enum KMIPKeyWrapType +{ + NotWrapped(0x00000001), + AsRegistered(0x00000002); + + private final int value; + + /** + * Constructor for Key Wrap Type enumeration. + * + * @param value The integer (hex) value associated with the name type. + */ + KMIPKeyWrapType(int value) + { + this.value = value; + } + + /** + * Returns the integer (hex) value associated with the name type. + * + * @return The value of the name type. + */ + public int getValue() + { + return value; + } + + /** + * Returns the Key Wrap Type constant corresponding to the given integer value. + * + * @param value The integer value of the Key Wrap Type. + * @return The corresponding NameType constant. + * @throws IllegalArgumentException if the value does not match any Key Wrap Type. + */ + public static KMIPKeyWrapType fromValue(int value) + { + for (KMIPKeyWrapType type : KMIPKeyWrapType.values()) + { + if (type.getValue() == value) + { + return type; + } + } + throw new IllegalArgumentException("Unknown NameType value: " + value); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPMaskGenerator.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPMaskGenerator.java new file mode 100644 index 0000000000..a290325e1c --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPMaskGenerator.java @@ -0,0 +1,51 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enumeration representing the mask generators used in cryptographic operations. + */ +public enum KMIPMaskGenerator +{ + MGF1(1); +// EXTENSIONS("8XXXXXXX"); + + private final int value; + + /** + * Constructor to initialize the enumeration with its value. + * + * @param value the string value associated with the mask generator. + */ + KMIPMaskGenerator(int value) + { + this.value = value; + } + + /** + * Returns the string value of the mask generator. + * + * @return the string value of the mask generator. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a KMIPMaskGenerator based on the provided value. + * + * @param value The hex value of the mask generator. + * @return The corresponding KeyRoleType enum. + * @throws IllegalArgumentException if the value does not match any role type. + */ + public static KMIPMaskGenerator fromValue(int value) + { + for (KMIPMaskGenerator mg : KMIPMaskGenerator.values()) + { + if (mg.value == value) + { + return mg; + } + } + throw new IllegalArgumentException("Unknown mask generator value: " + value); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPNameType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPNameType.java new file mode 100644 index 0000000000..4dd58950cb --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPNameType.java @@ -0,0 +1,53 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enumeration representing the type of a name in the key management system. + */ +public enum KMIPNameType + implements KMIPEnumeration +{ + UninterpretedTextString(0x00000001), // Human-readable text not interpreted by the system + URI(0x00000002); // Uniform Resource Identifier + + private final int value; + + /** + * Constructor for NameType enumeration. + * + * @param value The integer (hex) value associated with the name type. + */ + KMIPNameType(int value) + { + this.value = value; + } + + /** + * Returns the integer (hex) value associated with the name type. + * + * @return The value of the name type. + */ + public int getValue() + { + return value; + } + + /** + * Returns the NameType constant corresponding to the given integer value. + * + * @param value The integer value of the name type. + * @return The corresponding NameType constant. + * @throws IllegalArgumentException if the value does not match any NameType. + */ + public static KMIPNameType fromValue(int value) + { + for (KMIPNameType type : KMIPNameType.values()) + { + if (type.getValue() == value) + { + return type; + } + } + throw new IllegalArgumentException("Unknown NameType value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPObjectType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPObjectType.java new file mode 100644 index 0000000000..65db13a8ea --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPObjectType.java @@ -0,0 +1,51 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enumeration of Object Types. + */ +public enum KMIPObjectType + implements KMIPEnumeration +{ + Certificate(0x01), + SymmetricKey(0x02), + PublicKey(0x03), + PrivateKey(0x04), + SplitKey(0x05), + Reserved(0x06), + SecretData(0x07), + OpaqueObject(0x08), + PgpKey(0x09), + CertificateRequest(0x0A); + + private final int value; + + KMIPObjectType(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + /** + * Returns the ObjectType corresponding to the given value. + * + * @param value the integer value of the ObjectType + * @return the corresponding ObjectType + * @throws IllegalArgumentException if the value does not correspond to any ObjectType + */ + public static KMIPObjectType fromValue(int value) + { + for (KMIPObjectType type : KMIPObjectType.values()) + { + if (type.getValue() == value) + { + return type; + } + } + throw new IllegalArgumentException("No ObjectType found for value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPOperation.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPOperation.java new file mode 100644 index 0000000000..4a784345e7 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPOperation.java @@ -0,0 +1,96 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public enum KMIPOperation + implements KMIPEnumeration +{ + Create(0x00000001), + CreateKeyPair(0x00000002), + Register(0x00000003), + Rekey(0x00000004), + DeriveKey(0x00000005), + Certify(0x00000006), + Recertify(0x00000007), + Locate(0x00000008), + Check(0x00000009), + Get(0x0000000A), + GetAttributes(0x0000000B), + GetAttributeList(0x0000000C), + AddAttribute(0x0000000D), + ModifyAttribute(0x0000000E), + DeleteAttribute(0x0000000F), + ObtainLease(0x00000010), + GetUsageAllocation(0x00000011), + Activate(0x00000012), + Revoke(0x00000013), + Destroy(0x00000014), + Archive(0x00000015), + Recover(0x00000016), + Validate(0x00000017), + Query(0x00000018), + Cancel(0x00000019), + Poll(0x0000001A), + Notify(0x0000001B), + Put(0x0000001C), + RekeyKeyPair(0x0000001D), + DiscoverVersions(0x0000001E), + Encrypt(0x0000001F), + Decrypt(0x00000020), + Sign(0x00000021), + SignatureVerify(0x00000022), + Mac(0x00000023), + MacVerify(0x00000024), + RngRetrieve(0x00000025), + RngSeed(0x00000026), + Hash(0x00000027), + CreateSplitKey(0x00000028), + JoinSplitKey(0x00000029), + Import(0x0000002A), + Export(0x0000002B), + Log(0x0000002C), + Login(0x0000002D), + Logout(0x0000002E), + DelegatedLogin(0x0000002F), + AdjustAttribute(0x00000030), + SetAttribute(0x00000031), + SetEndpointRole(0x00000032), + Pkcs11(0x00000033), + Interop(0x00000034), + ReProvision(0x00000035), + SetDefaults(0x00000036), + SetConstraints(0x00000037), + GetConstraints(0x00000038), + QueryAsyncRequests(0x00000039), + Process(0x0000003A), + Ping(0x0000003B); + + private final int value; + + KMIPOperation(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static KMIPOperation fromValue(int value) + { + for (KMIPOperation op : values()) + { + if (op.value == value) + { + return op; + } + } + throw new IllegalArgumentException("Invalid Operation value: " + value); + } + + @Override + public String toString() + { + return String.format("%s (0x%08X)", name(), value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPPaddingMethod.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPPaddingMethod.java new file mode 100644 index 0000000000..156973555b --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPPaddingMethod.java @@ -0,0 +1,63 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * The PaddingMethod enum represents various padding methods used + * in cryptographic operations. + */ +public enum KMIPPaddingMethod +{ + + NONE(0x01), // No padding + OAEP(0x02), // Optimal Asymmetric Encryption Padding + PKCS5(0x03), // PKCS#5 Padding + SSL3(0x04), // SSL 3.0 Padding + ZEROS(0x05), // Padding with zeros + ANSI_X9_23(0x06), // ANSI X9.23 Padding + ISO_10126(0x07), // ISO 10126 Padding + PKCS1_V1_5(0x08), // PKCS#1 v1.5 Padding + X9_31(0x09), // X9.31 Padding + PSS(0x0A); // Probabilistic Signature Scheme (PSS) Padding + //EXTENSIONS("8XXXXXXX"); // Extensions for future use + + private final int value; + + /** + * Constructor for PaddingMethod. + * + * @param value The hex value corresponding to the padding method. + */ + KMIPPaddingMethod(int value) + { + this.value = value; + } + + /** + * Gets the hex value associated with the padding method. + * + * @return The hex value as a String. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a PaddingMethod based on the provided value. + * + * @param value The hex value of the padding method. + * @return The corresponding PaddingMethod enum. + * @throws IllegalArgumentException if the value does not match any method. + */ + public static KMIPPaddingMethod fromValue(int value) + { + for (KMIPPaddingMethod method : KMIPPaddingMethod.values()) + { + if (method.value == value) + { + return method; + } + } + throw new IllegalArgumentException("Unknown padding method value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPResultReason.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPResultReason.java new file mode 100644 index 0000000000..bef234ca2d --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPResultReason.java @@ -0,0 +1,399 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * This field indicates a reason for failure or a modifier for a partially successful operation and SHALL be + * present in responses that return a Result Status of Failure. In such a case, the Result Reason SHALL be + * set as specified. It SHALL NOT be present in any response that returns a Result Status of Success. + */ +public enum KMIPResultReason + implements KMIPEnumeration +{ + + /** + * No object with the specified Unique Identifier exists. + */ + ItemNotFound(0x00000001), + + /** + * Maximum Response Size has been exceeded. + */ + ResponseTooLarge(0x00000002), + + /** + * The authentication information in the request could not be validated, or was not found. + */ + AuthenticationNotSuccessful(0x00000003), + + /** + * The request message was not syntactically understood by the server. + */ + InvalidMessage(0x00000004), + + /** + * The operation requested by the request message is not supported by the server. + */ + OperationNotSupported(0x00000005), + + /** + * The operation required additional information in the request, which was not present. + */ + MissingData(0x00000006), + + /** + * The request is syntactically valid but some data in the request (other than an attribute value) has an invalid value. + */ + InvalidField(0x00000007), + + /** + * The operation is supported, but a specific feature specified in the request is not supported. + */ + FeatureNotSupported(0x00000008), + + /** + * The asynchronous operation was canceled by the Cancel operation before it completed successfully. + */ + OperationCanceledByRequester(0x00000009), + + /** + * The operation failed due to a cryptographic error. + */ + CryptographicFailure(0x0000000A), + + /** + * Client is not allowed to perform the specified operation. + */ + PermissionDenied(0x0000000C), + + /** + * The object SHALL be recovered from the archive before performing the operation. + */ + ObjectArchived(0x0000000D), + + /** + * The particular Application Namespace is not + * supported, and the server was not able to generate + * the Application Data field of an Application Specific + * Information attribute if the field was omitted from + * the client request + */ + ApplicationNamespaceNotSupported(0x0000000F), + + /** + * The object exists, but the server is unable to provide it in the desired Key Format Type. + */ + KeyFormatTypeNotSupported(0x00000010), + + /** + * The object exists, but the server is unable to provide it in the desired Key Compression Type. + */ + KeyCompressionTypeNotSupported(0x00000011), + + /** + * The Encoding Option is not supported as specified by the Encoding Option Enumeration. + */ + EncodingOptionError(0x00000012), + + /** + * A meta-data only object. The key value is not present on the server. + */ + KeyValueNotPresent(0x00000013), + + /** + * Operation requires attestation data which was not + * provided by the client, and the client has set the + * Attestation Capable indicator to True + */ + AttestationRequired(0x00000014), + + /** + * Operation requires attestation data and the + * attestation data provided by the client does not + * validate + */ + AttestationFailed(0x00000015), + + /** + * Sensitive keys may not be retrieved unwrapped. + */ + Sensitive(0x00000016), + + /** + * Object is not extractable. + */ + NotExtractable(0x00000017), + + /** + * for operations such as Import that require that no object with a specific unique identifier exists on a server + */ + ObjectAlreadyExists(0x00000018), + + /** + * The ticket provided was invalid. + */ + InvalidTicket(0x00000019), + + /** + * The usage limits or request count has been exceeded. + */ + UsageLimitExceeded(0x0000001A), + + /** + * The operation produced a number that is too large or too small to be stored in the specified data type. + */ + NumericRange(0x0000001B), + + /** + * A data type was invalid for the requested operation. + */ + InvalidDataType(0x0000001C), + + /** + * Attempt to set a Read Only Attribute. + */ + ReadOnlyAttribute(0x0000001D), + + /** + * Attempt to Set or Adjust an attribute that has multiple values + */ + MultiValuedAttribute(0x0000001E), + + /** + * Attribute is valid in the specification but unsupported by the server. + */ + UnsupportedAttribute(0x0000001F), + + /** + * A referenced attribute was found, but the specific instance was not found. + */ + AttributeInstanceNotFound(0x00000020), + + /** + * A referenced attribute was not found at all on an object + */ + AttributeNotFound(0x00000021), + + /** + * Attempt to set a Read Only Attribute. + */ + AttributeReadOnly(0x00000022), + + /** + * Attempt to provide multiple values for a single instance attribute. + */ + AttributeSingleValued(0x00000023), + + /** + * The cryptographic parameters provided are invalid. + */ + BadCryptographicParameters(0x00000024), + + /** + * Key Format Type is PKCS#12, but missing or + * multiple PKCS#12 Password Links, or not Secret + * Data, or not Active + */ + BadPassword(0x00000025), + + /** + * The low level TTLV, XML, JSON etc. was badly + * formed and not understood by the server.TTLV + * connections should be closed as future requests + * might not be correctly separated + */ + CodecError(0x00000026), + + /** + * Check cannot be performed on this object type. + */ + IllegalObjectType(0x00000028), + + /** + * The cryptographic algorithm or other parameters are not valid for the requested operation. + */ + IncompatibleCryptographicUsageMask(0x00000029), + + /** + * The server encountered an internal error and could not process the request at this time. + */ + InternalServerError(0x0000002A), + + /** + * No outstanding operation with the specified Asynchronous Correlation Value exists. + */ + InvalidAsynchronousCorrelationValue(0x0000002B), + + /** + * An attribute is invalid for this object or operation. + */ + InvalidAttribute(0x0000002C), + + /** + * The value supplied for an attribute is invalid. + */ + InvalidAttributeValue(0x0000002D), + + /** + * For streaming cryptographic operations, the correlation value is invalid. + */ + InvalidCorrelationValue(0x0000002E), + + /** + * Invalid Certificate Signing Request (CSR). + */ + InvalidCSR(0x0000002F), + + /** + * Specified object is not valid for the requested operation. + */ + InvalidObjectType(0x00000030), + + /** + * Key Wrap Type Type is not supported by the server + */ + KeyWrapTypeNotSupported(0x00000032), + + /** + * Missing IV when required for crypto operation + */ + MissingInitializationVector(0x00000034), + + /** + * Trying to perform an operation that requests the server to break the constraint on Name attribute being unique + */ + NonUniqueNameAttribute(0x00000035), + + /** + * Object exists, but has already been destroyed. + */ + ObjectDestroyed(0x00000036), + + /** + * A requested managed object was not found or did not exist. + */ + ObjectNotFound(0x00000037), + + /** + * Server limit has been exceeded, such as database size limit. + */ + ServerLimitExceeded(0x0000003A), + + /** + * An enumerated value is not known by the server. + */ + UnknownEnumeration(0x0000003B), + + /** + * The server does not support the supplied Message Extension. + */ + UnknownMessageExtension(0x0000003C), + + /** + * A tag is not known by the server. + */ + UnknownTag(0x0000003D), + + /** + * The cryptographic parameters are valid but unsupported by the server. + */ + UnsupportedCryptographicParameters(0x0000003E), + + /** + * The operation cannot be performed with the provided protocol version. + */ + UnsupportedProtocolVersion(0x0000003F), + + /** + * The Wrapping Object is archived. + */ + WrappingObjectArchived(0x00000040), + + /** + * The Wrapping Object exists, but is destroyed. + */ + WrappingObjectDestroyed(0x00000041), + + /** + * The Wrapping Object does not exist. + */ + WrappingObjectNotFound(0x00000042), + + /** + * The key lifecycle state is invalid for the operation, for example not Active for an Encrypt operation. + */ + WrongKeyLifecycleState(0x00000043), + + /** + * The operation could not be completed with the protections requested (or defaulted). + */ + ProtectionStorageUnavailable(0x00000044), + + /** + * There is a codec error in the PKCS#11 input parameter. + */ + PKCS11CodecError(0x00000045), + + /** + * The PKCS#11 function is invalid or unsupported. + */ + PKCS11InvalidFunction(0x00000046), + + /** + * The PKCS#11 interface is unknown or unavailable. + */ + PKCS11InvalidInterface(0x00000047), + + /** + * The operation could not be completed with the protections requested (or defaulted). + */ + PrivateProtectionStorageUnavailable(0x00000048), + + /** + * The operation could not be completed with the protections requested (or defaulted). + */ + PublicProtectionStorageUnavailable(0x00000049), + + /** + * + */ + UnknownObjectGroup(0x0000004A), + + /** + * The request failed because one or more constraints were violated. + */ + ConstraintViolation(0x0000004B), + + /** + * The asynchronous request specified was already processed. + */ + DuplicateProcessRequest(0x0000004C), + + /** + * The request failed for a reason other than the defined reasons above + */ + GeneralFailure(0x00000100); + + private final int value; + + KMIPResultReason(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static KMIPResultReason fromValue(int value) + { + for (KMIPResultReason algorithm : KMIPResultReason.values()) + { + if (algorithm.value == value) + { + return algorithm; + } + } + throw new IllegalArgumentException("Unknown cryptographic algorithm value: " + value); + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPResultStatus.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPResultStatus.java new file mode 100644 index 0000000000..8d0bf63303 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPResultStatus.java @@ -0,0 +1,61 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enumeration representing the possible result statuses for an operation. + */ +public enum KMIPResultStatus + implements KMIPEnumeration +{ + Success(0x00000000), // Success + OperationFailed(0x00000001), // Operation Failed + OperationPending(0x00000002), // Operation Pending + OperationUndone(0x00000003); // Operation Undone + + private final int value; + + /** + * Constructor for ResultStatus enum. + * + * @param value The integer value representing the status code. + */ + KMIPResultStatus(int value) + { + this.value = value; + } + + /** + * Gets the integer value associated with the result status. + * + * @return The integer value of the result status. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves a ResultStatus based on the provided integer value. + * + * @param value The integer value of the result status. + * @return The corresponding ResultStatus enum. + * @throws IllegalArgumentException if the value does not match any result status. + */ + public static KMIPResultStatus fromValue(int value) + { + for (KMIPResultStatus status : KMIPResultStatus.values()) + { + if (status.getValue() == value) + { + return status; + } + } + throw new IllegalArgumentException("Unknown result status value: " + Integer.toHexString(value)); + } + + @Override + public String toString() + { + return name() + "(0x" + Integer.toHexString(value) + ")"; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPSecretDataType.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPSecretDataType.java new file mode 100644 index 0000000000..99491d5498 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPSecretDataType.java @@ -0,0 +1,32 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public enum KMIPSecretDataType +{ + Password(0x00000001), + + Seed(0x00000002); + + private final int value; + + KMIPSecretDataType(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static KMIPSecretDataType fromValue(int value) + { + for (KMIPSecretDataType type : KMIPSecretDataType.values()) + { + if (type.getValue() == value) + { + return type; + } + } + throw new IllegalArgumentException("No SecretDataType found for value: " + value); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPSplitKeyMethod.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPSplitKeyMethod.java new file mode 100644 index 0000000000..b7484a6ac9 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPSplitKeyMethod.java @@ -0,0 +1,54 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public enum KMIPSplitKeyMethod + implements KMIPEnumeration +{ + XOR(0x00000001), // XOR method + PolynomialSharingGF2_16(0x00000002), // Polynomial Sharing GF (2^16) + PolynomialSharingPrimeField(0x00000003), // Polynomial Sharing Prime Field + PolynomialSharingGF2_8(0x00000004); // Polynomial Sharing GF (2^8) + + private final int value; + + KMIPSplitKeyMethod(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + /** + * Returns the SplitKeyMethod corresponding to the given value. + * + * @param value the integer value of the SplitKeyMethod + * @return the corresponding SplitKeyMethod + * @throws IllegalArgumentException if the value does not correspond to any SplitKeyMethod + */ + public static KMIPSplitKeyMethod fromValue(int value) + { + for (KMIPSplitKeyMethod method : KMIPSplitKeyMethod.values()) + { + if (method.getValue() == value) + { + return method; + } + } + throw new IllegalArgumentException("No SplitKeyMethod found for value: " + value); + } + + /** + * Checks if the given SplitKeyMethod is a polynomial method. + * + * @return true if the SplitKeyMethod is either POLYNOMIAL_GF_216, + * POLYNOMIAL_PRIME_FIELD, or POLYNOMIAL_GF_28; otherwise false. + */ + public boolean isPolynomial() + { + return this == PolynomialSharingGF2_16 || + this == PolynomialSharingPrimeField || + this == PolynomialSharingGF2_8; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPUniqueIdentifierEnum.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPUniqueIdentifierEnum.java new file mode 100644 index 0000000000..88e39f4e2d --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPUniqueIdentifierEnum.java @@ -0,0 +1,64 @@ +package org.bouncycastle.kmip.wire.enumeration; + +public enum KMIPUniqueIdentifierEnum + implements KMIPEnumeration +{ + IDPlaceholder(0x00000001), + Certify(0x00000002), + Create(0x00000003), + CreateKeyPair(0x00000004), + CreateKeyPairPrivateKey(0x00000005), + CreateKeyPairPublicKey(0x00000006), + Create_Split_Key(0x00000007), + DeriveKey(0x00000008), + Import(0x00000009), + Join_Split_Key(0x0000000A), + Locate(0x0000000B), + Register(0x0000000C), + Re_Key(0x0000000D), + Re_Certify(0x0000000E), + Re_KeyKeyPair(0x0000000F), + Re_KeyKeyPairPrivateKey(0x00000010), + Re_KeyKeyPairPublicKey(0x00000011); + + private final int value; + + /** + * Constructor for UniqueIdentifierEnum. + * + * @param value The hex value representing the unique identifier. + */ + KMIPUniqueIdentifierEnum(int value) + { + this.value = value; + } + + /** + * Gets the integer value of the enum. + * + * @return The hex value as an integer. + */ + public int getValue() + { + return value; + } + + /** + * Retrieves the UniqueIdentifierEnum based on the provided value. + * + * @param value The hex value of the unique identifier. + * @return The corresponding UniqueIdentifierEnum. + * @throws IllegalArgumentException if the value does not match any enum. + */ + public static KMIPUniqueIdentifierEnum fromValue(int value) + { + for (KMIPUniqueIdentifierEnum identifier : KMIPUniqueIdentifierEnum.values()) + { + if (identifier.value == value) + { + return identifier; + } + } + throw new IllegalArgumentException("Unknown Unique Identifier value: " + value); + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPWrappingMethod.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPWrappingMethod.java new file mode 100644 index 0000000000..e2b7b69b37 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/enumeration/KMIPWrappingMethod.java @@ -0,0 +1,66 @@ +package org.bouncycastle.kmip.wire.enumeration; + +/** + * Enum representing the Wrapping Method Enumeration. + *

      + * This enum defines the available methods for wrapping keys + * in cryptographic operations. Each wrapping method corresponds + * to a specific value and describes the way in which keys can + * be wrapped using encryption or MAC/signing techniques. + *

      + */ +public enum KMIPWrappingMethod +{ + /** + * Represents encryption only, using a symmetric key or + * public key, or authenticated encryption algorithms + * that use a single key. + */ + ENCRYPT(1), + /** + * Represents MAC/sign only, either MACing the Key Value + * with a symmetric key or signing the Key Value with a + * private key. + */ + MAC_SIGN(2), + /** + * Represents the process of applying MAC/sign to the Key + * Value and then encrypting it. + */ + ENCRYPT_THEN_MAC_SIGN(3), + /** + * Represents the process of applying MAC/sign to the Key + * Value and then encrypting it. + */ + MAC_SIGN_THEN_ENCRYPT(4), + /** + * Represents TR-31 wrapping method. + */ + TR31(5); + + private final int value; + + KMIPWrappingMethod(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static KMIPWrappingMethod fromValue(int value) + { + for (KMIPWrappingMethod method : KMIPWrappingMethod.values()) + { + if (method.value == value) + { + return method; + } + } + throw new IllegalArgumentException("Invalid WrappingMethod value: " + value); + } + +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPBatchItem.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPBatchItem.java new file mode 100644 index 0000000000..fe71dc5b71 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPBatchItem.java @@ -0,0 +1,23 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.enumeration.KMIPOperation; + +public abstract class KMIPBatchItem +{ + protected KMIPOperation operation; // Operation, if specified in the Batch Item + + public KMIPBatchItem(KMIPOperation operation) + { + this.operation = operation; + } + + public KMIPOperation getOperation() + { + return operation; + } + + public void setOperation(KMIPOperation operation) + { + this.operation = operation; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPHeader.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPHeader.java new file mode 100644 index 0000000000..87004a6541 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPHeader.java @@ -0,0 +1,81 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Date; + +import org.bouncycastle.kmip.wire.enumeration.KMIPAttestationType; + +public abstract class KMIPHeader +{ + protected KMIPProtocolVersion protocolVersion; + protected int batchCount; + protected String clientCorrelationValue; // Optional + protected String serverCorrelationValue; // Optional + protected Date timeStamp; // Optional + protected KMIPAttestationType[] attestationType; // Optional, repeated + + public KMIPHeader(KMIPProtocolVersion protocolVersion, int batchCount) + { + this.protocolVersion = protocolVersion; + this.batchCount = batchCount; + } + + public KMIPProtocolVersion getProtocolVersion() + { + return protocolVersion; + } + + public void setProtocolVersion(KMIPProtocolVersion protocolVersion) + { + this.protocolVersion = protocolVersion; + } + + public int getBatchCount() + { + return batchCount; + } + + public void setBatchCount(int batchCount) + { + this.batchCount = batchCount; + } + + public String getClientCorrelationValue() + { + return clientCorrelationValue; + } + + public void setClientCorrelationValue(String clientCorrelationValue) + { + this.clientCorrelationValue = clientCorrelationValue; + } + + public String getServerCorrelationValue() + { + return serverCorrelationValue; + } + + public void setServerCorrelationValue(String serverCorrelationValue) + { + this.serverCorrelationValue = serverCorrelationValue; + } + + public Date getTimeStamp() + { + return timeStamp; + } + + public void setTimeStamp(Date timeStamp) + { + this.timeStamp = timeStamp; + } + + public KMIPAttestationType[] getAttestationType() + { + return attestationType; + } + + public void setAttestationType(KMIPAttestationType[] attestationType) + { + this.attestationType = attestationType; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPMessage.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPMessage.java new file mode 100644 index 0000000000..443ae560b4 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPMessage.java @@ -0,0 +1,5 @@ +package org.bouncycastle.kmip.wire.message; + +public abstract class KMIPMessage +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPMessageExtension.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPMessageExtension.java new file mode 100644 index 0000000000..18f45a24ba --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPMessageExtension.java @@ -0,0 +1,90 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Map; + +/** + * The MessageExtension class represents an optional structure that can be appended + * to any batch item for adding vendor-specific extensions in protocol messages. + */ +public class KMIPMessageExtension +{ + + private String vendorIdentification; + private boolean criticalityIndicator; + private Map vendorExtension; // Map to hold vendor-specific extensions + + /** + * Constructor to initialize MessageExtension with all required fields. + * + * @param vendorIdentification A text string that uniquely identifies the vendor. + * @param criticalityIndicator Boolean indicating if the message is critical. + * @param vendorExtension A structure containing vendor-specific extensions. + */ + public KMIPMessageExtension(String vendorIdentification, boolean criticalityIndicator, Map vendorExtension) + { + this.vendorIdentification = vendorIdentification; + this.criticalityIndicator = criticalityIndicator; + this.vendorExtension = vendorExtension; + } + + /** + * Gets the vendor identification. + * + * @return The vendor identification string. + */ + public String getVendorIdentification() + { + return vendorIdentification; + } + + /** + * Gets the criticality indicator. + * + * @return The criticality indicator (True if critical, False otherwise). + */ + public boolean isCriticalityIndicator() + { + return criticalityIndicator; + } + + /** + * Gets the vendor extension structure. + * + * @return The map containing vendor-specific extensions. + */ + public Map getVendorExtension() + { + return vendorExtension; + } + + /** + * Sets the vendor identification. + * + * @param vendorIdentification The vendor identification string to set. + */ + public void setVendorIdentification(String vendorIdentification) + { + this.vendorIdentification = vendorIdentification; + } + + /** + * Sets the criticality indicator. + * + * @param criticalityIndicator The criticality indicator to set (True for critical, False for non-critical). + */ + public void setCriticalityIndicator(boolean criticalityIndicator) + { + this.criticalityIndicator = criticalityIndicator; + } + + /** + * Sets the vendor extension structure. + * + * @param vendorExtension A map of vendor-specific extensions to set. + */ + public void setVendorExtension(Map vendorExtension) + { + this.vendorExtension = vendorExtension; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPNonce.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPNonce.java new file mode 100644 index 0000000000..3544d83880 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPNonce.java @@ -0,0 +1,80 @@ +package org.bouncycastle.kmip.wire.message; + +/** + * A Nonce object is a structure used by the server to send a random value to the client. The Nonce + * Identifier is assigned by the server and used to identify the Nonce object. The Nonce Value consists of + * the random data created by the server. + * */ +public class KMIPNonce +{ + private byte[] nonceID; + private byte[] nonceValue; + + /** + * Constructor to initialize the Nonce with ID and Value. + * + * @param nonceID The identifier of the Nonce. + * @param nonceValue The random value of the Nonce. + */ + public KMIPNonce(byte[] nonceID, byte[] nonceValue) + { + if (nonceID == null || nonceID.length == 0) + { + throw new IllegalArgumentException("Nonce ID cannot be null or empty."); + } + if (nonceValue == null || nonceValue.length == 0) + { + throw new IllegalArgumentException("Nonce Value cannot be null or empty."); + } + this.nonceID = nonceID; + this.nonceValue = nonceValue; + } + + /** + * Gets the Nonce ID. + * + * @return The identifier of the Nonce. + */ + public byte[] getNonceID() + { + return nonceID; + } + + /** + * Sets the Nonce ID. + * + * @param nonceID The identifier of the Nonce. + */ + public void setNonceID(byte[] nonceID) + { + if (nonceID == null || nonceID.length == 0) + { + throw new IllegalArgumentException("Nonce ID cannot be null or empty."); + } + this.nonceID = nonceID; + } + + /** + * Gets the Nonce Value. + * + * @return The random value of the Nonce. + */ + public byte[] getNonceValue() + { + return nonceValue; + } + + /** + * Sets the Nonce Value. + * + * @param nonceValue The random value of the Nonce. + */ + public void setNonceValue(byte[] nonceValue) + { + if (nonceValue == null || nonceValue.length == 0) + { + throw new IllegalArgumentException("Nonce Value cannot be null or empty."); + } + this.nonceValue = nonceValue; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPPayload.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPPayload.java new file mode 100644 index 0000000000..aa29e62f9c --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPPayload.java @@ -0,0 +1,5 @@ +package org.bouncycastle.kmip.wire.message; + +public interface KMIPPayload +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPProtocolVersion.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPProtocolVersion.java new file mode 100644 index 0000000000..8b7689fc20 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPProtocolVersion.java @@ -0,0 +1,64 @@ +package org.bouncycastle.kmip.wire.message; + +/** + * This class represents the protocol version structure, containing both + * the major and minor version numbers. It ensures the compatibility + * of the protocol between communicating parties. + */ +public class KMIPProtocolVersion +{ + + private final int majorVersion; + private final int minorVersion; + + /** + * Constructor for KMIPProtocolVersion. + * + * @param majorVersion The major version number of the protocol. + * @param minorVersion The minor version number of the protocol. + */ + public KMIPProtocolVersion(int majorVersion, int minorVersion) + { + this.majorVersion = majorVersion; + this.minorVersion = minorVersion; + } + + /** + * Retrieves the major version of the protocol. + * + * @return the major version as an integer. + */ + public int getMajorVersion() + { + return majorVersion; + } + + /** + * Retrieves the minor version of the protocol. + * + * @return the minor version as an integer. + */ + public int getMinorVersion() + { + return minorVersion; + } + + /** + * Compares the current protocol version to another KMIPProtocolVersion instance. + * + * @param other the other ProtocolVersion to compare with. + * @return true if the major versions match and the current minor version is greater + * than or equal to the other version's minor version. + */ + public boolean isCompatibleWith(KMIPProtocolVersion other) + { + return this.majorVersion == other.majorVersion && this.minorVersion >= other.minorVersion; + } + + @Override + public String toString() + { + return "ProtocolVersion " + majorVersion + "." + minorVersion; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestBatchItem.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestBatchItem.java new file mode 100644 index 0000000000..63d4606429 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestBatchItem.java @@ -0,0 +1,64 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.enumeration.KMIPOperation; + +public class KMIPRequestBatchItem + extends KMIPBatchItem +{ + private boolean ephemeral; // Indicates if the data output should not be returned + // 9.21 This is an OPTIONAL field contained in a request, and is used for correlation between requests and + //responses. If a request has a Unique Batch Item ID, then responses to that request SHALL have the + //same Unique Batch Item ID. + private byte[] uniqueBatchItemId; // Optional unique ID for the batch item + private KMIPRequestPayload requestPayload; // Required request payload + private KMIPMessageExtension[] messageExtensions; // Optional message extensions + + // Constructor for mandatory fields + public KMIPRequestBatchItem(KMIPOperation operation, KMIPRequestPayload requestPayload) + { + super(operation); + this.requestPayload = requestPayload; + this.ephemeral = false; // Default to false + this.messageExtensions = new KMIPMessageExtension[0]; // Initialize list for message extensions + } + + public boolean getEphemeral() + { + return ephemeral; + } + + public void setEphemeral(boolean ephemeral) + { + this.ephemeral = ephemeral; + } + + public byte[] getUniqueBatchItemId() + { + return uniqueBatchItemId; + } + + public void setUniqueBatchItemId(byte[] uniqueBatchItemId) + { + this.uniqueBatchItemId = uniqueBatchItemId; + } + + public KMIPRequestPayload getRequestPayload() + { + return requestPayload; + } + + public void setRequestPayload(KMIPRequestPayload requestPayload) + { + this.requestPayload = requestPayload; + } + + public KMIPMessageExtension[] getMessageExtensions() + { + return messageExtensions; + } + + public void setMessageExtension(KMIPMessageExtension[] extensions) + { + this.messageExtensions = extensions; // Add extension to the list + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestHeader.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestHeader.java new file mode 100644 index 0000000000..8941d0a009 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestHeader.java @@ -0,0 +1,90 @@ +package org.bouncycastle.kmip.wire.message; + +/** + * This class represents the Request Header for a protocol message. + * It includes mandatory and optional fields to control various aspects + * of the request being sent. + */ +public class KMIPRequestHeader + extends KMIPHeader +{ + private int maximumResponseSize; // Optional + private boolean asynchronousIndicator; // Optional + private boolean attestationCapableIndicator; // Optional + private String authentication; // Optional + private String batchErrorContinuationOption; // Optional, default "Stop" + private boolean batchOrderOption; // Optional, default "True" + + /** + * Constructor to initialize required fields. + * + * @param protocolVersion The version of the protocol (required). + * @param batchCount The count of the batch (required). + */ + public KMIPRequestHeader(KMIPProtocolVersion protocolVersion, int batchCount) + { + super(protocolVersion, batchCount); + this.batchErrorContinuationOption = "Stop"; // Default value + this.batchOrderOption = true; // Default value + } + + public int getMaximumResponseSize() + { + return maximumResponseSize; + } + + public void setMaximumResponseSize(int maximumResponseSize) + { + this.maximumResponseSize = maximumResponseSize; + } + + public boolean getAsynchronousIndicator() + { + return asynchronousIndicator; + } + + public void setAsynchronousIndicator(boolean asynchronousIndicator) + { + this.asynchronousIndicator = asynchronousIndicator; + } + + public boolean getAttestationCapableIndicator() + { + return attestationCapableIndicator; + } + + public void setAttestationCapableIndicator(boolean attestationCapableIndicator) + { + this.attestationCapableIndicator = attestationCapableIndicator; + } + + public String getAuthentication() + { + return authentication; + } + + public void setAuthentication(String authentication) + { + this.authentication = authentication; + } + + public String getBatchErrorContinuationOption() + { + return batchErrorContinuationOption; + } + + public void setBatchErrorContinuationOption(String batchErrorContinuationOption) + { + this.batchErrorContinuationOption = batchErrorContinuationOption; + } + + public boolean getBatchOrderOption() + { + return batchOrderOption; + } + + public void setBatchOrderOption(boolean batchOrderOption) + { + this.batchOrderOption = batchOrderOption; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestMessage.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestMessage.java new file mode 100644 index 0000000000..969f3bf375 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestMessage.java @@ -0,0 +1,24 @@ +package org.bouncycastle.kmip.wire.message; + +public class KMIPRequestMessage + extends KMIPMessage +{ + private KMIPRequestHeader requestHeader; // Header of the request + private KMIPBatchItem[] batchItems; // List of batch items + + public KMIPRequestMessage(KMIPRequestHeader requestHeader, KMIPBatchItem[] batchItems) + { + this.requestHeader = requestHeader; + this.batchItems = batchItems; // Initialize the list + } + + public KMIPRequestHeader getRequestHeader() + { + return requestHeader; + } + + public KMIPBatchItem[] getBatchItems() + { + return batchItems; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayload.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayload.java new file mode 100644 index 0000000000..4bea20d181 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayload.java @@ -0,0 +1,6 @@ +package org.bouncycastle.kmip.wire.message; + +public abstract class KMIPRequestPayload + implements KMIPPayload +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadCreate.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadCreate.java new file mode 100644 index 0000000000..a4de1a086a --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadCreate.java @@ -0,0 +1,69 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Map; + +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; + +public class KMIPRequestPayloadCreate + extends KMIPRequestPayload +{ + private KMIPObjectType KMIPObjectType; // Type of object to be created (SymmetricKey, SecretData, etc.) + private Map attributes; // List of attributes for the object (e.g., Algorithm, Length) + private int protectionStorageMask; // Optional field for permissible storage masks + + /** + * Constructor to create the CreateRequestPayload with the required fields. + * + * @param KMIPObjectType The type of object to be created. + * @param attributes A list of attributes to be associated with the object. + */ + public KMIPRequestPayloadCreate(KMIPObjectType KMIPObjectType, Map attributes) + { + this.KMIPObjectType = KMIPObjectType; + this.attributes = attributes; + } + + /** + * Constructor to create the CreateRequestPayload with the optional protection storage mask. + * + * @param KMIPObjectType The type of object to be created. + * @param attributes A list of attributes to be associated with the object. + * @param protectionStorageMask Optional field specifying permissible storage mask selections. + */ + public KMIPRequestPayloadCreate(KMIPObjectType KMIPObjectType, Map attributes, int protectionStorageMask) + { + this.KMIPObjectType = KMIPObjectType; + this.attributes = attributes; + this.protectionStorageMask = protectionStorageMask; + } + + public KMIPObjectType getKMIPObjectType() + { + return KMIPObjectType; + } + + public void setKMIPObjectType(KMIPObjectType KMIPObjectType) + { + this.KMIPObjectType = KMIPObjectType; + } + + public Map getAttributes() + { + return attributes; + } + + public void setAttributes(Map attributes) + { + this.attributes = attributes; + } + + public int getProtectionStorageMask() + { + return protectionStorageMask; + } + + public void setProtectionStorageMask(int protectionStorageMask) + { + this.protectionStorageMask = protectionStorageMask; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadCreateSplitKey.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadCreateSplitKey.java new file mode 100644 index 0000000000..5451478ad4 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadCreateSplitKey.java @@ -0,0 +1,123 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Map; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; +import org.bouncycastle.kmip.wire.enumeration.KMIPSplitKeyMethod; + +/** + * RequestPayload represents the payload of a request for creating or splitting a key. + */ +public class KMIPRequestPayloadCreateSplitKey + extends KMIPRequestPayload +{ + // Required fields + private KMIPObjectType objectType; + private KMIPUniqueIdentifier uniqueIdentifier; // Optional + private int splitKeyParts; + private int splitKeyThreshold; + private KMIPSplitKeyMethod splitKeyMethod; + private int primeFieldSize; // Optional + private Map attributes; // Use an appropriate type for attributes + private int protectionStorageMasks; // Optional, adjust type as needed + + /** + * Constructor for RequestPayload with required fields. + * + * @param objectType Determines the type of object to be created. + * @param splitKeyParts The total number of parts in the split key. + * @param splitKeyThreshold The minimum number of parts needed to reconstruct the key. + * @param splitKeyMethod The method used for splitting the key. + * @param attributes Specifies desired object attributes. + */ + public KMIPRequestPayloadCreateSplitKey(KMIPObjectType objectType, int splitKeyParts, int splitKeyThreshold, + KMIPSplitKeyMethod splitKeyMethod, Map attributes) + { + this.objectType = objectType; + this.splitKeyParts = splitKeyParts; + this.splitKeyThreshold = splitKeyThreshold; + this.splitKeyMethod = splitKeyMethod; + this.attributes = attributes; + } + + public KMIPObjectType getObjectType() + { + return objectType; + } + + public void setObjectType(KMIPObjectType objectType) + { + this.objectType = objectType; + } + + public KMIPUniqueIdentifier getUniqueIdentifier() + { + return uniqueIdentifier; + } + + public void setUniqueIdentifier(KMIPUniqueIdentifier uniqueIdentifier) + { + this.uniqueIdentifier = uniqueIdentifier; + } + + public int getSplitKeyParts() + { + return splitKeyParts; + } + + public void setSplitKeyParts(int splitKeyParts) + { + this.splitKeyParts = splitKeyParts; + } + + public int getSplitKeyThreshold() + { + return splitKeyThreshold; + } + + public void setSplitKeyThreshold(int splitKeyThreshold) + { + this.splitKeyThreshold = splitKeyThreshold; + } + + public KMIPSplitKeyMethod getSplitKeyMethod() + { + return splitKeyMethod; + } + + public void setSplitKeyMethod(KMIPSplitKeyMethod splitKeyMethod) + { + this.splitKeyMethod = splitKeyMethod; + } + + public int getPrimeFieldSize() + { + return primeFieldSize; + } + + public void setPrimeFieldSize(int primeFieldSize) + { + this.primeFieldSize = primeFieldSize; + } + + public Map getAttributes() + { + return attributes; + } + + public void setAttributes(Map attributes) + { + this.attributes = attributes; + } + + public int getProtectionStorageMasks() + { + return protectionStorageMasks; + } + + public void setProtectionStorageMasks(int protectionStorageMasks) + { + this.protectionStorageMasks = protectionStorageMasks; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadDefault.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadDefault.java new file mode 100644 index 0000000000..313780cd77 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadDefault.java @@ -0,0 +1,23 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; + +public class KMIPRequestPayloadDefault + extends KMIPRequestPayload +{ + protected KMIPUniqueIdentifier uniqueIdentifier; + + public KMIPRequestPayloadDefault() + { + } + + public void setUniqueIdentifier(KMIPUniqueIdentifier uniqueIdentifier) + { + this.uniqueIdentifier = uniqueIdentifier; + } + + public KMIPUniqueIdentifier getUniqueIdentifiers() + { + return uniqueIdentifier; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadGet.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadGet.java new file mode 100644 index 0000000000..ad5a1464eb --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadGet.java @@ -0,0 +1,87 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyCompressionType; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyFormatType; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyWrapType; + +/** + * Represents a Get Request Payload for requesting a managed object from the server. + * The client specifies the Unique Identifier and various key formats if necessary. + */ +public class KMIPRequestPayloadGet + extends KMIPRequestPayload +{ + + /** + * Determines the object being requested. If omitted, then the ID Placeholder value is used by the server as the Unique Identifier. + * */ + private KMIPUniqueIdentifier uniqueIdentifier; + + // Optional Key Format Type. + private KMIPKeyFormatType keyFormatType; + + // Optional Key Wrap Type. + private KMIPKeyWrapType keyWrapType; + + // Optional Key Compression Type (for elliptic curve public keys). + private KMIPKeyCompressionType keyCompressionType; + + // Optional Key Wrapping Specification. + private String keyWrappingSpecification; + + public KMIPRequestPayloadGet() + { + } + + // Getters and Setters + public KMIPUniqueIdentifier getUniqueIdentifier() + { + return uniqueIdentifier; + } + + public void setUniqueIdentifier(KMIPUniqueIdentifier uniqueIdentifier) + { + this.uniqueIdentifier = uniqueIdentifier; + } + + public KMIPKeyFormatType getKeyFormatType() + { + return keyFormatType; + } + + public void setKeyFormatType(KMIPKeyFormatType keyFormatType) + { + this.keyFormatType = keyFormatType; + } + + public KMIPKeyWrapType getKeyWrapType() + { + return keyWrapType; + } + + public void setKeyWrapType(KMIPKeyWrapType keyWrapType) + { + this.keyWrapType = keyWrapType; + } + + public KMIPKeyCompressionType getKeyCompressionType() + { + return keyCompressionType; + } + + public void setKeyCompressionType(KMIPKeyCompressionType keyCompressionType) + { + this.keyCompressionType = keyCompressionType; + } + + public String getKeyWrappingSpecification() + { + return keyWrappingSpecification; + } + + public void setKeyWrappingSpecification(String keyWrappingSpecification) + { + this.keyWrappingSpecification = keyWrappingSpecification; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadJoinSplitKey.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadJoinSplitKey.java new file mode 100644 index 0000000000..03cbbee67d --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadJoinSplitKey.java @@ -0,0 +1,89 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Map; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; +import org.bouncycastle.kmip.wire.enumeration.KMIPSecretDataType; + +/** + * Request payload for the Join Split Key operation. + * This operation requests the server to combine a list of Split Keys into a single Managed Cryptographic Object. + */ +public class KMIPRequestPayloadJoinSplitKey + extends KMIPRequestPayload +{ + + // Required field to specify the type of object to be created. + private KMIPObjectType objectType; + + // Required field that may repeat to determine the Split Keys to combine. + private KMIPUniqueIdentifier[] uniqueIdentifiers; + + // Optional field to specify the secret data type if applicable. + private KMIPSecretDataType secretDataType; + + // Optional field to specify desired object attributes. + private Map attributes; + + // Optional field to specify permissible protection storage masks. + private int protectionStorageMasks; + + // Constructor + public KMIPRequestPayloadJoinSplitKey(KMIPObjectType objectType, KMIPUniqueIdentifier[] uniqueIdentifiers) + { + this.objectType = objectType; + this.uniqueIdentifiers = uniqueIdentifiers; + } + + public KMIPObjectType getObjectType() + { + return objectType; + } + + public void setObjectType(KMIPObjectType objectType) + { + this.objectType = objectType; + } + + public KMIPUniqueIdentifier[] getUniqueIdentifiers() + { + return uniqueIdentifiers; + } + + public void setUniqueIdentifiers(KMIPUniqueIdentifier[] uniqueIdentifiers) + { + this.uniqueIdentifiers = uniqueIdentifiers; + } + + public KMIPSecretDataType getSecretDataType() + { + return secretDataType; + } + + public void setSecretDataType(KMIPSecretDataType secretDataType) + { + this.secretDataType = secretDataType; + } + + public Map getAttributes() + { + return attributes; + } + + public void setAttributes(Map attributes) + { + this.attributes = attributes; + } + + public int getProtectionStorageMasks() + { + return protectionStorageMasks; + } + + public void setProtectionStorageMasks(int protectionStorageMasks) + { + this.protectionStorageMasks = protectionStorageMasks; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadRegister.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadRegister.java new file mode 100644 index 0000000000..033facdda6 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPRequestPayloadRegister.java @@ -0,0 +1,77 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Map; + +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; +import org.bouncycastle.kmip.wire.object.KMIPObject; + +public class KMIPRequestPayloadRegister + extends KMIPRequestPayload +{ + /** + * Determines the type of object being registered. + */ + private KMIPObjectType objectType; + + /** + * Specifies desired object attributes to be associated with the new object. + */ + private Map attributes; + + /** + * The object being registered. The object and attributes MAY be wrapped. + */ + private KMIPObject object; + + /** + * Specifies all permissible Protection Storage Mask selections for the new object + */ + private int protectionStorageMasks; + + public KMIPRequestPayloadRegister(KMIPObjectType objectType, Map attributes, KMIPObject object) + { + this.objectType = objectType; + this.attributes = attributes; + this.object = object; + } + + public KMIPObjectType getObjectType() + { + return objectType; + } + + public void setObjectType(KMIPObjectType objectType) + { + this.objectType = objectType; + } + + public Map getAttributes() + { + return attributes; + } + + public void setAttributes(Map attributes) + { + this.attributes = attributes; + } + + public int getProtectionStorageMasks() + { + return protectionStorageMasks; + } + + public void setObject(KMIPObject object) + { + this.object = object; + } + + public KMIPObject getObject() + { + return object; + } + + public void setProtectionStorageMasks(int protectionStorageMasks) + { + this.protectionStorageMasks = protectionStorageMasks; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseBatchItem.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseBatchItem.java new file mode 100644 index 0000000000..c14abfec7e --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseBatchItem.java @@ -0,0 +1,98 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.enumeration.KMIPOperation; +import org.bouncycastle.kmip.wire.enumeration.KMIPResultReason; +import org.bouncycastle.kmip.wire.enumeration.KMIPResultStatus; + +public class KMIPResponseBatchItem + extends KMIPBatchItem +{ + + private String uniqueBatchItemID; // Unique Batch Item ID, optional + private KMIPResultStatus resultStatus; // Result Status + private KMIPResultReason resultReason; // Result Reason, required if Result Status is Failure + private String resultMessage; // Optional, unless Result Status is Pending or Success + private String asyncCorrelationValue; // Required if Result Status is Pending + private KMIPResponsePayload responsePayload; // Structure, contents depend on the Operation + private KMIPMessageExtension messageExtension; // Optional Message Extension + + // Constructor + public KMIPResponseBatchItem(KMIPOperation operation, KMIPResultStatus resultStatus, + KMIPResponsePayload responsePayload) + { + super(operation); + this.resultStatus = resultStatus; + this.responsePayload = responsePayload; + } + + public String getUniqueBatchItemID() + { + return uniqueBatchItemID; + } + + public void setUniqueBatchItemID(String uniqueBatchItemID) + { + this.uniqueBatchItemID = uniqueBatchItemID; + } + + public KMIPResultStatus getResultStatus() + { + return resultStatus; + } + + public void setResultStatus(KMIPResultStatus resultStatus) + { + this.resultStatus = resultStatus; + } + + public KMIPResultReason getResultReason() + { + return resultReason; + } + + public void setResultReason(KMIPResultReason resultReason) + { + this.resultReason = resultReason; + } + + public String getResultMessage() + { + return resultMessage; + } + + public void setResultMessage(String resultMessage) + { + this.resultMessage = resultMessage; + } + + public String getAsyncCorrelationValue() + { + return asyncCorrelationValue; + } + + public void setAsyncCorrelationValue(String asyncCorrelationValue) + { + this.asyncCorrelationValue = asyncCorrelationValue; + } + + public KMIPResponsePayload getResponsePayload() + { + return responsePayload; + } + + public void setResponsePayload(KMIPResponsePayload responsePayload) + { + this.responsePayload = responsePayload; + } + + public KMIPMessageExtension getMessageExtension() + { + return messageExtension; + } + + public void setMessageExtension(KMIPMessageExtension messageExtension) + { + this.messageExtension = messageExtension; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseHeader.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseHeader.java new file mode 100644 index 0000000000..35647a7ebf --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseHeader.java @@ -0,0 +1,36 @@ +package org.bouncycastle.kmip.wire.message; + +import java.util.Date; + +public class KMIPResponseHeader + extends KMIPHeader +{ + private KMIPNonce nonce; // Optional + private byte[] serverHashedPassword; // Required if Hashed Password is used + + public KMIPResponseHeader(KMIPProtocolVersion protocolVersion, Date timeStamp, int batchCount) + { + super(protocolVersion, batchCount); + this.timeStamp = timeStamp; + } + + public KMIPNonce getNonce() + { + return nonce; + } + + public void setNonce(KMIPNonce nonce) + { + this.nonce = nonce; + } + + public byte[] getServerHashedPassword() + { + return serverHashedPassword; + } + + public void setServerHashedPassword(byte[] serverHashedPassword) + { + this.serverHashedPassword = serverHashedPassword; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseMessage.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseMessage.java new file mode 100644 index 0000000000..0c01e87737 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponseMessage.java @@ -0,0 +1,25 @@ +package org.bouncycastle.kmip.wire.message; + +public class KMIPResponseMessage + extends KMIPMessage +{ + private KMIPResponseHeader responseHeader; // Header of the response + private KMIPBatchItem[] batchItems; // List of batch items + + public KMIPResponseMessage(KMIPResponseHeader responseHeader, KMIPBatchItem[] batchItems) + { + this.responseHeader = responseHeader; + this.batchItems = batchItems; // Initialize the list + } + + public KMIPResponseHeader getResponseHeader() + { + return responseHeader; + } + + public KMIPBatchItem[] getBatchItems() + { + return batchItems; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayload.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayload.java new file mode 100644 index 0000000000..1aa99909bc --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayload.java @@ -0,0 +1,6 @@ +package org.bouncycastle.kmip.wire.message; + +public abstract class KMIPResponsePayload + implements KMIPPayload +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadCreate.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadCreate.java new file mode 100644 index 0000000000..ab1f621304 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadCreate.java @@ -0,0 +1,63 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; + +public class KMIPResponsePayloadCreate + extends KMIPResponsePayload +{ + private KMIPObjectType objectType; // Type of object created (e.g., symmetric key, secret data) + private KMIPUniqueIdentifier uniqueIdentifier; // The Unique Identifier of the newly created object + + /** + * Constructor for ResponsePayload. + * + * @param objectType The type of object created. + * @param uniqueIdentifier The unique identifier of the newly created object. + */ + public KMIPResponsePayloadCreate(KMIPObjectType objectType, KMIPUniqueIdentifier uniqueIdentifier) + { + this.objectType = objectType; + this.uniqueIdentifier = uniqueIdentifier; + } + + /** + * Get the type of the created object. + * + * @return The object type as a String. + */ + public KMIPObjectType getObjectType() + { + return objectType; + } + + /** + * Set the type of the created object. + * + * @param objectType The object type to set. + */ + public void setObjectType(KMIPObjectType objectType) + { + this.objectType = objectType; + } + + /** + * Get the unique identifier of the newly created object. + * + * @return The unique identifier as a String. + */ + public KMIPUniqueIdentifier getUniqueIdentifier() + { + return uniqueIdentifier; + } + + /** + * Set the unique identifier of the newly created object. + * + * @param uniqueIdentifier The unique identifier to set. + */ + public void setUniqueIdentifier(KMIPUniqueIdentifier uniqueIdentifier) + { + this.uniqueIdentifier = uniqueIdentifier; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadCreateSplitKey.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadCreateSplitKey.java new file mode 100644 index 0000000000..c364728bfe --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadCreateSplitKey.java @@ -0,0 +1,19 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; + +public class KMIPResponsePayloadCreateSplitKey + extends KMIPResponsePayload +{ + private KMIPUniqueIdentifier[] uniqueIdentifiers; + + public KMIPResponsePayloadCreateSplitKey(KMIPUniqueIdentifier[] uniqueIdentifiers) + { + this.uniqueIdentifiers = uniqueIdentifiers; + } + + public KMIPUniqueIdentifier[] getUniqueIdentifiers() + { + return uniqueIdentifiers; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadDefault.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadDefault.java new file mode 100644 index 0000000000..aa171391f7 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadDefault.java @@ -0,0 +1,19 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; + +public class KMIPResponsePayloadDefault + extends KMIPResponsePayload +{ + protected KMIPUniqueIdentifier uniqueIdentifier; + + public KMIPResponsePayloadDefault(KMIPUniqueIdentifier uniqueIdentifiers) + { + this.uniqueIdentifier = uniqueIdentifiers; + } + + public KMIPUniqueIdentifier getUniqueIdentifiers() + { + return uniqueIdentifier; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadGet.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadGet.java new file mode 100644 index 0000000000..ad9c6ebf02 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/message/KMIPResponsePayloadGet.java @@ -0,0 +1,45 @@ +package org.bouncycastle.kmip.wire.message; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; +import org.bouncycastle.kmip.wire.enumeration.KMIPObjectType; +import org.bouncycastle.kmip.wire.object.KMIPObject; + +public class KMIPResponsePayloadGet + extends KMIPResponsePayloadDefault +{ + + // Required Object Type. + private KMIPObjectType objectType; + + // Required Object being returned. + private KMIPObject object; // Can be of any type (Key, Certificate, Secret Data, etc.). + + // Constructor + public KMIPResponsePayloadGet(KMIPObjectType objectType, KMIPUniqueIdentifier uniqueIdentifier, KMIPObject object) + { + super(uniqueIdentifier); + this.objectType = objectType; + this.object = object; + } + + // Getters and Setters + public KMIPObjectType getObjectType() + { + return objectType; + } + + public void setObjectType(KMIPObjectType objectType) + { + this.objectType = objectType; + } + + public KMIPObject getObject() + { + return object; + } + + public void setObject(KMIPObject object) + { + this.object = object; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPCryptographicParameters.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPCryptographicParameters.java new file mode 100644 index 0000000000..29c8d0777b --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPCryptographicParameters.java @@ -0,0 +1,223 @@ +package org.bouncycastle.kmip.wire.object; + +import org.bouncycastle.kmip.wire.enumeration.KMIPBlockCipherMode; +import org.bouncycastle.kmip.wire.enumeration.KMIPCryptographicAlgorithm; +import org.bouncycastle.kmip.wire.enumeration.KMIPDigitalSignatureAlgorithm; +import org.bouncycastle.kmip.wire.enumeration.KMIPHashingAlgorithm; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyRoleType; +import org.bouncycastle.kmip.wire.enumeration.KMIPMaskGenerator; +import org.bouncycastle.kmip.wire.enumeration.KMIPPaddingMethod; + +/** + * Class representing the Cryptographic Parameters attribute structure. + */ +public class KMIPCryptographicParameters +{ + private KMIPBlockCipherMode blockCipherMode; // Block Cipher Mode + private org.bouncycastle.kmip.wire.enumeration.KMIPPaddingMethod KMIPPaddingMethod; // Padding Method + private KMIPHashingAlgorithm hashingAlgorithm; // Hashing Algorithm + private KMIPKeyRoleType keyRoleType; // Key Role Type + private KMIPDigitalSignatureAlgorithm digitalSignatureAlgorithm; // Digital Signature Algorithm + private KMIPCryptographicAlgorithm cryptographicAlgorithm; // Cryptographic Algorithm + private boolean randomIV; // Random IV + private int ivLength; // IV Length + private int tagLength; // Tag Length + private int fixedFieldLength; // Fixed Field Length + private int invocationFieldLength; // Invocation Field Length + private int counterLength; // Counter Length + private int initialCounterValue; // Initial Counter Value + private int saltLength; // Salt Length + private KMIPMaskGenerator maskGenerator; // Mask Generator + private KMIPHashingAlgorithm maskGeneratorHashingAlgorithm; // Mask Generator Hashing Algorithm + private byte[] pSource; // P Source + private int trailerField; // Trailer Field + + // Constructor + public KMIPCryptographicParameters() + { + // Default constructor + } + + // Getters and Setters for each field + + public KMIPBlockCipherMode getBlockCipherMode() + { + return blockCipherMode; + } + + public void setBlockCipherMode(KMIPBlockCipherMode blockCipherMode) + { + this.blockCipherMode = blockCipherMode; + } + + public KMIPPaddingMethod getPaddingMethod() + { + return KMIPPaddingMethod; + } + + public void setPaddingMethod(KMIPPaddingMethod KMIPPaddingMethod) + { + this.KMIPPaddingMethod = KMIPPaddingMethod; + } + + public KMIPHashingAlgorithm getHashingAlgorithm() + { + return hashingAlgorithm; + } + + public void setHashingAlgorithm(KMIPHashingAlgorithm hashingAlgorithm) + { + this.hashingAlgorithm = hashingAlgorithm; + } + + public KMIPKeyRoleType getKeyRoleType() + { + return keyRoleType; + } + + public void setKeyRoleType(KMIPKeyRoleType KMIPKeyRoleType) + { + this.keyRoleType = KMIPKeyRoleType; + } + + public KMIPDigitalSignatureAlgorithm getDigitalSignatureAlgorithm() + { + return digitalSignatureAlgorithm; + } + + public void setDigitalSignatureAlgorithm(KMIPDigitalSignatureAlgorithm digitalSignatureAlgorithm) + { + this.digitalSignatureAlgorithm = digitalSignatureAlgorithm; + } + + public KMIPCryptographicAlgorithm getCryptographicAlgorithm() + { + return cryptographicAlgorithm; + } + + public void setCryptographicAlgorithm(KMIPCryptographicAlgorithm cryptographicAlgorithm) + { + this.cryptographicAlgorithm = cryptographicAlgorithm; + } + + public boolean getRandomIV() + { + return randomIV; + } + + public void setRandomIV(boolean randomIV) + { + this.randomIV = randomIV; + } + + public int getIvLength() + { + return ivLength; + } + + public void setIvLength(int ivLength) + { + this.ivLength = ivLength; + } + + public int getTagLength() + { + return tagLength; + } + + public void setTagLength(int tagLength) + { + this.tagLength = tagLength; + } + + public int getFixedFieldLength() + { + return fixedFieldLength; + } + + public void setFixedFieldLength(int fixedFieldLength) + { + this.fixedFieldLength = fixedFieldLength; + } + + public int getInvocationFieldLength() + { + return invocationFieldLength; + } + + public void setInvocationFieldLength(int invocationFieldLength) + { + this.invocationFieldLength = invocationFieldLength; + } + + public int getCounterLength() + { + return counterLength; + } + + public void setCounterLength(int counterLength) + { + this.counterLength = counterLength; + } + + public int getInitialCounterValue() + { + return initialCounterValue; + } + + public void setInitialCounterValue(int initialCounterValue) + { + this.initialCounterValue = initialCounterValue; + } + + public int getSaltLength() + { + return saltLength; + } + + public void setSaltLength(int saltLength) + { + this.saltLength = saltLength; + } + + public KMIPMaskGenerator getMaskGenerator() + { + return maskGenerator; + } + + public void setMaskGenerator(KMIPMaskGenerator maskGenerator) + { + this.maskGenerator = maskGenerator; + } + + public KMIPHashingAlgorithm getMaskGeneratorHashingAlgorithm() + { + return maskGeneratorHashingAlgorithm; + } + + public void setMaskGeneratorHashingAlgorithm(KMIPHashingAlgorithm maskGeneratorKMIPHashingAlgorithm) + { + this.maskGeneratorHashingAlgorithm = maskGeneratorKMIPHashingAlgorithm; + } + + public byte[] getPSource() + { + return pSource; + } + + public void setPSource(byte[] pSource) + { + this.pSource = pSource; + } + + public int getTrailerField() + { + return trailerField; + } + + public void setTrailerField(int trailerField) + { + this.trailerField = trailerField; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyBlock.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyBlock.java new file mode 100644 index 0000000000..c79cbdb898 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyBlock.java @@ -0,0 +1,134 @@ +package org.bouncycastle.kmip.wire.object; + +import org.bouncycastle.kmip.wire.enumeration.KMIPCryptographicAlgorithm; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyCompressionType; +import org.bouncycastle.kmip.wire.enumeration.KMIPKeyFormatType; + +/** + * Represents a Key Block object, a structure used to encapsulate all information + * associated with a cryptographic key. + *

      + * The Key Block may contain the following properties: + * - Key Format Type: Indicates the format of the key (e.g., RSA, AES). + * - Key Compression Type: Indicates the format of the elliptic curve public key. + * - Key Value: The actual key data, which may be wrapped (encrypted) or in plaintext. + * - Cryptographic Algorithm: The algorithm used for the cryptographic key. + * - Cryptographic Length: The length of the cryptographic key in bits. + * - Key Wrapping Data: Data structure that is present if the key is wrapped. + */ +public class KMIPKeyBlock + extends KMIPObject +{ + + /** + * The format type of the key (e.g., RSA, AES). + */ + private KMIPKeyFormatType keyFormatType; + + /** + * The compression type of the key (e.g., compressed, uncompressed). + */ + private KMIPKeyCompressionType keyCompressionType; + + /** + * The key value, which can be a wrapped key (byte array) or plaintext (object structure). + */ + //TODO: create a class for KeyValue + private byte[] keyValue; // Could be byte[] for wrapped keys or a specific structure for plaintext keys. + + /** + * The cryptographic algorithm used for the key (e.g., RSA, AES). + */ + private KMIPCryptographicAlgorithm cryptographicAlgorithm; + + /** + * The length of the cryptographic key in bits. + */ + private int cryptographicLength; + + /** + * Data structure containing key wrapping information, if the key is wrapped. + */ + private org.bouncycastle.kmip.wire.object.KMIPKeyWrappingData KMIPKeyWrappingData; + + /** + * Constructs a new KeyBlock with the specified parameters. + * + * @param keyFormatType The format type of the key. + * @param keyValue The key value (wrapped or plaintext). + * @param cryptographicAlgorithm The cryptographic algorithm used for the key. + * @param cryptographicLength The length of the cryptographic key in bits. + */ + public KMIPKeyBlock(KMIPKeyFormatType keyFormatType, byte[] keyValue, KMIPCryptographicAlgorithm cryptographicAlgorithm, + int cryptographicLength) + { + this.keyFormatType = keyFormatType; + this.keyValue = keyValue; + this.cryptographicAlgorithm = cryptographicAlgorithm; + this.cryptographicLength = cryptographicLength; + } + + // Getters and Setters + + public KMIPKeyFormatType getKeyFormatType() + { + return keyFormatType; + } + + public void setKeyFormatType(KMIPKeyFormatType keyFormatType) + { + this.keyFormatType = keyFormatType; + } + + public KMIPKeyCompressionType getKeyCompressionType() + { + return keyCompressionType; + } + + public void setKeyCompressionType(KMIPKeyCompressionType keyCompressionType) + { + this.keyCompressionType = keyCompressionType; + } + + public byte[] getKeyValue() + { + return keyValue; + } + + public void setKeyValue(byte[] keyValue) + { + this.keyValue = keyValue; + } + + public KMIPCryptographicAlgorithm getCryptographicAlgorithm() + { + return cryptographicAlgorithm; + } + + public void setCryptographicAlgorithm(KMIPCryptographicAlgorithm KMIPCryptographicAlgorithm) + { + this.cryptographicAlgorithm = KMIPCryptographicAlgorithm; + } + + public int getCryptographicLength() + { + return cryptographicLength; + } + + public void setCryptographicLength(int cryptographicLength) + { + this.cryptographicLength = cryptographicLength; + } + + public KMIPKeyWrappingData getKeyWrappingData() + { + return KMIPKeyWrappingData; + } + + public void setKeyWrappingData(KMIPKeyWrappingData KMIPKeyWrappingData) + { + this.KMIPKeyWrappingData = KMIPKeyWrappingData; + } +} + + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyInformation.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyInformation.java new file mode 100644 index 0000000000..7658657440 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyInformation.java @@ -0,0 +1,54 @@ +package org.bouncycastle.kmip.wire.object; + +import org.bouncycastle.kmip.wire.attribute.KMIPUniqueIdentifier; + +public class KMIPKeyInformation + extends KMIPObject +{ + + /** + * Unique identifier of the encryption key. + */ + private KMIPUniqueIdentifier uniqueIdentifier; + + /** + * Optional cryptographic parameters associated with the encryption key. + */ + private KMIPCryptographicParameters cryptographicParameters; + + /** + * Constructs a new EncryptionKeyInformation with the specified parameters. + * + * @param uniqueIdentifier The unique identifier of the encryption key. + * @param cryptographicParameters Optional cryptographic parameters. + */ + public KMIPKeyInformation(KMIPUniqueIdentifier uniqueIdentifier, + KMIPCryptographicParameters cryptographicParameters) + { + this.uniqueIdentifier = uniqueIdentifier; + this.cryptographicParameters = cryptographicParameters; + } + + // Getters and Setters + + public KMIPUniqueIdentifier getUniqueIdentifier() + { + return uniqueIdentifier; + } + + public void setUniqueIdentifier(KMIPUniqueIdentifier uniqueIdentifier) + { + this.uniqueIdentifier = uniqueIdentifier; + } + + public KMIPCryptographicParameters getCryptographicParameters() + { + return cryptographicParameters; + } + + public void setCryptographicParameters(KMIPCryptographicParameters KMIPCryptographicParameters) + { + this.cryptographicParameters = KMIPCryptographicParameters; + } +} + diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyWrappingData.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyWrappingData.java new file mode 100644 index 0000000000..b7e360ec33 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPKeyWrappingData.java @@ -0,0 +1,137 @@ +package org.bouncycastle.kmip.wire.object; + +import org.bouncycastle.kmip.wire.enumeration.KMIPEncodingOption; +import org.bouncycastle.kmip.wire.enumeration.KMIPWrappingMethod; + +/** + * Represents the Key Wrapping Data structure, which contains optional information + * about the cryptographic key wrapping mechanism used to wrap the Key Value. + *

      + * This structure is used within a Key Block and may contain the following fields: + * - Wrapping Method: The method used to wrap the Key Value. + * - Encryption Key Information: Unique Identifier value of the encryption key and associated cryptographic parameters. + * - MAC/Signature Key Information: Unique Identifier value of the MAC/signature key and associated cryptographic parameters. + * - MAC/Signature: A MAC or signature of the Key Value. + * - IV/Counter/Nonce: Required by the wrapping method if applicable. + * - Encoding Option: Specifies the encoding of the Key Material within the wrapped Key Value structure. + */ +public class KMIPKeyWrappingData +{ + + /** + * The method used to wrap the Key Value (e.g., AES, RSA). + */ + private KMIPWrappingMethod wrappingMethod; + + /** + * Information about the encryption key used to encrypt the Key Value. + */ + private KMIPKeyInformation encryptionKeyInfo; + + /** + * Information about the MAC/signature key used for MAC/signing the Key Value. + */ + private KMIPKeyInformation macSignatureKeyInfo; + + /** + * A MAC or signature of the Key Value. + */ + private byte[] macSignature; + + /** + * Initialization vector, counter, or nonce, if required by the wrapping method. + */ + private byte[] ivCounterNonce; + + /** + * Specifies the encoding of the Key Material within the wrapped Key Value structure. + */ + private KMIPEncodingOption encodingOption; + + /** + * Constructs a new KeyWrappingData with the specified parameters. + * + * @param wrappingMethod The method used to wrap the Key Value. + * @param encryptionKeyInfo Information about the encryption key (optional). + * @param macSignatureKeyInfo Information about the MAC/signature key (optional). + * @param macSignature A MAC or signature of the Key Value (optional). + * @param ivCounterNonce IV, counter, or nonce if required by the wrapping method (optional). + * @param encodingOption The encoding option for the Key Value (optional). + */ + public KMIPKeyWrappingData(KMIPWrappingMethod wrappingMethod, + KMIPKeyInformation encryptionKeyInfo, + KMIPKeyInformation macSignatureKeyInfo, + byte[] macSignature, + byte[] ivCounterNonce, + KMIPEncodingOption encodingOption) + { + this.wrappingMethod = wrappingMethod; + this.encryptionKeyInfo = encryptionKeyInfo; + this.macSignatureKeyInfo = macSignatureKeyInfo; + this.macSignature = macSignature; + this.ivCounterNonce = ivCounterNonce; + this.encodingOption = encodingOption; + } + + // Getters and Setters + + public KMIPWrappingMethod getWrappingMethod() + { + return wrappingMethod; + } + + public void setWrappingMethod(KMIPWrappingMethod KMIPWrappingMethod) + { + this.wrappingMethod = KMIPWrappingMethod; + } + + public KMIPKeyInformation getEncryptionKeyInfo() + { + return encryptionKeyInfo; + } + + public void setEncryptionKeyInfo(KMIPKeyInformation encryptionKeyInfo) + { + this.encryptionKeyInfo = encryptionKeyInfo; + } + + public KMIPKeyInformation getMacSignatureKeyInfo() + { + return macSignatureKeyInfo; + } + + public void setMacSignatureKeyInfo(KMIPKeyInformation macSignatureKeyInfo) + { + this.macSignatureKeyInfo = macSignatureKeyInfo; + } + + public byte[] getMacSignature() + { + return macSignature; + } + + public void setMacSignature(byte[] macSignature) + { + this.macSignature = macSignature; + } + + public byte[] getIvCounterNonce() + { + return ivCounterNonce; + } + + public void setIvCounterNonce(byte[] ivCounterNonce) + { + this.ivCounterNonce = ivCounterNonce; + } + + public KMIPEncodingOption getEncodingOption() + { + return encodingOption; + } + + public void setEncodingOption(KMIPEncodingOption KMIPEncodingOption) + { + this.encodingOption = KMIPEncodingOption; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPObject.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPObject.java new file mode 100644 index 0000000000..ff1f3ad4ae --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPObject.java @@ -0,0 +1,5 @@ +package org.bouncycastle.kmip.wire.object; + +public abstract class KMIPObject +{ +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPSplitKey.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPSplitKey.java new file mode 100644 index 0000000000..b32aa3951c --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPSplitKey.java @@ -0,0 +1,105 @@ +package org.bouncycastle.kmip.wire.object; + +import java.math.BigInteger; + +import org.bouncycastle.kmip.wire.enumeration.KMIPSplitKeyMethod; + + +/** + * A Managed Cryptographic Object that is a Split Key. A split key is a secret, usually a symmetric key or a private key + * that has been split into a number of parts, each of which MAY then be distributed to several key holders, for + * additional security. The Split Key Parts field indicates the total number of parts, and the Split Key Threshold field + * indicates the minimum number of parts needed to reconstruct the entire key. The Key Part Identifier indicates which + * key part is contained in the cryptographic object, and SHALL be at least 1 and SHALL be less than or equal to Split + * Key Parts. + */ +public class KMIPSplitKey + extends KMIPObject +{ + + private final int splitKeyParts; // Total number of parts + private final int keyPartIdentifier; // Identifier for the key part + private final int splitKeyThreshold; // Minimum number of parts needed to reconstruct the key + private final KMIPSplitKeyMethod splitKeyMethod; // Method used for splitting the key + private final BigInteger primeFieldSize; // Required only if Split Key Method is Polynomial Sharing + + // Key Block Object Data (can be defined separately as needed) + private final KMIPKeyBlock KMIPKeyBlock; + + /** + * Constructs a SplitKey object. + * + * @param splitKeyParts Total number of parts. + * @param keyPartIdentifier Identifier for the key part. + * @param splitKeyThreshold Minimum number of parts needed to reconstruct the key. + * @param splitKeyMethod Method used for splitting the key. + * @param primeFieldSize Size of the prime field (if applicable). + * @param KMIPKeyBlock Key block object data. + */ + public KMIPSplitKey(int splitKeyParts, int keyPartIdentifier, int splitKeyThreshold, + KMIPSplitKeyMethod splitKeyMethod, BigInteger primeFieldSize, + KMIPKeyBlock KMIPKeyBlock) + { + // Validate required fields + if (splitKeyParts <= 0) + { + throw new IllegalArgumentException("Split Key Parts must be greater than 0."); + } + if (keyPartIdentifier <= 0) + { + throw new IllegalArgumentException("Key Part Identifier must be greater than 0."); + } + if (splitKeyThreshold <= 0 || splitKeyThreshold > splitKeyParts) + { + throw new IllegalArgumentException("Split Key Threshold must be greater than 0 and less than or equal to Split Key Parts."); + } + if (splitKeyMethod == null) + { + throw new IllegalArgumentException("Split Key Method must not be null."); + } + + // If the method requires primeFieldSize, ensure it is provided + if (splitKeyMethod == KMIPSplitKeyMethod.PolynomialSharingPrimeField && primeFieldSize == null) + { + throw new IllegalArgumentException("Prime Field Size is required when Split Key Method is Polynomial Sharing."); + } + + this.splitKeyParts = splitKeyParts; + this.keyPartIdentifier = keyPartIdentifier; + this.splitKeyThreshold = splitKeyThreshold; + this.splitKeyMethod = splitKeyMethod; + this.primeFieldSize = primeFieldSize; + this.KMIPKeyBlock = KMIPKeyBlock; + } + + // Getters + public int getSplitKeyParts() + { + return splitKeyParts; + } + + public int getKeyPartIdentifier() + { + return keyPartIdentifier; + } + + public int getSplitKeyThreshold() + { + return splitKeyThreshold; + } + + public KMIPSplitKeyMethod getSplitKeyMethod() + { + return splitKeyMethod; + } + + public BigInteger getPrimeFieldSize() + { + return primeFieldSize; + } + + public KMIPKeyBlock getKeyBlock() + { + return KMIPKeyBlock; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPSymmetricKey.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPSymmetricKey.java new file mode 100644 index 0000000000..a2b9b40333 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/object/KMIPSymmetricKey.java @@ -0,0 +1,22 @@ +package org.bouncycastle.kmip.wire.object; + +public class KMIPSymmetricKey + extends KMIPObject +{ + private KMIPKeyBlock keyBlock; // The KeyBlock that holds the actual key + + public KMIPSymmetricKey(KMIPKeyBlock keyBlock) + { + this.keyBlock = keyBlock; + } + + public KMIPKeyBlock getKeyBlock() + { + return keyBlock; + } + + public void setKeyBlock(KMIPKeyBlock keyBlock) + { + this.keyBlock = keyBlock; + } +} diff --git a/kmip/src/main/java/org/bouncycastle/kmip/wire/operation/KMIPKeyWrappingSpecification.java b/kmip/src/main/java/org/bouncycastle/kmip/wire/operation/KMIPKeyWrappingSpecification.java new file mode 100644 index 0000000000..1a0f7d6841 --- /dev/null +++ b/kmip/src/main/java/org/bouncycastle/kmip/wire/operation/KMIPKeyWrappingSpecification.java @@ -0,0 +1,93 @@ +package org.bouncycastle.kmip.wire.operation; + +import org.bouncycastle.kmip.wire.enumeration.KMIPEncodingOption; +import org.bouncycastle.kmip.wire.enumeration.KMIPWrappingMethod; +import org.bouncycastle.kmip.wire.object.KMIPKeyInformation; + +/** + * Represents the Key Wrapping Specification structure for wrapping a key. + * This structure includes the wrapping method, encryption or MAC/signature key info, + * attribute names, and encoding option. + */ +public class KMIPKeyWrappingSpecification +{ + + // Enumeration for Wrapping Method. + private KMIPWrappingMethod wrappingMethod; + + // Optional Encryption Key Information (required if MAC/Signature Key Information is omitted). + private KMIPKeyInformation encryptionKeyInformation; + + // Optional MAC/Signature Key Information (required if Encryption Key Information is omitted). + private KMIPKeyInformation macSignatureKeyInformation; + + // Optional list of attribute names to be wrapped with the key material. + private String[] attributeNames; + + // Optional Encoding Option (if not present, the wrapped Key Value will be TTLV encoded). + private KMIPEncodingOption encodingOption; + + // Constructor + public KMIPKeyWrappingSpecification(KMIPWrappingMethod wrappingMethod, KMIPKeyInformation encryptionKeyInformation, + KMIPKeyInformation macSignatureKeyInformation, String[] attributeNames, + KMIPEncodingOption encodingOption) + { + this.wrappingMethod = wrappingMethod; + this.encryptionKeyInformation = encryptionKeyInformation; + this.macSignatureKeyInformation = macSignatureKeyInformation; + this.attributeNames = attributeNames; + this.encodingOption = encodingOption; + } + + // Getters and Setters + public KMIPWrappingMethod getWrappingMethod() + { + return wrappingMethod; + } + + public void setWrappingMethod(KMIPWrappingMethod wrappingMethod) + { + this.wrappingMethod = wrappingMethod; + } + + public KMIPKeyInformation getEncryptionKeyInformation() + { + return encryptionKeyInformation; + } + + public void setEncryptionKeyInformation(KMIPKeyInformation encryptionKeyInformation) + { + this.encryptionKeyInformation = encryptionKeyInformation; + } + + public KMIPKeyInformation getMacSignatureKeyInformation() + { + return macSignatureKeyInformation; + } + + public void setMacSignatureKeyInformation(KMIPKeyInformation macSignatureKeyInformation) + { + this.macSignatureKeyInformation = macSignatureKeyInformation; + } + + public String[] getAttributeNames() + { + return attributeNames; + } + + public void setAttributeNames(String[] attributeNames) + { + this.attributeNames = attributeNames; + } + + public KMIPEncodingOption getEncodingOption() + { + return encodingOption; + } + + public void setEncodingOption(KMIPEncodingOption encodingOption) + { + this.encodingOption = encodingOption; + } +} + diff --git a/kmip/src/test/java/org/bouncycastle/kmip/test/KMIPSplitKeyTest.java b/kmip/src/test/java/org/bouncycastle/kmip/test/KMIPSplitKeyTest.java new file mode 100644 index 0000000000..123e4ed8b4 --- /dev/null +++ b/kmip/src/test/java/org/bouncycastle/kmip/test/KMIPSplitKeyTest.java @@ -0,0 +1,219 @@ +package org.bouncycastle.kmip.test; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import javax.xml.stream.XMLStreamException; + +import org.bouncycastle.kmip.wire.KMIPInputStream; +import org.bouncycastle.kmip.wire.message.KMIPMessage; +import org.bouncycastle.test.TestResourceFinder; + + +public class KMIPSplitKeyTest +{ + private static int indentLevel = 0; // Variable to track indentation level + + private static void parse(String filename) + { + try (InputStream inputStream = TestResourceFinder.findTestResource("crypto/split/", filename)) + { + KMIPInputStream stream = new KMIPInputStream(inputStream); + KMIPMessage[] messages = stream.parse(); + System.out.println(messages.length); + } + catch (FileNotFoundException e) + { + System.err.println("File not found: " + e.getMessage()); + } + catch (IOException e) + { + System.err.println("Error processing XML: " + e.getMessage()); + } + catch (XMLStreamException e) + { + System.err.println("Error parsing XML: " + e.getMessage()); + } + } + + public static void main(String[] args) + { + parse("TC-SJ-1-21.xml"); + parse("TC-SJ-2-21.xml"); + parse("TC-SJ-3-21.xml"); + parse("TC-SJ-4-21.xml"); + + +// XMLInputFactory factory = XMLInputFactory.newInstance(); +// KMIPTest test = new KMIPTest(); +// try (InputStream inputStream = TestResourceFinder.findTestResource("crypto/split/", "TC-SJ-2-21.xml")) +// { +// +// XMLEventReader eventReader = factory.createXMLEventReader(inputStream); +// +// while (eventReader.hasNext()) +// { +// XMLEvent event = eventReader.nextEvent(); +// +// // Process the start elements +// if (event.isStartElement()) +// { +// StartElement startElement = event.asStartElement(); +// printIndent(); // Print indentation based on the current level +// System.out.print("Start Element: " + startElement.getName().getLocalPart()); +// +// // Print attributes if there are any +// if (startElement.getAttributes() != null) +// { +// for (Iterator it = startElement.getAttributes(); it.hasNext(); ) +// { +// Attribute attribute = (Attribute)it.next(); +// System.out.print(" [Attribute: " + attribute.getName() + " = " + attribute.getValue() + "]"); +// } +// } +// System.out.println(); // Move to the next line +// indentLevel++; // Increase the indent level for child elements +// } +// +//// // Process character data +//// if (event.isCharacters()) { +//// Characters characters = event.asCharacters(); +//// String text = characters.getData().trim(); +//// if (!text.isEmpty()) { +//// printIndent(); // Print indentation +//// System.out.println("Text: " + text); // Print text content +//// } +//// } +// +// // Process end elements +// if (event.isEndElement()) +// { +// indentLevel--; // Decrease the indent level +// printIndent(); // Print indentation for end element +// EndElement endElement = event.asEndElement(); +// System.out.println("End Element: " + endElement.getName().getLocalPart()); +// } +// } +// } +// catch (FileNotFoundException e) +// { +// System.err.println("File not found: " + e.getMessage()); +// } +// catch (XMLStreamException | IOException e) +// { +// System.err.println("Error processing XML: " + e.getMessage()); +// } + } + + // Method to print indentation based on current level + private static void printIndent() + { + for (int i = 0; i < indentLevel; i++) + { + System.out.print(" "); // Adjust the number of spaces for indentation + } + } + + + // Helper to read the protocol version +// private static void readProtocolVersion(Element header) { +// Element protocolVersion = (Element) header.getElementsByTagName("ProtocolVersion").item(0); +// readElementValue(protocolVersion, "ProtocolVersionMajor"); +// readElementValue(protocolVersion, "ProtocolVersionMinor"); +// } +// +// // Helper method to read an element by its tag name +// private static void readElementValue(Element parent, String tagName) { +// Element element = (Element) parent.getElementsByTagName(tagName).item(0); +// if (element != null) { +// String type = element.getAttribute("type"); +// String value = element.getAttribute("value"); +// System.out.println(" " + tagName + " (" + type + "): " + value); +// } +// } +// +// // Helper to read attributes +// private static void readAttributes(Element attributes) { +// readElementValue(attributes, "CryptographicAlgorithm"); +// readElementValue(attributes, "CryptographicLength"); +// readElementValue(attributes, "CryptographicUsageMask"); +// +// // Handle Name separately +// Element name = (Element) attributes.getElementsByTagName("Name").item(0); +// if (name != null) { +// readElementValue(name, "NameValue"); +// readElementValue(name, "NameType"); +// } +// } +} +// +//public interface Document extends Node { +// // Creates a new Element with the given tag name. +// Element createElement(String tagName) throws DOMException; +// +// // Returns the root element of the document. +// Element getDocumentElement(); +// +// // Imports a node from another document to this document. +// Node importNode(Node importedNode, boolean deep) throws DOMException; +// +// // Returns a NodeList of all elements in the document with the specified tag name. +// NodeList getElementsByTagName(String tagname); +// +// // Returns an element by its ID. +// Element getElementById(String elementId); +//} +// +//public interface Element extends Node { +// // Returns the value of an attribute by name. +// String getAttribute(String name); +// +// // Sets the value of an attribute by name. +// void setAttribute(String name, String value) throws DOMException; +// +// // Returns a NodeList of all descendant elements with a given tag name. +// NodeList getElementsByTagName(String name); +// +// // Removes an attribute by name. +// void removeAttribute(String name) throws DOMException; +// +// void normalize(); +//} +// +//public interface Node { +// // Returns the name of this node. +// String getNodeName(); +// +// // Returns the value of this node. +// String getNodeValue() throws DOMException; +// +// // Returns the type of this node. +// short getNodeType(); +// +// // Returns the parent node of this node. +// Node getParentNode(); +// +// // Returns a NodeList of child nodes. +// NodeList getChildNodes(); +// +// // Returns the first child node. +// Node getFirstChild(); +// +// // Returns the last child node. +// Node getLastChild(); +// +// // Appends a new child node to this node. +// Node appendChild(Node newChild) throws DOMException; +// +// // Removes a child node from this node. +// Node removeChild(Node oldChild) throws DOMException; +//} +// +//public interface NodeList { +// // Returns the number of nodes in this list. +// int getLength(); +// +// // Returns the node at the specified index. +// Node item(int index); +//} \ No newline at end of file diff --git a/kmip/src/test/java/org/bouncycastle/test/PrintTestResult.java b/kmip/src/test/java/org/bouncycastle/test/PrintTestResult.java new file mode 100644 index 0000000000..2cca70b227 --- /dev/null +++ b/kmip/src/test/java/org/bouncycastle/test/PrintTestResult.java @@ -0,0 +1,36 @@ +package org.bouncycastle.test; + + +import java.util.Enumeration; + +import junit.framework.TestResult; + +public class PrintTestResult +{ + public static void printResult(TestResult result) + { + Enumeration e = result.failures(); + if (e != null) + { + while (e.hasMoreElements()) + { + System.out.println(e.nextElement()); + } + } + + e = result.errors(); + if (e != null) + { + while (e.hasMoreElements()) + { + System.out.println(e.nextElement()); + } + } + + if (!result.wasSuccessful()) + { + System.exit(1); + } + } +} + diff --git a/kmip/src/test/java/org/bouncycastle/test/TestResourceFinder.java b/kmip/src/test/java/org/bouncycastle/test/TestResourceFinder.java new file mode 100644 index 0000000000..14214bafae --- /dev/null +++ b/kmip/src/test/java/org/bouncycastle/test/TestResourceFinder.java @@ -0,0 +1,39 @@ +package org.bouncycastle.test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; + +public class TestResourceFinder +{ + private static final String dataDirName = "bc-test-data"; + + /** + * We search starting at the working directory looking for the bc-test-data directory. + * + * @throws FileNotFoundException + */ + public static InputStream findTestResource(String homeDir, String fileName) + throws FileNotFoundException + { + String wrkDirName = System.getProperty("user.dir"); + String separator = System.getProperty("file.separator"); + File wrkDir = new File(wrkDirName); + File dataDir = new File(wrkDir, dataDirName); + while (!dataDir.exists() && wrkDirName.length() > 1) + { + wrkDirName = wrkDirName.substring(0, wrkDirName.lastIndexOf(separator)); + wrkDir = new File(wrkDirName); + dataDir = new File(wrkDir, dataDirName); + } + + if (!dataDir.exists()) + { + String ln = System.getProperty("line.separator"); + throw new FileNotFoundException("Test data directory " + dataDirName + " not found." + ln + "Test data available from: https://github.com/bcgit/bc-test-data.git"); + } + + return new FileInputStream(new File(dataDir, homeDir + separator + fileName)); + } +} diff --git a/mail/build.gradle b/mail/build.gradle index e0f4a8099e..0c3be2b56f 100644 --- a/mail/build.gradle +++ b/mail/build.gradle @@ -18,36 +18,31 @@ dependencies { implementation project(':pkix') implementation group: 'javax.mail', name: 'mail', version: '1.4' - implementation files("$bc_prov") - implementation files("$bc_util") - implementation files("$bc_pkix") - implementation project(path: ':core') - - java9Implementation files("$bc_prov") - java9Implementation files("$bc_util") - java9Implementation files("$bc_pkix") + java9Implementation files(sourceSets.main.output.classesDirs) { builtBy compileJava } } +evaluationDependsOn(":prov") +evaluationDependsOn(":util") +evaluationDependsOn(":pkix") + compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + + options.release = 8 } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + + options.release = 9 + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" + def util_jar="${project(":util").jar.outputs.files.getFiles().getAt(0)}" + def pkix_jar="${project(":pkix").jar.outputs.files.getFiles().getAt(0)}" + options.compilerArgs += [ - '--module-path', "${bc_prov}${File.pathSeparator}${bc_util}${File.pathSeparator}${bc_pkix}" + '--module-path', "${prov_jar}${File.pathSeparator}${util_jar}${File.pathSeparator}${pkix_jar}" ] options.sourcepath = files(['src/main/java', 'src/main/jdk1.9']) @@ -59,12 +54,14 @@ jar { into('META-INF/versions/9') { from sourceSets.java9.output } + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bcmail') manifest.attributes('Bundle-SymbolicName': 'bcmail') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': 'org.bouncycastle.mail.*') - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.mail.*,org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "org.bouncycastle.mail.*;version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.mail.*,org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") } task sourcesJar(type: Jar) { @@ -92,4 +89,23 @@ artifacts { test { forkEvery = 1; maxParallelForks = 8; + jvmArgs = ['-Dtest.java.version.prefix=any'] } + +compileJava9Java.dependsOn([":prov:jar", ":util:jar",":pkix:jar"]) + +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcmail-$vmrange" + from components.java + + + artifact(javadocJar) + artifact(sourcesJar) + } + + + } +} \ No newline at end of file diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnveloped.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnveloped.java new file mode 100644 index 0000000000..7b6b9b8bc9 --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnveloped.java @@ -0,0 +1,41 @@ +package org.bouncycastle.mail.smime; + +import org.bouncycastle.cms.CMSAuthEnvelopedData; +import org.bouncycastle.cms.CMSException; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimePart; + +/** + * containing class for an S/MIME pkcs7-mime encrypted MimePart. + */ +public class SMIMEAuthEnveloped + extends CMSAuthEnvelopedData +{ + MimePart message; + + public SMIMEAuthEnveloped( + MimeBodyPart message) + throws MessagingException, CMSException + { + super(SMIMEUtil.getInputStream(message)); + + this.message = message; + } + + public SMIMEAuthEnveloped( + MimeMessage message) + throws MessagingException, CMSException + { + super(SMIMEUtil.getInputStream(message)); + + this.message = message; + } + + public MimePart getEncryptedContent() + { + return message; + } +} diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnvelopedGenerator.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnvelopedGenerator.java new file mode 100644 index 0000000000..99d2ab17bd --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnvelopedGenerator.java @@ -0,0 +1,201 @@ +package org.bouncycastle.mail.smime; + +import java.io.IOException; +import java.io.OutputStream; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import javax.activation.CommandMap; +import javax.activation.MailcapCommandMap; +import javax.mail.MessagingException; +import javax.mail.internet.MimeBodyPart; + +import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.cms.CMSAuthEnvelopedDataGenerator; +import org.bouncycastle.cms.CMSAuthEnvelopedDataStreamGenerator; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.RecipientInfoGenerator; +import org.bouncycastle.operator.OutputAEADEncryptor; +import org.bouncycastle.operator.OutputEncryptor; + +/** + * General class for generating a pkcs7-mime message using AEAD algorithm. + *

      + * A simple example of usage. + * + *

      + *      SMIMEAuthEnvelopedGenerator fact = new SMIMEAuthEnvelopedGenerator();
      + *
      + *      fact.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(recipientCert).setProvider("BC"));
      + *
      + *      MimeBodyPart mp = fact.generate(content, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_GCM).setProvider("BC").build());
      + * 
      + * + * Note: Most clients expect the MimeBodyPart to be in a MimeMultipart + * when it's sent. + */ +public class SMIMEAuthEnvelopedGenerator + extends SMIMEEnvelopedGenerator +{ + public static final String AES128_GCM = CMSAuthEnvelopedDataGenerator.AES128_GCM; + public static final String AES192_GCM = CMSAuthEnvelopedDataGenerator.AES192_GCM; + public static final String AES256_GCM = CMSAuthEnvelopedDataGenerator.AES256_GCM; + + static final String AUTH_ENVELOPED_DATA_CONTENT_TYPE = "application/pkcs7-mime; name=\"smime.p7m\"; smime-type=authEnveloped-data"; + + final private AuthEnvelopedGenerator authFact; + + static + { + AccessController.doPrivileged(new PrivilegedAction() + { + public Object run() + { + CommandMap commandMap = CommandMap.getDefaultCommandMap(); + + if (commandMap instanceof MailcapCommandMap) + { + CommandMap.setDefaultCommandMap(MailcapUtil.addCommands((MailcapCommandMap)commandMap)); + } + + return null; + } + }); + } + + /** + * base constructor + */ + public SMIMEAuthEnvelopedGenerator() + { + authFact = new AuthEnvelopedGenerator(); + } + + /** + * add a recipientInfoGenerator. + */ + public void addRecipientInfoGenerator( + RecipientInfoGenerator recipientInfoGen) + throws IllegalArgumentException + { + authFact.addRecipientInfoGenerator(recipientInfoGen); + } + + /** + * Use a BER Set to store the recipient information + */ + public void setBerEncodeRecipients( + boolean berEncodeRecipientSet) + { + authFact.setBEREncodeRecipients(berEncodeRecipientSet); + } + + /** + * return encrypted content type for enveloped data. + */ + protected String getEncryptedContentType() + { + return AUTH_ENVELOPED_DATA_CONTENT_TYPE; + } + + /** + * return content encryptor. + */ + protected SMIMEStreamingProcessor getContentEncryptor( + MimeBodyPart content, + OutputEncryptor encryptor) + throws SMIMEException + { + if (encryptor instanceof OutputAEADEncryptor) + { + return new ContentEncryptor(content, (OutputAEADEncryptor)encryptor); + } + // this would happen if the encryption algorithm is not AEAD algorithm + throw new SMIMEException("encryptor is not AEAD encryptor"); + } + + private static class AuthEnvelopedGenerator + extends CMSAuthEnvelopedDataStreamGenerator + { + private ASN1ObjectIdentifier dataType; + private ASN1EncodableVector recipientInfos; + + protected OutputStream open( + ASN1ObjectIdentifier dataType, + OutputStream out, + ASN1EncodableVector recipientInfos, + OutputAEADEncryptor encryptor) + throws IOException + { + this.dataType = dataType; + this.recipientInfos = recipientInfos; + + return super.open(dataType, out, recipientInfos, encryptor); + } + + OutputStream regenerate( + OutputStream out, + OutputAEADEncryptor encryptor) + throws IOException + { + return super.open(dataType, out, recipientInfos, encryptor); + } + } + + private class ContentEncryptor + implements SMIMEStreamingProcessor + { + private final MimeBodyPart _content; + private OutputAEADEncryptor _encryptor; + + private boolean _firstTime = true; + + ContentEncryptor( + MimeBodyPart content, + OutputAEADEncryptor encryptor) + { + _content = content; + _encryptor = encryptor; + } + + public void write(OutputStream out) + throws IOException + { + OutputStream encrypted; + + try + { + if (_firstTime) + { + encrypted = authFact.open(out, _encryptor); + + _firstTime = false; + } + else + { + encrypted = authFact.regenerate(out, _encryptor); + } + + CommandMap commandMap = CommandMap.getDefaultCommandMap(); + + if (commandMap instanceof MailcapCommandMap) + { + _content.getDataHandler().setCommandMap(MailcapUtil.addCommands((MailcapCommandMap)commandMap)); + } + + _content.writeTo(encrypted); + + encrypted.close(); + } + catch (MessagingException e) + { + throw new WrappingIOException(e.toString(), e); + } + catch (CMSException e) + { + throw new WrappingIOException(e.toString(), e); + } + } + } +} diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnvelopedParser.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnvelopedParser.java new file mode 100644 index 0000000000..e44f69c2d0 --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEAuthEnvelopedParser.java @@ -0,0 +1,72 @@ +package org.bouncycastle.mail.smime; + +import org.bouncycastle.cms.CMSAuthEnvelopedDataParser; +import org.bouncycastle.cms.CMSException; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimePart; +import java.io.IOException; + +/** + * Stream based containing class for an S/MIME pkcs7-mime encrypted MimePart using AEAD algorithm. + */ +public class SMIMEAuthEnvelopedParser + extends CMSAuthEnvelopedDataParser +{ + private final MimePart message; + + public SMIMEAuthEnvelopedParser( + MimeBodyPart message) + throws IOException, MessagingException, CMSException + { + this(message, 0); + } + + public SMIMEAuthEnvelopedParser( + MimeMessage message) + throws IOException, MessagingException, CMSException + { + this(message, 0); + } + + /** + * Create a parser from a MimeBodyPart using the passed in buffer size + * for reading it. + * + * @param message body part to be parsed. + * @param bufferSize bufferSoze to be used. + */ + public SMIMEAuthEnvelopedParser( + MimeBodyPart message, + int bufferSize) + throws IOException, MessagingException, CMSException + { + super(SMIMEUtil.getInputStream(message, bufferSize)); + + this.message = message; + } + + /** + * Create a parser from a MimeMessage using the passed in buffer size + * for reading it. + * + * @param message message to be parsed. + * @param bufferSize bufferSize to be used. + */ + public SMIMEAuthEnvelopedParser( + MimeMessage message, + int bufferSize) + throws IOException, MessagingException, CMSException + { + super(SMIMEUtil.getInputStream(message, bufferSize)); + + this.message = message; + } + + public MimePart getEncryptedContent() + { + return message; + } +} diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedGenerator.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedGenerator.java index e431726567..70a4af5742 100644 --- a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedGenerator.java +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedGenerator.java @@ -62,9 +62,9 @@ public class SMIMEEnvelopedGenerator public static final String SEED_WRAP = CMSEnvelopedDataGenerator.SEED_WRAP; public static final String ECDH_SHA1KDF = CMSEnvelopedDataGenerator.ECDH_SHA1KDF; - - private static final String ENCRYPTED_CONTENT_TYPE = "application/pkcs7-mime; name=\"smime.p7m\"; smime-type=enveloped-data"; + static final String ENVELOPED_DATA_CONTENT_TYPE = "application/pkcs7-mime; name=\"smime.p7m\"; smime-type=enveloped-data"; + private EnvelopedGenerator fact; static @@ -112,7 +112,26 @@ public void setBerEncodeRecipients( fact.setBEREncodeRecipients(berEncodeRecipientSet); } - /** + /** + * return encrypted content type for enveloped data. + */ + protected String getEncryptedContentType() + { + return ENVELOPED_DATA_CONTENT_TYPE; + } + + /** + * return content encryptor. + */ + protected SMIMEStreamingProcessor getContentEncryptor( + MimeBodyPart content, + OutputEncryptor encryptor) + throws SMIMEException + { + return new ContentEncryptor(content, encryptor); + } + + /** * if we get here we expect the Mime body part to be well defined. */ private MimeBodyPart make( @@ -124,8 +143,8 @@ private MimeBodyPart make( { MimeBodyPart data = new MimeBodyPart(); - data.setContent(new ContentEncryptor(content, encryptor), ENCRYPTED_CONTENT_TYPE); - data.addHeader("Content-Type", ENCRYPTED_CONTENT_TYPE); + data.setContent(getContentEncryptor(content, encryptor), getEncryptedContentType()); + data.addHeader("Content-Type", getEncryptedContentType()); data.addHeader("Content-Disposition", "attachment; filename=\"smime.p7m\""); data.addHeader("Content-Description", "S/MIME Encrypted Message"); data.addHeader("Content-Transfer-Encoding", encoding); @@ -249,7 +268,7 @@ OutputStream regenerate( } } - private static class WrappingIOException + protected static class WrappingIOException extends IOException { private Throwable cause; diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedUtil.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedUtil.java new file mode 100644 index 0000000000..fe4dae9089 --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEEnvelopedUtil.java @@ -0,0 +1,57 @@ +package org.bouncycastle.mail.smime; + +import java.util.HashSet; +import java.util.Set; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeBodyPart; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.RecipientInformationStore; + +public class SMIMEEnvelopedUtil +{ + private static Set authOIDs = new HashSet(); + + static + { + authOIDs.add(NISTObjectIdentifiers.id_aes128_GCM); + authOIDs.add(NISTObjectIdentifiers.id_aes128_GCM); + authOIDs.add(NISTObjectIdentifiers.id_aes128_GCM); + } + + /** + * Parse the passed in MimeMessage extracting the RecipientInfos from it. + * + * @param message the message to be parsed. + * @return the RecipientInformation store for the passed in message. + * @throws MessagingException + * @throws CMSException + */ + public static RecipientInformationStore getRecipientInfos(MimeBodyPart message) throws MessagingException, CMSException + { + if(message.getContentType().equals(SMIMEAuthEnvelopedGenerator.AUTH_ENVELOPED_DATA_CONTENT_TYPE)) + { + return new SMIMEAuthEnveloped(message).getRecipientInfos(); + } + return new SMIMEEnveloped(message).getRecipientInfos(); + } + + /** + * Utility method which will return an SMIMEEnvelopedGenerator or an + * SMIMEAuthEnvelopedGenerator as appropriate for the algorithm OID passed in. + * + * @param algorithm algorithm OID + * @return a SMIME Enveloped Generator class. + */ + public static SMIMEEnvelopedGenerator createGenerator(ASN1ObjectIdentifier algorithm) + { + if (authOIDs.contains(algorithm)) + { + return new SMIMEAuthEnvelopedGenerator(); + } + return new SMIMEEnvelopedGenerator(); + } +} diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESigned.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESigned.java index fd8698cc04..2a080a76dd 100644 --- a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESigned.java +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESigned.java @@ -23,6 +23,8 @@ /** * general class for handling a pkcs7-signature message. *

      + * (SMIMESignedParser may be preferred e.g. for large files, since it avoids loading all the data at once). + *

      * A simple example of usage - note, in the example below the validity of * the certificate isn't verified, just the fact that one of the certs * matches the given signer... diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESignedParser.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESignedParser.java index 964aa5c270..00172b74ac 100644 --- a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESignedParser.java +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMESignedParser.java @@ -64,8 +64,8 @@ public class SMIMESignedParser extends CMSSignedDataParser { - Object message; - MimeBodyPart content; + protected Object message; + protected MimeBodyPart content; private static File getTmpFile() throws MessagingException diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEToolkit.java b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEToolkit.java index 939dcc1e58..49016b6d33 100644 --- a/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEToolkit.java +++ b/mail/src/main/java/org/bouncycastle/mail/smime/SMIMEToolkit.java @@ -54,7 +54,10 @@ public SMIMEToolkit(DigestCalculatorProvider digestCalculatorProvider) public boolean isEncrypted(Part message) throws MessagingException { - return message.getHeader("Content-Type")[0].equals("application/pkcs7-mime; name=\"smime.p7m\"; smime-type=enveloped-data"); + String mainContentType = message.getHeader("Content-Type")[0]; + + return mainContentType.equals(SMIMEEnvelopedGenerator.ENVELOPED_DATA_CONTENT_TYPE) + || mainContentType.equals(SMIMEAuthEnvelopedGenerator.AUTH_ENVELOPED_DATA_CONTENT_TYPE); } /** diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/examples/package-info.java b/mail/src/main/java/org/bouncycastle/mail/smime/examples/package-info.java new file mode 100644 index 0000000000..76a4cc59e5 --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/examples/package-info.java @@ -0,0 +1,4 @@ +/** + * Example code demonstrating the use of the S/MIME package for a variety of uses. + */ +package org.bouncycastle.mail.smime.examples; diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/handlers/multipart_signed.java b/mail/src/main/java/org/bouncycastle/mail/smime/handlers/multipart_signed.java index 3abd395f01..7fba22651c 100644 --- a/mail/src/main/java/org/bouncycastle/mail/smime/handlers/multipart_signed.java +++ b/mail/src/main/java/org/bouncycastle/mail/smime/handlers/multipart_signed.java @@ -207,7 +207,7 @@ public void writeln(String s) { try { - byte abyte0[] = Strings.toByteArray(s); + byte abyte0[] = Strings.toUTF8ByteArray(s); super.out.write(abyte0); super.out.write(newline); } diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/handlers/package-info.java b/mail/src/main/java/org/bouncycastle/mail/smime/handlers/package-info.java new file mode 100644 index 0000000000..fe2ee3e574 --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/handlers/package-info.java @@ -0,0 +1,4 @@ +/** + * S/MIME handlers for the JavaMail API. + */ +package org.bouncycastle.mail.smime.handlers; diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/package-info.java b/mail/src/main/java/org/bouncycastle/mail/smime/package-info.java new file mode 100644 index 0000000000..3be9861ca1 --- /dev/null +++ b/mail/src/main/java/org/bouncycastle/mail/smime/package-info.java @@ -0,0 +1,10 @@ +/** + * High level classes for dealing with S/MIME objects (RFC 3851). + *

      + * There is one thing that is worth commenting about with these. If you're using + * AS2 on some other standard which specifies a different default content transfer encoding from RFC 2405, make + * sure you use the constructors on SMIMESigned and SMIMESignedGenerator that allow you to + * set the default ("binary" in the case of AS2 as opposed to "bit7" which is the default). + *

      + */ +package org.bouncycastle.mail.smime; diff --git a/mail/src/test/java/org/bouncycastle/mail/smime/test/AllTests.java b/mail/src/test/java/org/bouncycastle/mail/smime/test/AllTests.java index 65305772f1..662fc75958 100644 --- a/mail/src/test/java/org/bouncycastle/mail/smime/test/AllTests.java +++ b/mail/src/test/java/org/bouncycastle/mail/smime/test/AllTests.java @@ -49,6 +49,7 @@ public static Test suite() suite.addTestSuite(NewSMIMESignedTest.class); suite.addTestSuite(SignedMailValidatorTest.class); + suite.addTestSuite(NewSMIMEAuthEnvelopedTest.class); suite.addTestSuite(NewSMIMEEnvelopedTest.class); suite.addTestSuite(SMIMECompressedTest.class); suite.addTestSuite(SMIMEMiscTest.class); diff --git a/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEAuthEnvelopedTest.java b/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEAuthEnvelopedTest.java new file mode 100644 index 0000000000..5865303bc8 --- /dev/null +++ b/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEAuthEnvelopedTest.java @@ -0,0 +1,563 @@ +package org.bouncycastle.mail.smime.test; + +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.security.KeyPair; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Arrays; + +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cms.CMSAlgorithm; +import org.bouncycastle.cms.CMSAuthEnvelopedDataGenerator; +import org.bouncycastle.cms.KeyTransRecipientId; +import org.bouncycastle.cms.RecipientId; +import org.bouncycastle.cms.RecipientInformation; +import org.bouncycastle.cms.RecipientInformationStore; +import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; +import org.bouncycastle.cms.jcajce.JceKeyAgreeEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientId; +import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientInfoGenerator; +import org.bouncycastle.cms.jcajce.JceKeyTransAuthEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyTransRecipientId; +import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.mail.smime.SMIMEAuthEnveloped; +import org.bouncycastle.mail.smime.SMIMEAuthEnvelopedGenerator; +import org.bouncycastle.mail.smime.SMIMEAuthEnvelopedParser; +import org.bouncycastle.mail.smime.SMIMEEnveloped; +import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator; +import org.bouncycastle.mail.smime.SMIMEToolkit; +import org.bouncycastle.mail.smime.SMIMEUtil; +import org.bouncycastle.mail.smime.util.FileBackedMimeBodyPart; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; +import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.bouncycastle.util.encoders.Base64; + +public class NewSMIMEAuthEnvelopedTest + extends TestCase +{ + private static final String BC = BouncyCastleProvider.PROVIDER_NAME; + + private static String _signDN; + private static KeyPair _signKP; + + private static String _reciDN; + private static KeyPair _reciKP; + private static X509Certificate _reciCert; + + private static String _reciDN2; + private static KeyPair _reciKP2; + private static X509Certificate _reciCert2; + + private static KeyPair _origEcKP; + private static KeyPair _reciEcKP; + private static X509Certificate _reciEcCert; + private static KeyPair _reciEcKP2; + private static X509Certificate _reciEcCert2; + + private static boolean _initialised = false; + + static final byte[] testMessage = Base64.decode( + "TUlNRS1WZXJzaW9uOiAxLjANCkNvbnRlbnQtVHlwZTogbXVsdGlwYXJ0L21peGVkOyANCglib3VuZGFye" + + "T0iLS0tLT1fUGFydF8wXzI2MDM5NjM4Ni4xMzUyOTA0NzUwMTMyIg0KQ29udGVudC1MYW5ndWFnZTogZW" + + "4NCkNvbnRlbnQtRGVzY3JpcHRpb246IEEgbWFpbCBmb2xsb3dpbmcgdGhlIERJUkVDVCBwcm9qZWN0IHN" + + "wZWNpZmljYXRpb25zDQoNCi0tLS0tLT1fUGFydF8wXzI2MDM5NjM4Ni4xMzUyOTA0NzUwMTMyDQpDb250" + + "ZW50LVR5cGU6IHRleHQvcGxhaW47IG5hbWU9bnVsbDsgY2hhcnNldD11cy1hc2NpaQ0KQ29udGVudC1Uc" + + "mFuc2Zlci1FbmNvZGluZzogN2JpdA0KQ29udGVudC1EaXNwb3NpdGlvbjogaW5saW5lOyBmaWxlbmFtZT" + + "1udWxsDQoNCkNpYW8gZnJvbSB2aWVubmENCi0tLS0tLT1fUGFydF8wXzI2MDM5NjM4Ni4xMzUyOTA0NzU" + + "wMTMyLS0NCg=="); + + private static void init() + throws Exception + { + if (!_initialised) + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + + _initialised = true; + + _signDN = "O=Bouncy Castle, C=AU"; + _signKP = CMSTestUtil.makeKeyPair(); + + _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; + _reciKP = CMSTestUtil.makeKeyPair(); + _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); + + _reciDN2 = "CN=Fred, OU=Sales, O=Bouncy Castle, C=AU"; + _reciKP2 = CMSTestUtil.makeKeyPair(); + _reciCert2 = CMSTestUtil.makeCertificate(_reciKP2, _reciDN2, _signKP, _signDN); + + _origEcKP = CMSTestUtil.makeEcDsaKeyPair(); + _reciEcKP = CMSTestUtil.makeEcDsaKeyPair(); + _reciEcCert = CMSTestUtil.makeCertificate(_reciEcKP, _reciDN, _signKP, _signDN); + _reciEcKP2 = CMSTestUtil.makeEcDsaKeyPair(); + _reciEcCert2 = CMSTestUtil.makeCertificate(_reciEcKP2, _reciDN2, _signKP, _signDN); + } + } + + public NewSMIMEAuthEnvelopedTest(String name) + { + super(name); + } + + public static void main(String[] args) + { + junit.textui.TestRunner.run(NewSMIMEAuthEnvelopedTest.class); + } + + public static Test suite() + throws Exception + { + return new SMIMETestSetup(new TestSuite(NewSMIMEAuthEnvelopedTest.class)); + } + + public void setUp() + throws Exception + { + init(); + } + + private MimeMessage loadMessage(String name) + throws MessagingException, FileNotFoundException + { + Session session = Session.getDefaultInstance(System.getProperties(), null); + + return new MimeMessage(session, getClass().getResourceAsStream(name)); + } + + private X509Certificate loadCert(String name) + throws Exception + { + return (X509Certificate)CertificateFactory.getInstance("X.509", BC).generateCertificate(getClass().getResourceAsStream(name)); + } + + private PrivateKey loadKey(String name) + throws Exception + { + return new JcaPEMKeyConverter().setProvider("BC").getKeyPair((PEMKeyPair)(new PEMParser(new InputStreamReader(getClass().getResourceAsStream(name)))).readObject()).getPrivate(); + } + + public void testHeaders() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + + SMIMEAuthEnvelopedGenerator gen = new SMIMEAuthEnvelopedGenerator(); + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content + // we want encrypted. + // + + MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_GCM).setProvider(BC).build()); + + assertEquals("application/pkcs7-mime; name=\"smime.p7m\"; smime-type=authEnveloped-data", mp.getHeader("Content-Type")[0]); + assertEquals("attachment; filename=\"smime.p7m\"", mp.getHeader("Content-Disposition")[0]); + assertEquals("S/MIME Encrypted Message", mp.getHeader("Content-Description")[0]); + } + + public void testAES128Encrypted() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + String algorithm = SMIMEAuthEnvelopedGenerator.AES256_GCM; + + verifyAlgorithm(algorithm, msg); + } + + public void testAES192Encrypted() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + String algorithm = SMIMEAuthEnvelopedGenerator.AES256_GCM; + + verifyAlgorithm(algorithm, msg); + } + + public void testAES256Encrypted() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + String algorithm = SMIMEAuthEnvelopedGenerator.AES256_GCM; + + verifyAlgorithm(algorithm, msg); + } + + public void testSubKeyId() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + + SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); + + // + // create a subject key id - this has to be done the same way as + // it is done in the certificate associated with the private key + // + MessageDigest dig = MessageDigest.getInstance("SHA1", BC); + dig.update(SubjectPublicKeyInfo.getInstance(_reciCert.getPublicKey().getEncoded()).getPublicKeyData().getBytes()); + + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(dig.digest(), _reciCert.getPublicKey()).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content + // we want encrypted. + // + + MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build()); + + SMIMEEnveloped m = new SMIMEEnveloped(mp); + + dig.update(SubjectPublicKeyInfo.getInstance(_reciCert.getPublicKey().getEncoded()).getPublicKeyData().getBytes()); + + RecipientId recId = new KeyTransRecipientId(dig.digest()); + + RecipientInformationStore recipients = m.getRecipientInfos(); + RecipientInformation recipient = recipients.get(recId); + + MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(msg, res); + } + + public void testDotNetEncMailMatch() + throws Exception + { + MimeMessage message = loadMessage("dotnet_encrypted_mail.eml"); + + SMIMEEnveloped env = new SMIMEEnveloped(message); + + RecipientInformationStore store = env.getRecipientInfos(); + + assertNotNull(store.get(new JceKeyTransRecipientId(loadCert("dotnet_enc_cert.pem")))); + } + + public void testAES128() + throws Exception + { + MimeMessage message = loadMessage("test128.message"); + + SMIMEEnveloped env = new SMIMEEnveloped(message); + + RecipientInformationStore store = env.getRecipientInfos(); + + RecipientInformation recipInfo = store.get(new JceKeyTransRecipientId(loadCert("cert.pem"))); + + assertNotNull(recipInfo); + + byte[] content = recipInfo.getContent(new JceKeyTransEnvelopedRecipient(loadKey("key.pem"))); + + assertTrue(org.bouncycastle.util.Arrays.areEqual(testMessage, content)); + } + + public void testAES192() + throws Exception + { + MimeMessage message = loadMessage("test192.message"); + + SMIMEEnveloped env = new SMIMEEnveloped(message); + + RecipientInformationStore store = env.getRecipientInfos(); + + RecipientInformation recipInfo = store.get(new JceKeyTransRecipientId(loadCert("cert.pem"))); + + assertNotNull(recipInfo); + + byte[] content = recipInfo.getContent(new JceKeyTransEnvelopedRecipient(loadKey("key.pem"))); + + assertTrue(org.bouncycastle.util.Arrays.areEqual(testMessage, content)); + } + + public void testAES256() + throws Exception + { + MimeMessage message = loadMessage("test256.message"); + + SMIMEEnveloped env = new SMIMEEnveloped(message); + + RecipientInformationStore store = env.getRecipientInfos(); + + RecipientInformation recipInfo = store.get(new JceKeyTransRecipientId(loadCert("cert.pem"))); + + assertNotNull(recipInfo); + + byte[] content = recipInfo.getContent(new JceKeyTransEnvelopedRecipient(loadKey("key.pem"))); + + assertTrue(org.bouncycastle.util.Arrays.areEqual(testMessage, content)); + } + + public void testCapEncrypt() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + + SMIMEAuthEnvelopedGenerator gen = new SMIMEAuthEnvelopedGenerator(); + + // + // create a subject key id - this has to be done the same way as + // it is done in the certificate associated with the private key + // + MessageDigest dig = MessageDigest.getInstance("SHA256", BC); + + dig.update(_reciCert.getPublicKey().getEncoded()); + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(dig.digest(), _reciCert.getPublicKey()).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content + // we want encrypted. + // + MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_GCM).setProvider(BC).build()); + + SMIMEAuthEnveloped m = new SMIMEAuthEnveloped(mp); + + dig.update(_reciCert.getPublicKey().getEncoded()); + + RecipientId recId = new KeyTransRecipientId(dig.digest()); + + RecipientInformationStore recipients = m.getRecipientInfos(); + RecipientInformation recipient = recipients.get(recId); + + MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(msg, res); + } + + public void testChacha20Poly1305Encrypt() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + + SMIMEAuthEnvelopedGenerator gen = new SMIMEAuthEnvelopedGenerator(); + + // + // create a subject key id - this has to be done the same way as + // it is done in the certificate associated with the private key + // + MessageDigest dig = MessageDigest.getInstance("SHA256", BC); + + dig.update(_reciCert.getPublicKey().getEncoded()); + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(dig.digest(), _reciCert.getPublicKey()).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content + // we want encrypted. + // + MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.ChaCha20Poly1305).setProvider(BC).build()); + + SMIMEAuthEnveloped m = new SMIMEAuthEnveloped(mp); + + dig.update(_reciCert.getPublicKey().getEncoded()); + + RecipientId recId = new KeyTransRecipientId(dig.digest()); + + RecipientInformationStore recipients = m.getRecipientInfos(); + RecipientInformation recipient = recipients.get(recId); + + MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(msg, res); + } + + public void testTwoRecipients() + throws Exception + { + MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + + SMIMEAuthEnvelopedGenerator gen = new SMIMEAuthEnvelopedGenerator(); + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert2).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content we want encrypted. + // + MimeBodyPart mp = gen.generate(_msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_GCM).setProvider(BC).build()); + + SMIMEAuthEnvelopedParser m = new SMIMEAuthEnvelopedParser(mp); + + RecipientId recId = getRecipientId(_reciCert2); + + RecipientInformationStore recipients = m.getRecipientInfos(); + RecipientInformation recipient = recipients.get(recId); + + FileBackedMimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContentStream(new JceKeyTransAuthEnvelopedRecipient(_reciKP2.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(_msg, res); + + mp = gen.generate(_msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_GCM).setProvider(BC).build()); + + assertTrue(new SMIMEToolkit(new JcaDigestCalculatorProviderBuilder().build()).isEncrypted(mp)); + + m = new SMIMEAuthEnvelopedParser(mp); + + res.dispose(); + + recId = getRecipientId(_reciCert); + + recipients = m.getRecipientInfos(); + recipient = recipients.get(recId); + + res = SMIMEUtil.toMimeBodyPart(recipient.getContentStream(new JceKeyTransAuthEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(_msg, res); + + res.dispose(); + } + + private void verifyAlgorithm( + String algorithmOid, + MimeBodyPart msg) + throws Exception + { + SMIMEAuthEnvelopedGenerator gen = new SMIMEAuthEnvelopedGenerator(); + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content + // we want encrypted. + // + + MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(algorithmOid)).setProvider(BC).build()); + SMIMEAuthEnveloped m = new SMIMEAuthEnveloped(mp); + RecipientId recId = getRecipientId(_reciCert); + + RecipientInformationStore recipients = m.getRecipientInfos(); + RecipientInformation recipient = recipients.get(recId); + + MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(msg, res); + } + + private void verifyParserAlgorithm( + String algorithmOid, + MimeBodyPart msg) + throws Exception + { + SMIMEAuthEnvelopedGenerator gen = new SMIMEAuthEnvelopedGenerator(); + + gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + // + // generate a MimeBodyPart object which encapsulates the content + // we want encrypted. + // + + MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(algorithmOid)).setProvider(BC).build()); + SMIMEAuthEnvelopedParser m = new SMIMEAuthEnvelopedParser(mp); + RecipientId recId = getRecipientId(_reciCert); + + RecipientInformationStore recipients = m.getRecipientInfos(); + RecipientInformation recipient = recipients.get(recId); + + MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); + + SMIMETestUtil.verifyMessageBytes(msg, res); + } + + private RecipientId getRecipientId( + X509Certificate cert) + throws IOException, CertificateEncodingException + { + RecipientId recId = new JceKeyTransRecipientId(cert); + + return recId; + } + + public void testKDFAgreements() + throws Exception + { + MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); + + doTryAgreement(msg, CMSAlgorithm.ECDH_SHA1KDF); + doTryAgreement(msg, CMSAlgorithm.ECDH_SHA224KDF); + doTryAgreement(msg, CMSAlgorithm.ECDH_SHA256KDF); + doTryAgreement(msg, CMSAlgorithm.ECDH_SHA384KDF); + doTryAgreement(msg, CMSAlgorithm.ECDH_SHA512KDF); + + doTryAgreement(msg, CMSAlgorithm.ECCDH_SHA1KDF); + doTryAgreement(msg, CMSAlgorithm.ECCDH_SHA224KDF); + doTryAgreement(msg, CMSAlgorithm.ECCDH_SHA256KDF); + doTryAgreement(msg, CMSAlgorithm.ECCDH_SHA384KDF); + doTryAgreement(msg, CMSAlgorithm.ECCDH_SHA512KDF); + + doTryAgreement(msg, CMSAlgorithm.ECMQV_SHA1KDF); + doTryAgreement(msg, CMSAlgorithm.ECMQV_SHA224KDF); + doTryAgreement(msg, CMSAlgorithm.ECMQV_SHA256KDF); + doTryAgreement(msg, CMSAlgorithm.ECMQV_SHA384KDF); + doTryAgreement(msg, CMSAlgorithm.ECMQV_SHA512KDF); + } + + private void doTryAgreement(MimeBodyPart data, ASN1ObjectIdentifier algorithm) + throws Exception + { + SMIMEAuthEnvelopedGenerator edGen = new SMIMEAuthEnvelopedGenerator(); + + edGen.addRecipientInfoGenerator(new JceKeyAgreeRecipientInfoGenerator(algorithm, + _origEcKP.getPrivate(), _origEcKP.getPublic(), + CMSAlgorithm.AES128_WRAP).addRecipient(_reciEcCert).setProvider(BC)); + + MimeBodyPart res = edGen.generate( + data, + new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM).setProvider(BC).build()); + + SMIMEAuthEnveloped ed = new SMIMEAuthEnveloped(res); + + assertEquals(ed.getEncryptionAlgOID(), CMSAuthEnvelopedDataGenerator.AES128_GCM); + + RecipientInformationStore recipients = ed.getRecipientInfos(); + + confirmDataReceived(recipients, data, _reciEcCert, _reciEcKP.getPrivate(), BC); + confirmNumberRecipients(recipients, 1); + } + + private static void confirmDataReceived(RecipientInformationStore recipients, + MimeBodyPart expectedData, X509Certificate reciCert, PrivateKey reciPrivKey, String provider) + throws Exception + { + RecipientId rid = new JceKeyAgreeRecipientId(reciCert); + + RecipientInformation recipient = recipients.get(rid); + assertNotNull(recipient); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + expectedData.writeTo(bOut); + + byte[] actualData = recipient.getContent(new JceKeyAgreeEnvelopedRecipient(reciPrivKey).setProvider(provider)); + assertEquals(true, Arrays.equals(bOut.toByteArray(), actualData)); + } + + private static void confirmNumberRecipients(RecipientInformationStore recipients, int count) + { + assertEquals(count, recipients.getRecipients().size()); + } +} diff --git a/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEEnvelopedTest.java b/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEEnvelopedTest.java index 643de5aa24..7c8aebd4aa 100644 --- a/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEEnvelopedTest.java +++ b/mail/src/test/java/org/bouncycastle/mail/smime/test/NewSMIMEEnvelopedTest.java @@ -42,11 +42,13 @@ import org.bouncycastle.mail.smime.SMIMEEnveloped; import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator; import org.bouncycastle.mail.smime.SMIMEEnvelopedParser; +import org.bouncycastle.mail.smime.SMIMEToolkit; import org.bouncycastle.mail.smime.SMIMEUtil; import org.bouncycastle.mail.smime.util.FileBackedMimeBodyPart; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; +import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.encoders.Base64; public class NewSMIMEEnvelopedTest @@ -184,7 +186,7 @@ public void testDESEDE3Encrypted() { MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); String algorithm = SMIMEEnvelopedGenerator.DES_EDE3_CBC; - + verifyAlgorithm(algorithm, msg); } @@ -474,6 +476,8 @@ private void verifyAlgorithm( RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); + assertTrue(new SMIMEToolkit(new JcaDigestCalculatorProviderBuilder().build()).isEncrypted(mp)); + MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC))); SMIMETestUtil.verifyMessageBytes(msg, res); diff --git a/mail/src/test/java/org/bouncycastle/mail/smime/test/SMIMEToolkitTest.java b/mail/src/test/java/org/bouncycastle/mail/smime/test/SMIMEToolkitTest.java index 4d6c013104..54cb4b9c8a 100644 --- a/mail/src/test/java/org/bouncycastle/mail/smime/test/SMIMEToolkitTest.java +++ b/mail/src/test/java/org/bouncycastle/mail/smime/test/SMIMEToolkitTest.java @@ -44,6 +44,7 @@ import org.bouncycastle.mail.smime.SMIMESigned; import org.bouncycastle.mail.smime.SMIMESignedGenerator; import org.bouncycastle.mail.smime.SMIMEToolkit; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JcaPKIXIdentityBuilder; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; @@ -261,12 +262,14 @@ public void testSignedMessageVerificationEncapsulatedWithPKIXIdentity() MimeBodyPart res = gen.generateEncapsulated(msg); - Assert.assertTrue(toolkit.isValidSignature(res, new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(identity.getCertificate()))); + // TODO: certificate has expired + JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter(); + Assert.assertTrue(toolkit.isValidSignature(res, new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(keyConverter.getPublicKey(identity.getCertificate().getSubjectPublicKeyInfo())))); MimeMessage body = makeMimeMessage(res); - Assert.assertTrue(toolkit.isValidSignature(body, new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(identity.getCertificate()))); - Assert.assertTrue(toolkit.isValidSignature(body, new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(identity.getX509Certificate()))); + Assert.assertTrue(toolkit.isValidSignature(body, new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(keyConverter.getPublicKey(identity.getCertificate().getSubjectPublicKeyInfo())))); + Assert.assertTrue(toolkit.isValidSignature(body, new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(identity.getX509Certificate().getPublicKey()))); } public void testEncryptedMimeBodyPart() diff --git a/mls/build.gradle b/mls/build.gradle index 748d12b7e6..7b099b2e57 100644 --- a/mls/build.gradle +++ b/mls/build.gradle @@ -29,7 +29,6 @@ sourceSets { } dependencies { - implementation project(':core') implementation project(':util') implementation project(':pkix') implementation project(':prov') @@ -60,15 +59,15 @@ dependencies { // compileOnly "org.apache.tomcat:annotations-api:6.0.53" // runtimeOnly "io.grpc:grpc-netty-shaded:${grpcVersion}" // implementation "com.google.protobuf:protobuf-java-util:${protocVersion}" - - java9Implementation files("$bc_prov") - java9Implementation files("$bc_util") - java9Implementation files("$bc_pkix") java9Implementation files(sourceSets.main.output.classesDirs) { builtBy compileJava } } +evaluationDependsOn(":prov") +evaluationDependsOn(":util") +evaluationDependsOn(":pkix") + def grpcVersion = '1.58.0' // CURRENT_GRPC_VERSION def protocVersion = '3.22.3' @@ -78,8 +77,7 @@ checkstyleMain { } compileJava { - sourceCompatibility = 1.8 - targetCompatibility = 1.8 + options.release = 8 options.errorprone.disableWarningsInGeneratedCode = true options.errorprone.errorproneArgs = ["-Xep:IgnoredPureGetter:OFF"] @@ -87,13 +85,15 @@ compileJava { } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + + options.release = 9 + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" + def util_jar="${project(":util").jar.outputs.files.getFiles().getAt(0)}" + def pkix_jar="${project(":pkix").jar.outputs.files.getFiles().getAt(0)}" + + options.compilerArgs += [ - '--module-path', "${bc_prov}${File.pathSeparator}${bc_util}${File.pathSeparator}${bc_pkix}" + '--module-path', "${prov_jar}${File.pathSeparator}${util_jar}${File.pathSeparator}${pkix_jar}" ] options.sourcepath = files(['src/main/java', 'src/main/jdk1.9']) @@ -155,13 +155,14 @@ jar { } String packages = 'org.bouncycastle.mls.*' - + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bcmls') manifest.attributes('Bundle-SymbolicName': 'bcmls') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': "${packages}") - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!${packages},org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "${packages};version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!${packages},org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") } task sourcesJar(type: Jar) { @@ -186,3 +187,25 @@ artifacts { archives javadocJar archives sourcesJar } + +test { + jvmArgs = ['-Dtest.java.version.prefix=any'] +} + +compileJava9Java.dependsOn([":prov:jar", ":util:jar",":pkix:jar"]) + +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcmls-$vmrange" + from components.java + + + artifact(javadocJar) + artifact(sourcesJar) + } + + + } +} \ No newline at end of file diff --git a/mls/src/test/java/org/bouncycastle/mls/test/ClientVectorTest.java b/mls/src/test/java/org/bouncycastle/mls/test/ClientVectorTest.java index 4b96ccc867..71c7146784 100644 --- a/mls/src/test/java/org/bouncycastle/mls/test/ClientVectorTest.java +++ b/mls/src/test/java/org/bouncycastle/mls/test/ClientVectorTest.java @@ -3,6 +3,7 @@ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; +import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -11,6 +12,7 @@ import junit.framework.TestCase; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.mls.TreeKEM.TreeKEMPublicKey; import org.bouncycastle.mls.codec.MLSInputStream; import org.bouncycastle.mls.codec.MLSMessage; @@ -20,6 +22,7 @@ import org.bouncycastle.mls.protocol.Group; import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.encoders.Hex; public class ClientVectorTest @@ -134,6 +137,14 @@ public Epoch(List proposals, byte[] commit, byte[] epoch_authenticator) } MlsCipherSuite suite = MlsCipherSuite.getSuite(cipherSuite); + + if(cipherSuite == MlsCipherSuite.MLS_256_DHKEMP521_AES256GCM_SHA512_P521) + { + //Converts encoded HPKE private key for P521 to comply with length constraints + encryption_priv = BigIntegers.asUnsignedByteArray(66, new BigInteger(1, encryption_priv)); + init_priv = BigIntegers.asUnsignedByteArray(66, new BigInteger(1, init_priv)); + } + AsymmetricCipherKeyPair leafKeyPair = suite.getHPKE().deserializePrivateKey(encryption_priv, null); Map externalPsks = new HashMap(); for (PreSharedKeyID ext : externalPSKs) diff --git a/osgi_scan.sh b/osgi_scan.sh new file mode 100755 index 0000000000..cdfb607b25 --- /dev/null +++ b/osgi_scan.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e + +if ! command -v osgiscanner &> /dev/null +then + echo "osgiscanner not on path" + exit 1 +fi + +export script_loc=$( cd -- "$( dirname -- "$0" )" &> /dev/null && pwd ) +cd $script_loc + +export BCHOME=`pwd` + +osgiscanner -f osgi_scan.xml diff --git a/osgi_scan.xml b/osgi_scan.xml new file mode 100644 index 0000000000..6a9db0ba29 --- /dev/null +++ b/osgi_scan.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + +
      + +
      + + + + + + + + +
      + +
      + +
      + +
      + +
      + + + + + diff --git a/pg/build.gradle b/pg/build.gradle index f14cee7d4b..2bd4a4dd5a 100644 --- a/pg/build.gradle +++ b/pg/build.gradle @@ -4,6 +4,11 @@ plugins { } sourceSets { + main { + java { + srcDirs = ["$buildDir/generated-src"] + } + } java9 { java { srcDirs = ['src/main/jdk1.9'] @@ -13,7 +18,6 @@ sourceSets { dependencies { - implementation project(':core') implementation project(':prov') implementation project(':util') @@ -26,33 +30,45 @@ dependencies { testImplementation group: 'junit', name: 'junit', version: '4.13.2' } +evaluationDependsOn(":prov") +evaluationDependsOn(":util") + +task generateSources(type: Copy) { + from 'src/main/java' + into "$buildDir/generated-src" + filter { line -> line.replaceAll('@RELEASE_NAME@', "${version}") } +} + +compileJava.dependsOn generateSources + compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + + options.release = 8 } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + + options.release = 9 + + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" + def util_jar="${project(":util").jar.outputs.files.getFiles().getAt(0)}" + options.compilerArgs += [ - '--module-path', "${bc_prov}${File.pathSeparator}${bc_util}" + '--module-path', "${prov_jar}${File.pathSeparator}${util_jar}" ] - options.sourcepath = files(['src/main/java', 'src/main/jdk1.9']) + options.sourcepath = files(["$buildDir/generated-src", 'src/main/jdk1.9']) } jar.archiveBaseName = "bcpg-$vmrange" + task sourcesJar(type: Jar) { + dependsOn generateSources + archiveBaseName = jar.archiveBaseName archiveClassifier = 'sources' from sourceSets.main.allSource @@ -67,12 +83,14 @@ jar { into('META-INF/versions/9') { from sourceSets.java9.output } + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') manifest.attributes('Bundle-Name': 'bcpg') manifest.attributes('Bundle-SymbolicName': 'bcpg') - manifest.attributes('Export-Package': 'org.bouncycastle.{apache|bcpg|gpg|openpgp}.*') - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.{apache|bcpg|gpg|openpgp|}.*,org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "org.bouncycastle.{apache|bcpg|gpg|openpgp}.*;version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.{apache|bcpg|gpg|openpgp|}.*,org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") } @@ -91,5 +109,24 @@ artifacts { test { forkEvery = 1; maxParallelForks = 8; + maxHeapSize = "3g"; + jvmArgs = ['-Dtest.java.version.prefix=any'] } +compileJava9Java.dependsOn([":prov:jar", ":util:jar"]) + +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcpg-$vmrange" + from components.java + + + artifact(javadocJar) + artifact(sourcesJar) + } + + + } +} \ No newline at end of file diff --git a/pg/src/main/j2me/org/bouncycastle/bcpg/S2K.java b/pg/src/main/j2me/org/bouncycastle/bcpg/S2K.java index ae2fe6ee73..8e26638183 100644 --- a/pg/src/main/j2me/org/bouncycastle/bcpg/S2K.java +++ b/pg/src/main/j2me/org/bouncycastle/bcpg/S2K.java @@ -452,7 +452,7 @@ public Argon2Params(byte[] salt, int passes, int parallelism, int memSizeExp) // log_2(p) = log_e(p) / log_e(2) //double log2_p = Math.log((double)parallelism) / Math.log(2.0); - // see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-05.html#section-3.7.1.4-5 + // see https://www.rfc-editor.org/rfc/rfc9580.html#section-3.7.1.4-5 //if (memSizeExp < (3 + Math.ceil(log2_p)) || memSizeExp > 31) //{ //throw new IllegalArgumentException("Memory size exponent MUST be between 3+ceil(log_2(parallelism)) and 31"); diff --git a/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKey.java b/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKey.java index 229df26273..3ced9181e2 100644 --- a/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKey.java +++ b/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKey.java @@ -337,11 +337,12 @@ public long getKeyID() */ public byte[] getFingerprint() { - byte[] tmp = new byte[fingerprint.length]; - - System.arraycopy(fingerprint, 0, tmp, 0, tmp.length); - - return tmp; + return Arrays.clone(fingerprint); + } + + public boolean hasFingerprint(byte[] fingerprint) + { + return Arrays.areEqual(this.fingerprint, fingerprint); } /** diff --git a/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKeyRing.java b/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKeyRing.java index 03ad6b7a24..d16478feb3 100644 --- a/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKeyRing.java +++ b/pg/src/main/j2me/org/bouncycastle/openpgp/PGPPublicKeyRing.java @@ -15,7 +15,6 @@ import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.TrustPacket; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; -import org.bouncycastle.util.Arrays; /** * Class to hold a single master public key and its subkeys. @@ -135,7 +134,7 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) { PGPPublicKey k = (PGPPublicKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getFingerprint())) + if (k.hasFingerprint(fingerprint)) { return k; } diff --git a/pg/src/main/j2me/org/bouncycastle/openpgp/PGPSecretKeyRing.java b/pg/src/main/j2me/org/bouncycastle/openpgp/PGPSecretKeyRing.java index 1263dbcc9d..6248c51a1a 100644 --- a/pg/src/main/j2me/org/bouncycastle/openpgp/PGPSecretKeyRing.java +++ b/pg/src/main/j2me/org/bouncycastle/openpgp/PGPSecretKeyRing.java @@ -20,7 +20,6 @@ import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; -import org.bouncycastle.util.Arrays; /** * Class to hold a single master secret key and its subkeys. @@ -185,7 +184,7 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) { PGPPublicKey k = (PGPPublicKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getFingerprint())) + if (k.hasFingerprint(fingerprint)) { return k; } @@ -262,7 +261,7 @@ public PGPSecretKey getSecretKey(byte[] fingerprint) { PGPSecretKey k = (PGPSecretKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getPublicKey().getFingerprint())) + if (k.getPublicKey().hasFingerprint(fingerprint)) { return k; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/AEADAlgorithmTags.java b/pg/src/main/java/org/bouncycastle/bcpg/AEADAlgorithmTags.java index a98f14d96d..965bb5107f 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/AEADAlgorithmTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/AEADAlgorithmTags.java @@ -1,8 +1,31 @@ package org.bouncycastle.bcpg; +/** + * AEAD Algorithm IDs. + * RFC9580 (OpenPGP) defines IDs 1 through 3, while LibrePGP only defines 1 and 2. + * Further, the use of AEAD differs between OpenPGP and LibrePGP. + * + * @see + * OpenPGP - AEAD Algorithms + * @see + * LibrePGP - Encryption Modes + */ public interface AEADAlgorithmTags { - int EAX = 1; // EAX (IV len: 16 octets, Tag len: 16 octets) - int OCB = 2; // OCB (IV len: 15 octets, Tag len: 16 octets) - int GCM = 3; // GCM (IV len: 12 octets, Tag len: 16 octets) + /** + * EAX with 16-bit nonce/IV and 16-bit auth tag length. + */ + int EAX = 1; + /** + * OCB with 15-bit nonce/IV and 16-bit auth tag length. + * RFC9580-compliant implementations MUST implement OCB. + */ + int OCB = 2; + /** + * GCM with 12-bit nonce/IV and 16-bit auth tag length. + * OpenPGP only. + */ + int GCM = 3; + + // 100 to 110: Experimental algorithms } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/AEADEncDataPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/AEADEncDataPacket.java index 72ee63af87..f417e94d70 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/AEADEncDataPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/AEADEncDataPacket.java @@ -5,10 +5,13 @@ import org.bouncycastle.util.Arrays; /** - * Packet representing AEAD encrypted data. At the moment this appears to exist in the following + * Packet representing non-standard, LibrePGP OCB (AEAD) encrypted data. At the moment this appears to exist in the following * expired draft only, but it's appearing despite this. + * For standardized, interoperable OpenPGP AEAD encrypted data, see {@link SymmetricEncIntegrityPacket} of version + * {@link SymmetricEncIntegrityPacket#VERSION_2}. * - * @ref https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16 + * @see + * LibrePGP - OCB Encrypted Data Packet */ public class AEADEncDataPacket extends InputStreamPacket @@ -23,14 +26,21 @@ public class AEADEncDataPacket private final byte[] iv; public AEADEncDataPacket(BCPGInputStream in) + throws IOException + { + this(in, false); + } + + public AEADEncDataPacket(BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(in, AEAD_ENC_DATA); + super(in, AEAD_ENC_DATA, newPacketFormat); version = (byte)in.read(); if (version != VERSION_1) { - throw new IllegalArgumentException("wrong AEAD packet version: " + version); + throw new UnsupportedPacketVersionException("wrong AEAD packet version: " + version); } algorithm = (byte)in.read(); @@ -57,6 +67,10 @@ public byte getVersion() return version; } + /** + * Return the algorithm-id of the symmetric encryption algorithm used to encrypt the data. + * @return symmetric encryption algorithm + */ public byte getAlgorithm() { return algorithm; diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ArmoredInputStream.java b/pg/src/main/java/org/bouncycastle/bcpg/ArmoredInputStream.java index 3bf1cd3898..99cd1532ef 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ArmoredInputStream.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ArmoredInputStream.java @@ -4,6 +4,9 @@ import java.io.EOFException; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.bouncycastle.util.StringList; import org.bouncycastle.util.Strings; @@ -24,7 +27,7 @@ public class ArmoredInputStream extends InputStream { - /* + /** * set up the decoding table. */ private static final byte[] decodingTable; @@ -75,7 +78,7 @@ private static int decode(int in0, int in1, int in2, int in3, byte[] out) if (in2 == '=') { - b1 = decodingTable[in0] &0xff; + b1 = decodingTable[in0] & 0xff; b2 = decodingTable[in1] & 0xff; if ((b1 | b2) < 0) @@ -129,30 +132,33 @@ else if (in3 == '=') */ private boolean detectMissingChecksum = false; - private final CRC24 crc; - - InputStream in; - boolean start = true; - byte[] outBuf = new byte[3]; - int bufPtr = 3; - boolean crcFound = false; - boolean hasHeaders = true; - String header = null; - boolean newLineFound = false; - boolean clearText = false; - boolean restart = false; - StringList headerList= Strings.newList(); - int lastC = 0; - boolean isEndOfStream; - + private final CRC24 crc; + + InputStream in; + boolean start = true; + byte[] outBuf = new byte[3]; + int bufPtr = 3; + boolean crcFound = false; + boolean hasHeaders = true; + String header = null; + boolean newLineFound = false; + boolean clearText = false; + boolean restart = false; + StringList headerList = Strings.newList(); + int lastC = 0; + boolean isEndOfStream; + + private boolean validateAllowedHeaders = false; + private List allowedHeaders = defaultAllowedHeaders(); + /** - * Create a stream for reading a PGP armoured message, parsing up to a header + * Create a stream for reading a PGP armoured message, parsing up to a header * and then reading the data that follows. - * + * * @param in */ public ArmoredInputStream( - InputStream in) + InputStream in) throws IOException { this(in, true); @@ -160,21 +166,21 @@ public ArmoredInputStream( /** * Create an armoured input stream which will assume the data starts - * straight away, or parse for headers first depending on the value of + * straight away, or parse for headers first depending on the value of * hasHeaders. - * + * * @param in * @param hasHeaders true if headers are to be looked for, false otherwise. */ public ArmoredInputStream( - InputStream in, - boolean hasHeaders) + InputStream in, + boolean hasHeaders) throws IOException { this.in = in; this.hasHeaders = hasHeaders; this.crc = new FastCRC24(); - + if (hasHeaders) { parseHeaders(); @@ -184,40 +190,74 @@ public ArmoredInputStream( } private ArmoredInputStream( - InputStream in, - Builder builder) + InputStream in, + Builder builder) throws IOException { this.in = in; this.hasHeaders = builder.hasHeaders; this.detectMissingChecksum = builder.detectMissingCRC; this.crc = builder.ignoreCRC ? null : new FastCRC24(); + this.validateAllowedHeaders = builder.validateAllowedHeaders; + this.allowedHeaders = builder.allowedHeaders; if (hasHeaders) { parseHeaders(); } + if (validateAllowedHeaders) + { + rejectUnknownHeadersInCSFMessages(); + } + start = false; } + private void rejectUnknownHeadersInCSFMessages() + throws ArmoredInputException + { + Iterator headerLines = headerList.iterator(); + String header = (String)headerLines.next(); + + // Only reject unknown headers in cleartext signed messages + if (!header.startsWith("-----BEGIN PGP SIGNED MESSAGE-----")) + { + return; + } + + outerloop: + while (headerLines.hasNext()) + { + String headerLine = (String)headerLines.next(); + for (Iterator it = allowedHeaders.iterator(); it.hasNext(); ) + { + if (headerLine.startsWith((String)it.next() + ": ")) + { + continue outerloop; + } + } + throw new ArmoredInputException("Illegal ASCII armor header line in clearsigned message encountered: " + headerLine); + } + } + public int available() throws IOException { return in.available(); } - + private boolean parseHeaders() throws IOException { header = null; - - int c; - int last = 0; - boolean headerFound = false; - + + int c; + int last = 0; + boolean headerFound = false; + headerList = Strings.newList(); - + // // if restart we already have a header // @@ -234,15 +274,15 @@ private boolean parseHeaders() headerFound = true; break; } - + last = c; } } if (headerFound) { - boolean eolReached = false; - boolean crLf = false; + boolean eolReached = false; + boolean crLf = false; ByteArrayOutputStream buf = new ByteArrayOutputStream(); buf.write('-'); @@ -251,7 +291,7 @@ private boolean parseHeaders() { buf.write('-'); } - + while ((c = in.read()) >= 0) { if (last == '\r' && c == '\n') @@ -268,7 +308,16 @@ private boolean parseHeaders() } if (c == '\r' || (last != '\r' && c == '\n')) { - String line = Strings.fromUTF8ByteArray(buf.toByteArray()); + String line; + + try + { + line = Strings.fromUTF8ByteArray(buf.toByteArray()); + } + catch (Exception e) + { + throw new ArmoredInputException(e.getMessage()); + } if (line.trim().length() == 0) { break; @@ -293,10 +342,10 @@ private boolean parseHeaders() eolReached = true; } } - + last = c; } - + if (crLf) { int nl = in.read(); // skip last \n @@ -306,12 +355,12 @@ private boolean parseHeaders() } } } - + if (headerList.size() > 0) { header = headerList.get(0); } - + clearText = "-----BEGIN PGP SIGNED MESSAGE-----".equals(header); newLineFound = true; @@ -337,15 +386,17 @@ public boolean isEndOfStream() /** * Return the armor header line (if there is one) + * * @return the armor header line, null if none present. */ - public String getArmorHeaderLine() + public String getArmorHeaderLine() { return header; } - + /** * Return the armor headers (the lines after the armor header line), + * * @return an array of armor headers, null if there aren't any. */ public String[] getArmorHeaders() @@ -357,12 +408,12 @@ public String[] getArmorHeaders() return headerList.toStringArray(1, headerList.size()); } - - private int readIgnoreSpace() + + private int readIgnoreSpace() throws IOException { - int c = in.read(); - + int c = in.read(); + while (c == ' ' || c == '\t' || c == '\f' || c == '\u000B') // \u000B ~ \v { c = in.read(); @@ -375,11 +426,11 @@ private int readIgnoreSpace() return c; } - + public int read() throws IOException { - int c; + int c; if (start) { @@ -394,7 +445,7 @@ public int read() } start = false; } - + if (clearText) { c = in.read(); @@ -425,25 +476,25 @@ else if (newLineFound && c == '-') newLineFound = false; } } - + lastC = c; if (c < 0) { isEndOfStream = true; } - + return c; } if (bufPtr > 2 || crcFound) { c = readIgnoreSpace(); - + if (c == '\r' || c == '\n') { c = readIgnoreSpace(); - + while (c == '\n' || c == '\r') { c = readIgnoreSpace(); @@ -533,24 +584,24 @@ else if (newLineFound && c == '-') * an array of bytes. An attempt is made to read as many as * len bytes, but a smaller number may be read. * The number of bytes actually read is returned as an integer. - * + *

      * The first byte read is stored into element b[off], the * next one into b[off+1], and so on. The number of bytes read * is, at most, equal to len. - * + *

      * NOTE: We need to override the custom behavior of Java's {@link InputStream#read(byte[], int, int)}, * as the upstream method silently swallows {@link IOException IOExceptions}. * This would cause CRC checksum errors to go unnoticed. * - * @see Related BC bug report - * @param b byte array + * @param b byte array * @param off offset at which we start writing data to the array * @param len number of bytes we write into the array * @return total number of bytes read into the buffer - * * @throws IOException if an exception happens AT ANY POINT + * @see Related BC bug report */ - public int read(byte[] b, int off, int len) throws IOException + public int read(byte[] b, int off, int len) + throws IOException { checkIndexSize(b.length, off, len); @@ -567,7 +618,7 @@ public int read(byte[] b, int off, int len) throws IOException b[off] = (byte)c; int i = 1; - for (; i < len ; i++) + for (; i < len; i++) { c = read(); if (c == -1) @@ -610,6 +661,17 @@ public void setDetectMissingCRC(boolean detectMissing) this.detectMissingChecksum = detectMissing; } + private static List defaultAllowedHeaders() + { + List allowedHeaders = new ArrayList(); + allowedHeaders.add(ArmoredOutputStream.COMMENT_HDR); + allowedHeaders.add(ArmoredOutputStream.VERSION_HDR); + allowedHeaders.add(ArmoredOutputStream.CHARSET_HDR); + allowedHeaders.add(ArmoredOutputStream.HASH_HDR); + allowedHeaders.add(ArmoredOutputStream.MESSAGE_ID_HDR); + return allowedHeaders; + } + public static Builder builder() { return new Builder(); @@ -620,6 +682,8 @@ public static class Builder private boolean hasHeaders = true; private boolean detectMissingCRC = false; private boolean ignoreCRC = false; + private boolean validateAllowedHeaders = false; + private List allowedHeaders = defaultAllowedHeaders(); private Builder() { @@ -639,6 +703,18 @@ public Builder setParseForHeaders(boolean hasHeaders) return this; } + public Builder setValidateClearsignedMessageHeaders(boolean validateHeaders) + { + this.validateAllowedHeaders = validateHeaders; + return this; + } + + public Builder addAllowedArmorHeader(String header) + { + allowedHeaders.add(header.trim()); + return this; + } + /** * Change how the stream should react if it encounters missing CRC checksum. * The default value is false (ignore missing CRC checksums). If the behavior is set to true, diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ArmoredOutputStream.java b/pg/src/main/java/org/bouncycastle/bcpg/ArmoredOutputStream.java index aa957720ad..77cabdcb76 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ArmoredOutputStream.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ArmoredOutputStream.java @@ -612,6 +612,41 @@ public Builder addComment(String comment) return addHeader(COMMENT_HDR, comment); } + public Builder addEllipsizedComment(String comment) + { + int availableCommentCharsPerLine = 64 - (COMMENT_HDR.length() + 2); // ASCII armor width - header len + comment = comment.trim(); + + if (comment.length() > availableCommentCharsPerLine) + { + comment = comment.substring(0, availableCommentCharsPerLine - 1) + '…'; + } + addComment(comment); + return this; + } + + public Builder addSplitMultilineComment(String comment) + { + int availableCommentCharsPerLine = 64 - (COMMENT_HDR.length() + 2); // ASCII armor width - header len + + comment = comment.trim(); + for (String line : comment.split("\n")) + { + while (line.length() > availableCommentCharsPerLine) + { + // split comment into multiple lines + addComment(comment.substring(0, availableCommentCharsPerLine)); + line = line.substring(availableCommentCharsPerLine).trim(); + } + + if (line.length() != 0) + { + addComment(line); + } + } + return this; + } + /** * Set and replace the given header value with a single-line header. * If the value is

      null
      , this method will remove the header entirely. diff --git a/pg/src/main/java/org/bouncycastle/bcpg/BCPGInputStream.java b/pg/src/main/java/org/bouncycastle/bcpg/BCPGInputStream.java index f965ec3503..045ba3b6ba 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/BCPGInputStream.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/BCPGInputStream.java @@ -11,7 +11,8 @@ * Stream reader for PGP objects */ public class BCPGInputStream - extends InputStream implements PacketTags + extends InputStream + implements PacketTags { /** * If the argument is a {@link BCPGInputStream}, return it. @@ -29,19 +30,19 @@ public static BCPGInputStream wrap(InputStream in) return new BCPGInputStream(in); } - InputStream in; - boolean next = false; - int nextB; + InputStream in; + boolean next = false; + int nextB; - boolean mNext = false; - int mNextB; + boolean mNext = false; + int mNextB; public BCPGInputStream( - InputStream in) + InputStream in) { this.in = in; } - + public int available() throws IOException { @@ -113,9 +114,9 @@ public int read( } public void readFully( - byte[] buf, - int off, - int len) + byte[] buf, + int off, + int len) throws IOException { if (Streams.readFully(this, buf, off, len) < len) @@ -131,7 +132,7 @@ public byte[] readAll() } public void readFully( - byte[] buf) + byte[] buf) throws IOException { readFully(buf, 0, buf.length); @@ -141,7 +142,6 @@ public void readFully( * Obtains the tag of the next packet in the stream. * * @return the {@link PacketTags tag number}. - * * @throws IOException if an error occurs reading the tag from the stream. */ public int nextPacketTag() @@ -176,12 +176,13 @@ public int nextPacketTag() /** * Reads the next packet from the stream. + * * @throws IOException */ public Packet readPacket() throws IOException { - int hdr = this.read(); + int hdr = this.read(); if (hdr < 0) { @@ -193,36 +194,17 @@ public Packet readPacket() throw new IOException("invalid header encountered"); } - boolean newPacket = (hdr & 0x40) != 0; - int tag = 0; - int bodyLen = 0; - boolean partial = false; + boolean newPacket = (hdr & 0x40) != 0; + int tag = 0; + int bodyLen = 0; + boolean partial = false; if (newPacket) { tag = hdr & 0x3f; - - int l = this.read(); - - if (l < 192) - { - bodyLen = l; - } - else if (l <= 223) - { - int b = this.read(); - - bodyLen = ((l - 192) << 8) + (b) + 192; - } - else if (l == 255) - { - bodyLen = (this.read() << 24) | (this.read() << 16) | (this.read() << 8) | this.read(); - } - else - { - partial = true; - bodyLen = 1 << (l & 0x1f); - } + boolean[] flags = new boolean[3]; + bodyLen = StreamUtil.readBodyLen(this, flags); + partial = flags[StreamUtil.flag_partial]; } else { @@ -236,10 +218,10 @@ else if (l == 255) bodyLen = this.read(); break; case 1: - bodyLen = (this.read() << 8) | this.read(); + bodyLen = StreamUtil.read2OctetLength(this); break; case 2: - bodyLen = (this.read() << 24) | (this.read() << 16) | (this.read() << 8) | this.read(); + bodyLen = StreamUtil.read4OctetLength(this); break; case 3: partial = true; @@ -249,7 +231,7 @@ else if (l == 255) } } - BCPGInputStream objStream; + BCPGInputStream objStream; if (bodyLen == 0 && partial) { @@ -260,63 +242,63 @@ else if (l == 255) objStream = new BCPGInputStream( new BufferedInputStream(new PartialInputStream(this, partial, bodyLen))); } - + switch (tag) { case RESERVED: - return new ReservedPacket(objStream); + return new ReservedPacket(objStream, newPacket); case PUBLIC_KEY_ENC_SESSION: - return new PublicKeyEncSessionPacket(objStream); + return new PublicKeyEncSessionPacket(objStream, newPacket); case SIGNATURE: - return new SignaturePacket(objStream); + return new SignaturePacket(objStream, newPacket); case SYMMETRIC_KEY_ENC_SESSION: - return new SymmetricKeyEncSessionPacket(objStream); + return new SymmetricKeyEncSessionPacket(objStream, newPacket); case ONE_PASS_SIGNATURE: - return new OnePassSignaturePacket(objStream); + return new OnePassSignaturePacket(objStream, newPacket); case SECRET_KEY: - return new SecretKeyPacket(objStream); + return new SecretKeyPacket(objStream, newPacket); case PUBLIC_KEY: - return new PublicKeyPacket(objStream); + return new PublicKeyPacket(objStream, newPacket); case SECRET_SUBKEY: - return new SecretSubkeyPacket(objStream); + return new SecretSubkeyPacket(objStream, newPacket); case COMPRESSED_DATA: - return new CompressedDataPacket(objStream); + return new CompressedDataPacket(objStream, newPacket); case SYMMETRIC_KEY_ENC: - return new SymmetricEncDataPacket(objStream); + return new SymmetricEncDataPacket(objStream, newPacket); case MARKER: - return new MarkerPacket(objStream); + return new MarkerPacket(objStream, newPacket); case LITERAL_DATA: - return new LiteralDataPacket(objStream); + return new LiteralDataPacket(objStream, newPacket); case TRUST: - return new TrustPacket(objStream); + return new TrustPacket(objStream, newPacket); case USER_ID: - return new UserIDPacket(objStream); + return new UserIDPacket(objStream, newPacket); case USER_ATTRIBUTE: - return new UserAttributePacket(objStream); + return new UserAttributePacket(objStream, newPacket); case PUBLIC_SUBKEY: - return new PublicSubkeyPacket(objStream); + return new PublicSubkeyPacket(objStream, newPacket); case SYM_ENC_INTEGRITY_PRO: - return new SymmetricEncIntegrityPacket(objStream); + return new SymmetricEncIntegrityPacket(objStream, newPacket); case MOD_DETECTION_CODE: - return new ModDetectionCodePacket(objStream); + return new ModDetectionCodePacket(objStream, newPacket); case AEAD_ENC_DATA: - return new AEADEncDataPacket(objStream); + return new AEADEncDataPacket(objStream, newPacket); case PADDING: - return new PaddingPacket(objStream); + return new PaddingPacket(objStream, newPacket); case EXPERIMENTAL_1: case EXPERIMENTAL_2: case EXPERIMENTAL_3: case EXPERIMENTAL_4: - return new ExperimentalPacket(tag, objStream); + return new ExperimentalPacket(tag, objStream, newPacket); default: - return new UnknownPacket(tag, objStream); + return new UnknownPacket(tag, objStream, newPacket); } } /** - * @deprecated use skipMarkerAndPaddingPackets * @return the tag for the next non-marker/padding packet * @throws IOException on a parsing issue. + * @deprecated use skipMarkerAndPaddingPackets */ public int skipMarkerPackets() throws IOException @@ -326,6 +308,7 @@ public int skipMarkerPackets() /** * skip any marker and padding packets found in the stream. + * * @return the tag for the next non-marker/padding packet * @throws IOException on a parsing issue. */ @@ -334,7 +317,7 @@ public int skipMarkerAndPaddingPackets() { int tag; while ((tag = nextPacketTag()) == PacketTags.MARKER - || tag == PacketTags.PADDING) + || tag == PacketTags.PADDING) { readPacket(); } @@ -350,20 +333,20 @@ public void close() /** * a stream that overlays our input stream, allowing the user to only read a segment of it. - * + *

      * NB: dataLength will be negative if the segment length is in the upper range above 2**31. */ private static class PartialInputStream extends InputStream { - private BCPGInputStream in; - private boolean partial; - private int dataLength; + private BCPGInputStream in; + private boolean partial; + private int dataLength; PartialInputStream( - BCPGInputStream in, - boolean partial, - int dataLength) + BCPGInputStream in, + boolean partial, + int dataLength) { this.in = in; this.partial = partial; @@ -392,32 +375,13 @@ public int available() private int loadDataLength() throws IOException { - int l = in.read(); - - if (l < 0) + boolean[] flags = new boolean[3]; + dataLength = StreamUtil.readBodyLen(in, flags); + if (flags[StreamUtil.flag_eof]) { return -1; } - - partial = false; - if (l < 192) - { - dataLength = l; - } - else if (l <= 223) - { - dataLength = ((l - 192) << 8) + (in.read()) + 192; - } - else if (l == 255) - { - dataLength = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); - } - else - { - partial = true; - dataLength = 1 << (l & 0x1f); - } - + partial = flags[StreamUtil.flag_partial]; return dataLength; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/BCPGOutputStream.java b/pg/src/main/java/org/bouncycastle/bcpg/BCPGOutputStream.java index 6ce35b7454..d4432920d0 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/BCPGOutputStream.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/BCPGOutputStream.java @@ -29,7 +29,7 @@ public static BCPGOutputStream wrap(OutputStream out) } OutputStream out; - private boolean useOldFormat; + private PacketFormat packetFormat; private byte[] partialBuffer; private int partialBufferLength; private int partialPower; @@ -46,11 +46,11 @@ public static BCPGOutputStream wrap(OutputStream out) public BCPGOutputStream( OutputStream out) { - this(out, false); + this(out, PacketFormat.ROUNDTRIP); } /** - * Base constructor specifying whether or not to use packets in the new format + * Base constructor specifying whether to use packets in the new format * wherever possible. * * @param out output stream to write encoded data to. @@ -59,9 +59,16 @@ public BCPGOutputStream( public BCPGOutputStream( OutputStream out, boolean newFormatOnly) + { + this(out, newFormatOnly ? PacketFormat.CURRENT : PacketFormat.ROUNDTRIP); + } + + public BCPGOutputStream( + OutputStream out, + PacketFormat packetFormat) { this.out = out; - this.useOldFormat = !newFormatOnly; + this.packetFormat = packetFormat; } /** @@ -75,6 +82,7 @@ public BCPGOutputStream( throws IOException { this.out = out; + this.packetFormat = PacketFormat.LEGACY; this.writeHeader(tag, true, true, 0); } @@ -95,6 +103,7 @@ public BCPGOutputStream( throws IOException { this.out = out; + this.packetFormat = oldFormat ? PacketFormat.LEGACY : PacketFormat.CURRENT; if (length > 0xFFFFFFFFL) { @@ -122,6 +131,7 @@ public BCPGOutputStream( throws IOException { this.out = out; + this.packetFormat = PacketFormat.CURRENT; this.writeHeader(tag, false, false, length); } @@ -141,6 +151,7 @@ public BCPGOutputStream( throws IOException { this.out = out; + this.packetFormat = PacketFormat.CURRENT; this.writeHeader(tag, false, true, 0); this.partialBuffer = buffer; @@ -195,8 +206,7 @@ private void writeHeader( else if (bodyLen <= 0xffff) { this.write(hdr | 0x01); - this.write((byte)(bodyLen >> 8)); - this.write((byte)(bodyLen)); + StreamUtil.write2OctetLength(this, (int)bodyLen); } else { @@ -316,6 +326,11 @@ public void write( } } + /** + * Write a packet to the stream. + * @param p packet + * @throws IOException + */ public void writePacket( ContainedPacket p) throws IOException @@ -323,15 +338,54 @@ public void writePacket( p.encode(this); } + /** + * Write a packet to the stream. + * The packet will use the old encoding format if {@link #packetFormat} is {@link PacketFormat#LEGACY}, otherwise + * it will be encoded using the new packet format. + * @param tag packet tag + * @param body packet body + * @throws IOException + */ void writePacket( int tag, byte[] body) throws IOException { - this.writeHeader(tag, useOldFormat, false, body.length); + this.writeHeader(tag, packetFormat == PacketFormat.LEGACY, false, body.length); this.write(body); } + /** + * Write a packet. + * The packet format will be chosen primarily based on {@link #packetFormat}. + * If {@link #packetFormat} is {@link PacketFormat#CURRENT}, the packet will be encoded using the new format. + * If it is {@link PacketFormat#LEGACY}, the packet will use old encoding format. + * If it is {@link PacketFormat#ROUNDTRIP}, then the format will be determined by objectPrefersNewPacketFormat. + * + * @param objectPrefersNewPacketFormat whether the packet prefers to be encoded using the new packet format + * @param tag packet tag + * @param body packet body + * @throws IOException + */ + void writePacket( + boolean objectPrefersNewPacketFormat, + int tag, + byte[] body) + throws IOException + { + boolean oldPacketFormat = packetFormat == PacketFormat.LEGACY || + (packetFormat == PacketFormat.ROUNDTRIP && !objectPrefersNewPacketFormat); + this.writeHeader(tag, oldPacketFormat, false, body.length); + this.write(body); + } + + /** + * Write a packet, forcing the packet format to be either old or new. + * @param tag packet tag + * @param body packet body + * @param oldFormat if true, old format is forced, else force new format + * @throws IOException + */ void writePacket( int tag, byte[] body, @@ -379,4 +433,5 @@ public void close() out.flush(); out.close(); } + } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/CompressedDataPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/CompressedDataPacket.java index 9dcafaa61c..accd96445c 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/CompressedDataPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/CompressedDataPacket.java @@ -11,10 +11,18 @@ public class CompressedDataPacket int algorithm; CompressedDataPacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + CompressedDataPacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(in, COMPRESSED_DATA); + super(in, COMPRESSED_DATA, newPacketFormat); algorithm = in.read(); } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/CompressionAlgorithmTags.java b/pg/src/main/java/org/bouncycastle/bcpg/CompressionAlgorithmTags.java index 431f4bc480..154652d8c2 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/CompressionAlgorithmTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/CompressionAlgorithmTags.java @@ -1,7 +1,14 @@ package org.bouncycastle.bcpg; /** - * Basic tags for compression algorithms + * Basic tags for compression algorithms. + * + * @see + * RFC4880 - Compression Algorithms + * @see + * RFC9580 - Compression Algorithms + * @see + * LibrePGP - Compression Algorithms */ public interface CompressionAlgorithmTags { diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ContainedPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/ContainedPacket.java index 27c82a5e4d..8f87a96af7 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ContainedPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ContainedPacket.java @@ -12,21 +12,30 @@ public abstract class ContainedPacket extends Packet implements Encodable { + ContainedPacket(int packetTag) { - super(packetTag); + this(packetTag, false); + } + + ContainedPacket(int packetTag, boolean newPacketFormat) + { + super(packetTag, newPacketFormat); } public byte[] getEncoded() throws IOException { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - BCPGOutputStream pOut = new BCPGOutputStream(bOut); - - pOut.writePacket(this); + return getEncoded(PacketFormat.ROUNDTRIP); + } + public byte[] getEncoded(PacketFormat format) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, format); + pOut.writePacket(this); pOut.close(); - return bOut.toByteArray(); } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ECDHPublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/ECDHPublicBCPGKey.java index 65f408d8e3..807459052a 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ECDHPublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ECDHPublicBCPGKey.java @@ -7,7 +7,17 @@ import org.bouncycastle.math.ec.ECPoint; /** - * base class for an ECDH Public Key. + * Base class for an ECDH Public Key. + * This type is for use with {@link PublicKeyAlgorithmTags#ECDH}. + * The specific curve is identified by providing an OID. + * Regarding X25519, X448, consider the following: + * Modern implementations use dedicated key types {@link X25519PublicBCPGKey}, {@link X448PublicBCPGKey} along with + * dedicated algorithm tags {@link PublicKeyAlgorithmTags#X25519}, {@link PublicKeyAlgorithmTags#X448}. + * If you want to be compatible with legacy applications however, you should use this class instead. + * Note though, that for v6 keys, {@link X25519PublicBCPGKey} or {@link X448PublicBCPGKey} MUST be used for X25519, X448. + * + * @see + * OpenPGP - Algorithm-Specific Parts for ECDH Keys */ public class ECDHPublicBCPGKey extends ECPublicBCPGKey diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ECDSAPublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/ECDSAPublicBCPGKey.java index cf0965185a..a29bdb0aa7 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ECDSAPublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ECDSAPublicBCPGKey.java @@ -7,7 +7,11 @@ import org.bouncycastle.math.ec.ECPoint; /** - * base class for an ECDSA Public Key. + * Base class for an ECDSA Public Key. + * This type is used with {@link PublicKeyAlgorithmTags#ECDSA} and the curve is identified by providing an OID. + * + * @see + * OpenPGP - Algorithm-Specific Parts for ECDSA Keys */ public class ECDSAPublicBCPGKey extends ECPublicBCPGKey diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ECPublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/ECPublicBCPGKey.java index 38e1b0e4a9..b0631e3766 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ECPublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ECPublicBCPGKey.java @@ -8,7 +8,8 @@ import org.bouncycastle.math.ec.ECPoint; /** - * base class for an EC Public Key. + * Base class for an EC Public Key. + * For subclasses, see {@link ECDHPublicBCPGKey}, {@link ECDSAPublicBCPGKey} or {@link EdDSAPublicBCPGKey}. */ public abstract class ECPublicBCPGKey extends BCPGObject diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ECSecretBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/ECSecretBCPGKey.java index c595fa4b5f..b92c9c7c69 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ECSecretBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ECSecretBCPGKey.java @@ -4,7 +4,24 @@ import java.math.BigInteger; /** - * base class for an EC Secret Key. + * Base class for an EC Secret Key. + * This type is for use with {@link PublicKeyAlgorithmTags#ECDH} or {@link PublicKeyAlgorithmTags#ECDSA}. + * The specific curve is identified by providing an OID. + * Regarding X25519, X448, consider the following: + * ECDH keys using curve448 are unspecified. + * ECDH secret keys using curve25519 use big-endian MPI encoding, contrary to {@link X25519SecretBCPGKey} which uses + * native encoding. + * Modern implementations use dedicated key types {@link X25519SecretBCPGKey}, {@link X448SecretBCPGKey} along with + * dedicated algorithm tags {@link PublicKeyAlgorithmTags#X25519}, {@link PublicKeyAlgorithmTags#X448}. + * If you want to be compatible with legacy applications however, you should use this class instead. + * Note though, that for v6 keys, {@link X25519SecretBCPGKey} or {@link X448SecretBCPGKey} MUST be used for X25519, X448. + * + * @see + * OpenPGP - Algorithm-Specific Parts for ECDH Keys + * @see + * OpenPGP - Algorithm-Specific Parts for ECDSA Keys + * @see + * OpenPGP - Curve25519Legacy ECDH Secret Key Material (deprecated) */ public class ECSecretBCPGKey extends BCPGObject diff --git a/pg/src/main/java/org/bouncycastle/bcpg/Ed25519PublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/Ed25519PublicBCPGKey.java index e85d3a8377..b107b8c7c0 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/Ed25519PublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/Ed25519PublicBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Public key of type {@link PublicKeyAlgorithmTags#Ed25519}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link EdDSAPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#EDDSA_LEGACY}. + * + * @see + * OpenPGP - Algorithm-Specific Part for Ed25519 Keys + */ public class Ed25519PublicBCPGKey extends OctetArrayBCPGKey { + // 32 octets of the native public key public static final int LENGTH = 32; public Ed25519PublicBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/Ed25519SecretBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/Ed25519SecretBCPGKey.java index 386ed6e348..2c306fb2c6 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/Ed25519SecretBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/Ed25519SecretBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Secret key of type {@link PublicKeyAlgorithmTags#Ed25519}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link EdDSAPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#EDDSA_LEGACY}. + * + * @see + * OpenPGP - Algorithm-Specific Part for Ed25519 Keys + */ public class Ed25519SecretBCPGKey extends OctetArrayBCPGKey { + // 32 octets of the native secret key public static final int LENGTH = 32; public Ed25519SecretBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/Ed448PublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/Ed448PublicBCPGKey.java index 93b0021a34..a7103b80d2 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/Ed448PublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/Ed448PublicBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Public key of type {@link PublicKeyAlgorithmTags#Ed448}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link EdDSAPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#EDDSA_LEGACY}. + * + * @see + * OpenPGP - Algorithm-Specific Part for Ed448 Keys + */ public class Ed448PublicBCPGKey extends OctetArrayBCPGKey { + // 57 octets of the native public key public static final int LENGTH = 57; public Ed448PublicBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/Ed448SecretBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/Ed448SecretBCPGKey.java index ee5ba7c949..824db6afd5 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/Ed448SecretBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/Ed448SecretBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Secret key of type {@link PublicKeyAlgorithmTags#Ed448}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link EdDSAPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#EDDSA_LEGACY}. + * + * @see + * OpenPGP - Algorithm-Specific Part for Ed448 Keys + */ public class Ed448SecretBCPGKey extends OctetArrayBCPGKey { + // 57 octets of the native secret key public static final int LENGTH = 57; public Ed448SecretBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/EdDSAPublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/EdDSAPublicBCPGKey.java index 32767ba152..d6d95e4a96 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/EdDSAPublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/EdDSAPublicBCPGKey.java @@ -7,7 +7,14 @@ import org.bouncycastle.math.ec.ECPoint; /** - * base class for an EdDSA Public Key. + * Base class for an EdDSA Public Key. + * Here, the curve is identified by an OID and the key is MPI encoded. + * This class is used with {@link PublicKeyAlgorithmTags#EDDSA_LEGACY} only and MUST NOT be used with v6 keys. + * Modern OpenPGP uses dedicated key types: + * For {@link PublicKeyAlgorithmTags#Ed25519} see {@link Ed25519PublicBCPGKey} instead. + * For {@link PublicKeyAlgorithmTags#Ed448} see {@link Ed448PublicBCPGKey} instead. + * @see + * OpenPGP - Algorithm-Specific Parts for EdDSALegacy Keys (deprecated) */ public class EdDSAPublicBCPGKey extends ECPublicBCPGKey diff --git a/pg/src/main/java/org/bouncycastle/bcpg/EdSecretBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/EdSecretBCPGKey.java index 084ce8cd16..70cdb6b2ce 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/EdSecretBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/EdSecretBCPGKey.java @@ -4,7 +4,14 @@ import java.math.BigInteger; /** - * base class for an Edwards Curve Secret Key. + * Base class for an Edwards Curve (EdDSA) Secret Key. + * This class is used with {@link PublicKeyAlgorithmTags#EDDSA_LEGACY} only and MUST NOT be used with v6 keys. + * Modern OpenPGP uses dedicated key types: + * For {@link PublicKeyAlgorithmTags#Ed25519} see {@link Ed25519SecretBCPGKey} instead. + * For {@link PublicKeyAlgorithmTags#Ed448} see {@link Ed448SecretBCPGKey} instead. + * + * @see + * OpenPGP - Algorithm-Specific Parts for EdDSALegacy Keys (deprecated) */ public class EdSecretBCPGKey extends BCPGObject diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ExperimentalPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/ExperimentalPacket.java index 927b1bade9..b787b02ba9 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ExperimentalPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ExperimentalPacket.java @@ -11,7 +11,20 @@ public class ExperimentalPacket extends ContainedPacket implements PublicKeyAlgorithmTags { private byte[] contents; - + + /** + * + * @param in + * @throws IOException + */ + ExperimentalPacket( + int tag, + BCPGInputStream in) + throws IOException + { + this(tag, in, false); + } + /** * * @param in @@ -19,10 +32,11 @@ public class ExperimentalPacket */ ExperimentalPacket( int tag, - BCPGInputStream in) + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(tag); + super(tag, newPacketFormat); this.contents = in.readAll(); } @@ -44,6 +58,6 @@ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(getPacketTag(), contents); + out.writePacket(hasNewPacketFormat(), getPacketTag(), contents); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/FingerprintUtil.java b/pg/src/main/java/org/bouncycastle/bcpg/FingerprintUtil.java new file mode 100644 index 0000000000..9e249b3983 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/FingerprintUtil.java @@ -0,0 +1,193 @@ +package org.bouncycastle.bcpg; + +import org.bouncycastle.util.Pack; +import org.bouncycastle.util.encoders.Hex; + +import java.util.Locale; + +public class FingerprintUtil +{ + + /** + * Derive a key-id from the given key fingerprint. + * This method can derive key-ids from v4, v5 (LibrePGP) and v6 keys. + * For keys with other versions (2,3) it will return 0. + * + * @param keyVersion version of the key + * @param fingerprint fingerprint of the key + * @return derived key-id + */ + public static long keyIdFromFingerprint(int keyVersion, byte[] fingerprint) + { + switch (keyVersion) + { + case PublicKeyPacket.VERSION_4: + return keyIdFromV4Fingerprint(fingerprint); + case PublicKeyPacket.LIBREPGP_5: + return keyIdFromLibrePgpFingerprint(fingerprint); + case PublicKeyPacket.VERSION_6: + return keyIdFromV6Fingerprint(fingerprint); + default: + return 0; + } + } + + /** + * Derive a 64 bit key-id from a version 6 OpenPGP fingerprint. + * For v6 keys, the key-id corresponds to the left-most 8 octets of the fingerprint. + * + * @param v6Fingerprint 32 byte fingerprint + * @return key-id + */ + public static long keyIdFromV6Fingerprint(byte[] v6Fingerprint) + { + return longFromLeftMostBytes(v6Fingerprint); + } + + /** + * Derive a 64 bit key-id from a version 5 LibrePGP fingerprint. + * For such keys, the key-id corresponds to the left-most 8 octets of the fingerprint. + * + * @param v5Fingerprint 32 byte fingerprint + * @return key-id + */ + public static long keyIdFromLibrePgpFingerprint(byte[] v5Fingerprint) + { + return longFromLeftMostBytes(v5Fingerprint); + } + + /** + * Derive a 64 bit key-id from a version 4 OpenPGP fingerprint. + * For v4 keys, the key-id corresponds to the right-most 8 octets of the fingerprint. + * + * @param v4Fingerprint 20 byte fingerprint + * @return key-id + */ + public static long keyIdFromV4Fingerprint(byte[] v4Fingerprint) + { + return longFromRightMostBytes(v4Fingerprint); + } + + /** + * Convert the left-most 8 bytes from the given array to a long. + * + * @param bytes bytes + * @return long + */ + public static long longFromLeftMostBytes(byte[] bytes) + { + return readKeyID(bytes); + } + + /** + * Convert the right-most 8 bytes from the given array to a long. + * + * @param bytes bytes + * @return long + */ + public static long longFromRightMostBytes(byte[] bytes) + { + return readKeyID(bytes, bytes.length - 8); + } + + /** + * Read a key-ID from the first 8 octets of the given byte array. + * @param bytes byte array + * @return key-ID + */ + public static long readKeyID(byte[] bytes) + { + return readKeyID(bytes, 0); + } + + /** + * Read a key-ID from 8 octets of the given byte array starting at offset. + * @param bytes byte array + * @param offset offset + * @return key-ID + */ + public static long readKeyID(byte[] bytes, int offset) + { + if (bytes.length < 8) + { + throw new IllegalArgumentException("Byte array MUST contain at least 8 bytes"); + } + return Pack.bigEndianToLong(bytes, offset); + } + + /** + * Write the key-ID encoded as 8 octets to the given byte array, starting at index offset. + * @param keyID keyID + * @param bytes byte array + * @param offset starting offset + */ + public static void writeKeyID(long keyID, byte[] bytes, int offset) + { + if (bytes.length - offset < 8) + { + throw new IllegalArgumentException("Not enough space to write key-ID to byte array."); + } + Pack.longToBigEndian(keyID, bytes, offset); + } + + /** + * Write the key-ID to the first 8 octets of the given byte array. + * @param keyID keyID + * @param bytes byte array + */ + public static void writeKeyID(long keyID, byte[] bytes) + { + writeKeyID(keyID, bytes, 0); + } + + public static String prettifyFingerprint(byte[] fingerprint) + { + // -DM Hex.toHexString + char[] hex = Hex.toHexString(fingerprint).toUpperCase(Locale.getDefault()).toCharArray(); + StringBuilder sb = new StringBuilder(); + switch (hex.length) + { + case 32: + // v3 keys + for (int i = 0; i < 4; i++) + { + sb.append(hex, i * 4, 4).append(' '); + } + sb.append(' '); + for (int i = 4; i < 7; i++) + { + sb.append(hex, i * 4, 4).append(' '); + } + sb.append(hex, 28, 4); + return sb.toString(); + case 40: + // v4 keys + for (int i = 0; i <= 4; i++) + { + sb.append(hex, i * 4, 4).append(' '); + } + sb.append(' '); + for (int i = 5; i <= 8; i++) + { + sb.append(hex, i * 4, 4).append(' '); + } + sb.append(hex, 36, 4); + return sb.toString(); + case 64: + // v5, v6 keys + for (int i = 0; i < 4; i++) + { + sb.append(hex, i * 8, 8).append(' '); + } + sb.append(' '); + for (int i = 4; i < 7; i++) + { + sb.append(hex, i * 8, 8).append(' '); + } + sb.append(hex, 56, 8); + return sb.toString(); + default: + return new String(hex); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/HashAlgorithmTags.java b/pg/src/main/java/org/bouncycastle/bcpg/HashAlgorithmTags.java index eb0a114344..a908b41f54 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/HashAlgorithmTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/HashAlgorithmTags.java @@ -1,32 +1,113 @@ package org.bouncycastle.bcpg; /** - * basic tags for hash algorithms + * Basic tags for hash algorithms. + * + * @see + * RFC4880 - Hash Algorithms + * @see + * RFC9580 - Hash Algorithms + * @see + * LibrePGP - Hash Algorithms */ public interface HashAlgorithmTags { - int MD5 = 1; // MD5 - int SHA1 = 2; // SHA-1 - int RIPEMD160 = 3; // RIPE-MD/160 - int DOUBLE_SHA = 4; // Reserved for double-width SHA (experimental) - int MD2 = 5; // MD2 - int TIGER_192 = 6; // Reserved for TIGER/192 - int HAVAL_5_160 = 7; // Reserved for HAVAL (5 pass, 160-bit) - - int SHA256 = 8; // SHA-256 - int SHA384 = 9; // SHA-384 - int SHA512 = 10; // SHA-512 - int SHA224 = 11; // SHA-224 - int SHA3_256 = 12; // SHA3-256 - int SHA3_512 = 14; // SHA3-512 + /** + * MD5. + * Implementations MUST NOT use this to generate signatures. + * Implementations MUST NOT use this as a hash function in ECDH KDFs. + * Implementations MUST NOT generate packets with this hash function in an S2K KDF. + * Implementations MUST NOT use this hash function in an S2K KDF to decrypt v6+ packets. + */ + int MD5 = 1; + /** + * SHA-1. + * Implementations MUST NOT use this to generate signatures. + * Implementations MUST NOT use this as a hash function in ECDH KDFs. + * Implementations MUST NOT generate packets with this hash function in an S2K KDF. + * Implementations MUST NOT use this hash function in an S2K KDF to decrypt v6+ packets. + */ + int SHA1 = 2; + /** + * RIPEMD-160. + * Implementations MUST NOT use this to generate signatures. + * Implementations MUST NOT use this as a hash function in ECDH KDFs. + * Implementations MUST NOT generate packets with this hash function in an S2K KDF. + * Implementations MUST NOT use this hash function in an S2K KDF to decrypt v6+ packets. + */ + int RIPEMD160 = 3; + /** + * Reserved for double-width SHA (experimental). + */ + int DOUBLE_SHA = 4; + /** + * Reserved for MD2. + */ + int MD2 = 5; + /** + * Reserved for TIGER/192. + */ + int TIGER_192 = 6; + /** + * Reserved for HAVAL (5 pass, 160-bit). + */ + int HAVAL_5_160 = 7; + /** + * SHA2-256. + * Compliant implementations MUST implement. + */ + int SHA256 = 8; + /** + * SHA2-384. + */ + int SHA384 = 9; + /** + * SHA2-512. + */ + int SHA512 = 10; + /** + * SHA2-224. + */ + int SHA224 = 11; + /** + * SHA3-256. + */ + int SHA3_256 = 12; + /** + * SHA3-512. + */ + int SHA3_512 = 14; + /** + * Reserved for MD4. + * @deprecated non-standard + */ int MD4 = 301; - int SHA3_224 = 312; // SHA3-224 - int SHA3_256_OLD = 313; //SHA3-256 - int SHA3_384 = 314; // SHA3-384 - int SHA3_512_OLD = 315; // SHA3-512 + /** + * Reserved for SHA3-224. + * @deprecated non-standard + */ + int SHA3_224 = 312; + /** + * Reserved for SHA3-256. + * @deprecated non-standard + */ + int SHA3_256_OLD = 313; + /** + * Reserved for SHA3-384. + * @deprecated non-standard + */ + int SHA3_384 = 314; + /** + * Reserved for SHA3-512. + * @deprecated non-standard + */ + int SHA3_512_OLD = 315; - - int SM3 = 326; // SM3 + /** + * Reserved for SM3. + * @deprecated non-standard + */ + int SM3 = 326; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java b/pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java new file mode 100644 index 0000000000..07f78b72c0 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/HashUtils.java @@ -0,0 +1,53 @@ +package org.bouncycastle.bcpg; + +public class HashUtils +{ + + /** + * Return the length of the salt per hash algorithm, used in OpenPGP v6 signatures. + * + * @see + * OpenPGP - Salt Size declarations + * @param hashAlgorithm hash algorithm tag + * @return size of the salt for the given hash algorithm in bytes + */ + public static int getV6SignatureSaltSizeInBytes(int hashAlgorithm) + { + switch (hashAlgorithm) + { + case HashAlgorithmTags.SHA256: + case HashAlgorithmTags.SHA224: + case HashAlgorithmTags.SHA3_256: + case HashAlgorithmTags.SHA3_256_OLD: + return 16; + case HashAlgorithmTags.SHA384: + return 24; + case HashAlgorithmTags.SHA512: + case HashAlgorithmTags.SHA3_512: + case HashAlgorithmTags.SHA3_512_OLD: + return 32; + default: + throw new IllegalArgumentException("Salt size not specified for Hash Algorithm with ID " + hashAlgorithm); + } + } + + /** + * Return true, if the encountered saltLength matches the value the specification gives for the hashAlgorithm. + * + * @param hashAlgorithm hash algorithm tag + * @param saltSize encountered salt size + * @return true if the encountered size matches the spec + * @implNote LibrePGP allows for zero-length signature salt values, so this method only works for IETF OpenPGP v6. + */ + public boolean saltSizeMatchesSpec(int hashAlgorithm, int saltSize) + { + try + { + return saltSize == getV6SignatureSaltSizeInBytes(hashAlgorithm); + } + catch (IllegalArgumentException e) // Unknown algorithm or salt size is not specified for the hash algo + { + return false; + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/InputStreamPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/InputStreamPacket.java index f042703be2..2dfb9b87af 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/InputStreamPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/InputStreamPacket.java @@ -22,8 +22,15 @@ public InputStreamPacket( BCPGInputStream in, int packetTag) { - super(packetTag); - + this(in, packetTag, false); + } + + InputStreamPacket( + BCPGInputStream in, + int packetTag, + boolean newPacketFormat) + { + super(packetTag, newPacketFormat); this.in = in; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/KeyIdentifier.java b/pg/src/main/java/org/bouncycastle/bcpg/KeyIdentifier.java new file mode 100644 index 0000000000..9398792c2a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/KeyIdentifier.java @@ -0,0 +1,288 @@ +package org.bouncycastle.bcpg; + +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; + +/** + * Utility class for matching key-ids / fingerprints. + * A {@link KeyIdentifier} can be created from either a 64-bit key-id, a fingerprint, or both. + * This class was created to enable a seamless transition from use of key-ids in the API + * towards identifying keys via fingerprints. + */ +public class KeyIdentifier +{ + private final byte[] fingerprint; + private final long keyId; + + public KeyIdentifier(String hexEncoded) + { + this(Hex.decode(hexEncoded)); + } + + /** + * Create a new {@link KeyIdentifier} based on a keys fingerprint. + * For fingerprints matching the format of a v4, v5 or v6 key, the constructor will + * try to derive the corresponding key-id from the fingerprint. + * + * @param fingerprint fingerprint + */ + public KeyIdentifier(byte[] fingerprint) + { + // Long KeyID + if (fingerprint.length == 8) + { + keyId = FingerprintUtil.longFromRightMostBytes(fingerprint); + this.fingerprint = null; + return; + } + + this.fingerprint = Arrays.clone(fingerprint); + + // v4 + if (fingerprint.length == 20) + { + keyId = FingerprintUtil.keyIdFromV4Fingerprint(fingerprint); + } + // v5, v6 + else if (fingerprint.length == 32) + { + keyId = FingerprintUtil.keyIdFromV6Fingerprint(fingerprint); + } + else + { + keyId = 0L; + } + } + + /** + * Create a {@link KeyIdentifier} based on the given fingerprint and key-id. + * + * @param fingerprint fingerprint + * @param keyId key-id + */ + public KeyIdentifier(byte[] fingerprint, long keyId) + { + this.fingerprint = Arrays.clone(fingerprint); + this.keyId = keyId; + } + + /** + * Create a {@link KeyIdentifier} based on the given key-id. + * {@code fingerprint} will be set to {@code null}. + * + * @param keyId key-id + */ + public KeyIdentifier(long keyId) + { + if (keyId == 0L) + { + this.keyId = 0L; + this.fingerprint = new byte[0]; + } + else + { + this.keyId = keyId; + this.fingerprint = null; + } + } + + /** + * Create a wildcard {@link KeyIdentifier}. + */ + private KeyIdentifier() + { + this(0L); + } + + /** + * Create a wildcard {@link KeyIdentifier}. + * + * @return wildcard key identifier + */ + public static KeyIdentifier wildcard() + { + return new KeyIdentifier(); + } + + /** + * Return the fingerprint of the {@link KeyIdentifier}. + * {@code fingerprint} might be null, if the {@link KeyIdentifier} was created from just a key-id. + * If {@link #isWildcard()} returns true, this method returns an empty, but non-null array. + * + * @return fingerprint + */ + public byte[] getFingerprint() + { + return Arrays.clone(fingerprint); + } + + /** + * Return the key-id of the {@link KeyIdentifier}. + * This might be {@code 0L} if {@link #isWildcard()} returns true, or if an unknown + * fingerprint was passed in. + * + * @return key-id + */ + public long getKeyId() + { + return keyId; + } + + /** + * Returns true, if the {@link KeyIdentifier} specifies a wildcard (matches anything). + * This is for example used with anonymous recipient key-ids / fingerprints, where the recipient + * needs to try all available keys to decrypt the message. + * + * @return is wildcard + */ + public boolean isWildcard() + { + return keyId == 0L && (fingerprint == null || fingerprint.length == 0); + } + + /** + * Return true if the KeyIdentifier has a fingerprint corresponding to the passed in one. + * + * @param fingerprint the fingerprint to match against. + * @return true if there's a match, false otherwise. + */ + public boolean hasFingerprint(byte[] fingerprint) + { + return Arrays.constantTimeAreEqual(this.fingerprint, fingerprint); + } + + /** + * Return true, if this {@link KeyIdentifier} matches the given other {@link KeyIdentifier}. + * This will return true if the fingerprint matches, or if the key-id matches, + * or if {@link #isWildcard()} returns true. + * + * @param other the identifier we are matching against. + * @return true if we match other, false otherwise. + */ + public boolean matches(KeyIdentifier other) + { + if (isWildcard() || other.isWildcard()) + { + return true; + } + + return matchesExplicit(other); + } + + public boolean matchesExplicit(KeyIdentifier other) + { + if (fingerprint != null && other.fingerprint != null) + { + return Arrays.constantTimeAreEqual(fingerprint, other.fingerprint); + } + else + { + return keyId == other.keyId; + } + } + + public static boolean matches(List identifiers, KeyIdentifier identifier, boolean explicit) + { + for (Iterator it = identifiers.iterator(); it.hasNext();) + { + KeyIdentifier candidate = (KeyIdentifier)it.next(); + + if (!explicit && candidate.isWildcard()) + { + return true; + } + + if (candidate.getFingerprint() != null && + Arrays.constantTimeAreEqual(candidate.getFingerprint(), identifier.getFingerprint())) + { + return true; + } + + return candidate.getKeyId() == identifier.getKeyId(); + } + return false; + } + + /** + * Return true, if this {@link KeyIdentifier} is present in the given list of {@link KeyIdentifier} . + * This will return true if a fingerprint matches, or if a key-id matches, + * or if {@link #isWildcard()} returns true. + * + * @param others the list of key identifiers to check. + * @return true, if the identifier is present in the list, false otherwise. + */ + public boolean isPresentIn(List others) + { + for (Iterator it = others.iterator(); it.hasNext();) + { + if (this.matchesExplicit((KeyIdentifier)it.next())) + { + return true; + } + } + + return false; + } + + @Override + public boolean equals(Object obj) + { + if (obj == null) + { + return false; + } + if (this == obj) + { + return true; + } + if (!(obj instanceof KeyIdentifier)) + { + return false; + } + KeyIdentifier other = (KeyIdentifier) obj; + if (getFingerprint() != null && other.getFingerprint() != null) + { + return Arrays.constantTimeAreEqual(getFingerprint(), other.getFingerprint()); + } + return getKeyId() == other.getKeyId(); + } + + @Override + public int hashCode() + { + return (int) getKeyId(); + } + + public String toString() + { + if (isWildcard()) + { + return "*"; + } + + if (fingerprint == null) + { + return "" + keyId; + } + + // -DM Hex.toHexString + return Hex.toHexString(fingerprint).toUpperCase(Locale.getDefault()); + } + + public String toPrettyPrint() + { + if (isWildcard()) + { + return "*"; + } + if (fingerprint == null) + { + return "0x" + Long.toHexString(keyId).toUpperCase(Locale.getDefault()); + } + return FingerprintUtil.prettifyFingerprint(fingerprint); + } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/LiteralDataPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/LiteralDataPacket.java index 16e64c377b..2b1a196a51 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/LiteralDataPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/LiteralDataPacket.java @@ -16,10 +16,18 @@ public class LiteralDataPacket long modDate; LiteralDataPacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + LiteralDataPacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(in, LITERAL_DATA); + super(in, LITERAL_DATA, newPacketFormat); format = in.read(); int l = in.read(); @@ -35,7 +43,7 @@ public class LiteralDataPacket fileName[i] = (byte)ch; } - modDate = ((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); + modDate = StreamUtil.readTime(in); if (modDate < 0) { throw new IOException("literal data truncated in header"); @@ -55,7 +63,7 @@ public int getFormat() */ public long getModificationTime() { - return modDate * 1000L; + return modDate; } /** diff --git a/pg/src/main/java/org/bouncycastle/bcpg/MPInteger.java b/pg/src/main/java/org/bouncycastle/bcpg/MPInteger.java index df54d6c15f..286ab2ab34 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/MPInteger.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/MPInteger.java @@ -15,7 +15,7 @@ public MPInteger( BCPGInputStream in) throws IOException { - int length = (in.read() << 8) | in.read(); + int length = StreamUtil.read2OctetLength(in); byte[] bytes = new byte[(length + 7) / 8]; in.readFully(bytes); @@ -43,11 +43,8 @@ public void encode( BCPGOutputStream out) throws IOException { - int length = value.bitLength(); - - out.write(length >> 8); - out.write(length); - + StreamUtil.write2OctetLength(out, value.bitLength()); + byte[] bytes = value.toByteArray(); if (bytes[0] == 0) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/MarkerPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/MarkerPacket.java index 2f4a8da428..dad7658e3f 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/MarkerPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/MarkerPacket.java @@ -13,10 +13,18 @@ public class MarkerPacket byte[] marker = {(byte)0x50, (byte)0x47, (byte)0x50}; public MarkerPacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + public MarkerPacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(MARKER); + super(MARKER, newPacketFormat); in.readFully(marker); } @@ -25,6 +33,6 @@ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(MARKER, marker); + out.writePacket(hasNewPacketFormat(), MARKER, marker); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ModDetectionCodePacket.java b/pg/src/main/java/org/bouncycastle/bcpg/ModDetectionCodePacket.java index 7e837b510f..2fcef653da 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ModDetectionCodePacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ModDetectionCodePacket.java @@ -9,12 +9,20 @@ public class ModDetectionCodePacket extends ContainedPacket { private byte[] digest; - + ModDetectionCodePacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + ModDetectionCodePacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(MOD_DETECTION_CODE); + super(MOD_DETECTION_CODE, newPacketFormat); this.digest = new byte[20]; in.readFully(this.digest); @@ -44,6 +52,6 @@ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(MOD_DETECTION_CODE, digest, false); + out.writePacket(hasNewPacketFormat(), MOD_DETECTION_CODE, digest); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java b/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java index 666fb22465..474aab849e 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java @@ -1,44 +1,112 @@ package org.bouncycastle.bcpg; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.io.Streams; + import java.io.ByteArrayOutputStream; import java.io.IOException; /** - * generic signature object + * One-Pass-Signature packet. + * OPS packets are used to enable verification of signed messages in one-pass by providing necessary metadata + * about the signed data up front, so the consumer can start processing the signed data without needing + * to process the signature packet at the end of the data stream first. + * + * There are two versions of this packet currently defined. + * Version 3 OPS packets are used with {@link SignaturePacket SignaturePackets} of version 3 and 4. + * Version 6 OPS packets are used with {@link SignaturePacket SignaturePackets} of version 6. + * It is not clear to me, which version of the OPS packet is intended to be used with version 5 signatures. + * + * @see + * Definition of version 3 OPS packets in RFC4880 + * @see + * Definition of version 3 and 6 OPS packets in RFC9580 + * @see + * Definition of version 3 and 6 OPS packets in librepgp */ public class OnePassSignaturePacket extends ContainedPacket { - private int version; - private int sigType; - private int hashAlgorithm; - private int keyAlgorithm; - private long keyID; - private int isContaining; - + public static final int VERSION_3 = 3; + public static final int VERSION_6 = 6; + + private final int version; + private final int sigType; + private final int hashAlgorithm; + private final int keyAlgorithm; + private final long keyID; + private final byte[] fingerprint; + private final byte[] salt; + private final int isContaining; + + /** + * Parse a {@link OnePassSignaturePacket} from an OpenPGP packet input stream. + * @param in OpenPGP packet input stream + * @throws IOException when the end of stream is prematurely reached, or when the packet is malformed + */ OnePassSignaturePacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + OnePassSignaturePacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(ONE_PASS_SIGNATURE); + super(ONE_PASS_SIGNATURE, newPacketFormat); version = in.read(); sigType = in.read(); hashAlgorithm = in.read(); keyAlgorithm = in.read(); - - keyID |= (long)in.read() << 56; - keyID |= (long)in.read() << 48; - keyID |= (long)in.read() << 40; - keyID |= (long)in.read() << 32; - keyID |= (long)in.read() << 24; - keyID |= (long)in.read() << 16; - keyID |= (long)in.read() << 8; - keyID |= in.read(); - + + if (version == VERSION_3) + { + keyID = StreamUtil.readKeyID(in); + fingerprint = null; + salt = null; + } + else if (version == VERSION_6) + { + int saltLen = in.read(); + if (saltLen < 0) + { + throw new IOException("Version 6 OPS packet has invalid salt length."); + } + salt = new byte[saltLen]; + in.readFully(salt); + + fingerprint = new byte[32]; + in.readFully(fingerprint); + + keyID = FingerprintUtil.keyIdFromV6Fingerprint(fingerprint); + } + else + { + Streams.drain(in); + throw new UnsupportedPacketVersionException("Unsupported OnePassSignature packet version encountered: " + version); + } + isContaining = in.read(); } - + + /** + * Create a version 3 {@link OnePassSignaturePacket}. + * Version 3 OPS packets are used with version 3 and version 4 {@link SignaturePacket SignaturePackets}. + * + * To create an OPS packet for use with a version 6 {@link SignaturePacket}, + * see {@link OnePassSignaturePacket#OnePassSignaturePacket(int, int, int, byte[], byte[], boolean)}. + * + * @param sigType signature type + * @param hashAlgorithm hash algorithm tag + * @param keyAlgorithm public key algorithm tag + * @param keyID id of the signing key + * @param isNested if false, there is another OPS packet after this one, which applies to the same data. + * it true, the corresponding signature is calculated also over succeeding additional OPS packets. + */ public OnePassSignaturePacket( int sigType, int hashAlgorithm, @@ -48,14 +116,56 @@ public OnePassSignaturePacket( { super(ONE_PASS_SIGNATURE); - this.version = 3; + this.version = VERSION_3; this.sigType = sigType; this.hashAlgorithm = hashAlgorithm; this.keyAlgorithm = keyAlgorithm; this.keyID = keyID; + this.fingerprint = null; + this.salt = null; this.isContaining = (isNested) ? 0 : 1; } - + + /** + * Create a version 6 {@link OnePassSignaturePacket}. + * + * @param sigType signature type + * @param hashAlgorithm hash algorithm tag + * @param keyAlgorithm public key algorithm tag + * @param salt random salt. The length of this array depends on the hash algorithm in use. + * @param fingerprint 32 octet fingerprint of the (v6) signing key + * @param isNested if false, there is another OPS packet after this one, which applies to the same data. + * it true, the corresponding signature is calculated also over succeeding additional OPS packets. + */ + public OnePassSignaturePacket( + int sigType, + int hashAlgorithm, + int keyAlgorithm, + byte[] salt, + byte[] fingerprint, + boolean isNested) + { + super(ONE_PASS_SIGNATURE); + + this.version = VERSION_6; + this.sigType = sigType; + this.hashAlgorithm = hashAlgorithm; + this.keyAlgorithm = keyAlgorithm; + this.salt = salt; + this.fingerprint = fingerprint; + this.isContaining = (isNested) ? 0 : 1; + keyID = FingerprintUtil.keyIdFromV6Fingerprint(fingerprint); + } + + /** + * Return the packet version. + * @return version + */ + public int getVersion() + { + return version; + } + /** * Return the signature type. * @return the signature type @@ -66,7 +176,8 @@ public int getSignatureType() } /** - * return the encryption algorithm tag + * Return the ID of the public key encryption algorithm. + * @return public key algorithm tag */ public int getKeyAlgorithm() { @@ -74,7 +185,8 @@ public int getKeyAlgorithm() } /** - * return the hashAlgorithm tag + * Return the algorithm ID of the hash algorithm. + * @return hash algorithm tag */ public int getHashAlgorithm() { @@ -82,16 +194,37 @@ public int getHashAlgorithm() } /** - * @return long + * Return the key-id of the signing key. + * @return key id */ public long getKeyID() { return keyID; } + /** + * Return the version 6 fingerprint of the issuer. + * Only for version 6 packets. + * @return 32 bytes issuer fingerprint + */ + public byte[] getFingerprint() + { + return Arrays.clone(fingerprint); + } + + /** + * Return the salt used in the signature. + * Only for version 6 packets. + * @return salt + */ + public byte[] getSalt() + { + return Arrays.clone(salt); + } + /** * Return true, if the signature contains any signatures that follow. - * An bracketing OPS is followed by additional OPS packets and is calculated over all the data between itself + * A bracketing OPS is followed by additional OPS packets and is calculated over all the data between itself * and its corresponding signature (it is an attestation for encapsulated signatures). * * @return true if encapsulating, false otherwise @@ -102,7 +235,9 @@ public boolean isContaining() } /** - * + * Encode the contents of this packet into the given packet output stream. + * + * @param out OpenPGP packet output stream */ public void encode( BCPGOutputStream out) @@ -116,13 +251,22 @@ public void encode( pOut.write(hashAlgorithm); pOut.write(keyAlgorithm); - StreamUtil.writeKeyID(pOut, keyID); + if (version == VERSION_3) + { + StreamUtil.writeKeyID(pOut, keyID); + } + else if (version == VERSION_6) + { + pOut.write(salt.length); + pOut.write(salt); + pOut.write(fingerprint); + } pOut.write(isContaining); pOut.close(); - out.writePacket(ONE_PASS_SIGNATURE, bOut.toByteArray()); + out.writePacket(hasNewPacketFormat(), ONE_PASS_SIGNATURE, bOut.toByteArray()); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/Packet.java b/pg/src/main/java/org/bouncycastle/bcpg/Packet.java index 3356c04650..8456713607 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/Packet.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/Packet.java @@ -6,6 +6,7 @@ public class Packet implements PacketTags { private final int packetTag; + private final boolean newPacketFormat; // for API compatibility public Packet() @@ -14,8 +15,14 @@ public Packet() } Packet(int packetTag) + { + this(packetTag, false); + } + + Packet(int packetTag, boolean newPacketFormat) { this.packetTag = packetTag; + this.newPacketFormat = newPacketFormat; } /** @@ -28,14 +35,25 @@ public final int getPacketTag() return packetTag; } + /** + * Return true, if this instance of a packet was encoded using the new packet format. + * If the packet was encoded using the old legacy format, return false instead. + * + * @return true if new packet format encoding is used + */ + public boolean hasNewPacketFormat() + { + return newPacketFormat; + } + /** * Returns whether the packet is to be considered critical for v6 implementations. * Packets with tags less or equal to 39 are critical. * Tags 40 to 59 are reserved for unassigned, non-critical packets. * Tags 60 to 63 are non-critical private or experimental packets. * - * @see - * Packet Tags + * @see + * OpenPGP - Packet Tags * @return true if the packet is critical, false otherwise. */ public boolean isCritical() diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PacketFormat.java b/pg/src/main/java/org/bouncycastle/bcpg/PacketFormat.java new file mode 100644 index 0000000000..0783cddbda --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/PacketFormat.java @@ -0,0 +1,26 @@ +package org.bouncycastle.bcpg; + +/** + * OpenPGP Packet Header Length Format. + * + * @see + * OpenPGP Packet Headers + */ +public enum PacketFormat +{ + /** + * Always use the old (legacy) packet format. + */ + LEGACY, + + /** + * Always use the current (new) packet format. + */ + CURRENT, + + /** + * Let the individual packet decide the format (see {@link Packet#hasNewPacketFormat()}). + * This allows to round-trip packets without changing the packet format. + */ + ROUNDTRIP +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PacketTags.java b/pg/src/main/java/org/bouncycastle/bcpg/PacketTags.java index 5c34dfdb0b..ad72d8699c 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/PacketTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/PacketTags.java @@ -3,31 +3,204 @@ /** * Basic PGP packet tag types. */ -public interface PacketTags +public interface PacketTags { - int RESERVED = 0 ; // Reserved - a packet tag must not have this value - int PUBLIC_KEY_ENC_SESSION = 1; // Public-Key Encrypted Session Key Packet - int SIGNATURE = 2; // Signature Packet - int SYMMETRIC_KEY_ENC_SESSION = 3; // Symmetric-Key Encrypted Session Key Packet - int ONE_PASS_SIGNATURE = 4 ; // One-Pass Signature Packet - int SECRET_KEY = 5; // Secret Key Packet - int PUBLIC_KEY = 6 ; // Public Key Packet - int SECRET_SUBKEY = 7; // Secret Subkey Packet - int COMPRESSED_DATA = 8; // Compressed Data Packet - int SYMMETRIC_KEY_ENC = 9; // Symmetrically Encrypted Data Packet - int MARKER = 10; // Marker Packet - int LITERAL_DATA = 11; // Literal Data Packet - int TRUST = 12; // Trust Packet - int USER_ID = 13; // User ID Packet - int PUBLIC_SUBKEY = 14; // Public Subkey Packet - int USER_ATTRIBUTE = 17; // User attribute - int SYM_ENC_INTEGRITY_PRO = 18; // Symmetric encrypted, integrity protected - int MOD_DETECTION_CODE = 19; // Modification detection code - int AEAD_ENC_DATA = 20; // AEAD Encrypted Data (seems deprecated) - int PADDING = 21; // Padding Packet - - int EXPERIMENTAL_1 = 60; // Private or Experimental Values - int EXPERIMENTAL_2 = 61; - int EXPERIMENTAL_3 = 62; - int EXPERIMENTAL_4 = 63; + int RESERVED = 0; // Reserved - a packet tag must not have this value + + /** + * Public-Key (Persistent-Key) Encrypted Session-Key Packet. + * Packet class: {@link PublicKeyEncSessionPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPPublicKeyEncryptedData} + * + * @see + * Public-Key Encrypted Session Key Packet + */ + int PUBLIC_KEY_ENC_SESSION = 1; // Public-Key Encrypted Session Key Packet + + /** + * Signature Packet. + * Packet class: {@link SignaturePacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPSignature} + * + * @see + * Signature Packet + */ + int SIGNATURE = 2; // Signature Packet + + /** + * Symmetric Key (String-to-Key) Encrypted Session-Key Packet. + * Packet class: {@link SymmetricKeyEncSessionPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPSymmetricKeyEncryptedData} + * + * @see + * Symmetric-Key Encrypted Session-Key Packet + */ + int SYMMETRIC_KEY_ENC_SESSION = 3; // Symmetric-Key Encrypted Session Key Packet + + /** + * One-Pass-Signature Packet. + * Packet class: {@link OnePassSignaturePacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPOnePassSignature}, + * {@link org.bouncycastle.openpgp.PGPOnePassSignatureList} + * + * @see + * One-Pass-Signature Packet + */ + int ONE_PASS_SIGNATURE = 4; // One-Pass Signature Packet + + /** + * (Primary) Secret-Key Packet. + * Packet class: {@link SecretKeyPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPSecretKey} + * + * @see + * Secret-Key Packet + */ + int SECRET_KEY = 5; // Secret Key Packet + + /** + * (Primary) Public-Key Packet. + * Packet class: {@link PublicKeyPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPPublicKey} + * + * @see + * Public-Key Packet + */ + int PUBLIC_KEY = 6; // Public Key Packet + + /** + * Secret-Subkey Packet. + * Packet class: {@link SecretSubkeyPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPSecretKey} + * + * @see + * Secret-Subkey Packet + */ + int SECRET_SUBKEY = 7; // Secret Subkey Packet + + /** + * Compressed-Data Packet. + * Packet class: {@link CompressedDataPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPCompressedData} + * + * @see + * Compressed Data Packet + */ + int COMPRESSED_DATA = 8; // Compressed Data Packet + + /** + * Symmetrically Encrypted Data Packet. + * Packet class: {@link SymmetricEncDataPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPSymmetricKeyEncryptedData} + * Note: This encrypted data packet in favor of {@link #SYM_ENC_INTEGRITY_PRO}. + * + * @see + * Symmetrically Encrypted Data Packet + */ + int SYMMETRIC_KEY_ENC = 9; // Symmetrically Encrypted Data Packet + + /** + * Marker Packet. + * Packet class: {@link MarkerPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPMarker} + * This packet is deprecated and MUST be ignored. + * + * @see + * Marker Packet + */ + int MARKER = 10; // Marker Packet + + /** + * Literal Data Packet. + * Packet class: {@link LiteralDataPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPLiteralData} + * + * @see + * Literal Data Packet + */ + int LITERAL_DATA = 11; // Literal Data Packet + + /** + * Trust Packet. + * Packet class: {@link TrustPacket} + * This class has no dedicated business logic implementation. + * + * @see + * Trust Packet + */ + int TRUST = 12; // Trust Packet + + /** + * User ID Packet. + * Packet class: {@link UserIDPacket} + * + * @see + * User ID Packet + */ + int USER_ID = 13; // User ID Packet + + /** + * Public-Subkey Packet. + * Packet class: {@link PublicSubkeyPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPPublicKey} + * + * @see + * Public-Subkey Packet + */ + int PUBLIC_SUBKEY = 14; // Public Subkey Packet + + /** + * User Attribute Packet. + * Packet class: {@link UserAttributePacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPUserAttributeSubpacketVector} + * + * @see + * User Attribute Packet + */ + int USER_ATTRIBUTE = 17; // User attribute + + /** + * Symmetrically Encrypted, Integrity-Protected Data Packet. + * Packet class: {@link SymmetricEncIntegrityPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPSymmetricKeyEncryptedData} + * + * @see + * Symmetrically Encrypted Integrity Protected Data Packet + */ + int SYM_ENC_INTEGRITY_PRO = 18; // Symmetric encrypted, integrity protected + + /** + * Modification Detection Code Packet. + * This is no longer a stand-alone packet and has been integrated into the {@link #SYM_ENC_INTEGRITY_PRO}. + * + * @see + * Terminology Changes + */ + int MOD_DETECTION_CODE = 19; // Modification detection code + + /** + * OCB Encrypted Data Packet (LibrePGP only). + * This packet is not used by the official OpenPGP standard. + * Packet class: {@link AEADEncDataPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPEncryptedData} + * + * @see + * OCB Encrypted Data Packet + */ + int AEAD_ENC_DATA = 20; // AEAD Encrypted Data (seems deprecated) + + /** + * Padding Packet. + * Packet class: {@link PaddingPacket} + * Business logic: {@link org.bouncycastle.openpgp.PGPPadding} + * + * @see + * Padding Packet + */ + int PADDING = 21; // Padding Packet + + int EXPERIMENTAL_1 = 60; // Private or Experimental Values + int EXPERIMENTAL_2 = 61; + int EXPERIMENTAL_3 = 62; + int EXPERIMENTAL_4 = 63; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PaddingPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/PaddingPacket.java index e50b863eaf..6f3c128bf7 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/PaddingPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/PaddingPacket.java @@ -12,16 +12,22 @@ public class PaddingPacket private final byte[] padding; public PaddingPacket(BCPGInputStream in) + throws IOException + { + this(in, true); + } + + public PaddingPacket(BCPGInputStream in, boolean newPacketFormat) throws IOException { - super(PADDING); + super(PADDING, newPacketFormat); padding = Streams.readAll(in); } public PaddingPacket(byte[] padding) { - super(PADDING); + super(PADDING, true); this.padding = padding; } @@ -33,6 +39,10 @@ public PaddingPacket(int octetLen, SecureRandom random) private static byte[] randomBytes(int octetCount, SecureRandom random) { + if (octetCount <= 0) + { + throw new IllegalArgumentException("Octet count MUST NOT be 0 nor negative."); + } byte[] bytes = new byte[octetCount]; random.nextBytes(bytes); return bytes; @@ -47,6 +57,6 @@ public byte[] getPadding() public void encode(BCPGOutputStream pOut) throws IOException { - pOut.writePacket(PacketTags.PADDING, padding); + pOut.writePacket(hasNewPacketFormat(), PacketTags.PADDING, padding); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyAlgorithmTags.java b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyAlgorithmTags.java index ed06f600f4..e4030e957a 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyAlgorithmTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyAlgorithmTags.java @@ -1,33 +1,101 @@ package org.bouncycastle.bcpg; /** - * Public Key Algorithm tag numbers + * Public Key Algorithm IDs. + * + * @see + * RFC9580 - Public-Key Algorithms + * @see + * RFC4880 - Public-Key Algorithms + * @see + * LibrePGP - Public-Key Algorithms */ public interface PublicKeyAlgorithmTags { + /** + * RSA encryption/signing algorithm. + */ int RSA_GENERAL = 1; // RSA (Encrypt or Sign) + /** + * Deprecated tag for encrypt-only RSA. + * MUST NOT be generated. + * @deprecated use {@link #RSA_GENERAL} instead. + */ int RSA_ENCRYPT = 2; // RSA Encrypt-Only + /** + * Deprecated tag for sign-only RSA. + * MUST NOT be generated. + * @deprecated use {@link #RSA_GENERAL} instead. + */ int RSA_SIGN = 3; // RSA Sign-Only + /** + * Encrypt-only ElGamal. + */ int ELGAMAL_ENCRYPT = 16; // Elgamal (Encrypt-Only), see [ELGAMAL] + /** + * DSA. + */ int DSA = 17; // DSA (Digital Signature Standard) /** - * @deprecated use ECDH + * Deprecated tag for ECDH. + * @deprecated use {@link #ECDH} instead. + */ + int EC = 18; // Misnamed constant + /** + * Elliptic curve Diffie-Hellman. + */ + int ECDH = 18; // Elliptic Curve Diffie-Hellman + /** + * Elliptic curve digital signing algorithm. + */ + int ECDSA = 19; // Elliptic Curve Digital Signing Algorithm + /** + * Reserved tag for sign+encrypt ElGamal. + * MUST NOT be generated. + * An implementation MUST NOT generate ElGamal signatures. + * @deprecated use {@link #ELGAMAL_ENCRYPT} instead. + */ + int ELGAMAL_GENERAL = 20; // Reserved Elgamal (Encrypt or Sign) + /** + * Reserved tag for IETF-style S/MIME Diffie-Hellman. */ - int EC = 18; // Reserved for Elliptic Curve - int ECDH = 18; // Reserved for Elliptic Curve (actual algorithm name) - int ECDSA = 19; // Reserved for ECDSA - int ELGAMAL_GENERAL = 20; // Elgamal (Encrypt or Sign) int DIFFIE_HELLMAN = 21; // Reserved for Diffie-Hellman (X9.42, as defined for IETF-S/MIME) /** - * @deprecated use Ed25519 or Ed448 + * Misnamed tag for legacy EdDSA. + * @deprecated use {@link #EDDSA_LEGACY} instead. + */ + int EDDSA = 22; // EdDSA - (internet draft, but appearing in use); misnamed constant + /** + * Legacy EdDSA (curve identified by OID). + * MUST NOT be used with v6 keys (use {@link #Ed25519}, {@link #Ed448} instead). */ - int EDDSA = 22; // EdDSA - (internet draft, but appearing in use) int EDDSA_LEGACY = 22; // new name for old EDDSA tag. - - int X25519 = 25; - int X448 = 26; - int Ed25519 = 27; - int Ed448 = 28; + /** + * Reserved tag for AEDH. + */ + int AEDH = 23; // Reserved + /** + * Reserved tag for AEDSA. + */ + int AEDSA = 24; // Reserved + /** + * X25519 encryption algorithm. + * RFC9580-compliant implementations MUST implement support for this. + */ + int X25519 = 25; // X25519 + /** + * X448 encryption algorithm. + */ + int X448 = 26; // X448 + /** + * Ed25519 signing algorithm. + * RFC9580-compliant implementations MUST implement support for this. + */ + int Ed25519 = 27; // new style Ed25519 + /** + * Ed448 signing algorithm. + */ + int Ed448 = 28; // new style Ed448 int EXPERIMENTAL_1 = 100; int EXPERIMENTAL_2 = 101; diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyEncSessionPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyEncSessionPacket.java index 072bcdfdeb..d7a6e4ec52 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyEncSessionPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyEncSessionPacket.java @@ -33,10 +33,18 @@ public class PublicKeyEncSessionPacket private byte[] keyFingerprint; // v6 PublicKeyEncSessionPacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + PublicKeyEncSessionPacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(PUBLIC_KEY_ENC_SESSION); + super(PUBLIC_KEY_ENC_SESSION, newPacketFormat); version = in.read(); @@ -52,12 +60,23 @@ else if (version == VERSION_6) // anon recipient keyVersion = 0; keyFingerprint = new byte[0]; + keyID = 0L; } else { keyVersion = in.read(); keyFingerprint = new byte[keyInfoLen - 1]; in.readFully(keyFingerprint); + // Derived key-ID from fingerprint + // TODO: Replace with getKeyIdentifier + if (keyVersion == PublicKeyPacket.VERSION_4) + { + keyID = FingerprintUtil.keyIdFromV4Fingerprint(keyFingerprint); + } + else + { + keyID = FingerprintUtil.keyIdFromV6Fingerprint(keyFingerprint); + } } } else @@ -257,9 +276,16 @@ public void encode( } else if (version == VERSION_6) { - pOut.write(keyFingerprint.length + 1); - pOut.write(keyVersion); - pOut.write(keyFingerprint); + if (keyFingerprint.length != 0) + { + pOut.write(keyFingerprint.length + 1); + pOut.write(keyVersion); + pOut.write(keyFingerprint); + } + else + { + pOut.write(0); + } } pOut.write(algorithm); @@ -271,6 +297,6 @@ else if (version == VERSION_6) pOut.close(); - out.writePacket(PUBLIC_KEY_ENC_SESSION, bOut.toByteArray()); + out.writePacket(hasNewPacketFormat(), PUBLIC_KEY_ENC_SESSION, bOut.toByteArray()); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyPacket.java index 0026365b9a..b8a4fa0b25 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyPacket.java @@ -4,53 +4,169 @@ import java.io.IOException; import java.util.Date; +import org.bouncycastle.util.Pack; + /** - * basic packet for a PGP public key + * Base class for OpenPGP public (primary) keys. + * The public key packet holds the public parameters of an OpenPGP key pair. + * An OpenPGP certificate (transferable public key) consists of one primary key and optionally multiple subkey packets. + * + * @see + * RFC4880 - Public-Key Packet + * @see + * RFC9580 - Public-Key Packet + * @see + * LibrePGP - Public-Key Packet */ public class PublicKeyPacket extends ContainedPacket implements PublicKeyAlgorithmTags { + /** + * OpenPGP v3 keys are deprecated. + * They can only be used with RSA. + * + * @see + * OpenPGP - Version 3 Public Keys + */ public static final int VERSION_3 = 3; + /** + * OpenPGP v4 keys are (at the time of writing) widely used, but are subject to some attacks. + * + * @see + * OpenPGP - Version 4 Public Keys + */ public static final int VERSION_4 = 4; + /** + * Non-Standard LibrePGP introduced v5, which is only supported by a subset of vendors. + */ + public static final int LIBREPGP_5 = 5; + /** + * OpenPGP v6 keys are newly introduced. + * + * @see + * OpenPGP - Version 6 Public Keys + */ public static final int VERSION_6 = 6; private int version; + // Creation time of the key stored as seconds since epoch private long time; private int validDays; private int algorithm; private BCPGKey key; + /** + * Parse a {@link PublicKeyPacket} from an OpenPGP {@link BCPGInputStream}. + * The packet format is remembered as {@link PacketFormat#LEGACY}. + * @param in packet input stream + * @throws IOException + */ + PublicKeyPacket( + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + /** + * Parse a {@link PublicKeyPacket} from an OpenPGP {@link BCPGInputStream}. + * If

      newPacketFormat
      is true, the packet format is remembered as {@link PacketFormat#CURRENT}, + * otherwise as {@link PacketFormat#LEGACY}. + * @param in packet input stream + * @param newPacketFormat new packet format + * @throws IOException + */ PublicKeyPacket( - BCPGInputStream in) + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - this(PUBLIC_KEY, in); + this(PUBLIC_KEY, in, newPacketFormat); + } + + /** + * Parse a {@link PublicKeyPacket} or {@link PublicSubkeyPacket} from an OpenPGP {@link BCPGInputStream}. + * If
      keyTag
      is {@link #PUBLIC_KEY}, the packet is a primary key. + * If instead it is {@link #PUBLIC_SUBKEY}, it is a subkey packet. + * The packet format is remembered as {@link PacketFormat#LEGACY}. + * @param keyTag packet type ID + * @param in packet input stream + * @throws IOException + */ + PublicKeyPacket( + int keyTag, + BCPGInputStream in) + throws IOException + { + this(keyTag, in, false); } + /** + * Parse a {@link PublicKeyPacket} or {@link PublicSubkeyPacket} from an OpenPGP {@link BCPGInputStream}. + * If
      keyTag
      is {@link #PUBLIC_KEY}, the packet is a primary key. + * If instead it is {@link #PUBLIC_SUBKEY}, it is a subkey packet. + * If
      newPacketFormat
      is true, the packet format is remembered as {@link PacketFormat#CURRENT}, + * otherwise as {@link PacketFormat#LEGACY}. + * @param keyTag packet type ID + * @param in packet input stream + * @param newPacketFormat packet format + * @throws IOException if the key packet cannot be parsed + * + * @see + * OpenPGP - Version 3 Public Keys + * @see + * OpenPGP - Version 4 Public Keys + * @see + * OpenPGP - Version 6 Public Keys + * @see + * LibrePGP - Public-Key Packet Formats + */ PublicKeyPacket( int keyTag, - BCPGInputStream in) + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(keyTag); + super(keyTag, newPacketFormat); version = in.read(); - time = ((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); + if (version < 2 || version > VERSION_6) + { + throw new UnsupportedPacketVersionException("Unsupported Public Key Packet version encountered: " + version); + } - if (version <= VERSION_3) + time = StreamUtil.read4OctetLength(in) & 0xFFFFFFFFL; + + if (version == 2 || version == VERSION_3) { - validDays = (in.read() << 8) | in.read(); + validDays = StreamUtil.read2OctetLength(in); } algorithm = (byte)in.read(); - if (version == VERSION_6) + long keyOctets = -1; + + if (version == LIBREPGP_5 || version == VERSION_6) { // TODO: Use keyOctets to be able to parse unknown keys - long keyOctets = ((long)in.read() << 24) | ((long)in.read() << 16) | ((long)in.read() << 8) | in.read(); + keyOctets = StreamUtil.read4OctetLength(in); } - switch (algorithm) + parseKey(in, algorithm, keyOctets); + } + + /** + * Parse algorithm-specific public key material. + * @param in input stream which read just up to the public key material + * @param algorithmId public key algorithm ID + * @param optLen optional: Length of the public key material. -1 if not present. + * @throws IOException if the pk material cannot be parsed + */ + private void parseKey(BCPGInputStream in, int algorithmId, long optLen) + throws IOException + { + + switch (algorithmId) { case RSA_ENCRYPT: case RSA_GENERAL: @@ -86,17 +202,25 @@ public class PublicKeyPacket key = new Ed448PublicBCPGKey(in); break; default: + if (version == VERSION_6 || version == LIBREPGP_5) + { + // with version 5 & 6, we can gracefully handle unknown key types, as the length is known. + key = new UnknownBCPGKey((int) optLen, in); + break; + } throw new IOException("unknown PGP public key algorithm encountered: " + algorithm); } } /** - * Construct version 4 public key packet. + * Construct version 4 public primary key packet. * - * @param algorithm - * @param time - * @param key + * @param algorithm public key algorithm id + * @param time creation time + * @param key key object + * @deprecated use versioned {@link #PublicKeyPacket(int, int, Date, BCPGKey)} instead */ + @Deprecated public PublicKeyPacket( int algorithm, Date time, @@ -105,15 +229,32 @@ public PublicKeyPacket( this(VERSION_4, algorithm, time, key); } + /** + * Construct an OpenPGP public primary key packet. + * @param version packet version + * @param algorithm public key algorithm id + * @param time creation time + * @param key key object + */ public PublicKeyPacket( int version, int algorithm, Date time, BCPGKey key) - { - this(PUBLIC_KEY, version, algorithm, time, key); - } + { + this(PUBLIC_KEY, version, algorithm, time, key); + } + /** + * Construct an OpenPGP public key packet. + * If
      keyTag
      is {@link #PUBLIC_KEY}, the packet is a primary key. + * If instead it is {@link #PUBLIC_SUBKEY}, it is a subkey packet. + * @param keyTag public key packet type ID + * @param version packet version + * @param algorithm public key algorithm id + * @param time creation time + * @param key key object + */ PublicKeyPacket(int keyTag, int version, int algorithm, Date time, BCPGKey key) { super(keyTag); @@ -124,32 +265,59 @@ public PublicKeyPacket( this.key = key; } - + /** + * Return the packet version. + * @return packet version + */ public int getVersion() { return version; } + /** + * Return the {@link PublicKeyAlgorithmTags algorithm id} of the public key. + * @return algorithm id + */ public int getAlgorithm() { return algorithm; } + /** + * Only for v3 keys - The time in days since the keys creation, during which the key is valid. + * + * @return v3 key validity period in days since creation. + * @deprecated v4 and v6 keys instead signal their expiration time via the + * {@link org.bouncycastle.bcpg.sig.KeyExpirationTime} signature subpacket. + */ public int getValidDays() { return validDays; } + /** + * Return the keys creation time. + * @return creation time of the key + */ public Date getTime() { return new Date(time * 1000); } + /** + * Return the key object. + * @return key + */ public BCPGKey getKey() { return key; } + /** + * Return the encoded packet contents without the packet frame. + * @return encoded packet contents + * @throws IOException + */ public byte[] getEncodedContents() throws IOException { @@ -158,23 +326,18 @@ public byte[] getEncodedContents() pOut.write(version); - StreamUtil.writeTime(pOut, time); + StreamUtil.writeSeconds(pOut, time); if (version <= VERSION_3) { - pOut.write((byte)(validDays >> 8)); - pOut.write((byte)validDays); + StreamUtil.write2OctetLength(pOut, validDays); } pOut.write(algorithm); - if (version == VERSION_6) + if (version == VERSION_6 || version == LIBREPGP_5) { - int keyOctets = key.getEncoded().length; - pOut.write(keyOctets >> 24); - pOut.write(keyOctets >> 16); - pOut.write(keyOctets >> 8); - pOut.write(keyOctets); + StreamUtil.write4OctetLength(pOut, key.getEncoded().length); } pOut.writeObject((BCPGObject)key); @@ -184,10 +347,38 @@ public byte[] getEncodedContents() return bOut.toByteArray(); } + /** + * Encode the packet to the OpenPGP {@link BCPGOutputStream}. + * If the {@link BCPGOutputStream} packet format is set to {@link PacketFormat#ROUNDTRIP}, the result + * of {@link #hasNewPacketFormat()} determines, which packet format is used to encode the packet. + * Otherwise, the {@link BCPGOutputStream} dictates which format to use. + * @param out packet output stream + * @throws IOException + */ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(getPacketTag(), getEncodedContents()); + out.writePacket(hasNewPacketFormat(), getPacketTag(), getEncodedContents()); + } + + public static long getKeyID(PublicKeyPacket publicPk, byte[] fingerprint) + { + if (publicPk.version <= PublicKeyPacket.VERSION_3) + { + RSAPublicBCPGKey rK = (RSAPublicBCPGKey)publicPk.key; + + return rK.getModulus().longValue(); + } + else if (publicPk.version == PublicKeyPacket.VERSION_4) + { + return Pack.bigEndianToLong(fingerprint, fingerprint.length - 8); + } + else if (publicPk.version == PublicKeyPacket.LIBREPGP_5 || publicPk.version == PublicKeyPacket.VERSION_6) + { + return Pack.bigEndianToLong(fingerprint, 0); + } + + return 0; } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyUtils.java b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyUtils.java new file mode 100644 index 0000000000..70213770a4 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyUtils.java @@ -0,0 +1,55 @@ +package org.bouncycastle.bcpg; + +/** + * Utility methods related to OpenPGP public key algorithms. + */ +public class PublicKeyUtils +{ + + /** + * Return true, if the public key algorithm that corresponds to the given ID is capable of signing. + * + * @param publicKeyAlgorithm public key algorithm id + * @return true if algorithm can sign + */ + public static boolean isSigningAlgorithm(int publicKeyAlgorithm) + { + switch (publicKeyAlgorithm) + { + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_SIGN: + case PublicKeyAlgorithmTags.DSA: + case PublicKeyAlgorithmTags.ECDSA: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + case PublicKeyAlgorithmTags.Ed25519: + case PublicKeyAlgorithmTags.Ed448: + return true; + default: + return false; + } + } + +// /** +// * Return true, if the public key algorithm that corresponds to the given ID is capable of encryption. +// * @param publicKeyAlgorithm public key algorithm id +// * @return true if algorithm can encrypt +// */ +// public static boolean isEncryptionAlgorithm(int publicKeyAlgorithm) +// { +// switch (publicKeyAlgorithm) +// { +// case PublicKeyAlgorithmTags.RSA_GENERAL: +// case PublicKeyAlgorithmTags.RSA_ENCRYPT: +// case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: +// case PublicKeyAlgorithmTags.ECDH: +// case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: +// case PublicKeyAlgorithmTags.DIFFIE_HELLMAN: +// case PublicKeyAlgorithmTags.X25519: +// case PublicKeyAlgorithmTags.X448: +// return true; +// default: +// return false; +// } +// } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/PublicSubkeyPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/PublicSubkeyPacket.java index ea02f07f59..4c93e8b2eb 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/PublicSubkeyPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/PublicSubkeyPacket.java @@ -9,11 +9,20 @@ public class PublicSubkeyPacket extends PublicKeyPacket { + + PublicSubkeyPacket( + BCPGInputStream in) + throws IOException + { + this(in, false); + } + PublicSubkeyPacket( - BCPGInputStream in) + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(PUBLIC_SUBKEY, in); + super(PUBLIC_SUBKEY, in, newPacketFormat); } /** @@ -22,7 +31,9 @@ public class PublicSubkeyPacket * @param algorithm * @param time * @param key + * @deprecated use versioned {@link #PublicSubkeyPacket(int, int, Date, BCPGKey)} instead */ + @Deprecated public PublicSubkeyPacket( int algorithm, Date time, diff --git a/pg/src/main/java/org/bouncycastle/bcpg/ReservedPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/ReservedPacket.java index cf2f597c2f..bc766b6864 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/ReservedPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/ReservedPacket.java @@ -5,6 +5,11 @@ public class ReservedPacket { public ReservedPacket(BCPGInputStream in) { - super(in, RESERVED); + this(in, false); + } + + public ReservedPacket(BCPGInputStream in, boolean newPacketFormat) + { + super(in, RESERVED, newPacketFormat); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/S2K.java b/pg/src/main/java/org/bouncycastle/bcpg/S2K.java index 0d2889c8d0..7d1461eaed 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/S2K.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/S2K.java @@ -10,13 +10,39 @@ /** * Parameter specifier for the PGP string-to-key password based key derivation function. - *

      - * In iterated mode, S2K takes a single byte iteration count specifier, which is converted to an - * actual iteration count using a formula that grows the iteration count exponentially as the byte - * value increases. - *

      - * e.g. 0x01 == 1088 iterations, and 0xFF == 65,011,712 iterations. - *

      + * There are different S2K modes: + *
        + *
      • + * In {@link #SIMPLE} mode, a single iteration of the hash algorithm is performed to derived a key + * from the given passphrase. + * This mode is deprecated and MUST NOT be generated. + *
      • + *
      • + * The {@link #SALTED} mode is like {@link #SIMPLE}, but uses an additional salt value. + * This mode is deprecated and MUST NOT be generated. + *
      • + *
      • + * In {@link #SALTED_AND_ITERATED} mode, S2K takes a single byte iteration count specifier, which is converted to an + * actual iteration count using a formula that grows the iteration count exponentially as the byte + * value increases. + * e.g. 0x01 == 1088 iterations, and 0xFF == 65,011,712 iterations. + *
      • + *
      • + * The {@link #SALTED_AND_ITERATED} mode uses both iteration and a salt value. + * This mode is recommended for applications that want to stay backwards compatible. + *
      • + *
      • + * The new {@link #ARGON_2} mode does key derivation using salted Argon2, which is a memory-hard hash algorithm. + * This mode is generally recommended over {@link #SALTED_AND_ITERATED}. + *
      • + *
      + * + * @see + * RFC4880 - String-to-Key (S2K) Specifiers + * @see + * RFC9580 - String-to-Key (S2K) Specifier + * @see + * LibrePGP - String-to-Key (S2K) Specifiers */ public class S2K extends BCPGObject @@ -54,14 +80,34 @@ public class S2K /** * Memory-hard, salted key generation using Argon2 hash algorithm. + * @see Argon2Params */ public static final int ARGON_2 = 4; + /** + * GNU S2K extension. + * @see GNUDummyParams + */ public static final int GNU_DUMMY_S2K = 101; + /** + * Do not store the secret part at all. + * @see GNUDummyParams + */ public static final int GNU_PROTECTION_MODE_NO_PRIVATE_KEY = 1; + + /** + * A stub to access smartcards. + * @see GNUDummyParams + */ public static final int GNU_PROTECTION_MODE_DIVERT_TO_CARD = 2; + /** + * The (GnuPG) internal representation of a private key. + * @see GNUDummyParams + */ + public static final int GNU_PROTECTION_MODE_INTERNAL = 3; + int type; int algorithm; byte[] iv; @@ -71,6 +117,12 @@ public class S2K int parallelism; int memorySizeExponent; + /** + * Parse an S2K specifier from an OpenPGP packet input stream. + * @param in packet input stream + * @throws IOException + * @throws UnsupportedPacketVersionException if an unsupported S2K type is encountered + */ S2K( InputStream in) throws IOException @@ -127,7 +179,7 @@ public class S2K public S2K( int algorithm) { - this.type = 0; + this.type = SIMPLE; this.algorithm = algorithm; } @@ -141,7 +193,7 @@ public S2K( int algorithm, byte[] iv) { - this.type = 1; + this.type = SALTED; this.algorithm = algorithm; this.iv = iv; } @@ -158,7 +210,7 @@ public S2K( byte[] iv, int itCount) { - this.type = 3; + this.type = SALTED_AND_ITERATED; this.algorithm = algorithm; this.iv = iv; @@ -255,7 +307,14 @@ public static S2K gnuDummyS2K(GNUDummyParams parameters) } /** - * Gets the {@link HashAlgorithmTags digest algorithm} specified. + * Gets the S2K specifier type. + * + * @see #SIMPLE + * @see #SALTED + * @see #SALTED_AND_ITERATED + * @see #ARGON_2 + * + * @return type */ public int getType() { @@ -264,6 +323,9 @@ public int getType() /** * Gets the {@link HashAlgorithmTags hash algorithm} for this S2K. + * Only used for {@link #SIMPLE}, {@link #SALTED}, {@link #SALTED_AND_ITERATED} + * + * @return hash algorithm */ public int getHashAlgorithm() { @@ -272,6 +334,15 @@ public int getHashAlgorithm() /** * Gets the iv/salt to use for the key generation. + * The value of this field depends on the S2K {@link #type}: + *
        + *
      • {@link #SIMPLE}:
        null
      • + *
      • {@link #SALTED}: 8 octets
      • + *
      • {@link #SALTED_AND_ITERATED}: 8 octets
      • + *
      • {@link #ARGON_2}: 16 octets
      • + *
      + * + * @return IV */ public byte[] getIV() { @@ -280,6 +351,9 @@ public byte[] getIV() /** * Gets the actual (expanded) iteration count. + * Only used for {@link #SALTED_AND_ITERATED}. + * + * @return iteration count */ public long getIterationCount() { @@ -291,7 +365,7 @@ public long getIterationCount() } /** - * Return the number of passes - only Argon2 + * Return the number of passes - only Argon2. * * @return number of passes */ @@ -301,7 +375,12 @@ public int getPasses() } /** - * Gets the protection mode - only if GNU_DUMMY_S2K + * Gets the protection mode - only if GNU_DUMMY_S2K. + * + * @see #GNU_PROTECTION_MODE_NO_PRIVATE_KEY + * @see #GNU_PROTECTION_MODE_DIVERT_TO_CARD + * + * @return GNU dummy-s2k protection mode */ public int getProtectionMode() { @@ -309,7 +388,7 @@ public int getProtectionMode() } /** - * Gets the degree of parallelism - only if ARGON_2 + * Gets the degree of parallelism - only if ARGON_2. * * @return parallelism */ @@ -319,7 +398,7 @@ public int getParallelism() } /** - * Gets the memory size exponent - only if ARGON_2 + * Gets the memory size exponent - only if ARGON_2. * * @return memory size exponent */ @@ -328,6 +407,11 @@ public int getMemorySizeExponent() return memorySizeExponent; } + /** + * Encode the packet into the given {@link BCPGOutputStream}. + * @param out packet output stream + * @throws IOException + */ public void encode( BCPGOutputStream out) throws IOException @@ -396,6 +480,8 @@ private void writeOneOctetOrThrow(BCPGOutputStream out, int val, String valName) /** * Parameters for Argon2 S2K. + * @see + * OpenPGP - Argon2 */ public static class Argon2Params { @@ -431,7 +517,7 @@ public Argon2Params(SecureRandom secureRandom) * * @param passes number of iterations, must be greater than 0 * @param parallelism number of lanes, must be greater 0 - * @param memSizeExp exponent for memory consumption, must be between 3+ceil(log_2(p)) and 31 + * @param memSizeExp exponent for memory consumption, must be between
      3 + ⌈log₂p⌉
      and
      31
      * @param secureRandom secure random generator to initialize the salt vector */ public Argon2Params(int passes, int parallelism, int memSizeExp, SecureRandom secureRandom) @@ -445,7 +531,7 @@ public Argon2Params(int passes, int parallelism, int memSizeExp, SecureRandom se * @param salt 16 bytes of random salt * @param passes number of iterations, must be greater than 0 * @param parallelism number of lanes, must be greater 0 - * @param memSizeExp exponent for memory consumption, must be between 3+ceil(log_2(p)) and 31 + * @param memSizeExp exponent for memory consumption, must be between
      3 + ⌈log₂p⌉
      and
      31
      */ public Argon2Params(byte[] salt, int passes, int parallelism, int memSizeExp) { @@ -467,12 +553,12 @@ public Argon2Params(byte[] salt, int passes, int parallelism, int memSizeExp) } this.parallelism = parallelism; - // log_2(p) = log_e(p) / log_e(2) + // log₂p = logₑp / logₑ2 double log2_p = Math.log(parallelism) / Math.log(2); - // see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-05.html#section-3.7.1.4-5 + // see https://www.rfc-editor.org/rfc/rfc9580.html#section-3.7.1.4-5 if (memSizeExp < (3 + Math.ceil(log2_p)) || memSizeExp > 31) { - throw new IllegalArgumentException("Memory size exponent MUST be between 3+ceil(log_2(parallelism)) and 31"); + throw new IllegalArgumentException("Memory size exponent MUST be between 3 + ⌈log₂(parallelism)⌉ and 31"); } this.memSizeExp = memSizeExp; } @@ -485,7 +571,7 @@ public Argon2Params(byte[] salt, int passes, int parallelism, int memSizeExp) */ public static Argon2Params universallyRecommendedParameters() { - return new Argon2Params(1, 4, 21, new SecureRandom()); + return new Argon2Params(1, 4, 21, CryptoServicesRegistrar.getSecureRandom()); } /** @@ -497,7 +583,7 @@ public static Argon2Params universallyRecommendedParameters() */ public static Argon2Params memoryConstrainedParameters() { - return new Argon2Params(3, 4, 16, new SecureRandom()); + return new Argon2Params(3, 4, 16, CryptoServicesRegistrar.getSecureRandom()); } /** @@ -556,6 +642,9 @@ public int getMemSizeExp() /** * Parameters for the {@link #GNU_DUMMY_S2K} method. + * + * @see + * GNU extensions to the S2K algorithm */ public static class GNUDummyParams { @@ -587,6 +676,16 @@ public static GNUDummyParams divertToCard() return new GNUDummyParams(GNU_PROTECTION_MODE_DIVERT_TO_CARD); } + /** + * Factory method for a GNU Dummy S2K indicating an internal private key. + * + * @return params + */ + public static GNUDummyParams internal() + { + return new GNUDummyParams(GNU_PROTECTION_MODE_INTERNAL); + } + /** * Return the GNU Dummy S2K protection method. * diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SecretKeyPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SecretKeyPacket.java index decb8a1214..9b59fd4f5c 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SecretKeyPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SecretKeyPacket.java @@ -1,24 +1,26 @@ package org.bouncycastle.bcpg; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.io.Streams; /** - * basic packet for a PGP secret key + * Base class for OpenPGP secret (primary) keys. */ public class SecretKeyPacket extends ContainedPacket implements PublicKeyAlgorithmTags { /** - * Unprotected. + * S2K-usage octet indicating that the secret key material is unprotected. */ public static final int USAGE_NONE = 0x00; /** - * Malleable CFB. + * S2K-usage octet indicating that the secret key material is protected using malleable CFB. * Malleable-CFB-encrypted keys are vulnerable to corruption attacks * that can cause leakage of secret data when the secret key is used. * @@ -36,7 +38,7 @@ public class SecretKeyPacket public static final int USAGE_CHECKSUM = 0xff; /** - * CFB. + * S2K-usage octet indicating that the secret key material is protected using a cipher in CFB mode. * CFB-encrypted keys are vulnerable to corruption attacks that can * cause leakage of secret data when the secret key is use. * @@ -51,7 +53,7 @@ public class SecretKeyPacket public static final int USAGE_SHA1 = 0xfe; /** - * AEAD. + * S2K-usage octet indicating that the secret key material is protected using an AEAD scheme. * This usage protects against above-mentioned attacks. * Passphrase-protected secret key material in a v6 Secret Key or * v6 Secret Subkey packet SHOULD be protected with AEAD encryption @@ -60,6 +62,7 @@ public class SecretKeyPacket * Users should migrate to AEAD with all due speed. */ public static final int USAGE_AEAD = 0xfd; + private PublicKeyPacket pubKeyPacket; private byte[] secKeyData; private int s2kUsage; @@ -68,40 +71,97 @@ public class SecretKeyPacket private S2K s2k; private byte[] iv; + /** + * Parse a primary OpenPGP secret key packet from the given OpenPGP {@link BCPGInputStream}. + * The packet format is remembered as {@link PacketFormat#LEGACY}. + * @param in packet input stream + * @throws IOException + */ SecretKeyPacket( - BCPGInputStream in) - throws IOException + BCPGInputStream in) + throws IOException { this(SECRET_KEY, in); } /** - * @param in + * Parse a primary OpenPGP secret key packet from the given OpenPGP {@link BCPGInputStream}. + * If
      newPacketFormat
      is true, the packet format will be remembered as {@link PacketFormat#CURRENT}, + * otherwise as {@link PacketFormat#LEGACY}. + * @param in packet input stream + * @param newPacketFormat current or legacy packet format + * @throws IOException + */ + SecretKeyPacket( + BCPGInputStream in, + boolean newPacketFormat) + throws IOException + { + this(SECRET_KEY, in, newPacketFormat); + } + + /** + * Parse a {@link SecretKeyPacket} or {@link SecretSubkeyPacket} from the given OpenPGP {@link BCPGInputStream}. + * The return type depends on the
      keyTag
      : + * {@link PacketTags#SECRET_KEY} means the result is a {@link SecretKeyPacket}. + * {@link PacketTags#SECRET_SUBKEY} results in a {@link SecretSubkeyPacket}. + * The packet format will be remembered as {@link PacketFormat#LEGACY}. + * @param keyTag packet type ID + * @param in packet input stream * @throws IOException */ + SecretKeyPacket( + int keyTag, + BCPGInputStream in) + throws IOException + { + this(keyTag, in, false); + } + + /** + * Parse a {@link SecretKeyPacket} or {@link SecretSubkeyPacket} from an OpenPGP {@link BCPGInputStream}. + * The return type depends on the
      keyTag
      : + * {@link PacketTags#SECRET_KEY} means the result is a {@link SecretKeyPacket}. + * {@link PacketTags#SECRET_SUBKEY} results in a {@link SecretSubkeyPacket}. + * + * @param keyTag packet type ID + * @param in packet input stream + * @param newPacketFormat packet format + * @throws IOException if the secret key packet cannot be parsed + * + * @see + * OpenPGP - Secret-Key Packet Formats + * @see + * LibrePGP - Secret-Key Packet Formats + * @see + * Hardware-Backed Secret Keys + */ SecretKeyPacket( int keyTag, - BCPGInputStream in) + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(keyTag); + super(keyTag, newPacketFormat); if (this instanceof SecretSubkeyPacket) { - pubKeyPacket = new PublicSubkeyPacket(in); + pubKeyPacket = new PublicSubkeyPacket(in, newPacketFormat); } else { - pubKeyPacket = new PublicKeyPacket(in); + pubKeyPacket = new PublicKeyPacket(in, newPacketFormat); } int version = pubKeyPacket.getVersion(); s2kUsage = in.read(); - if (version == 6 && s2kUsage != USAGE_NONE) + int conditionalParameterLength = -1; + if (version == PublicKeyPacket.LIBREPGP_5 || + (version == PublicKeyPacket.VERSION_6 && s2kUsage != USAGE_NONE)) { // TODO: Use length to parse unknown parameters - int conditionalParameterLength = in.read(); + conditionalParameterLength = in.read(); } if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_SHA1 || s2kUsage == USAGE_AEAD) @@ -116,48 +176,74 @@ public class SecretKeyPacket { aeadAlgorithm = in.read(); } - if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_SHA1 || s2kUsage == USAGE_AEAD) + if (version == PublicKeyPacket.VERSION_6 && (s2kUsage == USAGE_SHA1 || s2kUsage == USAGE_AEAD)) + { + int s2KLen = in.read(); + byte[] s2kBytes = new byte[s2KLen]; + in.readFully(s2kBytes); + + // TODO: catch UnsupportedPacketVersionException gracefully + s2k = new S2K(new ByteArrayInputStream(s2kBytes)); + } + else { - if (version == PublicKeyPacket.VERSION_6) + if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_SHA1 || s2kUsage == USAGE_AEAD) { - // TODO: Use length to parse unknown S2Ks - int s2kLen = in.read(); + s2k = new S2K(in); } - s2k = new S2K(in); } if (s2kUsage == USAGE_AEAD) { iv = new byte[AEADUtils.getIVLength(aeadAlgorithm)]; Streams.readFully(in, iv); } - boolean isGNUDummyNoPrivateKey = s2k != null - && s2k.getType() == S2K.GNU_DUMMY_S2K - && s2k.getProtectionMode() == S2K.GNU_PROTECTION_MODE_NO_PRIVATE_KEY; - if (!(isGNUDummyNoPrivateKey)) + else { - if (s2kUsage != 0 && iv == null) + boolean isGNUDummyNoPrivateKey = s2k != null + && s2k.getType() == S2K.GNU_DUMMY_S2K + && s2k.getProtectionMode() == S2K.GNU_PROTECTION_MODE_NO_PRIVATE_KEY; + if (!(isGNUDummyNoPrivateKey)) { - if (encAlgorithm < 7) - { - iv = new byte[8]; - } - else + if (s2kUsage != USAGE_NONE && iv == null) { - iv = new byte[16]; + if (encAlgorithm < 7) + { + iv = new byte[8]; + } + else + { + iv = new byte[16]; + } + in.readFully(iv, 0, iv.length); } - in.readFully(iv, 0, iv.length); } } - - this.secKeyData = in.readAll(); + + if (version == PublicKeyPacket.LIBREPGP_5) + { + long keyOctetCount = ((long) in.read() << 24) | ((long) in.read() << 16) | ((long) in.read() << 8) | in.read(); + if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_NONE) + { + // encoded keyOctetCount does not contain checksum + keyOctetCount += 2; + } + this.secKeyData = new byte[(int) keyOctetCount]; + in.readFully(secKeyData); + } + else + { + this.secKeyData = in.readAll(); + } } /** - * @param pubKeyPacket - * @param encAlgorithm - * @param s2k - * @param iv - * @param secKeyData + * Construct a {@link SecretKeyPacket}. + * Note:
      secKeyData
      needs to be prepared by applying encryption/checksum beforehand. + * @param pubKeyPacket pubkey packet corresponding to this secret key packet. + * @param encAlgorithm algorithm id of the symmetric key algorithm that was used to encrypt the secret key material + * @param s2k s2k identifier for deriving a key from a passphrase + * @param iv IV that was used to encrypt the secret key material + * @param secKeyData encrypted/checksum'd secret key material */ public SecretKeyPacket( PublicKeyPacket pubKeyPacket, @@ -169,6 +255,16 @@ public SecretKeyPacket( this(SECRET_KEY, pubKeyPacket, encAlgorithm, s2k, iv, secKeyData); } + /** + * Construct a {@link SecretKeyPacket} or {@link SecretSubkeyPacket}. + * Note:
      secKeyData
      needs to be prepared by applying encryption/checksum beforehand. + * @param keyTag packet type ID + * @param pubKeyPacket pubkey packet corresponding to this secret key packet. + * @param encAlgorithm algorithm id of the symmetric key algorithm that was used to encrypt the secret key material + * @param s2k s2k identifier for deriving a key from a passphrase + * @param iv IV that was used to encrypt the secret key material + * @param secKeyData encrypted/checksum'd secret key material + */ SecretKeyPacket( int keyTag, PublicKeyPacket pubKeyPacket, @@ -180,6 +276,16 @@ public SecretKeyPacket( this(keyTag, pubKeyPacket, encAlgorithm, 0, encAlgorithm != SymmetricKeyAlgorithmTags.NULL ? USAGE_CHECKSUM : USAGE_NONE, s2k, iv, secKeyData); } + /** + * Construct a {@link SecretKeyPacket} or {@link SecretSubkeyPacket}. + * Note:
      secKeyData
      needs to be prepared by applying encryption/checksum beforehand. + * @param pubKeyPacket pubkey packet corresponding to this secret key packet. + * @param encAlgorithm algorithm id of the symmetric key algorithm that was used to encrypt the secret key material + * @param s2kUsage octet indicating, how the secert key material was protected + * @param s2k s2k identifier for deriving a key from a passphrase + * @param iv IV that was used to encrypt the secret key material + * @param secKeyData encrypted/checksum'd secret key material + */ public SecretKeyPacket( PublicKeyPacket pubKeyPacket, int encAlgorithm, @@ -191,6 +297,41 @@ public SecretKeyPacket( this(SECRET_KEY, pubKeyPacket, encAlgorithm, 0, s2kUsage, s2k, iv, secKeyData); } + /** + * Construct a {@link SecretKeyPacket} or {@link SecretSubkeyPacket}. + * Note:
      secKeyData
      needs to be prepared by applying encryption/checksum beforehand. + * @param pubKeyPacket pubkey packet corresponding to this secret key packet. + * @param encAlgorithm algorithm id of the symmetric key algorithm that was used to encrypt the secret key material + * @param aeadAlgorithm AEAD algorithm scheme used to protect the secret key material with + * @param s2kUsage octet indicating how the secret key material was encrypted + * @param s2k s2k identifier for deriving a key from a passphrase + * @param iv IV that was used to encrypt the secret key material + * @param secKeyData encrypted/checksum'd secret key material + */ + public SecretKeyPacket( + PublicKeyPacket pubKeyPacket, + int encAlgorithm, + int aeadAlgorithm, + int s2kUsage, + S2K s2k, + byte[] iv, + byte[] secKeyData) + { + this(SECRET_KEY, pubKeyPacket, encAlgorithm, aeadAlgorithm, s2kUsage, s2k, iv, secKeyData); + } + + /** + * Construct a {@link SecretKeyPacket} or {@link SecretSubkeyPacket}. + * Note:
      secKeyData
      needs to be prepared by applying encryption/checksum beforehand. + * @param keyTag packet type ID + * @param pubKeyPacket pubkey packet corresponding to this secret key packet. + * @param encAlgorithm algorithm id of the symmetric key algorithm that was used to encrypt the secret key material + * @param aeadAlgorithm AEAD algorithm scheme used to protect the secret key material with + * @param s2kUsage octet indicating how the secret key material was encrypted + * @param s2k s2k identifier for deriving a key from a passphrase + * @param iv IV that was used to encrypt the secret key material + * @param secKeyData encrypted/checksum'd secret key material + */ SecretKeyPacket( int keyTag, PublicKeyPacket pubKeyPacket, @@ -201,14 +342,14 @@ public SecretKeyPacket( byte[] iv, byte[] secKeyData) { - super(keyTag); + super(keyTag, pubKeyPacket.hasNewPacketFormat()); this.pubKeyPacket = pubKeyPacket; this.encAlgorithm = encAlgorithm; this.aeadAlgorithm = aeadAlgorithm; this.s2kUsage = s2kUsage; this.s2k = s2k; - this.iv = iv; + this.iv = Arrays.clone(iv); this.secKeyData = secKeyData; if (s2k != null && s2k.getType() == S2K.ARGON_2 && s2kUsage != USAGE_AEAD) @@ -225,41 +366,74 @@ public SecretKeyPacket( } } + /** + * Return the algorithm ID of the symmetric key algorithm that was used to encrypt the secret key material. + * @return symmetric key enc algorithm id + */ public int getEncAlgorithm() { return encAlgorithm; } + /** + * Return the algorithm ID of the AEAD algorithm that was used to protect the secret key material. + * @return aead algorithm id + */ public int getAeadAlgorithm() { return aeadAlgorithm; } + /** + * Return the S2K usage mode indicating how the secret key material is protected. + * @return s2k usage + */ public int getS2KUsage() { return s2kUsage; } + /** + * Return the IV that was used to protect the secret key material. + * @return IV + */ public byte[] getIV() { - return iv; + return Arrays.clone(iv); } + /** + * Return the S2K identifier describing, how to derive the symmetric key to protect the secret key material with. + * @return s2k identifier + */ public S2K getS2K() { return s2k; } + /** + * Return the public key packet corresponding to the secret key packet. + * @return public key packet + */ public PublicKeyPacket getPublicKeyPacket() { return pubKeyPacket; } + /** + * Return the encrypted/checksum'd secret key data. + * @return secret key data + */ public byte[] getSecretKeyData() { return secKeyData; } + /** + * Return the encoded packet content without packet frame. + * @return encoded packet contents + * @throws IOException + */ public byte[] getEncodedContents() throws IOException { @@ -272,7 +446,8 @@ public byte[] getEncodedContents() // conditional parameters byte[] conditionalParameters = encodeConditionalParameters(); - if (pubKeyPacket.getVersion() == PublicKeyPacket.VERSION_6 && s2kUsage != USAGE_NONE) + if (pubKeyPacket.getVersion() == PublicKeyPacket.LIBREPGP_5 || + (pubKeyPacket.getVersion() == PublicKeyPacket.VERSION_6 && s2kUsage != USAGE_NONE)) { pOut.write(conditionalParameters.length); } @@ -281,6 +456,16 @@ public byte[] getEncodedContents() // encrypted secret key if (secKeyData != null && secKeyData.length > 0) { + if (pubKeyPacket.getVersion() == PublicKeyPacket.LIBREPGP_5) + { + int keyOctetCount = secKeyData.length; + // v5 keyOctetCount does not include checksum octets + if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_NONE) + { + keyOctetCount -= 2; + } + StreamUtil.write4OctetLength(pOut, keyOctetCount); + } pOut.write(secKeyData); } @@ -319,10 +504,18 @@ private byte[] encodeConditionalParameters() return conditionalParameters.toByteArray(); } + /** + * Encode the packet into the given {@link BCPGOutputStream}. + * If the packet output stream has {@link PacketFormat#ROUNDTRIP} set, the packet format to encode the packet length + * with depends on the result of {@link #hasNewPacketFormat()}. + * Otherwise, the packet output stream dictates the packet format. + * @param out packet output stream + * @throws IOException + */ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(getPacketTag(), getEncodedContents()); + out.writePacket(hasNewPacketFormat(), getPacketTag(), getEncodedContents()); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SecretSubkeyPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SecretSubkeyPacket.java index b7610747d9..910d7b2f5b 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SecretSubkeyPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SecretSubkeyPacket.java @@ -18,9 +18,16 @@ public class SecretSubkeyPacket BCPGInputStream in) throws IOException { - super(SECRET_SUBKEY, in); + this(in, false); } + SecretSubkeyPacket( + BCPGInputStream in, + boolean newPacketFormat) + throws IOException + { + super(SECRET_SUBKEY, in, newPacketFormat); + } /** * Create a secret subkey packet. * If the encryption algorithm is NOT {@link SymmetricKeyAlgorithmTags#NULL}, @@ -75,7 +82,7 @@ public SecretSubkeyPacket( * @param iv optional iv for the AEAD algorithm or encryption algorithm * @param secKeyData secret key data */ - SecretSubkeyPacket( + public SecretSubkeyPacket( PublicKeyPacket pubKeyPacket, int encAlgorithm, int aeadAlgorithm, diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java index f2b7c2aa95..853a22090f 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java @@ -5,9 +5,11 @@ import java.io.IOException; import java.util.Vector; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; import org.bouncycastle.bcpg.sig.IssuerKeyID; import org.bouncycastle.bcpg.sig.SignatureCreationTime; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Pack; import org.bouncycastle.util.io.Streams; /** @@ -19,12 +21,12 @@ public class SignaturePacket public static final int VERSION_2 = 2; public static final int VERSION_3 = 3; public static final int VERSION_4 = 4; // https://datatracker.ietf.org/doc/rfc4880/ - public static final int VERSION_5 = 5; // https://datatracker.ietf.org/doc/draft-koch-openpgp-2015-rfc4880bis/ - public static final int VERSION_6 = 6; // https://datatracker.ietf.org/doc/draft-ietf-openpgp-crypto-refresh/ + public static final int VERSION_5 = 5; // https://datatracker.ietf.org/doc/draft-koch-librepgp/ + public static final int VERSION_6 = 6; // https://www.rfc-editor.org/rfc/rfc9580.html private int version; private int signatureType; - private long creationTime; + private long creationTime; // millis private long keyID; private int keyAlgorithm; private int hashAlgorithm; @@ -33,155 +35,262 @@ public class SignaturePacket private SignatureSubpacket[] hashedData; private SignatureSubpacket[] unhashedData; private byte[] signatureEncoding; + private byte[] salt; // v6 only SignaturePacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + SignaturePacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(SIGNATURE); + super(SIGNATURE, newPacketFormat); version = in.read(); - - if (version == VERSION_3 || version == VERSION_2) + switch (version) { - int l = in.read(); + case VERSION_2: + case VERSION_3: + parseV2_V3(in); + break; + case VERSION_4: + case VERSION_5: + parseV4_V5(in); + break; + case VERSION_6: + parseV6(in); + break; + default: + Streams.drain(in); + throw new UnsupportedPacketVersionException("unsupported version: " + version); + } + } - signatureType = in.read(); - creationTime = (((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read()) * 1000; + /** + * Parse a version 2 or version 3 signature. + * @param in input stream which already skipped over the version number + * @throws IOException if the packet is malformed + * + * @see + * Version 3 packet format + */ + private void parseV2_V3(BCPGInputStream in) + throws IOException + { + int l = in.read(); // length l MUST be 5 - keyID = StreamUtil.readKeyID(in); - keyAlgorithm = in.read(); - hashAlgorithm = in.read(); - } - else if (version == VERSION_4) - { - signatureType = in.read(); - keyAlgorithm = in.read(); - hashAlgorithm = in.read(); + signatureType = in.read(); + creationTime = StreamUtil.readTime(in); - int hashedLength = (in.read() << 8) | in.read(); - byte[] hashed = new byte[hashedLength]; + keyID = StreamUtil.readKeyID(in); + keyAlgorithm = in.read(); + hashAlgorithm = in.read(); - in.readFully(hashed); + // left 16 bits of the signed hash value + fingerPrint = new byte[2]; + in.readFully(fingerPrint); - // - // read the signature sub packet data. - // - SignatureSubpacket sub; - SignatureSubpacketInputStream sIn = new SignatureSubpacketInputStream( - new ByteArrayInputStream(hashed)); + parseSignature(in); + } - Vector v = new Vector(); - while ((sub = sIn.readPacket()) != null) - { - v.addElement(sub); - } + /** + * Parse a version 4 or version 5 signature. + * The difference between version 4 and 5 is that a version 5 signature contains additional metadata. + * @param in input stream which already skipped over the version number + * @throws IOException if the packet is malformed + * + * @see + * Version 4 packet format + * @see + * Version 5 packet format + */ + private void parseV4_V5(BCPGInputStream in) + throws IOException + { + signatureType = in.read(); + keyAlgorithm = in.read(); + hashAlgorithm = in.read(); - hashedData = new SignatureSubpacket[v.size()]; + parseSubpackets(in); - for (int i = 0; i != hashedData.length; i++) - { - SignatureSubpacket p = (SignatureSubpacket)v.elementAt(i); - if (p instanceof IssuerKeyID) - { - keyID = ((IssuerKeyID)p).getKeyID(); - } - else if (p instanceof SignatureCreationTime) - { - creationTime = ((SignatureCreationTime)p).getTime().getTime(); - } + // left 16 bits of the signed hash value + fingerPrint = new byte[2]; + in.readFully(fingerPrint); - hashedData[i] = p; - } + parseSignature(in); + } - int unhashedLength = (in.read() << 8) | in.read(); - byte[] unhashed = new byte[unhashedLength]; + /** + * Parse a version 6 signature. + * Version 6 signatures do use 4 octet subpacket area length descriptors and contain an additional salt value + * (which may or may not be of size 0, LibrePGP and OpenPGP are in disagreement here). + * @param in input stream which already skipped over the version number + * @throws IOException if the packet is malformed + * + * @see + * OpenPGP - Version 6 packet format + */ + private void parseV6(BCPGInputStream in) + throws IOException + { + signatureType = in.read(); + keyAlgorithm = in.read(); + hashAlgorithm = in.read(); + + parseSubpackets(in); + + // left 16 bits of the signed hash value + fingerPrint = new byte[2]; + in.readFully(fingerPrint); + + int saltSize = in.read(); + salt = new byte[saltSize]; + in.readFully(salt); - in.readFully(unhashed); + parseSignature(in); + } + + /** + * Parse the hashed and unhashed signature subpacket areas of the signature. + * Version 4 and 5 signature encode the area length using 2 octets, while version 6 uses 4 octet lengths instead. + * + * @param in input stream which skipped to after the hash algorithm octet + * @throws IOException if the packet is malformed + */ + private void parseSubpackets(BCPGInputStream in) + throws IOException + { - sIn = new SignatureSubpacketInputStream( - new ByteArrayInputStream(unhashed)); + Vector vec = readSignatureSubpacketVector(in); + hashedData = new SignatureSubpacket[vec.size()]; - v.removeAllElements(); - while ((sub = sIn.readPacket()) != null) + for (int i = 0; i != hashedData.length; i++) + { + SignatureSubpacket p = (SignatureSubpacket)vec.elementAt(i); + if (p instanceof IssuerKeyID) + { + keyID = ((IssuerKeyID)p).getKeyID(); + } + else if (p instanceof SignatureCreationTime) { - v.addElement(sub); + creationTime = ((SignatureCreationTime)p).getTime().getTime(); } - unhashedData = new SignatureSubpacket[v.size()]; + hashedData[i] = p; + } - for (int i = 0; i != unhashedData.length; i++) - { - SignatureSubpacket p = (SignatureSubpacket)v.elementAt(i); - if (p instanceof IssuerKeyID) - { - keyID = ((IssuerKeyID)p).getKeyID(); - } + vec = readSignatureSubpacketVector(in); + unhashedData = new SignatureSubpacket[vec.size()]; - unhashedData[i] = p; + for (int i = 0; i != unhashedData.length; i++) + { + SignatureSubpacket p = (SignatureSubpacket)vec.elementAt(i); + if (p instanceof IssuerKeyID) + { + keyID = ((IssuerKeyID)p).getKeyID(); } + + unhashedData[i] = p; + } + + setIssuerKeyId(); + setCreationTime(); + } + + private Vector readSignatureSubpacketVector(BCPGInputStream in) + throws IOException + { + int hashedLength; + if (version == 6) + { + hashedLength = StreamUtil.read4OctetLength(in); } else { - Streams.drain(in); - - throw new UnsupportedPacketVersionException("unsupported version: " + version); + hashedLength = StreamUtil.read2OctetLength(in); } + byte[] hashed = new byte[hashedLength]; - fingerPrint = new byte[2]; - in.readFully(fingerPrint); + in.readFully(hashed); + + // + // read the signature sub packet data. + // + SignatureSubpacket sub; + SignatureSubpacketInputStream sIn = new SignatureSubpacketInputStream( + new ByteArrayInputStream(hashed)); + + Vector vec = new Vector(); + while ((sub = sIn.readPacket()) != null) + { + vec.addElement(sub); + } + return vec; + } + /** + * Parse the algorithm-specific signature encoding. + * Ed25519 and Ed448 do not populate the signature MPInteger field, but instead read the raw signature to + * signatureEncoding directly. + * + * @param in input stream which skipped the head of the signature + * @throws IOException if the packet is malformed + */ + private void parseSignature(BCPGInputStream in) + throws IOException + { switch (keyAlgorithm) { - case RSA_GENERAL: - case RSA_SIGN: - MPInteger v = new MPInteger(in); - - signature = new MPInteger[1]; - signature[0] = v; - break; - case DSA: - MPInteger r = new MPInteger(in); - MPInteger s = new MPInteger(in); - - signature = new MPInteger[2]; - signature[0] = r; - signature[1] = s; - break; - case ELGAMAL_ENCRYPT: // yep, this really does happen sometimes. - case ELGAMAL_GENERAL: - MPInteger p = new MPInteger(in); - MPInteger g = new MPInteger(in); - MPInteger y = new MPInteger(in); - - signature = new MPInteger[3]; - signature[0] = p; - signature[1] = g; - signature[2] = y; - break; - case ECDSA: - case EDDSA_LEGACY: - case Ed448: - case Ed25519: - case X448: - case X25519: - MPInteger ecR = new MPInteger(in); - MPInteger ecS = new MPInteger(in); - - signature = new MPInteger[2]; - signature[0] = ecR; - signature[1] = ecS; - break; - default: - if (keyAlgorithm >= PublicKeyAlgorithmTags.EXPERIMENTAL_1 && keyAlgorithm <= PublicKeyAlgorithmTags.EXPERIMENTAL_11) - { - signature = null; - signatureEncoding = Streams.readAll(in); - } - else - { - throw new IOException("unknown signature key algorithm: " + keyAlgorithm); - } + case RSA_GENERAL: + case RSA_SIGN: + MPInteger v = new MPInteger(in); + + signature = new MPInteger[1]; + signature[0] = v; + break; + case DSA: + case ELGAMAL_ENCRYPT: // yep, this really does happen sometimes. + case ELGAMAL_GENERAL: + MPInteger r = new MPInteger(in); + MPInteger s = new MPInteger(in); + + signature = new MPInteger[2]; + signature[0] = r; + signature[1] = s; + break; + case Ed448: + signatureEncoding = new byte[org.bouncycastle.math.ec.rfc8032.Ed448.SIGNATURE_SIZE]; + in.readFully(signatureEncoding); + break; + case Ed25519: + signatureEncoding = new byte[org.bouncycastle.math.ec.rfc8032.Ed25519.SIGNATURE_SIZE]; + in.readFully(signatureEncoding); + break; + case ECDSA: + case EDDSA_LEGACY: + + MPInteger ecR = new MPInteger(in); + MPInteger ecS = new MPInteger(in); + + signature = new MPInteger[2]; + signature[0] = ecR; + signature[1] = ecS; + break; + default: + if (keyAlgorithm >= PublicKeyAlgorithmTags.EXPERIMENTAL_1 && keyAlgorithm <= PublicKeyAlgorithmTags.EXPERIMENTAL_11) + { + signature = null; + signatureEncoding = Streams.readAll(in); + } + else + { + throw new IOException("unknown signature key algorithm: " + keyAlgorithm); + } } } @@ -244,7 +353,22 @@ public SignaturePacket( byte[] fingerPrint, MPInteger[] signature) { - super(SIGNATURE); + this(version, false, signatureType, keyID, keyAlgorithm, hashAlgorithm, hashedData, unhashedData, fingerPrint, signature); + } + + public SignaturePacket( + int version, + boolean hasNewPacketFormat, + int signatureType, + long keyID, + int keyAlgorithm, + int hashAlgorithm, + SignatureSubpacket[] hashedData, + SignatureSubpacket[] unhashedData, + byte[] fingerPrint, + MPInteger[] signature) + { + super(SIGNATURE, hasNewPacketFormat); this.version = version; this.signatureType = signatureType; @@ -262,6 +386,66 @@ public SignaturePacket( } } + public SignaturePacket( + int version, + int signatureType, + long keyID, + int keyAlgorithm, + int hashAlgorithm, + SignatureSubpacket[] hashedData, + SignatureSubpacket[] unhashedData, + byte[] fingerPrint, + byte[] signatureEncoding, + byte[] salt) + { + super(SIGNATURE, true); + + this.version = version; + this.signatureType = signatureType; + this.keyID = keyID; + this.keyAlgorithm = keyAlgorithm; + this.hashAlgorithm = hashAlgorithm; + this.hashedData = hashedData; + this.unhashedData = unhashedData; + this.fingerPrint = fingerPrint; + this.signatureEncoding = Arrays.clone(signatureEncoding); + this.salt = Arrays.clone(salt); + if (hashedData != null) + { + setCreationTime(); + } + } + + public SignaturePacket( + int version, + int signatureType, + long keyID, + int keyAlgorithm, + int hashAlgorithm, + SignatureSubpacket[] hashedData, + SignatureSubpacket[] unhashedData, + byte[] fingerPrint, + MPInteger[] signature, + byte[] salt) + { + super(SIGNATURE, true); + + this.version = version; + this.signatureType = signatureType; + this.keyID = keyID; + this.keyAlgorithm = keyAlgorithm; + this.hashAlgorithm = hashAlgorithm; + this.hashedData = hashedData; + this.unhashedData = unhashedData; + this.fingerPrint = fingerPrint; + this.signature = signature; + this.salt = Arrays.clone(salt); + if (hashedData != null) + { + setCreationTime(); + } + } + /** * get the version number */ @@ -296,6 +480,16 @@ public byte[] getFingerPrint() return Arrays.clone(fingerPrint); } + /** + * Return the signature's salt. + * Only for v6 signatures. + * @return salt + */ + public byte[] getSalt() + { + return salt; + } + /** * return the signature trailer that must be included with the data * to reconstruct the signature @@ -306,19 +500,16 @@ public byte[] getSignatureTrailer() { byte[] trailer = null; - if (version == 3 || version == 2) + if (version == VERSION_3 || version == VERSION_2) { trailer = new byte[5]; long time = creationTime / 1000; trailer[0] = (byte)signatureType; - trailer[1] = (byte)(time >> 24); - trailer[2] = (byte)(time >> 16); - trailer[3] = (byte)(time >> 8); - trailer[4] = (byte)(time); + Pack.intToBigEndian((int)time, trailer, 1); } - else + else if (version == VERSION_4 || version == VERSION_5 || version == VERSION_6) { ByteArrayOutputStream sOut = new ByteArrayOutputStream(); SignatureSubpacket[] hashed = this.getHashedSubPackets(); @@ -338,19 +529,28 @@ public byte[] getSignatureTrailer() } byte[] data = hOut.toByteArray(); - - sOut.write((byte)(data.length >> 8)); - sOut.write((byte)data.length); + if (version != VERSION_6) + { + StreamUtil.write2OctetLength(sOut, data.length); + } + else + { + StreamUtil.write4OctetLength(sOut, data.length); + } sOut.write(data); byte[] hData = sOut.toByteArray(); sOut.write((byte)this.getVersion()); sOut.write((byte)0xff); - sOut.write((byte)(hData.length>> 24)); - sOut.write((byte)(hData.length >> 16)); - sOut.write((byte)(hData.length >> 8)); - sOut.write((byte)(hData.length)); + if (version == VERSION_5) + { + StreamUtil.write8OctetLength(sOut, hData.length); + } + else + { + StreamUtil.write4OctetLength(sOut, hData.length); + } } catch (IOException e) { @@ -382,6 +582,8 @@ public int getHashAlgorithm() /** * return the signature as a set of integers - note this is normalised to be the * ASN.1 encoding of what appears in the signature packet. + * Note, that Ed25519 and Ed448 returns null, as the raw signature is stored in signatureEncoding only. + * For those, use {@link #getSignatureBytes()} instead. */ public MPInteger[] getSignature() { @@ -447,51 +649,28 @@ public void encode( pOut.write(version); - if (version == 3 || version == 2) + if (version == VERSION_3 || version == VERSION_2) { pOut.write(5); // the length of the next block - long time = creationTime / 1000; - pOut.write(signatureType); - StreamUtil.writeTime(pOut, time); + StreamUtil.writeTime(pOut, creationTime); StreamUtil.writeKeyID(pOut, keyID); pOut.write(keyAlgorithm); pOut.write(hashAlgorithm); } - else if (version == 4) + else if (version == VERSION_4 || version == VERSION_5 || version == VERSION_6) { pOut.write(signatureType); pOut.write(keyAlgorithm); pOut.write(hashAlgorithm); - ByteArrayOutputStream sOut = new ByteArrayOutputStream(); - - for (int i = 0; i != hashedData.length; i++) - { - hashedData[i].encode(sOut); - } - - byte[] data = sOut.toByteArray(); - - pOut.write(data.length >> 8); - pOut.write(data.length); - pOut.write(data); - + ByteArrayOutputStream sOut = new ByteArrayOutputStream(); + writeSignatureSubpacketArray(sOut, pOut, hashedData); sOut.reset(); - - for (int i = 0; i != unhashedData.length; i++) - { - unhashedData[i].encode(sOut); - } - - data = sOut.toByteArray(); - - pOut.write(data.length >> 8); - pOut.write(data.length); - pOut.write(data); + writeSignatureSubpacketArray(sOut, pOut, unhashedData); } else { @@ -500,6 +679,12 @@ else if (version == 4) pOut.write(fingerPrint); + if (version == VERSION_6) + { + pOut.write(salt.length); + pOut.write(salt); + } + if (signature != null) { for (int i = 0; i != signature.length; i++) @@ -514,7 +699,28 @@ else if (version == 4) pOut.close(); - out.writePacket(SIGNATURE, bOut.toByteArray()); + out.writePacket(hasNewPacketFormat(), SIGNATURE, bOut.toByteArray()); + } + + private void writeSignatureSubpacketArray(ByteArrayOutputStream sOut, BCPGOutputStream pOut, SignatureSubpacket[] array) + throws IOException + { + for (int i = 0; i != array.length; i++) + { + array[i].encode(sOut); + } + + byte[] data = sOut.toByteArray(); + + if (version == VERSION_6) + { + StreamUtil.write4OctetLength(pOut, data.length); + } + else + { + StreamUtil.write2OctetLength(pOut, data.length); + } + pOut.write(data); } private void setCreationTime() @@ -529,6 +735,51 @@ private void setCreationTime() } } + /** + * Iterate over the hashed and unhashed signature subpackets to identify either a {@link IssuerKeyID} or + * {@link IssuerFingerprint} subpacket to derive the issuer key-ID from. + * The issuer {@link IssuerKeyID} and {@link IssuerFingerprint} subpacket information is "self-authenticating", + * as its authenticity can be verified by checking the signature with the corresponding key. + * Therefore, we can also check the unhashed signature subpacket area. + */ + private void setIssuerKeyId() + { + if (keyID != 0L) + { + return; + } + + for (int idx = 0; idx != hashedData.length; idx++) + { + SignatureSubpacket p = hashedData[idx]; + if (p instanceof IssuerKeyID) + { + keyID = ((IssuerKeyID) p).getKeyID(); + return; + } + if (p instanceof IssuerFingerprint) + { + keyID = ((IssuerFingerprint) p).getKeyID(); + return; + } + } + + for (int idx = 0; idx != unhashedData.length; idx++) + { + SignatureSubpacket p = unhashedData[idx]; + if (p instanceof IssuerKeyID) + { + keyID = ((IssuerKeyID) p).getKeyID(); + return; + } + if (p instanceof IssuerFingerprint) + { + keyID = ((IssuerFingerprint) p).getKeyID(); + return; + } + } + } + public static SignaturePacket fromByteArray(byte[] data) throws IOException { diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketInputStream.java b/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketInputStream.java index dab6e423ee..b66ba0813c 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketInputStream.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketInputStream.java @@ -12,10 +12,12 @@ import org.bouncycastle.bcpg.sig.IssuerKeyID; import org.bouncycastle.bcpg.sig.KeyExpirationTime; import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.LibrePGPPreferredEncryptionModes; import org.bouncycastle.bcpg.sig.NotationData; import org.bouncycastle.bcpg.sig.PolicyURI; import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; import org.bouncycastle.bcpg.sig.PreferredAlgorithms; +import org.bouncycastle.bcpg.sig.PreferredKeyServer; import org.bouncycastle.bcpg.sig.PrimaryUserID; import org.bouncycastle.bcpg.sig.RegularExpression; import org.bouncycastle.bcpg.sig.Revocable; @@ -68,33 +70,17 @@ public int read() public SignatureSubpacket readPacket() throws IOException { - int l = this.read(); - int bodyLen = 0; - - if (l < 0) + boolean[] flags = new boolean[3]; + int bodyLen = StreamUtil.readBodyLen(this, flags); + if (flags[StreamUtil.flag_eof]) { return null; } - - boolean isLongLength = false; - - if (l < 192) - { - bodyLen = l; - } - else if (l <= 223) - { - bodyLen = ((l - 192) << 8) + (in.read()) + 192; - } - else if (l == 255) - { - isLongLength = true; - bodyLen = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); - } - else + else if (flags[StreamUtil.flag_partial]) { throw new IOException("unexpected length header"); } + boolean isLongLength = flags[StreamUtil.flag_isLongLength]; int tag = in.read(); @@ -166,8 +152,12 @@ else if (l == 255) case PREFERRED_HASH_ALGS: case PREFERRED_SYM_ALGS: return new PreferredAlgorithms(type, isCritical, isLongLength, data); + case LIBREPGP_PREFERRED_ENCRYPTION_MODES: + return new LibrePGPPreferredEncryptionModes(isCritical, isLongLength, data); case PREFERRED_AEAD_ALGORITHMS: return new PreferredAEADCiphersuites(isCritical, isLongLength, data); + case PREFERRED_KEY_SERV: + return new PreferredKeyServer(isCritical, isLongLength, data); case KEY_FLAGS: return new KeyFlags(isCritical, isLongLength, data); case POLICY_URL: diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketTags.java b/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketTags.java index 73456727b4..9aea4c211f 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SignatureSubpacketTags.java @@ -30,8 +30,9 @@ public interface SignatureSubpacketTags int SIGNATURE_TARGET = 31; // signature target int EMBEDDED_SIGNATURE = 32; // embedded signature int ISSUER_FINGERPRINT = 33; // issuer key fingerprint -// public static final int PREFERRED_AEAD_ALGORITHMS = 34; // RESERVED since crypto-refresh-05 -int INTENDED_RECIPIENT_FINGERPRINT = 35; // intended recipient fingerprint + int LIBREPGP_PREFERRED_ENCRYPTION_MODES = 34; +// public static final int PREFERRED_AEAD_ALGORITHMS = 34;// RESERVED since rfc9580 + int INTENDED_RECIPIENT_FINGERPRINT = 35; // intended recipient fingerprint int ATTESTED_CERTIFICATIONS = 37; // attested certifications (RESERVED) int KEY_BLOCK = 38; // Key Block (RESERVED) int PREFERRED_AEAD_ALGORITHMS = 39; // preferred AEAD algorithms diff --git a/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java b/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java index 3d6456cd48..a5248a01e1 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java @@ -7,6 +7,8 @@ import java.io.OutputStream; import java.nio.channels.FileChannel; +import org.bouncycastle.util.Arrays; + class StreamUtil { private static final long MAX_MEMORY = Runtime.getRuntime().maxMemory(); @@ -109,11 +111,119 @@ static long readKeyID(BCPGInputStream in) static void writeTime(BCPGOutputStream pOut, long time) throws IOException { - pOut.write((byte)(time >> 24)); - pOut.write((byte)(time >> 16)); - pOut.write((byte)(time >> 8)); - pOut.write((byte)time); + StreamUtil.writeSeconds(pOut, time / 1000); + } + + static long readTime(BCPGInputStream in) + throws IOException + { + return readSeconds(in) * 1000L; + } + + static void writeSeconds(BCPGOutputStream pOut, long time) + throws IOException + { + StreamUtil.write4OctetLength(pOut, (int)time); + } + + static long readSeconds(BCPGInputStream in) + throws IOException + { + return ((long)read4OctetLength(in)) & 0xFFFFFFFFL; + } + + static void write2OctetLength(OutputStream pOut, int len) + throws IOException + { + pOut.write(len >> 8); + pOut.write(len); + } + + static int read2OctetLength(InputStream in) + throws IOException + { + return (in.read() << 8) | in.read(); + } + + static void write4OctetLength(OutputStream pOut, int len) + throws IOException + { + pOut.write(len >> 24); + pOut.write(len >> 16); + pOut.write(len >> 8); + pOut.write(len); + } + + static int read4OctetLength(InputStream in) + throws IOException + { + return (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); + } + + static int flag_eof = 0; + static int flag_isLongLength = 1; + static int flag_partial = 2; + /** + * Note: flags is an array of three boolean values: + * flags[0] indicates l is negative, flag for eof + * flags[1] indicates (is)longLength = true + * flags[2] indicate partial = true + */ + static int readBodyLen(InputStream in, boolean[] flags) + throws IOException + { + Arrays.fill(flags, false); + int l = in.read(); + int bodyLen = -1; + if (l < 0) + { + flags[flag_eof] = true; + } + if (l < 192) + { + bodyLen = l; + } + else if (l <= 223) + { + bodyLen = ((l - 192) << 8) + (in.read()) + 192; + } + else if (l == 255) + { + flags[flag_isLongLength] = true; + bodyLen = StreamUtil.read4OctetLength(in); + } + else + { + flags[flag_partial] = true; + bodyLen = 1 << (l & 0x1f); + } + return bodyLen; + } + + static void write8OctetLength(OutputStream pOut, long len) + throws IOException + { + pOut.write((int) (len >> 56)); + pOut.write((int) (len >> 48)); + pOut.write((int) (len >> 40)); + pOut.write((int) (len >> 32)); + pOut.write((int) (len >> 24)); + pOut.write((int) (len >> 16)); + pOut.write((int) (len >> 8)); + pOut.write((int) len); } + static long read8OctetLength(InputStream in) + throws IOException + { + return ((long) in.read() << 56) | + ((long) in.read() << 48) | + ((long) in.read() << 40) | + ((long) in.read() << 32) | + ((long) in.read() << 24) | + ((long) in.read() << 16) | + ((long) in.read() << 8) | + ((long) in.read()); + } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncDataPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncDataPacket.java index eeca55b97c..90cf34ece3 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncDataPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncDataPacket.java @@ -10,9 +10,16 @@ public class SymmetricEncDataPacket implements BCPGHeaderObject { public SymmetricEncDataPacket( - BCPGInputStream in) + BCPGInputStream in) { - super(in, SYMMETRIC_KEY_ENC); + this(in, false); + } + + public SymmetricEncDataPacket( + BCPGInputStream in, + boolean newPacketFormat) + { + super(in, SYMMETRIC_KEY_ENC, newPacketFormat); } public SymmetricEncDataPacket() diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncIntegrityPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncIntegrityPacket.java index d2f81746c1..79bc42357c 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncIntegrityPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricEncIntegrityPacket.java @@ -31,10 +31,18 @@ public class SymmetricEncIntegrityPacket byte[] salt; // V2 SymmetricEncIntegrityPacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + SymmetricEncIntegrityPacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(in, SYM_ENC_INTEGRITY_PRO); + super(in, SYM_ENC_INTEGRITY_PRO, newPacketFormat); version = in.read(); diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyAlgorithmTags.java b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyAlgorithmTags.java index 4004b31bd2..a587446988 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyAlgorithmTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyAlgorithmTags.java @@ -1,22 +1,75 @@ package org.bouncycastle.bcpg; /** - * Basic tags for symmetric key algorithms + * Basic tags for symmetric key algorithms. + * + * @see + * RFC9580 - Symmetric-Key Algorithms + * @see + * RFC4880 - Symmetric-Key Algorithms + * @see + * LibrePGP - Symmetric-Key Algorithms */ public interface SymmetricKeyAlgorithmTags { - int NULL = 0; // Plaintext or unencrypted data - int IDEA = 1; // IDEA [IDEA] - int TRIPLE_DES = 2; // Triple-DES (DES-EDE, as per spec -168 bit key derived from 192) - int CAST5 = 3; // CAST5 (128 bit key, as per RFC 2144) - int BLOWFISH = 4; // Blowfish (128 bit key, 16 rounds) [BLOWFISH] - int SAFER = 5; // SAFER-SK128 (13 rounds) [SAFER] - int DES = 6; // Reserved for DES/SK - int AES_128 = 7; // Reserved for AES with 128-bit key - int AES_192 = 8; // Reserved for AES with 192-bit key - int AES_256 = 9; // Reserved for AES with 256-bit key - int TWOFISH = 10; // Reserved for Twofish - int CAMELLIA_128 = 11; // Reserved for Camellia with 128-bit key - int CAMELLIA_192 = 12; // Reserved for Camellia with 192-bit key - int CAMELLIA_256 = 13; // Reserved for Camellia with 256-bit key + /** + * Plaintext or unencrypted data. + */ + int NULL = 0; + /** + * IDEA. + */ + int IDEA = 1; + /** + * Triple-DES (DES-EDE, as per spec - 168-bit key derived from 192). + */ + int TRIPLE_DES = 2; + /** + * CAST5 (128-bit key, as per RFC 2144). + */ + int CAST5 = 3; + /** + * Blowfish (128-bit key, 16 rounds). + */ + int BLOWFISH = 4; + /** + * Reserved for SAFER-SK128 (13 rounds). + */ + int SAFER = 5; + /** + * Reserved for DES/SK. + */ + int DES = 6; + /** + * AES with 128-bit key. + */ + int AES_128 = 7; + /** + * AES with 192-bit key. + */ + int AES_192 = 8; + /** + * AES with 256-bit key. + */ + int AES_256 = 9; + /** + * Twofish with 256-bit key. + */ + int TWOFISH = 10; + /** + * Camellia with 128-bit key. + */ + int CAMELLIA_128 = 11; + /** + * Camellia with 192-bit key. + */ + int CAMELLIA_192 = 12; + /** + * Camellia with 256-bit key. + */ + int CAMELLIA_256 = 13; + + // 100 to 110: Private/Experimental algorithms + + // 253, 254, 255 reserved to avoid collision with secret key encryption } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyEncSessionPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyEncSessionPacket.java index 25220f10b5..aef46b6f2a 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyEncSessionPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SymmetricKeyEncSessionPacket.java @@ -1,6 +1,5 @@ package org.bouncycastle.bcpg; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; @@ -19,6 +18,7 @@ public class SymmetricKeyEncSessionPacket /** * Version 5 SKESK packet. + * LibrePGP only. * Used only with {@link AEADEncDataPacket AED} packets. */ public static final int VERSION_5 = 5; @@ -43,7 +43,15 @@ public SymmetricKeyEncSessionPacket( BCPGInputStream in) throws IOException { - super(SYMMETRIC_KEY_ENC_SESSION); + this(in, false); + } + + public SymmetricKeyEncSessionPacket( + BCPGInputStream in, + boolean newPacketFormat) + throws IOException + { + super(SYMMETRIC_KEY_ENC_SESSION, newPacketFormat); version = in.read(); if (version == VERSION_4) @@ -56,27 +64,28 @@ public SymmetricKeyEncSessionPacket( } else if (version == VERSION_5 || version == VERSION_6) { - // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-5.3.2-3.2 - // SymAlg + AEADAlg + S2KCount + S2K + IV - int next5Fields5Count = in.read(); + int ivLen = 0; + if (version == VERSION_6) + { + // https://www.rfc-editor.org/rfc/rfc9580.html#section-5.3.2-3.2.1 + // SymAlg + AEADAlg + S2KCount + S2K + IV + ivLen = in.read(); // next5Fields5Count + } encAlgorithm = in.read(); aeadAlgorithm = in.read(); - - // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-5.3.2-3.5 - int s2kOctetCount = in.read(); - s2kBytes = new byte[s2kOctetCount]; - in.readFully(s2kBytes); - try + if (version == VERSION_6) { - s2k = new S2K(new ByteArrayInputStream(s2kBytes)); + // https://www.rfc-editor.org/rfc/rfc9580.html#section-5.3.2-3.5.1 + int s2kOctetCount = in.read(); + ivLen = ivLen - 3 - s2kOctetCount; } - catch (UnsupportedPacketVersionException e) + else { - - // We gracefully catch the error. + ivLen = AEADUtils.getIVLength(aeadAlgorithm); } - int ivLen = next5Fields5Count - 3 - s2kOctetCount; + s2k = new S2K(in); + iv = new byte[ivLen]; // also called nonce if (in.read(iv) != iv.length) { @@ -98,7 +107,6 @@ else if (version == VERSION_5 || version == VERSION_6) { throw new UnsupportedPacketVersionException("Unsupported PGP symmetric-key encrypted session key packet version encountered: " + version); } - } /** @@ -329,14 +337,21 @@ public void encode( pOut.write(secKeyData); } } - else if (version == VERSION_5 || version == VERSION_6) + else { - int s2kLen = s2k.getEncoded().length; - int count = 1 + 1 + 1 + s2kLen + iv.length; - pOut.write(count); // len of 5 following fields + int s2kLen = 0; + if (version == VERSION_6) + { + s2kLen = s2k.getEncoded().length; + int count = 1 + 1 + 1 + s2kLen + iv.length; + pOut.write(count); // len of 5 following fields + } pOut.write(encAlgorithm); pOut.write(aeadAlgorithm); - pOut.write(s2kLen); + if (version == VERSION_6) + { + pOut.write(s2kLen); + } pOut.writeObject(s2k); pOut.write(iv); @@ -349,6 +364,6 @@ else if (version == VERSION_5 || version == VERSION_6) pOut.close(); - out.writePacket(SYMMETRIC_KEY_ENC_SESSION, bOut.toByteArray()); + out.writePacket(hasNewPacketFormat(), SYMMETRIC_KEY_ENC_SESSION, bOut.toByteArray()); } -} +} \ No newline at end of file diff --git a/pg/src/main/java/org/bouncycastle/bcpg/TrustPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/TrustPacket.java index a009240504..db920ec297 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/TrustPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/TrustPacket.java @@ -10,12 +10,20 @@ public class TrustPacket extends ContainedPacket { byte[] levelAndTrustAmount; - + public TrustPacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + public TrustPacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(TRUST); + super(TRUST, newPacketFormat); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; @@ -47,6 +55,6 @@ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(TRUST, levelAndTrustAmount); + out.writePacket(hasNewPacketFormat(), TRUST, levelAndTrustAmount); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UnknownBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/UnknownBCPGKey.java new file mode 100644 index 0000000000..27eefece3e --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/UnknownBCPGKey.java @@ -0,0 +1,21 @@ +package org.bouncycastle.bcpg; + +import java.io.IOException; + +/** + * Key class for unknown/unsupported OpenPGP key types. + */ +public class UnknownBCPGKey + extends OctetArrayBCPGKey +{ + public UnknownBCPGKey(int length, BCPGInputStream in) + throws IOException + { + super(length, in); + } + + public UnknownBCPGKey(int length, byte[] key) + { + super(length, key); + } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UnknownPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/UnknownPacket.java index 80fbfb4dff..5f11541625 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/UnknownPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/UnknownPacket.java @@ -12,7 +12,13 @@ public class UnknownPacket public UnknownPacket(int tag, BCPGInputStream in) throws IOException { - super(tag); + this(tag, in, false); + } + + public UnknownPacket(int tag, BCPGInputStream in, boolean newPacketFormat) + throws IOException + { + super(tag, newPacketFormat); this.contents = in.readAll(); } @@ -26,6 +32,6 @@ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(getPacketTag(), contents); + out.writePacket(hasNewPacketFormat(), getPacketTag(), contents); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UserAttributePacket.java b/pg/src/main/java/org/bouncycastle/bcpg/UserAttributePacket.java index e87a36a7fe..d0b099cfb7 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/UserAttributePacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/UserAttributePacket.java @@ -11,12 +11,20 @@ public class UserAttributePacket extends ContainedPacket { private UserAttributeSubpacket[] subpackets; - + public UserAttributePacket( - BCPGInputStream in) + BCPGInputStream in) + throws IOException + { + this(in, false); + } + + public UserAttributePacket( + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(USER_ATTRIBUTE); + super(USER_ATTRIBUTE, newPacketFormat); UserAttributeSubpacketInputStream sIn = new UserAttributeSubpacketInputStream(in); UserAttributeSubpacket sub; @@ -59,6 +67,6 @@ public void encode( subpackets[i].encode(bOut); } - out.writePacket(USER_ATTRIBUTE, bOut.toByteArray()); + out.writePacket(hasNewPacketFormat(), USER_ATTRIBUTE, bOut.toByteArray()); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketInputStream.java b/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketInputStream.java index 2b1ed0d195..dfc33988f6 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketInputStream.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketInputStream.java @@ -10,111 +10,97 @@ * reader for user attribute sub-packets */ public class UserAttributeSubpacketInputStream - extends InputStream implements UserAttributeSubpacketTags + extends InputStream + implements UserAttributeSubpacketTags { - InputStream in; - + InputStream in; + public UserAttributeSubpacketInputStream( - InputStream in) + InputStream in) { this.in = in; } - + public int available() throws IOException { return in.available(); } - + public int read() throws IOException { return in.read(); } - + private void readFully( - byte[] buf, - int off, - int len) + byte[] buf, + int off, + int len) throws IOException { if (len > 0) { - int b = this.read(); - + int b = this.read(); + if (b < 0) { throw new EOFException(); } - + buf[off] = (byte)b; off++; len--; } - + while (len > 0) { - int l = in.read(buf, off, len); - + int l = in.read(buf, off, len); + if (l < 0) { throw new EOFException(); } - + off += l; len -= l; } } - + public UserAttributeSubpacket readPacket() throws IOException { - int l = this.read(); - int bodyLen = 0; - boolean longLength = false; - - if (l < 0) + boolean[] flags = new boolean[3]; + int bodyLen = StreamUtil.readBodyLen(this, flags); + if (flags[StreamUtil.flag_eof]) { return null; } - - if (l < 192) - { - bodyLen = l; - } - else if (l <= 223) + else if (flags[StreamUtil.flag_partial]) { - bodyLen = ((l - 192) << 8) + (in.read()) + 192; - } - else if (l == 255) - { - bodyLen = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); - longLength = true; + throw new IOException("unrecognised length reading user attribute sub packet"); } - else + boolean longLength = flags[StreamUtil.flag_isLongLength]; + + int tag = in.read(); + + if (tag < 0) { - throw new IOException("unrecognised length reading user attribute sub packet"); + throw new EOFException("unexpected EOF reading user attribute sub packet"); } - int tag = in.read(); + byte[] data = new byte[bodyLen - 1]; - if (tag < 0) - { - throw new EOFException("unexpected EOF reading user attribute sub packet"); - } - - byte[] data = new byte[bodyLen - 1]; + this.readFully(data, 0, data.length); - this.readFully(data, 0, data.length); - - int type = tag; + int type = tag; - switch (type) - { - case IMAGE_ATTRIBUTE: - return new ImageAttribute(longLength, data); - } + switch (type) + { + case IMAGE_ATTRIBUTE: + return new ImageAttribute(longLength, data); + } - return new UserAttributeSubpacket(type, longLength, data); + return new UserAttributeSubpacket(type, longLength, data); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketTags.java b/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketTags.java index 7a0e7b7607..7566673225 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/UserAttributeSubpacketTags.java @@ -2,8 +2,16 @@ /** * Basic PGP user attribute sub-packet tag types. + * + * @see + * RFC4880 - User Attribute Packet + * @see + * RFC9580 - User Attribute Packet */ public interface UserAttributeSubpacketTags { + /** + * Tag for an {@link org.bouncycastle.bcpg.attr.ImageAttribute}. + */ int IMAGE_ATTRIBUTE = 1; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UserDataPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/UserDataPacket.java index 2e91fd4a8f..f7564b66ea 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/UserDataPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/UserDataPacket.java @@ -1,5 +1,9 @@ package org.bouncycastle.bcpg; +/** + * Superclass for user identities ({@link UserIDPacket}, {@link UserAttributePacket}). + * The superclass is used to hold different user identity objects in the same collection. + */ public interface UserDataPacket { diff --git a/pg/src/main/java/org/bouncycastle/bcpg/UserIDPacket.java b/pg/src/main/java/org/bouncycastle/bcpg/UserIDPacket.java index 0cd550352d..7256e1466b 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/UserIDPacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/UserIDPacket.java @@ -13,12 +13,20 @@ public class UserIDPacket implements UserDataPacket { private byte[] idData; - + + public UserIDPacket( + BCPGInputStream in) + throws IOException + { + this(in, false); + } + public UserIDPacket( - BCPGInputStream in) + BCPGInputStream in, + boolean newPacketFormat) throws IOException { - super(USER_ID); + super(USER_ID, newPacketFormat); this.idData = in.readAll(); } @@ -67,6 +75,6 @@ public void encode( BCPGOutputStream out) throws IOException { - out.writePacket(USER_ID, idData); + out.writePacket(hasNewPacketFormat(), USER_ID, idData); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/X25519PublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/X25519PublicBCPGKey.java index 298ebd9098..1ce252b2ba 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/X25519PublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/X25519PublicBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Public key of type {@link PublicKeyAlgorithmTags#X25519}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link ECDHPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#ECDH}. + * + * @see + * OpenPGP - Algorithm-Specific Part for X25519 Keys + */ public class X25519PublicBCPGKey extends OctetArrayBCPGKey { + // 32 octets of the native public key public static final int LENGTH = 32; public X25519PublicBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/X25519SecretBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/X25519SecretBCPGKey.java index 81f54a77c0..8bba9a1228 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/X25519SecretBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/X25519SecretBCPGKey.java @@ -2,9 +2,22 @@ import java.io.IOException; +/** + * Secret key of type {@link PublicKeyAlgorithmTags#X25519}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link ECSecretBCPGKey} with + * {@link PublicKeyAlgorithmTags#ECDH}. + * Note: Contrary to {@link ECSecretBCPGKey} using {@link PublicKeyAlgorithmTags#ECDH}, which uses big-endian + * MPI encoding to encode the secret key material, {@link X25519SecretBCPGKey} uses native little-endian encoding. + * + * @see + * OpenPGP - Algorithm-Specific Part for X25519 Keys + */ public class X25519SecretBCPGKey extends OctetArrayBCPGKey { + // 32 octets of the native secret key public static final int LENGTH = 32; public X25519SecretBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/X448PublicBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/X448PublicBCPGKey.java index 48b88cf211..b3fb71496b 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/X448PublicBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/X448PublicBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Public key of type {@link PublicKeyAlgorithmTags#X448}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link ECDHPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#ECDH}. + * + * @see + * OpenPGP - Algorithm-Specific Part for X448 Keys + */ public class X448PublicBCPGKey extends OctetArrayBCPGKey { + // 56 octets of the native public key public static final int LENGTH = 56; public X448PublicBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/X448SecretBCPGKey.java b/pg/src/main/java/org/bouncycastle/bcpg/X448SecretBCPGKey.java index 65140dc8f5..b3dad65360 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/X448SecretBCPGKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/X448SecretBCPGKey.java @@ -2,9 +2,20 @@ import java.io.IOException; +/** + * Secret key of type {@link PublicKeyAlgorithmTags#X448}. + * This type was introduced with RFC9580 and can be used with v4, v6 keys. + * Note however, that legacy implementations might not understand this key type yet. + * For a key type compatible with legacy v4 implementations, see {@link ECDHPublicBCPGKey} with + * {@link PublicKeyAlgorithmTags#ECDH}. + * + * @see + * OpenPGP - Algorithm-Specific Part for X448 Keys + */ public class X448SecretBCPGKey extends OctetArrayBCPGKey { + // 56 octets of the native secret key public static final int LENGTH = 56; public X448SecretBCPGKey(BCPGInputStream in) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/attr/ImageAttribute.java b/pg/src/main/java/org/bouncycastle/bcpg/attr/ImageAttribute.java index 467f501585..437d33ba42 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/attr/ImageAttribute.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/attr/ImageAttribute.java @@ -7,7 +7,12 @@ import org.bouncycastle.bcpg.UserAttributeSubpacketTags; /** - * Basic type for a image attribute packet. + * User-Attribute Subpacket used to encode an image, e.g. the user's avatar. + * + * @see + * RFC4880 - Image Attribute Subpacket + * @see + * RFC9580 - Image Attribute Subpacket */ public class ImageAttribute extends UserAttributeSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/attr/package-info.java b/pg/src/main/java/org/bouncycastle/bcpg/attr/package-info.java new file mode 100644 index 0000000000..6ad500cd6a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/attr/package-info.java @@ -0,0 +1,4 @@ +/** + * Low level classes for dealing with OpenPGP user attributes. + */ +package org.bouncycastle.bcpg.attr; diff --git a/pg/src/main/java/org/bouncycastle/bcpg/package-info.java b/pg/src/main/java/org/bouncycastle/bcpg/package-info.java new file mode 100644 index 0000000000..a36cbc3160 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/package-info.java @@ -0,0 +1,8 @@ +/** + * Low level classes for dealing with OpenPGP objects. + *

      + * These classes deal with things at a raw OpenPGP packet level. For the most part + * you are probably better off looking at the org.bouncycastle.openpgp package + * for what you want. + */ +package org.bouncycastle.bcpg; diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/EmbeddedSignature.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/EmbeddedSignature.java index 821882cc28..55e65bed26 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/EmbeddedSignature.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/EmbeddedSignature.java @@ -4,7 +4,15 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * Packet embedded signature + * Signature Subpacket for embedding one Signature into another. + * This packet is used e.g. for embedding a primary-key binding signature + * ({@link org.bouncycastle.openpgp.PGPSignature#PRIMARYKEY_BINDING}) into a subkey-binding signature + * ({@link org.bouncycastle.openpgp.PGPSignature#SUBKEY_BINDING}) for a signing-capable subkey. + * + * @see + * RFC4880 - Embedded Signature + * @see + * RFC9580 - Embedded Signature */ public class EmbeddedSignature extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/Exportable.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/Exportable.java index e5160edf72..6956f65ef8 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/Exportable.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/Exportable.java @@ -4,7 +4,13 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving signature creation time. + * Signature Subpacket for marking a signature as exportable or non-exportable. + * Non-exportable signatures are not intended to be published. + * + * @see + * RFC4880 - Exportable Certification + * @see + * RFC9580 - Exportable Certification */ public class Exportable extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/Features.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/Features.java index e47bcc1e9e..3189d63975 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/Features.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/Features.java @@ -3,6 +3,14 @@ import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; +/** + * Signature Subpacket encoding, which features are supported by the key-holders implementation. + * + * @see + * RFC4880 - Features + * @see + * RFC9580 - Features + */ public class Features extends SignatureSubpacket { diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/IntendedRecipientFingerprint.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/IntendedRecipientFingerprint.java index b1d61421f5..dfc3d2c34d 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/IntendedRecipientFingerprint.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/IntendedRecipientFingerprint.java @@ -1,11 +1,16 @@ package org.bouncycastle.bcpg.sig; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.util.Arrays; /** - * packet giving the intended recipient fingerprint. + * Signature Subpacket containing the fingerprint of the intended recipients primary key. + * This packet can be used to prevent malicious forwarding/replay attacks. + * + * @see + * RFC9580 - Intended Recipient Fingerprint */ public class IntendedRecipientFingerprint extends SignatureSubpacket @@ -36,4 +41,9 @@ public byte[] getFingerprint() { return Arrays.copyOfRange(data, 1, data.length); } + + public KeyIdentifier getKeyIdentifier() + { + return new KeyIdentifier(getFingerprint()); + } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerFingerprint.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerFingerprint.java index 8432acb5e7..7837c93a77 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerFingerprint.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerFingerprint.java @@ -1,11 +1,18 @@ package org.bouncycastle.bcpg.sig; +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.util.Arrays; /** - * packet giving the issuer key fingerprint. + * Signature Subpacket containing the fingerprint of the issuers signing (sub-) key. + * This packet supersedes the {@link IssuerKeyID} subpacket. + * + * @see + * RFC9580 - Issuer Fingerprint */ public class IssuerFingerprint extends SignatureSubpacket @@ -36,4 +43,26 @@ public byte[] getFingerprint() { return Arrays.copyOfRange(data, 1, data.length); } + + public long getKeyID() + { + if (getKeyVersion() == PublicKeyPacket.VERSION_4) + { + return FingerprintUtil.keyIdFromV4Fingerprint(getFingerprint()); + } + if (getKeyVersion() == PublicKeyPacket.LIBREPGP_5) + { + return FingerprintUtil.keyIdFromLibrePgpFingerprint(getFingerprint()); + } + if (getKeyVersion() == PublicKeyPacket.VERSION_6) + { + return FingerprintUtil.keyIdFromV6Fingerprint(getFingerprint()); + } + return 0; + } + + public KeyIdentifier getKeyIdentifier() + { + return new KeyIdentifier(getFingerprint()); + } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerKeyID.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerKeyID.java index 737914cdfe..df12540c3a 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerKeyID.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/IssuerKeyID.java @@ -1,10 +1,19 @@ package org.bouncycastle.bcpg.sig; +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving the issuer key ID. + * Signature Subpacket containing the key-id of the issuers signing (sub-) key. + * If the version of that key is greater than 4, this subpacket MUST NOT be included in the signature. + * For these keys, consider the {@link IssuerFingerprint} subpacket instead. + * + * @see + * RFC4880 - Issuer + * @see + * RFC9580 - Issuer Key ID */ public class IssuerKeyID extends SignatureSubpacket @@ -13,16 +22,7 @@ protected static byte[] keyIDToBytes( long keyId) { byte[] data = new byte[8]; - - data[0] = (byte)(keyId >> 56); - data[1] = (byte)(keyId >> 48); - data[2] = (byte)(keyId >> 40); - data[3] = (byte)(keyId >> 32); - data[4] = (byte)(keyId >> 24); - data[5] = (byte)(keyId >> 16); - data[6] = (byte)(keyId >> 8); - data[7] = (byte)keyId; - + FingerprintUtil.writeKeyID(keyId, data); return data; } @@ -43,9 +43,11 @@ public IssuerKeyID( public long getKeyID() { - long keyID = ((long)(data[0] & 0xff) << 56) | ((long)(data[1] & 0xff) << 48) | ((long)(data[2] & 0xff) << 40) | ((long)(data[3] & 0xff) << 32) - | ((long)(data[4] & 0xff) << 24) | ((data[5] & 0xff) << 16) | ((data[6] & 0xff) << 8) | (data[7] & 0xff); - - return keyID; + return FingerprintUtil.readKeyID(data); + } + + public KeyIdentifier getKeyIdentifier() + { + return new KeyIdentifier(getKeyID()); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyExpirationTime.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyExpirationTime.java index e618720b59..1b746ef4ba 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyExpirationTime.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyExpirationTime.java @@ -4,7 +4,13 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving time after creation at which the key expires. + * Signature Subpacket containing the number of seconds after the key's creation date, after which the key expires. + * The special value of {@code 0} means that the key never expires. + * + * @see + * RFC4880 - Key Expiration Time + * @see + * RFC9580 - Key Expiration Time */ public class KeyExpirationTime extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyFlags.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyFlags.java index 06cb7833cb..a92b975f6d 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyFlags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/KeyFlags.java @@ -4,17 +4,50 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * Packet holding the key flag values. + * Signature Subpacket encoding the capabilities / intended uses of a key. + * + * @see + * RFC4880 - Key Flags + * @see + * RFC9580 - Key Flags */ public class KeyFlags extends SignatureSubpacket { + /** + * This key may be used to make User ID certifications (signature type IDs 0x10-0x13) + * or direct key signatures (signature type ID 0x1F) over other peoples keys. + */ public static final int CERTIFY_OTHER = 0x01; + + /** + * This key may be used to sign data. + */ public static final int SIGN_DATA = 0x02; + + /** + * This key may be used to encrypt communications. + */ public static final int ENCRYPT_COMMS = 0x04; + + /** + * This key may be used to encrypt storage. + */ public static final int ENCRYPT_STORAGE = 0x08; + + /** + * The private component of this key may have been split by a secret-sharing mechanism. + */ public static final int SPLIT = 0x10; + + /** + * This key may be used for authentication. + */ public static final int AUTHENTICATION = 0x20; + + /** + * The private component of this key may be in the possession of more than one person. + */ public static final int SHARED = 0x80; private static byte[] intToByteArray( diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/LibrePGPPreferredEncryptionModes.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/LibrePGPPreferredEncryptionModes.java new file mode 100644 index 0000000000..bfc6c5e950 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/LibrePGPPreferredEncryptionModes.java @@ -0,0 +1,23 @@ +package org.bouncycastle.bcpg.sig; + +import org.bouncycastle.bcpg.SignatureSubpacketTags; + +/** + * This is a deprecated LibrePGP signature subpacket with encryption mode numbers to indicate which modes + * the key holder prefers to use with OCB Encrypted Data Packets ({@link org.bouncycastle.bcpg.AEADEncDataPacket}). + * Implementations SHOULD ignore this subpacket and assume {@link org.bouncycastle.bcpg.AEADAlgorithmTags#OCB}. + */ +public class LibrePGPPreferredEncryptionModes + extends PreferredAlgorithms +{ + + public LibrePGPPreferredEncryptionModes(boolean isCritical, int[] encryptionModes) + { + this(isCritical, false, intToByteArray(encryptionModes)); + } + + public LibrePGPPreferredEncryptionModes(boolean critical, boolean isLongLength, byte[] data) + { + super(SignatureSubpacketTags.LIBREPGP_PREFERRED_ENCRYPTION_MODES, critical, isLongLength, data); + } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/NotationData.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/NotationData.java index b7bcd3c68f..b1c4e970d7 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/NotationData.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/NotationData.java @@ -7,8 +7,13 @@ import org.bouncycastle.util.Strings; /** - * Class provided a NotationData object according to - * RFC2440, Chapter 5.2.3.15. Notation Data + * Signature Subpacket encoding custom notations. + * Notations are key-value pairs. + * + * @see + * RFC4880 - Notation Data + * @see + * RFC9580 - Notation Data */ public class NotationData extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/PolicyURI.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/PolicyURI.java index 58878eb4e2..235c85e1ad 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/PolicyURI.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/PolicyURI.java @@ -5,6 +5,15 @@ import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; +/** + * Signature Subpacket for encoding a URI pointing to a document containing the policy under which the + * signature was created. + * + * @see + * RFC4880 - Policy URI + * @see + * RFC9580 - Policy URI + */ public class PolicyURI extends SignatureSubpacket { diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAEADCiphersuites.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAEADCiphersuites.java index 1ed5ae9001..d99a01e9fa 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAEADCiphersuites.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAEADCiphersuites.java @@ -1,9 +1,19 @@ package org.bouncycastle.bcpg.sig; +import java.util.ArrayList; +import java.util.List; + import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +/** + * Signature Subpacket containing the AEAD cipher suites (AEAD algorithm, Symmetric Key Algorithm pairs) + * preferred by the key holder's implementation. + * + * @see + * OpenPGP - Preferred AEAD Ciphersuites + */ public class PreferredAEADCiphersuites extends PreferredAlgorithms { @@ -13,11 +23,18 @@ public class PreferredAEADCiphersuites /** * AES-128 + OCB is a MUST implement and is therefore implicitly supported. * - * @see - * Crypto-Refresh § 5.2.3.15. Preferred AEAD Ciphersuites + * @see + * OpenPGP - Preferred AEAD Ciphersuites + * @see + * OpenPGP - Preferred AEAD Ciphersuites */ private static final Combination AES_128_OCB = new Combination(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.OCB); + public static PreferredAEADCiphersuites DEFAULT() + { + return new PreferredAEADCiphersuites(false, new Combination[]{AES_128_OCB}); + } + /** * Create a new PreferredAEADAlgorithms signature subpacket from raw data. * @@ -144,6 +161,51 @@ private static byte[] requireEven(byte[] encodedCombinations) return encodedCombinations; } + /** + * Return a {@link Builder} for constructing a {@link PreferredAEADCiphersuites} packet. + * @param isCritical true if the packet is considered critical. + * @return builder + */ + public static Builder builder(boolean isCritical) + { + return new Builder(isCritical); + } + + public static final class Builder + { + + private final List combinations = new ArrayList(); + private final boolean isCritical; + + private Builder(boolean isCritical) + { + this.isCritical = isCritical; + } + + /** + * Add a combination of cipher- and AEAD algorithm to the list of supported ciphersuites. + * @see SymmetricKeyAlgorithmTags for cipher algorithms + * @see AEADAlgorithmTags for AEAD algorithms + * @param symmetricAlgorithmId symmetric cipher algorithm ID + * @param aeadAlgorithmId AEAD algorithm ID + * @return builder + */ + public Builder addCombination(int symmetricAlgorithmId, int aeadAlgorithmId) + { + combinations.add(new Combination(symmetricAlgorithmId, aeadAlgorithmId)); + return this; + } + + /** + * Build a {@link PreferredAEADCiphersuites} from this builder. + * @return finished packet + */ + public PreferredAEADCiphersuites build() + { + return new PreferredAEADCiphersuites(isCritical, (Combination[])combinations.toArray(new Combination[0])); + } + } + /** * Algorithm combination of a {@link SymmetricKeyAlgorithmTags} and a {@link AEADAlgorithmTags}. */ diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAlgorithms.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAlgorithms.java index 16072bae79..a31aeb7c31 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAlgorithms.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredAlgorithms.java @@ -3,12 +3,31 @@ import org.bouncycastle.bcpg.SignatureSubpacket; /** - * packet giving signature creation time. + * Signature Subpacket containing algorithm preferences of the key holder's implementation. + * This class is used to implement: + *

        + *
      • Preferred Hash Algorithms
      • + *
      • Preferred Symmetric Key Algorithms
      • + *
      • Preferred Compression Algorithms
      • + *
      + * + * @see + * RFC9580 - Preferred Symmetric Ciphers for v1 SEIPD + * @see + * RFC9580 - Preferred Hash Algorithms + * @see + * RFC9580 - Preferred Compression Algorithms + * @see + * RFC4880 - Preferred Symmetric Algorithms + * @see + * RFC4880 - Preferred Hash Algorithms + * @see + * RFC4880 - Preferred Compression Algorithms */ public class PreferredAlgorithms extends SignatureSubpacket { - private static byte[] intToByteArray( + protected static byte[] intToByteArray( int[] v) { byte[] data = new byte[v.length]; diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredKeyServer.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredKeyServer.java new file mode 100644 index 0000000000..1be95a8892 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/PreferredKeyServer.java @@ -0,0 +1,46 @@ +package org.bouncycastle.bcpg.sig; + +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +/** + * Signature Subpacket containing the URI of the users preferred key server. + * This is a URI of a key server that the key holder prefers be used for updates. + * Note that keys with multiple User IDs can have a preferred key server for each User ID. + * Note also that since this is a URI, the key server can actually be a copy of the key + * retrieved by ftp, http, finger, etc. + * + * @see + * RFC4880 - Preferred Key Server + * @see + * RFC9580 - Preferred Key Server + */ +public class PreferredKeyServer + extends SignatureSubpacket +{ + public PreferredKeyServer(boolean critical, boolean isLongLength, byte[] data) + { + super(SignatureSubpacketTags.PREFERRED_KEY_SERV, critical, isLongLength, data); + } + + public PreferredKeyServer(boolean critical, String uri) + { + this(critical, false, Strings.toUTF8ByteArray(uri)); + } + + /** + * Return the URI of the users preferred key server. + * @return key server uri + */ + public String getURI() + { + return Strings.fromUTF8ByteArray(data); + } + + public byte[] getRawURI() + { + return Arrays.clone(data); + } +} diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/PrimaryUserID.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/PrimaryUserID.java index 53ac5ec829..776c5c9fca 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/PrimaryUserID.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/PrimaryUserID.java @@ -4,7 +4,12 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving whether or not the signature is signed using the primary user ID for the key. + * Signature Subpacket marking a User ID as primary. + * + * @see + * RFC4880 - Primary User ID + * @see + * RFC9580 - Primary User ID */ public class PrimaryUserID extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/RegularExpression.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/RegularExpression.java index eeea06b14c..c780011a8a 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/RegularExpression.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/RegularExpression.java @@ -6,7 +6,13 @@ import org.bouncycastle.util.Strings; /** - * Regexp Packet - RFC 4880 5.2.3.14. Note: the RFC says the byte encoding is to be null terminated. + * Signature Subpacket containing a regular expression limiting the scope of the signature. + * Note: the RFC says the byte encoding is to be null terminated. + * + * @see + * RFC4880 - Regular Expression + * @see + * RFC9580 - Regular Expression */ public class RegularExpression extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/Revocable.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/Revocable.java index 8ac92b50f1..dde5f95830 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/Revocable.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/Revocable.java @@ -4,7 +4,12 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving whether or not is revocable. + * Signature Subpacket marking a signature as non-revocable. + * + * @see + * RFC4880 - Revocable + * @see + * RFC9580 - Revocable */ public class Revocable extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKey.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKey.java index f9187e8c10..4c0960fc64 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKey.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKey.java @@ -1,12 +1,21 @@ package org.bouncycastle.bcpg.sig; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; /** * Represents revocation key OpenPGP signature sub packet. + * Note: This packet is deprecated. Applications MUST NOT generate such a packet. + * + * @see + * RFC4880 - Revocation Key + * @see + * RFC9580 - Revocation Key + * @deprecated since RFC9580 */ -public class RevocationKey extends SignatureSubpacket +public class RevocationKey + extends SignatureSubpacket { // 1 octet of class, // 1 octet of public-key algorithm ID, @@ -47,4 +56,9 @@ public byte[] getFingerprint() System.arraycopy(data, 2, fingerprint, 0, fingerprint.length); return fingerprint; } + + public KeyIdentifier getKeyIdentifier() + { + return new KeyIdentifier(getFingerprint()); + } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKeyTags.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKeyTags.java index a899c88a99..8cc79d9f48 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKeyTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationKeyTags.java @@ -1,8 +1,20 @@ package org.bouncycastle.bcpg.sig; +/** + * Revocation Key Class values. + * + * @see + * RFC4880 - Revocation Key + * @see + * RFC9580 - Revocation Key + */ public interface RevocationKeyTags { byte CLASS_DEFAULT = (byte)0x80; + + /** + * The revocation information is sensitive. + */ byte CLASS_SENSITIVE = (byte)0x40; } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReason.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReason.java index 34d9249e36..91634e79e1 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReason.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReason.java @@ -5,7 +5,12 @@ import org.bouncycastle.util.Strings; /** - * Represents revocation reason OpenPGP signature sub packet. + * Signature Subpacket for encoding the reason why a key was revoked. + * + * @see + * RFC4880 - Reason for Revocation + * @see + * RFC9580 - Reason for Revocation */ public class RevocationReason extends SignatureSubpacket { diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReasonTags.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReasonTags.java index e2741c0159..9210a07569 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReasonTags.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/RevocationReasonTags.java @@ -1,5 +1,13 @@ package org.bouncycastle.bcpg.sig; +/** + * Revocation reason tags. + * + * @see + * RFC4880 - Reason for Revocation + * @see + * RFC9580 - Reason for Revocation + */ public interface RevocationReasonTags { byte NO_REASON = 0; // No reason specified (key revocations or cert revocations) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureCreationTime.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureCreationTime.java index deeebae46c..3534b04434 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureCreationTime.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureCreationTime.java @@ -6,7 +6,12 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving signature creation time. + * Signature Subpacket containing the time at which the signature was created. + * + * @see + * RFC4880 - Signature Creation Time + * @see + * RFC9580 - Signature Creation Time */ public class SignatureCreationTime extends SignatureSubpacket @@ -36,6 +41,12 @@ public SignatureCreationTime( super(SignatureSubpacketTags.CREATION_TIME, critical, false, timeToBytes(date)); } + public SignatureCreationTime( + Date date) + { + this(true, date); + } + public Date getTime() { long time = Utils.timeFromBytes(data); diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureExpirationTime.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureExpirationTime.java index 4065985018..d89d86c10e 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureExpirationTime.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureExpirationTime.java @@ -4,7 +4,13 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving signature expiration time. + * Signature Subpacket containing the number of seconds after the signatures creation + * time after which the signature expires. + * + * @see + * RFC4880 - Signature Expiration Time + * @see + * RFC9580 - Signature Expiration Time */ public class SignatureExpirationTime extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureTarget.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureTarget.java index d8f49cbd5c..d436c0629c 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureTarget.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignatureTarget.java @@ -5,7 +5,12 @@ import org.bouncycastle.util.Arrays; /** - * RFC 4880, Section 5.2.3.25 - Signature Target subpacket. + * Signature Subpacket containing the hash value of another signature to which this signature applies to. + * + * @see + * RFC4880 - Signature Target + * @see + * RFC9580 - Signature Target */ public class SignatureTarget extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignerUserID.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignerUserID.java index ad0fc62eb5..9da8faf6dc 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/SignerUserID.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/SignerUserID.java @@ -6,7 +6,12 @@ import org.bouncycastle.util.Strings; /** - * packet giving the User ID of the signer. + * Signature Subpacket containing the User ID of the identity as which the issuer created the signature. + * + * @see + * RFC4880 - Signer's User ID + * @see + * RFC9580 - Signer's User ID */ public class SignerUserID extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/TrustSignature.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/TrustSignature.java index 1eb5c640c8..ef798d63b1 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/TrustSignature.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/TrustSignature.java @@ -4,7 +4,12 @@ import org.bouncycastle.bcpg.SignatureSubpacketTags; /** - * packet giving trust. + * Signature Subpacket encoding the level and amount of trust the issuer places into the certified key or identity. + * + * @see + * RFC4880 - Trust Packet + * @see + * RFC9580 - Trust Signature */ public class TrustSignature extends SignatureSubpacket diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/Utils.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/Utils.java index 074a38760b..3189049ffd 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/sig/Utils.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/Utils.java @@ -1,5 +1,7 @@ package org.bouncycastle.bcpg.sig; +import org.bouncycastle.util.Pack; + class Utils { /** @@ -55,19 +57,11 @@ static long timeFromBytes(byte[] bytes) throw new IllegalStateException("Byte array has unexpected length. Expected length 4, got " + bytes.length); } - return ((long)(bytes[0] & 0xff) << 24) - | ((bytes[1] & 0xff) << 16) - | ((bytes[2] & 0xff) << 8) - | (bytes[3] & 0xff); + return Pack.bigEndianToInt(bytes, 0) & 0xFFFFFFFFL; // time is unsigned } static byte[] timeToBytes(long t) { - byte[] data = new byte[4]; - data[0] = (byte)(t >> 24); - data[1] = (byte)(t >> 16); - data[2] = (byte)(t >> 8); - data[3] = (byte)t; - return data; + return Pack.intToBigEndian((int)t); } } diff --git a/pg/src/main/java/org/bouncycastle/bcpg/sig/package-info.java b/pg/src/main/java/org/bouncycastle/bcpg/sig/package-info.java new file mode 100644 index 0000000000..c874167947 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/bcpg/sig/package-info.java @@ -0,0 +1,4 @@ +/** + * Low level classes for dealing with OpenPGP signature attributes. + */ +package org.bouncycastle.bcpg.sig; diff --git a/pg/src/main/java/org/bouncycastle/gpg/SExpression.java b/pg/src/main/java/org/bouncycastle/gpg/SExpression.java index b9c57c2455..f35ed24c2e 100644 --- a/pg/src/main/java/org/bouncycastle/gpg/SExpression.java +++ b/pg/src/main/java/org/bouncycastle/gpg/SExpression.java @@ -104,6 +104,10 @@ private static SExpression parseExpression(InputStream src, SExpression expr, By if (c == ':') { + if (expr == null) + { + throw new IOException("invalid input stream at ':'"); + } try { int len = Integer.parseInt(Strings.fromByteArray(accumulator.toByteArray())); @@ -144,6 +148,11 @@ private static SExpression parseExpression(InputStream src, SExpression expr, By if (accumulator.size() > 0) { + if (expr == null) + { + throw new IOException("invalid input stream"); + } + expr.addValue(Strings.fromByteArray(accumulator.toByteArray())); } @@ -164,11 +173,19 @@ private static SExpression parseExpression(InputStream src, SExpression expr, By } else if (c == '#') { + if (expr == null) + { + throw new IOException("invalid input stream at '#'"); + } consumeUntilSkipWhiteSpace(src, accumulator, '#'); - expr.addValue(Hex.decode(Strings.fromByteArray(accumulator.toByteArray()))); + expr.addValue(Hex.decode(accumulator.toByteArray())); } else if (c == '"') { + if (expr == null) + { + throw new IOException("invalid input stream at '\"'"); + } consumeUntilSkipCRorLF(src, accumulator, '"'); expr.addValue(new SExpression.QuotedString(Strings.fromByteArray(accumulator.toByteArray()))); } diff --git a/pg/src/main/java/org/bouncycastle/gpg/SXprUtils.java b/pg/src/main/java/org/bouncycastle/gpg/SXprUtils.java index 5f0a699504..d78dabb3ef 100644 --- a/pg/src/main/java/org/bouncycastle/gpg/SXprUtils.java +++ b/pg/src/main/java/org/bouncycastle/gpg/SXprUtils.java @@ -1,5 +1,6 @@ package org.bouncycastle.gpg; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -51,7 +52,10 @@ static byte[] readBytes(InputStream in, int ch) byte[] data = new byte[len]; - Streams.readFully(in, data); + if (len != Streams.readFully(in, data)) + { + throw new EOFException(); + } return data; } @@ -95,7 +99,7 @@ static void skipCloseParenthesis(InputStream in) int ch = in.read(); if (ch != ')') { - throw new IOException("unknown character encountered"); + throw new IOException("unknown character encountered: " + (char)ch); } } } diff --git a/pg/src/main/java/org/bouncycastle/gpg/keybox/package-info.java b/pg/src/main/java/org/bouncycastle/gpg/keybox/package-info.java new file mode 100644 index 0000000000..875a411c44 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/gpg/keybox/package-info.java @@ -0,0 +1,4 @@ +/** + * Parsing classes for the GPG V2 KeyBox format. + */ +package org.bouncycastle.gpg.keybox; diff --git a/pg/src/main/java/org/bouncycastle/gpg/package-info.java b/pg/src/main/java/org/bouncycastle/gpg/package-info.java new file mode 100644 index 0000000000..c5890bfbef --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/gpg/package-info.java @@ -0,0 +1,4 @@ +/** + * Parsing classes for the GPG V2 SExpr format and other utilites. + */ +package org.bouncycastle.gpg; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/IntegrityProtectedInputStream.java b/pg/src/main/java/org/bouncycastle/openpgp/IntegrityProtectedInputStream.java new file mode 100644 index 0000000000..8d8efe5576 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/IntegrityProtectedInputStream.java @@ -0,0 +1,85 @@ +package org.bouncycastle.openpgp; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket; +import org.bouncycastle.util.Exceptions; + +/** + * {@link InputStream} that performs verification of integrity protection upon {@link #close()}. + */ +public class IntegrityProtectedInputStream + extends FilterInputStream +{ + + private final PGPEncryptedData esk; + + public IntegrityProtectedInputStream(InputStream in, PGPEncryptedData dataPacket) + { + super(in); + this.esk = dataPacket; + } + + @Override + public int read() + throws IOException + { + int i = in.read(); + if (i == -1) + { + close(); + } + return i; + } + + @Override + public int read(byte[] b) + throws IOException + { + int r = in.read(b); + if (r == -1) + { + close(); + } + return r; + } + + @Override + public int read(byte[] b, int off, int len) + throws IOException + { + int r = in.read(b, off, len); + if (r == -1) + { + close(); + } + return r; + } + + @Override + public void close() + throws IOException + { + super.close(); + if (esk.getEncData() instanceof SymmetricEncIntegrityPacket) + { + SymmetricEncIntegrityPacket seipd = (SymmetricEncIntegrityPacket) esk.getEncData(); + if (seipd.getVersion() == SymmetricEncIntegrityPacket.VERSION_1) + { + try + { + if (!esk.verify()) + { + throw new PGPException("Malformed integrity protected data."); + } + } + catch (PGPException e) + { + throw Exceptions.ioException(e.getMessage(), e); + } + } + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPDefaultSignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPDefaultSignatureGenerator.java index bc544d059f..94c4745e63 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPDefaultSignatureGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPDefaultSignatureGenerator.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.io.OutputStream; +import org.bouncycastle.bcpg.SignaturePacket; import org.bouncycastle.bcpg.UserAttributeSubpacket; abstract class PGPDefaultSignatureGenerator @@ -11,7 +12,13 @@ abstract class PGPDefaultSignatureGenerator protected byte lastb; protected OutputStream sigOut; protected int sigType; + protected final int version; + public PGPDefaultSignatureGenerator(int version) + { + this.version = version; + } + public void update( byte b) { @@ -108,9 +115,28 @@ protected void updateWithPublicKey(PGPPublicKey key) { byte[] keyBytes = getEncodedPublicKey(key); - this.update((byte)0x99); - this.update((byte)(keyBytes.length >> 8)); - this.update((byte)(keyBytes.length)); + if (version == SignaturePacket.VERSION_4) + { + this.update((byte) 0x99); + this.update((byte) (keyBytes.length >> 8)); + this.update((byte) (keyBytes.length)); + } + else if (version == SignaturePacket.VERSION_5) + { + this.update((byte) 0x9A); + this.update((byte) (keyBytes.length >> 24)); + this.update((byte) (keyBytes.length >> 16)); + this.update((byte) (keyBytes.length >> 8)); + this.update((byte) (keyBytes.length)); + } + else if (version == SignaturePacket.VERSION_6) + { + this.update((byte) 0x9B); + this.update((byte) (keyBytes.length >> 24)); + this.update((byte) (keyBytes.length >> 16)); + this.update((byte) (keyBytes.length >> 8)); + this.update((byte) (keyBytes.length)); + } this.update(keyBytes); } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedData.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedData.java index 8c56d1882d..c5083b851f 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedData.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedData.java @@ -175,6 +175,11 @@ public boolean isIntegrityProtected() return (encData instanceof SymmetricEncIntegrityPacket); } + public InputStreamPacket getEncData() + { + return encData; + } + /** * Checks whether the packet is protected using an AEAD algorithm. * @@ -183,7 +188,18 @@ public boolean isIntegrityProtected() */ public boolean isAEAD() { - return (encData instanceof AEADEncDataPacket); + if (encData instanceof AEADEncDataPacket) + { + return true; + } + if (encData instanceof SymmetricEncIntegrityPacket) + { + return ((SymmetricEncIntegrityPacket) encData).getVersion() == SymmetricEncIntegrityPacket.VERSION_2; + } + else + { + return false; + } } /** @@ -213,6 +229,12 @@ public boolean verify() // do nothing } + if (isAEAD()) + { + // AEAD data needs no manual verification, as decryption detects errors automatically + return true; + } + // // process the MDC packet // diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedDataGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedDataGenerator.java index 413446db31..046e5c1c1e 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedDataGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPEncryptedDataGenerator.java @@ -9,7 +9,6 @@ import org.bouncycastle.bcpg.AEADEncDataPacket; import org.bouncycastle.bcpg.BCPGHeaderObject; import org.bouncycastle.bcpg.BCPGOutputStream; -import org.bouncycastle.bcpg.ContainedPacket; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.PacketTags; import org.bouncycastle.bcpg.SymmetricEncDataPacket; @@ -88,7 +87,8 @@ public class PGPEncryptedDataGenerator private SecureRandom rand; // If true, force generation of a session key, even if we only have a single password-based encryption method // and could therefore use the S2K output as session key directly. - private boolean forceSessionKey = false; + private boolean forceSessionKey = true; + private SessionKeyExtractionCallback sessionKeyExtractionCallback = null; /** * Base constructor. @@ -121,7 +121,9 @@ public PGPEncryptedDataGenerator(PGPDataEncryptorBuilder encryptorBuilder, boole * Some versions of PGP always expect a session key, this will force use * of a session key even if a single PBE encryptor is provided. * - * @param forceSessionKey true if a session key should always be used, default is false. + * @param forceSessionKey true if a session key should always be used, default is true. + * @see + * RFC9580 - Description of the optional encrypted session key field */ public void setForceSessionKey(boolean forceSessionKey) { @@ -139,41 +141,9 @@ public void addMethod(PGPKeyEncryptionMethodGenerator method) methods.add(method); } - /** - * Write a checksum into the last two bytes of the array. - * - * @param sessionInfo byte array - */ - private void addCheckSum( - byte[] sessionInfo) - { - int check = 0; - - for (int i = 1; i != sessionInfo.length - 2; i++) - { - check += sessionInfo[i] & 0xff; - } - - sessionInfo[sessionInfo.length - 2] = (byte)(check >> 8); - sessionInfo[sessionInfo.length - 1] = (byte)(check); - } - - /** - * Create a session info array containing of the algorithm-id followed by the key and a two-byte checksum. - * - * @param algorithm symmetric algorithm - * @param keyBytes bytes of the key - * @return array of algorithm, key and checksum - */ - private byte[] createSessionInfo( - int algorithm, - byte[] keyBytes) + public void setSessionKeyExtractionCallback(SessionKeyExtractionCallback callback) { - byte[] sessionInfo = new byte[keyBytes.length + 3]; - sessionInfo[0] = (byte)algorithm; - System.arraycopy(keyBytes, 0, sessionInfo, 1, keyBytes.length); - addCheckSum(sessionInfo); - return sessionInfo; + this.sessionKeyExtractionCallback = callback; } /** @@ -216,115 +186,94 @@ private OutputStream open( pOut = new BCPGOutputStream(out, !useOldFormat); - defAlgorithm = dataEncryptorBuilder.getAlgorithm(); - rand = dataEncryptorBuilder.getSecureRandom(); - byte[] sessionKey; // session key, either protected by - or directly derived from session key encryption mechanism. - byte[] sessionInfo; // sessionKey with prepended alg-id, appended checksum - + byte[] sessionInfo = null; // sessionKey with prepended alg-id, appended checksum, null indicates direct use of S2K output as sessionKey/messageKey byte[] messageKey; // key used to encrypt the message. In OpenPGP v6 this is derived from sessionKey + salt. boolean directS2K = !forceSessionKey && methods.size() == 1 && - methods.get(0) instanceof PBEKeyEncryptionMethodGenerator; - if (directS2K) - { - sessionKey = ((PBEKeyEncryptionMethodGenerator)methods.get(0)).getKey(defAlgorithm); - sessionInfo = null; // null indicates direct use of S2K output as sessionKey/messageKey - } - else - { - sessionKey = PGPUtil.makeRandomKey(defAlgorithm, rand); - // prepend algorithm, append checksum - sessionInfo = createSessionInfo(defAlgorithm, sessionKey); - } - messageKey = sessionKey; - - // In OpenPGP v6, we need an additional step to derive a message key and IV from the session info. - // Since we cannot inject the IV into the data encryptor, we append it to the message key. - boolean isV5StyleAEAD = dataEncryptorBuilder.isV5StyleAEAD(); + methods.get(0) instanceof PBEKeyEncryptionMethodGenerator; // not public key + boolean isV5StyleAEAD = dataEncryptorBuilder.isV5StyleAEAD(); //v5 if (dataEncryptorBuilder.getAeadAlgorithm() != -1 && !isV5StyleAEAD) { + sessionKey = PGPUtil.makeRandomKey(defAlgorithm, rand); + // In OpenPGP v6, we need an additional step to derive a message key and IV from the session info. + // Since we cannot inject the IV into the data encryptor, we append it to the message key. byte[] info = SymmetricEncIntegrityPacket.createAAData( SymmetricEncIntegrityPacket.VERSION_2, defAlgorithm, dataEncryptorBuilder.getAeadAlgorithm(), dataEncryptorBuilder.getChunkSize()); - // messageKey = key and IV, will be separated in the data encryptor messageKey = AEADUtil.deriveMessageKeyAndIv( dataEncryptorBuilder.getAeadAlgorithm(), defAlgorithm, sessionKey, salt, info); } + else if (directS2K) + { + sessionKey = ((PBEKeyEncryptionMethodGenerator)methods.get(0)).getKey(defAlgorithm); + messageKey = sessionKey; + } + else + { + sessionKey = PGPUtil.makeRandomKey(defAlgorithm, rand); + messageKey = sessionKey; + } + + if (sessionKeyExtractionCallback != null) + { + sessionKeyExtractionCallback.extractSessionKey(new PGPSessionKey(defAlgorithm, sessionKey)); + } PGPDataEncryptor dataEncryptor = dataEncryptorBuilder.build(messageKey); digestCalc = dataEncryptor.getIntegrityCalculator(); - + BCPGHeaderObject encOut; for (int i = 0; i < methods.size(); i++) { PGPKeyEncryptionMethodGenerator method = (PGPKeyEncryptionMethodGenerator)methods.get(i); - // OpenPGP v5 or v6 - if (dataEncryptor instanceof PGPAEADDataEncryptor) - { - PGPAEADDataEncryptor aeadDataEncryptor = (PGPAEADDataEncryptor)dataEncryptor; - // data is encrypted by AEAD Encrypted Data packet (rfc4880bis10), so write v5 SKESK packet - if (isV5StyleAEAD) - { - writeOpenPGPv5ESKPacket(method, sessionInfo); - } - else // data is encrypted by v2 SEIPD (AEAD), so write v6 SKESK packet - { - writeOpenPGPv6ESKPacket(method, aeadDataEncryptor.getAEADAlgorithm(), sessionInfo); - } - } - // OpenPGP v4 - else // data is encrypted by v1 SEIPD or SED packet, so write v4 SKESK packet - { - writeOpenPGPv4ESKPacket(method, sessionInfo); - } + pOut.writePacket(method.generate(dataEncryptorBuilder, sessionKey)); } - try { + // OpenPGP v5 or v6 if (dataEncryptor instanceof PGPAEADDataEncryptor) { - PGPAEADDataEncryptor encryptor = (PGPAEADDataEncryptor)dataEncryptor; + PGPAEADDataEncryptor aeadDataEncryptor = (PGPAEADDataEncryptor)dataEncryptor; long ivOrSaltLen; - BCPGHeaderObject encOut; - // OpenPGP V5 style AEAD + // data is encrypted by AEAD Encrypted Data packet (rfc4880bis10), so write v5 SKESK packet if (isV5StyleAEAD) { - byte[] iv = encryptor.getIV(); + byte[] iv = aeadDataEncryptor.getIV(); encOut = new AEADEncDataPacket( - dataEncryptorBuilder.getAlgorithm(), encryptor.getAEADAlgorithm(), encryptor.getChunkSize(), iv); + defAlgorithm, aeadDataEncryptor.getAEADAlgorithm(), aeadDataEncryptor.getChunkSize(), iv); ivOrSaltLen = iv.length; } - else // OpenPGP V6 style AEAD + else // data is encrypted by v2 SEIPD (AEAD), so write v6 SKESK packet { + //AEAD(HKDF(S2K(passphrase), info), secrets, packetprefix) encOut = SymmetricEncIntegrityPacket.createVersion2Packet( - dataEncryptorBuilder.getAlgorithm(), - encryptor.getAEADAlgorithm(), - encryptor.getChunkSize(), + defAlgorithm, + aeadDataEncryptor.getAEADAlgorithm(), + aeadDataEncryptor.getChunkSize(), salt); ivOrSaltLen = salt.length; } - - if (buffer != null) + if (buffer == null) { - pOut = new ClosableBCPGOutputStream(out, encOut, buffer); + long chunkLength = 1L << (aeadDataEncryptor.getChunkSize() + 6); + long tagLengths = ((length + chunkLength - 1) / chunkLength) * 16L + 16L; // data blocks + final tag + pOut = new ClosableBCPGOutputStream(out, encOut, (length + tagLengths + 4L + ivOrSaltLen)); } else { - long chunkLength = 1L << (encryptor.getChunkSize() + 6); - long tagLengths = ((length + chunkLength - 1) / chunkLength) * 16 + 16; // data blocks + final tag - pOut = new ClosableBCPGOutputStream(out, encOut, (length + tagLengths + 4 + ivOrSaltLen)); + pOut = new ClosableBCPGOutputStream(out, encOut, buffer); } genOut = cOut = dataEncryptor.getOutputStream(pOut); } - else + // OpenPGP v4 + else // data is encrypted by v1 SEIPD or SED packet, so write v4 SKESK packet { - BCPGHeaderObject encOut; if (digestCalc != null) { - encOut = new SymmetricEncIntegrityPacket(); + encOut = SymmetricEncIntegrityPacket.createVersion1Packet(); if (useOldFormat) { throw new PGPException("symmetric-enc-integrity packets not supported in old PGP format"); @@ -362,95 +311,16 @@ private OutputStream open( inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4]; genOut.write(inLineIv); - } return new WrappedGeneratorStream(genOut, this); } - catch (Exception e) + catch (IOException e) { - throw new PGPException("Exception creating cipher", e); + throw e; } - } - - /** - * Write out a {@link org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket#VERSION_4 v4 SKESK} or - * {@link org.bouncycastle.bcpg.PublicKeyEncSessionPacket#VERSION_3 v3 PKESK} packet, - * depending on the method generator. This method is used by what can be referred to as OpenPGP v4. - * - * @param m session key encryption method generator - * @param sessionInfo session info - * @throws IOException - * @throws PGPException - */ - private void writeOpenPGPv4ESKPacket(PGPKeyEncryptionMethodGenerator m, byte[] sessionInfo) - throws IOException, PGPException - { - if (m instanceof PBEKeyEncryptionMethodGenerator) - { - PBEKeyEncryptionMethodGenerator mGen = (PBEKeyEncryptionMethodGenerator)m; - ContainedPacket esk = m.generate(mGen.getSessionKeyWrapperAlgorithm(defAlgorithm), sessionInfo); - pOut.writePacket(esk); - } - else - { - pOut.writePacket(m.generate(defAlgorithm, sessionInfo)); - } - } - - /** - * Write out a {@link org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket#VERSION_5 v5 SKESK} or - * {@link org.bouncycastle.bcpg.PublicKeyEncSessionPacket#VERSION_3 v3 PKESK} packet, - * depending on the method generator. This method is used by what can be referred to as OpenPGP v5. - * - * @param m session key encryption method generator. - * @param sessionInfo session info - * @throws IOException - * @throws PGPException - */ - private void writeOpenPGPv5ESKPacket(PGPKeyEncryptionMethodGenerator m, byte[] sessionInfo) - throws IOException, PGPException - { - if (m instanceof PBEKeyEncryptionMethodGenerator) - { - PBEKeyEncryptionMethodGenerator mGen = (PBEKeyEncryptionMethodGenerator)m; - ContainedPacket esk = m.generateV5( - mGen.getSessionKeyWrapperAlgorithm(defAlgorithm), - dataEncryptorBuilder.getAeadAlgorithm(), - sessionInfo); - pOut.writePacket(esk); - } - else - { - pOut.writePacket(m.generate(defAlgorithm, sessionInfo)); - } - } - - /** - * Write out a {@link org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket#VERSION_6 v6 SKESK} or - * {@link org.bouncycastle.bcpg.PublicKeyEncSessionPacket#VERSION_6 v6 PKESK} packet, - * depending on the method generator. This method is used by what can be referred to as OpenPGP v6. - * - * @param m session key encryption method generator. - * @param aeadAlgorithm AEAD encryption algorithm - * @param sessionInfo session info - * @throws IOException - * @throws PGPException - */ - private void writeOpenPGPv6ESKPacket(PGPKeyEncryptionMethodGenerator m, int aeadAlgorithm, byte[] sessionInfo) - throws IOException, PGPException - { - if (m instanceof PBEKeyEncryptionMethodGenerator) - { - PBEKeyEncryptionMethodGenerator mGen = (PBEKeyEncryptionMethodGenerator)m; - ContainedPacket esk = m.generateV6( - mGen.getSessionKeyWrapperAlgorithm(defAlgorithm), - aeadAlgorithm, - sessionInfo); - pOut.writePacket(esk); - } - else + catch (Exception e) { - pOut.writePacket(m.generate(defAlgorithm, sessionInfo)); + throw new PGPException("Exception creating cipher", e); } } @@ -581,4 +451,9 @@ public void close() this.finish(); } } + + public interface SessionKeyExtractionCallback + { + void extractSessionKey(PGPSessionKey sessionKey); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyPair.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyPair.java index 81c03f08c4..4977c9f36a 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyPair.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyPair.java @@ -1,28 +1,32 @@ package org.bouncycastle.openpgp; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PublicSubkeyPacket; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; + /** * General class to handle JCA key pairs and convert them into OpenPGP ones. *

      * A word for the unwary, the KeyID for a OpenPGP public key is calculated from - * a hash that includes the time of creation, if you pass a different date to the + * a hash that includes the time of creation, if you pass a different date to the * constructor below with the same public private key pair the KeyID will not be the - * same as for previous generations of the key, so ideally you only want to do + * same as for previous generations of the key, so ideally you only want to do * this once. */ public class PGPKeyPair { - protected PGPPublicKey pub; - protected PGPPrivateKey priv; + protected PGPPublicKey pub; + protected PGPPrivateKey priv; /** * Create a key pair from a PGPPrivateKey and a PGPPublicKey. - * - * @param pub the public key + * + * @param pub the public key * @param priv the private key */ public PGPKeyPair( - PGPPublicKey pub, - PGPPrivateKey priv) + PGPPublicKey pub, + PGPPrivateKey priv) { this.pub = pub; this.priv = priv; @@ -34,21 +38,49 @@ protected PGPKeyPair() /** * Return the keyID associated with this key pair. - * + * * @return keyID */ public long getKeyID() { return pub.getKeyID(); } - + + /** + * Return the {@link KeyIdentifier} associated with the public key. + * + * @return key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return getPublicKey().getKeyIdentifier(); + } + public PGPPublicKey getPublicKey() { return pub; } - + public PGPPrivateKey getPrivateKey() { return priv; } + + public PGPKeyPair asSubkey(KeyFingerPrintCalculator fingerPrintCalculator) + throws PGPException + { + if (pub.getPublicKeyPacket() instanceof PublicSubkeyPacket) + { + return this; // is already subkey + } + + PublicSubkeyPacket pubSubPkt = new PublicSubkeyPacket( + pub.getVersion(), + pub.getAlgorithm(), + pub.getCreationTime(), + pub.getPublicKeyPacket().getKey()); + return new PGPKeyPair( + new PGPPublicKey(pubSubPkt, fingerPrintCalculator), + new PGPPrivateKey(pub.getKeyID(), pubSubPkt, priv.getPrivateKeyDataPacket())); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRing.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRing.java index c3373e89b7..c9a7630d1d 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRing.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRing.java @@ -9,7 +9,9 @@ import java.util.logging.Logger; import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.Packet; +import org.bouncycastle.bcpg.PacketFormat; import org.bouncycastle.bcpg.PacketTags; import org.bouncycastle.bcpg.SignaturePacket; import org.bouncycastle.bcpg.TrustPacket; @@ -124,6 +126,10 @@ static void readUserIDs( */ public abstract PGPPublicKey getPublicKey(byte[] fingerprint); + public abstract PGPPublicKey getPublicKey(KeyIdentifier identifier); + + public abstract Iterator getPublicKeys(KeyIdentifier identifier); + /** * Return an iterator containing all the public keys carrying signatures issued from key keyID. * @@ -131,6 +137,8 @@ static void readUserIDs( */ public abstract Iterator getKeysWithSignaturesBy(long keyID); + public abstract Iterator getKeysWithSignaturesBy(KeyIdentifier identifier); + /** * Return the number of keys in the key ring. * @@ -144,6 +152,9 @@ public abstract void encode(OutputStream outStream) public abstract byte[] getEncoded() throws IOException; + public abstract byte[] getEncoded(PacketFormat format) + throws IOException; + private static boolean isUserTag(int tag) { switch (tag) diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRingGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRingGenerator.java index d45f9fab53..bb01c966b0 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRingGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPKeyRingGenerator.java @@ -4,6 +4,10 @@ import java.util.Iterator; import java.util.List; +import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.bcpg.ECPublicBCPGKey; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.PublicSubkeyPacket; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; @@ -13,74 +17,75 @@ import org.bouncycastle.openpgp.operator.PGPDigestCalculator; /** - * Generator for a PGP master and subkey ring. This class will generate + * Generator for a PGP primary and subkey ring. This class will generate * both the secret and public key rings */ public class PGPKeyRingGenerator -{ - List keys = new ArrayList(); +{ + private final List keys = new ArrayList(); - private PBESecretKeyEncryptor keyEncryptor; - private PGPDigestCalculator checksumCalculator; - private PGPKeyPair masterKey; - private PGPSignatureSubpacketVector hashedPcks; - private PGPSignatureSubpacketVector unhashedPcks; - private PGPContentSignerBuilder keySignerBuilder; + private final PBESecretKeyEncryptor keyEncryptor; + private final PGPDigestCalculator checksumCalculator; + private final PGPKeyPair primaryKey; + private final PGPSignatureSubpacketVector hashedPcks; + private final PGPSignatureSubpacketVector unhashedPcks; + private final PGPContentSignerBuilder keySignerBuilder; /** * Create a new key ring generator. * - * @param certificationLevel - * @param masterKey - * @param id id to associate with the key. + * @param certificationLevel certification level for user-ids + * @param primaryKey primary key + * @param id id to associate with the key. * @param checksumCalculator key checksum calculator - * @param hashedPcks - * @param unhashedPcks - * @param keySignerBuilder builder for key certifications - will be initialised with master secret key. - * @param keyEncryptor encryptor for secret subkeys. - * @throws PGPException + * @param hashedPcks hashed signature subpackets + * @param unhashedPcks unhashed signature subpackets + * @param keySignerBuilder builder for key certifications - will be initialised with primary secret key. + * @param keyEncryptor encryptor for secret subkeys. + * @throws PGPException error during signature generation */ public PGPKeyRingGenerator( - int certificationLevel, - PGPKeyPair masterKey, - String id, + int certificationLevel, + PGPKeyPair primaryKey, + String id, PGPDigestCalculator checksumCalculator, - PGPSignatureSubpacketVector hashedPcks, - PGPSignatureSubpacketVector unhashedPcks, - PGPContentSignerBuilder keySignerBuilder, - PBESecretKeyEncryptor keyEncryptor) + PGPSignatureSubpacketVector hashedPcks, + PGPSignatureSubpacketVector unhashedPcks, + PGPContentSignerBuilder keySignerBuilder, + PBESecretKeyEncryptor keyEncryptor) throws PGPException { - this.masterKey = masterKey; + this.primaryKey = sanitizeKeyPair(primaryKey); this.keyEncryptor = keyEncryptor; this.checksumCalculator = checksumCalculator; this.keySignerBuilder = keySignerBuilder; this.hashedPcks = hashedPcks; this.unhashedPcks = unhashedPcks; - keys.add(new PGPSecretKey(certificationLevel, masterKey, id, checksumCalculator, hashedPcks, unhashedPcks, keySignerBuilder, keyEncryptor)); + keys.add(new PGPSecretKey(certificationLevel, primaryKey, id, checksumCalculator, hashedPcks, unhashedPcks, keySignerBuilder, keyEncryptor)); } /** * Create a new key ring generator without a user-id, but instead with a primary key carrying a direct-key signature. - * @param masterKey primary key + * + * @param primaryKey primary key * @param checksumCalculator checksum calculator - * @param hashedPcks hashed signature subpackets - * @param unhashedPcks unhashed signature subpackets - * @param keySignerBuilder signer builder - * @param keyEncryptor key encryptor - * @throws PGPException + * @param hashedPcks hashed signature subpackets + * @param unhashedPcks unhashed signature subpackets + * @param keySignerBuilder signer builder + * @param keyEncryptor key encryptor + * @throws PGPException error during signature generation */ public PGPKeyRingGenerator( - PGPKeyPair masterKey, - PGPDigestCalculator checksumCalculator, - PGPSignatureSubpacketVector hashedPcks, - PGPSignatureSubpacketVector unhashedPcks, - PGPContentSignerBuilder keySignerBuilder, - PBESecretKeyEncryptor keyEncryptor) - throws PGPException + PGPKeyPair primaryKey, + PGPDigestCalculator checksumCalculator, + PGPSignatureSubpacketVector hashedPcks, + PGPSignatureSubpacketVector unhashedPcks, + PGPContentSignerBuilder keySignerBuilder, + PBESecretKeyEncryptor keyEncryptor) + throws PGPException { - this.masterKey = masterKey; + this.primaryKey = sanitizeKeyPair(primaryKey); this.keyEncryptor = keyEncryptor; this.checksumCalculator = checksumCalculator; this.keySignerBuilder = keySignerBuilder; @@ -91,7 +96,7 @@ public PGPKeyRingGenerator( try { - sigGen = new PGPSignatureGenerator(keySignerBuilder); + sigGen = new PGPSignatureGenerator(keySignerBuilder, primaryKey.getPublicKey()); } catch (Exception e) { @@ -99,15 +104,15 @@ public PGPKeyRingGenerator( } // Keyring without user-id needs direct key sig - sigGen.init(PGPSignature.DIRECT_KEY, masterKey.getPrivateKey()); + sigGen.init(PGPSignature.DIRECT_KEY, primaryKey.getPrivateKey()); sigGen.setHashedSubpackets(hashedPcks); sigGen.setUnhashedSubpackets(unhashedPcks); - PGPSecretKey secretKey = new PGPSecretKey(masterKey.getPrivateKey(), masterKey.getPublicKey(), checksumCalculator, true, keyEncryptor); + PGPSecretKey secretKey = new PGPSecretKey(primaryKey.getPrivateKey(), primaryKey.getPublicKey(), checksumCalculator, true, keyEncryptor); PGPPublicKey publicKey = secretKey.getPublicKey(); try { - PGPSignature certification = sigGen.generateCertification(masterKey.getPublicKey()); + PGPSignature certification = sigGen.generateCertification(primaryKey.getPublicKey()); publicKey = PGPPublicKey.addCertification(publicKey, certification); } @@ -123,26 +128,26 @@ public PGPKeyRingGenerator( /** * Create a new key ring generator based on an original secret key ring. The default hashed/unhashed sub-packets - * for subkey signatures will be inherited from the first signature on the master key (other than CREATION-TIME + * for subkey signatures will be inherited from the first signature on the primary key (other than CREATION-TIME * which will be ignored). * * @param originalSecretRing the secret key ring we want to add a subkeyto, - * @param secretKeyDecryptor a decryptor for the signing master key. + * @param secretKeyDecryptor a decryptor for the signing primary key. * @param checksumCalculator key checksum calculator - * @param keySignerBuilder builder for key certifications - will be initialised with master secret key. - * @param keyEncryptor encryptor for secret subkeys. - * @throws PGPException + * @param keySignerBuilder builder for key certifications - will be initialised with primary secret key. + * @param keyEncryptor encryptor for secret subkeys. + * @throws PGPException error during signature generation */ public PGPKeyRingGenerator( - PGPSecretKeyRing originalSecretRing, - PBESecretKeyDecryptor secretKeyDecryptor, - PGPDigestCalculator checksumCalculator, - PGPContentSignerBuilder keySignerBuilder, - PBESecretKeyEncryptor keyEncryptor) + PGPSecretKeyRing originalSecretRing, + PBESecretKeyDecryptor secretKeyDecryptor, + PGPDigestCalculator checksumCalculator, + PGPContentSignerBuilder keySignerBuilder, + PBESecretKeyEncryptor keyEncryptor) throws PGPException { - this.masterKey = new PGPKeyPair(originalSecretRing.getPublicKey(), - originalSecretRing.getSecretKey().extractPrivateKey(secretKeyDecryptor)); + this.primaryKey = sanitizeKeyPair(new PGPKeyPair(originalSecretRing.getPublicKey(), + originalSecretRing.getSecretKey().extractPrivateKey(secretKeyDecryptor))); this.keyEncryptor = keyEncryptor; this.checksumCalculator = checksumCalculator; this.keySignerBuilder = keySignerBuilder; @@ -165,93 +170,151 @@ public PGPKeyRingGenerator( keys.addAll(originalSecretRing.keys); } + private PGPKeyPair sanitizeKeyPair(PGPKeyPair keyPair) + throws PGPException + { + PGPPublicKey pubKey = keyPair.getPublicKey(); + if (pubKey.getVersion() == PublicKeyPacket.VERSION_6) + { + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT || + pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ELGAMAL_GENERAL) + { + // https://www.rfc-editor.org/rfc/rfc9580.html#name-elgamal + throw new PGPException("An implementation MUST NOT generate v6 ElGamal keys"); + } + + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.RSA_GENERAL) + { + // https://www.rfc-editor.org/rfc/rfc9580.html#name-rsa + if (pubKey.getBitStrength() < 3072) + { + throw new PGPException("An implementation MUST NOT generate v6 RSA keys of a size less than 3072 bits."); + } + } + + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.RSA_ENCRYPT || + pubKey.getAlgorithm() == PublicKeyAlgorithmTags.RSA_SIGN) + { + throw new PGPException("An implementation MUST NOT generate v6 RSA keys of type RSA_ENCRYPT/RSA_SIGN"); + } + + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.DSA) + { + // https://www.rfc-editor.org/rfc/rfc9580.html#name-dsa + throw new PGPException("An implementation MUST NOT generate v6 DSA keys."); + } + + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY) + { + throw new PGPException("An implementation MUST NOT generate v6 EDDSA_LEGACY keys."); + } + + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ECDH) + { + ECPublicBCPGKey ecKey = (ECPublicBCPGKey)pubKey.publicPk.getKey(); + if (ecKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + { + throw new PGPException("An implementation MUST NOT generate v6 ECDH keys over Curve25519Legacy."); + } + } + + if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.DIFFIE_HELLMAN) + { + throw new PGPException("An implementation MUST NOT generate v6 Diffie-Hellman keys."); + } + } + + return keyPair; + } + /** * Add a sub key to the key ring to be generated with default certification and inheriting - * the hashed/unhashed packets of the master key. - * + * the hashed/unhashed packets of the primary key. + * * @param keyPair the key pair to add. - * @throws PGPException + * @throws PGPException error during signature generation */ public void addSubKey( - PGPKeyPair keyPair) + PGPKeyPair keyPair) throws PGPException { - addSubKey(keyPair, hashedPcks, unhashedPcks); + addSubKey(sanitizeKeyPair(keyPair), hashedPcks, unhashedPcks); } /** * Add a sub key to the key ring to be generated with default certification and inheriting - * the hashed/unhashed packets of the master key. If bindingSignerBldr is not null it will be used to add a Primary Key Binding + * the hashed/unhashed packets of the primary key. If bindingSignerBldr is not null it will be used to add a Primary Key Binding * signature (type 0x19) into the hashedPcks for the key (required for signing subkeys). * - * @param keyPair the key pair to add. + * @param keyPair the key pair to add. * @param bindingSignerBldr provide a signing builder to create the Primary Key signature. - * @throws PGPException + * @throws PGPException error during signature generation */ public void addSubKey( - PGPKeyPair keyPair, - PGPContentSignerBuilder bindingSignerBldr) + PGPKeyPair keyPair, + PGPContentSignerBuilder bindingSignerBldr) throws PGPException { - addSubKey(keyPair, hashedPcks, unhashedPcks, bindingSignerBldr); + addSubKey(sanitizeKeyPair(keyPair), hashedPcks, unhashedPcks, bindingSignerBldr); } /** * Add a subkey with specific hashed and unhashed packets associated with it and default * certification. * - * @param keyPair public/private key pair. - * @param hashedPcks hashed packet values to be included in certification. + * @param keyPair public/private key pair. + * @param hashedPcks hashed packet values to be included in certification. * @param unhashedPcks unhashed packets values to be included in certification. - * @throws PGPException + * @throws PGPException error during signature generation */ public void addSubKey( - PGPKeyPair keyPair, + PGPKeyPair keyPair, PGPSignatureSubpacketVector hashedPcks, PGPSignatureSubpacketVector unhashedPcks) throws PGPException { - addSubKey(keyPair, hashedPcks, unhashedPcks, null); + addSubKey(sanitizeKeyPair(keyPair), hashedPcks, unhashedPcks, null); } /** * Add a subkey with specific hashed and unhashed packets associated with it and default * certification. If bindingSignerBldr is not null it will be used to add a Primary Key Binding * signature (type 0x19) into the hashedPcks for the key (required for signing subkeys). - * - * @param keyPair public/private key pair. - * @param hashedPcks hashed packet values to be included in certification. - * @param unhashedPcks unhashed packets values to be included in certification. + * + * @param keyPair public/private key pair. + * @param hashedPcks hashed packet values to be included in certification. + * @param unhashedPcks unhashed packets values to be included in certification. * @param bindingSignerBldr provide a signing builder to create the Primary Key signature. - * @throws PGPException + * @throws PGPException error during signature generation */ public void addSubKey( - PGPKeyPair keyPair, + PGPKeyPair keyPair, PGPSignatureSubpacketVector hashedPcks, PGPSignatureSubpacketVector unhashedPcks, - PGPContentSignerBuilder bindingSignerBldr) + PGPContentSignerBuilder bindingSignerBldr) throws PGPException { + sanitizeKeyPair(keyPair); try { // // generate the certification // - PGPSignatureGenerator sGen = new PGPSignatureGenerator(keySignerBuilder); + PGPSignatureGenerator sGen = new PGPSignatureGenerator(keySignerBuilder, primaryKey.getPublicKey()); - sGen.init(PGPSignature.SUBKEY_BINDING, masterKey.getPrivateKey()); + sGen.init(PGPSignature.SUBKEY_BINDING, primaryKey.getPrivateKey()); if (bindingSignerBldr != null) { // add primary key binding - PGPSignatureGenerator pGen = new PGPSignatureGenerator(bindingSignerBldr); + PGPSignatureGenerator pGen = new PGPSignatureGenerator(bindingSignerBldr, keyPair.getPublicKey()); pGen.init(PGPSignature.PRIMARYKEY_BINDING, keyPair.getPrivateKey()); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(hashedPcks); spGen.addEmbeddedSignature(false, - pGen.generateCertification(masterKey.getPublicKey(), keyPair.getPublicKey())); + pGen.generateCertification(primaryKey.getPublicKey(), keyPair.getPublicKey())); sGen.setHashedSubpackets(spGen.generate()); } else @@ -261,54 +324,54 @@ public void addSubKey( sGen.setUnhashedSubpackets(unhashedPcks); - List subSigs = new ArrayList(); - - subSigs.add(sGen.generateCertification(masterKey.getPublicKey(), keyPair.getPublicKey())); + List subSigs = new ArrayList(); + + subSigs.add(sGen.generateCertification(primaryKey.getPublicKey(), keyPair.getPublicKey())); // replace the public key packet structure with a public subkey one. PGPPublicKey pubSubKey = new PGPPublicKey(keyPair.getPublicKey(), null, subSigs); - pubSubKey.publicPk = new PublicSubkeyPacket(pubSubKey.getAlgorithm(), pubSubKey.getCreationTime(), pubSubKey.publicPk.getKey()); + pubSubKey.publicPk = new PublicSubkeyPacket(pubSubKey.getVersion(), pubSubKey.getAlgorithm(), pubSubKey.getCreationTime(), pubSubKey.publicPk.getKey()); keys.add(new PGPSecretKey(keyPair.getPrivateKey(), pubSubKey, checksumCalculator, keyEncryptor)); } catch (PGPException e) { throw e; - } + } catch (Exception e) { throw new PGPException("exception adding subkey: ", e); } } - + /** * Return the secret key ring. - * + * * @return a secret key ring. */ public PGPSecretKeyRing generateSecretKeyRing() { return new PGPSecretKeyRing(keys); } - + /** * Return the public key ring that corresponds to the secret key ring. - * + * * @return a public key ring. */ public PGPPublicKeyRing generatePublicKeyRing() { Iterator it = keys.iterator(); - List pubKeys = new ArrayList(); - + List pubKeys = new ArrayList(); + pubKeys.add(((PGPSecretKey)it.next()).getPublicKey()); - + while (it.hasNext()) { pubKeys.add(((PGPSecretKey)it.next()).getPublicKey()); } - + return new PGPPublicKeyRing(pubKeys); } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java index 629677c697..86cb90ee0f 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java @@ -6,11 +6,15 @@ import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashUtils; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.OnePassSignaturePacket; import org.bouncycastle.bcpg.Packet; +import org.bouncycastle.bcpg.SignaturePacket; import org.bouncycastle.openpgp.operator.PGPContentVerifier; import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilder; import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.util.Arrays; /** * A one pass signature object. @@ -41,6 +45,8 @@ public PGPOnePassSignature( PGPOnePassSignature( OnePassSignaturePacket sigPack) { + // v3 OPSs are typically used with v4 sigs + super(sigPack.getVersion() == OnePassSignaturePacket.VERSION_3 ? SignaturePacket.VERSION_4 : sigPack.getVersion()); this.sigPack = sigPack; this.sigType = sigPack.getSignatureType(); } @@ -61,6 +67,41 @@ public void init(PGPContentVerifierBuilderProvider verifierBuilderProvider, PGPP lastb = 0; sigOut = verifier.getOutputStream(); + + checkSaltSize(); + updateWithSalt(); + } + + private void checkSaltSize() + throws PGPException + { + if (getVersion() != SignaturePacket.VERSION_6) + { + return; + } + + int expectedSaltSize = HashUtils.getV6SignatureSaltSizeInBytes(getHashAlgorithm()); + if (expectedSaltSize != getSalt().length) + { + throw new PGPException("RFC9580 defines the salt size for " + PGPUtil.getDigestName(getHashAlgorithm()) + + " as " + expectedSaltSize + " octets, but signature has " + getSalt().length + " octets."); + } + } + + private void updateWithSalt() + throws PGPException + { + if (version == SignaturePacket.VERSION_6) + { + try + { + sigOut.write(getSalt()); + } + catch (IOException e) + { + throw new PGPException("Cannot salt the signature.", e); + } + } } /** @@ -74,6 +115,8 @@ public boolean verify( PGPSignature pgpSig) throws PGPException { + compareSalt(pgpSig); + try { sigOut.write(pgpSig.getSignatureTrailer()); @@ -88,11 +131,70 @@ public boolean verify( return verifier.verify(pgpSig.getSignature()); } + private void compareSalt(PGPSignature signature) + throws PGPException + { + if (version != SignaturePacket.VERSION_6) + { + return; + } + if (!Arrays.constantTimeAreEqual(getSalt(), signature.getSalt())) + { + throw new PGPException("Salt in OnePassSignaturePacket does not match salt in SignaturePacket."); + } + } + + /** + * Return the packet version. + * + * @return packet version + */ + public int getVersion() + { + return sigPack.getVersion(); + } + + /** + * Return the key-ID of the issuer signing key. + * For {@link OnePassSignaturePacket#VERSION_6} packets, the key-ID is derived from the fingerprint. + * + * @return key-ID + */ public long getKeyID() { return sigPack.getKeyID(); } + /** + * Return the issuer key fingerprint. + * Only for {@link OnePassSignaturePacket#VERSION_6} packets. + * @return fingerprint + */ + public byte[] getFingerprint() + { + return sigPack.getFingerprint(); + } + + /** + * Return a {@link KeyIdentifier} identifying this {@link PGPOnePassSignature}. + * + * @return key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return new KeyIdentifier(getFingerprint(), getKeyID()); + } + + /** + * Return the salt used in the corresponding signature. + * Only for {@link OnePassSignaturePacket#VERSION_6} packets. + * @return salt + */ + public byte[] getSalt() + { + return sigPack.getSalt(); + } + public int getSignatureType() { return sigPack.getSignatureType(); @@ -109,8 +211,8 @@ public int getKeyAlgorithm() } /** - * Return true, if the signature is contains any signatures that follow. - * An bracketing OPS is followed by additional OPS packets and is calculated over all the data between itself + * Return true, if the signature contains any signatures that follow. + * A bracketing OPS is followed by additional OPS packets and is calculated over all the data between itself * and its corresponding signature (it is an attestation for contained signatures). * * @return true if containing, false otherwise diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPPadding.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPPadding.java index 7661f38837..8582a247a0 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPPadding.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPPadding.java @@ -1,10 +1,16 @@ package org.bouncycastle.openpgp; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.OutputStream; +import java.security.SecureRandom; import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; import org.bouncycastle.bcpg.Packet; +import org.bouncycastle.bcpg.PacketFormat; import org.bouncycastle.bcpg.PaddingPacket; +import org.bouncycastle.crypto.CryptoServicesRegistrar; /** * The PGPPadding contains random data, and can be used to defend against traffic analysis on version 2 SEIPD messages @@ -16,10 +22,25 @@ public class PGPPadding { private PaddingPacket p; + /** + * Minimum random padding length in octets. + * Chosen totally arbitrarily. + */ + public static final int MIN_PADDING_LEN = 16; + + /** + * Maximum random padding length. + * Chosen somewhat arbitrarily, as SSH also uses max 255 bytes for random padding. + * + * @see + * rfc4253 - Binary Packet Protocol + */ + public static final int MAX_PADDING_LEN = 255; + /** * Default constructor. * - * @param in + * @param in packet input stream * @throws IOException */ public PGPPadding( @@ -34,8 +55,78 @@ public PGPPadding( p = (PaddingPacket)packet; } + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of n random bytes, where n is a number between (inclusive) {@link #MIN_PADDING_LEN} + * and {@link #MAX_PADDING_LEN}. + */ + public PGPPadding() + { + this(CryptoServicesRegistrar.getSecureRandom()); + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of n random bytes, where n is a number between (inclusive) {@link #MIN_PADDING_LEN} + * and {@link #MAX_PADDING_LEN}. + * + * @param random random number generator instance + */ + public PGPPadding(SecureRandom random) + { + this(MIN_PADDING_LEN + random.nextInt(MAX_PADDING_LEN - MIN_PADDING_LEN + 1), random); + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of

      len
      random bytes. + */ + public PGPPadding(int len) + { + this(len, CryptoServicesRegistrar.getSecureRandom()); + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of
      len
      random bytes. + * + * @param len number of random octets + * @param random random number generator instance + */ + public PGPPadding(int len, SecureRandom random) + { + this.p = new PaddingPacket(len, random); + } + + /** + * Return the padding octets as a byte array. + * @return padding octets + */ public byte[] getPadding() { return p.getPadding(); } + + public void encode(OutputStream outStream) + throws IOException + { + BCPGOutputStream pOut = BCPGOutputStream.wrap(outStream); + p.encode(pOut); + } + + public byte[] getEncoded() + throws IOException + { + return getEncoded(PacketFormat.ROUNDTRIP); + } + + public byte[] getEncoded(PacketFormat format) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, format); + encode(pOut); + pOut.close(); + return bOut.toByteArray(); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPPrivateKey.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPPrivateKey.java index 1cd1de7845..1d30aeafea 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPPrivateKey.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPPrivateKey.java @@ -1,7 +1,9 @@ package org.bouncycastle.openpgp; import org.bouncycastle.bcpg.BCPGKey; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; /** * general class to contain a private key for use with other openPGP @@ -43,6 +45,13 @@ public long getKeyID() return keyID; } + public KeyIdentifier getKeyIdentifier(KeyFingerPrintCalculator fingerprintCalculator) + throws PGPException + { + byte[] fingerprint = fingerprintCalculator.calculateFingerprint(publicKeyPacket); + return new KeyIdentifier(fingerprint, PublicKeyPacket.getKeyID(publicKeyPacket, fingerprint)); + } + /** * Return the public key packet associated with this private key, if available. * diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKey.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKey.java index 5b7b5f8d1e..4f69293bcb 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKey.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKey.java @@ -10,6 +10,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.gnu.GNUObjectIdentifiers; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParametersHolder; @@ -17,7 +18,10 @@ import org.bouncycastle.bcpg.BCPGOutputStream; import org.bouncycastle.bcpg.DSAPublicBCPGKey; import org.bouncycastle.bcpg.ECPublicBCPGKey; +import org.bouncycastle.bcpg.Ed448PublicBCPGKey; import org.bouncycastle.bcpg.ElGamalPublicBCPGKey; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.OctetArrayBCPGKey; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.PublicSubkeyPacket; @@ -27,6 +31,7 @@ import org.bouncycastle.bcpg.UserAttributePacket; import org.bouncycastle.bcpg.UserDataPacket; import org.bouncycastle.bcpg.UserIDPacket; +import org.bouncycastle.bcpg.X448PublicBCPGKey; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; import org.bouncycastle.util.Arrays; @@ -47,8 +52,7 @@ public class PGPPublicKey List subSigs = null; - private long keyID; - private byte[] fingerprint; + private KeyIdentifier keyIdentifier; private int keyStrength; private void init(KeyFingerPrintCalculator fingerPrintCalculator) @@ -56,40 +60,19 @@ private void init(KeyFingerPrintCalculator fingerPrintCalculator) { BCPGKey key = publicPk.getKey(); - this.fingerprint = fingerPrintCalculator.calculateFingerprint(publicPk); + byte[] fingerprint = fingerPrintCalculator.calculateFingerprint(publicPk); + long keyID = PublicKeyPacket.getKeyID(publicPk, fingerprint); + this.keyIdentifier = new KeyIdentifier(fingerprint, keyID); + + // key strength if (publicPk.getVersion() <= PublicKeyPacket.VERSION_3) { RSAPublicBCPGKey rK = (RSAPublicBCPGKey)key; - this.keyID = rK.getModulus().longValue(); this.keyStrength = rK.getModulus().bitLength(); } - else if (publicPk.getVersion() == PublicKeyPacket.VERSION_4) - { - this.keyID = ((long)(fingerprint[fingerprint.length - 8] & 0xff) << 56) - | ((long)(fingerprint[fingerprint.length - 7] & 0xff) << 48) - | ((long)(fingerprint[fingerprint.length - 6] & 0xff) << 40) - | ((long)(fingerprint[fingerprint.length - 5] & 0xff) << 32) - | ((long)(fingerprint[fingerprint.length - 4] & 0xff) << 24) - | ((long)(fingerprint[fingerprint.length - 3] & 0xff) << 16) - | ((long)(fingerprint[fingerprint.length - 2] & 0xff) << 8) - | ((fingerprint[fingerprint.length - 1] & 0xff)); - } - else if (publicPk.getVersion() == PublicKeyPacket.VERSION_6) - { - this.keyID = ((long)(fingerprint[0] & 0xff) << 56) - | ((long)(fingerprint[1] & 0xff) << 48) - | ((long)(fingerprint[2] & 0xff) << 40) - | ((long)(fingerprint[3] & 0xff) << 32) - | ((long)(fingerprint[4] & 0xff) << 24) - | ((long)(fingerprint[5] & 0xff) << 16) - | ((long)(fingerprint[6] & 0xff) << 8) - | ((long)(fingerprint[7] & 0xff)); - } - - // key strength - if (publicPk.getVersion() >= PublicKeyPacket.VERSION_4) + else if (publicPk.getVersion() >= PublicKeyPacket.VERSION_4) { if (key instanceof RSAPublicBCPGKey) { @@ -111,6 +94,14 @@ else if (key instanceof ECPublicBCPGKey) { this.keyStrength = 256; } + else if (curveOID.equals(EdECObjectIdentifiers.id_X448)) + { + this.keyStrength = X448PublicBCPGKey.LENGTH * 8; + } + else if (curveOID.equals(EdECObjectIdentifiers.id_Ed448)) + { + this.keyStrength = Ed448PublicBCPGKey.LENGTH * 8; + } else { X9ECParametersHolder ecParameters = ECNamedCurveTable.getByOIDLazy(curveOID); @@ -125,6 +116,10 @@ else if (key instanceof ECPublicBCPGKey) } } } + else if (key instanceof OctetArrayBCPGKey) + { + this.keyStrength = key.getEncoded().length * 8; + } } } @@ -172,9 +167,8 @@ public PGPPublicKey(PublicKeyPacket publicKeyPacket, KeyFingerPrintCalculator fi this.trustPk = trust; this.subSigs = subSigs; - this.fingerprint = key.fingerprint; - this.keyID = key.keyID; this.keyStrength = key.keyStrength; + this.keyIdentifier = key.keyIdentifier; } /** @@ -202,9 +196,8 @@ public PGPPublicKey(PublicKeyPacket publicKeyPacket, KeyFingerPrintCalculator fi this.subSigs.addAll(pubKey.subSigs); } - this.fingerprint = pubKey.fingerprint; - this.keyID = pubKey.keyID; this.keyStrength = pubKey.keyStrength; + this.keyIdentifier = pubKey.keyIdentifier; } PGPPublicKey( @@ -237,9 +230,8 @@ public PGPPublicKey(PublicKeyPacket publicKeyPacket, KeyFingerPrintCalculator fi throws PGPException { this.publicPk = original.publicPk; - this.fingerprint = original.fingerprint; this.keyStrength = original.keyStrength; - this.keyID = original.keyID; + this.keyIdentifier = original.keyIdentifier; this.trustPk = trustPk; this.keySigs = keySigs; @@ -405,7 +397,17 @@ private long getExpirationTimeFromSig( */ public long getKeyID() { - return keyID; + return keyIdentifier.getKeyId(); + } + + /** + * Return a {@link KeyIdentifier} identifying this key. + * + * @return key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return keyIdentifier; } /** @@ -415,11 +417,12 @@ public long getKeyID() */ public byte[] getFingerprint() { - byte[] tmp = new byte[fingerprint.length]; - - System.arraycopy(fingerprint, 0, tmp, 0, tmp.length); + return keyIdentifier.getFingerprint(); + } - return tmp; + public boolean hasFingerprint(byte[] fingerprint) + { + return keyIdentifier.hasFingerprint(fingerprint); } /** @@ -580,6 +583,20 @@ public Iterator getSignaturesForKeyID( return sigs.iterator(); } + public Iterator getSignaturesForKey(KeyIdentifier identifier) + { + List sigs = new ArrayList(); + for (Iterator it = getSignatures(); it.hasNext(); ) + { + PGPSignature sig = (PGPSignature)it.next(); + if (identifier.isPresentIn(sig.getKeyIdentifiers())) + { + sigs.add(sig); + } + } + return sigs.iterator(); + } + private Iterator getSignaturesForID( UserIDPacket id) { @@ -749,10 +766,7 @@ public void encode(OutputStream outStream, boolean forTransfer) if (subSigs == null) // not a sub-key { - for (int i = 0; i != keySigs.size(); i++) - { - ((PGPSignature)keySigs.get(i)).encode(out); - } + Util.encodePGPSignatures(out, keySigs, false); for (int i = 0; i != ids.size(); i++) { @@ -775,18 +789,12 @@ public void encode(OutputStream outStream, boolean forTransfer) } List sigs = (List)idSigs.get(i); - for (int j = 0; j != sigs.size(); j++) - { - ((PGPSignature)sigs.get(j)).encode(out, forTransfer); - } + Util.encodePGPSignatures(out, sigs, forTransfer); } } else { - for (int j = 0; j != subSigs.size(); j++) - { - ((PGPSignature)subSigs.get(j)).encode(out, forTransfer); - } + Util.encodePGPSignatures(out, subSigs, forTransfer); } } @@ -1149,28 +1157,7 @@ public static PGPPublicKey join( } // key signatures - for (Iterator it = copy.keySigs.iterator(); it.hasNext(); ) - { - PGPSignature keySig = (PGPSignature)it.next(); - boolean found = false; - for (int i = 0; i < keySigs.size(); i++) - { - PGPSignature existingKeySig = (PGPSignature)keySigs.get(i); - if (PGPSignature.isSignatureEncodingEqual(existingKeySig, keySig)) - { - found = true; - // join existing sig with copy to apply modifications in unhashed subpackets - existingKeySig = PGPSignature.join(existingKeySig, keySig); - keySigs.set(i, existingKeySig); - break; - } - } - if (found) - { - break; - } - keySigs.add(keySig); - } + joinPgpSignatureList(copy.keySigs, keySigs, true, true); // user-ids and id sigs for (int idIdx = 0; idIdx < copy.ids.size(); idIdx++) @@ -1210,27 +1197,7 @@ public static PGPPublicKey join( } List existingIdSigs = (List)idSigs.get(existingIdIndex); - for (Iterator it = copyIdSigs.iterator(); it.hasNext(); ) - { - PGPSignature newSig = (PGPSignature)it.next(); - boolean found = false; - for (int i = 0; i < existingIdSigs.size(); i++) - { - PGPSignature existingSig = (PGPSignature)existingIdSigs.get(i); - if (PGPSignature.isSignatureEncodingEqual(newSig, existingSig)) - { - found = true; - // join existing sig with copy to apply modifications in unhashed subpackets - existingSig = PGPSignature.join(existingSig, newSig); - existingIdSigs.set(i, existingSig); - break; - } - } - if (!found) - { - existingIdSigs.add(newSig); - } - } + joinPgpSignatureList(copyIdSigs, existingIdSigs, false, true); } // subSigs @@ -1242,27 +1209,7 @@ public static PGPPublicKey join( } else { - for (Iterator it = copy.subSigs.iterator(); it.hasNext(); ) - { - PGPSignature copySubSig = (PGPSignature)it.next(); - boolean found = false; - for (int i = 0; subSigs != null && i < subSigs.size(); i++) - { - PGPSignature existingSubSig = (PGPSignature)subSigs.get(i); - if (PGPSignature.isSignatureEncodingEqual(existingSubSig, copySubSig)) - { - found = true; - // join existing sig with copy to apply modifications in unhashed subpackets - existingSubSig = PGPSignature.join(existingSubSig, copySubSig); - subSigs.set(i, existingSubSig); - break; - } - } - if (!found && subSigs != null) - { - subSigs.add(copySubSig); - } - } + joinPgpSignatureList(copy.subSigs, subSigs, false, subSigs != null); } } @@ -1271,4 +1218,38 @@ public static PGPPublicKey join( return merged; } + + private static void joinPgpSignatureList(List source, + List rlt, + boolean needBreak, + boolean isNotNull) + throws PGPException + { + for (Iterator it = source.iterator(); it.hasNext(); ) + { + PGPSignature copySubSig = (PGPSignature)it.next(); + boolean found = false; + for (int i = 0; isNotNull && i < rlt.size(); i++) + { + PGPSignature existingSubSig = (PGPSignature)rlt.get(i); + if (existingSubSig.getVersion() == copySubSig.getVersion() && + PGPSignature.isSignatureEncodingEqual(existingSubSig, copySubSig)) + { + found = true; + // join existing sig with copy to apply modifications in unhashed subpackets + existingSubSig = PGPSignature.join(existingSubSig, copySubSig); + rlt.set(i, existingSubSig); + break; + } + } + if (found && needBreak) + { + break; + } + else if (!found && isNotNull) + { + rlt.add(copySubSig); + } + } + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyEncryptedData.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyEncryptedData.java index 792bd3ef19..5f375c7b84 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyEncryptedData.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyEncryptedData.java @@ -5,6 +5,7 @@ import org.bouncycastle.bcpg.AEADEncDataPacket; import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.bcpg.InputStreamPacket; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket; @@ -52,12 +53,24 @@ private boolean confirmCheckSum( * Return the keyID for the key used to encrypt the data. * * @return long + * @deprecated use {@link #getKeyIdentifier()} instead */ + @Deprecated public long getKeyID() { return keyData.getKeyID(); } + /** + * Return a {@link KeyIdentifier} for the key used to encrypt the data. + * + * @return key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return new KeyIdentifier(keyData.getKeyFingerprint(), keyData.getKeyID()); + } + /** * Return the symmetric key algorithm required to decrypt the data protected by this object. * @@ -72,13 +85,13 @@ public int getSymmetricAlgorithm( { if (keyData.getVersion() == PublicKeyEncSessionPacket.VERSION_3) { - byte[] plain = dataDecryptorFactory.recoverSessionData(keyData.getAlgorithm(), keyData.getEncSessionKey()); + byte[] plain = dataDecryptorFactory.recoverSessionData(keyData, encData); // symmetric cipher algorithm is stored in first octet of session data return plain[0]; } else if (keyData.getVersion() == PublicKeyEncSessionPacket.VERSION_6) { - // PKESK v5 stores the cipher algorithm in the SEIPD v2 packet fields. + // PKESK v6 stores the cipher algorithm in the SEIPD v2 packet fields. return ((SymmetricEncIntegrityPacket)encData).getCipherAlgorithm(); } else @@ -98,16 +111,57 @@ public PGPSessionKey getSessionKey( PublicKeyDataDecryptorFactory dataDecryptorFactory) throws PGPException { - byte[] sessionData = dataDecryptorFactory.recoverSessionData(keyData.getAlgorithm(), keyData.getEncSessionKey()); - if (keyData.getAlgorithm() == PublicKeyAlgorithmTags.X25519 || keyData.getAlgorithm() == PublicKeyAlgorithmTags.X448) + byte[] sessionInfo = dataDecryptorFactory.recoverSessionData(keyData, encData); + + // Confirm and discard checksum + if (containsChecksum(keyData.getAlgorithm())) + { + if (!confirmCheckSum(sessionInfo)) + { + throw new PGPException("Key checksum failed."); + } + sessionInfo = Arrays.copyOf(sessionInfo, sessionInfo.length - 2); + } + + byte[] sessionKey = Arrays.copyOfRange(sessionInfo, 1, sessionInfo.length); + int algorithm; + + // OCB (LibrePGP v5 style AEAD) + if (encData instanceof AEADEncDataPacket) { - return new PGPSessionKey(sessionData[0] & 0xff, Arrays.copyOfRange(sessionData, 1, sessionData.length)); + algorithm = ((AEADEncDataPacket) encData).getAlgorithm(); + } + + // SEIPD (OpenPGP v4 / OpenPGP v6) + else if (encData instanceof SymmetricEncIntegrityPacket) + { + SymmetricEncIntegrityPacket seipd = (SymmetricEncIntegrityPacket) encData; + if (seipd.getVersion() == SymmetricEncIntegrityPacket.VERSION_1) + { + algorithm = sessionInfo[0]; + } + else if (seipd.getVersion() == SymmetricEncIntegrityPacket.VERSION_2) + { + algorithm = seipd.getCipherAlgorithm(); + } + else + { + throw new UnsupportedPacketVersionException("Unsupported SEIPD packet version: " + seipd.getVersion()); + } } - if (!confirmCheckSum(sessionData)) + // SED (Legacy, no integrity protection!) + else { - throw new PGPKeyValidationException("key checksum failed"); + algorithm = sessionInfo[0]; } - return new PGPSessionKey(sessionData[0] & 0xff, Arrays.copyOfRange(sessionData, 1, sessionData.length - 2)); + + return new PGPSessionKey(algorithm & 0xff, sessionKey); + } + + private boolean containsChecksum(int algorithm) + { + return algorithm != PublicKeyAlgorithmTags.X25519 && + algorithm != PublicKeyAlgorithmTags.X448; } /** @@ -169,13 +223,38 @@ private InputStream getDataStream( } else { - boolean withIntegrityPacket = encData instanceof SymmetricEncIntegrityPacket; - PGPDataDecryptor dataDecryptor = dataDecryptorFactory.createDataDecryptor(withIntegrityPacket, sessionKey.getAlgorithm(), sessionKey.getKey()); + if (encData instanceof SymmetricEncIntegrityPacket) + { + SymmetricEncIntegrityPacket seipd = (SymmetricEncIntegrityPacket) encData; + // SEIPD v1 (OpenPGP v4) + if (seipd.getVersion() == SymmetricEncIntegrityPacket.VERSION_1) + { + PGPDataDecryptor dataDecryptor = dataDecryptorFactory.createDataDecryptor(true, sessionKey.getAlgorithm(), sessionKey.getKey()); - BCPGInputStream encIn = encData.getInputStream(); + BCPGInputStream encIn = encData.getInputStream(); + + processSymmetricEncIntegrityPacketDataStream(true, dataDecryptor, encIn); + } + // SEIPD v2 (OpenPGP v6 AEAD) + else + { + PGPDataDecryptor dataDecryptor = dataDecryptorFactory.createDataDecryptor(seipd, sessionKey); - processSymmetricEncIntegrityPacketDataStream(withIntegrityPacket, dataDecryptor, encIn); + BCPGInputStream encIn = encData.getInputStream(); + + encStream = new BCPGInputStream(dataDecryptor.getInputStream(encIn)); + } + } + // SED (Symmetrically Encrypted Data without Integrity Protection; Deprecated) + else + { + PGPDataDecryptor dataDecryptor = dataDecryptorFactory.createDataDecryptor(false, sessionKey.getAlgorithm(), sessionKey.getKey()); + + BCPGInputStream encIn = encData.getInputStream(); + + processSymmetricEncIntegrityPacketDataStream(false, dataDecryptor, encIn); + } // // some versions of PGP appear to produce 0 for the extra diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRing.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRing.java index ec345bf50b..10f8b29327 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRing.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRing.java @@ -17,13 +17,15 @@ import org.bouncycastle.bcpg.ArmoredInputException; import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.Packet; +import org.bouncycastle.bcpg.PacketFormat; import org.bouncycastle.bcpg.PacketTags; import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.TrustPacket; import org.bouncycastle.bcpg.UserDataPacket; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; -import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Iterable; import org.bouncycastle.util.Longs; @@ -184,7 +186,7 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) { PGPPublicKey k = (PGPPublicKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getFingerprint())) + if (k.hasFingerprint(fingerprint)) { return k; } @@ -193,6 +195,35 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) return null; } + @Override + public PGPPublicKey getPublicKey(KeyIdentifier identifier) + { + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + if (identifier.matchesExplicit(k.getKeyIdentifier())) + { + return k; + } + } + return null; + } + + @Override + public Iterator getPublicKeys(KeyIdentifier identifier) + { + List matches = new ArrayList(); + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + if (identifier.matchesExplicit(k.getKeyIdentifier())) + { + matches.add(k); + } + } + return matches.iterator(); + } + /** * Return any keys carrying a signature issued by the key represented by keyID. * @@ -218,6 +249,22 @@ public Iterator getKeysWithSignaturesBy(long keyID) return keysWithSigs.iterator(); } + @Override + public Iterator getKeysWithSignaturesBy(KeyIdentifier identifier) + { + List keysWithSigs = new ArrayList(); + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + Iterator sigIt = k.getSignaturesForKey(identifier); + if (sigIt.hasNext()) + { + keysWithSigs.add(k); + } + } + return keysWithSigs.iterator(); + } + /** * Return an iterator containing all the public keys. * @@ -239,10 +286,16 @@ public Iterator iterator() public byte[] getEncoded() throws IOException { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - this.encode(bOut); + return getEncoded(PacketFormat.ROUNDTRIP); + } + @Override + public byte[] getEncoded(PacketFormat format) throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, format); + this.encode(pOut); + pOut.close(); return bOut.toByteArray(); } @@ -478,7 +531,7 @@ public static PGPPublicKeyRing join( boolean allowSubkeySigsOnNonSubkey) throws PGPException { - if (!Arrays.areEqual(first.getPublicKey().getFingerprint(), second.getPublicKey().getFingerprint())) + if (!second.getPublicKey().hasFingerprint(first.getPublicKey().getFingerprint())) { throw new IllegalArgumentException("Cannot merge certificates with differing primary keys."); } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRingCollection.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRingCollection.java index f13b4742ad..52a232a3ab 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRingCollection.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPPublicKeyRingCollection.java @@ -278,7 +278,7 @@ public PGPPublicKey getPublicKey( } /** - * Return the PGP public key associated with the given key fingerprint. + * Return the public key ring which contains the key associated with the given key fingerprint. * * @param fingerprint the public key fingerprint to match against. * @return the PGP public key ring containing the PGP public key matching fingerprint. diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKey.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKey.java index fecddf9702..b6c814ed2f 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKey.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKey.java @@ -19,8 +19,10 @@ import org.bouncycastle.bcpg.EdSecretBCPGKey; import org.bouncycastle.bcpg.ElGamalSecretBCPGKey; import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.PublicKeyUtils; import org.bouncycastle.bcpg.PublicSubkeyPacket; import org.bouncycastle.bcpg.RSASecretBCPGKey; import org.bouncycastle.bcpg.S2K; @@ -99,13 +101,13 @@ private static PGPPublicKey buildPublicKey(boolean isMasterKey, PGPPublicKey pub if (isMasterKey && !(pubKey.isEncryptionKey() && pubPacket.getAlgorithm() != PublicKeyAlgorithmTags.RSA_GENERAL)) { PGPPublicKey mstKey = new PGPPublicKey(pubKey); - mstKey.publicPk = new PublicKeyPacket(pubPacket.getAlgorithm(), pubPacket.getTime(), pubPacket.getKey()); + mstKey.publicPk = new PublicKeyPacket(pubPacket.getVersion(), pubPacket.getAlgorithm(), pubPacket.getTime(), pubPacket.getKey()); return mstKey; } else { PGPPublicKey subKey = new PGPPublicKey(pubKey); - subKey.publicPk = new PublicSubkeyPacket(pubPacket.getAlgorithm(), pubPacket.getTime(), pubPacket.getKey()); + subKey.publicPk = new PublicSubkeyPacket(pubPacket.getVersion(), pubPacket.getAlgorithm(), pubPacket.getTime(), pubPacket.getKey()); return subKey; } } @@ -143,6 +145,11 @@ private static SecretKeyPacket buildSecretKeyPacket(boolean isMasterKey, PGPPriv S2K s2k = keyEncryptor.getS2K(); int s2kUsage; + if (keyEncryptor.getAeadAlgorithm() != 0) + { + s2kUsage = SecretKeyPacket.USAGE_AEAD; + return generateSecretKeyPacket(isMasterKey, pubKey.publicPk, encAlgorithm, keyEncryptor.getAeadAlgorithm(), s2kUsage, s2k, iv, encData); + } if (checksumCalculator != null) { @@ -159,11 +166,11 @@ private static SecretKeyPacket buildSecretKeyPacket(boolean isMasterKey, PGPPriv return generateSecretKeyPacket(isMasterKey, pubKey.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData); } - else + else if (pubKey.getVersion() != PublicKeyPacket.VERSION_6) { pOut.write(checksum(null, keyData, keyData.length)); - return generateSecretKeyPacket(isMasterKey, pubKey.publicPk, encAlgorithm, bOut.toByteArray()); } + return generateSecretKeyPacket(isMasterKey, pubKey.publicPk, encAlgorithm, bOut.toByteArray()); } catch (PGPException e) { @@ -199,6 +206,18 @@ private static SecretKeyPacket generateSecretKeyPacket(boolean isMasterKey, Publ } } + private static SecretKeyPacket generateSecretKeyPacket(boolean isMasterKey, PublicKeyPacket pubKey, int encAlgorithm, int aeadAlgorithm, int s2kUsage, S2K s2K, byte[] iv, byte[] secKeyData) + { + if (isMasterKey) + { + return new SecretKeyPacket(pubKey, encAlgorithm, aeadAlgorithm, s2kUsage, s2K, iv, secKeyData); + } + else + { + return new SecretSubkeyPacket(pubKey, encAlgorithm, aeadAlgorithm, s2kUsage, s2K, iv, secKeyData); + } + } + /** * Construct a PGPSecretKey using the passed in private/public key pair and binding it to the passed in id * using a generated certification of certificationLevel.The secret key checksum is calculated using the original @@ -316,7 +335,7 @@ else if (!hashedPcks.hasSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE)) // replace the public key packet structure with a public subkey one. PGPPublicKey pubSubKey = new PGPPublicKey(keyPair.getPublicKey(), null, subSigs); - pubSubKey.publicPk = new PublicSubkeyPacket(pubSubKey.getAlgorithm(), pubSubKey.getCreationTime(), pubSubKey.publicPk.getKey()); + pubSubKey.publicPk = new PublicSubkeyPacket(pubSubKey.getVersion(), pubSubKey.getAlgorithm(), pubSubKey.getCreationTime(), pubSubKey.publicPk.getKey()); this.pub = pubSubKey; this.secret = buildSecretKeyPacket(false, keyPair.getPrivateKey(), keyPair.getPublicKey(), keyEncryptor, checksumCalculator); @@ -400,11 +419,7 @@ private static PGPPublicKey certifiedPublicKey( */ public boolean isSigningKey() { - int algorithm = pub.getAlgorithm(); - - return ((algorithm == PGPPublicKey.RSA_GENERAL) || (algorithm == PGPPublicKey.RSA_SIGN) - || (algorithm == PGPPublicKey.DSA) || (algorithm == PGPPublicKey.ECDSA) || (algorithm == PGPPublicKey.EDDSA_LEGACY) - || (algorithm == PGPPublicKey.ELGAMAL_GENERAL) || (algorithm == PGPPublicKey.Ed448) || (algorithm == PGPPublicKey.Ed25519)); + return PublicKeyUtils.isSigningAlgorithm(pub.getAlgorithm()); } /** @@ -439,6 +454,17 @@ public int getKeyEncryptionAlgorithm() return secret.getEncAlgorithm(); } + /** + * Return the AEAD algorithm the key is encrypted with. + * Returns
      0
      if no AEAD is used. + * + * @return aead key encryption algorithm + */ + public int getAEADKeyEncryptionAlgorithm() + { + return secret.getAeadAlgorithm(); + } + /** * Return the keyID of the public key associated with this key. * @@ -449,6 +475,16 @@ public long getKeyID() return pub.getKeyID(); } + /** + * Return a {@link KeyIdentifier} for this key. + * + * @return identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return this.getPublicKey().getKeyIdentifier(); + } + /** * Return the fingerprint of the public key associated with this key. * @@ -461,6 +497,13 @@ public byte[] getFingerprint() /** * Return the S2K usage associated with this key. + * This value indicates, how the secret key material is protected: + *
        + *
      • {@link SecretKeyPacket#USAGE_NONE}: Unprotected
      • + *
      • {@link SecretKeyPacket#USAGE_CHECKSUM}: Password-protected using malleable CFB (deprecated)
      • + *
      • {@link SecretKeyPacket#USAGE_SHA1}: Password-protected using CFB
      • + *
      • {@link SecretKeyPacket#USAGE_AEAD}: Password-protected using AEAD (recommended)
      • + *
      * * @return the key's S2K usage */ @@ -521,17 +564,32 @@ private byte[] extractKeyData( try { byte[] key = decryptorFactory.makeKeyFromPassPhrase(secret.getEncAlgorithm(), secret.getS2K()); - if (secret.getPublicKeyPacket().getVersion() == 4) + if (secret.getPublicKeyPacket().getVersion() >= PublicKeyPacket.VERSION_4) { + if (secret.getS2KUsage() == SecretKeyPacket.USAGE_AEAD) + { + // privKey := AEAD(HKDF(S2K(passphrase), info), secrets, packetprefix) + return decryptorFactory.recoverKeyData( + secret.getEncAlgorithm(), + secret.getAeadAlgorithm(), + key, // s2k output = ikm for hkdf + secret.getIV(), // iv = aead nonce + secret.getPacketTag(), + secret.getPublicKeyPacket().getVersion(), + secret.getSecretKeyData(), + secret.getPublicKeyPacket().getEncodedContents()); + } + else + { + data = decryptorFactory.recoverKeyData(secret.getEncAlgorithm(), key, secret.getIV(), encData, 0, encData.length); - data = decryptorFactory.recoverKeyData(secret.getEncAlgorithm(), key, secret.getIV(), encData, 0, encData.length); - - boolean useSHA1 = secret.getS2KUsage() == SecretKeyPacket.USAGE_SHA1; - byte[] check = checksum(useSHA1 ? decryptorFactory.getChecksumCalculator(HashAlgorithmTags.SHA1) : null, data, (useSHA1) ? data.length - 20 : data.length - 2); + boolean useSHA1 = secret.getS2KUsage() == SecretKeyPacket.USAGE_SHA1; + byte[] check = checksum(useSHA1 ? decryptorFactory.getChecksumCalculator(HashAlgorithmTags.SHA1) : null, data, (useSHA1) ? data.length - 20 : data.length - 2); - if (!Arrays.constantTimeAreEqual(check.length, check, 0, data, data.length - check.length)) - { - throw new PGPException("checksum mismatch at in checksum of " + check.length + " bytes"); + if (!Arrays.constantTimeAreEqual(check.length, check, 0, data, data.length - check.length)) + { + throw new PGPException("checksum mismatch at in checksum of " + check.length + " bytes"); + } } } else // version 2 or 3, RSA only. @@ -752,10 +810,7 @@ public void encode(OutputStream outStream) if (pub.subSigs == null) // is not a sub key { - for (int i = 0; i != pub.keySigs.size(); i++) - { - ((PGPSignature)pub.keySigs.get(i)).encode(out); - } + Util.encodePGPSignatures(out, pub.keySigs, false); for (int i = 0; i != pub.ids.size(); i++) { @@ -778,19 +833,12 @@ public void encode(OutputStream outStream) } List sigs = (List)pub.idSigs.get(i); - - for (int j = 0; j != sigs.size(); j++) - { - ((PGPSignature)sigs.get(j)).encode(out); - } + Util.encodePGPSignatures(out, sigs, false); } } else { - for (int j = 0; j != pub.subSigs.size(); j++) - { - ((PGPSignature)pub.subSigs.get(j)).encode(out); - } + Util.encodePGPSignatures(out, pub.subSigs, false); } } @@ -949,7 +997,15 @@ public static PGPSecretKey copyWithNewPassword( SecretKeyPacket secret; - secret = generateSecretKeyPacket(!(key.secret instanceof SecretSubkeyPacket), key.secret.getPublicKeyPacket(), newEncAlgorithm, s2kUsage, s2k, iv, keyData); + if (newKeyEncryptor!= null && newKeyEncryptor.getAeadAlgorithm() > 0) + { + s2kUsage = SecretKeyPacket.USAGE_AEAD; + secret = generateSecretKeyPacket(!(key.secret instanceof SecretSubkeyPacket), key.secret.getPublicKeyPacket(), newEncAlgorithm, newKeyEncryptor.getAeadAlgorithm(), s2kUsage, s2k, iv, keyData); + } + else + { + secret = generateSecretKeyPacket(!(key.secret instanceof SecretSubkeyPacket), key.secret.getPublicKeyPacket(), newEncAlgorithm, s2kUsage, s2k, iv, keyData); + } return new PGPSecretKey(secret, key.pub); } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKeyRing.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKeyRing.java index d365b3ce89..8319fcb4c7 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKeyRing.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSecretKeyRing.java @@ -15,6 +15,9 @@ import org.bouncycastle.bcpg.ArmoredInputException; import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PacketFormat; import org.bouncycastle.bcpg.PacketTags; import org.bouncycastle.bcpg.PublicSubkeyPacket; import org.bouncycastle.bcpg.SecretKeyPacket; @@ -24,7 +27,6 @@ import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; -import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Iterable; /** @@ -246,7 +248,7 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) { PGPPublicKey k = (PGPPublicKey)extraPubKeys.get(i); - if (Arrays.areEqual(fingerprint, k.getFingerprint())) + if (k.hasFingerprint(fingerprint)) { return k; } @@ -255,6 +257,80 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) return null; } + @Override + public PGPPublicKey getPublicKey(KeyIdentifier identifier) + { + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + if (k.getPublicKey() != null && identifier.matchesExplicit(k.getKeyIdentifier())) + { + return k.getPublicKey(); + } + } + + for (Iterator it = extraPubKeys.iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + if (identifier.matchesExplicit(k.getKeyIdentifier())) + { + return k; + } + } + return null; + } + + @Override + public Iterator getPublicKeys(KeyIdentifier identifier) + { + List matches = new ArrayList(); + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + if (k.getPublicKey() != null && identifier.matchesExplicit(k.getKeyIdentifier())) + { + matches.add(k.getPublicKey()); + } + } + + for (Iterator it = extraPubKeys.iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + if (identifier.matchesExplicit(k.getKeyIdentifier())) + { + matches.add(k); + } + } + return matches.iterator(); + } + + public PGPSecretKey getSecretKey(KeyIdentifier identifier) + { + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + if (identifier.matchesExplicit(k.getKeyIdentifier())) + { + return k; + } + } + return null; + } + + public Iterator getSecretKeys(KeyIdentifier identifier) + { + List matches = new ArrayList(); + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + if (identifier.matchesExplicit(k.getKeyIdentifier())) + { + matches.add(k); + } + } + return matches.iterator(); + } + /** * Return any keys carrying a signature issued by the key represented by keyID. * @@ -280,6 +356,35 @@ public Iterator getKeysWithSignaturesBy(long keyID) return keysWithSigs.iterator(); } + @Override + public Iterator getKeysWithSignaturesBy(KeyIdentifier identifier) + { + List keysWithSigs = new ArrayList(); + for (Iterator it = keys.iterator(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + if (k.getPublicKey() == null) + { + continue; + } + Iterator sigIt = k.getPublicKey().getSignaturesForKey(identifier); + if (sigIt.hasNext()) + { + keysWithSigs.add(k.getPublicKey()); + } + } + for (Iterator it = extraPubKeys.iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + Iterator sigIt = k.getSignaturesForKey(identifier); + if (sigIt.hasNext()) + { + keysWithSigs.add(k); + } + } + return keysWithSigs.iterator(); + } + /** * Return an iterator containing all the public keys. * @@ -356,7 +461,7 @@ public PGPSecretKey getSecretKey(byte[] fingerprint) { PGPSecretKey k = (PGPSecretKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getPublicKey().getFingerprint())) + if (k.getPublicKey().hasFingerprint(fingerprint)) { return k; } @@ -387,13 +492,36 @@ public int size() return keys.size(); } + /** + * Return the OpenPGP certificate (Transferable Public Key) of this key. + * + * @return certificate + */ + public PGPPublicKeyRing toCertificate() + { + List pubKeys = new ArrayList(); + Iterator it = getPublicKeys(); + while (it.hasNext()) + { + pubKeys.add(it.next()); + } + return new PGPPublicKeyRing(pubKeys); + } + public byte[] getEncoded() throws IOException { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - this.encode(bOut); + return getEncoded(PacketFormat.ROUNDTRIP); + } + @Override + public byte[] getEncoded(PacketFormat format) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, format); + this.encode(pOut); + pOut.close(); return bOut.toByteArray(); } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java index 03c3fb67a9..7688b94600 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java @@ -5,6 +5,7 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; +import java.util.Iterator; import java.util.List; import org.bouncycastle.asn1.ASN1EncodableVector; @@ -12,12 +13,19 @@ import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashUtils; +import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.MPInteger; import org.bouncycastle.bcpg.Packet; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.SignaturePacket; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.TrustPacket; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; +import org.bouncycastle.bcpg.sig.IssuerKeyID; +import org.bouncycastle.bcpg.sig.RevocationReason; +import org.bouncycastle.bcpg.sig.RevocationReasonTags; import org.bouncycastle.math.ec.rfc8032.Ed25519; import org.bouncycastle.math.ec.rfc8032.Ed448; import org.bouncycastle.openpgp.operator.PGPContentVerifier; @@ -33,25 +41,164 @@ public class PGPSignature extends PGPDefaultSignatureGenerator { + /** + * The signature is made over some binary data. + * No preprocessing is applied. + *
      + * This signature type is used to create data signatures. + * + * @see + * RFC9580 - Binary Signature of a Document + */ public static final int BINARY_DOCUMENT = 0x00; + + /** + * The signature is made over text data. + * In a preprocessing step, the text data is canonicalized (line endings may be altered). + *
      + * This signature type is used to create data signatures. + * + * @see + * RFC9580 - Text Signature of a Canonical Document + */ public static final int CANONICAL_TEXT_DOCUMENT = 0x01; + + /** + * The signature is made only over its own signature subpackets. + * + * @see + * RFC9580 - Standalone Signature + */ public static final int STAND_ALONE = 0x02; + /** + * Generic certification over a user-id or user-attribute. + * The issuer of a generic certification does not make any claims as to what extent they checked + * the authenticity of the identity claim. + *
      + * This signature type is used to bind user information to primary keys, or to certify the identity claim + * of a third party. + * + * @see + * RFC9580 - Generic Certification Signature of a User ID and Public Key Packet + */ public static final int DEFAULT_CERTIFICATION = 0x10; + + /** + * Persona certification over a user-id or user-attribute. + * The issuer of a persona certification did explicitly not check the authenticity of the identity claim. + *
      + * This signature type is used to bind user information to primary keys, or to certify the identity claim + * of a third party. + * + * @see + * RFC9580 - Persona Certification Signature of a User ID and Public Key Packet + */ public static final int NO_CERTIFICATION = 0x11; + + /** + * Casual certification over a user-id or user-attribute. + * The issuer of a casual certification did some casual verification to check the authenticity of the + * identity claim. + *
      + * This signature type is used to bind user information to primary keys, or to certify the identity claim + * of a third party. + * + * @see + * RFC9580 - Casual Certification of a User ID an Public Key Packet + */ public static final int CASUAL_CERTIFICATION = 0x12; + + /** + * Positive certification over a user-id or user-attribute. + * The issuer of a positive certification did extensive effort to check the authenticity of the identity claim. + *
      + * This signature type is used to bind user information to primary keys, or to certify the identity claim + * of a third party. + * + * @see + * RFC9580 - Positive Certification Signature of a User ID and Public Key Packet + */ public static final int POSITIVE_CERTIFICATION = 0x13; + /** + * Subkey Binding Signature to bind a subkey to a primary key. + * This signature type is used to bind a subkey to the primary key of a certificate. + * + * @see + * RFC9580 - Subkey Binding Signature + */ public static final int SUBKEY_BINDING = 0x18; + + /** + * Primary-Key Binding Signature to bind a signing-capable subkey to a primary key. + * This (back-) signature is used as an embedded signature in a {@link #SUBKEY_BINDING} signature and acts as + * a claim by the subkey, stating that it is in fact a subkey of the primary key. + * + * @see + * RFC9580 - Primary Key Binding Signature + */ public static final int PRIMARYKEY_BINDING = 0x19; + + /** + * The signature is made directly over a primary key. + * If issued as a self-signature, its contents apply to the whole certificate, meaning this signature + * is appropriate to set algorithm preferences which also apply to its subkeys. + * Issued as a signature over a third-party certificate, it can be used to mark said certificate as a CA. + * + * @see + * RFC9580 - Direct Key Signature + */ public static final int DIRECT_KEY = 0x1f; + + /** + * The signature is used to revoke a primary key (and in turn the whole certificate with all its subkeys). + * + * @see + * RFC9580 - Key Revocation Signature + */ public static final int KEY_REVOCATION = 0x20; + + /** + * The signature is used to revoke the binding of a particular subkey. + * + * @see + * RFC9580 - Subkey Revocation Signature + */ public static final int SUBKEY_REVOCATION = 0x28; + + /** + * The signature is used to revoke a user-id certification signature + * ({@link #DEFAULT_CERTIFICATION}, {@link #NO_CERTIFICATION}, {@link #CASUAL_CERTIFICATION}, + * {@link #POSITIVE_CERTIFICATION}) or {@link #DIRECT_KEY} signature. + * Issued as a self-signature, it can be used to revoke an identity claim. + * Issued over a third-party certificate, it revokes the attestation of the third-party's claim. + * + * @see + * RFC9580 - Certification Revocation Signature + */ public static final int CERTIFICATION_REVOCATION = 0x30; + + /** + * The signature is only meaningful for the timestamp contained in it. + * + * @see + * RFC9580 - Timestamp Signature + */ public static final int TIMESTAMP = 0x40; + + /** + * This signature is issued over another signature and can act as an attestation of that signature. + * This concept can be used to "approve" third-party certifications over the own key, allowing + * third-party certifications to be published on key-servers that usually strip such signatures + * to prevent certificate flooding. + * + * @see + * RFC9580 - Third-Party Confirmation Signature/a> + */ public static final int THIRD_PARTY_CONFIRMATION = 0x50; - private final SignaturePacket sigPck; + final SignaturePacket sigPck; private final TrustPacket trustPck; private volatile PGPContentVerifier verifier; @@ -66,6 +213,13 @@ private static SignaturePacket cast(Packet packet) return (SignaturePacket)packet; } + /** + * Parse a {@link PGPSignature} from an OpenPGP packet input stream. + * + * @param pIn packet input stream + * @throws IOException + * @throws PGPException + */ public PGPSignature( BCPGInputStream pIn) throws IOException, PGPException @@ -76,6 +230,7 @@ public PGPSignature( PGPSignature( PGPSignature signature) { + super(signature.getVersion()); sigPck = signature.sigPck; sigType = signature.sigType; trustPck = signature.trustPck; @@ -91,6 +246,7 @@ public PGPSignature( SignaturePacket sigPacket, TrustPacket trustPacket) { + super(sigPacket.getVersion()); this.sigPck = sigPacket; this.sigType = sigPck.getSignatureType(); this.trustPck = trustPacket; @@ -146,9 +302,31 @@ public boolean isCertification() return isCertification(getSignatureType()); } + /** + * Initialize the signature for verification. + * + * @param verifierBuilderProvider provide the implementation for signature verification + * @param pubKey issuer public key + * @throws PGPException + */ public void init(PGPContentVerifierBuilderProvider verifierBuilderProvider, PGPPublicKey pubKey) throws PGPException { + if (sigType == 0xFF) + { + throw new PGPException("Illegal signature type 0xFF provided."); + } + + if (getVersion() == SignaturePacket.VERSION_6 && pubKey.getVersion() != PublicKeyPacket.VERSION_6) + { + throw new PGPException("MUST NOT verify v6 signature with non-v6 key."); + } + + if (getVersion() == SignaturePacket.VERSION_4 && pubKey.getVersion() != PublicKeyPacket.VERSION_4) + { + throw new PGPException("MUST NOT verify v4 signature with non-v4 key."); + } + PGPContentVerifierBuilder verifierBuilder = createVerifierProvider(verifierBuilderProvider); init(verifierBuilder.build(pubKey)); @@ -161,12 +339,57 @@ PGPContentVerifierBuilder createVerifierProvider(PGPContentVerifierBuilderProvid } void init(PGPContentVerifier verifier) + throws PGPException { this.verifier = verifier; this.lastb = 0; this.sigOut = verifier.getOutputStream(); + + checkSaltSize(); + updateWithSalt(); } + private void checkSaltSize() + throws PGPException + { + if (getVersion() != SignaturePacket.VERSION_6) + { + return; + } + + int expectedSaltSize = HashUtils.getV6SignatureSaltSizeInBytes(getHashAlgorithm()); + if (expectedSaltSize != sigPck.getSalt().length) + { + throw new PGPException("RFC9580 defines the salt size for " + PGPUtil.getDigestName(getHashAlgorithm()) + + " as " + expectedSaltSize + " octets, but signature has " + sigPck.getSalt().length + " octets."); + } + } + + private void updateWithSalt() + throws PGPException + { + if (getVersion() == SignaturePacket.VERSION_6) + { + try + { + sigOut.write(sigPck.getSalt()); + } + catch (IOException e) + { + throw new PGPException("Could not update with salt.", e); + } + } + } + + /** + * Finish the verification and return true if the signature is "correct". + * Note: The fact that this method returned
      true
      does not yet mean that the signature is valid. + * A correct signature may very well be expired, the issuer key may be revoked, etc. + * All these constraints are not checked by this method. + * + * @return true if the signature is correct + * @throws PGPException + */ public boolean verify() throws PGPException { @@ -379,6 +602,13 @@ boolean doVerifyCertification( return verifier.verify(this.getSignature()); } + /** + * Return the type id of the signature. + * + * @return type id + * @see
      + * RFC9580 - Signature Types + */ public int getSignatureType() { return sigPck.getSignatureType(); @@ -386,6 +616,10 @@ public int getSignatureType() /** * Return the id of the key that created the signature. + * Note: Since signatures of version 4 or later encode the issuer information inside a + * signature subpacket ({@link IssuerKeyID} or {@link IssuerFingerprint}), there is not + * a single source of truth for the key-id. + * To match any suitable issuer keys, use {@link #getKeyIdentifiers()} instead. * * @return keyID of the signatures corresponding key. */ @@ -394,6 +628,85 @@ public long getKeyID() return sigPck.getKeyID(); } + /** + * Create a list of {@link KeyIdentifier} objects, for all {@link IssuerFingerprint} + * and {@link IssuerKeyID} signature subpackets found in either the hashed or unhashed areas + * of the signature. + * + * @return all detectable {@link KeyIdentifier KeyIdentifiers} + */ + public List getKeyIdentifiers() + { + List identifiers = new ArrayList(); + if (getVersion() <= SignaturePacket.VERSION_3) + { + identifiers.add(new KeyIdentifier(getKeyID())); + } + else + { + identifiers.addAll(getHashedKeyIdentifiers()); + identifiers.addAll(getUnhashedKeyIdentifiers()); + } + return identifiers; + } + + public boolean hasKeyIdentifier(KeyIdentifier identifier) + { + for (Iterator it = getKeyIdentifiers().iterator(); it.hasNext(); ) + { + if (((KeyIdentifier)it.next()).matchesExplicit(identifier)) + { + return true; + } + } + return false; + } + + /** + * Return a list of all {@link KeyIdentifier KeyIdentifiers} that could be derived from + * any {@link IssuerFingerprint} or {@link IssuerKeyID} subpackets of the hashed signature + * subpacket area. + * + * @return hashed key identifiers + */ + public List getHashedKeyIdentifiers() + { + return extractKeyIdentifiers(sigPck.getHashedSubPackets()); + } + + /** + * Return a list of all {@link KeyIdentifier KeyIdentifiers} that could be derived from + * any {@link IssuerFingerprint} or {@link IssuerKeyID} subpackets of the unhashed signature + * subpacket area. + * + * @return unhashed key identifiers + */ + public List getUnhashedKeyIdentifiers() + { + return extractKeyIdentifiers(sigPck.getUnhashedSubPackets()); + } + + private List extractKeyIdentifiers(SignatureSubpacket[] subpackets) + { + List identifiers = new ArrayList(); + for (int idx = 0; idx != subpackets.length; idx++) + { + SignatureSubpacket s = subpackets[idx]; + if (s instanceof IssuerFingerprint) + { + IssuerFingerprint issuer = (IssuerFingerprint)s; + identifiers.add(new KeyIdentifier(issuer.getFingerprint())); + } + + if (s instanceof IssuerKeyID) + { + IssuerKeyID issuer = (IssuerKeyID)s; + identifiers.add(new KeyIdentifier(issuer.getKeyID())); + } + } + return identifiers; + } + /** * Return the creation time of the signature. * @@ -419,11 +732,28 @@ public boolean hasSubpackets() return sigPck.getHashedSubPackets() != null || sigPck.getUnhashedSubPackets() != null; } + /** + * Return the hashed subpackets of the signature. + * Hashed signature subpackets are covered by the signature. + * + * @return hashed signature subpackets + */ public PGPSignatureSubpacketVector getHashedSubPackets() { return createSubpacketVector(sigPck.getHashedSubPackets()); } + /** + * Return the unhashed subpackets of the signature. + * As unhashed signature subpackets are NOT covered by the signature, an attacker might inject false + * information after the fact, therefore only "self-authenticating" information from this area can + * be trusted. + * Self-authenticating information are for example the {@link org.bouncycastle.bcpg.sig.IssuerKeyID} + * or {@link org.bouncycastle.bcpg.sig.IssuerFingerprint}, whose authenticity can be confirmed by + * verifying the signature using the declared key. + * + * @return unhashed signature subpackets + */ public PGPSignatureSubpacketVector getUnhashedSubPackets() { return createSubpacketVector(sigPck.getUnhashedSubPackets()); @@ -439,6 +769,23 @@ private PGPSignatureSubpacketVector createSubpacketVector(SignatureSubpacket[] p return null; } + /** + * Return the salt of a v6 signature. + * + * @return salt + */ + byte[] getSalt() + { + return sigPck.getSalt(); + } + + /** + * Return the cryptographic raw signature contained in the OpenPGP signature packet. + * The value is dependent on the signing algorithm. + * + * @return cryptographic signature + * @throws PGPException + */ public byte[] getSignature() throws PGPException { @@ -451,22 +798,22 @@ public byte[] getSignature() { signature = BigIntegers.asUnsignedByteArray(sigValues[0].getValue()); } - else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY || - getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed25519) - { - byte[] a = BigIntegers.asUnsignedByteArray(sigValues[0].getValue()); - byte[] b = BigIntegers.asUnsignedByteArray(sigValues[1].getValue()); - signature = new byte[Ed25519.SIGNATURE_SIZE]; - System.arraycopy(a, 0, signature, Ed25519.PUBLIC_KEY_SIZE - a.length, a.length); - System.arraycopy(b, 0, signature, Ed25519.SIGNATURE_SIZE - b.length, b.length); - } - else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed448) + else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY) { byte[] a = BigIntegers.asUnsignedByteArray(sigValues[0].getValue()); byte[] b = BigIntegers.asUnsignedByteArray(sigValues[1].getValue()); - signature = new byte[Ed448.SIGNATURE_SIZE]; - System.arraycopy(a, 0, signature, Ed448.PUBLIC_KEY_SIZE - a.length, a.length); - System.arraycopy(b, 0, signature, Ed448.SIGNATURE_SIZE - b.length, b.length); + if (a.length + b.length > Ed25519.SIGNATURE_SIZE) + { + signature = new byte[Ed448.SIGNATURE_SIZE]; + System.arraycopy(a, 0, signature, Ed448.PUBLIC_KEY_SIZE - a.length, a.length); + System.arraycopy(b, 0, signature, Ed448.SIGNATURE_SIZE - b.length, b.length); + } + else + { + signature = new byte[Ed25519.SIGNATURE_SIZE]; + System.arraycopy(a, 0, signature, Ed25519.PUBLIC_KEY_SIZE - a.length, a.length); + System.arraycopy(b, 0, signature, Ed25519.SIGNATURE_SIZE - b.length, b.length); + } } else { @@ -492,6 +839,12 @@ else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed448) return signature; } + /** + * Return the OpenPGP packet encoding of the signature. + * + * @return OpenPGP packet encoding + * @throws IOException + */ public byte[] getEncoded() throws IOException { @@ -519,6 +872,13 @@ public byte[] getEncoded(boolean forTransfer) return bOut.toByteArray(); } + /** + * Encode the signature to an OpenPGP packet stream. + * This method does not strip out any trust packets. + * + * @param outStream packet stream + * @throws IOException + */ public void encode( OutputStream outStream) throws IOException @@ -567,15 +927,81 @@ public static boolean isCertification(int signatureType) || PGPSignature.POSITIVE_CERTIFICATION == signatureType; } + public static boolean isRevocation(int signatureType) + { + return PGPSignature.KEY_REVOCATION == signatureType + || PGPSignature.CERTIFICATION_REVOCATION == signatureType + || PGPSignature.SUBKEY_REVOCATION == signatureType; + } + + public boolean isHardRevocation() + { + if (!isRevocation(getSignatureType())) + { + return false; // no revocation + } + + if (!hasSubpackets()) + { + return true; // consider missing subpackets (and therefore missing reason) as hard revocation + } + + // only consider reasons from the hashed packet area + RevocationReason reason = getHashedSubPackets() != null ? + getHashedSubPackets().getRevocationReason() : null; + if (reason == null) + { + return true; // missing reason packet is hard + } + + byte code = reason.getRevocationReason(); + if (code >= 100 && code <= 110) + { + // private / experimental reasons are considered hard + return true; + } + + // Reason is not from the set of known soft reasons + return code != RevocationReasonTags.KEY_SUPERSEDED && + code != RevocationReasonTags.KEY_RETIRED && + code != RevocationReasonTags.USER_NO_LONGER_VALID; + } + + /** + * Return true, if the cryptographic signature encoding of the two signatures match. + * + * @param sig1 first signature + * @param sig2 second signature + * @return true if both signatures contain the same cryptographic signature + */ public static boolean isSignatureEncodingEqual(PGPSignature sig1, PGPSignature sig2) { return Arrays.areEqual(sig1.sigPck.getSignatureBytes(), sig2.sigPck.getSignatureBytes()); } + /** + * Join two copies of the same signature. + * As an entity might append additional information to an existing signatures unhashed subpacket area + * (e.g. an embedded {@link #THIRD_PARTY_CONFIRMATION} signature), an implementation might want to + * join an existing instance of a signature with an updated copy, e.g. retrieved from a key server. + * This method merges both signature instances by joining unhashed subpackets. + * + * @param sig1 first signature + * @param sig2 second signature + * @return merged signature + * @throws PGPException + */ public static PGPSignature join(PGPSignature sig1, PGPSignature sig2) throws PGPException { - if (!isSignatureEncodingEqual(sig1, sig2)) + if (sig1.getVersion() < SignaturePacket.VERSION_4) + { + // Version 2/3 signatures have no subpackets, so don't need to get merged. + return sig1; + } + + if (sig1.getVersion() != sig2.getVersion() || + !isSignatureEncodingEqual(sig1, sig2)) { throw new IllegalArgumentException("These are different signatures."); } @@ -608,6 +1034,8 @@ public static PGPSignature join(PGPSignature sig1, PGPSignature sig2) SignatureSubpacket[] unhashed = (SignatureSubpacket[])merged.toArray(new SignatureSubpacket[0]); return new PGPSignature( new SignaturePacket( + sig1.getVersion(), + sig1.sigPck.hasNewPacketFormat(), sig1.getSignatureType(), sig1.getKeyID(), sig1.getKeyAlgorithm(), diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureException.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureException.java new file mode 100644 index 0000000000..88b2887319 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureException.java @@ -0,0 +1,15 @@ +package org.bouncycastle.openpgp; + +public class PGPSignatureException + extends PGPException +{ + public PGPSignatureException(String message) + { + super(message); + } + + public PGPSignatureException(String message, Exception cause) + { + super(message, cause); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java index f38f80537b..4cabe079c0 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java @@ -5,14 +5,17 @@ import java.math.BigInteger; import java.util.Date; +import org.bouncycastle.bcpg.HashUtils; import org.bouncycastle.bcpg.MPInteger; import org.bouncycastle.bcpg.OnePassSignaturePacket; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.SignaturePacket; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; import org.bouncycastle.bcpg.sig.IssuerKeyID; import org.bouncycastle.bcpg.sig.SignatureCreationTime; +import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.openpgp.operator.PGPContentSigner; import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; import org.bouncycastle.util.Arrays; @@ -28,24 +31,69 @@ public class PGPSignatureGenerator private SignatureSubpacket[] hashed = new SignatureSubpacket[0]; private PGPContentSignerBuilder contentSignerBuilder; private PGPContentSigner contentSigner; + //private int providedKeyAlgorithm = -1; private int providedKeyAlgorithm = -1; + private PGPPublicKey signingPubKey; + private byte[] salt; /** - * Create a signature generator built on the passed in contentSignerBuilder. + * Create a version 4 signature generator built on the passed in contentSignerBuilder. * * @param contentSignerBuilder builder to produce PGPContentSigner objects for generating signatures. + * @deprecated use {@link #PGPSignatureGenerator(PGPContentSignerBuilder, PGPPublicKey)} instead. */ public PGPSignatureGenerator( PGPContentSignerBuilder contentSignerBuilder) { + this(contentSignerBuilder, SignaturePacket.VERSION_4); + } + + /** + * Create a signature generator built on the passed in contentSignerBuilder. + * + * @param contentSignerBuilder builder to produce PGPContentSigner objects for generating signatures. + * @param version signature version + */ + PGPSignatureGenerator( + PGPContentSignerBuilder contentSignerBuilder, + int version) + { + super(version); this.contentSignerBuilder = contentSignerBuilder; } + /** + * Create a signature generator built on the passed in contentSignerBuilder. + * The produces signature version will match the version of the passed in signing key. + * + * @param contentSignerBuilder builder to produce PGPContentSigner objects for generating signatures + * @param signingKey signing key + */ + public PGPSignatureGenerator( + PGPContentSignerBuilder contentSignerBuilder, + PGPPublicKey signingKey) + { + this(contentSignerBuilder, signingKey, signingKey.getVersion()); + } + + public PGPSignatureGenerator( + PGPContentSignerBuilder contentSignerBuilder, + PGPPublicKey signingKey, + int signatureVersion) + { + this(contentSignerBuilder, signatureVersion); + this.signingPubKey = signingKey; + if (signingKey.getVersion() == 6 && signatureVersion != 6) + { + throw new IllegalArgumentException("Version 6 keys MUST only generate version 6 signatures."); + } + } + /** * Initialise the generator for signing. * - * @param signatureType - * @param key + * @param signatureType type of signature + * @param key private signing key * @throws PGPException */ public void init( @@ -53,6 +101,10 @@ public void init( PGPPrivateKey key) throws PGPException { + if (signatureType == 0xFF) + { + throw new PGPException("Illegal signature type 0xFF provided."); + } contentSigner = contentSignerBuilder.build(signatureType, key); sigOut = contentSigner.getOutputStream(); sigType = contentSigner.getType(); @@ -62,8 +114,33 @@ public void init( { throw new PGPException("key algorithm mismatch"); } + + if (key.getPublicKeyPacket().getVersion() != version) + { + throw new PGPException("Key version mismatch."); + } + + if (version == SignaturePacket.VERSION_6) + { + int saltSize = HashUtils.getV6SignatureSaltSizeInBytes(contentSigner.getHashAlgorithm()); + salt = new byte[saltSize]; + CryptoServicesRegistrar.getSecureRandom().nextBytes(salt); + try + { + sigOut.write(salt); + } + catch (IOException e) + { + throw new PGPException("Cannot update signature with salt."); + } + } } + /** + * Set the hashed signature subpackets. + * Hashed signature subpackets are covered by the signature. + * @param hashedPcks hashed signature subpackets + */ public void setHashedSubpackets( PGPSignatureSubpacketVector hashedPcks) { @@ -76,6 +153,11 @@ public void setHashedSubpackets( hashed = hashedPcks.toSubpacketArray(); } + /** + * Set the unhashed signature subpackets. + * Unhashed signature subpackets are not covered by the signature. + * @param unhashedPcks unhashed signature subpackets + */ public void setUnhashedSubpackets( PGPSignatureSubpacketVector unhashedPcks) { @@ -99,7 +181,26 @@ public PGPOnePassSignature generateOnePassVersion( boolean isNested) throws PGPException { - return new PGPOnePassSignature(new OnePassSignaturePacket(sigType, contentSigner.getHashAlgorithm(), contentSigner.getKeyAlgorithm(), contentSigner.getKeyID(), isNested)); + if (version == SignaturePacket.VERSION_6) + { + return new PGPOnePassSignature(v6OPSPacket(isNested)); + } + else + { + return new PGPOnePassSignature(v3OPSPacket(isNested)); + } + } + + private OnePassSignaturePacket v3OPSPacket(boolean isNested) + { + return new OnePassSignaturePacket(sigType, contentSigner.getHashAlgorithm(), contentSigner.getKeyAlgorithm(), + contentSigner.getKeyID(), isNested); + } + + private OnePassSignaturePacket v6OPSPacket(boolean isNested) + { + return new OnePassSignaturePacket(sigType, contentSigner.getHashAlgorithm(), contentSigner.getKeyAlgorithm(), + salt, signingPubKey.getFingerprint(), isNested); } /** @@ -111,86 +212,77 @@ public PGPOnePassSignature generateOnePassVersion( public PGPSignature generate() throws PGPException { - MPInteger[] sigValues; - int version = 4; - ByteArrayOutputStream sOut = new ByteArrayOutputStream(); - SignatureSubpacket[] hPkts, unhPkts; - - if (packetNotPresent(hashed, SignatureSubpacketTags.CREATION_TIME)) - { - hPkts = insertSubpacket(hashed, new SignatureCreationTime(false, new Date())); - } - else - { - hPkts = hashed; - } - - if (packetNotPresent(hashed, SignatureSubpacketTags.ISSUER_KEY_ID) && packetNotPresent(unhashed, SignatureSubpacketTags.ISSUER_KEY_ID)) - { - unhPkts = insertSubpacket(unhashed, new IssuerKeyID(false, contentSigner.getKeyID())); - } - else - { - unhPkts = unhashed; - } + prepareSignatureSubpackets(); + ByteArrayOutputStream sOut = new ByteArrayOutputStream(); try { + // hash the "header" sOut.write((byte)version); sOut.write((byte)sigType); sOut.write((byte)contentSigner.getKeyAlgorithm()); sOut.write((byte)contentSigner.getHashAlgorithm()); + // hash signature subpackets ByteArrayOutputStream hOut = new ByteArrayOutputStream(); - - for (int i = 0; i != hPkts.length; i++) + for (int i = 0; i != hashed.length; i++) { - hPkts[i].encode(hOut); + hashed[i].encode(hOut); } - byte[] data = hOut.toByteArray(); + if (version == SignaturePacket.VERSION_6) + { + sOut.write((byte) (data.length >> 24)); + sOut.write((byte) (data.length >> 16)); + } sOut.write((byte)(data.length >> 8)); sOut.write((byte)data.length); sOut.write(data); - byte[] hData = sOut.toByteArray(); + // hash the "footer" + int dataLen = sOut.toByteArray().length; sOut.write((byte)version); sOut.write((byte)0xff); - sOut.write((byte)(hData.length >> 24)); - sOut.write((byte)(hData.length >> 16)); - sOut.write((byte)(hData.length >> 8)); - sOut.write((byte)(hData.length)); + sOut.write((byte)(dataLen >> 24)); + sOut.write((byte)(dataLen >> 16)); + sOut.write((byte)(dataLen >> 8)); + sOut.write((byte)(dataLen)); } catch (IOException e) { throw new PGPException("exception encoding hashed data.", e); } - byte[] trailer = sOut.toByteArray(); - blockUpdate(trailer, 0, trailer.length); - - if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.RSA_SIGN - || contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.RSA_GENERAL) // an RSA signature + MPInteger[] sigValues; + switch (contentSigner.getKeyAlgorithm()) + { + case PublicKeyAlgorithmTags.RSA_SIGN: + case PublicKeyAlgorithmTags.RSA_GENERAL: { sigValues = new MPInteger[1]; sigValues[0] = new MPInteger(new BigInteger(1, contentSigner.getSignature())); + break; } - else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY || - contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed25519 || - contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed448) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { byte[] enc = contentSigner.getSignature(); sigValues = new MPInteger[]{ new MPInteger(new BigInteger(1, Arrays.copyOfRange(enc, 0, enc.length / 2))), new MPInteger(new BigInteger(1, Arrays.copyOfRange(enc, enc.length / 2, enc.length))) }; + break; } - else - { + case PublicKeyAlgorithmTags.Ed25519: + case PublicKeyAlgorithmTags.Ed448: + // Contrary to EDDSA_LEGACY, the new PK algorithms Ed25519, Ed448 do not use MPI encoding + sigValues = null; + break; + default: sigValues = PGPUtil.dsaSigToMpi(contentSigner.getSignature()); + break; } byte[] digest = contentSigner.getDigest(); @@ -199,7 +291,64 @@ else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY fingerPrint[0] = digest[0]; fingerPrint[1] = digest[1]; - return new PGPSignature(new SignaturePacket(sigType, contentSigner.getKeyID(), contentSigner.getKeyAlgorithm(), contentSigner.getHashAlgorithm(), hPkts, unhPkts, fingerPrint, sigValues)); + SignaturePacket sigPckt; + if (sigValues != null) // MPI encoding + { + sigPckt = new SignaturePacket(version, sigType, contentSigner.getKeyID(), contentSigner.getKeyAlgorithm(), + contentSigner.getHashAlgorithm(), hashed, unhashed, fingerPrint, sigValues, salt); + } + else // native encoding + { + // Ed25519, Ed448 use raw encoding instead of MPI + + sigPckt = new SignaturePacket(version, sigType, contentSigner.getKeyID(), contentSigner.getKeyAlgorithm(), + contentSigner.getHashAlgorithm(), hashed, unhashed, fingerPrint, contentSigner.getSignature(), salt); + } + return new PGPSignature(sigPckt); + } + + protected void prepareSignatureSubpackets() + throws PGPException + { + switch (version) + { + case SignaturePacket.VERSION_4: + case SignaturePacket.VERSION_5: + { + // Insert hashed signature creation time if missing + if (packetNotPresent(hashed, SignatureSubpacketTags.CREATION_TIME)) + { + hashed = insertSubpacket(hashed, new SignatureCreationTime(true, new Date())); + } + + // Insert unhashed issuer key-ID if missing + if (packetNotPresent(hashed, SignatureSubpacketTags.ISSUER_KEY_ID) && packetNotPresent(unhashed, SignatureSubpacketTags.ISSUER_KEY_ID)) + { + unhashed = insertSubpacket(unhashed, new IssuerKeyID(false, contentSigner.getKeyID())); + } + + break; + } + + case SignaturePacket.VERSION_6: + { + // Insert hashed signature creation time if missing + if (packetNotPresent(hashed, SignatureSubpacketTags.CREATION_TIME)) + { + hashed = insertSubpacket(hashed, new SignatureCreationTime(true, new Date())); + } + + // Insert hashed issuer fingerprint subpacket if missing + if (packetNotPresent(hashed, SignatureSubpacketTags.ISSUER_FINGERPRINT) && + packetNotPresent(unhashed, SignatureSubpacketTags.ISSUER_FINGERPRINT) && + signingPubKey != null) + { + hashed = insertSubpacket(hashed, new IssuerFingerprint(true, version, signingPubKey.getFingerprint())); + } + + break; + } + } } /** diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketGenerator.java index 5d81b17980..33087c6c3c 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketGenerator.java @@ -1,10 +1,14 @@ package org.bouncycastle.openpgp; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.List; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.PacketFormat; import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.bcpg.sig.EmbeddedSignature; @@ -15,9 +19,12 @@ import org.bouncycastle.bcpg.sig.IssuerKeyID; import org.bouncycastle.bcpg.sig.KeyExpirationTime; import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.LibrePGPPreferredEncryptionModes; import org.bouncycastle.bcpg.sig.NotationData; import org.bouncycastle.bcpg.sig.PolicyURI; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; import org.bouncycastle.bcpg.sig.PreferredAlgorithms; +import org.bouncycastle.bcpg.sig.PreferredKeyServer; import org.bouncycastle.bcpg.sig.PrimaryUserID; import org.bouncycastle.bcpg.sig.RegularExpression; import org.bouncycastle.bcpg.sig.Revocable; @@ -35,7 +42,7 @@ */ public class PGPSignatureSubpacketGenerator { - List packets = new ArrayList(); + List packets = new ArrayList(); /** * Base constructor, creates an empty generator. @@ -53,10 +60,7 @@ public PGPSignatureSubpacketGenerator(PGPSignatureSubpacketVector sigSubV) { if (sigSubV != null) { - for (int i = 0; i != sigSubV.packets.length; i++) - { - packets.add(sigSubV.packets[i]); - } + packets.addAll(Arrays.asList(sigSubV.packets)); } } @@ -68,13 +72,22 @@ public PGPSignatureSubpacketGenerator(PGPSignatureSubpacketVector sigSubV) */ public void setRevocable(boolean isCritical, boolean isRevocable) { - if (contains(SignatureSubpacketTags.REVOCABLE)) - { - throw new IllegalStateException("Revocable exists in the Signature Subpacket Generator"); - } + removePacketsOfType(SignatureSubpacketTags.REVOCABLE); packets.add(new Revocable(isCritical, isRevocable)); } + /** + * Specify, whether the signature should be marked as exportable. + * If this subpacket is missing, the signature is treated as being exportable. + * The subpacket is marked as critical, as is required (for non-exportable signatures) by the spec. + * + * @param isExportable true if the signature should be exportable, false otherwise. + */ + public void setExportable(boolean isExportable) + { + setExportable(true, isExportable); + } + /** * Specify, whether or not the signature should be marked as exportable. * If this subpacket is missing, the signature is treated as being exportable. @@ -84,10 +97,7 @@ public void setRevocable(boolean isCritical, boolean isRevocable) */ public void setExportable(boolean isCritical, boolean isExportable) { - if (contains(SignatureSubpacketTags.EXPORTABLE)) - { - throw new IllegalStateException("Exportable Certification exists in the Signature Subpacket Generator"); - } + removePacketsOfType(SignatureSubpacketTags.EXPORTABLE); packets.add(new Exportable(isCritical, isExportable)); } @@ -95,10 +105,11 @@ public void setExportable(boolean isCritical, boolean isExportable) * Specify the set of features of the key. * * @param isCritical true if should be treated as critical, false otherwise. - * @param feature features + * @param feature features bitmap */ public void setFeature(boolean isCritical, byte feature) { + removePacketsOfType(SignatureSubpacketTags.FEATURES); packets.add(new Features(isCritical, feature)); } @@ -113,9 +124,22 @@ public void setFeature(boolean isCritical, byte feature) */ public void setTrust(boolean isCritical, int depth, int trustAmount) { + removePacketsOfType(SignatureSubpacketTags.TRUST_SIG); packets.add(new TrustSignature(isCritical, depth, trustAmount)); } + /** + * Set the number of seconds a key is valid for after the time of its creation. A + * value of zero means the key never expires. + * The subpacket will be marked as critical, as is recommended by the spec. + * + * @param seconds seconds from key creation to expiration + */ + public void setKeyExpirationTime(long seconds) + { + setKeyExpirationTime(true, seconds); + } + /** * Set the number of seconds a key is valid for after the time of its creation. A * value of zero means the key never expires. @@ -125,9 +149,23 @@ public void setTrust(boolean isCritical, int depth, int trustAmount) */ public void setKeyExpirationTime(boolean isCritical, long seconds) { + removePacketsOfType(SignatureSubpacketTags.KEY_EXPIRE_TIME); packets.add(new KeyExpirationTime(isCritical, seconds)); } + /** + * Set the number of seconds a signature is valid for after the time of its creation. + * A value of zero means the signature never expires. + * The subpacket will be marked as critical, as is recommended by the spec. + * . + * + * @param seconds seconds from signature creation to expiration + */ + public void setSignatureExpirationTime(long seconds) + { + setSignatureExpirationTime(true, seconds); + } + /** * Set the number of seconds a signature is valid for after the time of its creation. * A value of zero means the signature never expires. @@ -137,9 +175,24 @@ public void setKeyExpirationTime(boolean isCritical, long seconds) */ public void setSignatureExpirationTime(boolean isCritical, long seconds) { + removePacketsOfType(SignatureSubpacketTags.EXPIRE_TIME); packets.add(new SignatureExpirationTime(isCritical, seconds)); } + /** + * Set the creation time for the signature. + * The subpacket will be marked as critical, as is recommended by the spec. + *

      + * Note: this overrides the generation of a creation time when the signature is + * generated. + * + * @param date date + */ + public void setSignatureCreationTime(Date date) + { + setSignatureCreationTime(true, date); + } + /** * Set the creation time for the signature. *

      @@ -148,6 +201,7 @@ public void setSignatureExpirationTime(boolean isCritical, long seconds) */ public void setSignatureCreationTime(boolean isCritical, Date date) { + removePacketsOfType(SignatureSubpacketTags.CREATION_TIME); packets.add(new SignatureCreationTime(isCritical, date)); } @@ -160,6 +214,7 @@ public void setSignatureCreationTime(boolean isCritical, Date date) */ public void setPreferredHashAlgorithms(boolean isCritical, int[] algorithms) { + removePacketsOfType(SignatureSubpacketTags.PREFERRED_HASH_ALGS); packets.add(new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_HASH_ALGS, isCritical, algorithms)); } @@ -173,6 +228,7 @@ public void setPreferredHashAlgorithms(boolean isCritical, int[] algorithms) */ public void setPreferredSymmetricAlgorithms(boolean isCritical, int[] algorithms) { + removePacketsOfType(SignatureSubpacketTags.PREFERRED_SYM_ALGS); packets.add(new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_SYM_ALGS, isCritical, algorithms)); } @@ -186,27 +242,119 @@ public void setPreferredSymmetricAlgorithms(boolean isCritical, int[] algorithms */ public void setPreferredCompressionAlgorithms(boolean isCritical, int[] algorithms) { + removePacketsOfType(SignatureSubpacketTags.PREFERRED_COMP_ALGS); packets.add(new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_COMP_ALGS, isCritical, algorithms)); } /** + * This method is BROKEN! * Specify the preferred AEAD algorithms of this key. * * @param isCritical true if should be treated as critical, false otherwise. * @param algorithms array of algorithms in descending preference + * @deprecated use {@link #setPreferredAEADCiphersuites(boolean, PreferredAEADCiphersuites.Combination[])} + * or {@link #setPreferredLibrePgpEncryptionModes(boolean, int[])} instead. */ + @Deprecated public void setPreferredAEADAlgorithms(boolean isCritical, int[] algorithms) { + removePacketsOfType(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); packets.add(new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS, isCritical, algorithms)); } + /** + * Specify the preferred OpenPGP AEAD ciphersuites of this key. + * + * @param isCritical true, if this packet should be treated as critical, false otherwise. + * @param algorithms array of algorithms in descending preference + * @see + * RFC9580: Preferred AEAD Ciphersuites + */ + public void setPreferredAEADCiphersuites(boolean isCritical, PreferredAEADCiphersuites.Combination[] algorithms) + { + removePacketsOfType(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); + packets.add(new PreferredAEADCiphersuites(isCritical, algorithms)); + } + + /** + * Specify the preferred OpenPGP AEAD ciphersuites of this key. + * + * @param builder builder to build the ciphersuites packet from + * @see + * RFC9580: Preferred AEAD Ciphersuites + */ + public void setPreferredAEADCiphersuites(PreferredAEADCiphersuites.Builder builder) + { + removePacketsOfType(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); + packets.add(builder.build()); + } + + /** + * Set the preferred encryption modes for LibrePGP keys. + * Note: LibrePGP is not OpenPGP. An application strictly compliant to only the OpenPGP standard will not + * know how to handle LibrePGP encryption modes. + * The LibrePGP spec states that this subpacket shall be ignored and the application shall instead assume + * {@link org.bouncycastle.bcpg.AEADAlgorithmTags#OCB}. + * + * @param isCritical whether the packet is critical + * @param algorithms list of algorithms + * @see + * LibrePGP: Preferred Encryption Modes + * @see org.bouncycastle.bcpg.AEADAlgorithmTags for possible algorithms + * @deprecated the use of this subpacket is deprecated in LibrePGP + */ + @Deprecated + public void setPreferredLibrePgpEncryptionModes(boolean isCritical, int[] algorithms) + { + removePacketsOfType(SignatureSubpacketTags.LIBREPGP_PREFERRED_ENCRYPTION_MODES); + packets.add(new LibrePGPPreferredEncryptionModes(isCritical, algorithms)); + } + + /** + * Specify the preferred key server for the signed user-id / key. + * Note, that the key server might also be a http/ftp etc. URI pointing to the key itself. + * + * @param isCritical true if the subpacket should be treated as critical + * @param uri key server URI + * @deprecated use {@link #addPreferredKeyServer(boolean, String)} instead. + */ + @Deprecated + public void setPreferredKeyServer(boolean isCritical, String uri) + { + addPreferredKeyServer(isCritical, uri); + } + + /** + * Specify a preferred key server for the signed user-id / key. + * Note, that the key server might also be a http/ftp etc. URI pointing to the key itself. + * + * @param isCritical true if the subpacket should be treated as critical + * @param uri key server URI + */ + public void addPreferredKeyServer(boolean isCritical, String uri) + { + packets.add(new PreferredKeyServer(isCritical, uri)); + } + public void addPolicyURI(boolean isCritical, String policyUri) { packets.add(new PolicyURI(isCritical, policyUri)); } + /** + * Set this keys key flags. + * See {@link PGPKeyFlags}. + * The subpacket will be marked as critical, as is recommended by the spec. + * + * @param flags flags + */ + public void setKeyFlags(int flags) + { + setKeyFlags(true, flags); + } + /** * Set this keys key flags. * See {@link PGPKeyFlags}. @@ -216,6 +364,7 @@ public void addPolicyURI(boolean isCritical, String policyUri) */ public void setKeyFlags(boolean isCritical, int flags) { + removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); packets.add(new KeyFlags(isCritical, flags)); } @@ -299,9 +448,16 @@ public void setEmbeddedSignature(boolean isCritical, PGPSignature pgpSignature) public void addEmbeddedSignature(boolean isCritical, PGPSignature pgpSignature) throws IOException { - byte[] sig = pgpSignature.getEncoded(); + // Encode the signature forcing legacy packet format, such that we consistently cut off the proper amount + // of header bytes + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.LEGACY); + pgpSignature.encode(pOut); + pOut.close(); + byte[] sig = bOut.toByteArray(); byte[] data; + // Cut off the header bytes if (sig.length - 1 > 256) { data = new byte[sig.length - 3]; @@ -318,6 +474,7 @@ public void addEmbeddedSignature(boolean isCritical, PGPSignature pgpSignature) public void setPrimaryUserID(boolean isCritical, boolean isPrimaryUserID) { + removePacketsOfType(SignatureSubpacketTags.PRIMARY_USER_ID); packets.add(new PrimaryUserID(isCritical, isPrimaryUserID)); } @@ -360,6 +517,7 @@ public void addNotationData(boolean isCritical, boolean isHumanReadable, String */ public void setRevocationReason(boolean isCritical, byte reason, String description) { + removePacketsOfType(SignatureSubpacketTags.REVOCATION_REASON); packets.add(new RevocationReason(isCritical, reason, description)); } @@ -368,8 +526,8 @@ public void setRevocationReason(boolean isCritical, byte reason, String descript * * @param isCritical true if should be treated as critical, false otherwise. * @param keyAlgorithm algorithm of the revocation key - * @param fingerprint fingerprint of the revocation key - * @deprecated use {@link #addRevocationKey(boolean, int, byte[])} instead. + * @param fingerprint fingerprint of the revocation key (v4 only) + * @deprecated the revocation key mechanism is deprecated. Applications MUST NOT generate such a packet. */ public void setRevocationKey(boolean isCritical, int keyAlgorithm, byte[] fingerprint) { @@ -381,7 +539,8 @@ public void setRevocationKey(boolean isCritical, int keyAlgorithm, byte[] finger * * @param isCritical true if should be treated as critical, false otherwise. * @param keyAlgorithm algorithm of the revocation key - * @param fingerprint fingerprint of the revocation key + * @param fingerprint fingerprint of the revocation key (v4 only) + * @deprecated the revocation key mechanism is deprecated. Applications MUST NOT generate such a packet. */ public void addRevocationKey(boolean isCritical, int keyAlgorithm, byte[] fingerprint) { @@ -397,6 +556,7 @@ public void addRevocationKey(boolean isCritical, int keyAlgorithm, byte[] finger */ public void setIssuerKeyID(boolean isCritical, long keyID) { + removePacketsOfType(SignatureSubpacketTags.ISSUER_KEY_ID); packets.add(new IssuerKeyID(isCritical, keyID)); } @@ -410,6 +570,7 @@ public void setIssuerKeyID(boolean isCritical, long keyID) */ public void setSignatureTarget(boolean isCritical, int publicKeyAlgorithm, int hashAlgorithm, byte[] hashData) { + removePacketsOfType(SignatureSubpacketTags.SIGNATURE_TARGET); packets.add(new SignatureTarget(isCritical, publicKeyAlgorithm, hashAlgorithm, hashData)); } @@ -432,6 +593,7 @@ public void setIssuerFingerprint(boolean isCritical, PGPSecretKey secretKey) */ public void setIssuerFingerprint(boolean isCritical, PGPPublicKey publicKey) { + removePacketsOfType(SignatureSubpacketTags.ISSUER_FINGERPRINT); packets.add(new IssuerFingerprint(isCritical, publicKey.getVersion(), publicKey.getFingerprint())); } @@ -447,6 +609,19 @@ public void setIntendedRecipientFingerprint(boolean isCritical, PGPPublicKey pub addIntendedRecipientFingerprint(isCritical, publicKey); } + /** + * Adds a intended recipient fingerprint for an encrypted payload the signature is associated with. + * The subpacket will be marked as critical, as is recommended by the spec. + * + * @param publicKey the public key the encrypted payload was encrypted against. + */ + public void addIntendedRecipientFingerprint(PGPPublicKey publicKey) + { + // RFC9580 states, that the packet SHOULD be critical if generated in a v6 signature, + // but it doesn't harm to default to critical for any signature version + addIntendedRecipientFingerprint(true, publicKey); + } + /** * Adds a intended recipient fingerprint for an encrypted payload the signature is associated with. * @@ -481,6 +656,26 @@ public boolean removePacket(SignatureSubpacket packet) return packets.remove(packet); } + /** + * Remove all {@link SignatureSubpacket} objects of the given subpacketType from the underlying subpacket vector. + * + * @param subpacketType type to remove + * @return true if any packet was removed, false otherwise + */ + public boolean removePacketsOfType(int subpacketType) + { + boolean remove = false; + for (int i = packets.size() - 1; i >= 0; i--) + { + if (((SignatureSubpacket)packets.get(i)).getType() == subpacketType) + { + packets.remove(i); + remove = true; + } + } + return remove; + } + /** * Return true if a particular subpacket type exists. * @@ -527,7 +722,7 @@ public SignatureSubpacket[] getSubpackets( public PGPSignatureSubpacketVector generate() { return new PGPSignatureSubpacketVector( - (SignatureSubpacket[])packets.toArray(new SignatureSubpacket[packets.size()])); + (SignatureSubpacket[])packets.toArray(new SignatureSubpacket[0])); } private boolean contains(int type) @@ -542,6 +737,17 @@ private boolean contains(int type) return false; } + /** + * Adds a regular expression. + * The subpacket is marked as critical, as is recommended by the spec. + * + * @param regularExpression the regular expression + */ + public void addRegularExpression(String regularExpression) + { + addRegularExpression(true, regularExpression); + } + /** * Adds a regular expression. * diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketVector.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketVector.java index 7aea047a55..10e36a478e 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketVector.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureSubpacketVector.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.Date; import java.util.List; @@ -15,8 +16,10 @@ import org.bouncycastle.bcpg.sig.IssuerKeyID; import org.bouncycastle.bcpg.sig.KeyExpirationTime; import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.LibrePGPPreferredEncryptionModes; import org.bouncycastle.bcpg.sig.NotationData; import org.bouncycastle.bcpg.sig.PolicyURI; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; import org.bouncycastle.bcpg.sig.PreferredAlgorithms; import org.bouncycastle.bcpg.sig.PrimaryUserID; import org.bouncycastle.bcpg.sig.RegularExpression; @@ -34,6 +37,33 @@ */ public class PGPSignatureSubpacketVector { + /** + * Create a new {@link PGPSignatureSubpacketVector} from the given {@link Collection} of + * {@link SignatureSubpacket} items. + * If the collection is

      null
      , return an empty {@link PGPSignatureSubpacketVector}. + * + * @param packets collection of items or null + * @return PGPSignatureSubpacketVector + */ + public static PGPSignatureSubpacketVector fromSubpackets(Collection packets) + { + if (packets == null) + { + return fromSubpackets((SignatureSubpacket[]) null); + } + else + { + return fromSubpackets((SignatureSubpacket[])packets.toArray(new SignatureSubpacket[0])); + } + } + + /** + * Create a new {@link PGPSignatureSubpacketVector} from the given {@link SignatureSubpacket[]}. + * If the array is
      null
      , return an empty {@link PGPSignatureSubpacketVector}. + * + * @param packets array of items or null + * @return PGPSignatureSubpacketVector + */ public static PGPSignatureSubpacketVector fromSubpackets(SignatureSubpacket[] packets) { if (packets == null) @@ -257,6 +287,13 @@ public int[] getPreferredCompressionAlgorithms() return ((PreferredAlgorithms)p).getPreferences(); } + /** + * This method is BROKEN! + * @deprecated use {@link #getPreferredAEADCiphersuites()} or {@link #getPreferredLibrePgpEncryptionModes()} + * instead. + * @return preferred AEAD Algorithms + */ + @Deprecated public int[] getPreferredAEADAlgorithms() { SignatureSubpacket p = this.getSubpacket(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); @@ -269,6 +306,40 @@ public int[] getPreferredAEADAlgorithms() return ((PreferredAlgorithms)p).getPreferences(); } + /** + * Return the preferred AEAD ciphersuites denoted in the signature. + * + * @return OpenPGP AEAD ciphersuites + */ + public PreferredAEADCiphersuites getPreferredAEADCiphersuites() + { + SignatureSubpacket p = this.getSubpacket(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); + + if (p == null) + { + return null; + } + return (PreferredAEADCiphersuites) p; + } + + /** + * Return the preferred LibrePGP encryption modes denoted in the signature. + * Note: The LibrePGP spec states that this subpacket shall be ignored and the application + * shall instead assume {@link org.bouncycastle.bcpg.AEADAlgorithmTags#OCB}. + * + * @return LibrePGP encryption modes + */ + public int[] getPreferredLibrePgpEncryptionModes() + { + SignatureSubpacket p = this.getSubpacket(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); + + if (p == null) + { + return null; + } + return ((LibrePGPPreferredEncryptionModes) p).getPreferences(); + } + public int getKeyFlags() { SignatureSubpacket p = this.getSubpacket(SignatureSubpacketTags.KEY_FLAGS); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPV3SignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPV3SignatureGenerator.java index c743ce901c..bca26ef189 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPV3SignatureGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPV3SignatureGenerator.java @@ -19,45 +19,51 @@ public class PGPV3SignatureGenerator { private PGPContentSignerBuilder contentSignerBuilder; private PGPContentSigner contentSigner; - private int providedKeyAlgorithm = -1; +// private int providedKeyAlgorithm = -1; /** * Create a signature generator built on the passed in contentSignerBuilder. * - * @param contentSignerBuilder builder to produce PGPContentSigner objects for generating signatures. + * @param contentSignerBuilder builder to produce PGPContentSigner objects for generating signatures. */ public PGPV3SignatureGenerator( PGPContentSignerBuilder contentSignerBuilder) { + super(SignaturePacket.VERSION_3); this.contentSignerBuilder = contentSignerBuilder; } - + /** * Initialise the generator for signing. - * + * * @param signatureType * @param key * @throws PGPException */ public void init( - int signatureType, + int signatureType, PGPPrivateKey key) throws PGPException { + if (signatureType == 0xFF) + { + throw new PGPException("Illegal signature type 0xFF provided."); + } + contentSigner = contentSignerBuilder.build(signatureType, key); sigOut = contentSigner.getOutputStream(); sigType = contentSigner.getType(); lastb = 0; - if (providedKeyAlgorithm >= 0 && providedKeyAlgorithm != contentSigner.getKeyAlgorithm()) - { - throw new PGPException("key algorithm mismatch"); - } +// if (providedKeyAlgorithm >= 0 && providedKeyAlgorithm != contentSigner.getKeyAlgorithm()) +// { +// throw new PGPException("key algorithm mismatch"); +// } } /** * Return the one pass header associated with the current signature. - * + * * @param isNested * @return PGPOnePassSignature * @throws PGPException @@ -68,10 +74,10 @@ public PGPOnePassSignature generateOnePassVersion( { return new PGPOnePassSignature(new OnePassSignaturePacket(sigType, contentSigner.getHashAlgorithm(), contentSigner.getKeyAlgorithm(), contentSigner.getKeyID(), isNested)); } - + /** * Return a V3 signature object containing the current signature state. - * + * * @return PGPSignature * @throws PGPException */ @@ -95,7 +101,7 @@ public PGPSignature generate() MPInteger[] sigValues; if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.RSA_SIGN || contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.RSA_GENERAL) - // an RSA signature + // an RSA signature { sigValues = new MPInteger[1]; sigValues[0] = new MPInteger(new BigInteger(1, contentSigner.getSignature())); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/Util.java b/pg/src/main/java/org/bouncycastle/openpgp/Util.java index 76242fa45b..af4a6c68e9 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/Util.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/Util.java @@ -2,6 +2,8 @@ import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; import org.bouncycastle.bcpg.BCPGInputStream; @@ -32,4 +34,13 @@ static BCPGInputStream createBCPGInputStream(InputStream pgIn, int tag1, int tag throw new IOException("unexpected tag " + bcIn.nextPacketTag() + " encountered"); } + + static void encodePGPSignatures(OutputStream stream, List sigs, boolean forTransfer) + throws IOException + { + for (int i = 0; i != sigs.size(); i++) + { + ((PGPSignature)sigs.get(i)).encode(stream, forTransfer); + } + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/AbstractOpenPGPDocumentSignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/AbstractOpenPGPDocumentSignatureGenerator.java new file mode 100644 index 0000000000..4111697472 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/AbstractOpenPGPDocumentSignatureGenerator.java @@ -0,0 +1,326 @@ +package org.bouncycastle.openpgp.api; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.bouncycastle.bcpg.sig.PreferredAlgorithms; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.api.exception.InvalidSigningKeyException; +import org.bouncycastle.openpgp.api.exception.KeyPassphraseException; + +public class AbstractOpenPGPDocumentSignatureGenerator> +{ + + protected final OpenPGPImplementation implementation; + protected final OpenPGPPolicy policy; + + // Below lists all use the same indexing + protected final List signatureGenerators = new ArrayList(); + protected final List signingKeys = new ArrayList(); + protected final List signatureCallbacks = new ArrayList(); + protected final List signingKeyPassphraseProviders = new ArrayList(); + + protected final KeyPassphraseProvider.DefaultKeyPassphraseProvider defaultKeyPassphraseProvider = + new KeyPassphraseProvider.DefaultKeyPassphraseProvider(); + + protected SubkeySelector signingKeySelector = new SubkeySelector() + { + @Override + public List select(OpenPGPCertificate certificate, + final OpenPGPPolicy policy) + { + List result = new ArrayList(); + for (Iterator it = certificate.getSigningKeys().iterator(); it.hasNext(); ) + { + OpenPGPCertificate.OpenPGPComponentKey key = it.next(); + if (policy.isAcceptablePublicKey(key.getPGPPublicKey())) + { + result.add(key); + } + } + return result; + } + }; + + public AbstractOpenPGPDocumentSignatureGenerator(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + this.implementation = implementation; + this.policy = policy; + } + + /** + * Replace the default signing key selector with a custom implementation. + * The signing key selector is responsible for selecting one or more signing subkeys from a signing key. + * + * @param signingKeySelector selector for signing (sub-)keys + * @return this + */ + public T setSigningKeySelector(SubkeySelector signingKeySelector) + { + if (signingKeySelector == null) + { + throw new NullPointerException(); + } + this.signingKeySelector = signingKeySelector; + return (T)this; + } + + /** + * Add a passphrase for unlocking signing keys to the set of available passphrases. + * + * @param passphrase passphrase + * @return this + */ + public T addKeyPassphrase(char[] passphrase) + { + defaultKeyPassphraseProvider.addPassphrase(passphrase); + return (T)this; + } + + /** + * Add an {@link OpenPGPKey} for message signing. + * The {@link #signingKeySelector} is responsible for selecting one or more subkeys of the key to sign with. + * If no (sub-)key in the signing key is capable of creating signatures, or if the key is expired or revoked, + * this method will throw an {@link InvalidSigningKeyException}. + * + * @param key OpenPGP key + * @return this + * @throws InvalidSigningKeyException if the key is not capable of signing + */ + public T addSigningKey( + OpenPGPKey key) + throws InvalidSigningKeyException + { + return addSigningKey(key, defaultKeyPassphraseProvider); + } + + /** + * Add an {@link OpenPGPKey} for message signing, using the provided {@link KeyPassphraseProvider} to + * unlock protected subkeys. + * The {@link #signingKeySelector} is responsible for selecting one or more subkeys of the key to sign with. + * If no (sub-)key in the signing key is capable of creating signatures, or if the key is expired or revoked, + * this method will throw an {@link InvalidSigningKeyException}. + * + * @param key OpenPGP key + * @param passphraseProvider provides the passphrase to unlock the signing key + * @return this + * @throws InvalidSigningKeyException if the OpenPGP key does not contain a usable signing subkey + */ + public T addSigningKey( + OpenPGPKey key, + KeyPassphraseProvider passphraseProvider) + throws InvalidSigningKeyException + { + return addSigningKey(key, passphraseProvider, null); + } + + /** + * Add an {@link OpenPGPKey} for message signing, using the {@link SignatureParameters.Callback} to + * allow modification of the signature contents. + * The {@link #signingKeySelector} is responsible for selecting one or more subkeys of the key to sign with. + * If no (sub-)key in the signing key is capable of creating signatures, or if the key is expired or revoked, + * this method will throw an {@link InvalidSigningKeyException}. + * + * @param key OpenPGP key + * @param signatureCallback optional callback to modify the signature contents with + * @return this + * @throws InvalidSigningKeyException if the OpenPGP key does not contain a usable signing subkey + */ + public T addSigningKey( + OpenPGPKey key, + SignatureParameters.Callback signatureCallback) + throws InvalidSigningKeyException + { + return addSigningKey(key, defaultKeyPassphraseProvider, signatureCallback); + } + + /** + * Add an {@link OpenPGPKey} for message signing, using the given {@link KeyPassphraseProvider} + * for unlocking protected subkeys and using the {@link SignatureParameters.Callback} to allow + * modification of the signature contents. + * The {@link #signingKeySelector} is responsible for selecting one or more subkeys of the key to sign with. + * If no (sub-)key in the signing key is capable of creating signatures, or if the key is expired or revoked, + * this method will throw an {@link InvalidSigningKeyException}. + * + * @param key OpenPGP key + * @param passphraseProvider key passphrase provider + * @param signatureCallback optional callback to modify the signature contents with + * @return this + * @throws InvalidSigningKeyException if the OpenPGP key does not contain a usable signing subkey + */ + public T addSigningKey( + OpenPGPKey key, + KeyPassphraseProvider passphraseProvider, + SignatureParameters.Callback signatureCallback) + throws InvalidSigningKeyException + { + List signingSubkeys = signingKeySelector.select(key, policy); + if (signingSubkeys.isEmpty()) + { + throw new InvalidSigningKeyException(key); + } + + for (Iterator it = signingSubkeys.iterator(); it.hasNext(); ) + { + OpenPGPKey.OpenPGPSecretKey signingKey = key.getSecretKey((OpenPGPCertificate.OpenPGPComponentKey)it.next()); + addSigningKey(signingKey, passphraseProvider, signatureCallback); + } + + return (T)this; + } + + /** + * Add the given signing (sub-)key for message signing, using the optional passphrase to unlock the + * key in case its locked, and using the given {@link SignatureParameters.Callback} to allow + * modification of the signature contents. + * + * @param signingKey signing (sub-)key + * @param passphrase optional subkey passphrase + * @param signatureCallback optional callback to modify the signature contents + * @return this + * @throws InvalidSigningKeyException if the subkey is not signing-capable + */ + public T addSigningKey( + OpenPGPKey.OpenPGPSecretKey signingKey, + char[] passphrase, + SignatureParameters.Callback signatureCallback) + throws InvalidSigningKeyException + { + return addSigningKey( + signingKey, + defaultKeyPassphraseProvider.addPassphrase(signingKey, passphrase), + signatureCallback); + } + + /** + * Add the given signing (sub-)key for message signing, using the passphrase provider to unlock the + * key in case its locked, and using the given {@link SignatureParameters.Callback} to allow + * modification of the signature contents. + * + * @param signingKey signing (sub-)key + * @param passphraseProvider passphrase provider for unlocking the subkey + * @param signatureCallback optional callback to modify the signature contents + * @return this + * @throws InvalidSigningKeyException if the subkey is not signing-capable + */ + public T addSigningKey( + OpenPGPKey.OpenPGPSecretKey signingKey, + KeyPassphraseProvider passphraseProvider, + SignatureParameters.Callback signatureCallback) + throws InvalidSigningKeyException + { + if (!signingKey.isSigningKey()) + { + throw new InvalidSigningKeyException(signingKey); + } + + signingKeys.add(signingKey); + signingKeyPassphraseProviders.add(passphraseProvider); + signatureCallbacks.add(signatureCallback); + return (T)this; + } + + protected PGPSignatureGenerator initSignatureGenerator( + OpenPGPKey.OpenPGPSecretKey signingKey, + KeyPassphraseProvider passphraseProvider, + SignatureParameters.Callback signatureCallback) + throws PGPException + { + SignatureParameters parameters = Utils.applySignatureParameters(signatureCallback, + SignatureParameters.dataSignature(policy).setSignatureHashAlgorithm(getPreferredHashAlgorithm(signingKey))); + + if (parameters == null) + { + throw new IllegalStateException("SignatureParameters Callback MUST NOT return null."); + } + + if (!signingKey.isSigningKey(parameters.getSignatureCreationTime())) + { + throw new InvalidSigningKeyException(signingKey); + } + + char[] passphrase = passphraseProvider.getKeyPassword(signingKey); + PGPKeyPair unlockedKey = signingKey.unlock(passphrase).getKeyPair(); + if (unlockedKey == null) + { + throw new KeyPassphraseException(signingKey, new PGPException("Cannot unlock secret key.")); + } + + return Utils.getPgpSignatureGenerator(implementation, signingKey.getPGPPublicKey(), + unlockedKey.getPrivateKey(), parameters, null, null); + } + + private int getPreferredHashAlgorithm(OpenPGPCertificate.OpenPGPComponentKey key) + { + // Determine the Hash Algorithm to use by inspecting the signing key's hash algorithm preferences + // TODO: Instead inspect the hash algorithm preferences of recipient certificates? + PreferredAlgorithms hashPreferences = key.getHashAlgorithmPreferences(); + if (hashPreferences != null) + { + int[] prefs = hashPreferences.getPreferences(); + List acceptablePrefs = new ArrayList(); + for (int i = 0; i < prefs.length; i++) + { + int algo = prefs[i]; + if (policy.isAcceptableDocumentSignatureHashAlgorithm(algo, new Date())) + { + acceptablePrefs.add(algo); + } + } + if (!acceptablePrefs.isEmpty()) + { + return acceptablePrefs.get(0); + } + } + return policy.getDefaultDocumentSignatureHashAlgorithm(); +// PreferredAlgorithms hashPreferences = key.getHashAlgorithmPreferences(); +// if (hashPreferences != null) +// { +// int[] pref = Arrays.stream(hashPreferences.getPreferences()) +// .filter(new IntPredicate() +// { // Replace lambda with anonymous class for IntPredicate +// @Override +// public boolean test(int it) +// { +// return policy.isAcceptableDocumentSignatureHashAlgorithm(it, new Date()); +// } +// }) +// .toArray(); +// if (pref.length != 0) +// { +// return pref[0]; +// } +// } +// return policy.getDefaultDocumentSignatureHashAlgorithm(); + } + + /** + * Set a callback that will be fired, if a passphrase for a protected signing key is missing. + * This can be used for example to implement interactive on-demand passphrase prompting. + * + * @param callback passphrase provider + * @return builder + */ + public T setMissingKeyPassphraseCallback(KeyPassphraseProvider callback) + { + defaultKeyPassphraseProvider.setMissingPassphraseCallback(callback); + return (T)this; + } + + protected void addSignToGenerator() + throws PGPException + { + for (int i = 0; i < signingKeys.size(); i++) + { + OpenPGPKey.OpenPGPSecretKey signingKey = signingKeys.get(i); + KeyPassphraseProvider keyPassphraseProvider = signingKeyPassphraseProviders.get(i); + SignatureParameters.Callback signatureCallback = signatureCallbacks.get(i); + PGPSignatureGenerator sigGen = initSignatureGenerator(signingKey, keyPassphraseProvider, signatureCallback); + signatureGenerators.add(sigGen); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/AbstractOpenPGPKeySignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/AbstractOpenPGPKeySignatureGenerator.java new file mode 100644 index 0000000000..927131bce9 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/AbstractOpenPGPKeySignatureGenerator.java @@ -0,0 +1,181 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.CompressionAlgorithmTags; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; + +public abstract class AbstractOpenPGPKeySignatureGenerator +{ + + /** + * Standard AEAD encryption preferences (SEIPDv2). + * By default, only announce support for OCB + AES. + */ + protected SignatureSubpacketsFunction defaultAeadAlgorithmPreferences = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); + subpackets.setPreferredAEADCiphersuites(PreferredAEADCiphersuites.builder(false) + .addCombination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB) + .addCombination(SymmetricKeyAlgorithmTags.AES_192, AEADAlgorithmTags.OCB) + .addCombination(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.OCB)); + return subpackets; + } + }; + + /** + * Standard symmetric-key encryption preferences (SEIPDv1). + * By default, announce support for AES. + */ + protected SignatureSubpacketsFunction defaultSymmetricKeyPreferences = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.PREFERRED_SYM_ALGS); + subpackets.setPreferredSymmetricAlgorithms(false, new int[]{ + SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 + }); + return subpackets; + } + }; + + /** + * Standard signature hash algorithm preferences. + * By default, only announce SHA3 and SHA2 algorithms. + */ + protected SignatureSubpacketsFunction defaultHashAlgorithmPreferences = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.PREFERRED_HASH_ALGS); + subpackets.setPreferredHashAlgorithms(false, new int[]{ + HashAlgorithmTags.SHA3_512, HashAlgorithmTags.SHA3_256, + HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA256 + }); + return subpackets; + } + }; + + /** + * Standard compression algorithm preferences. + * By default, announce support for all known algorithms. + */ + protected SignatureSubpacketsFunction defaultCompressionAlgorithmPreferences = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.PREFERRED_COMP_ALGS); + subpackets.setPreferredCompressionAlgorithms(false, new int[]{ + CompressionAlgorithmTags.UNCOMPRESSED, CompressionAlgorithmTags.ZIP, + CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2 + }); + return subpackets; + } + }; + + /** + * Standard features to announce. + * By default, announce SEIPDv1 (modification detection) and SEIPDv2. + */ + protected SignatureSubpacketsFunction defaultFeatures = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.FEATURES); + subpackets.setFeature(false, (byte)(Features.FEATURE_MODIFICATION_DETECTION | Features.FEATURE_SEIPD_V2)); + return subpackets; + } + }; + + /** + * Standard signature subpackets for signing subkey's binding signatures. + * Sets the keyflag subpacket to SIGN_DATA. + */ + protected SignatureSubpacketsFunction signingSubkeySubpackets = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + subpackets.setKeyFlags(true, KeyFlags.SIGN_DATA); + return subpackets; + } + }; + + /** + * Standard signature subpackets for encryption subkey's binding signatures. + * Sets the keyflag subpacket to ENCRYPT_STORAGE|ENCRYPT_COMMS. + */ + protected SignatureSubpacketsFunction encryptionSubkeySubpackets = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + subpackets.setKeyFlags(true, KeyFlags.ENCRYPT_STORAGE | KeyFlags.ENCRYPT_COMMS); + return subpackets; + } + }; + + /** + * Standard signature subpackets for the direct-key signature. + * Sets default features, hash-, compression-, symmetric-key-, and AEAD algorithm preferences. + */ + protected SignatureSubpacketsFunction directKeySignatureSubpackets = new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets = defaultFeatures.apply(subpackets); + subpackets = defaultHashAlgorithmPreferences.apply(subpackets); + subpackets = defaultCompressionAlgorithmPreferences.apply(subpackets); + subpackets = defaultSymmetricKeyPreferences.apply(subpackets); + subpackets = defaultAeadAlgorithmPreferences.apply(subpackets); + return subpackets; + } + }; + + public void setDefaultAeadAlgorithmPreferences(SignatureSubpacketsFunction aeadAlgorithmPreferences) + { + this.defaultAeadAlgorithmPreferences = aeadAlgorithmPreferences; + } + + public void setDefaultSymmetricKeyPreferences(SignatureSubpacketsFunction symmetricKeyPreferences) + { + this.defaultSymmetricKeyPreferences = symmetricKeyPreferences; + } + + public void setDefaultHashAlgorithmPreferences(SignatureSubpacketsFunction hashAlgorithmPreferences) + { + this.defaultHashAlgorithmPreferences = hashAlgorithmPreferences; + } + + public void setDefaultCompressionAlgorithmPreferences(SignatureSubpacketsFunction compressionAlgorithmPreferences) + { + this.defaultCompressionAlgorithmPreferences = compressionAlgorithmPreferences; + } + + public void setDirectKeySignatureSubpackets(SignatureSubpacketsFunction directKeySignatureSubpackets) + { + this.directKeySignatureSubpackets = directKeySignatureSubpackets; + } + + public void setDefaultFeatures(SignatureSubpacketsFunction features) + { + this.defaultFeatures = features; + } + + public void setSigningSubkeySubpackets(SignatureSubpacketsFunction signingSubkeySubpackets) + { + this.signingSubkeySubpackets = signingSubkeySubpackets; + } + + public void setEncryptionSubkeySubpackets(SignatureSubpacketsFunction encryptionSubkeySubpackets) + { + this.encryptionSubkeySubpackets = encryptionSubkeySubpackets; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/DoubleBufferedInputStream.java b/pg/src/main/java/org/bouncycastle/openpgp/api/DoubleBufferedInputStream.java new file mode 100644 index 0000000000..63254ec488 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/DoubleBufferedInputStream.java @@ -0,0 +1,194 @@ +package org.bouncycastle.openpgp.api; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Implementation of an {@link InputStream} that double-buffers data from an underlying input stream. + * Upon reaching the end of the underlying data stream, the underlying data stream is + * automatically closed. + * Any exceptions while reading from the underlying input stream cause the {@link DoubleBufferedInputStream} + * to withhold pending data. + * This is done in order to minimize the risk of emitting unauthenticated plaintext, while at the same + * time being somewhat resource-efficient. + * The minimum number of bytes to withhold can be configured ({@link #BUFFER_SIZE} by default). + */ +public class DoubleBufferedInputStream + extends InputStream +{ + private static final int BUFFER_SIZE = 1024 * 1024 * 32; // 32 MiB + private byte[] buf1; + private byte[] buf2; + private int b1Pos; + private int b1Max; + private int b2Max; + private final I in; + private boolean closed = false; + + /** + * Create a {@link DoubleBufferedInputStream}, which buffers twice 32MiB. + * + * @param in input stream + */ + public DoubleBufferedInputStream(I in) + { + this(in, BUFFER_SIZE); + } + + /** + * Create a {@link DoubleBufferedInputStream}, which buffers twice the given buffer size in bytes. + * + * @param in input stream + * @param bufferSize buffer size + */ + public DoubleBufferedInputStream(I in, int bufferSize) + { + if (bufferSize <= 0) + { + throw new IllegalArgumentException("Buffer size cannot be zero nor negative."); + } + this.buf1 = new byte[bufferSize]; + this.buf2 = new byte[bufferSize]; + this.in = in; + b1Pos = -1; // indicate to fill() that we need to initialize + } + + /** + * Return the underlying {@link InputStream}. + * + * @return underlying input stream + */ + public I getInputStream() + { + return in; + } + + /** + * Buffer some data from the underlying {@link InputStream}. + * + * @throws IOException re-throw exceptions from the underlying input stream + */ + private void fill() + throws IOException + { + // init + if (b1Pos == -1) + { + // fill both buffers with data + b1Max = in.read(buf1); + b2Max = in.read(buf2); + + if (b2Max == -1) + { + // data fits into b1 -> close underlying stream + close(); + } + + b1Pos = 0; + return; + } + + // no data + if (b1Max <= 0) + { + return; + } + + // Reached end of buf1 + if (b1Pos == b1Max) + { + // swap buffers + byte[] t = buf1; + buf1 = buf2; + buf2 = t; + b1Max = b2Max; + + // reset reader pos + b1Pos = 0; + + // fill buf2 + try + { + b2Max = in.read(buf2); + // could not fill the buffer, or swallowed an IOException + if (b2Max != buf2.length) + { + // provoke the IOException otherwise swallowed by read(buf) + int i = in.read(); + // no exception was thrown, so either data became available, or EOF + if (i != -1) + { + // data became available, push to buf2 + buf2[b2Max++] = (byte)i; + } + } + } + catch (IOException e) + { + // set buffer max's to -1 to indicate to stop emitting data immediately + b1Max = -1; + b2Max = -1; + close(); + + throw e; + } + + // EOF + if (b2Max == -1) + { + close(); + } + } + } + + @Override + public void close() + throws IOException + { + // close the inner stream only once + if (!closed) + { + closed = true; + in.close(); + } + } + + @Override + public int read() + throws IOException + { + // fill the buffer(s) + fill(); + + // EOF / exception? + if (b1Max == -1) + { + close(); + return -1; + } + + // return byte from the buffer + return buf1[b1Pos++]; + } + + @Override + public int read(byte[] b, int off, int len) + throws IOException + { + // Fill the buffer(s) + fill(); + + // EOF / exception? + if (b1Max == -1) + { + close(); + return -1; + } + + int ret = Math.min(b1Max - b1Pos, len); + // emit data from the buffer + System.arraycopy(buf1, b1Pos, b, off, ret); + b1Pos += ret; + return ret; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/EncryptedDataPacketType.java b/pg/src/main/java/org/bouncycastle/openpgp/api/EncryptedDataPacketType.java new file mode 100644 index 0000000000..e8f5a67aa8 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/EncryptedDataPacketType.java @@ -0,0 +1,37 @@ +package org.bouncycastle.openpgp.api; + +/** + * Encryption Mode. + */ +public enum EncryptedDataPacketType +{ + /** + * Symmetrically-Encrypted Data packet. + * This method is deprecated, as it does not protect against malleability. + * + * @deprecated + */ + @Deprecated + SED, // deprecated + /** + * Symmetrically-Encrypted-Integrity-Protected Data packet version 1. + * This method protects the message using symmetric encryption as specified in RFC4880. + * Support for this encryption mode is signalled using + * {@link org.bouncycastle.bcpg.sig.Features#FEATURE_MODIFICATION_DETECTION}. + */ + SEIPDv1, // v4 + + /** + * Symmetrically-Encrypted-Integrity-Protected Data packet version 2. + * This method protects the message using an AEAD encryption scheme specified in RFC9580. + * Support for this feature is signalled using {@link org.bouncycastle.bcpg.sig.Features#FEATURE_SEIPD_V2}. + */ + SEIPDv2, // v6 + + /** + * LibrePGP OCB-Encrypted Data packet. + * This method protects the message using an AEAD encryption scheme specified in LibrePGP. + * Support for this feature is signalled using {@link org.bouncycastle.bcpg.sig.Features#FEATURE_AEAD_ENCRYPTED_DATA}. + */ + LIBREPGP_OED // "v5" +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/KeyPairGeneratorCallback.java b/pg/src/main/java/org/bouncycastle/openpgp/api/KeyPairGeneratorCallback.java new file mode 100644 index 0000000000..68825e773b --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/KeyPairGeneratorCallback.java @@ -0,0 +1,60 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; + +/** + * Callback to generate a {@link PGPKeyPair} from a {@link PGPKeyPairGenerator} instance. + */ +public abstract class KeyPairGeneratorCallback +{ + /** + * Generate a {@link PGPKeyPair} by calling a factory method on a given generator instance. + * + * @param generator PGPKeyPairGenerator + * @return generated key pair + * @throws PGPException + */ + public abstract PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException; + + public static KeyPairGeneratorCallback primaryKey() + { + return new KeyPairGeneratorCallback() + { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generatePrimaryKey(); + } + }; + } + + public static KeyPairGeneratorCallback encryptionKey() + { + return new KeyPairGeneratorCallback() + { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEncryptionSubkey(); + } + }; + } + + public static KeyPairGeneratorCallback signingKey() + { + return new KeyPairGeneratorCallback() + { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateSigningSubkey(); + } + }; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/KeyPassphraseProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/api/KeyPassphraseProvider.java new file mode 100644 index 0000000000..8c8c81eccb --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/KeyPassphraseProvider.java @@ -0,0 +1,132 @@ +package org.bouncycastle.openpgp.api; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.bouncycastle.util.Arrays; + +public interface KeyPassphraseProvider +{ + /** + * Return the passphrase for the given key. + * This callback is only fired, if the key is locked and a passphrase is required to unlock it. + * Returning null means, that the passphrase is not available. + * + * @param key the locked (sub-)key. + * @return passphrase or null + */ + char[] getKeyPassword(OpenPGPKey.OpenPGPSecretKey key); + + class DefaultKeyPassphraseProvider + implements KeyPassphraseProvider + { + private final Map passphraseMap = new HashMap(); + private final List allPassphrases = new ArrayList(); + private KeyPassphraseProvider callback; + + public DefaultKeyPassphraseProvider() + { + + } + + public DefaultKeyPassphraseProvider(OpenPGPKey key, char[] passphrase) + { + allPassphrases.add(passphrase); + + for (Iterator it = key.getSecretKeys().values().iterator(); it.hasNext(); ) + { + OpenPGPKey.OpenPGPSecretKey subkey = (OpenPGPKey.OpenPGPSecretKey)it.next(); + passphraseMap.put(subkey, passphrase); + } + } + + @Override + public char[] getKeyPassword(OpenPGPKey.OpenPGPSecretKey key) + { + if (!key.isLocked()) + { + passphraseMap.put(key, null); + return null; + } + + char[] passphrase = passphraseMap.get(key); + if (passphrase != null) + { + return passphrase; + } + + for (char[] knownPassphrase : allPassphrases) + { + if (key.isPassphraseCorrect(knownPassphrase)) + { + addPassphrase(key, knownPassphrase); + return knownPassphrase; + } + } + + if (callback != null) + { + passphrase = callback.getKeyPassword(key); + addPassphrase(key, passphrase); + } + return passphrase; + } + + public DefaultKeyPassphraseProvider addPassphrase(char[] passphrase) + { + boolean found = false; + for (Iterator it = allPassphrases.iterator(); it.hasNext();) + { + char[] existing = (char[])it.next(); + found |= (Arrays.areEqual(existing, passphrase)); + } + + if (!found) + { + allPassphrases.add(passphrase); + } + return this; + } + + public DefaultKeyPassphraseProvider addPassphrase(OpenPGPKey key, char[] passphrase) + { + for (OpenPGPKey.OpenPGPSecretKey subkey : key.getSecretKeys().values()) + { + if (!subkey.isLocked()) + { + passphraseMap.put(subkey, null); + continue; + } + + char[] existentPassphrase = passphraseMap.get(subkey); + if (existentPassphrase == null || !subkey.isPassphraseCorrect(existentPassphrase)) + { + passphraseMap.put(subkey, passphrase); + } + } + return this; + } + + public DefaultKeyPassphraseProvider addPassphrase(OpenPGPKey.OpenPGPSecretKey key, char[] passphrase) + { + if (!key.isLocked()) + { + passphraseMap.put(key, null); + return this; + } + + passphraseMap.put(key, passphrase); + + return this; + } + + public DefaultKeyPassphraseProvider setMissingPassphraseCallback(KeyPassphraseProvider callback) + { + this.callback = callback; + return this; + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/MessageEncryptionMechanism.java b/pg/src/main/java/org/bouncycastle/openpgp/api/MessageEncryptionMechanism.java new file mode 100644 index 0000000000..ddb5b8666a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/MessageEncryptionMechanism.java @@ -0,0 +1,140 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; + +/** + * Encryption mode (SEIPDv1 / SEIPDv2 / OED) and algorithms. + */ +public class MessageEncryptionMechanism +{ + private final EncryptedDataPacketType mode; + private final int symmetricKeyAlgorithm; + private final int aeadAlgorithm; + + /** + * Create a {@link MessageEncryptionMechanism} tuple. + * + * @param mode encryption mode (packet type) + * @param symmetricKeyAlgorithm symmetric key algorithm for message encryption + * @param aeadAlgorithm aead algorithm for message encryption + */ + private MessageEncryptionMechanism(EncryptedDataPacketType mode, + int symmetricKeyAlgorithm, + int aeadAlgorithm) + { + this.mode = mode; + this.symmetricKeyAlgorithm = symmetricKeyAlgorithm; + this.aeadAlgorithm = aeadAlgorithm; + } + + public EncryptedDataPacketType getMode() + { + return mode; + } + + public int getSymmetricKeyAlgorithm() + { + return symmetricKeyAlgorithm; + } + + public int getAeadAlgorithm() + { + return aeadAlgorithm; + } + + /** + * The data will not be encrypted. + * Useful for sign-only operations. + * + * @return unencrypted encryption setup + */ + public static MessageEncryptionMechanism unencrypted() + { + int none = 0; + return new MessageEncryptionMechanism(EncryptedDataPacketType.SEIPDv1, + SymmetricKeyAlgorithmTags.NULL, none); + } + + /** + * The data will be encrypted and integrity protected using a SEIPDv1 packet. + * + * @param symmetricKeyAlgorithm symmetric cipher algorithm for message encryption + * @return sym. enc. integrity protected encryption setup + */ + public static MessageEncryptionMechanism integrityProtected(int symmetricKeyAlgorithm) + { + int none = 0; + return new MessageEncryptionMechanism(EncryptedDataPacketType.SEIPDv1, symmetricKeyAlgorithm, none); + } + + /** + * The data will be OCB-encrypted as specified by the non-standard LibrePGP document. + * + * @param symmetricKeyAlgorithm symmetric key algorithm which will be combined with OCB to form + * an OCB-encrypted data packet + * @return LibrePGP OCB encryption setup + */ + public static MessageEncryptionMechanism librePgp(int symmetricKeyAlgorithm) + { + return new MessageEncryptionMechanism(EncryptedDataPacketType.LIBREPGP_OED, + symmetricKeyAlgorithm, AEADAlgorithmTags.OCB); + } + + /** + * The data will be AEAD-encrypted using the method described in RFC9580. + * + * @param symmetricKeyAlgorithm symmetric cipher algorithm + * @param aeadAlgorithm AEAD algorithm + * @return AEAD encryption setup + */ + public static MessageEncryptionMechanism aead(int symmetricKeyAlgorithm, int aeadAlgorithm) + { + return new MessageEncryptionMechanism(EncryptedDataPacketType.SEIPDv2, symmetricKeyAlgorithm, aeadAlgorithm); + } + + public static MessageEncryptionMechanism aead(PreferredAEADCiphersuites.Combination combination) + { + return aead(combination.getSymmetricAlgorithm(), combination.getAeadAlgorithm()); + } + + /** + * Return true, if the message will be encrypted. + * + * @return is encrypted + */ + public boolean isEncrypted() + { + return symmetricKeyAlgorithm != SymmetricKeyAlgorithmTags.NULL; + } + + @Override + public int hashCode() + { + return mode.hashCode() + + 13 * symmetricKeyAlgorithm + + 17 * aeadAlgorithm; + } + + @Override + public boolean equals(Object obj) + { + if (obj == null) + { + return false; + } + if (this == obj) + { + return true; + } + if (!(obj instanceof MessageEncryptionMechanism)) + { + return false; + } + MessageEncryptionMechanism m = (MessageEncryptionMechanism)obj; + return getMode() == m.getMode() + && getSymmetricKeyAlgorithm() == m.getSymmetricKeyAlgorithm() + && getAeadAlgorithm() == m.getAeadAlgorithm(); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/MissingMessagePassphraseCallback.java b/pg/src/main/java/org/bouncycastle/openpgp/api/MissingMessagePassphraseCallback.java new file mode 100644 index 0000000000..b3ff38af90 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/MissingMessagePassphraseCallback.java @@ -0,0 +1,13 @@ +package org.bouncycastle.openpgp.api; + +public interface MissingMessagePassphraseCallback +{ + /** + * Return a passphrase for message decryption. + * Returning null means, that no passphrase is available and decryption is aborted. + * + * @return passphrase + */ + char[] getMessagePassphrase(); + +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPApi.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPApi.java new file mode 100644 index 0000000000..db6e63d410 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPApi.java @@ -0,0 +1,240 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; + +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.openpgp.PGPException; + +/** + * Main entry to the high level OpenPGP API. + */ +public abstract class OpenPGPApi +{ + private final OpenPGPImplementation implementation; + private final OpenPGPPolicy policy; + + /** + * Instantiate an {@link OpenPGPApi} based on the given {@link OpenPGPImplementation}. + * + * @param implementation OpenPGP implementation + */ + public OpenPGPApi(OpenPGPImplementation implementation) + { + this(implementation, implementation.policy()); + } + + /** + * Instantiate an {@link OpenPGPApi} object, passing in an {@link OpenPGPImplementation} and custom + * {@link OpenPGPPolicy}. + * + * @param implementation OpenPGP implementation + * @param policy algorithm policy + */ + public OpenPGPApi(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + this.implementation = implementation; + this.policy = policy; + } + + /** + * Return an {@link OpenPGPKeyReader} which can be used to parse binary or ASCII armored + * {@link OpenPGPKey OpenPGPKeys} or {@link OpenPGPCertificate OpenPGPCertificates}. + * + * @return key reader + */ + public OpenPGPKeyReader readKeyOrCertificate() + { + return new OpenPGPKeyReader(implementation, policy); + } + + /** + * Return an {@link OpenPGPKeyGenerator} which can be used to generate {@link OpenPGPKey OpenPGPKeys}. + * This method returns a generator for OpenPGP v6 keys as defined by rfc9580. + * + * @return key generator + * @throws PGPException if the key generator cannot be set up + */ + public OpenPGPKeyGenerator generateKey() + throws PGPException + { + return generateKey(PublicKeyPacket.VERSION_6); + } + + /** + * Return an {@link OpenPGPKeyGenerator} which can be used to generate {@link OpenPGPKey OpenPGPKeys} + * of the given key version. + * Valid version numbers are: + *
        + *
      • {@link PublicKeyPacket#VERSION_4} (rfc4880)
      • + *
      • {@link PublicKeyPacket#VERSION_6} (rfc9580)
      • + *
      • {@link PublicKeyPacket#LIBREPGP_5} (LibrePGP; experimental)
      • + *
      + * + * @param version key version number + * @return key generator + * @throws PGPException if the key generator cannot be set up + */ + public abstract OpenPGPKeyGenerator generateKey(int version) + throws PGPException; + + /** + * Return an {@link OpenPGPKeyGenerator} which can be used to generate {@link OpenPGPKey OpenPGPKeys}. + * The key and signatures will have a creation time of the passed creationTime. + * This method returns a generator for OpenPGP v6 keys as defined by rfc9580. + * + * @param creationTime key + signature creation time + * @return key generator + * @throws PGPException if the key generator cannot be set up + */ + public OpenPGPKeyGenerator generateKey(Date creationTime) + throws PGPException + { + return generateKey(PublicKeyPacket.VERSION_6, creationTime); + } + + /** + * Return an {@link OpenPGPKeyGenerator} which can be used to generate {@link OpenPGPKey OpenPGPKeys} + * of the given key version. + * The key and signatures will have a creation time of the passed creationTime. + * Valid version numbers are: + *
        + *
      • {@link PublicKeyPacket#VERSION_4} (rfc4880)
      • + *
      • {@link PublicKeyPacket#VERSION_6} (rfc9580)
      • + *
      • {@link PublicKeyPacket#LIBREPGP_5} (LibrePGP; experimental)
      • + *
      + * + * @param version key version number + * @param creationTime key + signatures creation time + * @return key generator + * @throws PGPException if the key generator cannot be set up + */ + public abstract OpenPGPKeyGenerator generateKey(int version, + Date creationTime) + throws PGPException; + + /** + * Return an {@link OpenPGPKeyGenerator} which can be used to generate {@link OpenPGPKey OpenPGPKeys}. + * The key and signatures will have a creation time of the passed creationTime. + * If aeadProtection is true, the key will use AEAD+Argon2 to protect the secret key material, + * otherwise it will use salted+iterated CFB mode. + * This method returns a generator for OpenPGP v6 keys as defined by rfc9580. + * + * @param creationTime key + signature creation time + * @param aeadProtection whether to use AEAD or CFB protection + * @return key generator + * @throws PGPException if the key generator cannot be set up + */ + public OpenPGPKeyGenerator generateKey(Date creationTime, boolean aeadProtection) + throws PGPException + { + return generateKey(PublicKeyPacket.VERSION_6, creationTime, aeadProtection); + } + + /** + * Return an {@link OpenPGPKeyGenerator} which can be used to generate {@link OpenPGPKey OpenPGPKeys} + * of the given key version. + * The key and signatures will have a creation time of the passed creationTime. + * If aeadProtection is true, the key will use AEAD+Argon2 to protect the secret key material, + * otherwise it will use salted+iterated CFB mode. + * Valid version numbers are: + *
        + *
      • {@link PublicKeyPacket#VERSION_4} (rfc4880)
      • + *
      • {@link PublicKeyPacket#VERSION_6} (rfc9580)
      • + *
      • {@link PublicKeyPacket#LIBREPGP_5} (LibrePGP; experimental)
      • + *
      + * + * @param creationTime key + signature creation time + * @param aeadProtection whether to use AEAD or CFB protection + * @return key generator + * @throws PGPException if the key generator cannot be set up + */ + public abstract OpenPGPKeyGenerator generateKey(int version, + Date creationTime, + boolean aeadProtection) + throws PGPException; + + /** + * Create an inline-signed and/or encrypted OpenPGP message. + * + * @return message generator + */ + public OpenPGPMessageGenerator signAndOrEncryptMessage() + { + return new OpenPGPMessageGenerator(implementation, policy); + } + + /** + * Create one or more detached signatures over some data. + * + * @return signature generator + */ + public OpenPGPDetachedSignatureGenerator createDetachedSignature() + { + return new OpenPGPDetachedSignatureGenerator(implementation, policy); + } + + /** + * Decrypt and/or verify an OpenPGP message. + * + * @return message processor + */ + public OpenPGPMessageProcessor decryptAndOrVerifyMessage() + { + return new OpenPGPMessageProcessor(implementation, policy); + } + + /** + * Verify detached signatures over some data. + * + * @return signature processor + */ + public OpenPGPDetachedSignatureProcessor verifyDetachedSignature() + { + return new OpenPGPDetachedSignatureProcessor(implementation, policy); + } + + public OpenPGPKeyEditor editKey(OpenPGPKey key) + throws PGPException + { + return editKey(key, (char[]) null); + } + + public OpenPGPKeyEditor editKey(OpenPGPKey key, final char[] primaryKeyPassphrase) + throws PGPException + { + return new OpenPGPKeyEditor( + key, + new KeyPassphraseProvider() + { + @Override + public char[] getKeyPassword(OpenPGPKey.OpenPGPSecretKey key) + { + return primaryKeyPassphrase; + } + }, + implementation, + policy); + } + + /** + * Modify an {@link OpenPGPKey}. + * + * @param key OpenPGP key + * @return key editor + */ + public OpenPGPKeyEditor editKey(OpenPGPKey key, KeyPassphraseProvider primaryKeyPassphraseProvider) + throws PGPException + { + return new OpenPGPKeyEditor(key, primaryKeyPassphraseProvider, implementation, policy); + } + + /** + * Return the underlying {@link OpenPGPImplementation} of this API handle. + * + * @return OpenPGP implementation + */ + public OpenPGPImplementation getImplementation() + { + return implementation; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPCertificate.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPCertificate.java new file mode 100644 index 0000000000..267cfd72ce --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPCertificate.java @@ -0,0 +1,3635 @@ +package org.bouncycastle.openpgp.api; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyUtils; +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.KeyExpirationTime; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; +import org.bouncycastle.bcpg.sig.PreferredAlgorithms; +import org.bouncycastle.bcpg.sig.PrimaryUserID; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyRing; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureException; +import org.bouncycastle.openpgp.PGPSignatureList; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; +import org.bouncycastle.openpgp.PGPUserAttributeSubpacketVector; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.openpgp.api.exception.IncorrectOpenPGPSignatureException; +import org.bouncycastle.openpgp.api.exception.MalformedOpenPGPSignatureException; +import org.bouncycastle.openpgp.api.exception.MissingIssuerCertException; +import org.bouncycastle.openpgp.api.util.UTCUtil; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; + +/** + * OpenPGP certificates (TPKs - transferable public keys) are long-living structures that may change during + * their lifetime. A key-holder may add new components like subkeys or identities, along with associated + * binding self-signatures to the certificate and old components may expire / get revoked at some point. + * Since any such changes may have an influence on whether a data signature is valid at a given time, or what subkey + * should be used when generating an encrypted / signed message, an API is needed that provides a view on the + * certificate that takes into consideration a relevant window in time. + *

      + * Compared to a {@link PGPPublicKeyRing}, an {@link OpenPGPCertificate} has been evaluated at (or rather for) + * a given evaluation time. It offers a clean API for accessing the key-holder's preferences at a specific + * point in time and makes sure, that relevant self-signatures on certificate components are validated and verified. + * + * @see OpenPGP for Application Developers - Chapter 4 + * for background information on the terminology used in this class. + */ +public class OpenPGPCertificate +{ + final OpenPGPImplementation implementation; + final OpenPGPPolicy policy; + + protected PGPKeyRing keyRing; + + private final OpenPGPPrimaryKey primaryKey; + private final Map subkeys; + + // Note: get() needs to be accessed with OpenPGPCertificateComponent.getPublicComponent() to ensure + // proper functionality with secret key components. + private final Map componentSignatureChains; + + /** + * Instantiate an {@link OpenPGPCertificate} from a passed {@link PGPKeyRing} using the default + * {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + * + * @param keyRing key ring + */ + public OpenPGPCertificate(PGPKeyRing keyRing) + { + this(keyRing, OpenPGPImplementation.getInstance()); + } + + /** + * Instantiate an {@link OpenPGPCertificate} from a parsed {@link PGPKeyRing} + * using the provided {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + * + * @param keyRing public key ring + * @param implementation OpenPGP implementation + */ + public OpenPGPCertificate(PGPKeyRing keyRing, OpenPGPImplementation implementation) + { + this(keyRing, implementation, implementation.policy()); + } + + /** + * Instantiate an {@link OpenPGPCertificate} from a parsed {@link PGPKeyRing} + * using the provided {@link OpenPGPImplementation} and provided {@link OpenPGPPolicy}. + * + * @param keyRing public key ring + * @param implementation OpenPGP implementation + * @param policy OpenPGP policy + */ + public OpenPGPCertificate(PGPKeyRing keyRing, OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + this.implementation = implementation; + this.policy = policy; + + this.keyRing = keyRing; + this.subkeys = new LinkedHashMap(); + this.componentSignatureChains = new LinkedHashMap(); + + Iterator rawKeys = keyRing.getPublicKeys(); + + PGPPublicKey rawPrimaryKey = rawKeys.next(); + this.primaryKey = new OpenPGPPrimaryKey(rawPrimaryKey, this); + processPrimaryKey(primaryKey); + + while (rawKeys.hasNext()) + { + PGPPublicKey rawSubkey = rawKeys.next(); + OpenPGPSubkey subkey = new OpenPGPSubkey(rawSubkey, this); + subkeys.put(rawSubkey.getKeyIdentifier(), subkey); + processSubkey(subkey); + } + } + + /** + * Return true, if this object is an {@link OpenPGPKey}, false otherwise. + * + * @return true if this is a secret key + */ + public boolean isSecretKey() + { + return false; + } + + /** + * Return a {@link List} of all {@link OpenPGPUserId OpenPGPUserIds} on the certificate, regardless of their + * validity. + * + * @return all user ids + */ + public List getAllUserIds() + { + return getPrimaryKey().getUserIDs(); + } + + /** + * Return a {@link List} of all valid {@link OpenPGPUserId OpenPGPUserIds} on the certificate. + * + * @return valid user ids + */ + public List getValidUserIds() + { + return getValidUserIds(new Date()); + } + + /** + * Return a {@link List} containing all {@link OpenPGPUserId OpenPGPUserIds} that are valid at the given + * evaluation time. + * + * @param evaluationTime reference time + * @return user ids that are valid at the given evaluation time + */ + public List getValidUserIds(Date evaluationTime) + { + return getPrimaryKey().getValidUserIDs(evaluationTime); + } + + /** + * Get a {@link Map} of all public {@link OpenPGPComponentKey component keys} keyed by their {@link KeyIdentifier}. + * + * @return all public keys + */ + public Map getPublicKeys() + { + Map keys = new HashMap(); + keys.put(primaryKey.getKeyIdentifier(), primaryKey); + keys.putAll(subkeys); + return keys; + } + + /** + * Return the primary key of the certificate. + * + * @return primary key + */ + public OpenPGPPrimaryKey getPrimaryKey() + { + return primaryKey; + } + + /** + * Return a {@link Map} containing the subkeys of this certificate, keyed by their {@link KeyIdentifier}. + * Note: This map does NOT contain the primary key ({@link #getPrimaryKey()}). + * + * @return subkeys + */ + public Map getSubkeys() + { + return new LinkedHashMap(subkeys); + } + + /** + * Return a {@link List} containing all {@link OpenPGPComponentKey component keys} that carry any of the + * given key flags at evaluation time. + * + * Note: To get all component keys that have EITHER {@link KeyFlags#ENCRYPT_COMMS} OR {@link KeyFlags#ENCRYPT_STORAGE}, + * call this method like this: + *

      +     * keys = getComponentKeysWithFlag(date, KeyFlags.ENCRYPT_COMMS, KeyFlags.ENCRYPT_STORAGE);
      +     * 
      + * If you instead want to access all keys, that have BOTH flags, you need to
      &
      both flags: + *
      +     * keys = getComponentKeysWithFlag(date, KeyFlags.ENCRYPT_COMMS & KeyFlags.ENCRYPT_STORAGE);
      +     * 
      + * + * @param evaluationTime reference time + * @param keyFlags key flags + * @return list of keys that carry any of the given key flags at evaluation time + */ + public List getComponentKeysWithFlag(Date evaluationTime, final int... keyFlags) + { + return filterKeys(evaluationTime, new KeyFilter() + { + @Override + public boolean test(OpenPGPComponentKey key, Date time) + { + return key.hasKeyFlags(time, keyFlags); + } + }); + } + + /** + * Return a {@link List} containing all {@link OpenPGPCertificateComponent components} of the certificate. + * Components are primary key, subkeys and identities (user-ids, user attributes). + * + * @return list of components + */ + public List getComponents() + { + return new ArrayList(componentSignatureChains.keySet()); + } + + /** + * Return all {@link OpenPGPComponentKey OpenPGPComponentKeys} in the certificate. + * The return value is a {@link List} containing the {@link OpenPGPPrimaryKey} and all + * {@link OpenPGPSubkey OpenPGPSubkeys}. + * + * @return list of all component keys + */ + public List getKeys() + { + List keys = new ArrayList(); + keys.add(primaryKey); + keys.addAll(subkeys.values()); + return keys; + } + + /** + * Return a {@link List} of all {@link OpenPGPComponentKey component keys} that are valid right now. + * + * @return all valid keys + */ + public List getValidKeys() + { + return getValidKeys(new Date()); + } + + /** + * Return a {@link List} of all {@link OpenPGPComponentKey component keys} that are valid at the given + * evaluation time. + * + * @param evaluationTime reference time + * @return all keys that are valid at evaluation time + */ + public List getValidKeys(Date evaluationTime) + { + return filterKeys(evaluationTime, new KeyFilter() + { + @Override + public boolean test(OpenPGPComponentKey key, Date time) + { + return true; + } + }); + } + + /** + * Return the {@link OpenPGPComponentKey} identified by the passed in {@link KeyIdentifier}. + * + * @param identifier key identifier + * @return component key + */ + public OpenPGPComponentKey getKey(KeyIdentifier identifier) + { + if (identifier.matchesExplicit(getPrimaryKey().getPGPPublicKey().getKeyIdentifier())) + { + return primaryKey; + } + + return subkeys.get(identifier); + } + + /** + * Return the {@link OpenPGPComponentKey} that likely issued the passed in {@link PGPSignature}. + * + * @param signature signature + * @return issuer (sub-)key + */ + public OpenPGPComponentKey getSigningKeyFor(PGPSignature signature) + { + List keyIdentifiers = signature.getKeyIdentifiers(); + + // Subkey binding signatures do not require issuer + int type = signature.getSignatureType(); + if (type == PGPSignature.SUBKEY_BINDING || + type == PGPSignature.SUBKEY_REVOCATION) + { + return primaryKey; + } + + // issuer is primary key + if (KeyIdentifier.matches(keyIdentifiers, getPrimaryKey().getKeyIdentifier(), true)) + { + return primaryKey; + } + + for (Iterator it = subkeys.keySet().iterator(); it.hasNext(); ) + { + KeyIdentifier subkeyIdentifier = it.next(); + if (KeyIdentifier.matches(keyIdentifiers, subkeyIdentifier, true)) + { + return subkeys.get(subkeyIdentifier); + } + } + + return null; // external issuer + } + + /** + * Return the {@link PGPKeyRing} that this certificate is based on. + * + * @return underlying key ring + */ + public PGPKeyRing getPGPKeyRing() + { + return keyRing; + } + + /** + * Return the underlying {@link PGPPublicKeyRing}. + * + * @return public keys + */ + public PGPPublicKeyRing getPGPPublicKeyRing() + { + if (keyRing instanceof PGPPublicKeyRing) + { + return (PGPPublicKeyRing)keyRing; + } + + List list = new ArrayList(); + for (Iterator it = keyRing.getPublicKeys(); it.hasNext(); ) + { + list.add(it.next()); + } + return new PGPPublicKeyRing(list); + } + + /** + * Return the {@link KeyIdentifier} of the certificates primary key. + * + * @return primary key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return primaryKey.getKeyIdentifier(); + } + + /** + * Return a list of ALL (sub-)key's identifiers, including those of expired / revoked / unbound keys. + * + * @return all keys identifiers + */ + public List getAllKeyIdentifiers() + { + List identifiers = new ArrayList(); + for (Iterator it = keyRing.getPublicKeys(); it.hasNext(); ) + { + PGPPublicKey key = it.next(); + identifiers.add(key.getKeyIdentifier()); + } + return identifiers; + } + + /** + * Return the current self-certification signature. + * This is either a DirectKey signature on the primary key, or the latest self-certification on + * a {@link OpenPGPUserId}. + * + * @return latest certification signature + */ + public OpenPGPComponentSignature getCertification() + { + return getCertification(new Date()); + } + + /** + * Return the most recent self-certification signature at evaluation time. + * This is either a DirectKey signature on the primary key, or the (at evaluation time) latest + * self-certification on an {@link OpenPGPUserId}. + * + * @param evaluationTime reference time + * @return latest certification signature + */ + public OpenPGPComponentSignature getCertification(Date evaluationTime) + { + return primaryKey.getCertification(evaluationTime); + } + + /** + * Return the most recent revocation signature on the certificate. + * This is either a KeyRevocation signature on the primary key, or the latest certification revocation + * signature on an {@link OpenPGPUserId}. + * + * @return latest certification revocation + */ + public OpenPGPComponentSignature getRevocation() + { + return getRevocation(new Date()); + } + + /** + * Return the (at evaluation time) most recent revocation signature on the certificate. + * This is either a KeyRevocation signature on the primary key, or the latest certification revocation + * signature on an {@link OpenPGPUserId}. + * + * @param evaluationTime reference time + * @return latest certification revocation + */ + public OpenPGPComponentSignature getRevocation(Date evaluationTime) + { + return primaryKey.getRevocation(evaluationTime); + } + + /** + * Return the last time, the key was modified (before right now). + * A modification is the addition of a new subkey, or key signature. + * + * @return last modification time + */ + public Date getLastModificationDate() + { + return getLastModificationDateAt(new Date()); + } + + /** + * Return the last time, the key was modified before or at the given evaluation time. + * + * @param evaluationTime evaluation time + * @return last modification time before or at evaluation time + */ + public Date getLastModificationDateAt(Date evaluationTime) + { + Date latestModification = null; + // Signature creation times + for (Iterator it = getComponents().iterator(); it.hasNext(); ) + { + OpenPGPSignatureChains componentChains = getAllSignatureChainsFor(it.next()); + + componentChains = componentChains.getChainsAt(evaluationTime); + for (Iterator it2 = componentChains.iterator(); it2.hasNext(); ) + { + for (Iterator it3 = it2.next().iterator(); it3.hasNext(); ) + { + OpenPGPSignatureChain.Link link = it3.next(); + if (latestModification == null || link.since().after(latestModification)) + { + latestModification = link.since(); + } + } + } + } + + if (latestModification != null) + { + return latestModification; + } + + // Key creation times + for (Iterator it = getKeys().iterator(); it.hasNext(); ) + { + OpenPGPComponentKey key = it.next(); + if (key.getCreationTime().after(evaluationTime)) + { + continue; + } + + if (latestModification == null || key.getCreationTime().after(latestModification)) + { + latestModification = key.getCreationTime(); + } + } + return latestModification; + } + + /** + * Join two copies of the same {@link OpenPGPCertificate}, merging its {@link OpenPGPCertificateComponent components} + * into a single instance. + * The ASCII armored {@link String} might contain more than one {@link OpenPGPCertificate}. + * Items that are not a copy of the base certificate are silently ignored. + * + * @param certificate base certificate + * @param armored ASCII armored {@link String} containing one or more copies of the same certificate, + * possibly containing a different set of components + * @return merged certificate + * @throws IOException if the armored data cannot be processed + * @throws PGPException if a protocol level error occurs + */ + public static OpenPGPCertificate join(OpenPGPCertificate certificate, String armored) + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(armored.getBytes()); + InputStream decoderStream = PGPUtil.getDecoderStream(bIn); + BCPGInputStream wrapper = BCPGInputStream.wrap(decoderStream); + PGPObjectFactory objFac = certificate.implementation.pgpObjectFactory(wrapper); + + Object next; + while ((next = objFac.nextObject()) != null) + { + if (next instanceof PGPPublicKeyRing) + { + PGPPublicKeyRing publicKeys = (PGPPublicKeyRing)next; + OpenPGPCertificate otherCert = new OpenPGPCertificate(publicKeys, certificate.implementation); + try + { + return join(certificate, otherCert); + } + catch (IllegalArgumentException e) + { + // skip over wrong certificate + } + } + + else if (next instanceof PGPSecretKeyRing) + { + throw new IllegalArgumentException("Joining with a secret key is not supported."); + } + + else if (next instanceof PGPSignatureList) + { + // parse and join delegations / revocations + // those are signatures of type DIRECT_KEY or KEY_REVOCATION issued either by the primary key itself + // (self-signatures) or by a 3rd party (delegations / delegation revocations) + PGPSignatureList signatures = (PGPSignatureList)next; + + PGPPublicKeyRing publicKeys = certificate.getPGPPublicKeyRing(); + PGPPublicKey primaryKey = publicKeys.getPublicKey(); + for (Iterator it = signatures.iterator(); it.hasNext(); ) + { + primaryKey = PGPPublicKey.addCertification(primaryKey, it.next()); + } + publicKeys = PGPPublicKeyRing.insertPublicKey(publicKeys, primaryKey); + return new OpenPGPCertificate(publicKeys, certificate.implementation); + } + } + return null; + } + + /** + * Join two copies of the same {@link OpenPGPCertificate}, merging its {@link OpenPGPCertificateComponent components} + * into a single instance. + * + * @param certificate base certificate + * @param other copy of the same certificate, potentially carrying a different set of components + * @return merged certificate + * @throws PGPException if a protocol level error occurs + */ + public static OpenPGPCertificate join(OpenPGPCertificate certificate, OpenPGPCertificate other) + throws PGPException + { + PGPPublicKeyRing joined = PGPPublicKeyRing.join( + certificate.getPGPPublicKeyRing(), other.getPGPPublicKeyRing()); + return new OpenPGPCertificate(joined, certificate.implementation); + } + + /** + * Return the primary keys fingerprint in binary format. + * + * @return primary key fingerprint + */ + public byte[] getFingerprint() + { + return primaryKey.getPGPPublicKey().getFingerprint(); + } + + /** + * Return the primary keys fingerprint as a pretty-printed {@link String}. + * + * @return pretty-printed primary key fingerprint + */ + public String getPrettyFingerprint() + { + return FingerprintUtil.prettifyFingerprint(getFingerprint()); + } + + /** + * Return an ASCII armored {@link String} containing the certificate. + * + * @return armored certificate + * @throws IOException if the cert cannot be encoded + */ + public String toAsciiArmoredString() + throws IOException + { + return toAsciiArmoredString(PacketFormat.ROUNDTRIP); + } + + /** + * Return an ASCII armored {@link String} containing the certificate. + * + * @param packetFormat packet length encoding format + * @return armored certificate + * @throws IOException if the cert cannot be encoded + */ + public String toAsciiArmoredString(PacketFormat packetFormat) + throws IOException + { + ArmoredOutputStream.Builder armorBuilder = ArmoredOutputStream.builder() + .clearHeaders(); + // Add fingerprint comment + armorBuilder.addSplitMultilineComment(getPrettyFingerprint()); + + // Add user-id comments + for (Iterator it = getPrimaryKey().getUserIDs().iterator(); it.hasNext(); ) + { + armorBuilder.addEllipsizedComment(it.next().getUserId()); + } + + return toAsciiArmoredString(packetFormat, armorBuilder); + } + + /** + * Return an ASCII armored {@link String} containing the certificate. + * The {@link ArmoredOutputStream.Builder} can be used to customize the ASCII armor (headers, CRC etc.). + * + * @param packetFormat packet length encoding format + * @param armorBuilder builder for the ASCII armored output stream + * @return armored certificate + * @throws IOException if the cert cannot be encoded + */ + public String toAsciiArmoredString(PacketFormat packetFormat, ArmoredOutputStream.Builder armorBuilder) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = armorBuilder.build(bOut); + + aOut.write(getEncoded(packetFormat)); + aOut.close(); + return bOut.toString(); + } + + /** + * Return a byte array containing the binary representation of the certificate. + * + * @return binary encoded certificate + * @throws IOException if the certificate cannot be encoded + */ + public byte[] getEncoded() + throws IOException + { + return getEncoded(PacketFormat.ROUNDTRIP); + } + + /** + * Return a byte array containing the binary representation of the certificate, encoded using the + * given packet length encoding format. + * + * @param format packet length encoding format + * @return binary encoded certificate + * @throws IOException if the certificate cannot be encoded + */ + public byte[] getEncoded(PacketFormat format) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, format); + + // Make sure we export a TPK + List list = new ArrayList(); + for (Iterator it = getPGPKeyRing().getPublicKeys(); it.hasNext(); ) + { + list.add(it.next()); + } + PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(list); + + publicKeys.encode(pOut, true); + pOut.close(); + return bOut.toByteArray(); + } + + private OpenPGPSignatureChain getSignatureChainFor(OpenPGPCertificateComponent component, + OpenPGPComponentKey origin, + Date evaluationDate) + { + // Check if there are signatures at all for the component + OpenPGPSignatureChains chainsForComponent = getAllSignatureChainsFor(component); + boolean isPrimaryKey = component == getPrimaryKey(); + if (isPrimaryKey && chainsForComponent.getCertificationAt(evaluationDate) == null) + { + // If cert has no direct-key signatures, consider primary UID bindings instead + OpenPGPUserId primaryUserId = getPrimaryUserId(evaluationDate); + if (primaryUserId != null) + { + chainsForComponent.addAll(getAllSignatureChainsFor(primaryUserId)); + } + } + + // Isolate chains which originate from the passed origin key component + OpenPGPSignatureChains fromOrigin = chainsForComponent.fromOrigin(origin); + if (fromOrigin == null) + { + return null; + } + + // Return chain that currently takes precedence + return fromOrigin.getChainAt(evaluationDate); + } + + /** + * Return all {@link OpenPGPSignatureChain OpenPGPSignatureChains} binding the given + * {@link OpenPGPCertificateComponent}. + * + * @param component certificate component + * @return all chains of the component + */ + private OpenPGPSignatureChains getAllSignatureChainsFor(OpenPGPCertificateComponent component) + { + OpenPGPSignatureChains chains = new OpenPGPSignatureChains(component.getPublicComponent()); + chains.addAll(componentSignatureChains.get(component.getPublicComponent())); + return chains; + } + + /** + * Process the given {@link OpenPGPPrimaryKey}, parsing all its signatures and identities. + * + * @param primaryKey primary key + */ + private void processPrimaryKey(OpenPGPPrimaryKey primaryKey) + { + OpenPGPSignatureChains keySignatureChains = new OpenPGPSignatureChains(primaryKey); + List keySignatures = primaryKey.getKeySignatures(); + + // Key Signatures + addSignaturesToChains(keySignatures, keySignatureChains); + componentSignatureChains.put(primaryKey, keySignatureChains); + + // Identities + for (Iterator it = primaryKey.identityComponents.iterator(); it.hasNext(); ) + { + OpenPGPIdentityComponent identity = it.next(); + OpenPGPSignatureChains identityChains = new OpenPGPSignatureChains(identity); + List bindings; + + if (identity instanceof OpenPGPUserId) + { + bindings = primaryKey.getUserIdSignatures((OpenPGPUserId)identity); + } + else + { + bindings = primaryKey.getUserAttributeSignatures((OpenPGPUserAttribute)identity); + } + addSignaturesToChains(bindings, identityChains); + componentSignatureChains.put(identity, identityChains); + } + } + + /** + * Process the given {@link OpenPGPSubkey}, parsing all its binding signatures. + * + * @param subkey subkey + */ + private void processSubkey(OpenPGPSubkey subkey) + { + List bindingSignatures = subkey.getKeySignatures(); + OpenPGPSignatureChains subkeyChains = new OpenPGPSignatureChains(subkey); + + for (Iterator it = bindingSignatures.iterator(); it.hasNext(); ) + { + OpenPGPComponentSignature sig = it.next(); + OpenPGPComponentKey issuer = subkey.getCertificate().getSigningKeyFor(sig.getSignature()); + if (issuer == null) + { + continue; // external key + } + + OpenPGPSignatureChains issuerChains = getAllSignatureChainsFor(issuer); + if (!issuerChains.chains.isEmpty()) + { + for (Iterator it2 = issuerChains.chains.iterator(); it2.hasNext(); ) + { + subkeyChains.add(it2.next().plus(sig)); + } + } + else + { + subkeyChains.add(new OpenPGPSignatureChain(OpenPGPSignatureChain.Link.create(sig))); + } + } + this.componentSignatureChains.put(subkey, subkeyChains); + } + + /** + * Return true, if the passed in component is - at evaluation time - properly bound to the certificate. + * + * @param component OpenPGP certificate component + * @param evaluationTime evaluation time + * @return true if component is bound at evaluation time, false otherwise + */ + private boolean isBound(OpenPGPCertificateComponent component, + Date evaluationTime) + { + return isBoundBy(component, getPrimaryKey(), evaluationTime); + } + + /** + * Return true, if the passed in component is - at evaluation time - properly bound to the certificate with + * a signature chain originating at the passed in root component. + * + * @param component OpenPGP certificate component + * @param root root certificate component + * @param evaluationTime evaluation time + * @return true if component is bound at evaluation time, originating at root, false otherwise + */ + private boolean isBoundBy(OpenPGPCertificateComponent component, + OpenPGPComponentKey root, + Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket keyExpiration = + component.getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.KEY_EXPIRE_TIME); + if (keyExpiration != null) + { + KeyExpirationTime kexp = (KeyExpirationTime)keyExpiration.getSubpacket(); + if (kexp.getTime() != 0) + { + OpenPGPComponentKey key = component.getKeyComponent(); + Date expirationDate = new Date(1000 * kexp.getTime() + key.getCreationTime().getTime()); + if (expirationDate.before(evaluationTime)) + { + // Key is expired. + return false; + } + } + } + + try + { + OpenPGPSignatureChain chain = getSignatureChainFor(component, root, evaluationTime); + if (chain == null) + { + // Component is not bound at all + return false; + } + + // Chain needs to be valid (signatures correct) + if (chain.isValid(implementation.pgpContentVerifierBuilderProvider(), policy)) + { + // Chain needs to not contain a revocation signature, otherwise the component is considered revoked + return !chain.isRevocation(); + } + + // Signature is not correct + return false; + } + catch (PGPException e) + { + // Signature verification failed (signature broken?) + return false; + } + } + + /** + * Return a {@link List} containing all currently marked, valid encryption keys. + * + * @return encryption keys + */ + public List getEncryptionKeys() + { + return getEncryptionKeys(new Date()); + } + + /** + * Return a list of all keys that are - at evaluation time - valid encryption keys. + * + * @param evaluationTime evaluation time + * @return encryption keys + */ + public List getEncryptionKeys(Date evaluationTime) + { + return filterKeys(evaluationTime, new KeyFilter() + { + @Override + public boolean test(OpenPGPComponentKey key, Date time) + { + return key.isEncryptionKey(time); + } + }); + } + + /** + * Return a {@link List} containing all currently valid marked signing keys. + * + * @return list of signing keys + */ + public List getSigningKeys() + { + return getSigningKeys(new Date()); + } + + /** + * Return a list of all keys that - at evaluation time - are validly marked as signing keys. + * + * @param evaluationTime evaluation time + * @return list of signing keys + */ + public List getSigningKeys(Date evaluationTime) + { + return filterKeys(evaluationTime, new KeyFilter() + { + @Override + public boolean test(OpenPGPComponentKey key, Date time) + { + return key.isSigningKey(time); + } + }); + } + + /** + * Return a {@link List} containing all currently valid marked certification keys. + * + * @return list of certification keys + */ + public List getCertificationKeys() + { + return getCertificationKeys(new Date()); + } + + /** + * Return a list of all keys that - at evaluation time - are validly marked as certification keys. + * + * @param evaluationTime evaluation time + * @return list of certification keys + */ + public List getCertificationKeys(Date evaluationTime) + { + return filterKeys(evaluationTime, new KeyFilter() + { + @Override + public boolean test(OpenPGPComponentKey key, Date time) + { + return key.isCertificationKey(time); + } + }); + } + + /** + * Return {@link OpenPGPSignatureChains} that contain preference information. + * + * @return signature chain containing certificate-wide preferences (typically DK signature) + */ + private OpenPGPSignatureChain getPreferenceSignature(Date evaluationTime) + { + OpenPGPSignatureChain directKeyBinding = getPrimaryKey().getSignatureChains() + .fromOrigin(getPrimaryKey()) + .getCertificationAt(evaluationTime); + + if (directKeyBinding != null) + { + return directKeyBinding; + } + + List uidBindings = new ArrayList(); + for (Iterator it = getPrimaryKey().getUserIDs().iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain uidBinding = getAllSignatureChainsFor(it.next()) + .fromOrigin(getPrimaryKey()).getCertificationAt(evaluationTime); + + if (uidBinding != null) + { + uidBindings.add(uidBinding); + } + } + + //uidBindings.sort(Comparator.comparing(OpenPGPSignatureChain::getSince).reversed()); + uidBindings.sort(new Comparator() + { + @Override + public int compare(OpenPGPSignatureChain o1, OpenPGPSignatureChain o2) + { + // Reverse comparison for descending order (mimics .reversed()) + return o2.getSince().compareTo(o1.getSince()); + } + }); + for (Iterator it = uidBindings.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain binding = it.next(); + PGPSignature sig = binding.getSignature().getSignature(); + if (sig.getHashedSubPackets().isPrimaryUserID()) + { + return binding; + } + } + + return uidBindings.isEmpty() ? null : uidBindings.get(0); + } + + /** + * Return all identities ({@link OpenPGPUserId User IDs}, {@link OpenPGPUserAttribute User Attributes} + * of the certificate. + * + * @return identities + */ + public List getIdentities() + { + return new ArrayList(primaryKey.identityComponents); + } + + /** + * Return the current primary {@link OpenPGPUserId} of the certificate. + * + * @return primary user id + */ + public OpenPGPUserId getPrimaryUserId() + { + return getPrimaryUserId(new Date()); + } + + /** + * Return the {@link OpenPGPUserId} that is considered primary at the given evaluation time. + * + * @param evaluationTime evaluation time + * @return primary user-id at evaluation time + */ + public OpenPGPUserId getPrimaryUserId(Date evaluationTime) + { + return primaryKey.getExplicitOrImplicitPrimaryUserId(evaluationTime); + } + + /** + * Return the {@link OpenPGPUserId} object matching the given user-id {@link String}. + * + * @param userId user-id + * @return user-id + */ + public OpenPGPUserId getUserId(String userId) + { + for (Iterator it = primaryKey.getUserIDs().iterator(); it.hasNext(); ) + { + OpenPGPUserId uid = (OpenPGPUserId)it.next(); + if (uid.getUserId().equals(userId)) + { + return uid; + } + } + return null; + } + + /** + * Return the time at which the certificate expires. + * + * @return expiration time of the certificate + */ + public Date getExpirationTime() + { + return getExpirationTime(new Date()); + } + + /** + * Return the time at which the certificate is expected to expire, considering the given evaluation time. + * + * @param evaluationTime reference time + * @return expiration time at evaluation time + */ + public Date getExpirationTime(Date evaluationTime) + { + return getPrimaryKey().getKeyExpirationDateAt(evaluationTime); + } + + /** + * Return an {@link OpenPGPSignatureChain} from the given 3rd-party certificate to this certificate, + * which represents a delegation of trust. + * If no delegation signature is found, return null. + * + * @param thirdPartyCertificate {@link OpenPGPCertificate} of a 3rd party. + * @return chain containing the latest delegation issued by the 3rd-party certificate + */ + public OpenPGPSignatureChain getDelegationBy(OpenPGPCertificate thirdPartyCertificate) + { + return getDelegationBy(thirdPartyCertificate, new Date()); + } + + /** + * Return an {@link OpenPGPSignatureChain} from the given 3rd-party certificate to this certificate, + * which represents a delegation of trust at evaluation time. + * If no delegation signature is found, return null. + * + * @param thirdPartyCertificate {@link OpenPGPCertificate} of a 3rd party. + * @param evaluationTime reference time + * @return chain containing the (at evaluation time) latest delegation issued by the 3rd-party certificate + */ + public OpenPGPSignatureChain getDelegationBy( + OpenPGPCertificate thirdPartyCertificate, + Date evaluationTime) + { + OpenPGPSignatureChains chainsBy = getPrimaryKey(). + getMergedDanglingExternalSignatureChainEndsFrom(thirdPartyCertificate, evaluationTime); + return chainsBy.getCertificationAt(evaluationTime); + } + + /** + * Return an {@link OpenPGPSignatureChain} from the given 3rd-party certificate to this certificate, + * which represents a revocation of trust. + * + * @param thirdPartyCertificate {@link OpenPGPCertificate} of a 3rd party. + * @return chain containing the latest revocation issued by the 3rd party certificate + */ + public OpenPGPSignatureChain getRevocationBy(OpenPGPCertificate thirdPartyCertificate) + { + return getRevocationBy(thirdPartyCertificate, new Date()); + } + + /** + * Return an {@link OpenPGPSignatureChain} from the given 3rd-party certificate to this certificate, + * which (at evaluation time) represents a revocation of trust. + * + * @param thirdPartyCertificate {@link OpenPGPCertificate} of a 3rd party. + * @param evaluationTime reference time + * @return chain containing the (at evaluation time) latest revocation issued by the 3rd party certificate + */ + public OpenPGPSignatureChain getRevocationBy( + OpenPGPCertificate thirdPartyCertificate, + Date evaluationTime) + { + OpenPGPSignatureChains chainsBy = getPrimaryKey() + .getMergedDanglingExternalSignatureChainEndsFrom(thirdPartyCertificate, evaluationTime); + return chainsBy.getRevocationAt(evaluationTime); + } + + /** + * Component on an OpenPGP certificate. + * Components can either be {@link OpenPGPComponentKey keys} or {@link OpenPGPIdentityComponent identities}. + */ + public static abstract class OpenPGPCertificateComponent + { + private final OpenPGPCertificate certificate; + + public OpenPGPCertificateComponent(OpenPGPCertificate certificate) + { + this.certificate = certificate; + } + + /** + * Return this components {@link OpenPGPCertificate}. + * + * @return certificate + */ + public OpenPGPCertificate getCertificate() + { + return certificate; + } + + /** + * Return a detailed String representation of this component. + * + * @return detailed String representation + */ + public abstract String toDetailString(); + + /** + * Return true, if the component is currently validly bound to the certificate. + * + * @return true if bound + */ + public boolean isBound() + { + return isBoundAt(new Date()); + } + + /** + * Return true, if this component is - at evaluation time - properly bound to its certificate. + * + * @param evaluationTime evaluation time + * @return true if bound, false otherwise + */ + public boolean isBoundAt(Date evaluationTime) + { + return getCertificate().isBound(this, evaluationTime); + } + + /** + * Return all {@link OpenPGPSignatureChains} that bind this component. + * + * @return signature chains + */ + public OpenPGPSignatureChains getSignatureChains() + { + OpenPGPSignatureChains chains = getCertificate().getAllSignatureChainsFor(this); + if (getPublicComponent() instanceof OpenPGPPrimaryKey) + { + OpenPGPPrimaryKey pk = (OpenPGPPrimaryKey)getPublicComponent(); + if (!pk.getUserIDs().isEmpty()) + { + chains.addAll(getCertificate().getAllSignatureChainsFor(pk.getUserIDs().get(0))); + } + } + return chains; + } + + /** + * Return the (at evaluation time) latest certification signature binding this component. + * + * @param evaluationTime reference time + * @return latest component certification signature + */ + public OpenPGPComponentSignature getCertification(Date evaluationTime) + { + OpenPGPSignatureChain certification = getSignatureChains().getCertificationAt(evaluationTime); + if (certification != null) + { + return certification.getSignature(); + } + return null; + } + + /** + * Return the (at evaluation time) latest revocation signature revoking this component. + * + * @param evaluationTime reference time + * @return latest component revocation signature + */ + public OpenPGPComponentSignature getRevocation(Date evaluationTime) + { + OpenPGPSignatureChain revocation = getSignatureChains().getRevocationAt(evaluationTime); + if (revocation != null) + { + return revocation.getSignature(); + } + return null; + } + + /** + * Return the latest self-signature on the component. + * That might either be a certification signature, or a revocation. + * + * @return latest self signature + */ + public OpenPGPComponentSignature getLatestSelfSignature() + { + return getLatestSelfSignature(new Date()); + } + + /** + * Return the (at evaluation time) latest self-signature on the component. + * That might either be a certification signature, or a revocation. + * + * @param evaluationTime reference time + * @return latest self signature + */ + public abstract OpenPGPComponentSignature getLatestSelfSignature(Date evaluationTime); + + /** + * Return the public {@link OpenPGPCertificateComponent} that belongs to this component. + * For public components (pubkeys, identities...), that's simply this, while secret components + * return their corresponding public component. + * This is used to properly map secret key and public key components in {@link Map Maps} that use + * {@link OpenPGPCertificateComponent components} as map keys. + * + * @return public certificate component + */ + protected OpenPGPCertificateComponent getPublicComponent() + { + return this; + } + + /** + * Return the {@link OpenPGPComponentKey} belonging to this {@link OpenPGPCertificateComponent}. + * If this {@link OpenPGPCertificateComponent} is an instance of {@link OpenPGPComponentKey}, + * the method simply returns
      this
      . + * If instead, the {@link OpenPGPCertificateComponent} is an {@link OpenPGPIdentityComponent}, + * the primary key it is bound to is returned. + * + * @return {@link OpenPGPComponentKey} of this {@link OpenPGPCertificateComponent}. + */ + protected abstract OpenPGPComponentKey getKeyComponent(); + + /** + * Return the {@link KeyFlags} signature subpacket that currently applies to the key. + * + * @return key flags subpacket + */ + public KeyFlags getKeyFlags() + { + return getKeyFlags(new Date()); + } + + /** + * Return the {@link KeyFlags} signature subpacket that - at evaluation time - applies to the key. + * + * @param evaluationTime evaluation time + * @return key flags subpacket + */ + public KeyFlags getKeyFlags(Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = getApplyingSubpacket( + evaluationTime, SignatureSubpacketTags.KEY_FLAGS); + if (subpacket != null) + { + return (KeyFlags)subpacket.getSubpacket(); + } + return null; + } + + /** + * Return
      true
      , if the key has any of the given key flags. + *

      + * Note: To check if the key has EITHER flag A or B, call

      hasKeyFlags(evalTime, A, B)
      . + * To instead check, if the key has BOTH flags A AND B, call
      hasKeyFlags(evalTime, A & B)
      . + * + * @param evaluationTime evaluation time + * @param flags key flags (see {@link KeyFlags} for possible values) + * @return true if the key has ANY of the provided flags + */ + public boolean hasKeyFlags(Date evaluationTime, int... flags) + { + KeyFlags keyFlags = getKeyFlags(evaluationTime); + if (keyFlags == null) + { + // Key has no key-flags + return false; + } + + // Check if key has the desired key-flags + for (int i = 0; i < flags.length; ++i) + { + if (((keyFlags.getFlags() & flags[i]) == flags[i])) + { + return true; + } + } + return false; + } + + /** + * Return the {@link Features} signature subpacket that currently applies to the key. + * + * @return feature signature subpacket + */ + public Features getFeatures() + { + return getFeatures(new Date()); + } + + /** + * Return the {@link Features} signature subpacket that - at evaluation time - applies to the key. + * + * @param evaluationTime evaluation time + * @return features subpacket + */ + public Features getFeatures(Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.FEATURES); + if (subpacket != null) + { + return (Features)subpacket.getSubpacket(); + } + return null; + } + + /** + * Return the {@link PreferredAEADCiphersuites} that apply to this (sub-)key. + * Note: This refers to AEAD preferences as defined in rfc9580, NOT LibrePGP AEAD algorithms. + * + * @return AEAD algorithm preferences + */ + public PreferredAEADCiphersuites getAEADCipherSuitePreferences() + { + return getAEADCipherSuitePreferences(new Date()); + } + + /** + * Return the {@link PreferredAEADCiphersuites} that - at evaluation time - apply to this (sub-)key. + * Note: This refers to AEAD preferences as defined in rfc9580, NOT LibrePGP AEAD algorithms. + * + * @param evaluationTime evaluation time + * @return AEAD algorithm preferences at evaluation time + */ + public PreferredAEADCiphersuites getAEADCipherSuitePreferences(Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = getApplyingSubpacket(evaluationTime, + SignatureSubpacketTags.PREFERRED_AEAD_ALGORITHMS); + if (subpacket != null) + { + return (PreferredAEADCiphersuites)subpacket.getSubpacket(); + } + return null; + } + + /** + * Return the current symmetric encryption algorithm preferences of this (sub-)key. + * + * @return current preferred symmetric-key algorithm preferences + */ + public PreferredAlgorithms getSymmetricCipherPreferences() + { + return getSymmetricCipherPreferences(new Date()); + } + + /** + * Return the symmetric encryption algorithm preferences of this (sub-)key at evaluation time. + * + * @param evaluationTime evaluation time + * @return current preferred symmetric-key algorithm preferences + */ + public PreferredAlgorithms getSymmetricCipherPreferences(Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.PREFERRED_SYM_ALGS); + if (subpacket != null) + { + return (PreferredAlgorithms)subpacket.getSubpacket(); + } + return null; + } + + /** + * Return the current signature hash algorithm preferences of this (sub-)key. + * + * @return hash algorithm preferences + */ + public PreferredAlgorithms getHashAlgorithmPreferences() + { + return getHashAlgorithmPreferences(new Date()); + } + + /** + * Return the signature hash algorithm preferences of this (sub-)key at evaluation time. + * + * @param evaluationTime evaluation time + * @return hash algorithm preferences + */ + public PreferredAlgorithms getHashAlgorithmPreferences(Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.PREFERRED_HASH_ALGS); + if (subpacket != null) + { + return (PreferredAlgorithms)subpacket.getSubpacket(); + } + return null; + } + + /** + * Return the compression algorithm preferences of this (sub-)key. + * + * @return compression algorithm preferences + */ + public PreferredAlgorithms getCompressionAlgorithmPreferences() + { + return getCompressionAlgorithmPreferences(new Date()); + } + + /** + * Return the compression algorithm preferences of this (sub-)key at evaluation time. + * + * @param evaluationTime reference time + * @return compression algorithm preferences + */ + public PreferredAlgorithms getCompressionAlgorithmPreferences(Date evaluationTime) + { + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.PREFERRED_COMP_ALGS); + if (subpacket != null) + { + return (PreferredAlgorithms)subpacket.getSubpacket(); + } + return null; + } + + /** + * Return the {@link Date}, at which the key expires. + * + * @return key expiration time + */ + public Date getKeyExpirationDate() + { + return getKeyExpirationDateAt(new Date()); + } + + /** + * Return the {@link Date}, at which the key - at evaluation time - expires. + * + * @param evaluationTime evaluation time + * @return key expiration time + */ + public Date getKeyExpirationDateAt(Date evaluationTime) + { + return getLatestSelfSignature(evaluationTime).getKeyExpirationTime(); + } + + /** + * Return the {@link SignatureSubpacket} instance of the given subpacketType, which currently applies to + * the key. Since subpackets from the Direct-Key signature apply to all subkeys of a certificate, + * this method first inspects the signature that immediately applies to this key (e.g. a subkey-binding + * signature), and - if the queried subpacket is found in there, returns that instance. + * Otherwise, indirectly applying signatures (e.g. Direct-Key signatures) are queried. + * That way, preferences from the direct-key signature are considered, but per-key overwrites take precedence. + * + * @param evaluationTime evaluation time + * @param subpacketType subpacket type that is being searched for + * @return subpacket from directly or indirectly applying signature + * @see + * OpenPGP for application developers - Attribute Shadowing + */ + protected OpenPGPSignature.OpenPGPSignatureSubpacket getApplyingSubpacket(Date evaluationTime, int subpacketType) + { + OpenPGPSignatureChain binding = getSignatureChains().getCertificationAt(evaluationTime); + if (binding == null) + { + // is not bound + return null; + } + + // Check signatures + try + { + if (!binding.isValid()) + { + // Binding is incorrect + return null; + } + } + catch (PGPSignatureException e) + { + // Binding cannot be verified + return null; + } + + // find signature "closest to the key", e.g. subkey binding signature + OpenPGPComponentSignature keySignature = binding.getSignature(); + + PGPSignatureSubpacketVector hashedSubpackets = keySignature.getSignature().getHashedSubPackets(); + if (hashedSubpackets == null || !hashedSubpackets.hasSubpacket(subpacketType)) + { + // If the subkey binding signature doesn't carry the desired subpacket, + // check direct-key or primary uid sig instead + OpenPGPSignatureChain preferenceBinding = getCertificate().getPreferenceSignature(evaluationTime); + if (preferenceBinding == null) + { + // No direct-key / primary uid sig found -> No subpacket + return null; + } + keySignature = preferenceBinding.getSignature(); + hashedSubpackets = keySignature.getSignature().getHashedSubPackets(); + } + // else -> attribute from DK sig is shadowed by SB sig + + // Extract subpacket from hashed area + SignatureSubpacket subpacket = hashedSubpackets.getSubpacket(subpacketType); + if (subpacket == null) + { + return null; + } + return OpenPGPSignature.OpenPGPSignatureSubpacket.hashed(subpacket, keySignature); + } + + /** + * Iterate over signatures issued over this component by the given 3rd-party certificate, + * merge them with the (at evaluation time) valid self-certification chain and return the + * results. + * + * @param thirdPartyCertificate certificate of a 3rd party + * @param evaluationTime reference time + * @return all 3rd party signatures on this component, merged with their issuer chains + */ + protected OpenPGPSignatureChains getMergedDanglingExternalSignatureChainEndsFrom( + OpenPGPCertificate thirdPartyCertificate, + Date evaluationTime) + { + OpenPGPSignatureChains chainsBy = new OpenPGPSignatureChains(this); + + OpenPGPSignatureChains allChains = getCertificate().getAllSignatureChainsFor(this) + .getChainsAt(evaluationTime); + for (Iterator it = allChains.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain.Link rootLink = it.next().getRootLink(); + for (Iterator it2 = thirdPartyCertificate.getKeys().iterator(); it2.hasNext(); ) + { + OpenPGPComponentKey issuerKey = it2.next(); + if (KeyIdentifier.matches( + rootLink.getSignature().getKeyIdentifiers(), + issuerKey.getKeyIdentifier(), + true)) + { + OpenPGPSignatureChain externalChain = issuerKey.getSignatureChains().getChainAt(evaluationTime); + externalChain = externalChain.plus( + new OpenPGPComponentSignature(rootLink.signature.getSignature(), issuerKey, this)); + chainsBy.add(externalChain); + } + } + } + return chainsBy; + } + } + + /** + * OpenPGP Signature made over some {@link OpenPGPCertificateComponent} on a {@link OpenPGPCertificate}. + */ + public static class OpenPGPComponentSignature + extends OpenPGPSignature + { + + private final OpenPGPCertificateComponent target; + + /** + * Component signature. + * + * @param signature signature + * @param issuer key that issued the signature. + * Is nullable (e.g. for 3rd party sigs where the certificate is not available). + * @param target signed certificate component + */ + public OpenPGPComponentSignature(PGPSignature signature, + OpenPGPComponentKey issuer, + OpenPGPCertificateComponent target) + { + super(signature, issuer); + this.target = target; + } + + /** + * Return the {@link OpenPGPComponentKey} that issued this signature. + * + * @return issuer + */ + public OpenPGPComponentKey getIssuerComponent() + { + return getIssuer(); + } + + /** + * Return the {@link OpenPGPCertificateComponent} that this signature was calculated over. + * + * @return target + */ + public OpenPGPCertificateComponent getTargetComponent() + { + return target; + } + + /** + * Return the {@link OpenPGPComponentKey} that this signature is calculated over. + * Contrary to {@link #getTargetComponent()}, which returns the actual target, this method returns the + * {@link OpenPGPComponentKey} "closest" to the target. + * For a subkey-binding signature, this is the target subkey, while for an identity-binding signature + * (binding for a user-id or attribute) the return value is the {@link OpenPGPComponentKey} which + * carries the identity. + * + * @return target key component of the signature + */ + public OpenPGPComponentKey getTargetKeyComponent() + { + if (getTargetComponent() instanceof OpenPGPIdentityComponent) + { + // Identity signatures indirectly authenticate the primary key + return ((OpenPGPIdentityComponent)getTargetComponent()).getPrimaryKey(); + } + if (getTargetComponent() instanceof OpenPGPComponentKey) + { + // Key signatures authenticate the target key + return (OpenPGPComponentKey)getTargetComponent(); + } + throw new IllegalArgumentException("Unknown target type."); + } + + /** + * Return the key expiration time stored in the signature. + * + * @return key expiration time + */ + public Date getKeyExpirationTime() + { + PGPSignatureSubpacketVector hashed = signature.getHashedSubPackets(); + if (hashed == null) + { + // v3 sigs have no expiration + return null; + } + long exp = hashed.getKeyExpirationTime(); + if (exp < 0) + { + throw new RuntimeException("Negative key expiration time"); + } + + if (exp == 0L) + { + // Explicit or implicit no expiration + return null; + } + + return new Date(getTargetKeyComponent().getCreationTime().getTime() + 1000 * exp); + } + + /** + * Verify this signature. + * + * @param implementation OpenPGP implementation + * @throws PGPSignatureException if the signature cannot be verified successfully + */ + public void verify(OpenPGPImplementation implementation) + throws PGPSignatureException + { + verify(implementation.pgpContentVerifierBuilderProvider(), implementation.policy()); + } + + /** + * Verify this signature. + * + * @param contentVerifierBuilderProvider provider for verifiers + * @param policy algorithm policy + * @throws PGPSignatureException if the signature cannot be verified successfully + */ + public void verify(PGPContentVerifierBuilderProvider contentVerifierBuilderProvider, + OpenPGPPolicy policy) + throws PGPSignatureException + { + if (issuer == null) + { + // No issuer available + throw new MissingIssuerCertException(this, "Issuer certificate unavailable."); + } + + sanitize(issuer, policy); + + // Direct-Key signature + if (signature.getSignatureType() == PGPSignature.DIRECT_KEY + || signature.getSignatureType() == PGPSignature.KEY_REVOCATION) + { + verifyKeySignature( + issuer, + target.getKeyComponent(), + contentVerifierBuilderProvider); + } + + // Subkey binding signature + else if (signature.getSignatureType() == PGPSignature.SUBKEY_BINDING) + { + // For signing-capable subkeys, check the embedded primary key binding signature + verifyEmbeddedPrimaryKeyBinding(contentVerifierBuilderProvider, policy, getCreationTime()); + + // Binding signature MUST NOT predate the subkey itself + if (((OpenPGPSubkey)target).getCreationTime().after(signature.getCreationTime())) + { + isCorrect = false; + throw new MalformedOpenPGPSignatureException(this, "Subkey binding signature predates subkey creation time."); + } + + verifyKeySignature( + issuer, + (OpenPGPSubkey)target, + contentVerifierBuilderProvider); + } + + else if (signature.getSignatureType() == PGPSignature.SUBKEY_REVOCATION) + { + // Binding signature MUST NOT predate the subkey itself + if (((OpenPGPSubkey)target).getCreationTime().after(signature.getCreationTime())) + { + isCorrect = false; + throw new MalformedOpenPGPSignatureException(this, "Subkey revocation signature predates subkey creation time."); + } + + verifyKeySignature( + issuer, + (OpenPGPSubkey)target, + contentVerifierBuilderProvider); + } + + // User-ID binding + else if (target instanceof OpenPGPUserId) + { + verifyUserIdSignature( + issuer, + (OpenPGPUserId)target, + contentVerifierBuilderProvider); + } + + // User-Attribute binding + else if (target instanceof OpenPGPUserAttribute) + { + verifyUserAttributeSignature( + issuer, + (OpenPGPUserAttribute)target, + contentVerifierBuilderProvider); + } + + else + { + throw new PGPSignatureException("Unexpected signature type: " + getType()); + } + } + + /** + * Verify a signature of type {@link PGPSignature#PRIMARYKEY_BINDING}, which is typically embedded as + * {@link org.bouncycastle.bcpg.sig.EmbeddedSignature} inside a signature of type + * {@link PGPSignature#SUBKEY_BINDING} for a signing capable subkey. + * + * @param contentVerifierBuilderProvider provider for content verifier builders + * @param policy algorithm policy + * @param signatureCreationTime creation time of the signature + * @throws PGPSignatureException if an exception happens during signature verification + */ + private void verifyEmbeddedPrimaryKeyBinding(PGPContentVerifierBuilderProvider contentVerifierBuilderProvider, + OpenPGPPolicy policy, Date signatureCreationTime) + throws PGPSignatureException + { + int keyFlags = signature.getHashedSubPackets().getKeyFlags(); + if ((keyFlags & KeyFlags.SIGN_DATA) != KeyFlags.SIGN_DATA) + { + // Non-signing key - no embedded primary key binding sig required + return; + } + + OpenPGPComponentKey subkey = getTargetKeyComponent(); + // Signing subkey needs embedded primary key binding signature + List embeddedSignatures = new ArrayList(); + try + { + PGPSignatureList sigList = signature.getHashedSubPackets().getEmbeddedSignatures(); + addSignatures(embeddedSignatures, sigList); + sigList = signature.getUnhashedSubPackets().getEmbeddedSignatures(); + addSignatures(embeddedSignatures, sigList); + } + catch (PGPException e) + { + throw new PGPSignatureException("Cannot extract embedded signature.", e); + } + + if (embeddedSignatures.isEmpty()) + { + throw new MalformedOpenPGPSignatureException( + this, + "Signing key SubkeyBindingSignature MUST contain embedded PrimaryKeyBindingSignature."); + } + + PGPSignatureException exception = null; + for (Iterator it = embeddedSignatures.iterator(); it.hasNext(); ) + { + PGPSignature primaryKeyBinding = it.next(); + OpenPGPCertificate.OpenPGPComponentSignature backSig = + new OpenPGPCertificate.OpenPGPComponentSignature( + primaryKeyBinding, + subkey, + issuer); + + if (primaryKeyBinding.getSignatureType() != PGPSignature.PRIMARYKEY_BINDING) + { + exception = new PGPSignatureException("Unexpected embedded signature type: " + primaryKeyBinding.getSignatureType()); + continue; + } + + if (!backSig.isEffectiveAt(signatureCreationTime)) + { + exception = new PGPSignatureException("Embedded PrimaryKeyBinding signature is expired or not yet effective."); + continue; + } + + try + { + backSig.sanitize(subkey, policy); + + // needs to be called last to prevent false positives + backSig.verifyKeySignature(subkey, issuer, contentVerifierBuilderProvider); + + // valid -> return successfully + return; + } + catch (PGPSignatureException e) + { + exception = e; + } + } + + // if we end up here, it means we have only found invalid sigs + throw exception; + } + + private static void addSignatures(List embeddedSignatures, PGPSignatureList sigList) + { + for (Iterator it = sigList.iterator(); it.hasNext(); ) + { + embeddedSignatures.add(it.next()); + } + } + + /** + * Verify a signature of type {@link PGPSignature#DIRECT_KEY}, {@link PGPSignature#KEY_REVOCATION}, + * {@link PGPSignature#SUBKEY_BINDING} or {@link PGPSignature#SUBKEY_REVOCATION}. + * + * @param issuer issuing component key + * @param target targeted component key + * @param contentVerifierBuilderProvider provider for content verifier builders + * @throws PGPSignatureException if an exception happens during signature verification + */ + protected void verifyKeySignature( + OpenPGPComponentKey issuer, + OpenPGPComponentKey target, + PGPContentVerifierBuilderProvider contentVerifierBuilderProvider) + throws PGPSignatureException + { + this.isTested = true; + try + { + signature.init(contentVerifierBuilderProvider, issuer.getPGPPublicKey()); + if (signature.getSignatureType() == PGPSignature.DIRECT_KEY + || signature.getSignatureType() == PGPSignature.KEY_REVOCATION) + { + // Direct-Key Signature + isCorrect = signature.verifyCertification(target.getPGPPublicKey()); + } + else if (signature.getSignatureType() == PGPSignature.PRIMARYKEY_BINDING) + { + isCorrect = signature.verifyCertification(target.getPGPPublicKey(), issuer.getPGPPublicKey()); + } + else + { + // Subkey Binding Signature + isCorrect = signature.verifyCertification(issuer.getPGPPublicKey(), target.getPGPPublicKey()); + } + + if (!isCorrect) + { + throw new IncorrectOpenPGPSignatureException(this, "Key Signature is not correct."); + } + } + catch (PGPException e) + { + this.isCorrect = false; + throw new PGPSignatureException("Key Signature could not be verified.", e); + } + } + + /** + * Verify a certification signature over an {@link OpenPGPUserId}. + * The signature is of type {@link PGPSignature#DEFAULT_CERTIFICATION}, {@link PGPSignature#NO_CERTIFICATION}, + * {@link PGPSignature#CASUAL_CERTIFICATION}, {@link PGPSignature#POSITIVE_CERTIFICATION} or + * {@link PGPSignature#CERTIFICATION_REVOCATION}. + * + * @param issuer issuing component key + * @param target targeted userid + * @param contentVerifierBuilderProvider provider for content verifier builders + * @throws PGPSignatureException if an exception happens during signature verification + */ + protected void verifyUserIdSignature(OpenPGPComponentKey issuer, + OpenPGPUserId target, + PGPContentVerifierBuilderProvider contentVerifierBuilderProvider) + throws PGPSignatureException + { + this.isTested = true; + try + { + signature.init(contentVerifierBuilderProvider, issuer.getPGPPublicKey()); + isCorrect = signature.verifyCertification(target.getUserId(), target.getPrimaryKey().getPGPPublicKey()); + if (!isCorrect) + { + throw new IncorrectOpenPGPSignatureException(this, "UserID Signature is not correct."); + } + } + catch (PGPException e) + { + this.isCorrect = false; + throw new PGPSignatureException("UserID Signature could not be verified.", e); + } + } + + /** + * Verify a certification signature over an {@link OpenPGPUserAttribute}. + * The signature is of type {@link PGPSignature#DEFAULT_CERTIFICATION}, {@link PGPSignature#NO_CERTIFICATION}, + * {@link PGPSignature#CASUAL_CERTIFICATION}, {@link PGPSignature#POSITIVE_CERTIFICATION} or + * {@link PGPSignature#CERTIFICATION_REVOCATION}. + * + * @param issuer issuing component key + * @param target targeted userid + * @param contentVerifierBuilderProvider provider for content verifier builders + * @throws PGPSignatureException if an exception happens during signature verification + */ + protected void verifyUserAttributeSignature(OpenPGPComponentKey issuer, + OpenPGPUserAttribute target, + PGPContentVerifierBuilderProvider contentVerifierBuilderProvider) + throws PGPSignatureException + { + this.isTested = true; + try + { + signature.init(contentVerifierBuilderProvider, issuer.getPGPPublicKey()); + isCorrect = signature.verifyCertification(target.getUserAttribute(), target.getPrimaryKey().getPGPPublicKey()); + if (!isCorrect) + { + throw new IncorrectOpenPGPSignatureException(this, "UserAttribute Signature is not correct."); + } + } + catch (PGPException e) + { + this.isCorrect = false; + throw new PGPSignatureException("Could not verify UserAttribute Signature.", e); + } + } + + @Override + protected String getTargetDisplay() + { + return target.toString(); + } + } + + /** + * A component key is either an {@link OpenPGPPrimaryKey}, or an {@link OpenPGPSubkey}. + * + * @see + * OpenPGP for Application Developers - Layers of keys in OpenPGP + */ + public static abstract class OpenPGPComponentKey + extends OpenPGPCertificateComponent + { + protected final PGPPublicKey rawPubkey; + + /** + * Constructor. + * + * @param rawPubkey public key + * @param certificate certificate + */ + public OpenPGPComponentKey(PGPPublicKey rawPubkey, OpenPGPCertificate certificate) + { + super(certificate); + this.rawPubkey = rawPubkey; + } + + /** + * Return the underlying {@link PGPPublicKey} of this {@link OpenPGPComponentKey}. + * + * @return public key + */ + public PGPPublicKey getPGPPublicKey() + { + return rawPubkey; + } + + /** + * Return the {@link KeyIdentifier} of this key. + * + * @return key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + return rawPubkey.getKeyIdentifier(); + } + + /** + * Return the public key algorithm. + * + * @return public key algorithm id + * @see org.bouncycastle.bcpg.PublicKeyAlgorithmTags + */ + public int getAlgorithm() + { + return getPGPPublicKey().getAlgorithm(); + } + + /** + * Return the public key version. + * + * @return key version + */ + public int getVersion() + { + return getPGPPublicKey().getVersion(); + } + + /** + * Return the creation time of this key. + * + * @return creation time + */ + public Date getCreationTime() + { + return rawPubkey.getCreationTime(); + } + + /** + * Return true, if this {@link OpenPGPComponentKey} represents the primary key of an {@link OpenPGPCertificate}. + * + * @return true if primary, false if subkey + */ + public abstract boolean isPrimaryKey(); + + @Override + public OpenPGPComponentSignature getLatestSelfSignature(Date evaluationTime) + { + OpenPGPSignatureChain currentDKChain = getSignatureChains().getChainAt(evaluationTime); + if (currentDKChain != null && !currentDKChain.chainLinks.isEmpty()) + { + return currentDKChain.getSignature(); + } + return null; + } + + /** + * Return true, if the key is currently marked as encryption key. + * + * @return true if the key is an encryption key, false otherwise + */ + public boolean isEncryptionKey() + { + return isEncryptionKey(new Date()); + } + + /** + * Return true, if the is - at evaluation time - marked as an encryption key. + * + * @param evaluationTime evaluation time + * @return true if key is an encryption key at evaluation time, false otherwise + */ + public boolean isEncryptionKey(Date evaluationTime) + { + if (!rawPubkey.isEncryptionKey()) + { + // Skip keys that are not encryption-capable by algorithm + return false; + } + + return hasKeyFlags(evaluationTime, KeyFlags.ENCRYPT_STORAGE) || + hasKeyFlags(evaluationTime, KeyFlags.ENCRYPT_COMMS); + } + + /** + * Return true, if the key is currently marked as a signing key for message signing. + * + * @return true, if key is currently signing key + */ + public boolean isSigningKey() + { + return isSigningKey(new Date()); + } + + /** + * Return true, if the key is - at evaluation time - marked as signing key for message signing. + * + * @param evaluationTime evaluation time + * @return true if key is signing key at evaluation time + */ + public boolean isSigningKey(Date evaluationTime) + { + if (!PublicKeyUtils.isSigningAlgorithm(rawPubkey.getAlgorithm())) + { + // Key is not signing-capable by algorithm + return false; + } + + return hasKeyFlags(evaluationTime, KeyFlags.SIGN_DATA); + } + + /** + * Return true, if the key is currently marked as certification key that can sign 3rd-party certificates. + * + * @return true, if key is certification key + */ + public boolean isCertificationKey() + { + return isCertificationKey(new Date()); + } + + /** + * Return true, if the key is - at evaluation time - marked as certification key that can sign 3rd-party + * certificates. + * + * @param evaluationTime evaluation time + * @return true if key is certification key at evaluation time + */ + public boolean isCertificationKey(Date evaluationTime) + { + if (!PublicKeyUtils.isSigningAlgorithm(rawPubkey.getAlgorithm())) + { + // Key is not signing-capable by algorithm + return false; + } + + return hasKeyFlags(evaluationTime, KeyFlags.CERTIFY_OTHER); + } + + @Override + protected OpenPGPComponentKey getKeyComponent() + { + // This already IS a component key + return this; + } + + @Override + public int hashCode() + { + return getPGPPublicKey().hashCode(); + } + + @Override + public boolean equals(Object obj) + { + if (obj == null) + { + return false; + } + if (this == obj) + { + return true; + } + if (!(obj instanceof OpenPGPComponentKey)) + { + return false; + } + OpenPGPComponentKey other = (OpenPGPComponentKey)obj; + return getPGPPublicKey().equals(other.getPGPPublicKey()); + } + } + + /** + * The primary key of a {@link OpenPGPCertificate}. + */ + public static class OpenPGPPrimaryKey + extends OpenPGPComponentKey + { + @Override + public String toString() + { + return "PrimaryKey[" + Long.toHexString(getKeyIdentifier().getKeyId()).toUpperCase(Locale.getDefault()) + "]"; + } + + @Override + public String toDetailString() + { + return "PrimaryKey[" + getKeyIdentifier() + "] (" + UTCUtil.format(getCreationTime()) + ")"; + } + + protected final List identityComponents; + + public OpenPGPPrimaryKey(PGPPublicKey rawPubkey, OpenPGPCertificate certificate) + { + super(rawPubkey, certificate); + this.identityComponents = new ArrayList(); + + Iterator userIds = rawPubkey.getUserIDs(); + while (userIds.hasNext()) + { + identityComponents.add(new OpenPGPUserId(userIds.next(), this)); + } + + Iterator userAttributes = rawPubkey.getUserAttributes(); + while (userAttributes.hasNext()) + { + identityComponents.add(new OpenPGPUserAttribute(userAttributes.next(), this)); + } + } + + @Override + public boolean isPrimaryKey() + { + return true; + } + + /** + * Return the latest DirectKey self-signature on this primary key. + * + * @return latest direct key self-signature. + */ + public OpenPGPComponentSignature getLatestDirectKeySelfSignature() + { + return getLatestDirectKeySelfSignature(new Date()); + } + + /** + * Return the (at evaluation time) latest DirectKey self-signature on this primary key. + * + * @param evaluationTime reference time + * @return latest (at evaluation time) direct key self-signature + */ + public OpenPGPComponentSignature getLatestDirectKeySelfSignature(Date evaluationTime) + { + OpenPGPSignatureChain currentDKChain = getCertificate().getAllSignatureChainsFor(this) + .getCertificationAt(evaluationTime); + if (currentDKChain != null && !currentDKChain.chainLinks.isEmpty()) + { + return currentDKChain.getSignature(); + } + + return null; + } + + /** + * Return the latest KeyRevocation self-signature on this primary key. + * + * @return latest key revocation self-signature + */ + public OpenPGPComponentSignature getLatestKeyRevocationSelfSignature() + { + return getLatestKeyRevocationSelfSignature(new Date()); + } + + /** + * Return the (at evaluation time) latest KeyRevocation self-signature on this primary key. + * + * @param evaluationTime reference time + * @return latest (at evaluation time) key revocation self-signature + */ + public OpenPGPComponentSignature getLatestKeyRevocationSelfSignature(Date evaluationTime) + { + OpenPGPSignatureChain currentRevocationChain = getCertificate().getAllSignatureChainsFor(this) + .getRevocationAt(evaluationTime); + if (currentRevocationChain != null && !currentRevocationChain.chainLinks.isEmpty()) + { + return currentRevocationChain.getSignature(); + } + return null; + } + + @Override + public OpenPGPComponentSignature getLatestSelfSignature(Date evaluationTime) + { + List signatures = new ArrayList(); + + OpenPGPComponentSignature directKeySig = getLatestDirectKeySelfSignature(evaluationTime); + if (directKeySig != null) + { + signatures.add(directKeySig); + } + + OpenPGPComponentSignature keyRevocation = getLatestKeyRevocationSelfSignature(evaluationTime); + if (keyRevocation != null) + { + signatures.add(keyRevocation); + } + + for (Iterator it = getCertificate().getIdentities().iterator(); it.hasNext(); ) + { + OpenPGPComponentSignature identitySig = it.next().getLatestSelfSignature(evaluationTime); + if (identitySig != null) + { + signatures.add(identitySig); + } + } + + OpenPGPComponentSignature latest = null; + for (Iterator it = signatures.iterator(); it.hasNext(); ) + { + OpenPGPComponentSignature signature = it.next(); + if (latest == null || signature.getCreationTime().after(latest.getCreationTime())) + { + latest = signature; + } + } + return latest; + } + + /** + * Return all {@link OpenPGPUserId OpenPGPUserIds} on this key. + * + * @return user ids + */ + public List getUserIDs() + { + List userIds = new ArrayList(); + for (Iterator it = identityComponents.iterator(); it.hasNext(); ) + { + OpenPGPIdentityComponent identity = it.next(); + if (identity instanceof OpenPGPUserId) + { + userIds.add((OpenPGPUserId)identity); + } + } + return userIds; + } + + /** + * Return a {@link List} containing all currently valid {@link OpenPGPUserId OpenPGPUserIds} on this + * primary key. + * + * @return valid userids + */ + public List getValidUserIds() + { + return getValidUserIDs(new Date()); + } + + /** + * Return a {@link List} containing all valid (at evaluation time) {@link OpenPGPUserId OpenPGPUserIds} + * on this primary key. + * + * @param evaluationTime reference time + * @return valid (at evaluation time) userids + */ + public List getValidUserIDs(Date evaluationTime) + { + List userIds = new ArrayList(); + for (Iterator it = identityComponents.iterator(); it.hasNext(); ) + { + OpenPGPIdentityComponent identity = it.next(); + if (identity instanceof OpenPGPUserId && identity.isBoundAt(evaluationTime)) + { + userIds.add((OpenPGPUserId)identity); + } + } + return userIds; + } + + /** + * Return the {@link OpenPGPUserId}, which is - at evaluation time - explicitly marked as primary. + * + * @param evaluationTime evaluation time + * @return explicit primary userid + */ + public OpenPGPUserId getExplicitPrimaryUserId(Date evaluationTime) + { + // Return the latest, valid, explicitly marked as primary UserID + OpenPGPSignature latestBinding = null; + OpenPGPUserId latestUid = null; + + for (Iterator it = getUserIDs().iterator(); it.hasNext(); ) + { + OpenPGPUserId userId = it.next(); + OpenPGPSignature.OpenPGPSignatureSubpacket subpacket = + userId.getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.PRIMARY_USER_ID); + if (subpacket == null) + { + // Not bound at this time, or not explicit + continue; + } + + PrimaryUserID primaryUserId = (PrimaryUserID)subpacket.getSubpacket(); + if (!primaryUserId.isPrimaryUserID()) + { + // explicitly marked as not primary + continue; + } + + if (latestBinding == null || + subpacket.getSignature().getCreationTime().after(latestBinding.getCreationTime())) + { + latestBinding = subpacket.getSignature(); + latestUid = userId; + } + } + return latestUid; + } + + /** + * Return the {@link OpenPGPUserId}, which is - at evaluation time - considered primary, + * either because it is explicitly marked as primary userid, or because it is implicitly primary + * (e.g. because it is the sole user-id on the key). + * + * @param evaluationTime evaluation time + * @return primary user-id + */ + public OpenPGPUserId getExplicitOrImplicitPrimaryUserId(Date evaluationTime) + { + OpenPGPUserId explicitPrimaryUserId = getExplicitPrimaryUserId(evaluationTime); + if (explicitPrimaryUserId != null) + { + return explicitPrimaryUserId; + } + + // If no explicitly marked, valid primary UserID is found, return the oldest, valid UserId instead. + OpenPGPSignature oldestBinding = null; + OpenPGPUserId oldestUid = null; + + for (Iterator it = getUserIDs().iterator(); it.hasNext(); ) + { + OpenPGPUserId userId = it.next(); + OpenPGPSignatureChain chain = userId.getSignatureChains() + .getCertificationAt(evaluationTime); + if (chain == null) + { + // Not valid at this time + continue; + } + + OpenPGPSignature binding = chain.getSignature(); + if (oldestBinding == null || + binding.getCreationTime().before(oldestBinding.getCreationTime())) + { + oldestBinding = binding; + oldestUid = userId; + } + } + return oldestUid; + } + + /** + * Return all {@link OpenPGPUserAttribute OpenPGPUserAttributes} on this key. + * + * @return user attributes + */ + public List getUserAttributes() + { + List userAttributes = new ArrayList(); + for (Iterator it = identityComponents.iterator(); it.hasNext(); ) + { + OpenPGPIdentityComponent identity = it.next(); + if (identity instanceof OpenPGPUserAttribute) + { + userAttributes.add((OpenPGPUserAttribute)identity); + } + } + return userAttributes; + } + + /** + * Return all direct-key and key-revocation signatures on the primary key. + * + * @return key signatures + */ + protected List getKeySignatures() + { + Iterator iterator = rawPubkey.getSignatures(); + List list = new ArrayList(); + while (iterator.hasNext()) + { + PGPSignature sig = iterator.next(); + int type = sig.getSignatureType(); + if (type != PGPSignature.DIRECT_KEY && type != PGPSignature.KEY_REVOCATION) + { + continue; + } + // try to find issuer for self-signature + OpenPGPCertificate.OpenPGPComponentKey issuer = getCertificate() + .getSigningKeyFor(sig); + + list.add(new OpenPGPCertificate.OpenPGPComponentSignature(sig, issuer, this)); + } + return list; + } + + /** + * Return all signatures on the given {@link OpenPGPUserId}. + * + * @param identity user-id + * @return list of user-id signatures + */ + protected List getUserIdSignatures(OpenPGPUserId identity) + { + Iterator iterator = rawPubkey.getSignaturesForID(identity.getUserId()); + return signIterToList(identity, iterator); + } + + /** + * Return all signatures on the given {@link OpenPGPUserAttribute}. + * + * @param identity user-attribute + * @return list of user-attribute signatures + */ + protected List getUserAttributeSignatures(OpenPGPUserAttribute identity) + { + Iterator iterator = rawPubkey.getSignaturesForUserAttribute(identity.getUserAttribute()); + return signIterToList(identity, iterator); + } + + private List signIterToList(OpenPGPIdentityComponent identity, Iterator iterator) + { + List list = new ArrayList(); + while (iterator.hasNext()) + { + PGPSignature sig = iterator.next(); + // try to find issuer for self-signature + OpenPGPComponentKey issuer = getCertificate() + .getSigningKeyFor(sig); + + list.add(new OpenPGPComponentSignature(sig, issuer, identity)); + } + return list; + } + } + + /** + * A subkey on a {@link OpenPGPCertificate}. + */ + public static class OpenPGPSubkey + extends OpenPGPComponentKey + { + public OpenPGPSubkey(PGPPublicKey rawPubkey, OpenPGPCertificate certificate) + { + super(rawPubkey, certificate); + } + + @Override + public boolean isPrimaryKey() + { + return false; + } + + @Override + public String toString() + { + return "Subkey[" + Long.toHexString(getKeyIdentifier().getKeyId()).toUpperCase(Locale.getDefault()) + "]"; + } + + @Override + public String toDetailString() + { + return "Subkey[" + getKeyIdentifier() + "] (" + UTCUtil.format(getCreationTime()) + ")"; + } + + /** + * Return all subkey-binding and -revocation signatures on the subkey. + * + * @return subkey signatures + */ + protected List getKeySignatures() + { + Iterator iterator = rawPubkey.getSignatures(); + List list = new ArrayList(); + while (iterator.hasNext()) + { + PGPSignature sig = iterator.next(); + int type = sig.getSignatureType(); + if (type != PGPSignature.SUBKEY_BINDING && type != PGPSignature.SUBKEY_REVOCATION) + { + continue; + } + // try to find issuer for self-signature + OpenPGPCertificate.OpenPGPComponentKey issuer = getCertificate() + .getSigningKeyFor(sig); + + list.add(new OpenPGPCertificate.OpenPGPComponentSignature(sig, issuer, this)); + } + return list; + } + } + + /** + * An identity bound to the {@link OpenPGPPrimaryKey} of a {@link OpenPGPCertificate}. + * An identity may either be a {@link OpenPGPUserId} or (deprecated) {@link OpenPGPUserAttribute}. + */ + public static abstract class OpenPGPIdentityComponent + extends OpenPGPCertificateComponent + { + private final OpenPGPPrimaryKey primaryKey; + + public OpenPGPIdentityComponent(OpenPGPPrimaryKey primaryKey) + { + super(primaryKey.getCertificate()); + this.primaryKey = primaryKey; + } + + /** + * Return the primary key, which this identity belongs to. + * + * @return primary key + */ + public OpenPGPPrimaryKey getPrimaryKey() + { + return primaryKey; + } + + @Override + public OpenPGPComponentSignature getLatestSelfSignature(Date evaluationTime) + { + OpenPGPSignatureChain currentChain = getSignatureChains().getChainAt(evaluationTime); + if (currentChain != null && !currentChain.chainLinks.isEmpty()) + { + return currentChain.getSignature(); + } + return null; + } + + @Override + protected OpenPGPComponentKey getKeyComponent() + { + return primaryKey; + } + + /** + * Return the latest {@link OpenPGPSignatureChain} containing a certification issued by the given + * 3rd-party certificate over this identity component. + * + * @param thirdPartyCertificate certificate of a 3rd party + * @return 3rd party certification + */ + public OpenPGPSignatureChain getCertificationBy(OpenPGPCertificate thirdPartyCertificate) + { + return getCertificationBy(thirdPartyCertificate, new Date()); + } + + /** + * Return the latest (at evaluation time) {@link OpenPGPSignatureChain} containing a certification + * issued by the given 3rd-party certificate over this identity component. + * + * @param evaluationTime reference time + * @param thirdPartyCertificate certificate of a 3rd party + * @return 3rd party certification + */ + public OpenPGPSignatureChain getCertificationBy( + OpenPGPCertificate thirdPartyCertificate, + Date evaluationTime) + { + OpenPGPSignatureChains chainsBy = getMergedDanglingExternalSignatureChainEndsFrom(thirdPartyCertificate, evaluationTime); + return chainsBy.getCertificationAt(evaluationTime); + } + + /** + * Return the latest {@link OpenPGPSignatureChain} containing a revocation issued by the given + * 3rd-party certificate over this identity component. + * + * @param thirdPartyCertificate certificate of a 3rd party + * @return 3rd party revocation signature + */ + public OpenPGPSignatureChain getRevocationBy(OpenPGPCertificate thirdPartyCertificate) + { + return getRevocationBy(thirdPartyCertificate, new Date()); + } + + /** + * Return the latest (at evaluation time) {@link OpenPGPSignatureChain} containing a revocation issued by the given + * 3rd-party certificate over this identity component. + * + * @param thirdPartyCertificate certificate of a 3rd party + * @param evaluationTime reference time + * @return 3rd party revocation signature + */ + public OpenPGPSignatureChain getRevocationBy( + OpenPGPCertificate thirdPartyCertificate, + Date evaluationTime) + { + OpenPGPSignatureChains chainsBy = getMergedDanglingExternalSignatureChainEndsFrom(thirdPartyCertificate, evaluationTime); + return chainsBy.getRevocationAt(evaluationTime); + } + + @Override + public String toDetailString() + { + return toString(); + } + } + + /** + * A UserId. + */ + public static class OpenPGPUserId + extends OpenPGPIdentityComponent + { + private final String userId; + + public OpenPGPUserId(String userId, OpenPGPPrimaryKey primaryKey) + { + super(primaryKey); + this.userId = userId; + } + + /** + * Return the {@link String} representation of the {@link OpenPGPUserId}. + * + * @return user-id + */ + public String getUserId() + { + return userId; + } + + @Override + public String toString() + { + return "UserID[" + userId + "]"; + } + + @Override + public boolean equals(Object obj) + { + if (obj == null) + { + return false; + } + if (this == obj) + { + return true; + } + if (!(obj instanceof OpenPGPUserId)) + { + return false; + } + return getUserId().equals(((OpenPGPUserId)obj).getUserId()); + } + + @Override + public int hashCode() + { + return userId.hashCode(); + } + } + + /** + * A UserAttribute. + * Use of UserAttributes is deprecated in RFC9580. + */ + public static class OpenPGPUserAttribute + extends OpenPGPIdentityComponent + { + + private final PGPUserAttributeSubpacketVector userAttribute; + + public OpenPGPUserAttribute(PGPUserAttributeSubpacketVector userAttribute, OpenPGPPrimaryKey primaryKey) + { + super(primaryKey); + this.userAttribute = userAttribute; + } + + /** + * Return the underlying {@link PGPUserAttributeSubpacketVector} representing this {@link OpenPGPUserAttribute}. + * + * @return user attribute subpacket vector + */ + public PGPUserAttributeSubpacketVector getUserAttribute() + { + return userAttribute; + } + + @Override + public String toString() + { + return "UserAttribute" + userAttribute.toString(); + } + } + + /** + * Chain of {@link OpenPGPSignature signatures}. + * Such a chain originates from a certificates primary key and points towards some certificate component that + * is bound to the certificate. + * As for example a subkey can only be bound by a primary key that holds either at least one + * direct-key self-signature or at least one user-id binding signature, multiple signatures may form + * a validity chain. + * An {@link OpenPGPSignatureChain} can either be a certification + * ({@link #isCertification()}), e.g. it represents a positive binding, + * or it can be a revocation ({@link #isRevocation()}) which invalidates a positive binding. + */ + public static class OpenPGPSignatureChain + implements Comparable, Iterable + { + private final List chainLinks = new ArrayList(); + + private OpenPGPSignatureChain(Link rootLink) + { + this.chainLinks.add(rootLink); + } + + private OpenPGPSignatureChain(List links) + { + this.chainLinks.addAll(links); + } + + // copy constructor + private OpenPGPSignatureChain(OpenPGPSignatureChain copy) + { + this(copy.chainLinks); + } + + /** + * Return the signature from the leaf of the chain, which directly applies to the + * {@link OpenPGPCertificateComponent}. + * + * @return signature + */ + public OpenPGPComponentSignature getSignature() + { + return getLeafLink().getSignature(); + } + + /** + * Return the first revocation signature in the chain, or null if the chain does not contain any revocations. + * + * @return first revocation signature + */ + public OpenPGPComponentSignature getRevocation() + { + for (OpenPGPComponentSignature signature : getSignatures()) + { + if (signature.isRevocation()) + { + return signature; + } + } + return null; + } + + /** + * Return a List of all signatures in the chain. + * + * @return list of signatures + */ + public List getSignatures() + { + List signatures = new ArrayList(); + for (Link link : chainLinks) + { + signatures.add(link.getSignature()); + } + return signatures; + } + + /** + * Return an NEW instance of the {@link OpenPGPSignatureChain} with the new link appended. + * + * @param sig signature + * @return new instance + */ + public OpenPGPSignatureChain plus(OpenPGPComponentSignature sig) + { + if (getLeafLinkTargetKey() != sig.getIssuerComponent()) + { + throw new IllegalArgumentException("Chain head is not equal to link issuer."); + } + + OpenPGPSignatureChain chain = new OpenPGPSignatureChain(this); + + chain.chainLinks.add(Link.create(sig)); + + return chain; + } + + /** + * Factory method for creating an {@link OpenPGPSignatureChain} with only a single link. + * + * @param sig signature + * @return chain + */ + public static OpenPGPSignatureChain direct(OpenPGPComponentSignature sig) + { + return new OpenPGPSignatureChain(Link.create(sig)); + } + + /** + * Return the very first link in the chain. + * This is typically a link that originates from the issuing certificates primary key. + * + * @return root link + */ + public Link getRootLink() + { + return chainLinks.get(0); + } + + /** + * Return the issuer of the root link. This is typically the issuing certificates primary key. + * + * @return root links issuer + */ + public OpenPGPComponentKey getRootLinkIssuer() + { + return getRootLink().getSignature().getIssuer(); + } + + /** + * Return the last link in the chain, which applies to the chains target component. + * + * @return leaf link + */ + public Link getLeafLink() + { + return chainLinks.get(chainLinks.size() - 1); + } + + /** + * Return the {@link OpenPGPComponentKey} to which the leaf link applies to. + * For subkey binding signatures, this is the subkey. + * For user-id certification signatures, it is the primary key. + * + * @return target key component of the leaf link + */ + public OpenPGPComponentKey getLeafLinkTargetKey() + { + return getSignature().getTargetKeyComponent(); + } + + /** + * Return true, if the chain only consists of non-revocation signatures and is therefore a certification chain. + * + * @return true if the chain is a certification, false if it contains a revocation link. + */ + public boolean isCertification() + { + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + if (it.next() instanceof Revocation) + { + return false; + } + } + return true; + } + + /** + * Return true, if the chain contains at least one revocation signature. + * + * @return true if the chain is a revocation. + */ + public boolean isRevocation() + { + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + if (it.next() instanceof Revocation) + { + return true; + } + } + return false; + } + + /** + * Return true, if the chain contains at least one link that represents a hard revocation. + * + * @return true if chain is hard revocation, false if it is a certification or soft revocation + */ + public boolean isHardRevocation() + { + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + if (it.next().signature.signature.isHardRevocation()) + { + return true; + } + } + return false; + } + + /** + * Return the date since which this signature chain is valid. + * This is the creation time of the most recent link in the chain. + * + * @return most recent signature creation time + */ + public Date getSince() + { + Date latestDate = null; + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + Link link = (Link)it.next(); + OpenPGPComponentSignature signature = link.getSignature(); + Date currentDate = signature.getCreationTime(); + if (latestDate == null || currentDate.after(latestDate)) + { + latestDate = currentDate; + } + } + return latestDate; + } +// public Date getSince() +// { +// // Find most recent chain link +//// return chainLinks.stream() +//// .map(it -> it.signature) +//// .max(Comparator.comparing(OpenPGPComponentSignature::getCreationTime)) +//// .map(OpenPGPComponentSignature::getCreationTime) +//// .orElse(null); +// return chainLinks.stream() +// .map(new Function() +// { +// @Override +// public OpenPGPComponentSignature apply(Link it) +// { +// return it.signature; // Replace lambda: `it -> it.signature` +// } +// +// }) +// .max(new Comparator() +// { +// @Override +// public int compare(Object o1, Object o2) +// { +// // Replace method reference: `Comparator.comparing(OpenPGPComponentSignature::getCreationTime)` +// return ((OpenPGPComponentSignature)o1).getCreationTime().compareTo(((OpenPGPComponentSignature)o2).getCreationTime()); +// } +// }) +// .map(new Function() +// { +// @Override +// public Date apply(Object sig) +// { +// return ((OpenPGPComponentSignature)sig).getCreationTime(); // Replace method reference: `OpenPGPComponentSignature::getCreationTime` +// } +// }) +// .orElse(null); +// } + + /** + * Return the date until which the chain link is valid. + * This is the earliest expiration time of any signature in the chain. + * + * @return earliest expiration time + */ + public Date getUntil() + { + Date soonestExpiration = null; + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + Link link = it.next(); + Date until = link.until(); + if (until != null) + { + soonestExpiration = (soonestExpiration == null) ? until : + (until.before(soonestExpiration) ? until : soonestExpiration); + } + } + return soonestExpiration; + } + + /** + * Return true if the chain is effective at the given evaluation date, meaning all link signatures have + * been created before the evaluation time, and none signature expires before the evaluation time. + * + * @param evaluationDate reference time + * @return true if chain is effective at evaluation date + */ + public boolean isEffectiveAt(Date evaluationDate) + { + if (isHardRevocation()) + { + return true; + } + Date since = getSince(); + Date until = getUntil(); + // since <= eval <= until + return !evaluationDate.before(since) && (until == null || !evaluationDate.after(until)); + } + + /** + * Return true if the signature chain is valid, meaning all its chain links are valid. + * + * @return true if chain is valid + * @throws PGPSignatureException if an exception occurs during signature verification + */ + public boolean isValid() + throws PGPSignatureException + { + OpenPGPComponentKey rootKey = getRootLinkIssuer(); + if (rootKey == null) + { + throw new MissingIssuerCertException(getRootLink().signature, "Missing issuer certificate."); + } + OpenPGPCertificate cert = rootKey.getCertificate(); + return isValid(cert.implementation.pgpContentVerifierBuilderProvider(), cert.policy); + } + + /** + * Return true if the signature chain is valid, meaning all its chain links are valid. + * + * @param contentVerifierBuilderProvider provider for content verifier builders + * @param policy algorithm policy + * @return true if chain is valid + * @throws PGPSignatureException if an exception occurs during signature verification + */ + public boolean isValid(PGPContentVerifierBuilderProvider contentVerifierBuilderProvider, OpenPGPPolicy policy) + throws PGPSignatureException + { + boolean correct = true; + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + Link link = it.next(); + if (!link.signature.isTested) + { + link.verify(contentVerifierBuilderProvider, policy); + } + + if (!link.signature.isCorrect) + { + correct = false; + } + } + return correct; + } + + @Override + public String toString() + { + StringBuilder b = new StringBuilder(); + String until = getUntil() == null ? "EndOfTime" : UTCUtil.format(getUntil()); + b.append("From ").append(UTCUtil.format(getSince())).append(" until ").append(until).append("\n"); + for (Iterator it = chainLinks.iterator(); it.hasNext(); ) + { + Link link = it.next(); + b.append(" ").append(link.toString()).append("\n"); + } + return b.toString(); + } + + @Override + public int compareTo(OpenPGPSignatureChain other) + { + if (this == other) + { + return 0; + } + + if (isHardRevocation()) + { + return -1; + } + + if (other.isHardRevocation()) + { + return 1; + } + + int compare = -getRootLink().since().compareTo(other.getRootLink().since()); + if (compare != 0) + { + return compare; + } + + compare = -getLeafLink().since().compareTo(other.getLeafLink().since()); + if (compare != 0) + { + return compare; + } + + if (isRevocation()) + { + return 1; + } + return -1; + } + + @Override + public Iterator iterator() + { + return chainLinks.iterator(); + } + + /** + * Link in a {@link OpenPGPSignatureChain}. + */ + public static abstract class Link + { + protected final OpenPGPComponentSignature signature; + + public Link(OpenPGPComponentSignature signature) + { + this.signature = signature; + } + + /** + * Return the {@link Date} since when the link is effective. + * This is the creation time of the signature. + * + * @return signature creation time + */ + public Date since() + { + return signature.getCreationTime(); + } + + /** + * Return the {@link Date} until the signature is effective. + * This is, depending on which event is earlier in time, either the signature expiration time, + * or the key expiration time. + * + * @return time until the link is valid + */ + public Date until() + { + Date backSigExpiration = getBackSigExpirationTime(); + Date expirationTime = signature.getExpirationTime(); + + if (expirationTime == null) + { + return backSigExpiration; + } + + if (backSigExpiration == null || expirationTime.before(backSigExpiration)) + { + return expirationTime; + } + return backSigExpiration; + } + + /** + * Return the expiration time of the primary key binding signature. + * + * @return primary key binding signature expiration time + */ + private Date getBackSigExpirationTime() + { + if (signature.getSignature().getSignatureType() != PGPSignature.SUBKEY_BINDING) + { + return null; + } + + PGPSignatureSubpacketVector hashedSubpackets = signature.getSignature().getHashedSubPackets(); + if (hashedSubpackets == null) + { + return null; + } + + int keyFlags = signature.getSignature().getHashedSubPackets().getKeyFlags(); + if ((keyFlags & KeyFlags.SIGN_DATA) != KeyFlags.SIGN_DATA) + { + return null; + } + + try + { + PGPSignatureList embeddedSigs = hashedSubpackets.getEmbeddedSignatures(); + if (!embeddedSigs.isEmpty()) + { + OpenPGPComponentSignature backSig = new OpenPGPComponentSignature( + embeddedSigs.get(0), + // Primary Key Binding Signature has issuer and target swapped + /* issuer= */getSignature().getTargetKeyComponent(), + /* target= */getSignature().getIssuer()); + return backSig.getExpirationTime(); + } + return null; + } + catch (PGPException e) + { + return null; + } + } + + /** + * Verify the link signature. + * + * @param contentVerifierBuilderProvider provider for content verifier builders + * @param policy algorithm policy + * @return true if the signature is valid, false otherwise + * @throws PGPSignatureException if an exception occurs during signature verification + */ + public boolean verify(PGPContentVerifierBuilderProvider contentVerifierBuilderProvider, + OpenPGPPolicy policy) + throws PGPSignatureException + { + signature.verify(contentVerifierBuilderProvider, policy); // throws if invalid + return true; + } + + @Override + public String toString() + { + return signature.toString(); + } + + /** + * Factory method for creating Links from component signatures. + * Returns either a {@link Certification} in case the signature is a binding, + * or a {@link Revocation} in case the signature is a revocation signature. + * + * @param signature component signature + * @return link + */ + public static Link create(OpenPGPComponentSignature signature) + { + if (signature.isRevocation()) + { + return new Revocation(signature); + } + else + { + return new Certification(signature); + } + } + + /** + * Return the signature of the link. + * + * @return signature + */ + public OpenPGPComponentSignature getSignature() + { + return signature; + } + } + + /** + * "Positive" signature chain link. + */ + public static class Certification + extends Link + { + /** + * Positive certification. + * + * @param signature signature + */ + public Certification(OpenPGPComponentSignature signature) + { + super(signature); + } + } + + /** + * "Negative" signature chain link. + */ + public static class Revocation + extends Link + { + /** + * Revocation. + * + * @param signature signature + */ + public Revocation(OpenPGPComponentSignature signature) + { + super(signature); + } + + @Override + public Date since() + { + if (signature.signature.isHardRevocation()) + { + // hard revocations are valid retroactively, so we return the beginning of time here + return new Date(0L); + } + return super.since(); + } + + @Override + public Date until() + { + if (signature.signature.isHardRevocation()) + { + // hard revocations do not expire, so they are effective indefinitely + return new Date(Long.MAX_VALUE); + } + return super.until(); + } + } + } + + /** + * Collection of multiple {@link OpenPGPSignatureChain} objects. + */ + public static class OpenPGPSignatureChains + implements Iterable + { + private final OpenPGPCertificateComponent targetComponent; + private final Set chains = new TreeSet(); + + public OpenPGPSignatureChains(OpenPGPCertificateComponent component) + { + this.targetComponent = component; + } + + /** + * Add a single chain to the collection. + * + * @param chain chain + */ + public void add(OpenPGPSignatureChain chain) + { + this.chains.add(chain); + } + + /** + * Add all chains to the collection. + * + * @param otherChains other chains + */ + public void addAll(OpenPGPSignatureChains otherChains) + { + this.chains.addAll(otherChains.chains); + } + + /** + * Return true if the collection is empty. + * + * @return true if empty + */ + public boolean isEmpty() + { + return chains.isEmpty(); + } + + /** + * Return a positive certification chain for the component for the given evaluationTime. + * + * @param evaluationTime time for which validity of the {@link OpenPGPCertificateComponent} is checked. + * @return positive certification chain or null + */ + public OpenPGPSignatureChain getCertificationAt(Date evaluationTime) + { + for (Iterator it = chains.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain chain = it.next(); + boolean isEffective = chain.isEffectiveAt(evaluationTime); + boolean isCertification = chain.isCertification(); + if (isEffective && isCertification) + { + return chain; + } + } + return null; + } + + /** + * Return all {@link OpenPGPSignatureChain} objects, which are valid at the given evaluation time. + * + * @param evaluationTime reference time + * @return valid chains at reference time + */ + public OpenPGPSignatureChains getChainsAt(Date evaluationTime) + { + OpenPGPSignatureChains effectiveChains = new OpenPGPSignatureChains(targetComponent); + for (Iterator it = chains.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain chain = it.next(); + if (chain.isEffectiveAt(evaluationTime)) + { + effectiveChains.add(chain); + } + } + return effectiveChains; + } + + /** + * Return a negative certification chain for the component for the given evaluationTime. + * + * @param evaluationTime time for which revocation-ness of the {@link OpenPGPCertificateComponent} is checked. + * @return negative certification chain or null + */ + public OpenPGPSignatureChain getRevocationAt(Date evaluationTime) + { + for (Iterator it = chains.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain chain = it.next(); + if (chain.isRevocation() && chain.isEffectiveAt(evaluationTime)) + { + return chain; + } + } + return null; + } + + @Override + public String toString() + { + StringBuilder b = new StringBuilder(targetComponent.toDetailString()) + .append(" is bound with ").append(chains.size()).append(" chains:").append("\n"); + for (Iterator it = chains.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain chain = it.next(); + b.append(chain.toString()); + } + return b.toString(); + } + + /** + * Return all {@link OpenPGPSignatureChain} items which originate from the root {@link OpenPGPComponentKey}. + * + * @param root root key + * @return all chains with root key as origin + */ + public OpenPGPSignatureChains fromOrigin(OpenPGPComponentKey root) + { + OpenPGPSignatureChains chainsFromRoot = new OpenPGPSignatureChains(root); + for (Iterator it = chains.iterator(); it.hasNext(); ) + { + OpenPGPSignatureChain chain = it.next(); + if (chain.getRootLinkIssuer() == root) + { + chainsFromRoot.add(chain); + } + } + return chainsFromRoot; + } + + /** + * Return the latest chain, which is valid at the given evaluation time. + * + * @param evaluationDate reference time + * @return latest valid chain + */ + public OpenPGPSignatureChain getChainAt(Date evaluationDate) + { + OpenPGPSignatureChains atDate = getChainsAt(evaluationDate); + Iterator it = atDate.chains.iterator(); + if (it.hasNext()) + { + return it.next(); + } + return null; + } + + @Override + public Iterator iterator() + { + return chains.iterator(); + } + } + + private interface KeyFilter + { + boolean test(OpenPGPComponentKey key, Date evaluationTime); + } + + private List filterKeys(Date evaluationTime, KeyFilter filter) + { + List result = new ArrayList(); + for (Iterator it = getKeys().iterator(); it.hasNext(); ) + { + OpenPGPComponentKey key = it.next(); + if (isBound(key, evaluationTime) && filter.test(key, evaluationTime)) + { + result.add(key); + } + } + return result; + } + + private void addSignaturesToChains(List signatures, OpenPGPSignatureChains chains) + { + for (Iterator it = signatures.iterator(); it.hasNext(); ) + { + chains.add(OpenPGPSignatureChain.direct(it.next())); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDefaultPolicy.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDefaultPolicy.java new file mode 100644 index 0000000000..b751ce27ee --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDefaultPolicy.java @@ -0,0 +1,261 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.api.util.UTCUtil; + +public class OpenPGPDefaultPolicy + implements OpenPGPPolicy +{ + private final Map documentHashAlgorithmCutoffDates = new HashMap(); + private final Map certificateHashAlgorithmCutoffDates = new HashMap(); + private final Map symmetricKeyAlgorithmCutoffDates = new HashMap(); + private final Map publicKeyMinimalBitStrengths = new HashMap(); + private int defaultDocumentSignatureHashAlgorithm = HashAlgorithmTags.SHA512; + private int defaultCertificationSignatureHashAlgorithm = HashAlgorithmTags.SHA512; + private int defaultSymmetricKeyAlgorithm = SymmetricKeyAlgorithmTags.AES_128; + + public OpenPGPDefaultPolicy() + { + /* + * Certification Signature Hash Algorithms + */ + setDefaultCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + // SHA-3 + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA3_512); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA3_256); + // SHA-2 + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA384); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA256); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA224); + // SHA-1 + acceptCertificationSignatureHashAlgorithmUntil(HashAlgorithmTags.SHA1, UTCUtil.parse("2023-02-01 00:00:00 UTC")); + + acceptCertificationSignatureHashAlgorithmUntil(HashAlgorithmTags.RIPEMD160, UTCUtil.parse("2023-02-01 00:00:00 UTC")); + acceptCertificationSignatureHashAlgorithmUntil(HashAlgorithmTags.MD5, UTCUtil.parse("1997-02-01 00:00:00 UTC")); + + /* + * Document Signature Hash Algorithms + */ + setDefaultDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + // SHA-3 + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA3_512); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA3_256); + // SHA-2 + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA384); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA256); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA224); + + /* + * Symmetric Key Algorithms + */ + setDefaultSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_128); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_256); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_192); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_128); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.TWOFISH); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.CAMELLIA_256); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.CAMELLIA_192); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.CAMELLIA_128); + + /* + * Public Key Algorithms and key strengths + */ + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.RSA_GENERAL, 2000); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.RSA_ENCRYPT, 2000); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.RSA_SIGN, 2000); + + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.ECDSA, 250); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.EDDSA_LEGACY, 250); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.ECDH, 250); + + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.X25519); + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.X448); + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.Ed25519); + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.Ed448); + } + + public OpenPGPDefaultPolicy rejectHashAlgorithm(int hashAlgorithmId) + { + certificateHashAlgorithmCutoffDates.remove(hashAlgorithmId); + documentHashAlgorithmCutoffDates.remove(hashAlgorithmId); + return this; + } + + public OpenPGPDefaultPolicy acceptCertificationSignatureHashAlgorithm(int hashAlgorithmId) + { + return acceptCertificationSignatureHashAlgorithmUntil(hashAlgorithmId, null); + } + + public OpenPGPDefaultPolicy acceptCertificationSignatureHashAlgorithmUntil(int hashAlgorithmId, Date until) + { + certificateHashAlgorithmCutoffDates.put(hashAlgorithmId, until); + return this; + } + + public OpenPGPDefaultPolicy acceptDocumentSignatureHashAlgorithm(int hashAlgorithmId) + { + return acceptDocumentSignatureHashAlgorithmUntil(hashAlgorithmId, null); + } + + public OpenPGPDefaultPolicy acceptDocumentSignatureHashAlgorithmUntil(int hashAlgorithmId, Date until) + { + documentHashAlgorithmCutoffDates.put(hashAlgorithmId, until); + return this; + } + + public OpenPGPDefaultPolicy rejectSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + symmetricKeyAlgorithmCutoffDates.remove(symmetricKeyAlgorithmId); + return this; + } + + public OpenPGPDefaultPolicy acceptSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + return acceptSymmetricKeyAlgorithmUntil(symmetricKeyAlgorithmId, null); + } + + public OpenPGPDefaultPolicy acceptSymmetricKeyAlgorithmUntil(int symmetricKeyAlgorithmId, Date until) + { + symmetricKeyAlgorithmCutoffDates.put(symmetricKeyAlgorithmId, until); + return this; + } + + public OpenPGPDefaultPolicy rejectPublicKeyAlgorithm(int publicKeyAlgorithmId) + { + publicKeyMinimalBitStrengths.remove(publicKeyAlgorithmId); + return this; + } + + public OpenPGPDefaultPolicy acceptPublicKeyAlgorithm(int publicKeyAlgorithmId) + { + publicKeyMinimalBitStrengths.put(publicKeyAlgorithmId, null); + return this; + } + + public OpenPGPDefaultPolicy acceptPublicKeyAlgorithmWithMinimalStrength(int publicKeyAlgorithmId, int minBitStrength) + { + publicKeyMinimalBitStrengths.put(publicKeyAlgorithmId, minBitStrength); + return this; + } + + @Override + public boolean isAcceptableDocumentSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime) + { + return isAcceptable(hashAlgorithmId, signatureCreationTime, documentHashAlgorithmCutoffDates); + } + + @Override + public boolean isAcceptableRevocationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime) + { + return isAcceptable(hashAlgorithmId, signatureCreationTime, certificateHashAlgorithmCutoffDates); + } + + @Override + public boolean isAcceptableCertificationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime) + { + return isAcceptable(hashAlgorithmId, signatureCreationTime, certificateHashAlgorithmCutoffDates); + } + + @Override + public int getDefaultCertificationSignatureHashAlgorithm() + { + return defaultCertificationSignatureHashAlgorithm; + } + + public OpenPGPDefaultPolicy setDefaultCertificationSignatureHashAlgorithm(int hashAlgorithmId) + { + defaultCertificationSignatureHashAlgorithm = hashAlgorithmId; + return this; + } + + @Override + public int getDefaultDocumentSignatureHashAlgorithm() + { + return defaultDocumentSignatureHashAlgorithm; + } + + public OpenPGPDefaultPolicy setDefaultDocumentSignatureHashAlgorithm(int hashAlgorithmId) + { + defaultDocumentSignatureHashAlgorithm = hashAlgorithmId; + return this; + } + + @Override + public boolean isAcceptableSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + return isAcceptable(symmetricKeyAlgorithmId, symmetricKeyAlgorithmCutoffDates); + } + + @Override + public int getDefaultSymmetricKeyAlgorithm() + { + return defaultSymmetricKeyAlgorithm; + } + + public OpenPGPDefaultPolicy setDefaultSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + defaultSymmetricKeyAlgorithm = symmetricKeyAlgorithmId; + return this; + } + + @Override + public boolean isAcceptablePublicKeyStrength(int publicKeyAlgorithmId, int bitStrength) + { + return isAcceptable(publicKeyAlgorithmId, bitStrength, publicKeyMinimalBitStrengths); + } + + @Override + public OpenPGPNotationRegistry getNotationRegistry() + { + return null; + } + + private boolean isAcceptable(int algorithmId, Date usageDate, Map cutoffTable) + { + if (!cutoffTable.containsKey(algorithmId)) + { + // algorithm is not listed in the map at all + return false; + } + + Date cutoffDate = cutoffTable.get(algorithmId); + if (cutoffDate == null) + { + // no cutoff date given -> algorithm is acceptable indefinitely + return true; + } + + return usageDate.before(cutoffDate); + } + + private boolean isAcceptable(int algorithmId, Map cutoffTable) + { + return cutoffTable.containsKey(algorithmId); + } + + private boolean isAcceptable(int algorithmId, int bitStrength, Map minBitStrengths) + { + if (!minBitStrengths.containsKey(algorithmId)) + { + // algorithm is not listed in the map at all + return false; + } + + Integer minBitStrength = minBitStrengths.get(algorithmId); + if (minBitStrength == null) + { + // no minimal bit strength defined -> accept all strengths + return true; + } + + return bitStrength >= minBitStrength; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDetachedSignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDetachedSignatureGenerator.java new file mode 100644 index 0000000000..68b5390c12 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDetachedSignatureGenerator.java @@ -0,0 +1,96 @@ +package org.bouncycastle.openpgp.api; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; + +/** + * High-Level OpenPGP Signature Generator for Detached Signatures. + * Detached signatures can be stored and distributed as a distinct object alongside the signed data. + * They are used for example to sign Release files of some Linux software distributions. + *

      + * To use this class, instantiate it, optionally providing a concrete {@link OpenPGPImplementation} and + * {@link OpenPGPPolicy} for algorithm policing. + * Then, add the desired {@link OpenPGPKey} you want to use for signing the data via one or more + * calls to {@link #addSigningKey(OpenPGPKey, KeyPassphraseProvider)}. + * You have fine-grained control over the signature by using the method + * {@link #addSigningKey(OpenPGPKey.OpenPGPSecretKey, char[], SignatureParameters.Callback)}. + * Lastly, retrieve a list of detached {@link OpenPGPSignature.OpenPGPDocumentSignature signatures} by calling + * {@link #sign(InputStream)}, passing in an {@link InputStream} containing the data you want to sign. + */ +public class OpenPGPDetachedSignatureGenerator + extends AbstractOpenPGPDocumentSignatureGenerator +{ + /** + * Instantiate a signature generator using the default {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + */ + public OpenPGPDetachedSignatureGenerator() + { + this(OpenPGPImplementation.getInstance()); + } + + /** + * Instantiate a signature generator using the passed in {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + * + * @param implementation custom OpenPGP implementation + */ + public OpenPGPDetachedSignatureGenerator(OpenPGPImplementation implementation) + { + this(implementation, implementation.policy()); + } + + /** + * Instantiate a signature generator using a custom {@link OpenPGPImplementation} and custom {@link OpenPGPPolicy}. + * + * @param implementation custom OpenPGP implementation + * @param policy custom OpenPGP policy + */ + public OpenPGPDetachedSignatureGenerator(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + super(implementation, policy); + } + + /** + * Pass in an {@link InputStream} containing the data that shall be signed and return a list of detached + * signatures. + * + * @param inputStream data to be signed + * @return detached signatures + * + * @throws IOException if something goes wrong processing the data + * @throws PGPException if signing fails + */ + public List sign(InputStream inputStream) + throws IOException, PGPException + { + addSignToGenerator(); + + byte[] buf = new byte[2048]; + int r; + while ((r = inputStream.read(buf)) != -1) + { + for (Iterator it = signatureGenerators.iterator(); it.hasNext();) + { + ((PGPSignatureGenerator) it.next()).update(buf, 0, r); + } + } + + List documentSignatures = new ArrayList(); + for (int i = 0; i < signatureGenerators.size(); i++) + { + PGPSignatureGenerator sigGen = signatureGenerators.get(i); + PGPSignature signature = sigGen.generate(); + OpenPGPSignature.OpenPGPDocumentSignature docSig = new OpenPGPSignature.OpenPGPDocumentSignature( + signature, signingKeys.get(i)); + documentSignatures.add(docSig); + } + + return documentSignatures; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDetachedSignatureProcessor.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDetachedSignatureProcessor.java new file mode 100644 index 0000000000..b2146e5ba6 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPDetachedSignatureProcessor.java @@ -0,0 +1,298 @@ +package org.bouncycastle.openpgp.api; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureException; +import org.bouncycastle.openpgp.PGPSignatureList; +import org.bouncycastle.openpgp.PGPUtil; + +/** + * High-Level Processor for Messages Signed Using Detached OpenPGP Signatures. + *

      + * To use this class, first instantiate the processor, optionally passing in a concrete + * {@link OpenPGPImplementation} and {@link OpenPGPPolicy}. + * Then, pass in any detached signatures you want to verify using {@link #addSignatures(InputStream)}. + * Next, provide the expected issuers {@link OpenPGPCertificate OpenPGPCertificates} for signature + * verification using {@link #addVerificationCertificate(OpenPGPCertificate)}. + * Signatures for which no certificate was provided, and certificates for which no signature was added, + * are ignored. + * Optionally, you can specify a validity date range for the signatures using + * {@link #verifyNotBefore(Date)} and {@link #verifyNotAfter(Date)}. + * Signatures outside this range will be ignored as invalid. + * Lastly, provide an {@link InputStream} containing the original plaintext data, over which you want to + * verify the detached signatures using {@link #process(InputStream)}. + * As a result you will receive a list containing all processed + * {@link OpenPGPSignature.OpenPGPDocumentSignature OpenPGPDocumentSignatures}. + * For these, you can check validity by calling {@link OpenPGPSignature.OpenPGPDocumentSignature#isValid()}. + */ +public class OpenPGPDetachedSignatureProcessor +{ + private final OpenPGPImplementation implementation; + private final OpenPGPPolicy policy; + private final OpenPGPKeyMaterialPool.OpenPGPCertificatePool certificatePool = new OpenPGPKeyMaterialPool.OpenPGPCertificatePool(); + private final List pgpSignatures = new ArrayList(); + private Date verifyNotAfter = new Date(); // now + private Date verifyNotBefore = new Date(0L); // beginning of time + + private OpenPGPMessageProcessor.PGPExceptionCallback exceptionCallback = null; + + /** + * Instantiate a signature processor using the default {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + */ + public OpenPGPDetachedSignatureProcessor() + { + this(OpenPGPImplementation.getInstance()); + } + + /** + * Instantiate a signature processor using a custom {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + * + * @param implementation custom OpenPGP implementation + */ + public OpenPGPDetachedSignatureProcessor(OpenPGPImplementation implementation) + { + this(implementation, implementation.policy()); + } + + /** + * Instantiate a signature processor using a custom {@link OpenPGPImplementation} and custom {@link OpenPGPPolicy}. + * + * @param implementation custom OpenPGP implementation + * @param policy custom OpenPGP policy + */ + public OpenPGPDetachedSignatureProcessor(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + this.implementation = implementation; + this.policy = policy; + } + + /** + * Read one or more {@link PGPSignature detached signatures} from the provided {@link InputStream} and + * add them to the processor. + * + * @param inputStream input stream of armored or unarmored detached OpenPGP signatures + * @return this + * @throws IOException if something goes wrong reading from the stream + */ + public OpenPGPDetachedSignatureProcessor addSignatures(InputStream inputStream) + throws IOException + { + InputStream decoderStream = PGPUtil.getDecoderStream(inputStream); + BCPGInputStream pIn = BCPGInputStream.wrap(decoderStream); + PGPObjectFactory objFac = implementation.pgpObjectFactory(pIn); + Object next; + while ((next = objFac.nextObject()) != null) + { + if (next instanceof PGPSignatureList) + { + addSignatures((PGPSignatureList)next); + } + else if (next instanceof PGPSignature) + { + addSignature((PGPSignature)next); + } + } + return this; + } + + /** + * Add one or more {@link PGPSignature detached signatures} from the given {@link PGPSignatureList} to the + * processor. + * + * @param signatures detached signature list + * @return this + */ + public OpenPGPDetachedSignatureProcessor addSignatures(PGPSignatureList signatures) + { + for (Iterator it = signatures.iterator(); it.hasNext(); ) + { + addSignature(it.next()); + } + return this; + } + + /** + * Add a single {@link PGPSignature detached signature} to the processor. + * + * @param signature detached signature + * @return this + */ + public OpenPGPDetachedSignatureProcessor addSignature(PGPSignature signature) + { + pgpSignatures.add(signature); + return this; + } + + /** + * Add an issuers {@link OpenPGPCertificate} for signature verification. + * + * @param certificate OpenPGP certificate + * @return this + */ + public OpenPGPDetachedSignatureProcessor addVerificationCertificate(OpenPGPCertificate certificate) + { + this.certificatePool.addItem(certificate); + return this; + } + + /** + * Reject detached signatures made before

      date
      . + * By default, this value is set to the beginning of time. + * + * @param date date + * @return this + */ + public OpenPGPDetachedSignatureProcessor verifyNotBefore(Date date) + { + this.verifyNotBefore = date; + return this; + } + + /** + * Reject detached signatures made after the given
      date
      . + * By default, this value is set to the current time at instantiation time, in order to prevent + * verification of signatures from the future. + * + * @param date date + * @return this + */ + public OpenPGPDetachedSignatureProcessor verifyNotAfter(Date date) + { + this.verifyNotAfter = date; + return this; + } + + /** + * Process the plaintext data from the given {@link InputStream} and return a list of processed + * detached signatures. + * Note: This list will NOT contain any malformed signatures, or signatures for which no verification key was found. + * Correctness of these signatures can be checked via {@link OpenPGPSignature.OpenPGPDocumentSignature#isValid()}. + * + * @param inputStream data over which the detached signatures are calculated + * @return list of processed detached signatures + * @throws IOException if the data cannot be processed + */ + public List process(InputStream inputStream) + throws IOException + { + List documentSignatures = new ArrayList(); + for (Iterator it = pgpSignatures.iterator(); it.hasNext(); ) + { + PGPSignature signature = (PGPSignature)it.next(); + // Match up signatures with certificates + + KeyIdentifier identifier = OpenPGPSignature.getMostExpressiveIdentifier(signature.getKeyIdentifiers()); + if (identifier == null) + { + // Missing issuer -> ignore sig + continue; + } + + OpenPGPCertificate certificate = certificatePool.provide(identifier); + if (certificate == null) + { + // missing cert -> ignore sig + continue; + } + + OpenPGPCertificate.OpenPGPComponentKey signingKey = certificate.getKey(identifier); + if (signingKey == null) + { + // unbound signing subkey -> ignore sig + continue; + } + + // Initialize signatures with verification key + try + { + signature.init(implementation.pgpContentVerifierBuilderProvider(), signingKey.getPGPPublicKey()); + } + catch (PGPException e) + { + if (exceptionCallback != null) + { + exceptionCallback.onException(e); + } + continue; + } + + OpenPGPSignature.OpenPGPDocumentSignature sig = + new OpenPGPSignature.OpenPGPDocumentSignature(signature, signingKey); + try + { + // sanitize signature (required subpackets, check algorithm policy...) + sig.sanitize(signingKey, policy); + } + catch (PGPSignatureException e) + { + if (exceptionCallback != null) + { + exceptionCallback.onException(e); + } + continue; + } + + // check allowed date range + if (!sig.createdInBounds(verifyNotBefore, verifyNotAfter)) + { + continue; + } + + // sig qualifies for further processing :) + documentSignatures.add(sig); + } + + // Process plaintext + byte[] buf = new byte[2048]; + int r; + while ((r = inputStream.read(buf)) != -1) + { + for (Iterator it = documentSignatures.iterator(); it.hasNext(); ) + { + ((OpenPGPSignature.OpenPGPDocumentSignature)it.next()).getSignature().update(buf, 0, r); + } + } + + // Verify signatures + for (Iterator it = documentSignatures.iterator(); it.hasNext(); ) + { + try + { + // verify the signature. Correctness can be checked via + ((OpenPGPSignature.OpenPGPDocumentSignature)it.next()).verify(); + } + catch (PGPException e) + { + if (exceptionCallback != null) + { + exceptionCallback.onException(e); + } + } + } + + return documentSignatures; + } + + /** + * Add a callback to which any OpenPGP-related exceptions are forwarded. + * Useful for debugging purposes. + * + * @param callback callback + * @return this + */ + public OpenPGPDetachedSignatureProcessor setExceptionCallback(OpenPGPMessageProcessor.PGPExceptionCallback callback) + { + this.exceptionCallback = callback; + return this; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPEncryptionNegotiator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPEncryptionNegotiator.java new file mode 100644 index 0000000000..953bf33940 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPEncryptionNegotiator.java @@ -0,0 +1,305 @@ +package org.bouncycastle.openpgp.api; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; +import org.bouncycastle.bcpg.sig.PreferredAlgorithms; + +public abstract class OpenPGPEncryptionNegotiator +{ + /** + * Negotiate encryption mode and algorithms. + * + * @param configuration message generator configuration + * @return negotiated encryption mode and algorithms + */ + public abstract MessageEncryptionMechanism negotiateEncryption(OpenPGPMessageGenerator configuration); + + static PreferredAEADCiphersuites negotiateAEADCiphersuite(List certificates, OpenPGPPolicy policy) + { + return new PreferredAEADCiphersuites(false, new PreferredAEADCiphersuites.Combination[]{ + bestAEADCiphersuiteByWeight(certificates, policy) + }); + } + + /** + * Return true, if all recipient {@link OpenPGPCertificate certificates} contain at least one subkey that supports + * {@link Features#FEATURE_SEIPD_V2}. + * + * @param certificates certificates + * @return true if all certificates support the feature, false otherwise + */ + static boolean allRecipientsSupportSeipd2(List certificates) + { + return allRecipientsSupportEncryptionFeature(certificates, Features.FEATURE_SEIPD_V2); + } + + static boolean allRecipientsSupportLibrePGPOED(List certificates) + { + return allRecipientsSupportEncryptionFeature(certificates, Features.FEATURE_AEAD_ENCRYPTED_DATA); + } + + static boolean allRecipientsSupportEncryptionFeature(List certificates, byte feature) + { + for (Iterator it = certificates.iterator(); it.hasNext(); ) + { + List encryptionKeys = ((OpenPGPCertificate)it.next()).getEncryptionKeys(); + if (encryptionKeys.isEmpty()) + { + continue; + } + + boolean recipientHasSupport = false; + for (Iterator ckIt = encryptionKeys.iterator(); ckIt.hasNext(); ) + { + Features features = ((OpenPGPCertificate.OpenPGPComponentKey)ckIt.next()).getFeatures(); + if (features != null && features.supportsFeature(feature)) + { + recipientHasSupport = true; + break; + } + } + + if (!recipientHasSupport) + { + return false; + } + } + return true; + } + + public static PreferredAEADCiphersuites.Combination bestAEADCiphersuiteByWeight( + Collection certificates, OpenPGPPolicy policy) + { + return processCertificates( + certificates, + policy, + new KeyProcessor() + { + public boolean processKey(OpenPGPCertificate.OpenPGPComponentKey key, Map capableKeys) + { + Features features = key.getFeatures(); + if (features != null && features.supportsSEIPDv2()) + { + PreferredAEADCiphersuites prefs = key.getAEADCipherSuitePreferences(); + if (prefs != null) + { + capableKeys.put(key, prefs); + return true; + } + } + return false; + } + + public List getAlgorithms(PreferredAEADCiphersuites prefs, OpenPGPPolicy policy) + { + // Weigh the preferences descending by index: w(p_i) = 1/(i+1) + // This way, combinations with a smaller index have a higher weight than combinations with larger index. + // Additionally, we divide this weight by the number of capable subkeys per cert in order to + // prevent a certificate with many capable subkeys from outvoting other certificates + List result = new ArrayList(); + for (PreferredAEADCiphersuites.Combination c : prefs.getAlgorithms()) + { + if (c.getSymmetricAlgorithm() != SymmetricKeyAlgorithmTags.NULL + && policy.isAcceptableSymmetricKeyAlgorithm(c.getSymmetricAlgorithm())) + { + result.add(c); + } + } + return result; + } + }, + PreferredAEADCiphersuites.DEFAULT().getAlgorithms()[0] + ); + } + + static int bestSymmetricKeyAlgorithmByWeight( + Collection certificates, + OpenPGPPolicy policy) + { + return processCertificates( + certificates, + policy, + new KeyProcessor() + { + @Override + public boolean processKey(OpenPGPCertificate.OpenPGPComponentKey key, + Map capableKeys) + { + Features features = key.getFeatures(); + if (features != null && features.supportsModificationDetection()) + { + PreferredAlgorithms prefs = key.getSymmetricCipherPreferences(); + if (prefs != null) + { + capableKeys.put(key, prefs); + return true; + } + } + return false; + } + + @Override + public List getAlgorithms(PreferredAlgorithms preferences, OpenPGPPolicy policy) + { + // Weigh the preferences descending by index: w(p_i) = 1/(i+1) + // This way, combinations with a smaller index have a higher weight than combinations with larger index. + // Additionally, we divide this weight by the number of capable subkeys per cert in order to + // prevent a certificate with many capable subkeys from outvoting other certificates + List result = new ArrayList(); + int[] prefs = preferences.getPreferences(); + for (int i = 0; i < prefs.length; i++) + { + int alg = prefs[i]; + if (alg != SymmetricKeyAlgorithmTags.NULL && + policy.isAcceptableSymmetricKeyAlgorithm(alg)) + { + result.add(alg); + } + } + return result; + } + }, + SymmetricKeyAlgorithmTags.AES_128 // Default value + ); + } + + static int bestOEDEncryptionModeByWeight(Collection certificates, + final OpenPGPPolicy policy) + { + return processCertificates( + certificates, + policy, + new KeyProcessor() + { + @Override + public boolean processKey(OpenPGPCertificate.OpenPGPComponentKey key, + Map capableKeys) + { + // Only consider encryption keys capable of OED + Features features = key.getFeatures(); + if (features != null && features.supportsFeature(Features.FEATURE_AEAD_ENCRYPTED_DATA)) + { + PreferredAlgorithms prefs = key.getSymmetricCipherPreferences(); + if (prefs != null) + { + capableKeys.put(key, prefs); + return true; + } + } + return false; + } + + @Override + public List getAlgorithms(PreferredAlgorithms preferences, OpenPGPPolicy policy) + { + // Count the keys symmetric key preferences (that can be used with OED) and update the weight map + + List result = new ArrayList(); + int[] prefs = preferences.getPreferences(); + for (int i = 0; i < prefs.length; i++) + { + int alg = prefs[i]; + if (isOEDCompatible(alg) && + policy.isAcceptableSymmetricKeyAlgorithm(alg)) + { + result.add(alg); + } + } + return result; + } + + private boolean isOEDCompatible(int alg) + { + switch (alg) + { + case SymmetricKeyAlgorithmTags.AES_128: + case SymmetricKeyAlgorithmTags.AES_192: + case SymmetricKeyAlgorithmTags.AES_256: + case SymmetricKeyAlgorithmTags.CAMELLIA_128: + case SymmetricKeyAlgorithmTags.CAMELLIA_192: + case SymmetricKeyAlgorithmTags.CAMELLIA_256: + return true; + default: + return false; + } + } + }, + SymmetricKeyAlgorithmTags.AES_128 // Default value + ); + } + + private interface KeyProcessor + { + /** + * Process a certificate's encryption key and return true to include it + */ + boolean processKey(OpenPGPCertificate.OpenPGPComponentKey key, Map capableKeys); + + /** + * Process preferences and return algorithms to consider + */ + List getAlgorithms(T preferences, OpenPGPPolicy policy); + } + + private static R processCertificates( + Collection certificates, + OpenPGPPolicy policy, + KeyProcessor keyProcessor, + R defaultResult) + { + Map weights = new HashMap(); + + // Go through all certificate's capable subkeys + for (Iterator it = certificates.iterator(); it.hasNext(); ) + { + List encryptionKeys = it.next().getEncryptionKeys(); + if (encryptionKeys.isEmpty()) + { + continue; + } + + // Only consider encryption keys capable of SEIPDv1/OED + Map capableKeys = new HashMap(); + for (Iterator ckIt = encryptionKeys.iterator(); ckIt.hasNext(); ) + { + keyProcessor.processKey(ckIt.next(), capableKeys); + } + + // Count the keys [AEAD preferences | symmetric key preferences (that can be used with OED)] + // and update the weight map + for (Iterator ckIt = capableKeys.keySet().iterator(); ckIt.hasNext(); ) + { + T prefs = capableKeys.get(ckIt.next()); + List algorithms = keyProcessor.getAlgorithms(prefs, policy); + for (int i = 0; i < algorithms.size(); i++) + { + R c = algorithms.get(i); + float current = weights.containsKey(c) ? weights.get(c) : 0; + weights.put(c, current + (1f / (i + 1)) / capableKeys.size()); + } + } + } + + R maxKey = defaultResult; + float maxWeight = -1; + // Select the entry with the highest weight + for (Iterator> it = weights.entrySet().iterator(); it.hasNext(); ) + { + Map.Entry entry = it.next(); + if (entry.getValue() > maxWeight) + { + maxWeight = entry.getValue(); + maxKey = entry.getKey(); + } + } + return maxKey; + } +} \ No newline at end of file diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPImplementation.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPImplementation.java new file mode 100644 index 0000000000..1697e54879 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPImplementation.java @@ -0,0 +1,210 @@ +package org.bouncycastle.openpgp.api; + +import java.io.InputStream; + +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.api.bc.BcOpenPGPImplementation; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; +import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilderProvider; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilderProvider; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.PGPKeyPairGeneratorProvider; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.SessionKeyDataDecryptorFactory; + +/** + * Bouncy Castle provides two implementations of OpenPGP operators. + * The
      JCA/JCE
      implementation makes use of Java Cryptography Architecture and the + * Java Cryptography Extension, while
      Bc
      uses Bouncy Castles Lightweight Cryptography API. + * The purpose of {@link OpenPGPImplementation} is to define a shared interface for instantiating concrete + * objects of either API. + * It is advised to define the desired implementation by calling {@link #setInstance(OpenPGPImplementation)} and + * acquiring it via {@link #getInstance()}, as swapping out the entire implementation can then be done by + * replacing the instance in one single place. + * This pattern was successfully explored by PGPainless. + */ +public abstract class OpenPGPImplementation +{ + private static OpenPGPImplementation INSTANCE; + private OpenPGPPolicy policy = new OpenPGPDefaultPolicy(); + + /** + * Replace the {@link OpenPGPImplementation} instance that is returned by {@link #getInstance()}. + * @param implementation instance + */ + public static void setInstance(OpenPGPImplementation implementation) + { + INSTANCE = implementation; + } + + /** + * Return the currently set {@link OpenPGPImplementation} instance. + * The default is {@link BcOpenPGPImplementation}. + * + * @return instance + */ + public static OpenPGPImplementation getInstance() + { + if (INSTANCE == null) + { + setInstance(new BcOpenPGPImplementation()); + } + return INSTANCE; + } + + public OpenPGPPolicy policy() + { + return policy; + } + + public OpenPGPImplementation setPolicy(OpenPGPPolicy policy) + { + this.policy = policy; + return this; + } + + /** + * Return an instance of {@link PGPObjectFactory} based on the given {@link InputStream}. + * + * @param packetInputStream packet input stream + * @return object factory + */ + public abstract PGPObjectFactory pgpObjectFactory(InputStream packetInputStream); + + /** + * Return an instance of {@link PGPContentVerifierBuilderProvider} which is responsible for providing + * implementations needed for signature verification. + * + * @return content verifier builder provider + */ + public abstract PGPContentVerifierBuilderProvider pgpContentVerifierBuilderProvider(); + + /** + * Return an instance of {@link PBESecretKeyDecryptorBuilderProvider} which is responsible for providing + * implementations needed for secret key unlocking. + * + * @return secret key decryptor builder provider + */ + public abstract PBESecretKeyDecryptorBuilderProvider pbeSecretKeyDecryptorBuilderProvider(); + + /** + * Return an instance of {@link PGPDataEncryptorBuilder} which is responsible for providing implementations + * needed for creating encrypted data packets. + * + * @param symmetricKeyAlgorithm symmetric encryption algorithm + * @return data encryptor builder + */ + public abstract PGPDataEncryptorBuilder pgpDataEncryptorBuilder( + int symmetricKeyAlgorithm); + + /** + * Return an instance of {@link PublicKeyKeyEncryptionMethodGenerator} which is responsible for + * creating public-key-based encryptors for OpenPGP messages. + * Public-key-based encryptors are used when a message is encrypted for a recipients public key. + * + * @param encryptionSubkey subkey for which a message shall be encrypted + * @return public-key key-encryption method generator + */ + public abstract PublicKeyKeyEncryptionMethodGenerator publicKeyKeyEncryptionMethodGenerator( + PGPPublicKey encryptionSubkey); + + /** + * Return an instance of {@link PBEKeyEncryptionMethodGenerator} which is responsible for creating + * symmetric-key-based encryptors for OpenPGP messages, using {@link S2K#SALTED_AND_ITERATED} mode. + * Symmetric-key-based encryptors are used when a message is encrypted using a passphrase. + * + * @param messagePassphrase passphrase to encrypt the message with + * @return pbe key encryption method generator + */ + public abstract PBEKeyEncryptionMethodGenerator pbeKeyEncryptionMethodGenerator( + char[] messagePassphrase); + + /** + * Return an instance of {@link PBEKeyEncryptionMethodGenerator} which is responsible for creating + * symmetric-key-based encryptors for OpenPGP messages, using {@link S2K#ARGON_2} mode. + * Symmetric-key-based encryptors are used when a message is encrypted using a passphrase. + * + * @param messagePassphrase passphrase to encrypt the message with + * @param argon2Params parameters for the Argon2 hash function + * @return pbe key encryption method generator + */ + public abstract PBEKeyEncryptionMethodGenerator pbeKeyEncryptionMethodGenerator( + char[] messagePassphrase, + S2K.Argon2Params argon2Params); + + /** + * Return an instance of {@link PGPContentSignerBuilder}, which is responsible for providing concrete + * implementations needed for signature creation. + * + * @param publicKeyAlgorithm the signing-keys public-key algorithm + * @param hashAlgorithm signature hash algorithm + * @return content signer builder + */ + public abstract PGPContentSignerBuilder pgpContentSignerBuilder( + int publicKeyAlgorithm, + int hashAlgorithm); + + /** + * Return an instance of the {@link PBEDataDecryptorFactory}, which is responsible for providing concrete + * implementations needed to decrypt OpenPGP messages that were encrypted symmetrically with a passphrase. + * + * @param messagePassphrase message passphrase + * @return pbe data decryptor factory + * @throws PGPException if the factory cannot be instantiated + */ + public abstract PBEDataDecryptorFactory pbeDataDecryptorFactory( + char[] messagePassphrase) + throws PGPException; + + /** + * Return an instance of the {@link SessionKeyDataDecryptorFactory}, which is responsible for providing + * concrete implementations needed to decrypt OpenPGP messages using a {@link PGPSessionKey}. + * + * @param sessionKey session key + * @return session-key data decryptor factory + */ + public abstract SessionKeyDataDecryptorFactory sessionKeyDataDecryptorFactory( + PGPSessionKey sessionKey); + + /** + * Return an instance of the {@link PublicKeyDataDecryptorFactory}, which is responsible for providing + * concrete implementations needed to decrypt OpenPGP messages using a {@link PGPPrivateKey}. + * + * @param decryptionKey private decryption key + * @return public-key data decryptor factory + */ + public abstract PublicKeyDataDecryptorFactory publicKeyDataDecryptorFactory( + PGPPrivateKey decryptionKey); + + /** + * Return an instance of the {@link PGPDigestCalculatorProvider}, which is responsible for providing + * concrete {@link org.bouncycastle.openpgp.operator.PGPDigestCalculator} implementations. + * + * @return pgp digest calculator provider + * @throws PGPException if the provider cannot be instantiated + */ + public abstract PGPDigestCalculatorProvider pgpDigestCalculatorProvider() + throws PGPException; + + public abstract PGPKeyPairGeneratorProvider pgpKeyPairGeneratorProvider(); + + public abstract PGPContentSignerBuilderProvider pgpContentSignerBuilderProvider(int hashAlgorithmId); + + public abstract KeyFingerPrintCalculator keyFingerPrintCalculator(); + + public abstract PBESecretKeyEncryptorFactory pbeSecretKeyEncryptorFactory(boolean aead) throws PGPException; + + public abstract PBESecretKeyEncryptorFactory pbeSecretKeyEncryptorFactory(boolean aead, int symmetricKeyAlgorithm, int iterationCount) throws PGPException; +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKey.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKey.java new file mode 100644 index 0000000000..2a0009ddda --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKey.java @@ -0,0 +1,583 @@ +package org.bouncycastle.openpgp.api; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPKeyValidationException; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.api.exception.KeyPassphraseException; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilderProvider; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; + +/** + * An {@link OpenPGPKey} (TSK - transferable secret key) is the pendant to an {@link OpenPGPCertificate}, + * but containing the secret key material in addition to the public components. + * It consists of one or multiple {@link OpenPGPSecretKey} objects. + */ +public class OpenPGPKey + extends OpenPGPCertificate +{ + // This class extends OpenPGPCertificate, but also holds secret key components in a dedicated map. + private final Map secretKeys; + + /** + * Create an {@link OpenPGPKey} instance based on a {@link PGPSecretKeyRing}. + * The {@link OpenPGPImplementation} will be acquired by invoking {@link OpenPGPImplementation#getInstance()}. + * + * @param keyRing secret key ring + */ + public OpenPGPKey(PGPSecretKeyRing keyRing) + { + this(keyRing, OpenPGPImplementation.getInstance()); + } + + /** + * Create an {@link OpenPGPKey} instance based on a {@link PGPSecretKeyRing}, + * a provided {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}. + * + * @param keyRing secret key ring + * @param implementation OpenPGP implementation + */ + public OpenPGPKey(PGPSecretKeyRing keyRing, OpenPGPImplementation implementation) + { + this(keyRing, implementation, implementation.policy()); + } + + /** + * Create an {@link OpenPGPKey} instance based on a {@link PGPSecretKeyRing}, + * a provided {@link OpenPGPImplementation} and {@link OpenPGPPolicy}. + * + * @param keyRing secret key ring + * @param implementation OpenPGP implementation + * @param policy OpenPGP policy + */ + public OpenPGPKey(PGPSecretKeyRing keyRing, OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + super(keyRing, implementation, policy); + + // Process and map secret keys + this.secretKeys = new HashMap(); + for (Iterator it = getKeys().iterator(); it.hasNext(); ) + { + OpenPGPComponentKey key = (OpenPGPComponentKey)it.next(); + KeyIdentifier identifier = key.getKeyIdentifier(); + PGPSecretKey secretKey = keyRing.getSecretKey(identifier); + if (secretKey == null) + { + continue; + } + + secretKeys.put(identifier, new OpenPGPSecretKey(key, secretKey, implementation.pbeSecretKeyDecryptorBuilderProvider())); + } + } + + @Override + public boolean isSecretKey() + { + return true; + } + + /** + * Return the {@link OpenPGPCertificate} of this {@link OpenPGPKey}. + * + * @return certificate + */ + public OpenPGPCertificate toCertificate() + { + return new OpenPGPCertificate(getPGPPublicKeyRing(), implementation, policy); + } + + @Override + public List getComponents() + { + // We go through the list of components returned by OpenPGPCertificate and replace those components + // where we have the secret key available + + // contains only public components + List components = super.getComponents(); + for (int i = components.size() - 1; i >= 0; i--) + { + OpenPGPCertificateComponent component = (OpenPGPCertificateComponent)components.get(i); + if (component instanceof OpenPGPComponentKey) + { + OpenPGPSecretKey secretKey = getSecretKey((OpenPGPComponentKey)component); + if (secretKey != null) + { + // swap in secret component + components.remove(i); + components.add(i, secretKey); + } + } + } + return components; + } + + /** + * Return the {@link OpenPGPSecretKey} of this key's primary key. + * + * @return primary secret key + */ + public OpenPGPSecretKey getPrimarySecretKey() + { + return getSecretKey(getPrimaryKey()); + } + + /** + * Return a {@link Map} containing all {@link OpenPGPSecretKey} components (secret subkeys) of the key. + * + * @return secret key components + */ + public Map getSecretKeys() + { + return new HashMap(secretKeys); + } + + /** + * Return the {@link OpenPGPSecretKey} identified by the passed {@link KeyIdentifier}. + * + * @param identifier key identifier + * @return corresponding secret key or null + */ + public OpenPGPSecretKey getSecretKey(KeyIdentifier identifier) + { + return secretKeys.get(identifier); + } + + /** + * Return the {@link OpenPGPSecretKey} that corresponds to the passed {@link OpenPGPComponentKey}. + * + * @param key component key + * @return corresponding secret key or null + */ + public OpenPGPSecretKey getSecretKey(OpenPGPComponentKey key) + { + return getSecretKey(key.getKeyIdentifier()); + } + + /** + * Replace the given secret key component. + * + * @param secretKey secret key + */ + void replaceSecretKey(OpenPGPSecretKey secretKey) + { + keyRing = PGPSecretKeyRing.insertSecretKey((PGPSecretKeyRing)keyRing, secretKey.rawSecKey); + secretKeys.put(secretKey.getKeyIdentifier(), secretKey); + } + + @Override + public PGPSecretKeyRing getPGPKeyRing() + { + return getPGPSecretKeyRing(); + } + + /** + * Return the underlying {@link PGPSecretKeyRing}. + * + * @return secret key ring + */ + public PGPSecretKeyRing getPGPSecretKeyRing() + { + return (PGPSecretKeyRing)super.getPGPKeyRing(); + } + + @Override + public byte[] getEncoded(PacketFormat packetFormat) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, packetFormat); + getPGPSecretKeyRing().encode(pOut); + pOut.close(); + return bOut.toByteArray(); + } + + /** + * Secret key component of a {@link org.bouncycastle.openpgp.api.OpenPGPCertificate.OpenPGPPrimaryKey} or + * {@link org.bouncycastle.openpgp.api.OpenPGPCertificate.OpenPGPSubkey}. + */ + public static class OpenPGPSecretKey + extends OpenPGPComponentKey + { + private final PGPSecretKey rawSecKey; + private final OpenPGPComponentKey pubKey; + private final PBESecretKeyDecryptorBuilderProvider decryptorBuilderProvider; + + /** + * Constructor. + * + * @param pubKey corresponding public key component + * @param secKey secret key + * @param decryptorBuilderProvider for unlocking private keys + */ + public OpenPGPSecretKey(OpenPGPComponentKey pubKey, + PGPSecretKey secKey, + PBESecretKeyDecryptorBuilderProvider decryptorBuilderProvider) + { + super(pubKey.getPGPPublicKey(), pubKey.getCertificate()); + this.decryptorBuilderProvider = decryptorBuilderProvider; + this.rawSecKey = secKey; + this.pubKey = pubKey; + } + + @Override + protected OpenPGPCertificateComponent getPublicComponent() + { + // return the public key component to properly map this secret key to its public key component when + // the public key component is used as key in a map. + return pubKey; + } + + @Override + public boolean isPrimaryKey() + { + return getPublicKey().isPrimaryKey(); + } + + @Override + public OpenPGPComponentSignature getLatestSelfSignature(Date evaluationTime) + { + return getPublicKey().getLatestSelfSignature(evaluationTime); + } + + /** + * Return the {@link OpenPGPKey} which this {@link OpenPGPSecretKey} belongs to. + * + * @return OpenPGPKey + */ + public OpenPGPKey getOpenPGPKey() + { + return (OpenPGPKey)getCertificate(); + } + + @Override + public String toDetailString() + { + return "Private" + pubKey.toDetailString(); + } + + /** + * Return the underlying {@link PGPSecretKey}. + * + * @return secret key + */ + public PGPSecretKey getPGPSecretKey() + { + return rawSecKey; + } + + /** + * Return the public {@link OpenPGPComponentKey} corresponding to this {@link OpenPGPSecretKey}. + * + * @return public component key + */ + public OpenPGPComponentKey getPublicKey() + { + return pubKey; + } + + /** + * If true, the secret key is not available in plain and likely needs to be decrypted by providing + * a key passphrase. + * + * @return true if the key is locked + */ + public boolean isLocked() + { + return getPGPSecretKey().getS2KUsage() != SecretKeyPacket.USAGE_NONE; + } + + /** + * Unlock an unprotected {@link OpenPGPSecretKey}. + * + * @return unlocked private key + * @throws PGPException if the key cannot be unlocked + */ + public OpenPGPPrivateKey unlock() + throws PGPException + { + return unlock((char[])null); + } + + /** + * Unlock a protected {@link OpenPGPSecretKey}. + * + * @param passphraseProvider provider for key passphrases + * @return unlocked private key + * @throws PGPException if the key cannot be unlocked + */ + public OpenPGPPrivateKey unlock(KeyPassphraseProvider passphraseProvider) + throws PGPException + { + if (!isLocked()) + { + return unlock((char[])null); + } + return unlock(passphraseProvider.getKeyPassword(this)); + } + + /** + * Access the {@link PGPKeyPair} by unlocking the potentially locked secret key using the provided + * passphrase. Note: If the key is not locked, it is sufficient to pass null as passphrase. + * + * @param passphrase passphrase or null + * @return keypair containing unlocked private key + * @throws PGPException if the key cannot be unlocked + */ + public OpenPGPPrivateKey unlock(char[] passphrase) + throws PGPException + { + sanitizeProtectionMode(); + PBESecretKeyDecryptor decryptor = null; + try + { + if (passphrase != null) + { + decryptor = decryptorBuilderProvider.provide().build(passphrase); + } + + PGPPrivateKey privateKey = getPGPSecretKey().extractPrivateKey(decryptor); + if (privateKey == null) + { + return null; + } + + PGPKeyPair unlockedKey = new PGPKeyPair(getPGPSecretKey().getPublicKey(), privateKey); + return new OpenPGPPrivateKey(this, unlockedKey); + } + catch (PGPException e) + { + throw new KeyPassphraseException(this, e); + } + } + + private void sanitizeProtectionMode() + throws PGPException + { + if (!isLocked()) + { + return; + } + + PGPSecretKey secretKey = getPGPSecretKey(); + S2K s2k = secretKey.getS2K(); + if (s2k == null) + { + throw new PGPKeyValidationException("Legacy CFB using MD5 is not allowed."); + } + + if (s2k.getType() == S2K.ARGON_2 && secretKey.getS2KUsage() != SecretKeyPacket.USAGE_AEAD) + { + throw new PGPKeyValidationException("Argon2 without AEAD is not allowed."); + } + + if (getVersion() == PublicKeyPacket.VERSION_6) + { + if (secretKey.getS2KUsage() == SecretKeyPacket.USAGE_CHECKSUM) + { + throw new PGPKeyValidationException("Version 6 keys MUST NOT use malleable CFB."); + } + if (s2k.getType() == S2K.SIMPLE) + { + throw new PGPKeyValidationException("Version 6 keys MUST NOT use SIMPLE S2K."); + } + } + } + + /** + * Return true if the provided passphrase is correct. + * + * @param passphrase passphrase + * @return true if the passphrase is correct + */ + public boolean isPassphraseCorrect(char[] passphrase) + { + if (passphrase != null && !isLocked()) + { + return false; + } + + try + { + OpenPGPPrivateKey privateKey = unlock(passphrase); + return privateKey.unlockedKey != null; + } + catch (PGPException e) + { + return false; + } + } + } + + /** + * Unlocked {@link OpenPGPSecretKey}. + */ + public static class OpenPGPPrivateKey + { + private final OpenPGPSecretKey secretKey; + private final PGPKeyPair unlockedKey; + + public OpenPGPPrivateKey(OpenPGPSecretKey secretKey, PGPKeyPair unlockedKey) + { + this.secretKey = secretKey; + this.unlockedKey = unlockedKey; + } + + /** + * Return the public {@link OpenPGPComponentKey} of this {@link OpenPGPPrivateKey}. + * + * @return public component key + */ + public OpenPGPComponentKey getPublicKey() + { + return secretKey.getPublicKey(); + } + + /** + * Return the {@link OpenPGPSecretKey} in its potentially locked form. + * + * @return secret key + */ + public OpenPGPSecretKey getSecretKey() + { + return secretKey; + } + + /** + * Return the unlocked {@link PGPKeyPair} containing the decrypted {@link PGPPrivateKey}. + * + * @return unlocked private key + */ + public PGPKeyPair getKeyPair() + { + return unlockedKey; + } + + /** + * Return the used {@link OpenPGPImplementation}. + * + * @return implementation + */ + private OpenPGPImplementation getImplementation() + { + return getSecretKey().getOpenPGPKey().implementation; + } + + /** + * Return a NEW instance of the {@link OpenPGPSecretKey} locked with the new passphrase. + * If the key was unprotected before, or if it was protected using AEAD, the new instance will be + * protected using AEAD as well. + * + * @param newPassphrase new passphrase + * @return new instance of the key, locked with the new passphrase + * @throws PGPException if the key cannot be locked + */ + public OpenPGPSecretKey changePassphrase(char[] newPassphrase) + throws PGPException + { + boolean useAead = !secretKey.isLocked() || + secretKey.getPGPSecretKey().getS2KUsage() == SecretKeyPacket.USAGE_AEAD; + + return changePassphrase(newPassphrase, getImplementation(), useAead); + } + + /** + * Return a NEW instance of the {@link OpenPGPSecretKey} locked with the new passphrase. + * + * @param newPassphrase new passphrase + * @param implementation OpenPGP implementation + * @param useAEAD whether to protect the key using AEAD + * @return new instance of the key, locked with the new passphrase + * @throws PGPException if the key cannot be locked + */ + public OpenPGPSecretKey changePassphrase(char[] newPassphrase, + OpenPGPImplementation implementation, + boolean useAEAD) + throws PGPException + { + return changePassphrase(newPassphrase, implementation.pbeSecretKeyEncryptorFactory(useAEAD)); + } + + /** + * Return a NEW instance of the {@link OpenPGPSecretKey} locked with the new passphrase. + * + * @param newPassphrase new passphrase + * @param keyEncryptorFactory factory for {@link PBESecretKeyEncryptor} instances + * @return new instance of the key, locked with the new passphrase + * @throws PGPException if the key cannot be locked + */ + public OpenPGPSecretKey changePassphrase(char[] newPassphrase, + PBESecretKeyEncryptorFactory keyEncryptorFactory) + throws PGPException + { + PBESecretKeyEncryptor keyEncryptor; + if (newPassphrase == null || newPassphrase.length == 0) + { + keyEncryptor = null; + } + else + { + keyEncryptor = keyEncryptorFactory.build( + newPassphrase, + getKeyPair().getPublicKey().getPublicKeyPacket()); + } + + return changePassphrase(keyEncryptor); + } + + /** + * Return a NEW instance of the {@link OpenPGPSecretKey} locked using the given {@link PBESecretKeyEncryptor}. + * + * @param keyEncryptor encryptor + * @return new instance of the key, locked with the key encryptor + * @throws PGPException if the key cannot be locked + */ + public OpenPGPSecretKey changePassphrase(PBESecretKeyEncryptor keyEncryptor) + throws PGPException + { + PGPSecretKey encrypted = new PGPSecretKey( + getKeyPair().getPrivateKey(), + getKeyPair().getPublicKey(), + getImplementation().pgpDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), + getSecretKey().isPrimaryKey(), + keyEncryptor); + + OpenPGPSecretKey sk = new OpenPGPSecretKey( + getSecretKey().getPublicKey(), + encrypted, + getImplementation().pbeSecretKeyDecryptorBuilderProvider()); + sk.sanitizeProtectionMode(); + return sk; + } + + /** + * Return a NEW instance of the {@link OpenPGPSecretKey} with removed passphrase protection. + * + * @return unlocked new instance of the key + * @throws PGPException if the key cannot be unlocked + */ + public OpenPGPSecretKey removePassphrase() + throws PGPException + { + return changePassphrase((PBESecretKeyEncryptor)null); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyEditor.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyEditor.java new file mode 100644 index 0000000000..0f9b9a1f59 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyEditor.java @@ -0,0 +1,478 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; + +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PublicKeyUtils; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPKeyValidationException; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.api.exception.OpenPGPKeyException; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; + +public class OpenPGPKeyEditor + extends AbstractOpenPGPKeySignatureGenerator +{ + + private final OpenPGPImplementation implementation; + private final OpenPGPPolicy policy; + private OpenPGPKey key; + private final OpenPGPKey.OpenPGPPrivateKey primaryKey; + + public OpenPGPKeyEditor(OpenPGPKey key, KeyPassphraseProvider passphraseProvider) + throws PGPException + { + this(key, passphraseProvider, key.implementation); + } + + public OpenPGPKeyEditor(OpenPGPKey key, + KeyPassphraseProvider passphraseProvider, + OpenPGPImplementation implementation) + throws PGPException + { + this(key, passphraseProvider, implementation, implementation.policy()); + } + + public OpenPGPKeyEditor(OpenPGPKey key, + KeyPassphraseProvider passphraseProvider, + OpenPGPImplementation implementation, + OpenPGPPolicy policy) + throws PGPException + { + this.key = key; + this.primaryKey = key.getPrimarySecretKey().unlock(passphraseProvider); + this.implementation = implementation; + this.policy = policy; + } + + public OpenPGPKeyEditor addDirectKeySignature(SignatureParameters.Callback signatureCallback) + throws PGPException + { + SignatureParameters parameters = Utils.applySignatureParameters(signatureCallback, + SignatureParameters.directKeySignature(policy)); + + if (parameters != null) + { + PGPPublicKey publicPrimaryKey = key.getPrimaryKey().getPGPPublicKey(); + + PGPSignatureGenerator dkSigGen = Utils.getPgpSignatureGenerator(implementation, publicPrimaryKey, + primaryKey.getKeyPair().getPrivateKey(), parameters, parameters.getSignatureCreationTime(), null); + + PGPPublicKey pubKey = Utils.injectCertification(publicPrimaryKey, dkSigGen); + this.key = generateOpenPGPKey(pubKey); + } + return this; + } + + /** + * Add a user-id to the primary key. + * If the key already contains the given user-id, a new certification signature will be added to the user-id. + * + * @param userId user-id + * @return this + * @throws PGPException if the key cannot be modified + */ + public OpenPGPKeyEditor addUserId(String userId) + throws PGPException + { + return addUserId(userId, null); + } + + /** + * Add a user-id to the primary key, modifying the contents of the certification signature using the given + * {@link SignatureParameters.Callback}. + * If the key already contains the given user-id, a new certification signature will be added to the user-id. + * + * @param userId user-id + * @param signatureCallback callback to modify the certification signature contents + * @return this + * @throws PGPException if the key cannot be modified + */ + public OpenPGPKeyEditor addUserId(String userId, + SignatureParameters.Callback signatureCallback) + throws PGPException + { + // care needs to run with Java 5 + if (userId == null || userId.trim().length() == 0) + { + throw new IllegalArgumentException("User-ID cannot be null or empty."); + } + + SignatureParameters parameters = Utils.applySignatureParameters(signatureCallback, + SignatureParameters.certification(policy)); + + if (parameters != null) + { + PGPPublicKey publicPrimaryKey = key.getPrimaryKey().getPGPPublicKey(); + + PGPSignatureGenerator uidSigGen = Utils.getPgpSignatureGenerator(implementation, publicPrimaryKey, + primaryKey.getKeyPair().getPrivateKey(), parameters, parameters.getSignatureCreationTime(), null); + + this.key = generateOpenPGPKey(Utils.injectCertification(userId, publicPrimaryKey, uidSigGen)); + } + return this; + } + + /** + * Revoke the given {@link OpenPGPCertificate.OpenPGPIdentityComponent}. + * + * @param identity user-id to be revoked + * @return this + * @throws PGPException if the key cannot be modified + */ + public OpenPGPKeyEditor revokeIdentity(OpenPGPCertificate.OpenPGPIdentityComponent identity) + throws PGPException + { + return revokeIdentity(identity, null); + } + + /** + * Revoke the given {@link OpenPGPCertificate.OpenPGPUserId}, allowing modification of the revocation signature + * using the given {@link SignatureParameters.Callback}. + * + * @param identity user-id to revoke + * @param signatureCallback callback to modify the revocation signature contents + * @return this + * @throws PGPException if the key cannot be modified + */ + public OpenPGPKeyEditor revokeIdentity(OpenPGPCertificate.OpenPGPIdentityComponent identity, + SignatureParameters.Callback signatureCallback) + throws PGPException + { + if (!key.getComponents().contains(identity)) + { + throw new IllegalArgumentException("UserID or UserAttribute is not part of the certificate."); + } + + SignatureParameters parameters = Utils.applySignatureParameters(signatureCallback, + SignatureParameters.certificationRevocation(policy)); + + if (parameters != null) + { + PGPPublicKey publicPrimaryKey = key.getPrimaryKey().getPGPPublicKey(); + + PGPSignatureGenerator idSigGen = Utils.getPgpSignatureGenerator(implementation, publicPrimaryKey, + primaryKey.getKeyPair().getPrivateKey(), parameters, parameters.getSignatureCreationTime(), null); + + // Inject signature into the certificate + PGPPublicKey pubKey; + if (identity instanceof OpenPGPCertificate.OpenPGPUserId) + { + OpenPGPCertificate.OpenPGPUserId userId = (OpenPGPCertificate.OpenPGPUserId)identity; + pubKey = Utils.injectCertification(userId.getUserId(), publicPrimaryKey, idSigGen); + } + else + { + OpenPGPCertificate.OpenPGPUserAttribute userAttribute = (OpenPGPCertificate.OpenPGPUserAttribute)identity; + PGPSignature uattrSig = idSigGen.generateCertification(userAttribute.getUserAttribute(), publicPrimaryKey); + pubKey = PGPPublicKey.addCertification(publicPrimaryKey, userAttribute.getUserAttribute(), uattrSig); + } + this.key = generateOpenPGPKey(pubKey); + } + return this; + } + + public OpenPGPKeyEditor addEncryptionSubkey() + throws PGPException + { + return addEncryptionSubkey(KeyPairGeneratorCallback.encryptionKey()); + } + + public OpenPGPKeyEditor addEncryptionSubkey(KeyPairGeneratorCallback keyGenCallback) + throws PGPException + { + return addEncryptionSubkey(keyGenCallback, key.getPrimaryKey().getVersion(), new Date()); + } + + public OpenPGPKeyEditor addEncryptionSubkey(KeyPairGeneratorCallback keyGenCallback, + int version, + Date creationTime) + throws PGPException + { + PGPKeyPairGenerator kpGen = implementation.pgpKeyPairGeneratorProvider() + .get(version, creationTime); + return addEncryptionSubkey(keyGenCallback.generateFrom(kpGen), null); + } + + public OpenPGPKeyEditor addEncryptionSubkey(PGPKeyPair encryptionSubkey, + SignatureParameters.Callback bindingSigCallback) + throws PGPException + { + if (!encryptionSubkey.getPublicKey().isEncryptionKey()) + { + throw new PGPKeyValidationException("Provided subkey is not encryption-capable."); + } + + updateKey(encryptionSubkey, bindingSigCallback, key.getPrimaryKey().getPGPPublicKey(), new Utils.HashedSubpacketsOperation() + { + @Override + public void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + hashedSubpackets.setKeyFlags(KeyFlags.ENCRYPT_STORAGE | KeyFlags.ENCRYPT_COMMS); + } + }); + + return this; + } + + public OpenPGPKeyEditor addSigningSubkey() + throws PGPException + { + return addSigningSubkey(KeyPairGeneratorCallback.signingKey()); + } + + public OpenPGPKeyEditor addSigningSubkey(KeyPairGeneratorCallback keyGenCallback) + throws PGPException + { + return addSigningSubkey(keyGenCallback, key.getPrimaryKey().getVersion(), new Date()); + } + + public OpenPGPKeyEditor addSigningSubkey(KeyPairGeneratorCallback keyGenCallback, + int version, + Date creationTime) + throws PGPException + { + PGPKeyPairGenerator kpGen = implementation.pgpKeyPairGeneratorProvider() + .get(version, creationTime); + return addSigningSubkey(keyGenCallback.generateFrom(kpGen), null, null); + } + + public OpenPGPKeyEditor addSigningSubkey(PGPKeyPair signingSubkey, + SignatureParameters.Callback bindingSigCallback, + SignatureParameters.Callback backSigCallback) + throws PGPException + { + if (!PublicKeyUtils.isSigningAlgorithm(signingSubkey.getPublicKey().getAlgorithm())) + { + throw new PGPKeyValidationException("Provided subkey is not signing-capable."); + } + + SignatureParameters backSigParameters = Utils.applySignatureParameters(backSigCallback, + SignatureParameters.primaryKeyBinding(policy)); + + PGPPublicKey publicPrimaryKey = key.getPrimaryKey().getPGPPublicKey(); + + final PGPSignature backSig = Utils.getBackSignature(signingSubkey, backSigParameters, publicPrimaryKey, implementation, null); + + updateKey(signingSubkey, bindingSigCallback, publicPrimaryKey, new Utils.HashedSubpacketsOperation() + { + @Override + public void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + hashedSubpackets.setKeyFlags(KeyFlags.SIGN_DATA); + Utils.addEmbeddedSiganture(backSig, hashedSubpackets); + } + }); + + return this; + } + + /** + * Add a component key to the certificate. + * The bindingSigCallback can be used to modify the subkey binding signature. + * If it is null, no subkey binding signature will be generated. + * The backSigCallback can be used to modify the embedded primary key binding signature. + * If it is null, no primary key binding signature will be generated. + * You MUST only pass a non-null value here, if the subkey is capable of creating signatures. + * + * @param subkey component key + * @param bindingSigCallback callback to modify the subkey binding signature + * @param backSigCallback callback to modify the embedded primary key binding signature + * @return this + * @throws PGPException + */ + public OpenPGPKeyEditor addSubkey(PGPKeyPair subkey, + SignatureParameters.Callback bindingSigCallback, + SignatureParameters.Callback backSigCallback) + throws PGPException + { + if (PublicKeyUtils.isSigningAlgorithm(subkey.getPublicKey().getAlgorithm()) + && backSigCallback != null) + { + throw new PGPKeyValidationException("Provided subkey is not signing-capable, so we cannot create a back-signature."); + } + + PGPPublicKey publicSubKey = subkey.getPublicKey(); + + SignatureParameters backSigParameters = Utils.applySignatureParameters(backSigCallback, + SignatureParameters.primaryKeyBinding(policy)); + + PGPPublicKey publicPrimaryKey = key.getPrimaryKey().getPGPPublicKey(); + + final PGPSignature backSig = Utils.getBackSignature(subkey, backSigParameters, publicPrimaryKey, implementation, null); + + SignatureParameters parameters = Utils.applySignatureParameters(bindingSigCallback, + SignatureParameters.subkeyBinding(policy)); + + if (parameters != null) + { + PGPSignatureGenerator subKeySigGen = Utils.getPgpSignatureGenerator(implementation, publicPrimaryKey, + primaryKey.getKeyPair().getPrivateKey(), parameters, parameters.getSignatureCreationTime(), + new Utils.HashedSubpacketsOperation() + { + @Override + public void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + Utils.addEmbeddedSiganture(backSig, hashedSubpackets); + } + }); + + // Inject signature into the certificate + publicSubKey = Utils.injectCertification(publicSubKey, subKeySigGen, publicPrimaryKey); + } + + this.key = generateOpenPGPKey(subkey, publicSubKey); + + return this; + } + + public OpenPGPKeyEditor revokeComponentKey(OpenPGPCertificate.OpenPGPComponentKey componentKey) + throws PGPException + { + return revokeComponentKey(componentKey, null); + } + + public OpenPGPKeyEditor revokeComponentKey(OpenPGPCertificate.OpenPGPComponentKey componentKey, + SignatureParameters.Callback revocationSignatureCallback) + throws PGPException + { + boolean contained = key.getKey(componentKey.getKeyIdentifier()) != null; + if (!contained) + { + throw new IllegalArgumentException("Provided component key is not part of the OpenPGP key."); + } + + boolean isSubkeyRevocation = !componentKey.getKeyIdentifier().equals(key.getKeyIdentifier()); + SignatureParameters parameters; + if (isSubkeyRevocation) + { + // Generate Subkey Revocation Signature + parameters = SignatureParameters.subkeyRevocation(policy); + } + else + { + // Generate Key Revocation Signature + parameters = SignatureParameters.keyRevocation(policy); + } + + parameters = Utils.applySignatureParameters(revocationSignatureCallback, parameters); + + PGPPublicKey publicPrimaryKey = key.getPrimaryKey().getPGPPublicKey(); + PGPSignatureGenerator revGen = Utils.getPgpSignatureGenerator(implementation, publicPrimaryKey, + primaryKey.getKeyPair().getPrivateKey(), parameters, parameters.getSignatureCreationTime(), null); + + if (isSubkeyRevocation) + { + publicPrimaryKey = Utils.injectCertification(componentKey.getPGPPublicKey(), revGen, publicPrimaryKey); + } + else + { + publicPrimaryKey = Utils.injectCertification(publicPrimaryKey, revGen); + } + this.key = generateOpenPGPKey(publicPrimaryKey); + + return this; + } + + public OpenPGPKeyEditor revokeKey() + throws PGPException + { + return revokeKey(null); + } + + public OpenPGPKeyEditor revokeKey(SignatureParameters.Callback revocationSignatureCallback) + throws PGPException + { + return revokeComponentKey(key.getPrimaryKey(), revocationSignatureCallback); + } + + /** + * Change the passphrase of the given component key. + * + * @param componentKeyIdentifier identifier of the component key, whose passphrase shall be changed + * @param oldPassphrase old passphrase (or null) + * @param newPassphrase new passphrase (or null) + * @param useAEAD whether to use AEAD + * @return this + * @throws OpenPGPKeyException if the secret component of the component key is missing + * @throws PGPException if the key passphrase cannot be changed + */ + public OpenPGPKeyEditor changePassphrase(KeyIdentifier componentKeyIdentifier, + char[] oldPassphrase, + char[] newPassphrase, + boolean useAEAD) + throws OpenPGPKeyException, PGPException + { + OpenPGPKey.OpenPGPSecretKey secretKey = key.getSecretKey(componentKeyIdentifier); + if (secretKey == null) + { + throw new OpenPGPKeyException(key, "Secret component key " + componentKeyIdentifier + + " is missing from the key."); + } + + OpenPGPKey.OpenPGPPrivateKey privateKey = secretKey.unlock(oldPassphrase); + secretKey = privateKey.changePassphrase(newPassphrase, implementation, useAEAD); + + key.replaceSecretKey(secretKey); + return this; + } + + /** + * Return the modified {@link OpenPGPKey}. + * + * @return modified key + */ + public OpenPGPKey done() + { + return key; + } + + private OpenPGPKey generateOpenPGPKey(PGPPublicKey publicPrimaryKey) + { + PGPPublicKeyRing publicKeyRing = PGPPublicKeyRing.insertPublicKey(key.getPGPPublicKeyRing(), publicPrimaryKey); + PGPSecretKeyRing secretKeyRing = PGPSecretKeyRing.replacePublicKeys(key.getPGPKeyRing(), publicKeyRing); + return new OpenPGPKey(secretKeyRing, implementation, policy); + } + + private OpenPGPKey generateOpenPGPKey(PGPKeyPair subkey, PGPPublicKey publicSubKey) + throws PGPException + { + PGPSecretKey secretSubkey = new PGPSecretKey( + subkey.getPrivateKey(), + publicSubKey, + implementation.pgpDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), + false, + null); + PGPSecretKeyRing secretKeyRing = PGPSecretKeyRing.insertSecretKey(key.getPGPKeyRing(), secretSubkey); + return new OpenPGPKey(secretKeyRing, implementation, policy); + } + + private void updateKey(PGPKeyPair subkey, SignatureParameters.Callback bindingSigCallback, PGPPublicKey publicPrimaryKey, Utils.HashedSubpacketsOperation operation) + throws PGPException + { + SignatureParameters parameters = Utils.applySignatureParameters(bindingSigCallback, + SignatureParameters.subkeyBinding(policy)); + + if (parameters != null) + { + PGPSignatureGenerator subKeySigGen = Utils.getPgpSignatureGenerator(implementation, publicPrimaryKey, + primaryKey.getKeyPair().getPrivateKey(), parameters, parameters.getSignatureCreationTime(), + operation); + + PGPPublicKey publicSubKey = Utils.injectCertification(subkey.getPublicKey(), subKeySigGen, publicPrimaryKey); + this.key = generateOpenPGPKey(subkey, publicSubKey); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyGenerator.java new file mode 100644 index 0000000000..7ce19c3ad3 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyGenerator.java @@ -0,0 +1,733 @@ +package org.bouncycastle.openpgp.api; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.PublicKeyUtils; +import org.bouncycastle.bcpg.PublicSubkeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; +import org.bouncycastle.openpgp.operator.PGPKeyPairGeneratorProvider; +import org.bouncycastle.util.Arrays; + +/** + * High-level generator class for OpenPGP v6 keys. + */ +public class OpenPGPKeyGenerator + extends AbstractOpenPGPKeySignatureGenerator +{ + // SECONDS + private static final long SECONDS_PER_MINUTE = 60; + private static final long SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE; + private static final long SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR; + private static final long SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY; + + private final int keyVersion; + private final OpenPGPImplementation implementationProvider; + private final Configuration configuration; // contains BC or JCA/JCE implementations + + public OpenPGPKeyGenerator(OpenPGPImplementation implementation, + boolean aead, + Date creationTime) + throws PGPException + { + this(implementation, PublicKeyPacket.VERSION_6, aead, creationTime); + } + + public OpenPGPKeyGenerator(OpenPGPImplementation implementationProvider, + int version, + boolean aead, + Date creationTime) + throws PGPException + { + this( + implementationProvider, + version, + implementationProvider.pgpKeyPairGeneratorProvider(), + implementationProvider.pgpDigestCalculatorProvider(), + implementationProvider.pbeSecretKeyEncryptorFactory(aead), + implementationProvider.keyFingerPrintCalculator(), + creationTime + ); + } + + /** + * Generate a new OpenPGP key generator for v6 keys. + * + * @param kpGenProvider key pair generator provider + * @param digestCalculatorProvider digest calculator provider + * @param keyEncryptionBuilderProvider secret key encryption builder provider (AEAD) + * @param keyFingerPrintCalculator calculator for key fingerprints + * @param creationTime key creation time + */ + public OpenPGPKeyGenerator( + OpenPGPImplementation implementationProvider, + int keyVersion, + PGPKeyPairGeneratorProvider kpGenProvider, + PGPDigestCalculatorProvider digestCalculatorProvider, + PBESecretKeyEncryptorFactory keyEncryptionBuilderProvider, + KeyFingerPrintCalculator keyFingerPrintCalculator, + Date creationTime) + { + if (keyVersion != PublicKeyPacket.VERSION_4 && + keyVersion != PublicKeyPacket.LIBREPGP_5 && + keyVersion != PublicKeyPacket.VERSION_6) + { + throw new IllegalArgumentException("Generating keys of version " + keyVersion + " is not supported."); + } + + this.implementationProvider = implementationProvider; + this.keyVersion = keyVersion; + this.configuration = new Configuration(creationTime, kpGenProvider, digestCalculatorProvider, keyEncryptionBuilderProvider, keyFingerPrintCalculator); + } + + /** + * Generate an OpenPGP key consisting of a certify-only primary key, + * a dedicated signing-subkey and dedicated encryption-subkey. + * The key will optionally carry the provided user-id. + * See {@link PGPKeyPairGenerator#generatePrimaryKey()} for the primary key type, + * {@link PGPKeyPairGenerator#generateSigningSubkey()} for the signing-subkey type and + * {@link PGPKeyPairGenerator#generateEncryptionSubkey()} for the encryption-subkey key type. + * + * @param userId nullable user id + * @return OpenPGP key + * @throws PGPException if the key cannot be prepared + */ + public WithPrimaryKey classicKey(String userId) + throws PGPException + { + WithPrimaryKey builder = withPrimaryKey() + .addSigningSubkey() + .addEncryptionSubkey(); + + if (userId != null) + { + builder.addUserId(userId); + } + + return builder; + } + + /** + * Generate an OpenPGP key consisting of an Ed25519 certify-only primary key, + * a dedicated Ed25519 sign-only subkey and dedicated X25519 encryption-only subkey. + * The key will optionally carry the provided user-id. + * + * @param userId nullable user id + * @return OpenPGP key + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey ed25519x25519Key(String userId) + throws PGPException + { + WithPrimaryKey builder = withPrimaryKey(new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEd25519KeyPair(); + } + }) + .addSigningSubkey(new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEd25519KeyPair(); + } + }) + .addEncryptionSubkey(new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateX25519KeyPair(); + } + }); + + if (userId != null) + { + builder.addUserId(userId); + } + + return builder; + } + + + /** + * Generate an OpenPGP key consisting of an Ed448 certify-only primary key, + * a dedicated Ed448 sign-only subkey and dedicated X448 encryption-only subkey. + * The key will optionally carry the provided user-id. + * + * @param userId nullable user id + * @return OpenPGP key + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey ed448x448Key(String userId) + throws PGPException + { + WithPrimaryKey builder = withPrimaryKey(new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEd448KeyPair(); + } + }) + .addSigningSubkey(new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEd448KeyPair(); + } + }) + .addEncryptionSubkey(new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateX448KeyPair(); + } + }); + + if (userId != null) + { + builder.addUserId(userId); + } + + return builder; + } + + /** + * Generate a sign-only OpenPGP key. + * The key consists of a single, user-id-less primary key, which is capable of signing and certifying. + * See {@link PGPKeyPairGenerator#generatePrimaryKey()} for the key type. + * + * @return sign-only (+certify) OpenPGP key + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey signOnlyKey() + throws PGPException + { + return withPrimaryKey( + KeyPairGeneratorCallback.primaryKey(), + SignatureParameters.Callback.Util.modifyHashedSubpackets(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + subpackets.setKeyFlags(true, KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA); + return subpackets; + } + })); + } + + /** + * Generate an OpenPGP key with a certification-capable primary key. + * See {@link PGPKeyPairGenerator#generatePrimaryKey()} for the primary key type + * + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey withPrimaryKey() + throws PGPException + { + return withPrimaryKey(KeyPairGeneratorCallback.primaryKey()); + } + + /** + * Generate an OpenPGP key with a certification-capable primary key. + * The primary key type can be decided using the {@link KeyPairGeneratorCallback}. + * + * @param keyGenCallback callback to decide the key type + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey withPrimaryKey( + KeyPairGeneratorCallback keyGenCallback) + throws PGPException + { + return withPrimaryKey(keyGenCallback, null); + } + + /** + * Generate an OpenPGP key with a certification-capable primary key. + * The primary key type can be decided using the {@link KeyPairGeneratorCallback}. + * The {@link SignatureParameters.Callback} can be used to modify the preferences in the direct-key self signature. + * If the callback itself is null, the generator will create a default direct-key signature. + * If the result of {@link SignatureParameters.Callback#apply(SignatureParameters)} is null, no direct-key + * signature will be generated for the key. + * + * @param keyGenCallback callback to decide the key type + * @param preferenceSignatureCallback callback to modify the direct-key signature + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey withPrimaryKey( + KeyPairGeneratorCallback keyGenCallback, + SignatureParameters.Callback preferenceSignatureCallback) + throws PGPException + { + PGPKeyPair primaryKeyPair = keyGenCallback.generateFrom(configuration.kpGenProvider.get( + keyVersion, configuration.keyCreationTime)); + + if (primaryKeyPair.getPublicKey().getPublicKeyPacket() instanceof PublicSubkeyPacket) + { + throw new IllegalArgumentException("Primary key MUST NOT consist of subkey packet."); + } + + if (!PublicKeyUtils.isSigningAlgorithm(primaryKeyPair.getPublicKey().getAlgorithm())) + { + throw new PGPException("Primary key MUST use signing-capable algorithm."); + } + + SignatureParameters parameters = Utils.applySignatureParameters(preferenceSignatureCallback, + SignatureParameters.directKeySignature(implementationProvider.policy())); + + if (parameters != null) + { + PGPSignatureGenerator preferenceSigGen = Utils.getPgpSignatureGenerator(implementationProvider, + primaryKeyPair.getPublicKey(), primaryKeyPair.getPrivateKey(), parameters, configuration.keyCreationTime, + new Utils.HashedSubpacketsOperation() + { + @Override + public void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + hashedSubpackets = directKeySignatureSubpackets.apply(hashedSubpackets); + hashedSubpackets.setKeyFlags(true, KeyFlags.CERTIFY_OTHER); + hashedSubpackets.setKeyExpirationTime(false, 5 * SECONDS_PER_YEAR); + } + }); + + primaryKeyPair = new PGPKeyPair( + Utils.injectCertification(primaryKeyPair.getPublicKey(), preferenceSigGen), + primaryKeyPair.getPrivateKey()); + } + + return new WithPrimaryKey(implementationProvider, configuration, primaryKeyPair); + } + + /** + * Intermediate builder class. + * Constructs an OpenPGP key from a specified primary key. + */ + public class WithPrimaryKey + { + private final OpenPGPImplementation implementation; + private final Configuration configuration; + private PGPKeyPair primaryKey; + private final List subkeys = new ArrayList(); + + /** + * Builder. + * + * @param implementation cryptographic implementation + * @param primaryKey specified primary key + */ + private WithPrimaryKey(OpenPGPImplementation implementation, Configuration configuration, PGPKeyPair primaryKey) + { + this.implementation = implementation; + this.configuration = configuration; + this.primaryKey = primaryKey; + } + + /** + * Attach a User-ID with a positive certification to the key. + * + * @param userId user-id + * @return builder + * @throws PGPException if the user-id cannot be added + */ + public WithPrimaryKey addUserId(String userId) + throws PGPException + { + return addUserId(userId, null); + } + + /** + * Attach a User-ID with a positive certification to the key. + * The subpackets of the user-id certification can be modified using the userIdSubpackets callback. + * + * @param userId user-id + * @param signatureParameters signature parameters + * @return builder + * @throws PGPException if the user-id cannot be added + */ + public WithPrimaryKey addUserId( + String userId, + SignatureParameters.Callback signatureParameters) + throws PGPException + { + // care - needs to run with Java 5. + if (userId == null || userId.trim().length() == 0) + { + throw new IllegalArgumentException("User-ID cannot be null or empty."); + } + + SignatureParameters parameters = Utils.applySignatureParameters(signatureParameters, + SignatureParameters.certification(implementation.policy())); + + if (parameters != null) + { + PGPSignatureGenerator uidSigGen = Utils.getPgpSignatureGenerator(implementation, primaryKey.getPublicKey(), + primaryKey.getPrivateKey(), parameters, configuration.keyCreationTime, null); + primaryKey = new PGPKeyPair(Utils.injectCertification(userId, primaryKey.getPublicKey(), uidSigGen), primaryKey.getPrivateKey()); + } + + return this; + } + + /** + * Add an encryption-capable subkey to the OpenPGP key. + * See {@link PGPKeyPairGenerator#generateEncryptionSubkey()} for the key type. + * + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addEncryptionSubkey() + throws PGPException + { + return addEncryptionSubkey(KeyPairGeneratorCallback.encryptionKey()); + } + + /** + * Add an encryption-capable subkey to the OpenPGP key. + * The type of the subkey can be decided by implementing the {@link KeyPairGeneratorCallback}. + * + * @param keyGenCallback callback to decide the encryption subkey type + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addEncryptionSubkey(KeyPairGeneratorCallback keyGenCallback) + throws PGPException + { + return addEncryptionSubkey(keyGenCallback, null); + } + + /** + * Add an encryption-capable subkey to the OpenPGP key. + * The type of the subkey can be decided by implementing the {@link KeyPairGeneratorCallback}. + * The binding signature can be modified by implementing the {@link SignatureSubpacketsFunction}. + * + * @param generatorCallback callback to specify the encryption key type. + * @param bindingSubpacketsCallback nullable callback to modify the binding signature subpackets + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addEncryptionSubkey( + KeyPairGeneratorCallback generatorCallback, + SignatureParameters.Callback bindingSubpacketsCallback) + throws PGPException + { + PGPKeyPairGenerator generator = configuration.kpGenProvider.get( + keyVersion, configuration.keyCreationTime); + PGPKeyPair subkey = generatorCallback.generateFrom(generator); + subkey = subkey.asSubkey(implementation.keyFingerPrintCalculator()); + + return addEncryptionSubkey(subkey, bindingSubpacketsCallback); + } + + /** + * Add an encryption-capable subkey to the OpenPGP key. + * IMPORTANT: The custom key encryptor will only be used, if in the final step the key is retrieved + * using {@link #build()}. + * If instead {@link #build(char[])} is used, the key-specific encryptor is overwritten with an encryptor + * built from the argument passed into {@link #build(char[])}. + * + * @param encryptionSubkey encryption subkey + * @param bindingSubpacketsCallback nullable callback to modify the subkey binding signature subpackets + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addEncryptionSubkey( + PGPKeyPair encryptionSubkey, + SignatureParameters.Callback bindingSubpacketsCallback) + throws PGPException + { + if (!(encryptionSubkey.getPublicKey().getPublicKeyPacket() instanceof PublicSubkeyPacket)) + { + throw new IllegalArgumentException("Encryption subkey MUST NOT consist of a primary key packet."); + } + + if (!encryptionSubkey.getPublicKey().isEncryptionKey()) + { + throw new PGPException("Encryption key MUST use encryption-capable algorithm."); + } + + encryptionSubkey = updateSubkey(encryptionSubkey, bindingSubpacketsCallback, new Utils.HashedSubpacketsOperation() + { + @Override + public void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + hashedSubpackets = encryptionSubkeySubpackets.apply(hashedSubpackets); + } + }); + + subkeys.add(encryptionSubkey); + return this; + } + + /** + * Add a signing-capable subkey to the OpenPGP key. + * The binding signature will contain a primary-key back-signature. + * See {@link PGPKeyPairGenerator#generateSigningSubkey()} for the key type. + * + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addSigningSubkey() + throws PGPException + { + return addSigningSubkey(KeyPairGeneratorCallback.signingKey()); + } + + /** + * Add a signing-capable subkey to the OpenPGP key. + * The signing-key type can be specified by overriding the {@link KeyPairGeneratorCallback}. + * The binding signature will contain a primary-key back-signature. + * IMPORTANT: The custom subkey passphrase will only be used, if in the final step the key is retrieved + * using {@link #build()}. + * If instead {@link #build(char[])} is used, the key-specific passphrase is overwritten with the argument + * passed into {@link #build(char[])}. + * + * @param keyGenCallback callback to specify the signing-key type + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addSigningSubkey(KeyPairGeneratorCallback keyGenCallback) + throws PGPException + { + return addSigningSubkey(keyGenCallback, null, null); + } + + /** + * Add a signing-capable subkey to the OpenPGP key. + * The signing-key type can be specified by overriding the {@link KeyPairGeneratorCallback}. + * The binding signature will contain a primary-key back-signature. + * The contents of the binding signature(s) can be modified by overriding the respective + * {@link SignatureSubpacketsFunction} instances. + * IMPORTANT: The custom subkey passphrase will only be used, if in the final step the key is retrieved + * using {@link #build()}. + * If instead {@link #build(char[])} is used, the key-specific passphrase is overwritten with the argument + * passed into {@link #build(char[])}. + * + * @param keyGenCallback callback to specify the signing-key type + * @param bindingSignatureCallback callback to modify the contents of the signing subkey binding signature + * @param backSignatureCallback callback to modify the contents of the embedded primary key binding signature + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addSigningSubkey(KeyPairGeneratorCallback keyGenCallback, + SignatureParameters.Callback bindingSignatureCallback, + SignatureParameters.Callback backSignatureCallback) + throws PGPException + { + PGPKeyPair subkey = keyGenCallback.generateFrom(configuration.kpGenProvider.get( + keyVersion, configuration.keyCreationTime)); + subkey = subkey.asSubkey(configuration.keyFingerprintCalculator); + return addSigningSubkey(subkey, bindingSignatureCallback, backSignatureCallback); + } + + /** + * Add a signing-capable subkey to the OpenPGP key. + * The signing-key type can be specified by overriding the {@link KeyPairGeneratorCallback}. + * The binding signature will contain a primary-key back-signature. + * The contents of the binding signature(s) can be modified by overriding the respective + * {@link SignatureSubpacketsFunction} instances. + * IMPORTANT: The custom key encryptor will only be used, if in the final step the key is retrieved + * using {@link #build()}. + * If instead {@link #build(char[])} is used, the key-specific encryptor is overwritten with an encryptor + * built from the argument passed into {@link #build(char[])}. + * + * @param signingSubkey signing subkey + * @param bindingSignatureCallback callback to modify the contents of the signing subkey binding signature + * @param backSignatureCallback callback to modify the contents of the embedded primary key binding signature + * @return builder + * @throws PGPException if the key cannot be generated + */ + public WithPrimaryKey addSigningSubkey(PGPKeyPair signingSubkey, + SignatureParameters.Callback bindingSignatureCallback, + SignatureParameters.Callback backSignatureCallback) + throws PGPException + { + if (!(signingSubkey.getPublicKey().getPublicKeyPacket() instanceof PublicSubkeyPacket)) + { + throw new IllegalArgumentException("Signing subkey MUST NOT consist of primary key packet."); + } + + if (!PublicKeyUtils.isSigningAlgorithm(signingSubkey.getPublicKey().getAlgorithm())) + { + throw new PGPException("Signing key MUST use signing-capable algorithm."); + } + + SignatureParameters parameters = Utils.applySignatureParameters(backSignatureCallback, + SignatureParameters.primaryKeyBinding(implementation.policy())); + + // Generate PrimaryKeySignature (Back-Signature) + final PGPSignature backSig = Utils.getBackSignature(signingSubkey, parameters, primaryKey.getPublicKey(), + implementation, configuration.keyCreationTime); + + signingSubkey = updateSubkey(signingSubkey, bindingSignatureCallback, new Utils.HashedSubpacketsOperation() + { + @Override + public void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + hashedSubpackets = signingSubkeySubpackets.apply(hashedSubpackets); + Utils.addEmbeddedSiganture(backSig, hashedSubpackets); + } + }); + + subkeys.add(signingSubkey); + + return this; + } + + + /** + * Build the {@link PGPSecretKeyRing OpenPGP key} without protecting the secret keys. + * + * @return OpenPGP key + * @throws PGPException if the key cannot be generated + */ + public OpenPGPKey build() + throws PGPException + { + return build(null); + } + + /** + * Build the {@link PGPSecretKeyRing OpenPGP key} using a single passphrase used to protect all subkeys. + * The passphrase will override whichever key protectors were specified in previous builder steps. + * + * @param passphrase nullable passphrase + * @return OpenPGP key + * @throws PGPException if the key cannot be generated + */ + public OpenPGPKey build(char[] passphrase) + throws PGPException + { + PBESecretKeyEncryptor primaryKeyEncryptor = configuration.keyEncryptorBuilderProvider + .build(passphrase, primaryKey.getPublicKey().getPublicKeyPacket()); + PGPSecretKey primarySecretKey = new PGPSecretKey( + primaryKey.getPrivateKey(), + primaryKey.getPublicKey(), + configuration.digestCalculatorProvider.get(HashAlgorithmTags.SHA1), + true, + primaryKeyEncryptor); + sanitizeKeyEncryptor(primaryKeyEncryptor); + List keys = new ArrayList(); + keys.add(primarySecretKey); + + for (Iterator it = subkeys.iterator(); it.hasNext(); ) + { + PGPKeyPair key = (PGPKeyPair)it.next(); + PBESecretKeyEncryptor subkeyEncryptor = configuration.keyEncryptorBuilderProvider + .build(passphrase, key.getPublicKey().getPublicKeyPacket()); + PGPSecretKey subkey = new PGPSecretKey( + key.getPrivateKey(), + key.getPublicKey(), + configuration.digestCalculatorProvider.get(HashAlgorithmTags.SHA1), + false, + subkeyEncryptor); + sanitizeKeyEncryptor(subkeyEncryptor); + keys.add(subkey); + } + + if (passphrase != null) + { + Arrays.fill(passphrase, (char)0); + } + + PGPSecretKeyRing secretKeys = new PGPSecretKeyRing(keys); + return new OpenPGPKey(secretKeys, implementation); + } + + protected void sanitizeKeyEncryptor(PBESecretKeyEncryptor keyEncryptor) + { + if (keyEncryptor == null) + { + // Unprotected is okay + return; + } + + S2K s2k = keyEncryptor.getS2K(); + if (s2k.getType() == S2K.SIMPLE || s2k.getType() == S2K.SALTED) + { + throw new IllegalArgumentException("S2K specifiers SIMPLE and SALTED are not allowed for secret key encryption."); + } + else if (s2k.getType() == S2K.ARGON_2) + { + if (keyEncryptor.getAeadAlgorithm() == 0) + { + throw new IllegalArgumentException("Argon2 MUST be used with AEAD."); + } + } + } + + private PGPKeyPair updateSubkey(PGPKeyPair subkey, SignatureParameters.Callback bindingSubpacketsCallback, + Utils.HashedSubpacketsOperation operation) + throws PGPException + { + SignatureParameters parameters = Utils.applySignatureParameters(bindingSubpacketsCallback, + SignatureParameters.subkeyBinding(implementation.policy()).setSignatureCreationTime(configuration.keyCreationTime)); + + if (parameters != null) + { + PGPSignatureGenerator bindingSigGen = Utils.getPgpSignatureGenerator(implementation, primaryKey.getPublicKey(), + primaryKey.getPrivateKey(), parameters, parameters.getSignatureCreationTime(), operation); + + PGPPublicKey publicSubkey = Utils.injectCertification(subkey.getPublicKey(), bindingSigGen, primaryKey.getPublicKey()); + subkey = new PGPKeyPair(publicSubkey, subkey.getPrivateKey()); + } + return subkey; + } + } + + /** + * Bundle implementation-specific provider classes. + */ + private static class Configuration + { + final Date keyCreationTime; + final PGPKeyPairGeneratorProvider kpGenProvider; + final PGPDigestCalculatorProvider digestCalculatorProvider; + final PBESecretKeyEncryptorFactory keyEncryptorBuilderProvider; + final KeyFingerPrintCalculator keyFingerprintCalculator; + + public Configuration(Date keyCreationTime, + PGPKeyPairGeneratorProvider keyPairGeneratorProvider, + PGPDigestCalculatorProvider digestCalculatorProvider, + PBESecretKeyEncryptorFactory keyEncryptorBuilderProvider, + KeyFingerPrintCalculator keyFingerPrintCalculator) + { + this.keyCreationTime = new Date((keyCreationTime.getTime() / 1000) * 1000); + this.kpGenProvider = keyPairGeneratorProvider; + this.digestCalculatorProvider = digestCalculatorProvider; + this.keyEncryptorBuilderProvider = keyEncryptorBuilderProvider; + this.keyFingerprintCalculator = keyFingerPrintCalculator; + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyMaterialPool.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyMaterialPool.java new file mode 100644 index 0000000000..9dd543316a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyMaterialPool.java @@ -0,0 +1,210 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.bouncycastle.bcpg.KeyIdentifier; + +/** + * Implementation of the {@link OpenPGPKeyMaterialProvider} which caches items in a {@link HashMap}. + * It allows to provide key or certificates dynamically via a {@link #callback} that can be set using + * {@link #setMissingItemCallback(OpenPGPKeyMaterialProvider)}. + * Results from this callback are automatically cached for later access. This behavior can be adjusted via + * {@link #setCacheResultsFromCallback(boolean)}. + * + * @param {@link OpenPGPCertificate} or {@link OpenPGPKey} + */ +public abstract class OpenPGPKeyMaterialPool + implements OpenPGPKeyMaterialProvider +{ + private final Map pool = new HashMap(); + private OpenPGPKeyMaterialProvider callback = null; + private boolean cacheResultsFromCallback = true; + + /** + * Create an empty pool. + */ + public OpenPGPKeyMaterialPool() + { + + } + + /** + * Create a pool from the single provided item. + * @param item item + */ + public OpenPGPKeyMaterialPool(M item) + { + addItem(item); + } + + /** + * Create a pool and initialize its contents with the provided collection of items. + * @param items collection of keys or certificates + */ + public OpenPGPKeyMaterialPool(Collection items) + { + for (M item : items) + { + addItem(item); + } + } + + /** + * Set a callback that gets fired whenever an item is requested, which is not found in the pool. + * + * @param callback callback + * @return this + */ + public OpenPGPKeyMaterialPool setMissingItemCallback(OpenPGPKeyMaterialProvider callback) + { + if (callback == null) + { + throw new NullPointerException(); + } + this.callback = callback; + return this; + } + + /** + * Decide, whether the implementation should add {@link OpenPGPCertificate certificates} returned by + * {@link #callback} to the pool of cached certificates. + * + * @param cacheResults if true, cache certificates from callback + * @return this + */ + public OpenPGPKeyMaterialPool setCacheResultsFromCallback(boolean cacheResults) + { + this.cacheResultsFromCallback = cacheResults; + return this; + } + + @Override + public M provide(KeyIdentifier componentKeyIdentifier) + { + M result = pool.get(componentKeyIdentifier); + if (result == null && callback != null) + { + // dynamically request certificate or key from callback + result = callback.provide(componentKeyIdentifier); + if (cacheResultsFromCallback) + { + addItem(result); + } + } + return result; + } + + /** + * Add a certificate to the pool. + * Note: If multiple items share the same subkey material, adding an item might overwrite the reference to + * another item for that subkey. + * + * @param item OpenPGP key or certificate that shall be added into the pool + * @return this + */ + public OpenPGPKeyMaterialPool addItem(M item) + { + if (item != null) + { + for (Iterator it = item.getAllKeyIdentifiers().iterator(); it.hasNext();) + { + pool.put(it.next(), item); + } + } + return this; + } + + /** + * Return all items from the pool. + * @return all items + */ + public Collection getAllItems() + { + Stream distinct = pool.values().stream().distinct(); + return distinct.collect(Collectors.toList()); + } + + /** + * Implementation of {@link OpenPGPKeyMaterialPool} tailored to provide {@link OpenPGPKey OpenPGPKeys}. + */ + public static class OpenPGPKeyPool + extends OpenPGPKeyMaterialPool + implements OpenPGPKeyProvider + { + public OpenPGPKeyPool() + { + super(); + } + + public OpenPGPKeyPool(Collection items) + { + super(items); + } + + @Override + public OpenPGPKeyPool setMissingItemCallback(OpenPGPKeyMaterialProvider callback) + { + super.setMissingItemCallback(callback); + return this; + } + + @Override + public OpenPGPKeyPool setCacheResultsFromCallback(boolean cacheResults) + { + super.setCacheResultsFromCallback(cacheResults); + return this; + } + + @Override + public OpenPGPKeyPool addItem(OpenPGPKey item) + { + super.addItem(item); + return this; + } + } + + /** + * Implementation of {@link OpenPGPKeyMaterialPool} tailored to providing + * {@link OpenPGPCertificate OpenPGPCertificates}. + */ + public static class OpenPGPCertificatePool + extends OpenPGPKeyMaterialPool + implements OpenPGPCertificateProvider + { + public OpenPGPCertificatePool() + { + super(); + } + + public OpenPGPCertificatePool(Collection items) + { + super(items); + } + + @Override + public OpenPGPCertificatePool setMissingItemCallback(OpenPGPKeyMaterialProvider callback) + { + super.setMissingItemCallback(callback); + return this; + } + + @Override + public OpenPGPCertificatePool setCacheResultsFromCallback(boolean cacheResults) + { + super.setCacheResultsFromCallback(cacheResults); + return this; + } + + @Override + public OpenPGPCertificatePool addItem(OpenPGPCertificate item) + { + super.addItem(item); + return this; + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyMaterialProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyMaterialProvider.java new file mode 100644 index 0000000000..61b0af8c73 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyMaterialProvider.java @@ -0,0 +1,40 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.bcpg.KeyIdentifier; + +/** + * Interface for providing OpenPGP keys or certificates. + * + * @param either {@link OpenPGPCertificate} or {@link OpenPGPKey} + */ +public interface OpenPGPKeyMaterialProvider +{ + /** + * Provide the requested {@link OpenPGPCertificate} or {@link OpenPGPKey} containing the component key identified + * by the passed in {@link KeyIdentifier}. + * + * @param componentKeyIdentifier identifier of a component key (primary key or subkey) + * @return the OpenPGP certificate or key containing the identified component key + */ + M provide(KeyIdentifier componentKeyIdentifier); + + /** + * Interface for requesting {@link OpenPGPCertificate OpenPGPCertificates} by providing a {@link KeyIdentifier}. + * The {@link KeyIdentifier} can either be that of the certificates primary key, or of a subkey. + */ + interface OpenPGPCertificateProvider + extends OpenPGPKeyMaterialProvider + { + + } + + /** + * Interface for requesting {@link OpenPGPKey OpenPGPKeys} by providing a {@link KeyIdentifier}. + * The {@link KeyIdentifier} can either be that of the keys primary key, or of a subkey. + */ + interface OpenPGPKeyProvider + extends OpenPGPKeyMaterialProvider + { + + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyReader.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyReader.java new file mode 100644 index 0000000000..de20829c78 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPKeyReader.java @@ -0,0 +1,346 @@ +package org.bouncycastle.openpgp.api; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.openpgp.PGPMarker; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.Streams; + +/** + * Reader for {@link OpenPGPKey OpenPGPKeys} or {@link OpenPGPCertificate OpenPGPCertificates}. + */ +public class OpenPGPKeyReader +{ + private final OpenPGPImplementation implementation; + private final OpenPGPPolicy policy; + + public OpenPGPKeyReader() + { + this(OpenPGPImplementation.getInstance()); + } + + public OpenPGPKeyReader(OpenPGPImplementation implementation) + { + this(implementation, implementation.policy()); + } + + public OpenPGPKeyReader(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + this.implementation = implementation; + this.policy = policy; + } + + /** + * Parse a single {@link OpenPGPCertificate} from an ASCII armored string. + * + * @param armored ASCII armored string + * @return parsed certificate + * @throws IOException if the parsed object is a secret key or if the cert cannot be parsed + */ + public OpenPGPCertificate parseCertificate(String armored) + throws IOException + { + OpenPGPCertificate certificate = parseCertificateOrKey(armored); + if (certificate instanceof OpenPGPKey) + { + throw new IOException("Could not parse OpenPGPCertificate: Is OpenPGPKey."); + } + return certificate; + } + + /** + * Parse a single {@link OpenPGPCertificate} from an {@link InputStream}. + * + * @param inputStream ASCII armored or binary input stream + * @return parsed certificate + * @throws IOException if the parsed object is a secret key or if the cert cannot be parsed + */ + public OpenPGPCertificate parseCertificate(InputStream inputStream) + throws IOException + { + OpenPGPCertificate certificate = parseCertificateOrKey(inputStream); + if (certificate instanceof OpenPGPKey) + { + throw new IOException("Could not parse OpenPGPCertificate: Is OpenPGPKey."); + } + return certificate; + } + + /** + * Parse a single {@link OpenPGPCertificate} from bytes. + * + * @param bytes ASCII armored or binary bytes + * @return parsed certificate + * @throws IOException if the parsed object is a secret key or if the cert cannot be parsed + */ + public OpenPGPCertificate parseCertificate(byte[] bytes) + throws IOException + { + OpenPGPCertificate certificate = parseCertificateOrKey(bytes); + if (certificate instanceof OpenPGPKey) + { + throw new IOException("Could not parse OpenPGPCertificate: Is OpenPGPKey."); + } + return certificate; + } + + /** + * Parse a single {@link OpenPGPCertificate} or {@link OpenPGPKey} from an ASCII armored string. + * + * @param armored ASCII armored string + * @return parsed certificate or key + * @throws IOException if the key or certificate cannot be parsed + */ + public OpenPGPCertificate parseCertificateOrKey(String armored) + throws IOException + { + return parseCertificateOrKey(Strings.toUTF8ByteArray(armored)); + } + + /** + * Parse a single {@link OpenPGPCertificate} or {@link OpenPGPKey} from an {@link InputStream}. + * + * @param inputStream input stream containing the ASCII armored or binary key or certificate + * @return parsed certificate or key + * @throws IOException if the key or certificate cannot be parsed + */ + public OpenPGPCertificate parseCertificateOrKey(InputStream inputStream) + throws IOException + { + return parseCertificateOrKey(Streams.readAll(inputStream)); + } + + /** + * Parse a single {@link OpenPGPCertificate} or {@link OpenPGPKey} from bytes. + * + * @param bytes ASCII armored or binary key or certificate + * @return parsed certificate or key + * @throws IOException if the key or certificate cannot be parsed + */ + public OpenPGPCertificate parseCertificateOrKey(byte[] bytes) + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + InputStream decoderStream = PGPUtil.getDecoderStream(bIn); + BCPGInputStream pIn = BCPGInputStream.wrap(decoderStream); + PGPObjectFactory objectFactory = implementation.pgpObjectFactory(pIn); + Object object = objectFactory.nextObject(); + + while (object instanceof PGPMarker) + { + object = objectFactory.nextObject(); + } + if (object instanceof PGPSecretKeyRing) + { + return new OpenPGPKey((PGPSecretKeyRing) object, implementation, policy); + } + else if (object instanceof PGPPublicKeyRing) + { + return new OpenPGPCertificate((PGPPublicKeyRing) object, implementation, policy); + } + else + { + throw new IOException("Neither a certificate, nor secret key."); + } + } + + /** + * Parse an {@link OpenPGPKey} from an ASCII armored string. + * + * @param armored ASCII armored string + * @return parsed key + * @throws IOException if the key cannot be parsed. + */ + public OpenPGPKey parseKey(String armored) + throws IOException + { + return parseKey(Strings.toUTF8ByteArray(armored)); + } + + /** + * Parse an {@link OpenPGPKey} from an {@link InputStream} + * + * @param inputStream containing the ASCII armored or binary key + * @return parsed key + * @throws IOException if the key cannot be parsed. + */ + public OpenPGPKey parseKey(InputStream inputStream) + throws IOException + { + return parseKey(Streams.readAll(inputStream)); + } + + /** + * Parse an {@link OpenPGPKey} from bytes. + * + * @param bytes ASCII armored or binary key + * @return parsed key + * @throws IOException if the key cannot be parsed. + */ + public OpenPGPKey parseKey(byte[] bytes) + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + InputStream decoderStream = PGPUtil.getDecoderStream(bIn); + BCPGInputStream pIn = BCPGInputStream.wrap(decoderStream); + PGPObjectFactory objectFactory = implementation.pgpObjectFactory(pIn); + + Object object = objectFactory.nextObject(); + while (object instanceof PGPMarker) + { + object = objectFactory.nextObject(); + } + if (!(object instanceof PGPSecretKeyRing)) + { + throw new IOException("Not a secret key."); + } + + PGPSecretKeyRing keyRing = (PGPSecretKeyRing) object; + return new OpenPGPKey(keyRing, implementation, policy); + } + + public List parseKeysOrCertificates(String armored) + throws IOException + { + return parseKeysOrCertificates(Strings.toUTF8ByteArray(armored)); + } + + public List parseKeysOrCertificates(InputStream inputStream) + throws IOException + { + return parseKeysOrCertificates(Streams.readAll(inputStream)); + } + + public List parseKeysOrCertificates(byte[] bytes) + throws IOException + { + List certsOrKeys = new ArrayList(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + InputStream decoderStream = PGPUtil.getDecoderStream(bIn); + // Call getDecoderStream() twice, to make sure the stream is a BufferedInputStreamExt. + // This is necessary, so that for streams containing multiple concatenated armored blocks of keys, + // we parse all of them and do not quit after reading the first one. + decoderStream = PGPUtil.getDecoderStream(decoderStream); + PGPObjectFactory objectFactory = implementation.pgpObjectFactory(decoderStream); + Object object; + + while ((object = objectFactory.nextObject()) != null) + { + if (object instanceof PGPMarker) + { + continue; + } + if (object instanceof PGPSecretKeyRing) + { + certsOrKeys.add(new OpenPGPKey((PGPSecretKeyRing) object, implementation, policy)); + } + else if (object instanceof PGPPublicKeyRing) + { + certsOrKeys.add(new OpenPGPCertificate((PGPPublicKeyRing) object, implementation, policy)); + } + else + { + throw new IOException("Neither a certificate, nor secret key."); + } + } + return certsOrKeys; + } + + public List parseCertificates(String armored) + throws IOException + { + return parseCertificates(Strings.toUTF8ByteArray(armored)); + } + + public List parseCertificates(InputStream inputStream) + throws IOException + { + return parseCertificates(Streams.readAll(inputStream)); + } + + public List parseCertificates(byte[] bytes) + throws IOException + { + List certs = new ArrayList(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + InputStream decoderStream = PGPUtil.getDecoderStream(bIn); + // Call getDecoderStream() twice, to make sure the stream is a BufferedInputStreamExt. + // This is necessary, so that for streams containing multiple concatenated armored blocks of certs, + // we parse all of them and do not quit after reading the first one. + decoderStream = PGPUtil.getDecoderStream(decoderStream); + PGPObjectFactory objectFactory = implementation.pgpObjectFactory(decoderStream); + Object object; + + while ((object = objectFactory.nextObject()) != null) + { + if (object instanceof PGPMarker) + { + continue; + } + else if (object instanceof PGPPublicKeyRing) + { + certs.add(new OpenPGPCertificate((PGPPublicKeyRing) object, implementation, policy)); + } + else + { + throw new IOException("Encountered unexpected packet: " + object.getClass().getName()); + } + } + return certs; + } + + public List parseKeys(String armored) + throws IOException + { + return parseKeys(Strings.toUTF8ByteArray(armored)); + } + + public List parseKeys(InputStream inputStream) + throws IOException + { + return parseKeys(Streams.readAll(inputStream)); + } + + public List parseKeys(byte[] bytes) + throws IOException + { + List keys = new ArrayList(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + InputStream decoderStream = PGPUtil.getDecoderStream(bIn); + // Call getDecoderStream() twice, to make sure the stream is a BufferedInputStreamExt. + // This is necessary, so that for streams containing multiple concatenated armored blocks of keys, + // we parse all of them and do not quit after reading the first one. + decoderStream = PGPUtil.getDecoderStream(decoderStream); + PGPObjectFactory objectFactory = implementation.pgpObjectFactory(decoderStream); + Object object; + + while ((object = objectFactory.nextObject()) != null) + { + if (object instanceof PGPMarker) + { + continue; + } + else if (object instanceof PGPSecretKeyRing) + { + keys.add(new OpenPGPKey((PGPSecretKeyRing) object, implementation, policy)); + } + else + { + throw new IOException("Encountered unexpected packet: " + object.getClass().getName()); + } + } + return keys; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageGenerator.java new file mode 100644 index 0000000000..09f751bb05 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageGenerator.java @@ -0,0 +1,669 @@ +package org.bouncycastle.openpgp.api; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.CompressionAlgorithmTags; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.openpgp.PGPCompressedDataGenerator; +import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPLiteralDataGenerator; +import org.bouncycastle.openpgp.PGPOnePassSignature; +import org.bouncycastle.openpgp.PGPPadding; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.api.exception.InvalidEncryptionKeyException; +import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; + +/** + * Generator for OpenPGP messages. + * This class can generate armored/unarmored, encrypted and/or signed OpenPGP message artifacts. + * By default, the generator will merely pack plaintext into an armored + * {@link org.bouncycastle.bcpg.LiteralDataPacket}. + * If however, the user provides one or more recipient certificates/keys + * ({@link #addEncryptionCertificate(OpenPGPCertificate)} / + * {@link #addEncryptionCertificate(OpenPGPCertificate.OpenPGPComponentKey)}) + * or message passphrases {@link #addEncryptionPassphrase(char[])}, the message will be encrypted. + * The encryption mechanism is automatically decided, based on the provided recipient certificates, aiming to maximize + * interoperability. + * If the user provides one or more signing keys by calling {@link #addSigningKey(OpenPGPKey)} or + * {@link #addSigningKey(OpenPGPKey.OpenPGPSecretKey, KeyPassphraseProvider, SignatureParameters.Callback)}, + * the message will be signed. + */ +public class OpenPGPMessageGenerator + extends AbstractOpenPGPDocumentSignatureGenerator +{ + public static final int BUFFER_SIZE = 1024; + + private boolean isArmored = true; + public boolean isAllowPadding = true; + private final List encryptionKeys = new ArrayList(); + private final List messagePassphrases = new ArrayList(); + + // Literal Data metadata + private Date fileModificationDate = null; + private String filename = null; + private char format = PGPLiteralData.BINARY; + private PGPEncryptedDataGenerator.SessionKeyExtractionCallback sessionKeyExtractionCallback; + + public OpenPGPMessageGenerator() + { + this(OpenPGPImplementation.getInstance()); + } + + public OpenPGPMessageGenerator(OpenPGPImplementation implementation) + { + this(implementation, implementation.policy()); + } + + public OpenPGPMessageGenerator(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + super(implementation, policy); + } + + /** + * Add a recipients certificate to the set of encryption keys. + * Subkeys will be selected using the default {@link SubkeySelector}, which can be replaced by calling + * {@link #setEncryptionKeySelector(SubkeySelector)}. + * The recipient will be able to decrypt the message using their corresponding secret key. + * + * @param recipientCertificate recipient certificate (public key) + * @return this + */ + public OpenPGPMessageGenerator addEncryptionCertificate(OpenPGPCertificate recipientCertificate) + throws InvalidEncryptionKeyException + { + return addEncryptionCertificate(recipientCertificate, encryptionKeySelector); + } + + /** + * Add a recipients certificate to the set of encryption keys. + * Subkeys will be selected using the provided {@link SubkeySelector}. + * The recipient will be able to decrypt the message using their corresponding secret key. + * + * @param recipientCertificate recipient certificate (public key) + * @param subkeySelector selector for encryption subkeys + * @return this + * @throws InvalidEncryptionKeyException if the certificate is not capable of encryption + */ + public OpenPGPMessageGenerator addEncryptionCertificate(OpenPGPCertificate recipientCertificate, + SubkeySelector subkeySelector) + throws InvalidEncryptionKeyException + { + List subkeys = + subkeySelector.select(recipientCertificate, policy); + if (subkeys.isEmpty()) + { + throw new InvalidEncryptionKeyException(recipientCertificate); + } + this.encryptionKeys.addAll(subkeys); + return this; + } + + /** + * Add a (sub-)key to the set of recipient encryption keys. + * The recipient will be able to decrypt the message using their corresponding secret key. + * + * @param encryptionKey encryption capable subkey + * @return this + * @throws InvalidEncryptionKeyException if the key is not capable of encryption + */ + public OpenPGPMessageGenerator addEncryptionCertificate(OpenPGPCertificate.OpenPGPComponentKey encryptionKey) + throws InvalidEncryptionKeyException + { + if (!encryptionKey.isEncryptionKey()) + { + throw new InvalidEncryptionKeyException(encryptionKey); + } + encryptionKeys.add(encryptionKey); + return this; + } + + /** + * Add a message passphrase. + * In addition to optional public key encryption, the message will be decryptable using the given passphrase. + * + * @param passphrase passphrase + * @return this + */ + public OpenPGPMessageGenerator addEncryptionPassphrase(char[] passphrase) + { + messagePassphrases.add(passphrase); + return this; + } + + /** + * Specify, whether the output OpenPGP message will be ASCII armored or not. + * + * @param armored boolean + * @return this + */ + public OpenPGPMessageGenerator setArmored(boolean armored) + { + this.isArmored = armored; + return this; + } + + public OpenPGPMessageGenerator setAllowPadding(boolean allowPadding) + { + this.isAllowPadding = allowPadding; + return this; + } + + /** + * Set metadata (filename, modification date, binary format) from a file. + * + * @param file file + * @return this + */ + public OpenPGPMessageGenerator setFileMetadata(File file) + { + this.filename = file.getName(); + this.fileModificationDate = new Date(file.lastModified()); + this.format = PGPLiteralData.BINARY; + return this; + } + + /** + * Set a callback which fires once the session key for message encryption is known. + * This callback can be used to extract the session key, e.g. to emit it to the user (in case of SOP). + * + * @param callback callback + * @return this + */ + public OpenPGPMessageGenerator setSessionKeyExtractionCallback( + PGPEncryptedDataGenerator.SessionKeyExtractionCallback callback) + { + this.sessionKeyExtractionCallback = callback; + return this; + } + + /** + * Open an {@link OpenPGPMessageOutputStream} over the given output stream. + * + * @param out output stream + * @return OpenPGP message output stream + * @throws PGPException if the output stream cannot be created + */ + public OpenPGPMessageOutputStream open(OutputStream out) + throws PGPException, IOException + { + OpenPGPMessageOutputStream.Builder streamBuilder = OpenPGPMessageOutputStream.builder(); + + applyOptionalAsciiArmor(streamBuilder); + applyOptionalEncryption(streamBuilder, sessionKeyExtractionCallback); + applySignatures(streamBuilder); + applyOptionalCompression(streamBuilder); + applyLiteralDataWrap(streamBuilder); + + return streamBuilder.build(out); + } + + /** + * Apply ASCII armor if necessary. + * The output will only be wrapped in ASCII armor, if {@link #setArmored(boolean)} is set + * to true (is true by default). + * The {@link ArmoredOutputStream} will be instantiated using the {@link ArmoredOutputStreamFactory} + * which can be replaced using {@link #setArmorStreamFactory(ArmoredOutputStreamFactory)}. + * + * @param builder OpenPGP message output stream builder + */ + private void applyOptionalAsciiArmor(OpenPGPMessageOutputStream.Builder builder) + { + if (isArmored) + { + builder.armor(armorStreamFactory); + } + } + + /** + * Optionally apply message encryption. + * If no recipient certificates and no encryption passphrases were supplied, no encryption + * will be applied. + * Otherwise, encryption mode and algorithms will be negotiated and message encryption will be applied. + * + * @param builder OpenPGP message output stream builder + * @param sessionKeyExtractionCallback callback to extract the session key (nullable) + */ + private void applyOptionalEncryption( + OpenPGPMessageOutputStream.Builder builder, + PGPEncryptedDataGenerator.SessionKeyExtractionCallback sessionKeyExtractionCallback) + { + MessageEncryptionMechanism encryption = encryptionNegotiator.negotiateEncryption(this); + if (!encryption.isEncrypted()) + { + return; // No encryption + } + + PGPDataEncryptorBuilder encBuilder = implementation.pgpDataEncryptorBuilder( + encryption.getSymmetricKeyAlgorithm()); + + // Specify container type for the plaintext + switch (encryption.getMode()) + { + case SEIPDv1: + encBuilder.setWithIntegrityPacket(true); + break; + + case SEIPDv2: + encBuilder.setWithAEAD(encryption.getAeadAlgorithm(), 6); + encBuilder.setUseV6AEAD(); + break; + + case LIBREPGP_OED: + encBuilder.setWithAEAD(encryption.getAeadAlgorithm(), 6); + encBuilder.setUseV5AEAD(); + break; + } + + final PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + // For sake of interoperability and simplicity, we always use a dedicated session key for message encryption + // even if only a single PBE encryption method was added and S2K result could be used as session-key directly. + encGen.setForceSessionKey(true); + encGen.setSessionKeyExtractionCallback(sessionKeyExtractionCallback); + + // Setup asymmetric message encryption + for (OpenPGPCertificate.OpenPGPComponentKey encryptionSubkey : encryptionKeys) + { + PublicKeyKeyEncryptionMethodGenerator method = implementation.publicKeyKeyEncryptionMethodGenerator( + encryptionSubkey.getPGPPublicKey()); + encGen.addMethod(method); + } + + // Setup symmetric (password-based) message encryption + for (char[] passphrase : messagePassphrases) + { + PBEKeyEncryptionMethodGenerator skeskGen; + switch (encryption.getMode()) + { + case SEIPDv1: + case LIBREPGP_OED: + // "v4" and LibrePGP use symmetric-key encrypted session key packets version 4 (SKESKv4) + skeskGen = implementation.pbeKeyEncryptionMethodGenerator(passphrase); + break; + + case SEIPDv2: + // v6 uses symmetric-key encrypted session key packets version 6 (SKESKv6) using AEAD + skeskGen = implementation.pbeKeyEncryptionMethodGenerator( + passphrase, S2K.Argon2Params.memoryConstrainedParameters()); + break; + default: + continue; + } + + skeskGen.setSecureRandom(CryptoServicesRegistrar.getSecureRandom()); // Prevent NPE + encGen.addMethod(skeskGen); + } + + // Finally apply encryption + builder.encrypt(new OpenPGPMessageOutputStream.OutputStreamFactory() + { + @Override + public OutputStream get(OutputStream o) + throws PGPException, IOException + { + try + { + return encGen.open(o, new byte[BUFFER_SIZE]); + } + catch (IOException e) + { + throw new PGPException("Could not open encryptor OutputStream", e); + } + } + }); + + // Optionally, append a padding packet as the last packet inside the SEIPDv2 packet. + if (encryption.getMode() == EncryptedDataPacketType.SEIPDv2 && isAllowPadding) + { + builder.padding(new OpenPGPMessageOutputStream.OutputStreamFactory() + { + @Override + public OutputStream get(OutputStream o) + { + return new OpenPGPMessageOutputStream.PaddingPacketAppenderOutputStream(o, new OpenPGPMessageOutputStream.PaddingPacketFactory() + { + @Override + public PGPPadding providePaddingPacket() + { + return new PGPPadding(); + } + }); + } + }); + } + } + + /** + * Apply OpenPGP inline-signatures. + * + * @param builder OpenPGP message output stream builder + */ + private void applySignatures(OpenPGPMessageOutputStream.Builder builder) + { + builder.sign(new OpenPGPMessageOutputStream.OutputStreamFactory() + { + @Override + public OutputStream get(OutputStream o) + throws PGPException, IOException + { + addSignToGenerator(); + + // One-Pass-Signatures + Iterator sigGens = signatureGenerators.iterator(); + while (sigGens.hasNext()) + { + PGPSignatureGenerator gen = sigGens.next(); + PGPOnePassSignature ops = gen.generateOnePassVersion(sigGens.hasNext()); + ops.encode(o); + } + + return new OpenPGPMessageOutputStream.SignatureGeneratorOutputStream(o, signatureGenerators); + } + }); + } + + private void applyOptionalCompression(OpenPGPMessageOutputStream.Builder builder) + { + int compressionAlgorithm = compressionNegotiator.negotiateCompression(this, policy); + if (compressionAlgorithm == CompressionAlgorithmTags.UNCOMPRESSED) + { + return; // Uncompressed + } + + final PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(compressionAlgorithm); + + builder.compress(new OpenPGPMessageOutputStream.OutputStreamFactory() + { + @Override + public OutputStream get(OutputStream o) + throws PGPException, IOException + { + try + { + return compGen.open(o, new byte[BUFFER_SIZE]); + } + catch (IOException e) + { + throw new PGPException("Could not apply compression", e); + } + } + }); + } + + /** + * Setup wrapping of the message plaintext in a literal data packet. + * + * @param builder OpenPGP message output stream + */ + private void applyLiteralDataWrap(OpenPGPMessageOutputStream.Builder builder) + { + final PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + builder.literalData(new OpenPGPMessageOutputStream.OutputStreamFactory() + { + @Override + public OutputStream get(final OutputStream o) + throws PGPException, IOException + { + try + { + return litGen.open(o, + format, + filename != null ? filename : "", + fileModificationDate != null ? fileModificationDate : PGPLiteralData.NOW, + new byte[BUFFER_SIZE]); + } + catch (IOException e) + { + throw new PGPException("Could not apply literal data wrapping", e); + } + } + }); + } + + // Factory for creating ASCII armor + private ArmoredOutputStreamFactory armorStreamFactory = + new ArmoredOutputStreamFactory() + { + @Override + public ArmoredOutputStream get(OutputStream outputStream) + { + return ArmoredOutputStream.builder() + .clearHeaders() // Hide version + .enableCRC(false) // Disable CRC sum + .build(outputStream); + } + }; + + private SubkeySelector encryptionKeySelector = new SubkeySelector() + { + @Override + public List select(OpenPGPCertificate certificate, + OpenPGPPolicy policy) + { + List result = new ArrayList(); + for (Iterator it = certificate.getEncryptionKeys().iterator(); it.hasNext(); ) + { + OpenPGPCertificate.OpenPGPComponentKey key = it.next(); + if (policy.isAcceptablePublicKey(key.getPGPPublicKey())) + { + result.add(key); + } + } + return result; + } + }; + + // Encryption method negotiator for when only password-based encryption is requested + private OpenPGPEncryptionNegotiator passwordBasedEncryptionNegotiator = new OpenPGPEncryptionNegotiator() + { + @Override + public MessageEncryptionMechanism negotiateEncryption(OpenPGPMessageGenerator configuration) + { + return MessageEncryptionMechanism.aead(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB); + } + }; + + // Encryption method negotiator for when public-key encryption is requested + private OpenPGPEncryptionNegotiator publicKeyBasedEncryptionNegotiator = new OpenPGPEncryptionNegotiator() + { + @Override + public MessageEncryptionMechanism negotiateEncryption(OpenPGPMessageGenerator configuration) + { +// List certificates = encryptionKeys.stream() +// .map(OpenPGPCertificate.OpenPGPCertificateComponent::getCertificate) +// .distinct() +// .collect(Collectors.toList()); + + List certificates = new ArrayList(); + Set uniqueCertificates = new HashSet(); // For distinctness + + for (Iterator it = encryptionKeys.iterator(); it.hasNext(); ) + { + OpenPGPCertificate cert = it.next().getCertificate(); + if (uniqueCertificates.add(cert)) + { // `Set.add()` returns true if the element was new + certificates.add(cert); + } + } + + // Decide, if SEIPDv2 (OpenPGP v6-style AEAD) is supported by all recipients. + if (OpenPGPEncryptionNegotiator.allRecipientsSupportSeipd2(certificates)) + { + PreferredAEADCiphersuites commonDenominator = + OpenPGPEncryptionNegotiator.negotiateAEADCiphersuite(certificates, policy); + return MessageEncryptionMechanism.aead(commonDenominator.getAlgorithms()[0]); + } + else if (OpenPGPEncryptionNegotiator.allRecipientsSupportLibrePGPOED(certificates)) + { + return MessageEncryptionMechanism.librePgp( + OpenPGPEncryptionNegotiator.bestOEDEncryptionModeByWeight(certificates, policy)); + } + else + { + return MessageEncryptionMechanism.integrityProtected( + OpenPGPEncryptionNegotiator.bestSymmetricKeyAlgorithmByWeight( + certificates, policy)); + } + + } + }; + + // Primary encryption method negotiator + private final OpenPGPEncryptionNegotiator encryptionNegotiator = new OpenPGPEncryptionNegotiator() + { + @Override + public MessageEncryptionMechanism negotiateEncryption(OpenPGPMessageGenerator configuration) + { + // No encryption methods provided -> Unencrypted message + if (encryptionKeys.isEmpty() && messagePassphrases.isEmpty()) + { + return MessageEncryptionMechanism.unencrypted(); + } + + // No public-key encryption requested -> password-based encryption + else if (encryptionKeys.isEmpty()) + { + // delegate negotiation to pbe negotiator + return passwordBasedEncryptionNegotiator.negotiateEncryption(configuration); + } + else + { + // delegate negotiation to pkbe negotiator + return publicKeyBasedEncryptionNegotiator.negotiateEncryption(configuration); + } + } + }; + + + // TODO: Implement properly, taking encryption into account (sign-only should not compress) + private CompressionNegotiator compressionNegotiator = new CompressionNegotiator() + { + @Override + public int negotiateCompression(OpenPGPMessageGenerator configuration, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.UNCOMPRESSED; + } + }; + + /** + * Replace the default {@link OpenPGPEncryptionNegotiator} that gets to decide, which + * {@link MessageEncryptionMechanism} mode to use if only password-based encryption is used. + * + * @param pbeNegotiator custom PBE negotiator. + * @return this + */ + public OpenPGPMessageGenerator setPasswordBasedEncryptionNegotiator(OpenPGPEncryptionNegotiator pbeNegotiator) + { + if (pbeNegotiator == null) + { + throw new NullPointerException(); + } + this.passwordBasedEncryptionNegotiator = pbeNegotiator; + return this; + } + + /** + * Replace the default {@link OpenPGPEncryptionNegotiator} that decides, which + * {@link MessageEncryptionMechanism} mode to use if public-key encryption is used. + * + * @param pkbeNegotiator custom encryption negotiator that gets to decide if PK-based encryption is used + * @return this + */ + public OpenPGPMessageGenerator setPublicKeyBasedEncryptionNegotiator(OpenPGPEncryptionNegotiator pkbeNegotiator) + { + if (pkbeNegotiator == null) + { + throw new NullPointerException(); + } + this.publicKeyBasedEncryptionNegotiator = pkbeNegotiator; + return this; + } + + /** + * Replace the default encryption key selector with a custom implementation. + * The encryption key selector is responsible for selecting one or more encryption subkeys from a + * recipient certificate. + * + * @param encryptionKeySelector selector for encryption (sub-)keys + * @return this + */ + public OpenPGPMessageGenerator setEncryptionKeySelector(SubkeySelector encryptionKeySelector) + { + if (encryptionKeySelector == null) + { + throw new NullPointerException(); + } + this.encryptionKeySelector = encryptionKeySelector; + return this; + } + + + /** + * Replace the default {@link CompressionNegotiator} with a custom implementation. + * The {@link CompressionNegotiator} is used to negotiate, whether and how to compress the literal data packet. + * + * @param compressionNegotiator negotiator + * @return this + */ + public OpenPGPMessageGenerator setCompressionNegotiator(CompressionNegotiator compressionNegotiator) + { + if (compressionNegotiator == null) + { + throw new NullPointerException(); + } + this.compressionNegotiator = compressionNegotiator; + return this; + } + + /** + * Replace the {@link ArmoredOutputStreamFactory} with a custom implementation. + * + * @param factory factory for {@link ArmoredOutputStream} instances + * @return this + */ + public OpenPGPMessageGenerator setArmorStreamFactory(ArmoredOutputStreamFactory factory) + { + if (factory == null) + { + throw new NullPointerException(); + } + this.armorStreamFactory = factory; + return this; + } + + + public interface ArmoredOutputStreamFactory + extends OpenPGPMessageOutputStream.OutputStreamFactory + { + ArmoredOutputStream get(OutputStream out); + } + + public interface CompressionNegotiator + { + /** + * Negotiate a compression algorithm. + * Returning {@link org.bouncycastle.bcpg.CompressionAlgorithmTags#UNCOMPRESSED} will result in no compression. + * + * @param messageGenerator message generator + * @return negotiated compression algorithm ID + */ + int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy); + } + +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageInputStream.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageInputStream.java new file mode 100644 index 0000000000..6601c07e35 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageInputStream.java @@ -0,0 +1,1157 @@ +package org.bouncycastle.openpgp.api; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.bouncycastle.bcpg.AEADEncDataPacket; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket; +import org.bouncycastle.openpgp.PGPCompressedData; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPMarker; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPOnePassSignature; +import org.bouncycastle.openpgp.PGPOnePassSignatureList; +import org.bouncycastle.openpgp.PGPPadding; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureException; +import org.bouncycastle.openpgp.PGPSignatureList; + +/** + * An {@link InputStream} that processes an OpenPGP message. + * Its contents are the plaintext from the messages LiteralData packet. + * You can get information about the message (signatures, encryption method, message metadata) + * by reading ALL data from the stream, closing it with {@link #close()} and then retrieving a {@link Result} object + * by calling {@link #getResult()}. + */ +public class OpenPGPMessageInputStream + extends InputStream +{ + public static int MAX_RECURSION = 16; + + private final PGPObjectFactory objectFactory; + private final OpenPGPImplementation implementation; + + private final OpenPGPMessageProcessor processor; + + private final Result.Builder resultBuilder; + private final Layer layer; // the packet layer processed by this input stream + + private InputStream in; + private final List packetHandlers = new ArrayList() + {{ + add(new SignatureListHandler()); + add(new OnePassSignatureHandler()); + add(new MarkerHandler()); + add(new LiteralDataHandler()); + add(new CompressedDataHandler()); + add(new EncryptedDataHandler()); + add(new DefaultPacketHandler()); // Must be last + }}; + + private final List closeHandlers = new ArrayList() + {{ + add(new SignatureListHandler()); + add(new PaddingHandler()); + add(new MarkerHandler()); + add(new DefaultPacketHandler()); + }}; + + OpenPGPMessageInputStream(PGPObjectFactory objectFactory, + OpenPGPMessageProcessor processor) + { + this(objectFactory, processor, Result.builder()); + } + + private OpenPGPMessageInputStream(PGPObjectFactory objectFactory, + OpenPGPMessageProcessor processor, + Result.Builder resultBuilder) + { + this.objectFactory = objectFactory; + this.processor = processor; + this.implementation = processor.getImplementation(); + this.resultBuilder = resultBuilder; + try + { + this.layer = resultBuilder.openLayer(); + } + catch (PGPException e) + { + // cannot happen + throw new AssertionError(e); + } + } + + void process() + throws IOException, PGPException + { + Object next; + while ((next = objectFactory.nextObject()) != null) + { + for (PacketHandler handler : packetHandlers) + { + if (handler.canHandle(next)) + { + handler.handle(next); + break; + } + } + + if (in != null) + { + return; // Found data stream, stop processing + } + } + } + + @Override + public void close() + throws IOException + { + in.close(); + Object next; + + while ((next = objectFactory.nextObject()) != null) + { + boolean handled = false; + for (Iterator it = closeHandlers.iterator(); it.hasNext();) + { + PacketHandler handler = (PacketHandler)it.next(); + if (handler.canHandle(next)) + { + handler.close(next); + handled = true; + break; + } + } + + if (!handled) + { + processor.onException(new PGPException("Unexpected trailing packet encountered: " + + next.getClass().getName())); + } + } + + resultBuilder.verifySignatures(processor); + resultBuilder.closeLayer(); + } + + @Override + public int read() + throws IOException + { + int i = in.read(); + if (i >= 0) + { + layer.onePassSignatures.update(i); + layer.prefixedSignatures.update(i); +// byte b = (byte)i; +// layer.onePassVerifier.update(b); +// layer.prefixedVerifier.update(b); + } + return i; + } + + @Override + public int read(byte[] b) + throws IOException + { + int i = in.read(b); + if (i >= 0) + { + layer.onePassSignatures.update(b, 0, i); + layer.prefixedSignatures.update(b, 0, i); +// layer.onePassVerifier.update(b, 0, i); +// layer.prefixedVerifier.update(b, 0, i); + } + return i; + } + + @Override + public int read(byte[] b, int off, int len) + throws IOException + { + int bytesRead = in.read(b, off, len); + if (bytesRead > 0) + { + layer.onePassSignatures.update(b, off, bytesRead); + layer.prefixedSignatures.update(b, off, bytesRead); +// layer.onePassVerifier.update(b, off, bytesRead); +// layer.prefixedVerifier.update(b, off, bytesRead); + } + return bytesRead; + } + + public Result getResult() + { + return resultBuilder.build(); + } + + public static class Result + { + private final List documentSignatures = new ArrayList(); + private OpenPGPCertificate.OpenPGPComponentKey decryptionKey; + private char[] decryptionPassphrase; + private PGPSessionKey sessionKey; + private MessageEncryptionMechanism encryptionMethod = MessageEncryptionMechanism.unencrypted(); + private int compressionAlgorithm = 0; + private String filename; + private char fileFormat; + private Date fileModificationTime; + + private Result(List layers) + { + for (Iterator it = layers.iterator(); it.hasNext(); ) + { + Layer l = it.next(); + if (l.signatures != null) + { + documentSignatures.addAll(l.signatures); + } + + if (l.nested instanceof EncryptedData) + { + EncryptedData encryptedData = (EncryptedData)l.nested; + encryptionMethod = encryptedData.encryption; + sessionKey = encryptedData.sessionKey; + decryptionKey = encryptedData.decryptionKey; + decryptionPassphrase = encryptedData.decryptionPassphrase; + } + else if (l.nested instanceof CompressedData) + { + CompressedData compressedData = (CompressedData)l.nested; + compressionAlgorithm = compressedData.compressionAlgorithm; + } + else if (l.nested instanceof LiteralData) + { + LiteralData literalData = (LiteralData)l.nested; + filename = literalData.filename; + fileFormat = literalData.encoding; + fileModificationTime = literalData.modificationTime; + } + } + } + + static Builder builder() + { + return new Builder(); + } + + public MessageEncryptionMechanism getEncryptionMethod() + { + return encryptionMethod; + } + + public OpenPGPCertificate.OpenPGPComponentKey getDecryptionKey() + { + return decryptionKey; + } + + public char[] getDecryptionPassphrase() + { + return decryptionPassphrase; + } + + public PGPSessionKey getSessionKey() + { + return sessionKey; + } + + public int getCompressionAlgorithm() + { + return compressionAlgorithm; + } + + public String getFilename() + { + return filename; + } + + public char getFileFormat() + { + return fileFormat; + } + + public Date getFileModificationTime() + { + return fileModificationTime; + } + + public List getSignatures() + { + return new ArrayList(documentSignatures); + } + + static class Builder + { + private final List layers = new ArrayList(); + + private Builder() + { + + } + + Layer last() + { + return layers.get(layers.size() - 1); + } + + /** + * Enter a nested OpenPGP packet layer. + * + * @return the new layer + * @throws PGPException if the parser exceeded the maximum nesting depth ({@link #MAX_RECURSION}). + */ + Layer openLayer() + throws PGPException + { + if (layers.size() >= MAX_RECURSION) + { + throw new PGPException("Exceeded maximum packet nesting depth."); + } + Layer layer = new Layer(); + layers.add(layer); + return layer; + } + + /** + * Close a nested OpenPGP packet layer. + */ + void closeLayer() + { + for (int i = layers.size() - 1; i >= 0; i--) + { + Layer l = layers.get(i); + if (l.isOpen()) + { + l.close(); + return; + } + } + } + + /** + * Set the nested packet type of the current layer to {@link CompressedData}. + * + * @param compressionAlgorithm compression algorithm ID + */ + void compressed(int compressionAlgorithm) + { + last().setNested(new CompressedData(compressionAlgorithm)); + } + + /** + * Add One-Pass-Signature packets on the current layer. + * + * @param pgpOnePassSignatures one pass signature packets + */ + void onePassSignatures(PGPOnePassSignatureList pgpOnePassSignatures) + { +// last().onePassVerifier.addSignatures(pgpOnePassSignatures.iterator()); + last().onePassSignatures.addOnePassSignatures(pgpOnePassSignatures); + } + + /** + * Build the {@link Result}. + * + * @return result + */ + Result build() + { + return new Result(layers); + } + + /** + * Add prefixed signatures on the current layer. + * + * @param prefixedSigs prefixed signatures + */ + void prefixedSignatures(PGPSignatureList prefixedSigs) + { + last().prefixedSignatures.addAll(prefixedSigs); + //last().prefixedVerifier.addSignatures(prefixedSigs.iterator()); + } + + /** + * Initialize any signatures on the current layer, prefixed and one-pass-signatures. + * + * @param processor message processor + */ + void initSignatures(OpenPGPMessageProcessor processor) + { + last().onePassSignatures.init(processor); + last().prefixedSignatures.init(processor); +// last().onePassVerifier.commonInit(processor); +// last().prefixedVerifier.commonInit(processor); + } + + /** + * Verify all signatures on the current layer, prefixed and one-pass-signatures. + * + * @param processor message processor + */ + void verifySignatures(OpenPGPMessageProcessor processor) + { + Layer last = last(); + if (last.signatures != null) + { + return; + } + + last.signatures = new ArrayList(); + last.signatures.addAll(last.onePassSignatures.verify(processor)); + last.signatures.addAll(last.prefixedSignatures.verify(processor)); +// last.signatures.addAll(last.onePassVerifier.verify(processor)); +// last.signatures.addAll(last.prefixedVerifier.verify(processor)); + } + + /** + * Set literal data metadata on the current layer. + * + * @param fileName filename + * @param format data format + * @param modificationTime modification time + */ + void literalData(String fileName, char format, Date modificationTime) + { + last().setNested(new LiteralData(fileName, format, modificationTime)); + } + + /** + * Set metadata from an encrypted data packet on the current layer. + * + * @param decrypted decryption result + */ + void encrypted(OpenPGPMessageProcessor.Decrypted decrypted) + { + last().setNested(new EncryptedData(decrypted)); + } + } + } + + static class Layer + { + private final OnePassSignatures onePassSignatures = new OnePassSignatures(); + private final PrefixedSignatures prefixedSignatures = new PrefixedSignatures(); +// private final OnePassSignatureVerifier onePassVerifier = new OnePassSignatureVerifier(); +// private final PrefixedSignatureVerifier prefixedVerifier = new PrefixedSignatureVerifier(); + private List signatures = null; + + private Nested nested; + private boolean open = true; + + void setNested(Nested nested) + { + this.nested = nested; + } + + void close() + { + this.open = false; + } + + boolean isOpen() + { + return open; + } + } + + static class Nested + { + } + + static class CompressedData + extends Nested + { + private final int compressionAlgorithm; + + public CompressedData(int algorithm) + { + this.compressionAlgorithm = algorithm; + } + } + + static class LiteralData + extends Nested + { + private final String filename; + private final char encoding; + private final Date modificationTime; + + LiteralData(String filename, char encoding, Date modificationTime) + { + this.filename = filename; + this.encoding = encoding; + this.modificationTime = modificationTime; + } + } + + static class EncryptedData + extends Nested + { + private final OpenPGPCertificate.OpenPGPComponentKey decryptionKey; + private final char[] decryptionPassphrase; + private final PGPSessionKey sessionKey; + private final MessageEncryptionMechanism encryption; + + EncryptedData(OpenPGPMessageProcessor.Decrypted decrypted) + { + this.decryptionKey = decrypted.decryptionKey; + this.decryptionPassphrase = decrypted.decryptionPassphrase; + this.sessionKey = decrypted.sessionKey; + if (decrypted.esk.getEncData() instanceof SymmetricEncIntegrityPacket) + { + SymmetricEncIntegrityPacket seipd = (SymmetricEncIntegrityPacket)decrypted.esk.getEncData(); + if (seipd.getVersion() == SymmetricEncIntegrityPacket.VERSION_2) + { + encryption = MessageEncryptionMechanism.aead( + seipd.getCipherAlgorithm(), seipd.getAeadAlgorithm()); + } + else + { + encryption = MessageEncryptionMechanism.integrityProtected(sessionKey.getAlgorithm()); + } + } + else if (decrypted.esk.getEncData() instanceof AEADEncDataPacket) + { + encryption = MessageEncryptionMechanism.librePgp(sessionKey.getAlgorithm()); + } + else + { + throw new RuntimeException("Unexpected encrypted data packet type: " + decrypted.esk.getClass().getName()); + } + } + } + + private static class PacketHandler + { + public boolean canHandle(Object packet) + { + return false; + } + + public void handle(Object packet) + throws IOException, PGPException + { + + } + + public void close(Object packet) + throws IOException + { + + } + } + + private class SignatureListHandler + extends PacketHandler + { + public boolean canHandle(Object packet) + { + return packet instanceof PGPSignatureList; + } + + public void handle(Object packet) + { + PGPSignatureList prefixedSigs = (PGPSignatureList)packet; + resultBuilder.prefixedSignatures(prefixedSigs); + } + + public void close(Object packet) + { + PGPSignatureList sigList = (PGPSignatureList)packet; + resultBuilder.last().onePassSignatures.addSignatures(sigList); + //resultBuilder.last().onePassVerifier.addPGPSinatures(sigList.iterator()); + } + } + + private class LiteralDataHandler + extends PacketHandler + { + @Override + public boolean canHandle(Object packet) + { + return packet instanceof PGPLiteralData; + } + + @Override + public void handle(Object packet) + throws IOException, PGPException + { + PGPLiteralData literalData = (PGPLiteralData)packet; + resultBuilder.literalData( + literalData.getFileName(), + (char)literalData.getFormat(), + literalData.getModificationTime() + ); + in = literalData.getDataStream(); + resultBuilder.initSignatures(processor); + } + } + + private class OnePassSignatureHandler + extends PacketHandler + { + @Override + public boolean canHandle(Object packet) + { + return packet instanceof PGPOnePassSignatureList; + } + + @Override + public void handle(Object packet) + throws IOException, PGPException + { + PGPOnePassSignatureList pgpOnePassSignatures = (PGPOnePassSignatureList)packet; + resultBuilder.onePassSignatures(pgpOnePassSignatures); + } + } + + private static class MarkerHandler + extends PacketHandler + { + @Override + public boolean canHandle(Object packet) + { + return packet instanceof PGPMarker; + } + } + + private class CompressedDataHandler + extends PacketHandler + { + @Override + public boolean canHandle(Object packet) + { + return packet instanceof PGPCompressedData; + } + + @Override + public void handle(Object packet) + throws IOException, PGPException + { + PGPCompressedData compressedData = (PGPCompressedData)packet; + resultBuilder.compressed(compressedData.getAlgorithm()); + + InputStream decompressed = compressedData.getDataStream(); + processNestedStream(decompressed); + } + + private void processNestedStream(InputStream input) + throws IOException, PGPException + { + InputStream decodeIn = BCPGInputStream.wrap(input); + PGPObjectFactory decFac = implementation.pgpObjectFactory(decodeIn); + OpenPGPMessageInputStream nestedIn = + new OpenPGPMessageInputStream(decFac, processor, resultBuilder); + in = nestedIn; + nestedIn.process(); + } + } + + private class EncryptedDataHandler + extends PacketHandler + { + @Override + public boolean canHandle(Object packet) + { + return packet instanceof PGPEncryptedDataList; + } + + @Override + public void handle(Object packet) + throws IOException, PGPException + { + PGPEncryptedDataList encryptedDataList = (PGPEncryptedDataList)packet; + OpenPGPMessageProcessor.Decrypted decrypted = processor.decrypt(encryptedDataList); + + resultBuilder.encrypted(decrypted); + processNestedStream(decrypted.inputStream); + } + + private void processNestedStream(InputStream input) + throws IOException, PGPException + { + InputStream decodeIn = BCPGInputStream.wrap(input); + PGPObjectFactory decFac = implementation.pgpObjectFactory(decodeIn); + OpenPGPMessageInputStream nestedIn = + new OpenPGPMessageInputStream(decFac, processor, resultBuilder); + in = nestedIn; + nestedIn.process(); + } + } + + private static class PaddingHandler + extends PacketHandler + { + public boolean canHandle(Object packet) + { + return packet instanceof PGPPadding; + } + } + + private class DefaultPacketHandler + extends PacketHandler + { + @Override + public boolean canHandle(Object packet) + { + return true; // Catch-all handler + } + + @Override + public void handle(Object packet) + throws PGPException + { + processor.onException(new PGPException("Unexpected packet: " + packet.getClass().getName())); + } + } + + static class OnePassSignatures + { + private final List onePassSignatures = new ArrayList(); + private final List signatures = new ArrayList(); + private final Map issuers = new HashMap(); + + OnePassSignatures() + { + + } + + void addOnePassSignatures(PGPOnePassSignatureList onePassSignatures) + { + for (Iterator it = onePassSignatures.iterator(); it.hasNext();) + { + PGPOnePassSignature ops = (PGPOnePassSignature)it.next(); + this.onePassSignatures.add(ops); + } + } + + void addSignatures(PGPSignatureList signatures) + { + for (Iterator it = signatures.iterator(); it.hasNext();) + { + PGPSignature signature = (PGPSignature)it.next(); + this.signatures.add(signature); + } + } + + void init(OpenPGPMessageProcessor processor) + { + + for (Iterator it = onePassSignatures.iterator(); it.hasNext();) + { + PGPOnePassSignature ops = (PGPOnePassSignature)it.next(); + KeyIdentifier identifier = ops.getKeyIdentifier(); + OpenPGPCertificate cert = processor.provideCertificate(identifier); + if (cert == null) + { + continue; + } + + try + { + OpenPGPCertificate.OpenPGPComponentKey key = cert.getKey(identifier); + issuers.put(ops, key); + ops.init(processor.getImplementation().pgpContentVerifierBuilderProvider(), + key.getPGPPublicKey()); + } + catch (PGPException e) + { + processor.onException(e); + } + } + } + + void update(int i) + { + for (Iterator it = onePassSignatures.iterator(); it.hasNext();) + { + PGPOnePassSignature onePassSignature = (PGPOnePassSignature)it.next(); + if (issuers.containsKey(onePassSignature)) + { + onePassSignature.update((byte) i); + } + } + } + + void update(byte[] b, int off, int len) + { + for (Iterator it = onePassSignatures.iterator(); it.hasNext();) + { + PGPOnePassSignature onePassSignature = (PGPOnePassSignature)it.next(); + if (issuers.containsKey(onePassSignature)) + { + onePassSignature.update(b, off, len); + } + } + } + + List verify( + OpenPGPMessageProcessor processor) + { + OpenPGPPolicy policy = processor.getImplementation().policy(); + List dataSignatures = new ArrayList(); + int num = onePassSignatures.size(); + for (int i = 0; i < signatures.size(); i++) + { + PGPSignature signature = signatures.get(i); + PGPOnePassSignature ops = onePassSignatures.get(num - i - 1); + OpenPGPCertificate.OpenPGPComponentKey key = issuers.get(ops); + if (key == null) + { + continue; + } + + OpenPGPSignature.OpenPGPDocumentSignature dataSignature = + new OpenPGPSignature.OpenPGPDocumentSignature(signature, key); + try + { + dataSignature.sanitize(key, policy); + } + catch (PGPSignatureException e) + { + // continue + } + + if (!dataSignature.createdInBounds(processor.getVerifyNotBefore(), processor.getVerifyNotAfter())) + { + // sig is not in bounds + continue; + } + + try + { + dataSignature.verify(ops); + } + catch (PGPException e) + { + processor.onException(e); + } + dataSignatures.add(dataSignature); + } + return dataSignatures; + } + } + + static class PrefixedSignatures + { + private final List prefixedSignatures = new ArrayList(); + private final List dataSignatures = new ArrayList(); + + PrefixedSignatures() + { + + } + + void addAll(PGPSignatureList signatures) + { + for (Iterator it = signatures.iterator(); it.hasNext();) + { + PGPSignature signature = (PGPSignature)it.next(); + this.prefixedSignatures.add(signature); + } + } + + void init(OpenPGPMessageProcessor processor) + { + for (Iterator it = prefixedSignatures.iterator(); it.hasNext();) + { + PGPSignature sig = (PGPSignature)it.next(); + KeyIdentifier identifier = OpenPGPSignature.getMostExpressiveIdentifier(sig.getKeyIdentifiers()); + if (identifier == null) + { + dataSignatures.add(new OpenPGPSignature.OpenPGPDocumentSignature(sig, null)); + continue; + } + OpenPGPCertificate cert = processor.provideCertificate(identifier); + if (cert == null) + { + dataSignatures.add(new OpenPGPSignature.OpenPGPDocumentSignature(sig, null)); + continue; + } + + OpenPGPCertificate.OpenPGPComponentKey key = cert.getKey(identifier); + OpenPGPSignature.OpenPGPDocumentSignature signature = new OpenPGPSignature.OpenPGPDocumentSignature(sig, key); + dataSignatures.add(signature); + try + { + signature.signature.init( + processor.getImplementation().pgpContentVerifierBuilderProvider(), + cert.getKey(identifier).getPGPPublicKey()); + } + catch (PGPException e) + { + processor.onException(e); + } + } + } + + void update(int i) + { + for (Iterator it = prefixedSignatures.iterator(); it.hasNext();) + { + PGPSignature signature = (PGPSignature)it.next(); + signature.update((byte) i); + } + } + + void update(byte[] buf, int off, int len) + { + for (Iterator it = prefixedSignatures.iterator(); it.hasNext();) + { + PGPSignature signature = (PGPSignature)it.next(); + signature.update(buf, off, len); + } + } + + List verify(OpenPGPMessageProcessor processor) + { + List verifiedSignatures = new ArrayList(); + OpenPGPPolicy policy = processor.getImplementation().policy(); + for (Iterator it = dataSignatures.iterator(); it.hasNext();) + { + OpenPGPSignature.OpenPGPDocumentSignature sig = (OpenPGPSignature.OpenPGPDocumentSignature)it.next(); + try + { + sig.sanitize(sig.issuer, policy); + } + catch (PGPSignatureException e) + { + processor.onException(e); + continue; + } + + try + { + sig.verify(); + } + catch (PGPException e) + { + processor.onException(e); + } + verifiedSignatures.add(sig); + } + return verifiedSignatures; + } + } + +// private static abstract class BaseSignatureVerifier +// { +// protected final List signatures = new ArrayList<>(); +// protected final Map issuers = new HashMap<>(); +// +// public void addSignatures(Iterator it) +// { +// while (it.hasNext()) +// { +// this.signatures.add(it.next()); +// } +// } +// +// protected void commonInit(OpenPGPMessageProcessor processor) +// throws PGPException +// { +// for (R sig : signatures) +// { +// KeyIdentifier identifier = getKeyIdentifier(sig); +// OpenPGPCertificate cert = processor.provideCertificate(identifier); +// +// if (cert != null) +// { +// OpenPGPCertificate.OpenPGPComponentKey key = cert.getKey(identifier); +// issuers.put(sig, key); +// initSignature(sig, key, processor); +// } +// } +// } +// +// public abstract void update(byte i); +// +// public abstract void update(byte[] buf, int off, int len); +// +// public List verify( +// OpenPGPMessageProcessor processor) +// { +// List results = new ArrayList<>(); +// OpenPGPPolicy policy = processor.getImplementation().policy(); +// +// for (R sig : signatures) +// { +// KeyIdentifier keyId = getKeyIdentifier(sig); +// OpenPGPCertificate.OpenPGPComponentKey key = issuers.get(keyId); +// +// OpenPGPSignature.OpenPGPDocumentSignature docSig = +// new OpenPGPSignature.OpenPGPDocumentSignature((PGPSignature)sig, key); +// +// try +// { +// if (key != null) +// { +// docSig.verify(); +// } +// docSig.sanitize(key, policy); +// } +// catch (PGPException e) +// { +// processor.onException(e); +// } +// +// results.add(docSig); +// } +// return results; +// } +// +// protected abstract KeyIdentifier getKeyIdentifier(R sig); +// +// protected abstract void initSignature(R sig, +// OpenPGPCertificate.OpenPGPComponentKey key, +// OpenPGPMessageProcessor processor) +// throws PGPException; +// } +// +// private static class OnePassSignatureVerifier +// extends BaseSignatureVerifier +// { +// private final List pgpSignatureList = new ArrayList<>(); +// +// public void addPGPSinatures(Iterator it) +// { +// while (it.hasNext()) +// { +// pgpSignatureList.add(it.next()); +// } +// } +// +// @Override +// protected KeyIdentifier getKeyIdentifier(PGPOnePassSignature sig) +// { +// // One-pass signatures directly include their key ID +// return sig.getKeyIdentifier(); +// } +// +// @Override +// protected void initSignature(PGPOnePassSignature sig, +// OpenPGPCertificate.OpenPGPComponentKey key, +// OpenPGPMessageProcessor processor) +// throws PGPException +// { +// // Initialize for one-pass signature verification +// sig.init(processor.getImplementation().pgpContentVerifierBuilderProvider(), +// key.getPGPPublicKey() +// ); +// } +// +// public void update(byte i) +// { +// for (PGPOnePassSignature sig : signatures) +// { +// sig.update(i); +// } +// } +// +// public void update(byte[] buf, int off, int len) +// { +// for (PGPOnePassSignature sig : signatures) +// { +// sig.update(buf, off, len); +// } +// } +// +// public List verify( +// OpenPGPMessageProcessor processor) +// { +// OpenPGPPolicy policy = processor.getImplementation().policy(); +// List dataSignatures = new ArrayList<>(); +// int num = signatures.size(); +// for (int i = 0; i < signatures.size(); i++) +// { +// PGPSignature signature = pgpSignatureList.get(i); +// PGPOnePassSignature ops = signatures.get(num - i - 1); +// OpenPGPCertificate.OpenPGPComponentKey key = issuers.get(ops); +// if (key == null) +// { +// continue; +// } +// +// OpenPGPSignature.OpenPGPDocumentSignature dataSignature = +// new OpenPGPSignature.OpenPGPDocumentSignature(signature, key); +// try +// { +// dataSignature.sanitize(key, policy); +// } +// catch (PGPSignatureException e) +// { +// // continue +// } +// +// if (!dataSignature.createdInBounds(processor.getVerifyNotBefore(), processor.getVerifyNotAfter())) +// { +// // sig is not in bounds +// continue; +// } +// +// try +// { +// dataSignature.verify(ops); +// } +// catch (PGPException e) +// { +// processor.onException(e); +// } +// dataSignatures.add(dataSignature); +// } +// return dataSignatures; +// } +// } +// +// private static class PrefixedSignatureVerifier +// extends BaseSignatureVerifier +// { +// @Override +// protected KeyIdentifier getKeyIdentifier(PGPSignature sig) +// { +// // Prefixed signatures may have multiple key identifiers +// return OpenPGPSignature.getMostExpressiveIdentifier(sig.getKeyIdentifiers()); +// } +// +// @Override +// protected void initSignature(PGPSignature sig, +// OpenPGPCertificate.OpenPGPComponentKey key, +// OpenPGPMessageProcessor processor) +// throws PGPException +// { +// // Initialize for prefixed signature verification +// sig.init( +// processor.getImplementation().pgpContentVerifierBuilderProvider(), +// key.getPGPPublicKey() +// ); +// } +// +// public void update(byte i) +// { +// for (PGPSignature sig : signatures) +// { +// sig.update(i); +// } +// } +// +// public void update(byte[] buf, int off, int len) +// { +// for (PGPSignature sig : signatures) +// { +// sig.update(buf, off, len); +// } +// } +// } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageOutputStream.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageOutputStream.java new file mode 100644 index 0000000000..b5ba7ae790 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageOutputStream.java @@ -0,0 +1,471 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPPadding; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.util.io.TeeOutputStream; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; +import java.util.Stack; + +/** + * Implementation of an {@link OutputStream} tailored to creating OpenPGP messages. + * Since not all OpenPGP-related OutputStreams forward {@link #close()} calls, we need to keep track of nested streams + * and close them in order. + * This stream can create OpenPGP messages following the following EBNF (which is a subset of the EBNF defined in RFC9580): + *
        + *
      • OpenPGP Message := ASCII-Armor(Optionally Encrypted Message) | Optionally Encrypted Message
      • + *
      • Literal Message := LiteralDataPacket
      • + *
      • Optionally Compressed Message := Literal Message | + * CompressedDataPacket(Literal Message)
      • + *
      • Optionally Signed Message := Optionally Compressed Message | + * OnePassSignaturePacket + Optionally Signed Message + SignaturePacket
      • + *
      • Optionally Padded Message := Optionally Signed Message | Optionally Signed Message + PaddingPacket
      • + *
      • Encrypted Message := SEIPDv1(Optionally Padded Message) | + * SEIPDv2(Optionally Padded Message) | + * OED(Optionally Padded Message)
      • + *
      • Optionally Encrypted Message := Optionally Padded Message | Encrypted Message
      • + *
      + * Therefore, this stream is capable of creating a wide variety of OpenPGP message, from simply + * LiteralDataPacket-wrapped plaintext over signed messages to encrypted, signed and padded messages. + * The following considerations lead to why this particular subset was chosen: + *
        + *
      • An encrypted message is not distinguishable from randomness, so it makes no sense to compress it
      • + *
      • Since signatures also consist of data which is not distinguishable from randomness, + * it makes no sense to compress them either
      • + *
      • Padding packets are used to prevent traffic analysis. + * Since they contain random data, we do not compress them. + * If a message is encrypted, we want to encrypt the padding packet to prevent an intermediate from stripping it
      • + *
      • Since (v4) signatures leak some metadata about the message plaintext (the hash and the issuer), + * for encrypted messages we always place signatures inside the encryption container (sign-then-encrypt)
      • + *
      • Prefix-signed messages (where a SignaturePacket is prefixed to an OpenPGP message) are + * inferior to One-Pass-Signed messages, so this stream cannot produce those.
      • + *
      • Messages using the Cleartext-Signature Framework are "different enough" to deserve their own + * message generator / stream.
      • + *
      + */ +public class OpenPGPMessageOutputStream + extends OutputStream +{ + // sink for the OpenPGP message + private final OutputStream baseOut; // non-null + + private final OutputStream armorOut; // nullable + private final OutputStream encodeOut; // non-null + private final OutputStream encryptOut; // nullable + private final OutputStream paddingOut; // nullable + private final OutputStream signOut; // nullable + private final OutputStream compressOut; // nullable + private final OutputStream literalOut; // non-null + + // pipe plaintext data into this stream + private final OutputStream plaintextOut; // non-null + + OpenPGPMessageOutputStream(OutputStream baseOut, Builder builder) + throws PGPException, IOException + { + this.baseOut = baseOut; + OutputStream innermostOut = baseOut; + + // ASCII ARMOR + if (builder.armorFactory != null) + { + armorOut = builder.armorFactory.get(innermostOut); + innermostOut = armorOut; + } + else + { + armorOut = null; + } + + // BCPG (decide packet length encoding format) + encodeOut = new BCPGOutputStream(innermostOut, PacketFormat.CURRENT); + innermostOut = encodeOut; + + // ENCRYPT + if (builder.encryptionStreamFactory != null) + { + encryptOut = builder.encryptionStreamFactory.get(innermostOut); + innermostOut = encryptOut; + } + else + { + encryptOut = null; + } + + // PADDING + if (builder.paddingStreamFactory != null) + { + paddingOut = builder.paddingStreamFactory.get(innermostOut); + innermostOut = paddingOut; + } + else + { + paddingOut = null; + } + + // SIGN + if (builder.signatureStreamFactory != null) + { + signOut = builder.signatureStreamFactory.get(innermostOut); + // signOut does not forward write() calls down, so we do *not* set innermostOut to it + } + else + { + signOut = null; + } + + // COMPRESS + if (builder.compressionStreamFactory != null) + { + compressOut = builder.compressionStreamFactory.get(innermostOut); + innermostOut = compressOut; + } + else + { + compressOut = null; + } + + // LITERAL DATA + if (builder.literalDataStreamFactory == null) + { + throw new PGPException("Missing instructions for LiteralData encoding."); + } + literalOut = builder.literalDataStreamFactory.get(innermostOut); + + if (signOut != null) + { + this.plaintextOut = new TeeOutputStream(literalOut, signOut); + } + else + { + this.plaintextOut = literalOut; + } + } + + @Override + public void write(int i) + throws IOException + { + plaintextOut.write(i); + } + + @Override + public void write(byte[] b) + throws IOException + { + write(b, 0, b.length); + } + + @Override + public void write(byte[] b, int off, int len) + throws IOException + { + plaintextOut.write(b, off, len); + } + + @Override + public void flush() + throws IOException + { + literalOut.flush(); + if (compressOut != null) + { + compressOut.flush(); + } + if (signOut != null) + { + signOut.flush(); + } + if (paddingOut != null) + { + paddingOut.flush(); + } + if (encryptOut != null) + { + encryptOut.flush(); + } + encodeOut.flush(); + if (armorOut != null) + { + armorOut.flush(); + } + baseOut.flush(); + } + + @Override + public void close() + throws IOException + { + literalOut.close(); + if (compressOut != null) + { + compressOut.close(); + } + if (signOut != null) + { + signOut.close(); + } + if (paddingOut != null) + { + paddingOut.close(); + } + if (encryptOut != null) + { + encryptOut.close(); + } + encodeOut.close(); + if (armorOut != null) + { + armorOut.close(); + } + baseOut.close(); + } + + /** + * Factory class for wrapping output streams. + */ + public interface OutputStreamFactory + { + /** + * Wrap the given base stream with another {@link OutputStream} and return the result. + * @param base base output stream + * @return wrapped output stream + * @throws PGPException if the wrapping stream cannot be instantiated + */ + OutputStream get(OutputStream base) throws PGPException, IOException; + } + + static Builder builder() + { + return new Builder(); + } + + /** + * Builder class for {@link OpenPGPMessageOutputStream} instances. + */ + static class Builder + { + private OpenPGPMessageGenerator.ArmoredOutputStreamFactory armorFactory; + private OutputStreamFactory paddingStreamFactory; + private OutputStreamFactory encryptionStreamFactory; + private OutputStreamFactory signatureStreamFactory; + private OutputStreamFactory compressionStreamFactory; + private OutputStreamFactory literalDataStreamFactory; + + /** + * Specify a factory for ASCII armoring the message. + * + * @param factory armor stream factory + * @return this + */ + public Builder armor(OpenPGPMessageGenerator.ArmoredOutputStreamFactory factory) + { + this.armorFactory = factory; + return this; + } + + /** + * Specify a factory for encrypting the message. + * + * @param factory encryption stream factory + * @return this + */ + public Builder encrypt(OutputStreamFactory factory) + { + this.encryptionStreamFactory = factory; + return this; + } + + /** + * Specify a factory for padding the message. + * + * @param factory padding stream factory + * @return this + */ + public Builder padding(OutputStreamFactory factory) + { + this.paddingStreamFactory = factory; + return this; + } + + /** + * Specify a factory for signing the message. + * + * @param factory signing stream factory + * @return this + */ + public Builder sign(OutputStreamFactory factory) + { + this.signatureStreamFactory = factory; + return this; + } + + /** + * Specify a factory for compressing the message. + * ' + * @param factory compression stream factory + * @return this + */ + public Builder compress(OutputStreamFactory factory) + { + this.compressionStreamFactory = factory; + return this; + } + + /** + * Specify a factory for literal-data-wrapping the message. + * + * @param factory literal data stream factory + * @return this + */ + public Builder literalData(OutputStreamFactory factory) + { + this.literalDataStreamFactory = factory; + return this; + } + + /** + * Construct the {@link OpenPGPMessageOutputStream} over the base output stream. + * + * @param baseOut base output stream + * @return OpenPGP message output stream + * @throws PGPException if a stream cannot be created + * @throws IOException if a signature cannot be generated + */ + public OpenPGPMessageOutputStream build(OutputStream baseOut) + throws PGPException, IOException + { + return new OpenPGPMessageOutputStream(baseOut, this); + } + } + + /** + * OutputStream which updates {@link PGPSignatureGenerator} instances with data that is written to it. + * Note: Data written to this stream will *NOT* be forwarded to the underlying {@link OutputStream}. + * Once {@link #close()} is called, it will generate {@link PGPSignature} objects from the generators and write + * those to the underlying {@link OutputStream}. + */ + static class SignatureGeneratorOutputStream + extends OutputStream + { + + private final OutputStream out; + private final List signatureGenerators; + + public SignatureGeneratorOutputStream(OutputStream out, List signatureGenerators) + { + this.out = out; + this.signatureGenerators = signatureGenerators; + } + + @Override + public void write(int i) + throws IOException + { + for (PGPSignatureGenerator sigGen : signatureGenerators) + { + sigGen.update((byte)i); + } + } + + @Override + public void write(byte[] b) + throws IOException + { + for (PGPSignatureGenerator sigGen : signatureGenerators) + { + sigGen.update(b); + } + } + + @Override + public void write(byte[] b, int off, int len) + throws IOException + { + for (PGPSignatureGenerator sigGen : signatureGenerators) + { + sigGen.update(b, off, len); + } + } + + @Override + public void close() + throws IOException + { + for (int i = signatureGenerators.size() - 1; i >= 0; i--) + { + PGPSignatureGenerator gen = signatureGenerators.get(i); + PGPSignature sig = null; + try + { + sig = gen.generate(); + } + catch (PGPException e) + { + throw new RuntimeException(e); + } + sig.encode(out); + } + } + } + + /** + * OutputStream which appends a {@link org.bouncycastle.bcpg.PaddingPacket} to the data + * once {@link #close()} is called. + */ + static class PaddingPacketAppenderOutputStream + extends OutputStream + { + private final OutputStream out; + private final PaddingPacketFactory packetFactory; + + public PaddingPacketAppenderOutputStream(OutputStream out, PaddingPacketFactory packetFactory) + { + this.out = out; + this.packetFactory = packetFactory; + } + + @Override + public void write(byte[] b) + throws IOException + { + out.write(b); + } + + @Override + public void write(byte[] b, int off, int len) + throws IOException + { + out.write(b, off, len); + } + + @Override + public void write(int i) + throws IOException + { + out.write(i); + } + + @Override + public void close() + throws IOException + { + packetFactory.providePaddingPacket().encode(out); + out.close(); + } + } + + /** + * Factory interface for creating PGPPadding objects. + */ + public interface PaddingPacketFactory + { + PGPPadding providePaddingPacket(); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageProcessor.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageProcessor.java new file mode 100644 index 0000000000..546d70a1bd --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPMessageProcessor.java @@ -0,0 +1,543 @@ +package org.bouncycastle.openpgp.api; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.openpgp.IntegrityProtectedInputStream; +import org.bouncycastle.openpgp.PGPEncryptedData; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPBEEncryptedData; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.PGPSessionKeyEncryptedData; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.openpgp.api.exception.KeyPassphraseException; +import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.SessionKeyDataDecryptorFactory; +import org.bouncycastle.util.Arrays; + +public class OpenPGPMessageProcessor +{ + private final OpenPGPImplementation implementation; + private final Configuration configuration; + + /** + * Create a new {@link OpenPGPMessageProcessor} using the default {@link OpenPGPImplementation}. + */ + public OpenPGPMessageProcessor() + { + this(OpenPGPImplementation.getInstance()); + } + + /** + * Create a new {@link OpenPGPMessageProcessor} using the given {@link OpenPGPImplementation}. + * + * @param implementation openpgp implementation + */ + public OpenPGPMessageProcessor(OpenPGPImplementation implementation) + { + this(implementation, implementation.policy()); + } + + public OpenPGPMessageProcessor(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + this.implementation = implementation; + this.configuration = new Configuration(policy); + } + + /** + * Add an {@link OpenPGPCertificate} for signature verification. + * If the message contains any signatures, the provided certificate will be considered as a candidate to verify + * the signature. + * + * @param issuerCertificate OpenPGP certificate + * @return this + */ + public OpenPGPMessageProcessor addVerificationCertificate(OpenPGPCertificate issuerCertificate) + { + configuration.certificatePool.addItem(issuerCertificate); + return this; + } + + public OpenPGPMessageProcessor verifyNotAfter(Date date) + { + configuration.verifyNotAfter = date; + return this; + } + + public OpenPGPMessageProcessor verifyNotBefore(Date date) + { + configuration.verifyNotBefore = date; + return this; + } + + /** + * Add an {@link OpenPGPKey} as potential decryption key. + * If the message is encrypted for an {@link OpenPGPKey}, this key can be tried to decrypt the message. + * Keys added via this method will also be available for message decryption if the message was encrypted + * to an anonymous recipient (wildcard key-id / fingerprint). + * + * @param key OpenPGP key + * @return this + */ + public OpenPGPMessageProcessor addDecryptionKey(OpenPGPKey key) + { + configuration.keyPool.addItem(key); + return this; + } + + /** + * Add an {@link OpenPGPKey} as potential decryption key, along with a {@link KeyPassphraseProvider} dedicated + * to this key. + * If the message is encrypted for an {@link OpenPGPKey}, this key can be tried to decrypt the message. + * Keys added via this method will also be available for message decryption if the message was encrypted + * to an anonymous recipient (wildcard key-id / fingerprint). + * + * @param key OpenPGP key + * @return this + */ + public OpenPGPMessageProcessor addDecryptionKey(OpenPGPKey key, char[] passphrase) + { + configuration.keyPool.addItem(key); + configuration.keyPassphraseProvider.addPassphrase(key, passphrase); + return this; + } + + /** + * Add a passphrase for secret key decryption. + * If the corresponding {@link OpenPGPKey} which key this passphrase is for is known in advance, + * it is highly advised to call {@link #addDecryptionKey(OpenPGPKey, char[])} instead, due to performance reasons. + * + * @param passphrase key-passphrase + * @return this + */ + public OpenPGPMessageProcessor addDecryptionKeyPassphrase(char[] passphrase) + { + configuration.keyPassphraseProvider.addPassphrase(passphrase); + return this; + } + + /** + * Set a provider for dynamically requesting missing passphrases used to unlock encrypted + * {@link OpenPGPKey OpenPGPKeys}. + * This provider is called, if a key cannot be unlocked using any passphrase provided via + * {@link #addDecryptionKey(OpenPGPKey, char[])}. + * + * @param keyPassphraseProvider key passphrase provider + * @return this + */ + public OpenPGPMessageProcessor setMissingOpenPGPKeyPassphraseProvider( + KeyPassphraseProvider keyPassphraseProvider) + { + this.configuration.keyPassphraseProvider.setMissingPassphraseCallback(keyPassphraseProvider); + return this; + } + + /** + * Set a {@link OpenPGPKeyMaterialProvider.OpenPGPCertificateProvider} to allow dynamic requesting certificates + * for signature verification. + * This provider is called if the requested {@link OpenPGPCertificate} has not yet been added explicitly + * via {@link #addVerificationCertificate(OpenPGPCertificate)}. + * This allows lazily requesting verification certificates at runtime. + * + * @param certificateProvider provider for OpenPGP certificates + * @return this + */ + public OpenPGPMessageProcessor setMissingOpenPGPCertificateProvider( + OpenPGPKeyMaterialProvider.OpenPGPCertificateProvider certificateProvider) + { + configuration.certificatePool.setMissingItemCallback(certificateProvider); + return this; + } + + /** + * Set a provider for {@link OpenPGPKey OpenPGPKeys}, which can be used to decrypt encrypted messages. + * This provider is called if an {@link OpenPGPKey} required to decrypt the message has not yet been + * explicitly added via {@link #addDecryptionKey(OpenPGPKey)}. + * This allows lazily requesting decryption keys at runtime. + * + * @param keyProvider provider for OpenPGP keys + * @return this + */ + public OpenPGPMessageProcessor setMissingOpenPGPKeyProvider( + OpenPGPKeyMaterialProvider.OpenPGPKeyProvider keyProvider) + { + configuration.keyPool.setMissingItemCallback(keyProvider); + return this; + } + + /** + * Set a passphrase to decrypt a symmetrically encrypted OpenPGP message. + * + * @param messagePassphrase passphrase for message decryption + * @return this + */ + public OpenPGPMessageProcessor addMessagePassphrase(char[] messagePassphrase) + { + this.configuration.addMessagePassphrase(messagePassphrase); + return this; + } + + /** + * Set a {@link MissingMessagePassphraseCallback} which will be invoked if the message is encrypted using a passphrase, + * but no working passphrase was provided. + * + * @param callback callback + * @return this + */ + public OpenPGPMessageProcessor setMissingMessagePassphraseCallback( + MissingMessagePassphraseCallback callback) + { + this.configuration.missingMessagePassphraseCallback = callback; + return this; + } + + /** + * Set a {@link PGPSessionKey} with which an encrypted OpenPGP message can be decrypted without the need for + * using a private key or passphrase. + * Typically, this method can be used, if the {@link PGPSessionKey} of a message is already known (e.g. because + * the message has already been decrypted before). + * The benefit of this is, that public-key operations can be costly. + * + * @param sessionKey session key + * @return this + */ + public OpenPGPMessageProcessor setSessionKey(PGPSessionKey sessionKey) + { + configuration.sessionKey = sessionKey; + return this; + } + + /** + * Process an OpenPGP message. + * + * @param messageIn input stream of the OpenPGP message + * @return plaintext input stream + * @throws IOException + * @throws PGPException + */ + public OpenPGPMessageInputStream process(InputStream messageIn) + throws IOException, PGPException + { + // Remove potential ASCII armoring + InputStream packetInputStream = PGPUtil.getDecoderStream(messageIn); + + PGPObjectFactory objectFactory = implementation.pgpObjectFactory(packetInputStream); + OpenPGPMessageInputStream in = new OpenPGPMessageInputStream(objectFactory, this); + in.process(); + return in; + } + + Date getVerifyNotBefore() + { + return configuration.verifyNotBefore; + } + + Date getVerifyNotAfter() + { + return configuration.verifyNotAfter; + } + + /** + * Bundle together metadata about the decryption result. + * That includes the encrypted data packet itself, the passphrase or (sub-)key that was used to decrypt the + * session-key, the session-key itself and lastly the resulting decrypted packet input stream. + */ + static class Decrypted + { + final InputStream inputStream; + final PGPSessionKey sessionKey; + final PGPEncryptedData esk; + OpenPGPCertificate.OpenPGPComponentKey decryptionKey; + char[] decryptionPassphrase; + + public Decrypted(PGPEncryptedData encryptedData, + PGPSessionKey decryptedSessionKey, + InputStream decryptedIn) + { + this.esk = encryptedData; + this.sessionKey = decryptedSessionKey; + this.inputStream = decryptedIn; + } + } + + /** + * Decrypt an encrypted data packet by trying passphrases and/or decryption keys. + * + * @param encDataList encrypted data + * @return decrypted data + * @throws PGPException in case of an error + */ + Decrypted decrypt(PGPEncryptedDataList encDataList) + throws PGPException + { + // Since decryption using session key is the most "deliberate" and "specific", we'll try that first + if (configuration.sessionKey != null) + { + // decrypt with provided session key + SessionKeyDataDecryptorFactory decryptorFactory = + implementation.sessionKeyDataDecryptorFactory(configuration.sessionKey); + PGPSessionKeyEncryptedData encData = encDataList.extractSessionKeyEncryptedData(); + InputStream decryptedIn = encData.getDataStream(decryptorFactory); + IntegrityProtectedInputStream verifyingIn = new IntegrityProtectedInputStream(decryptedIn, encData); + + return new Decrypted(encData, configuration.sessionKey, verifyingIn); + } + + List skesks = skesks(encDataList); + List pkesks = pkesks(encDataList); + + PGPException exception = null; + + // If the user explicitly provided a message passphrase, we'll try that next + if (!skesks.isEmpty() && !configuration.messagePassphrases.isEmpty()) + { + for (PGPPBEEncryptedData skesk : skesks) + { + for (char[] passphrase : configuration.messagePassphrases) + { + try + { + // Extract message session key with passphrase + PBEDataDecryptorFactory passphraseDecryptorFactory = + implementation.pbeDataDecryptorFactory(passphrase); + PGPSessionKey decryptedSessionKey = skesk.getSessionKey(passphraseDecryptorFactory); + + // Decrypt the message with the decrypted session key + SessionKeyDataDecryptorFactory skDecryptorFactory = + implementation.sessionKeyDataDecryptorFactory(decryptedSessionKey); + PGPSessionKeyEncryptedData encData = encDataList.extractSessionKeyEncryptedData(); + InputStream decryptedIn = encData.getDataStream(skDecryptorFactory); + IntegrityProtectedInputStream verifyingIn = new IntegrityProtectedInputStream(decryptedIn, encData); + + Decrypted decrypted = new Decrypted(encData, decryptedSessionKey, verifyingIn); + decrypted.decryptionPassphrase = passphrase; + + return decrypted; + } + catch (PGPException e) + { + onException(e); + // cache first exception, then continue to try next skesk if present + exception = exception != null ? exception : e; + } + } + } + } + + // Then we'll try decryption using secret key(s) + for (PGPPublicKeyEncryptedData pkesk : pkesks) + { + KeyIdentifier identifier = pkesk.getKeyIdentifier(); + OpenPGPKey key = configuration.keyPool.provide(identifier); + if (key == null) + { + continue; + } + + OpenPGPKey.OpenPGPSecretKey decryptionKey = key.getSecretKeys().get(identifier); + if (decryptionKey == null) + { + continue; + } + + try + { + if (!decryptionKey.isEncryptionKey()) + { + throw new PGPException("Key is not an encryption key and can therefore not decrypt."); + } + + char[] keyPassphrase = configuration.keyPassphraseProvider.getKeyPassword(decryptionKey); + PGPKeyPair unlockedKey = decryptionKey.unlock(keyPassphrase).getKeyPair(); + if (unlockedKey == null) + { + throw new KeyPassphraseException(decryptionKey, new PGPException("Cannot unlock secret key.")); + } + + // Decrypt the message session key using the private key + PublicKeyDataDecryptorFactory pkDecryptorFactory = + implementation.publicKeyDataDecryptorFactory(unlockedKey.getPrivateKey()); + PGPSessionKey decryptedSessionKey = pkesk.getSessionKey(pkDecryptorFactory); + + // Decrypt the message using the decrypted session key + SessionKeyDataDecryptorFactory skDecryptorFactory = + implementation.sessionKeyDataDecryptorFactory(decryptedSessionKey); + PGPSessionKeyEncryptedData encData = encDataList.extractSessionKeyEncryptedData(); + InputStream decryptedIn = encData.getDataStream(skDecryptorFactory); + IntegrityProtectedInputStream verifyingIn = new IntegrityProtectedInputStream(decryptedIn, encData); + Decrypted decrypted = new Decrypted(encData, decryptedSessionKey, verifyingIn); + decrypted.decryptionKey = decryptionKey; + return decrypted; + } + catch (PGPException e) + { + onException(e); + } + } + + // And lastly, we'll prompt the user dynamically for a message passphrase + if (!skesks.isEmpty() && configuration.missingMessagePassphraseCallback != null) + { + char[] passphrase; + while ((passphrase = configuration.missingMessagePassphraseCallback.getMessagePassphrase()) != null) + { + for (PGPPBEEncryptedData skesk : skesks) + { + try + { + // Decrypt the message session key using a passphrase + PBEDataDecryptorFactory passphraseDecryptorFactory = implementation.pbeDataDecryptorFactory(passphrase); + PGPSessionKey decryptedSessionKey = skesk.getSessionKey(passphraseDecryptorFactory); + + // Decrypt the data using the decrypted session key + SessionKeyDataDecryptorFactory skDecryptorFactory = implementation.sessionKeyDataDecryptorFactory(decryptedSessionKey); + PGPSessionKeyEncryptedData encData = encDataList.extractSessionKeyEncryptedData(); + InputStream decryptedIn = encData.getDataStream(skDecryptorFactory); + IntegrityProtectedInputStream verifyingIn = new IntegrityProtectedInputStream(decryptedIn, encData); + Decrypted decrypted = new Decrypted(encData, decryptedSessionKey, verifyingIn); + decrypted.decryptionPassphrase = passphrase; + return decrypted; + } + catch (PGPException e) + { + onException(e); + // cache first exception, then continue to try next skesk if present + exception = exception != null ? exception : e; + } + } + } + + if (exception != null) + { + throw exception; + } + } + + throw new PGPException("No working decryption method found."); + } + + /** + * Return all symmetric-key-encrypted-session-key (SKESK) packets leading the encrypted data packet. + * + * @param encDataList encrypted data list + * @return list of skesk packets (might be empty) + */ + private List skesks(PGPEncryptedDataList encDataList) + { + List list = new ArrayList(); + for (PGPEncryptedData encData : encDataList) + { + if (encData instanceof PGPPBEEncryptedData) + { + list.add((PGPPBEEncryptedData) encData); + } + } + return list; + } + + /** + * Return all public-key-encrypted-session-key (PKESK) packets leading the encrypted data packet. + * + * @param encDataList encrypted data list + * @return list of pkesk packets (might be empty) + */ + private List pkesks(PGPEncryptedDataList encDataList) + { + List list = new ArrayList(); + for (PGPEncryptedData encData : encDataList) + { + if (encData instanceof PGPPublicKeyEncryptedData) + { + list.add((PGPPublicKeyEncryptedData) encData); + } + } + return list; + } + + OpenPGPCertificate provideCertificate(KeyIdentifier identifier) + { + return configuration.certificatePool.provide(identifier); + } + + OpenPGPImplementation getImplementation() + { + return implementation; + } + + /** + * Method that can be called if a {@link PGPException} is thrown. + * If the user provided a {@link PGPExceptionCallback} ({@link Configuration#exceptionCallback} is not null), + * the exception will be passed along to that callback. + * Otherwise, nothing happens. + * + * @param e exception + */ + void onException(PGPException e) + { + if (configuration.exceptionCallback != null) + { + configuration.exceptionCallback.onException(e); + } + } + + public static class Configuration + { + private final OpenPGPPolicy policy; + private final OpenPGPKeyMaterialPool.OpenPGPCertificatePool certificatePool; + private final OpenPGPKeyMaterialPool.OpenPGPKeyPool keyPool; + private final KeyPassphraseProvider.DefaultKeyPassphraseProvider keyPassphraseProvider; + public final List messagePassphrases = new ArrayList(); + private MissingMessagePassphraseCallback missingMessagePassphraseCallback; + private PGPExceptionCallback exceptionCallback = null; + private PGPSessionKey sessionKey; + private Date verifyNotAfter = new Date(); // now + private Date verifyNotBefore = new Date(0L); // beginning of time + + public Configuration(OpenPGPPolicy policy) + { + this.policy = policy; + this.certificatePool = new OpenPGPKeyMaterialPool.OpenPGPCertificatePool(); + this.keyPool = new OpenPGPKeyMaterialPool.OpenPGPKeyPool(); + this.keyPassphraseProvider = new KeyPassphraseProvider.DefaultKeyPassphraseProvider(); + } + + /** + * Add a passphrase that will be tried when a symmetric-key-encrypted-session-key packet is found + * during the decryption process. + * + * @param messagePassphrase passphrase to decrypt the message with + * @return this + */ + public Configuration addMessagePassphrase(char[] messagePassphrase) + { + boolean found = false; + for (char[] existing : messagePassphrases) + { + found |= Arrays.areEqual(existing, messagePassphrase); + } + + if (!found) + { + messagePassphrases.add(messagePassphrase); + } + return this; + } + } + + /** + * Callback to handle {@link PGPException PGPExceptions}. + */ + public interface PGPExceptionCallback + { + void onException(PGPException e); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPPolicy.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPPolicy.java new file mode 100644 index 0000000000..e8f870a479 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPPolicy.java @@ -0,0 +1,324 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.sig.NotationData; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; + +/** + * Policy for OpenPGP algorithms and features. + */ +public interface OpenPGPPolicy +{ + /** + * Return true, if the given {@link PGPPublicKey} is an acceptable signing key. + * Note: Although signing requires a secret key, we perform checks on the public part for consistency. + * + * @param key key + * @return true if acceptable signing key + */ + default boolean isAcceptableSigningKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is an acceptable signature verification key. + * Note: The asymmetry between this and {@link #isAcceptableSigningKey(PGPPublicKey)} is useful + * to prevent creation of signatures using a legacy key, while still allowing verification of + * signatures made using the same key. + * + * @param key key + * @return true if acceptable verification key + */ + default boolean isAcceptableVerificationKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable for encrypting messages. + * + * @param key key + * @return true if acceptable encryption key + */ + default boolean isAcceptableEncryptionKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable for decrypting messages. + * Note: Although decryption requires a secret key, we perform checks on the public part for consistency. + * The asymmetry between this and {@link #isAcceptableEncryptionKey(PGPPublicKey)} is useful + * to prevent creation of new encrypted messages using a legacy key, while still allowing decryption + * of existing messages using the same key. + * + * @param key key + * @return true if acceptable decryption key + */ + default boolean isAcceptableDecryptionKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable. + * + * @param key key + * @return true if acceptable key + */ + default boolean isAcceptablePublicKey(PGPPublicKey key) + { + return isAcceptablePublicKeyStrength(key.getAlgorithm(), key.getBitStrength()); + } + + /** + * Return true, if the given {@link PGPSignature} is acceptable (uses acceptable hash algorithm, + * does not contain unknown critical notations or subpackets). + * Note: A signature being acceptable does NOT mean that it is correct or valid. + * + * @param signature signature + * @return true if acceptable + */ + default boolean isAcceptableSignature(PGPSignature signature) + { + return hasAcceptableSignatureHashAlgorithm(signature) && + hasNoCriticalUnknownNotations(signature) && + hasNoCriticalUnknownSubpackets(signature); + } + + /** + * Return true, if the given {@link PGPSignature} was made using an acceptable signature hash algorithm. + * + * @param signature signature + * @return true if hash algorithm is acceptable + */ + default boolean hasAcceptableSignatureHashAlgorithm(PGPSignature signature) + { + switch (signature.getSignatureType()) + { + case PGPSignature.DEFAULT_CERTIFICATION: + case PGPSignature.NO_CERTIFICATION: + case PGPSignature.CASUAL_CERTIFICATION: + case PGPSignature.POSITIVE_CERTIFICATION: + case PGPSignature.DIRECT_KEY: + case PGPSignature.SUBKEY_BINDING: + case PGPSignature.PRIMARYKEY_BINDING: + return hasAcceptableCertificationSignatureHashAlgorithm(signature); + + case PGPSignature.CERTIFICATION_REVOCATION: + case PGPSignature.KEY_REVOCATION: + case PGPSignature.SUBKEY_REVOCATION: + return hasAcceptableRevocationSignatureHashAlgorithm(signature); + + case PGPSignature.BINARY_DOCUMENT: + case PGPSignature.CANONICAL_TEXT_DOCUMENT: + default: + return hasAcceptableDocumentSignatureHashAlgorithm(signature); + } + } + + /** + * Return true, if the {@link PGPSignature} uses an acceptable data/document signature hash algorithm. + * + * @param signature data / document signature + * @return true if hash algorithm is acceptable + */ + default boolean hasAcceptableDocumentSignatureHashAlgorithm(PGPSignature signature) + { + return isAcceptableDocumentSignatureHashAlgorithm(signature.getHashAlgorithm(), signature.getCreationTime()); + } + + /** + * Return true, if the {@link PGPSignature} uses an acceptable revocation signature hash algorithm. + * + * @param signature revocation signature + * @return true if hash algorithm is acceptable + */ + default boolean hasAcceptableRevocationSignatureHashAlgorithm(PGPSignature signature) + { + return isAcceptableRevocationSignatureHashAlgorithm(signature.getHashAlgorithm(), signature.getCreationTime()); + } + + /** + * Return true, if the {@link PGPSignature} uses an acceptable certification signature hash algorithm. + * + * @param signature certification signature + * @return true if hash algorithm is acceptable + */ + default boolean hasAcceptableCertificationSignatureHashAlgorithm(PGPSignature signature) + { + return isAcceptableCertificationSignatureHashAlgorithm(signature.getHashAlgorithm(), signature.getCreationTime()); + } + + /** + * Return true, if the hashed subpacket area of the signature does NOT contain unknown critical notations. + * @param signature signature + * @return true if signature is free from unknown critical notations + */ + default boolean hasNoCriticalUnknownNotations(PGPSignature signature) + { + PGPSignatureSubpacketVector hashedSubpackets = signature.getHashedSubPackets(); + if (hashedSubpackets == null) + { + return true; + } + + OpenPGPNotationRegistry registry = getNotationRegistry(); + + NotationData[] notations = hashedSubpackets.getNotationDataOccurrences(); + for (NotationData notation : notations) + { + if (notation.isCritical() && !registry.isNotationKnown(notation.getNotationName())) + { + return false; + } + } + return true; + } + + /** + * Return true, if the hashed subpacket area of the signature does NOT contain unknown critical subpackets. + * @param signature signature + * @return true if signature is free from unknown critical subpackets + */ + default boolean hasNoCriticalUnknownSubpackets(PGPSignature signature) + { + PGPSignatureSubpacketVector hashedSubpackets = signature.getHashedSubPackets(); + if (hashedSubpackets == null) + { + return true; + } + + for (SignatureSubpacket subpacket : hashedSubpackets.toArray()) + { + if (subpacket.isCritical() && + // only consider subpackets which are not recognized by SignatureSubpacketInputStream + subpacket.getClass().equals(SignatureSubpacket.class)) + { + if (!isKnownSignatureSubpacket(subpacket.getType())) + { + return false; + } + } + } + return true; + } + + /** + * Return true, if the given signature subpacket ID is known by the implementation. + * Note: This method is only called for subpackets not recognized by + * {@link org.bouncycastle.bcpg.SignatureSubpacketInputStream}. + * + * @param signatureSubpacketTag signature subpacket ID + * @return true if subpacket tag is known + */ + default boolean isKnownSignatureSubpacket(int signatureSubpacketTag) + { + // Overwrite this, allowing custom critical signature subpackets + return false; + } + + /** + * Return true, if the given hash algorithm is - at signature creation time - an acceptable document signature + * hash algorithm. + * + * @param hashAlgorithmId hash algorithm ID + * @param signatureCreationTime optional signature creation time + * @return true if hash algorithm is acceptable at creation time + */ + boolean isAcceptableDocumentSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime); + + /** + * Return true, if the given hash algorithm is - at signature creation time - an acceptable revocation signature + * hash algorithm. + * + * @param hashAlgorithmId hash algorithm ID + * @param signatureCreationTime optional signature creation time + * @return true if hash algorithm is acceptable at creation time + */ + boolean isAcceptableRevocationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime); + + /** + * Return true, if the given hash algorithm is - at signature creation time - an acceptable certification signature + * hash algorithm. + * + * @param hashAlgorithmId hash algorithm ID + * @param signatureCreationTime optional signature creation time + * @return true if hash algorithm is acceptable at creation time + */ + boolean isAcceptableCertificationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime); + + /** + * Return the default certification signature hash algorithm ID. + * This is used as fallback, if negotiation of a commonly supported hash algorithm fails. + * + * @return default certification signature hash algorithm ID + */ + int getDefaultCertificationSignatureHashAlgorithm(); + + /** + * Return the default document signature hash algorithm ID. + * This is used as fallback, if negotiation of a commonly supported hash algorithm fails. + * + * @return default document signature hash algorithm ID + */ + int getDefaultDocumentSignatureHashAlgorithm(); + + /** + * Return true, if the given symmetric-key algorithm is acceptable. + * + * @param symmetricKeyAlgorithmId symmetric-key algorithm + * @return true if symmetric-key algorithm is acceptable + */ + boolean isAcceptableSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId); + + /** + * Return the default symmetric-key algorithm, which is used as a fallback if symmetric encryption algorithm + * negotiation fails. + * + * @return default symmetric-key algorithm + */ + int getDefaultSymmetricKeyAlgorithm(); + + /** + * Return true, if the given bitStrength is acceptable for the given public key algorithm ID. + * + * @param publicKeyAlgorithmId ID of a public key algorithm + * @param bitStrength key bit strength + * @return true if strength is acceptable + */ + boolean isAcceptablePublicKeyStrength(int publicKeyAlgorithmId, int bitStrength); + + /** + * Return the policies {@link OpenPGPNotationRegistry} containing known notation names. + * + * @return notation registry + */ + OpenPGPNotationRegistry getNotationRegistry(); + + /** + * The {@link OpenPGPNotationRegistry} can be used to register known notations, such that signatures containing + * notation instances of the same name, which are marked as critical do not invalidate the signature. + */ + class OpenPGPNotationRegistry + { + private final Set knownNotations = new HashSet(); + + public boolean isNotationKnown(String notationName) + { + return knownNotations.contains(notationName); + } + + public void addKnownNotation(String notationName) + { + this.knownNotations.add(notationName); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPSignature.java b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPSignature.java new file mode 100644 index 0000000000..0421bdc8c1 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/OpenPGPSignature.java @@ -0,0 +1,724 @@ +package org.bouncycastle.openpgp.api; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.SignaturePacket; +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.NotationData; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPOnePassSignature; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureException; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; +import org.bouncycastle.openpgp.api.exception.MalformedOpenPGPSignatureException; +import org.bouncycastle.openpgp.api.util.UTCUtil; +import org.bouncycastle.util.encoders.Hex; + +/** + * An OpenPGP signature. + * This is a wrapper around {@link PGPSignature} which tracks the verification state of the signature. + */ +public abstract class OpenPGPSignature +{ + protected final PGPSignature signature; + protected final OpenPGPCertificate.OpenPGPComponentKey issuer; + protected boolean isTested = false; + protected boolean isCorrect = false; + + /** + * Create an {@link OpenPGPSignature}. + * + * @param signature signature + * @param issuer issuer subkey + */ + public OpenPGPSignature(PGPSignature signature, OpenPGPCertificate.OpenPGPComponentKey issuer) + { + this.signature = signature; + this.issuer = issuer; + } + + /** + * Return the {@link PGPSignature}. + * + * @return signature + */ + public PGPSignature getSignature() + { + return signature; + } + + /** + * Return the {@link OpenPGPCertificate.OpenPGPComponentKey} subkey that issued this signature. + * This method might return null, if the issuer certificate is not available. + * + * @return issuer subkey or null + */ + public OpenPGPCertificate.OpenPGPComponentKey getIssuer() + { + return issuer; + } + + /** + * Return the {@link OpenPGPCertificate} that contains the subkey that issued this signature. + * This method might return null if the issuer certificate is not available + * + * @return issuer certificate or null + */ + public OpenPGPCertificate getIssuerCertificate() + { + return issuer != null ? issuer.getCertificate() : null; + } + + /** + * Return a {@link List} of possible {@link KeyIdentifier} candidates. + * + * @return key identifier candidates + */ + public List getKeyIdentifiers() + { + return signature.getKeyIdentifiers(); + } + + /** + * Return the most expressive {@link KeyIdentifier} from available candidates. + * + * @return most expressive key identifier + */ + public KeyIdentifier getKeyIdentifier() + { + List identifiers = getKeyIdentifiers(); + return getMostExpressiveIdentifier(identifiers); + } + + /** + * Return the most expressive issuer {@link KeyIdentifier}. + * Due to historic reasons, signatures MAY contain more than one issuer packet, which might contain inconsistent + * information (issuer key-ids / issuer fingerprints). + * Throw wildcards (anonymous issuers) into the mix, and it becomes apparent, that there needs to be a way to + * select the "best" issuer identifier. + * If there are more than one issuer packet, this method returns the most expressive (prefer fingerprints over + * key-ids, prefer non-wildcard over wildcard) and returns that. + * + * @param identifiers list of available identifiers + * @return the best identifier + */ + public static KeyIdentifier getMostExpressiveIdentifier(List identifiers) + { + if (identifiers.isEmpty()) + { + // none + return null; + } + if (identifiers.size() == 1) + { + // single + return identifiers.get(0); + } + + // Find most expressive identifier + for (Iterator it = identifiers.iterator(); it.hasNext();) + { + KeyIdentifier identifier = (KeyIdentifier)it.next(); + + // non-wildcard and has fingerprint + if (!identifier.isWildcard() && identifier.getFingerprint() != null) + { + return identifier; + } + } + + // Find non-wildcard identifier + for (Iterator it = identifiers.iterator(); it.hasNext();) + { + KeyIdentifier identifier = (KeyIdentifier)it.next(); + // non-wildcard (and no fingerprint) + if (!identifier.isWildcard()) + { + return identifier; + } + } + // else return first identifier + return identifiers.get(0); + } + + /** + * Return true, if this signature has been tested and is correct. + * + * @return true if the signature is tested and is correct, false otherwise + */ + public boolean isTestedCorrect() + { + return isTested && isCorrect; + } + + /** + * Return the creation time of the signature. + * + * @return signature creation time + */ + public Date getCreationTime() + { + return signature.getCreationTime(); + } + + /** + * Return the expiration time of the signature. + * If no expiration time was included (or if the signature was explicitly marked as non-expiring), + * return null, otherwise return the time of expiration. + * The signature is no longer valid, once the expiration time is exceeded. + * + * @return expiration time + */ + public Date getExpirationTime() + { + PGPSignatureSubpacketVector hashed = signature.getHashedSubPackets(); + if (hashed == null) + { + // v3 sigs have no expiration + return null; + } + long exp = hashed.getSignatureExpirationTime(); + if (exp < 0) + { + throw new RuntimeException("Negative expiration time"); + } + + if (exp == 0L) + { + // Explicit or implicit no expiration + return null; + } + + return new Date(getCreationTime().getTime() + 1000 * exp); + } + + /** + * Return true, if the signature is not a hard revocation, and if the evaluation time falls into the period + * between signature creation time and expiration or revocation. + * + * @param evaluationTime time for which you want to determine effectiveness of the signature + * @return true if the signature is effective at the given evaluation time + */ + public boolean isEffectiveAt(Date evaluationTime) + { + if (isHardRevocation()) + { + // hard revocation is valid at all times + return true; + } + + // creation <= eval < expiration + Date creation = getCreationTime(); + Date expiration = getExpirationTime(); + return !evaluationTime.before(creation) && (expiration == null || evaluationTime.before(expiration)); + } + + /** + * Return true, if this signature is a hard revocation. + * Contrary to soft revocations (the key / signature / user-id was gracefully retired), a hard revocation + * has a serious reason, like key compromise, or no reason at all. + * Hard revocations invalidate the key / signature / user-id retroactively, while soft revocations only + * invalidate from the time of revocation signature creation onwards. + * + * @return true if the signature is a hard revocation + */ + public boolean isHardRevocation() + { + return signature.isHardRevocation(); + } + + /** + * Return true, if this signature is a certification. + * Certification signatures are used to bind user-ids to a key. + * + * @return true if the signature is a certification + */ + public boolean isCertification() + { + return signature.isCertification(); + } + + + /** + * Check certain requirements for OpenPGP signatures. + * + * @param issuer signature issuer + * @throws MalformedOpenPGPSignatureException if the signature is malformed + */ + void sanitize(OpenPGPCertificate.OpenPGPComponentKey issuer, + OpenPGPPolicy policy) + throws PGPSignatureException + { + if (!policy.isAcceptablePublicKey(issuer.getPGPPublicKey())) + { + throw new PGPSignatureException("Unacceptable issuer key."); + } + if (!policy.hasAcceptableSignatureHashAlgorithm(signature)) + { + throw new PGPSignatureException("Unacceptable hash algorithm: " + signature.getHashAlgorithm()); + } + + if (signature.getVersion() < SignaturePacket.VERSION_4) + { + if (signature.getCreationTime().before(issuer.getCreationTime())) + { + throw new MalformedOpenPGPSignatureException( + this, "Signature predates issuer key creation time."); + } + return; + } + + PGPSignatureSubpacketVector hashed = signature.getHashedSubPackets(); + if (hashed == null) + { + throw new MalformedOpenPGPSignatureException( + this, "Missing hashed signature subpacket area."); + } + PGPSignatureSubpacketVector unhashed = signature.getUnhashedSubPackets(); + + if (hashed.getSignatureCreationTime() == null) + { + // Signatures MUST have hashed creation time subpacket + throw new MalformedOpenPGPSignatureException( + this, "Signature does not have a hashed SignatureCreationTime subpacket."); + } + + if (hashed.getSignatureCreationTime().before(issuer.getCreationTime())) + { + throw new MalformedOpenPGPSignatureException( + this, "Signature predates issuer key creation time."); + } + + NotationData[] notations = hashed.getNotationDataOccurrences(); + for (int i = 0; i< notations.length; i++ ) + { + NotationData notation = notations[i]; + if (notation.isCritical()) + { + throw new MalformedOpenPGPSignatureException( + this, "Critical unknown NotationData encountered: " + notation.getNotationName()); + } + } + + SignatureSubpacket[] signatureSubpackets = hashed.toArray(); + for (int i = 0; i != signatureSubpackets.length; i++) + { + SignatureSubpacket unknownSubpacket = signatureSubpackets[i]; + // SignatureSubpacketInputStream returns unknown subpackets as SignatureSubpacket + if (unknownSubpacket.isCritical() && + unknownSubpacket.getClass().equals(SignatureSubpacket.class)) + { + throw new MalformedOpenPGPSignatureException( + this, "Critical hashed unknown SignatureSubpacket encountered: " + unknownSubpacket.getType()); + } + } + + switch (signature.getVersion()) + { + case SignaturePacket.VERSION_4: + case SignaturePacket.VERSION_5: + if (hashed.getIssuerFingerprint() == null && + unhashed.getIssuerFingerprint() == null && + hashed.getSubpacket(SignatureSubpacketTags.ISSUER_KEY_ID) == null && + unhashed.getSubpacket(SignatureSubpacketTags.ISSUER_KEY_ID) == null) + { + int type = signature.getSignatureType(); + if (type != PGPSignature.SUBKEY_BINDING && type != PGPSignature.PRIMARYKEY_BINDING) + { + throw new MalformedOpenPGPSignatureException( + this, "Missing IssuerKeyID and IssuerFingerprint subpacket."); + } + } + break; + + case SignaturePacket.VERSION_6: + if (hashed.getSubpacket(SignatureSubpacketTags.ISSUER_KEY_ID) != null) + { + throw new MalformedOpenPGPSignatureException( + this, "v6 signature MUST NOT contain IssuerKeyID subpacket."); + } + if (hashed.getIssuerFingerprint() == null && unhashed.getIssuerFingerprint() == null) + { + throw new MalformedOpenPGPSignatureException( + this, "v6 signature MUST contain IssuerFingerprint subpacket."); + } + break; + + default: + } + } + + /** + * Return true, if this signature is a revocation, false otherwise. + * @return true if signature is revocation + */ + public boolean isRevocation() + { + return PGPSignature.isRevocation(signature.getSignatureType()); + } + + @Override + public String toString() + { + String issuerInfo = getIssuerDisplay(); + String period = UTCUtil.format(getCreationTime()) + + (getExpirationTime() == null ? "" : ">" + UTCUtil.format(getExpirationTime())); + String validity = isTested ? (isCorrect ? "✓" : "✗") : "❓"; + // -DM Hex.toHexString + return getType() + (signature.isHardRevocation() ? "(hard)" : "") + " " + Hex.toHexString(signature.getDigestPrefix()) + + " " + issuerInfo + " -> " + getTargetDisplay() + " (" + period + ") " + validity; + } + + protected String getIssuerDisplay() + { + if (issuer != null) + { + return issuer.toString(); + } + + KeyIdentifier issuerIdentifier = getKeyIdentifier(); + if (issuerIdentifier == null) + { + return "External[unknown]"; + } + + if (issuerIdentifier.isWildcard()) + { + return "Anonymous"; + } + return "External[" + Long.toHexString(issuerIdentifier.getKeyId()) + .toUpperCase(Locale.getDefault()) + "]"; + } + + protected abstract String getTargetDisplay(); + + protected String getType() + { + switch (signature.getSignatureType()) + { + case PGPSignature.BINARY_DOCUMENT: + return "BINARY_DOCUMENT"; + case PGPSignature.CANONICAL_TEXT_DOCUMENT: + return "CANONICAL_TEXT_DOCUMENT"; + case PGPSignature.STAND_ALONE: + return "STANDALONE"; + case PGPSignature.DEFAULT_CERTIFICATION: + return "DEFAULT_CERTIFICATION"; + case PGPSignature.NO_CERTIFICATION: + return "NO_CERTIFICATION"; + case PGPSignature.CASUAL_CERTIFICATION: + return "CASUAL_CERTIFICATION"; + case PGPSignature.POSITIVE_CERTIFICATION: + return "POSITIVE_CERTIFICATION"; + case PGPSignature.SUBKEY_BINDING: + return "SUBKEY_BINDING"; + case PGPSignature.PRIMARYKEY_BINDING: + return "PRIMARYKEY_BINDING"; + case PGPSignature.DIRECT_KEY: + return "DIRECT_KEY"; + case PGPSignature.KEY_REVOCATION: + return "KEY_REVOCATION"; + case PGPSignature.SUBKEY_REVOCATION: + return "SUBKEY_REVOCATION"; + case PGPSignature.CERTIFICATION_REVOCATION: + return "CERTIFICATION_REVOCATION"; + case PGPSignature.TIMESTAMP: + return "TIMESTAMP"; + case PGPSignature.THIRD_PARTY_CONFIRMATION: + return "THIRD_PARTY_CONFIRMATION"; + default: + return "UNKNOWN (" + signature.getSignatureType() + ")"; + } + } + + /** + * Return an ASCII armored String representation of the signature. + * If the signature contains issuer information, the fingerprint or key-id of the issuer will be added + * to the ASCII armor as a comment header. + * + * @return ASCII armored signature + * @throws IOException if the signature cannot be encoded + */ + public String toAsciiArmoredString() + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream.Builder aBuilder = ArmoredOutputStream.builder() + .clearHeaders(); + if (getKeyIdentifier() != null) + { + aBuilder.addSplitMultilineComment(getKeyIdentifier().toPrettyPrint()); + } + ArmoredOutputStream aOut = aBuilder.build(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + getSignature().encode(pOut); + pOut.close(); + aOut.close(); + return bOut.toString(); + } + + /** + * {@link SignatureSubpacket} and the {@link OpenPGPSignature} that contains it. + */ + public static final class OpenPGPSignatureSubpacket + { + private final SignatureSubpacket subpacket; + private final OpenPGPSignature signature; + private final boolean hashed; + + private OpenPGPSignatureSubpacket(SignatureSubpacket subpacket, + OpenPGPSignature signature, + boolean hashed) + { + this.signature = signature; + this.subpacket = subpacket; + this.hashed = hashed; + } + + /** + * Create a {@link OpenPGPSignatureSubpacket} contained in the hashed area of an {@link OpenPGPSignature}. + * + * @param subpacket subpacket + * @param signature the signature containing the subpacket + * @return OpenPGPSignatureSubpacket + */ + public static OpenPGPSignatureSubpacket hashed(SignatureSubpacket subpacket, OpenPGPSignature signature) + { + return new OpenPGPSignatureSubpacket(subpacket, signature, true); + } + + /** + * Create a {@link OpenPGPSignatureSubpacket} contained in the unhashed area of an {@link OpenPGPSignature}. + * + * @param subpacket subpacket + * @param signature the signature containing the subpacket + * @return OpenPGPSignatureSubpacket + */ + public static OpenPGPSignatureSubpacket unhashed(SignatureSubpacket subpacket, OpenPGPSignature signature) + { + return new OpenPGPSignatureSubpacket(subpacket, signature, false); + } + + /** + * Return the {@link OpenPGPSignature} that contains the {@link SignatureSubpacket}. + * @return signature + */ + public OpenPGPSignature getSignature() + { + return signature; + } + + /** + * Return the {@link SignatureSubpacket} itself. + * @return + */ + public SignatureSubpacket getSubpacket() + { + return subpacket; + } + + /** + * Return
      true
      if the subpacket is contained in the hashed area of the {@link OpenPGPSignature}, + * false otherwise. + * @return true if the subpacket is hashed, false if it is unhashed + */ + public boolean isHashed() + { + return hashed; + } + } + + /** + * An {@link OpenPGPSignature} made over a binary or textual document (e.g. a message). + * Also known as a Data Signature. + * An {@link OpenPGPDocumentSignature} CANNOT live on a {@link OpenPGPCertificate}. + */ + public static class OpenPGPDocumentSignature + extends OpenPGPSignature + { + protected final OpenPGPDocumentSignature attestedSignature; + + /** + * Create a document signature of level 0 (signature is made directly over the document). + * + * @param signature signature + * @param issuer public issuer-signing-key-component (or null if not available) + */ + public OpenPGPDocumentSignature(PGPSignature signature, OpenPGPCertificate.OpenPGPComponentKey issuer) + { + super(signature, issuer); + this.attestedSignature = null; + } + + @Override + protected String getTargetDisplay() + { + return ""; + } + + /** + * Create a document signature of level greater than 0 (signature is made as an attestation over + * other signature(s) + document). + * If the attested signature is itself an attestation, it will recursively contain its attested signature. + * + * @param signature attestation signature + * @param issuer public issuer signing-key-component (or null if not available) + * @param attestedSignature the attested signature + */ + public OpenPGPDocumentSignature(PGPSignature signature, + OpenPGPCertificate.OpenPGPComponentKey issuer, + OpenPGPDocumentSignature attestedSignature) + { + super(signature, issuer); + this.attestedSignature = attestedSignature; + } + + /** + * Return the signature attestation level of this signature. + * If this signature was created directly over a document, this method returns 0. + * A level greater than 0 indicates that the signature is an attestation over at least one other signature. + * + * @return signature attestation level + */ + public int getSignatureLevel() + { + if (attestedSignature == null) + { + return 0; // signature over data + } + else + { + return 1 + attestedSignature.getSignatureLevel(); + } + } + + /** + * Return the attested signature (or null if this is not an attestation signature). + * + * @return attested signature or null + */ + public OpenPGPDocumentSignature getAttestedSignature() + { + return attestedSignature; + } + + /** + * Verify the correctness of an inline signature by evaluating the corresponding {@link PGPOnePassSignature}. + * + * @param ops one-pass-signature packet + * @return true if the signature is correct, false otherwise + * @throws PGPException if the signature cannot be verified + */ + public boolean verify(PGPOnePassSignature ops) + throws PGPException + { + isTested = true; + isCorrect = ops.verify(signature); + return isCorrect; + } + + /** + * Verify the correctness of a prefixed-signature. + * + * @return true if the signature is correct, false otherwise + * @throws PGPException if the signature cannot be verified + */ + public boolean verify() + throws PGPException + { + isTested = true; + isCorrect = signature.verify(); + return isCorrect; + } + + /** + * Return true, if the signature is valid at this moment. + * A valid signature is effective, correct and was issued by a valid signing key. + * + * @return true if the signature is valid now. + */ + public boolean isValid() + throws PGPSignatureException + { + return isValid(OpenPGPImplementation.getInstance().policy()); + } + + /** + * Return true, if the signature is valid at this moment using the given policy. + * A valid signature is effective, correct and was issued by a valid signing key. + * + * @param policy policy + * @return true if the signature is valid now. + */ + public boolean isValid(OpenPGPPolicy policy) + throws PGPSignatureException + { + return isValidAt(getCreationTime(), policy); + } + + /** + * Return true, if th signature is valid at the given date. + * A valid signature is effective, correct and was issued by a valid signing key. + * + * @param date evaluation time + * @return true if the signature is valid at the given date + * @throws IllegalStateException if the signature has not yet been tested using a
      verify()
      method. + */ + public boolean isValidAt(Date date) + throws PGPSignatureException + { + return isValidAt(date, OpenPGPImplementation.getInstance().policy()); + } + + /** + * Return true, if th signature is valid at the given date using the given policy. + * A valid signature is effective, correct and was issued by a valid signing key. + * + * @param date evaluation time + * @param policy policy + * @return true if the signature is valid at the given date + * @throws IllegalStateException if the signature has not yet been tested using a
      verify()
      method. + */ + public boolean isValidAt(Date date, OpenPGPPolicy policy) + throws PGPSignatureException + { + if (!isTested) + { + throw new IllegalStateException("Signature has not yet been verified."); + } + if (!isTestedCorrect()) + { + return false; + } + + sanitize(issuer, policy); + + return issuer.getCertificate().getPrimaryKey().isBoundAt(date) && + issuer.isBoundAt(date) && + issuer.isSigningKey(date); + } + + /** + * Check, if the creation time of the signature is within the interval + *
      notBefore <= creationTime <= notAfter
      + * + * @param notBefore earliest accepted creation time + * @param notAfter latest accepted creation time + * @return true if sig was created in bounds, false otherwise + */ + public boolean createdInBounds(Date notBefore, Date notAfter) + { + return !getCreationTime().before(notBefore) && !getCreationTime().after(notAfter); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/SignatureParameters.java b/pg/src/main/java/org/bouncycastle/openpgp/api/SignatureParameters.java new file mode 100644 index 0000000000..26611a7d0c --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/SignatureParameters.java @@ -0,0 +1,338 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; + +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.util.Arrays; + +/** + * Parameters for signature generation. + * Some signature builders allow the user to pass in a {@link Callback}, which can be used to modify + * {@link SignatureParameters} instances prior to signature generation. + */ +public class SignatureParameters +{ + private int signatureType; + private Date signatureCreationTime = new Date(); + private int signatureHashAlgorithmId; + private SignatureSubpacketsFunction hashedSubpacketsFunction; + private SignatureSubpacketsFunction unhashedSubpacketsFunction; + + private final int[] allowedSignatureTypes; + + private SignatureParameters(int... allowedSignatureTypes) + { + this.allowedSignatureTypes = allowedSignatureTypes; + } + + /** + * Create default signature parameters object for a direct-key signature. + * When issued as a self-signature, direct-key signatures can be used to store algorithm preferences + * on the key, which apply to the entire certificate (including all subkeys). + * When issued as a third-party signature, direct-key signatures act as delegations, with which for example the + * web-of-trust can be built. + * + * @param policy algorithm policy + * @return parameters + * @see + * OpenPGP Web-of-Trust + */ + public static SignatureParameters directKeySignature(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.DIRECT_KEY) + .setSignatureType(PGPSignature.DIRECT_KEY) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create default signature parameters for a key revocation signature. + * When issued as a self-signature, key revocation signatures can be used to revoke an entire certificate. + * To revoke only individual subkeys, see {@link #subkeyRevocation(OpenPGPPolicy)} instead. + * When issued as a third-party signature, key revocation signatures are used to revoke earlier delegation + * signatures. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters keyRevocation(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.KEY_REVOCATION) + .setSignatureType(PGPSignature.KEY_REVOCATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a certification signature. + * The default signature type is {@link PGPSignature#POSITIVE_CERTIFICATION}, but can be changed to + * {@link PGPSignature#DEFAULT_CERTIFICATION}, {@link PGPSignature#NO_CERTIFICATION}, + * {@link PGPSignature#CASUAL_CERTIFICATION}. + * When issued as a self-signature, certifications can be used to bind user-ids to the certificate. + * When issued as third-party signatures, certificates act as a statement, expressing that the issuer + * is convinced that the user-id "belongs to" the certificate. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters certification(OpenPGPPolicy policy) + { + return new SignatureParameters( + PGPSignature.DEFAULT_CERTIFICATION, + PGPSignature.NO_CERTIFICATION, + PGPSignature.CASUAL_CERTIFICATION, + PGPSignature.POSITIVE_CERTIFICATION) + .setSignatureType(PGPSignature.POSITIVE_CERTIFICATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a subkey binding signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters subkeyBinding(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.SUBKEY_BINDING) + .setSignatureType(PGPSignature.SUBKEY_BINDING) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create default signature parameters for a subkey revocation signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters subkeyRevocation(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.SUBKEY_REVOCATION) + .setSignatureType(PGPSignature.SUBKEY_REVOCATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a primary-key binding (back-sig) signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters primaryKeyBinding(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.PRIMARYKEY_BINDING) + .setSignatureType(PGPSignature.PRIMARYKEY_BINDING) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a certification-revocation signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters certificationRevocation(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.CERTIFICATION_REVOCATION) + .setSignatureType(PGPSignature.CERTIFICATION_REVOCATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a data/document signature. + * The default signature type is {@link PGPSignature#BINARY_DOCUMENT}, but can be changed to + * {@link PGPSignature#CANONICAL_TEXT_DOCUMENT}. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters dataSignature(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.BINARY_DOCUMENT, PGPSignature.CANONICAL_TEXT_DOCUMENT) + .setSignatureType(PGPSignature.BINARY_DOCUMENT) + .setSignatureHashAlgorithm(policy.getDefaultDocumentSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Change the signature type of the signature to-be-generated to the given type. + * Depending on which factory method was used to instantiate the signature parameters object, + * only certain signature types are allowed. Passing an illegal signature type causes an + * {@link IllegalArgumentException} to be thrown. + * + * @param signatureType signature type + * @return parameters + * @throws IllegalArgumentException if an illegal signature type is passed + */ + public SignatureParameters setSignatureType(int signatureType) + { + if (!Arrays.contains(allowedSignatureTypes, signatureType)) + { + throw new IllegalArgumentException("Illegal signature type provided."); + } + + this.signatureType = signatureType; + return this; + } + + /** + * Return the signature type for the signature to-be-generated. + * + * @return signature type + */ + public int getSignatureType() + { + return signatureType; + } + + /** + * Change the creation time of the signature to-be-generated. + * + * @param signatureCreationTime signature creation time + * @return parameters + */ + public SignatureParameters setSignatureCreationTime(Date signatureCreationTime) + { + if (signatureCreationTime == null) + { + throw new NullPointerException("Signature creation time cannot be null."); + } + + this.signatureCreationTime = signatureCreationTime; + + return this; + } + + /** + * Return the creation time of the signature to-be-generated. + * + * @return signature creation time + */ + public Date getSignatureCreationTime() + { + return signatureCreationTime; + } + + /** + * Change the hash algorithm for the signature to-be-generated. + * + * @param signatureHashAlgorithmId signature hash algorithm id + * @return parameters + */ + public SignatureParameters setSignatureHashAlgorithm(int signatureHashAlgorithmId) + { + this.signatureHashAlgorithmId = signatureHashAlgorithmId; + return this; + } + + /** + * Return the hash algorithm id of the signature to-be-generated. + * + * @return hash algorithm id + */ + public int getSignatureHashAlgorithmId() + { + return signatureHashAlgorithmId; + } + + /** + * Set a function, which is applied to the hashed subpackets area of the signature to-be-generated. + * + * @param subpacketsFunction function to apply to the hashed signature subpackets + * @return parameters + */ + public SignatureParameters setHashedSubpacketsFunction(SignatureSubpacketsFunction subpacketsFunction) + { + this.hashedSubpacketsFunction = subpacketsFunction; + return this; + } + + /** + * Apply the hashed subpackets function set via {@link #setHashedSubpacketsFunction(SignatureSubpacketsFunction)} + * to the given hashed subpackets. + * + * @param hashedSubpackets hashed signature subpackets + * @return modified hashed subpackets + */ + PGPSignatureSubpacketGenerator applyToHashedSubpackets(PGPSignatureSubpacketGenerator hashedSubpackets) + { + if (hashedSubpacketsFunction != null) + { + return hashedSubpacketsFunction.apply(hashedSubpackets); + } + return hashedSubpackets; + } + + /** + * Set a function, which is applied to the unhashed subpackets area of the signature to-be-generated. + * + * @param subpacketsFunction function to apply to the unhashed signature subpackets + * @return parameters + */ + public SignatureParameters setUnhashedSubpacketsFunction(SignatureSubpacketsFunction subpacketsFunction) + { + this.unhashedSubpacketsFunction = subpacketsFunction; + return this; + } + + /** + * Apply the unhashed subpackets function set via {@link #setUnhashedSubpacketsFunction(SignatureSubpacketsFunction)} + * to the given unhashed subpackets. + * + * @param unhashedSubpackets unhashed signature subpackets + * @return modified unhashed subpackets + */ + PGPSignatureSubpacketGenerator applyToUnhashedSubpackets(PGPSignatureSubpacketGenerator unhashedSubpackets) + { + if (unhashedSubpacketsFunction != null) + { + return unhashedSubpacketsFunction.apply(unhashedSubpackets); + } + return unhashedSubpackets; + } + + /** + * Callback, allowing the user to modify {@link SignatureParameters} before use. + */ + public interface Callback + { + /** + * Apply custom changes to {@link SignatureParameters}. + * + * @param parameters parameters instance + * @return modified parameters, or null + */ + default SignatureParameters apply(SignatureParameters parameters) + { + return parameters; + } + + static class Util + { + /** + * Shortcut method returning a {@link Callback} which only applies the given + * {@link SignatureSubpacketsFunction} to the hashed signature subpacket area of a signature. + * + * @param function signature subpackets function to apply to the hashed area + * @return callback + */ + public static Callback modifyHashedSubpackets(SignatureSubpacketsFunction function) + { + return new Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + return parameters.setHashedSubpacketsFunction(function); + } + }; + } + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/SignatureSubpacketsFunction.java b/pg/src/main/java/org/bouncycastle/openpgp/api/SignatureSubpacketsFunction.java new file mode 100644 index 0000000000..9d7637e89a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/SignatureSubpacketsFunction.java @@ -0,0 +1,28 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; + +/** + * Callback to modify the contents of a {@link PGPSignatureSubpacketGenerator}. + * The {@link OpenPGPKeyGenerator} already prepopulates the hashed subpacket areas of signatures during + * key generation. This callback is useful to apply custom changes to the hashed subpacket area during the + * generation process. + */ +@FunctionalInterface +public interface SignatureSubpacketsFunction +{ + /** + * Apply some changes to the given {@link PGPSignatureSubpacketGenerator} and return the result. + * It is also possible to replace the whole {@link PGPSignatureSubpacketGenerator} by returning another instance. + * Tipp: In order to replace a subpacket, make sure to prevent duplicates by first removing subpackets + * of the same type using {@link PGPSignatureSubpacketGenerator#removePacketsOfType(int)}. + * To inspect the current contents of the generator, it is best to call + * {@link PGPSignatureSubpacketGenerator#generate()} and in turn inspect its contents using + * {@link PGPSignatureSubpacketVector#toArray()}. + * + * @param subpackets original subpackets + * @return non-null modified subpackets + */ + PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets); +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/SubkeySelector.java b/pg/src/main/java/org/bouncycastle/openpgp/api/SubkeySelector.java new file mode 100644 index 0000000000..5369b4a2f4 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/SubkeySelector.java @@ -0,0 +1,24 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.openpgp.PGPKeyRing; + +import java.util.List; + +/** + * Interface for selecting a subset of keys from a {@link PGPKeyRing}. + * This is useful e.g. for selecting a signing key from an OpenPGP key, or a for selecting all + * encryption capable subkeys of a certificate. + */ +public interface SubkeySelector +{ + /** + * Given a {@link PGPKeyRing}, select a subset of the key rings (sub-)keys and return their + * {@link KeyIdentifier KeyIdentifiers}. + * + * @param certificate OpenPGP key or certificate + * @param policy OpenPGP algorithm policy + * @return non-null list of identifiers + */ + List select(OpenPGPCertificate certificate, OpenPGPPolicy policy); +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/Utils.java b/pg/src/main/java/org/bouncycastle/openpgp/api/Utils.java new file mode 100644 index 0000000000..cd506e99ce --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/Utils.java @@ -0,0 +1,118 @@ +package org.bouncycastle.openpgp.api; + +import java.io.IOException; +import java.util.Date; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; + +class Utils +{ + static void addEmbeddedSiganture(final PGPSignature backSig, PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException + { + if (backSig != null) + { + try + { + hashedSubpackets.addEmbeddedSignature(true, backSig); + } + catch (IOException e) + { + throw new PGPException("Cannot encode embedded back-signature.", e); + } + } + } + + static PGPSignature getBackSignature(PGPKeyPair signingSubkey, SignatureParameters backSigParameters, + PGPPublicKey publicPrimaryKey, OpenPGPImplementation implementation, Date date) + throws PGPException + { + PGPSignature backSig = null; + if (backSigParameters != null) + { + PGPSignatureGenerator backSigGen = getPgpSignatureGenerator(implementation, signingSubkey.getPublicKey(), + signingSubkey.getPrivateKey(), backSigParameters, date, null); + + backSig = backSigGen.generateCertification(publicPrimaryKey, signingSubkey.getPublicKey()); + } + return backSig; + } + + static PGPPublicKey injectCertification(PGPPublicKey publicKey, PGPSignatureGenerator revGen, PGPPublicKey publicPrimaryKey) + throws PGPException + { + PGPSignature revocation = revGen.generateCertification(publicPrimaryKey, publicKey); + return PGPPublicKey.addCertification(publicKey, revocation); + } + + static PGPPublicKey injectCertification(PGPPublicKey publicKey, PGPSignatureGenerator revGen) + throws PGPException + { + // Inject signature into the certificate + PGPSignature revocation = revGen.generateCertification(publicKey); + return PGPPublicKey.addCertification(publicKey, revocation); + } + + static PGPPublicKey injectCertification(String userId, PGPPublicKey publicPrimaryKey, PGPSignatureGenerator uidSigGen) + throws PGPException + { + // Inject UID and signature into the certificate + PGPSignature uidSig = uidSigGen.generateCertification(userId, publicPrimaryKey); + return PGPPublicKey.addCertification(publicPrimaryKey, userId, uidSig); + } + + public interface HashedSubpacketsOperation + { + void operate(PGPSignatureSubpacketGenerator hashedSubpackets) + throws PGPException; + } + + static PGPSignatureGenerator getPgpSignatureGenerator(OpenPGPImplementation implementationProvider, + PGPPublicKey publicKey, + PGPPrivateKey privateKey, + SignatureParameters parameters, + Date date, + HashedSubpacketsOperation operation) + throws PGPException + { + PGPSignatureGenerator sigGen = new PGPSignatureGenerator( + implementationProvider.pgpContentSignerBuilder( + publicKey.getAlgorithm(), + parameters.getSignatureHashAlgorithmId()), + publicKey); + sigGen.init(parameters.getSignatureType(), privateKey); + + final PGPSignatureSubpacketGenerator hashedSubpackets = new PGPSignatureSubpacketGenerator(); + hashedSubpackets.setIssuerFingerprint(true, publicKey); + if (date != null) + { + hashedSubpackets.setSignatureCreationTime(date); + } + if (operation != null) + { + operation.operate(hashedSubpackets); + } + parameters.applyToHashedSubpackets(hashedSubpackets); + sigGen.setHashedSubpackets(hashedSubpackets.generate()); + + PGPSignatureSubpacketGenerator unhashedSubpackets = new PGPSignatureSubpacketGenerator(); + unhashedSubpackets = parameters.applyToUnhashedSubpackets(unhashedSubpackets); + sigGen.setUnhashedSubpackets(unhashedSubpackets.generate()); + return sigGen; + } + + static SignatureParameters applySignatureParameters(SignatureParameters.Callback signatureCallback, SignatureParameters parameters) + { + if (signatureCallback != null) + { + parameters = signatureCallback.apply(parameters); + } + return parameters; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPApi.java b/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPApi.java new file mode 100644 index 0000000000..297cd8cdac --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPApi.java @@ -0,0 +1,60 @@ +package org.bouncycastle.openpgp.api.bc; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPImplementation; +import org.bouncycastle.openpgp.api.OpenPGPPolicy; +import org.bouncycastle.openpgp.api.OpenPGPKeyGenerator; + +import java.util.Date; + +/** + * Implementation of {@link OpenPGPApi} using Bouncy Castles implementation of OpenPGP classes. + */ +public class BcOpenPGPApi + extends OpenPGPApi +{ + public BcOpenPGPApi() + { + this(new BcOpenPGPImplementation()); + } + + public BcOpenPGPApi(OpenPGPImplementation implementation) + { + super(implementation); + } + + public BcOpenPGPApi(OpenPGPPolicy policy) + { + this(new BcOpenPGPImplementation(), policy); + } + + public BcOpenPGPApi(OpenPGPImplementation implementation, OpenPGPPolicy policy) + { + super(implementation, policy); + } + + @Override + public OpenPGPKeyGenerator generateKey(int version) + throws PGPException + { + return new BcOpenPGPKeyGenerator(version); + } + + @Override + public OpenPGPKeyGenerator generateKey(int version, + Date creationTime) + throws PGPException + { + return new BcOpenPGPKeyGenerator(version, creationTime); + } + + @Override + public OpenPGPKeyGenerator generateKey(int version, + Date creationTime, + boolean aeadProtection) + throws PGPException + { + return new BcOpenPGPKeyGenerator(version, creationTime, aeadProtection); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPImplementation.java b/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPImplementation.java new file mode 100644 index 0000000000..ff6f24b9d2 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPImplementation.java @@ -0,0 +1,161 @@ +package org.bouncycastle.openpgp.api.bc; + +import java.io.InputStream; + +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.api.OpenPGPImplementation; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; +import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilderProvider; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilderProvider; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.PGPKeyPairGeneratorProvider; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.SessionKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcAEADSecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcCFBSecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.bc.BcPBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPairGeneratorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.bc.BcSessionKeyDataDecryptorFactory; + +/** + * Implementation of {@link OpenPGPImplementation} using Bouncy Castles implementation of OpenPGP classes. + */ +public class BcOpenPGPImplementation + extends OpenPGPImplementation +{ + @Override + public PGPObjectFactory pgpObjectFactory(InputStream packetInputStream) + { + return new BcPGPObjectFactory(packetInputStream) + .setThrowForUnknownCriticalPackets(true); + } + + @Override + public PGPContentVerifierBuilderProvider pgpContentVerifierBuilderProvider() + { + return new BcPGPContentVerifierBuilderProvider(); + } + + @Override + public PBESecretKeyDecryptorBuilderProvider pbeSecretKeyDecryptorBuilderProvider() + { + return new BcPBESecretKeyDecryptorBuilderProvider(); + } + + @Override + public PGPDataEncryptorBuilder pgpDataEncryptorBuilder(int symmetricKeyAlgorithm) + { + return new BcPGPDataEncryptorBuilder(symmetricKeyAlgorithm); + } + + @Override + public PublicKeyKeyEncryptionMethodGenerator publicKeyKeyEncryptionMethodGenerator(PGPPublicKey encryptionSubkey) + { + return new BcPublicKeyKeyEncryptionMethodGenerator(encryptionSubkey); + } + + @Override + public PBEKeyEncryptionMethodGenerator pbeKeyEncryptionMethodGenerator(char[] messagePassphrase) + { + return new BcPBEKeyEncryptionMethodGenerator(messagePassphrase); + } + + @Override + public PBEKeyEncryptionMethodGenerator pbeKeyEncryptionMethodGenerator(char[] messagePassphrase, S2K.Argon2Params argon2Params) + { + return new BcPBEKeyEncryptionMethodGenerator(messagePassphrase, argon2Params); + } + + @Override + public PGPContentSignerBuilder pgpContentSignerBuilder(int publicKeyAlgorithm, int hashAlgorithm) + { + return new BcPGPContentSignerBuilder(publicKeyAlgorithm, hashAlgorithm); + } + + @Override + public PBEDataDecryptorFactory pbeDataDecryptorFactory(char[] messagePassphrase) + throws PGPException + { + return new BcPBEDataDecryptorFactory(messagePassphrase, pgpDigestCalculatorProvider()); + } + + @Override + public SessionKeyDataDecryptorFactory sessionKeyDataDecryptorFactory(PGPSessionKey sessionKey) + { + return new BcSessionKeyDataDecryptorFactory(sessionKey); + } + + @Override + public PublicKeyDataDecryptorFactory publicKeyDataDecryptorFactory(PGPPrivateKey decryptionKey) + { + return new BcPublicKeyDataDecryptorFactory(decryptionKey); + } + + @Override + public PGPDigestCalculatorProvider pgpDigestCalculatorProvider() + throws PGPException + { + return new BcPGPDigestCalculatorProvider(); + } + + @Override + public PGPKeyPairGeneratorProvider pgpKeyPairGeneratorProvider() + { + return new BcPGPKeyPairGeneratorProvider(); + } + + @Override + public PGPContentSignerBuilderProvider pgpContentSignerBuilderProvider(int hashAlgorithmId) + { + return new BcPGPContentSignerBuilderProvider(hashAlgorithmId); + } + + @Override + public KeyFingerPrintCalculator keyFingerPrintCalculator() + { + return new BcKeyFingerprintCalculator(); + } + + @Override + public PBESecretKeyEncryptorFactory pbeSecretKeyEncryptorFactory(boolean aead) + { + return pbeSecretKeyEncryptorFactory(aead, SymmetricKeyAlgorithmTags.AES_128, 0x60); + } + + @Override + public PBESecretKeyEncryptorFactory pbeSecretKeyEncryptorFactory(boolean aead, int symmetricKeyAlgorithm, int iterationCount) + { + if (aead) + { + return new BcAEADSecretKeyEncryptorFactory(); + } + else + { + return new BcCFBSecretKeyEncryptorFactory(symmetricKeyAlgorithm, iterationCount); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPKeyGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPKeyGenerator.java new file mode 100644 index 0000000000..218fb6c73d --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/bc/BcOpenPGPKeyGenerator.java @@ -0,0 +1,51 @@ +package org.bouncycastle.openpgp.api.bc; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPKeyGenerator; + +import java.util.Date; + +/** + * Bouncy Castle implementation of {@link OpenPGPKeyGenerator}. + */ +public class BcOpenPGPKeyGenerator + extends OpenPGPKeyGenerator +{ + + /** + * Create a new key generator for OpenPGP v6 keys. + * + * @param version key version + */ + public BcOpenPGPKeyGenerator(int version) + throws PGPException + { + this(version, new Date()); + } + + /** + * Create a new key generator for OpenPGP v6 keys. + * The key creation time will be set to {@code creationTime} + * + * @param version key version + * @param creationTime creation time of the generated OpenPGP key + */ + public BcOpenPGPKeyGenerator(int version, Date creationTime) + throws PGPException + { + this(version, creationTime, true); + } + + /** + * Create a new OpenPGP key generator for v6 keys. + * + * @param version key version + * @param creationTime creation time of the key and signatures + * @param aeadProtection whether the key shall be protected using AEAD. If false, the key is protected using CFB. + */ + public BcOpenPGPKeyGenerator(int version, Date creationTime, boolean aeadProtection) + throws PGPException + { + super(new BcOpenPGPImplementation(), version, aeadProtection, creationTime); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/IncorrectOpenPGPSignatureException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/IncorrectOpenPGPSignatureException.java new file mode 100644 index 0000000000..44d5c34aa4 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/IncorrectOpenPGPSignatureException.java @@ -0,0 +1,15 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.api.OpenPGPSignature; + +/** + * An OpenPGP signature is not correct. + */ +public class IncorrectOpenPGPSignatureException + extends OpenPGPSignatureException +{ + public IncorrectOpenPGPSignatureException(OpenPGPSignature signature, String message) + { + super(signature, message); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/InvalidEncryptionKeyException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/InvalidEncryptionKeyException.java new file mode 100644 index 0000000000..9e3f04b488 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/InvalidEncryptionKeyException.java @@ -0,0 +1,37 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.util.Arrays; + +/** + * Exception that gets thrown if the user tries to encrypt a message for an + * {@link org.bouncycastle.openpgp.api.OpenPGPCertificate} that does not contain any usable, valid encryption keys. + */ +public class InvalidEncryptionKeyException + extends OpenPGPKeyException +{ + + public InvalidEncryptionKeyException(OpenPGPCertificate certificate) + { + super(certificate, "Certificate " + certificate.getKeyIdentifier() + + " does not contain any usable subkeys capable of encryption."); + } + + public InvalidEncryptionKeyException(OpenPGPCertificate.OpenPGPComponentKey encryptionSubkey) + { + super(encryptionSubkey, componentKeyErrorMessage(encryptionSubkey)); + } + + private static String componentKeyErrorMessage(OpenPGPCertificate.OpenPGPComponentKey componentKey) + { + if (componentKey.getKeyIdentifier().equals(componentKey.getCertificate().getKeyIdentifier())) + { + return "The primary key " + componentKey.getKeyIdentifier() + " is not usable for encryption."; + } + else + { + return "The subkey " + componentKey.getKeyIdentifier() + " from the certificate " + + componentKey.getCertificate().getKeyIdentifier() + " is not usable for encryption."; + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/InvalidSigningKeyException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/InvalidSigningKeyException.java new file mode 100644 index 0000000000..fccdefecb9 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/InvalidSigningKeyException.java @@ -0,0 +1,33 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; + +public class InvalidSigningKeyException + extends OpenPGPKeyException +{ + + public InvalidSigningKeyException(OpenPGPKey key) + { + super(key, "The key " + key.getKeyIdentifier() + + " does not contain any usable component keys capable of signing."); + } + + public InvalidSigningKeyException(OpenPGPCertificate.OpenPGPComponentKey componentKey) + { + super(componentKey, componentKeyErrorMessage(componentKey)); + } + + private static String componentKeyErrorMessage(OpenPGPCertificate.OpenPGPComponentKey componentKey) + { + if (componentKey.getKeyIdentifier().equals(componentKey.getCertificate().getKeyIdentifier())) + { + return "The primary key " + componentKey.getKeyIdentifier() + " is not usable for signing."; + } + else + { + return "The subkey " + componentKey.getKeyIdentifier() + " from the certificate " + + componentKey.getCertificate().getKeyIdentifier() + " is not usable for signing."; + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/KeyPassphraseException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/KeyPassphraseException.java new file mode 100644 index 0000000000..7a51216fdf --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/KeyPassphraseException.java @@ -0,0 +1,34 @@ +package org.bouncycastle.openpgp.api.exception; + + +import org.bouncycastle.openpgp.api.OpenPGPCertificate; + +public class KeyPassphraseException + extends OpenPGPKeyException +{ + private final Exception cause; + + public KeyPassphraseException(OpenPGPCertificate.OpenPGPComponentKey key, Exception cause) + { + super(key, componentKeyErrorMessage(key, cause)); + this.cause = cause; + } + + private static String componentKeyErrorMessage(OpenPGPCertificate.OpenPGPComponentKey key, Exception cause) + { + if (key.getKeyIdentifier().equals(key.getCertificate().getKeyIdentifier())) + { + return "Cannot unlock primary key " + key.getKeyIdentifier() + ": " + cause.getMessage(); + } + else + { + return "Cannot unlock subkey " + key.getKeyIdentifier() + " from key " + + key.getCertificate().getKeyIdentifier() + ": " + cause.getMessage(); + } + } + + public Exception getCause() + { + return cause; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/MalformedOpenPGPSignatureException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/MalformedOpenPGPSignatureException.java new file mode 100644 index 0000000000..06d941a7cf --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/MalformedOpenPGPSignatureException.java @@ -0,0 +1,16 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.api.OpenPGPSignature; + +/** + * An OpenPGP Signature is malformed (missing required subpackets, etc.). + */ +public class MalformedOpenPGPSignatureException + extends OpenPGPSignatureException +{ + + public MalformedOpenPGPSignatureException(OpenPGPSignature signature, String message) + { + super(signature, message); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/MissingIssuerCertException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/MissingIssuerCertException.java new file mode 100644 index 0000000000..4a37432966 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/MissingIssuerCertException.java @@ -0,0 +1,15 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.api.OpenPGPSignature; + +/** + * The OpenPGP certificate (public key) required to verify a signature is not available. + */ +public class MissingIssuerCertException + extends OpenPGPSignatureException +{ + public MissingIssuerCertException(OpenPGPSignature signature, String message) + { + super(signature, message); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/OpenPGPKeyException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/OpenPGPKeyException.java new file mode 100644 index 0000000000..04e5787ea5 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/OpenPGPKeyException.java @@ -0,0 +1,68 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; + +/** + * Exception representing an unusable or invalid {@link org.bouncycastle.openpgp.api.OpenPGPKey} + * or {@link OpenPGPCertificate}. + * Note: The term "key" is used to refer to both a certificate and a key. + */ +public class OpenPGPKeyException + extends PGPException +{ + private final OpenPGPCertificate key; + private final OpenPGPCertificate.OpenPGPComponentKey componentKey; + + private OpenPGPKeyException(OpenPGPCertificate key, + OpenPGPCertificate.OpenPGPComponentKey componentKey, + String message) + { + super(message); + this.key = key; + this.componentKey = componentKey; + } + + /** + * Something is wrong with a key or certificate in general (no particular subkey). + * + * @param key certificate or key + * @param message message + */ + public OpenPGPKeyException(OpenPGPCertificate key, String message) + { + this(key, null, message); + } + + /** + * Something is wrong with an individual component key of a key or certificate. + * + * @param componentKey component key + * @param message message + */ + public OpenPGPKeyException(OpenPGPCertificate.OpenPGPComponentKey componentKey, String message) + { + this(componentKey.getCertificate(), componentKey, message); + } + + /** + * Return the problematic key or certificate. + * + * @return key or certificate + */ + public OpenPGPCertificate getKey() + { + return key; + } + + /** + * Return the problematic component key. + * Might be null, if the problem affects the entire key or certificate. + * + * @return component key + */ + public OpenPGPCertificate.OpenPGPComponentKey getComponentKey() + { + return componentKey; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/exception/OpenPGPSignatureException.java b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/OpenPGPSignatureException.java new file mode 100644 index 0000000000..16df89d966 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/exception/OpenPGPSignatureException.java @@ -0,0 +1,21 @@ +package org.bouncycastle.openpgp.api.exception; + +import org.bouncycastle.openpgp.PGPSignatureException; +import org.bouncycastle.openpgp.api.OpenPGPSignature; + +public class OpenPGPSignatureException + extends PGPSignatureException +{ + private final OpenPGPSignature signature; + + public OpenPGPSignatureException(OpenPGPSignature signature, String message) + { + super(message); + this.signature = signature; + } + + public OpenPGPSignature getSignature() + { + return signature; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPApi.java b/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPApi.java new file mode 100644 index 0000000000..771208cdab --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPApi.java @@ -0,0 +1,63 @@ +package org.bouncycastle.openpgp.api.jcajce; + +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPPolicy; +import org.bouncycastle.openpgp.api.OpenPGPKeyGenerator; + +import java.security.Provider; +import java.security.SecureRandom; +import java.util.Date; + +/** + * Implementation of {@link OpenPGPApi} using the JCA/JCE implementation of OpenPGP classes. + */ +public class JcaOpenPGPApi + extends OpenPGPApi +{ + private final Provider provider; + + public JcaOpenPGPApi(Provider provider) + { + this(provider, CryptoServicesRegistrar.getSecureRandom()); + } + + public JcaOpenPGPApi(Provider provider, SecureRandom random) + { + super(new JcaOpenPGPImplementation(provider, random)); + this.provider = provider; + } + + public JcaOpenPGPApi(Provider provider, OpenPGPPolicy policy) + { + this(provider, CryptoServicesRegistrar.getSecureRandom(), policy); + } + + public JcaOpenPGPApi(Provider provider, SecureRandom random, OpenPGPPolicy policy) + { + super(new JcaOpenPGPImplementation(provider, random), policy); + this.provider = provider; + } + + @Override + public OpenPGPKeyGenerator generateKey(int version) + throws PGPException + { + return new JcaOpenPGPKeyGenerator(version, provider); + } + + @Override + public OpenPGPKeyGenerator generateKey(int version, Date creationTime) + throws PGPException + { + return new JcaOpenPGPKeyGenerator(version, creationTime, provider); + } + + @Override + public OpenPGPKeyGenerator generateKey(int version, Date creationTime, boolean aeadProtection) + throws PGPException + { + return new JcaOpenPGPKeyGenerator(version, creationTime, aeadProtection, provider); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPImplementation.java b/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPImplementation.java new file mode 100644 index 0000000000..08425937ef --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPImplementation.java @@ -0,0 +1,229 @@ +package org.bouncycastle.openpgp.api.jcajce; + +import java.io.InputStream; +import java.security.Provider; +import java.security.SecureRandom; + +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.api.OpenPGPImplementation; +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; +import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilderProvider; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilderProvider; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.PGPKeyPairGeneratorProvider; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.SessionKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcaAEADSecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcaCFBSecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPairGeneratorProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.jcajce.JceSessionKeyDataDecryptorFactoryBuilder; + +/** + * Implementation of {@link OpenPGPImplementation} using the JCA/JCE implementation of OpenPGP classes. + */ +public class JcaOpenPGPImplementation + extends OpenPGPImplementation +{ + private final Provider provider; + private final SecureRandom secureRandom; + + public JcaOpenPGPImplementation() + { + this(new BouncyCastleProvider(), CryptoServicesRegistrar.getSecureRandom()); + } + + public JcaOpenPGPImplementation(Provider provider, SecureRandom secureRandom) + { + this.provider = provider; + this.secureRandom = secureRandom; + } + + @Override + public PGPObjectFactory pgpObjectFactory(InputStream packetInputStream) + { + return new JcaPGPObjectFactory(packetInputStream) + .setThrowForUnknownCriticalPackets(true); + } + + @Override + public PGPContentVerifierBuilderProvider pgpContentVerifierBuilderProvider() + { + JcaPGPContentVerifierBuilderProvider p = new JcaPGPContentVerifierBuilderProvider(); + p.setProvider(provider); + return p; + } + + @Override + public PBESecretKeyDecryptorBuilderProvider pbeSecretKeyDecryptorBuilderProvider() + { + JcaPGPDigestCalculatorProviderBuilder dp = new JcaPGPDigestCalculatorProviderBuilder(); + dp.setProvider(provider); + JcePBESecretKeyDecryptorBuilderProvider p = new JcePBESecretKeyDecryptorBuilderProvider(dp) + .setProvider(provider); + return p; + } + + @Override + public PGPDataEncryptorBuilder pgpDataEncryptorBuilder(int symmetricKeyAlgorithm) + { + JcePGPDataEncryptorBuilder b = new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithm); + b.setProvider(provider); + b.setSecureRandom(secureRandom); + return b; + } + + @Override + public PublicKeyKeyEncryptionMethodGenerator publicKeyKeyEncryptionMethodGenerator(PGPPublicKey encryptionSubkey) + { + JcePublicKeyKeyEncryptionMethodGenerator g = new JcePublicKeyKeyEncryptionMethodGenerator(encryptionSubkey); + g.setProvider(provider); + g.setSecureRandom(secureRandom); + return g; + } + + @Override + public PBEKeyEncryptionMethodGenerator pbeKeyEncryptionMethodGenerator(char[] messagePassphrase) + { + JcePBEKeyEncryptionMethodGenerator g = new JcePBEKeyEncryptionMethodGenerator(messagePassphrase); + g.setProvider(provider); + g.setSecureRandom(secureRandom); + return g; + } + + @Override + public PBEKeyEncryptionMethodGenerator pbeKeyEncryptionMethodGenerator(char[] messagePassphrase, S2K.Argon2Params argon2Params) + { + JcePBEKeyEncryptionMethodGenerator g = new JcePBEKeyEncryptionMethodGenerator(messagePassphrase, argon2Params); + g.setProvider(provider); + g.setSecureRandom(secureRandom); + return g; + } + + @Override + public PGPContentSignerBuilder pgpContentSignerBuilder(int publicKeyAlgorithm, int hashAlgorithm) + { + JcaPGPContentSignerBuilder b = new JcaPGPContentSignerBuilder(publicKeyAlgorithm, hashAlgorithm); + b.setProvider(provider); + b.setDigestProvider(provider); + b.setSecureRandom(secureRandom); + return b; + } + + @Override + public PBEDataDecryptorFactory pbeDataDecryptorFactory(char[] messagePassphrase) + throws PGPException + { + return new JcePBEDataDecryptorFactoryBuilder(pgpDigestCalculatorProvider()) + .setProvider(provider) + .build(messagePassphrase); + } + + @Override + public SessionKeyDataDecryptorFactory sessionKeyDataDecryptorFactory(PGPSessionKey sessionKey) + { + return new JceSessionKeyDataDecryptorFactoryBuilder() + .setProvider(provider) + .build(sessionKey); + } + + @Override + public PublicKeyDataDecryptorFactory publicKeyDataDecryptorFactory(PGPPrivateKey decryptionKey) + { + return new JcePublicKeyDataDecryptorFactoryBuilder() + .setProvider(provider) + .setContentProvider(provider) + .build(decryptionKey); + } + + @Override + public PGPDigestCalculatorProvider pgpDigestCalculatorProvider() + throws PGPException + { + return new JcaPGPDigestCalculatorProviderBuilder() + .setProvider(provider) + .build(); + } + + @Override + public PGPKeyPairGeneratorProvider pgpKeyPairGeneratorProvider() + { + return new JcaPGPKeyPairGeneratorProvider() + .setProvider(provider) + .setSecureRandom(secureRandom); + } + + @Override + public PGPContentSignerBuilderProvider pgpContentSignerBuilderProvider(int hashAlgorithmId) + { + return new JcaPGPContentSignerBuilderProvider(hashAlgorithmId) + .setSecurityProvider(provider) + .setDigestProvider(provider) + .setSecureRandom(secureRandom); + } + + @Override + public KeyFingerPrintCalculator keyFingerPrintCalculator() + { + return new JcaKeyFingerprintCalculator() + .setProvider(provider); + } + + @Override + public PBESecretKeyEncryptorFactory pbeSecretKeyEncryptorFactory(boolean aead) + throws PGPException + { + if (aead) + { + return new JcaAEADSecretKeyEncryptorFactory() + .setProvider(provider); + } + else + { + return new JcaCFBSecretKeyEncryptorFactory(SymmetricKeyAlgorithmTags.AES_128, 0x60) + .setProvider(provider); + } + } + + @Override + public PBESecretKeyEncryptorFactory pbeSecretKeyEncryptorFactory(boolean aead, int symmetricKeyAlgorithm, int iterationCount) + throws PGPException + { + if (aead) + { + return new JcaAEADSecretKeyEncryptorFactory() + .setProvider(provider); + } + else + { + return new JcaCFBSecretKeyEncryptorFactory(symmetricKeyAlgorithm, iterationCount) + .setProvider(provider); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPKeyGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPKeyGenerator.java new file mode 100644 index 0000000000..c0401336f7 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/jcajce/JcaOpenPGPKeyGenerator.java @@ -0,0 +1,43 @@ +package org.bouncycastle.openpgp.api.jcajce; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPKeyGenerator; + +import java.security.Provider; +import java.security.SecureRandom; +import java.util.Date; + +/** + * JCA/JCE implementation of the {@link OpenPGPKeyGenerator}. + */ +public class JcaOpenPGPKeyGenerator + extends OpenPGPKeyGenerator +{ + + public JcaOpenPGPKeyGenerator(int version, Provider provider) + throws PGPException + { + this(version, new Date(), provider); + } + + public JcaOpenPGPKeyGenerator(int version, Date creationTime, Provider provider) + throws PGPException + { + this(version, creationTime, true, provider); + } + + /** + * Create a new OpenPGP key generator for v6 keys. + * + * @param creationTime creation time of the key and signatures + */ + public JcaOpenPGPKeyGenerator(int version, Date creationTime, boolean aeadProtection, Provider provider) + throws PGPException + { + super( + new JcaOpenPGPImplementation(provider, new SecureRandom()), + version, + aeadProtection, + creationTime); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/api/package-info.java new file mode 100644 index 0000000000..099545ae27 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/package-info.java @@ -0,0 +1,23 @@ +/** + * The
      api
      package contains a high-level OpenPGP API layer on top of the + *
      openpgp
      mid-level API. + * It is tailored to provide a modern OpenPGP experience, following the guidance from rfc9580 ("OpenPGP v6"), + * while also being interoperable with rfc4880 ("OpenPGP v4"). + *

      + * From an architectural point of view, the hierarchy of the individual layers is as follows: + *

        + *
      • + *
        api
        specifies a high-level API using mid-level implementations from
        openpgp
        . + * This layer strives to be easy to use, hard to misuse and secure by default. + *
      • + *
      • + *
        openpgp
        defines a powerful, flexible, but quite verbose API using packet definitions + * from
        bcpg
        . + *
      • + *
      • + *
        bcpg
        implements serialization / deserialization of OpenPGP packets. + * It does not contain any business logic. + *
      • + *
      + */ +package org.bouncycastle.openpgp.api; \ No newline at end of file diff --git a/pg/src/main/java/org/bouncycastle/openpgp/api/util/UTCUtil.java b/pg/src/main/java/org/bouncycastle/openpgp/api/util/UTCUtil.java new file mode 100644 index 0000000000..78ce9a5f7d --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/api/util/UTCUtil.java @@ -0,0 +1,51 @@ +package org.bouncycastle.openpgp.api.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +/** + * Utility class for parsing and formatting UTC timestamps. + */ +public class UTCUtil +{ + private static SimpleDateFormat utc() + { + // Java's SimpleDateFormat is not thread-safe, therefore we return a new instance on every invocation. + // See https://stackoverflow.com/a/6840856/11150851 + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); + format.setTimeZone(TimeZone.getTimeZone("UTC")); + return format; + } + + /** + * Format a {@link Date} as UTC timestamp. + * + * @param timestamp date + * @return formatted timestamp + */ + public static String format(Date timestamp) + { + return utc().format(timestamp); + } + + /** + * Parse a UTC timestamp. + * The timestamp needs to be provided in the form 'yyyy-MM-dd HH:mm:ss z'. + * + * @param utcTimestamp timestamp + * @return date + */ + public static Date parse(String utcTimestamp) + { + try + { + return utc().parse(utcTimestamp); + } + catch (ParseException e) + { + throw new IllegalArgumentException("Malformed UTC timestamp: " + utcTimestamp, e); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/bc/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/bc/package-info.java new file mode 100644 index 0000000000..7661cb25d7 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/bc/package-info.java @@ -0,0 +1,7 @@ +/** + * BC light weight based OpenPGP objects. + *

      + * Some high-level OpenPGP classes require access to cryptographic algorithms. The classes in this package provide extensions using the BC light weight API. + *

      + */ +package org.bouncycastle.openpgp.bc; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/examples/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/examples/package-info.java new file mode 100644 index 0000000000..30ff56eeec --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/examples/package-info.java @@ -0,0 +1,4 @@ +/** + * Examples of use of the org.bouncycastle.openpgp package. + */ +package org.bouncycastle.openpgp.examples; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/jcajce/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/jcajce/package-info.java new file mode 100644 index 0000000000..98ce86e1fc --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/jcajce/package-info.java @@ -0,0 +1,7 @@ +/** + * JCA/JCE provider based OpenPGP objects. + *

      + * Some high-level OpenPGP classes require access to cryptographic algorithms. The classes in this package provide extensions using the JCA/JCE. + *

      + */ +package org.bouncycastle.openpgp.jcajce; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/AEADSecretKeyEncryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/AEADSecretKeyEncryptorBuilder.java new file mode 100644 index 0000000000..76100c76aa --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/AEADSecretKeyEncryptorBuilder.java @@ -0,0 +1,21 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.bcpg.PublicKeyPacket; + +/** + * Implementation provider for AEAD-based {@link PBESecretKeyEncryptor PBESecretKeyEncryptors}. + */ +public interface AEADSecretKeyEncryptorBuilder +{ + /** + * Build a new {@link PBESecretKeyEncryptor} using the given passphrase. + * Note: As the AEAD protection mechanism includes the public key packet of the key into the calculation, + * if the key you want to protect is supposed to be a subkey, you need to convert it to one before + * calling this method. See {@link org.bouncycastle.openpgp.PGPKeyPair#asSubkey(KeyFingerPrintCalculator)}. + * + * @param passphrase passphrase + * @param pubKey public primary or subkey packet + * @return encryptor using AEAD + */ + PBESecretKeyEncryptor build(char[] passphrase, final PublicKeyPacket pubKey); +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/AbstractPublicKeyDataDecryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/AbstractPublicKeyDataDecryptorFactory.java new file mode 100644 index 0000000000..95590d701b --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/AbstractPublicKeyDataDecryptorFactory.java @@ -0,0 +1,82 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.bcpg.InputStreamPacket; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; +import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket; +import org.bouncycastle.bcpg.X25519PublicBCPGKey; +import org.bouncycastle.bcpg.X448PublicBCPGKey; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.util.Arrays; + +public abstract class AbstractPublicKeyDataDecryptorFactory + implements PublicKeyDataDecryptorFactory +{ + + @Override + public final byte[] recoverSessionData(PublicKeyEncSessionPacket pkesk, InputStreamPacket encData) + throws PGPException + { + byte[] sessionData = recoverSessionData(pkesk.getAlgorithm(), pkesk.getEncSessionKey(), pkesk.getVersion()); + return prependSKAlgorithmToSessionData(pkesk, encData, sessionData); + } + + @Override + public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + throws PGPException + { + return recoverSessionData(keyAlgorithm, secKeyData, PublicKeyEncSessionPacket.VERSION_3); + } + + protected byte[] prependSKAlgorithmToSessionData(PublicKeyEncSessionPacket pkesk, + InputStreamPacket encData, + byte[] decryptedSessionData) + throws PGPException + { + // V6 PKESK packets do not include the session key algorithm, so source it from the SEIPD2 instead + if (!containsSKAlg(pkesk.getVersion())) + { + if (!(encData instanceof SymmetricEncIntegrityPacket) || + ((SymmetricEncIntegrityPacket) encData).getVersion() != SymmetricEncIntegrityPacket.VERSION_2) + { + throw new PGPException("v6 PKESK packet MUST precede v2 SEIPD packet"); + } + + SymmetricEncIntegrityPacket seipd2 = (SymmetricEncIntegrityPacket) encData; + return Arrays.prepend(decryptedSessionData, + (byte) (seipd2.getCipherAlgorithm() & 0xff)); + } + // V3 PKESK does store the session key algorithm either encrypted or unencrypted, depending on the PK algorithm + else + { + switch (pkesk.getAlgorithm()) + { + case PublicKeyAlgorithmTags.X25519: + // X25519 does not encrypt SK algorithm + return Arrays.prepend(decryptedSessionData, + pkesk.getEncSessionKey()[0][X25519PublicBCPGKey.LENGTH + 1]); + case PublicKeyAlgorithmTags.X448: + // X448 does not encrypt SK algorithm + return Arrays.prepend(decryptedSessionData, + pkesk.getEncSessionKey()[0][X448PublicBCPGKey.LENGTH + 1]); + default: + // others already prepended session key algorithm to session key + return decryptedSessionData; + } + } + } + + protected boolean containsSKAlg(int pkeskVersion) + { + return pkeskVersion != PublicKeyEncSessionPacket.VERSION_6; + } + + protected static void checkRange(int pLen, byte[] enc) + throws PGPException + { + if (pLen > enc.length) + { + throw new PGPException("encoded length out of range"); + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEDataDecryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEDataDecryptorFactory.java index 0a4e7896b0..f88cda461e 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEDataDecryptorFactory.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEDataDecryptorFactory.java @@ -7,6 +7,8 @@ /** * A factory for performing PBE decryption operations. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation to use for symmetric decryption of SKESK (symmetric-key-encrypted session-key) packets. */ public abstract class PBEDataDecryptorFactory implements PGPDataDecryptorFactory diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEKeyEncryptionMethodGenerator.java index 48de87704b..f87ceb7f22 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBEKeyEncryptionMethodGenerator.java @@ -14,8 +14,7 @@ * PGP style PBE encryption method. *

      * A pass phrase is used to generate an encryption key using the PGP {@link S2K string-to-key} - * method. This class always uses the {@link S2K#SALTED_AND_ITERATED salted and iterated form of the - * S2K algorithm}. + * method. *

      * Note that the iteration count provided to this method is a single byte as described by the * {@link S2K} algorithm, and the actual iteration count ranges exponentially from @@ -23,7 +22,7 @@ *

      */ public abstract class PBEKeyEncryptionMethodGenerator - extends PGPKeyEncryptionMethodGenerator + implements PGPKeyEncryptionMethodGenerator { private char[] passPhrase; private PGPDigestCalculator s2kDigestCalculator; @@ -161,100 +160,90 @@ public byte[] getKey(int encAlgorithm) return PGPUtil.makeKeyFromPassPhrase(s2kDigestCalculator, encAlgorithm, s2k, passPhrase); } - @Override - public ContainedPacket generateV5(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException - { - return generate(kekAlgorithm, sessionInfo); - // TODO: Implement v5 SKESK creation properly. - // return generateV5ESK(kekAlgorithm, aeadAlgorithm, sessionInfo); - } - - @Override - public ContainedPacket generateV6(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException - { - return generateV6ESK(kekAlgorithm, aeadAlgorithm, sessionInfo); - } - - // If we use this method, roundtripping v5 AEAD is broken. - // TODO: Investigate - private ContainedPacket generateV5ESK(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException - { - byte[] ikm = getKey(kekAlgorithm); - byte[] info = new byte[] { - (byte) 0xC3, - (byte) SymmetricKeyEncSessionPacket.VERSION_5, - (byte) kekAlgorithm, - (byte) aeadAlgorithm - }; - - byte[] iv = new byte[AEADUtils.getIVLength(aeadAlgorithm)]; - random.nextBytes(iv); - - int tagLen = AEADUtils.getAuthTagLength(aeadAlgorithm); - byte[] eskAndTag = getEskAndTag(kekAlgorithm, aeadAlgorithm, sessionInfo, ikm, iv, info); - byte[] esk = Arrays.copyOfRange(eskAndTag, 0, eskAndTag.length - tagLen); - byte[] tag = Arrays.copyOfRange(eskAndTag, esk.length, eskAndTag.length); - - return SymmetricKeyEncSessionPacket.createV5Packet(kekAlgorithm, aeadAlgorithm, iv, s2k, esk, tag); - } - - private ContainedPacket generateV6ESK(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException - { - byte[] ikm = getKey(kekAlgorithm); - byte[] info = new byte[] { - (byte) 0xC3, - (byte) SymmetricKeyEncSessionPacket.VERSION_6, - (byte) kekAlgorithm, - (byte) aeadAlgorithm - }; - byte[] kek = generateV6KEK(kekAlgorithm, ikm, info); - - byte[] iv = new byte[AEADUtils.getIVLength(aeadAlgorithm)]; - random.nextBytes(iv); - - int tagLen = AEADUtils.getAuthTagLength(aeadAlgorithm); - byte[] eskAndTag = getEskAndTag(kekAlgorithm, aeadAlgorithm, sessionInfo, kek, iv, info); - byte[] esk = Arrays.copyOfRange(eskAndTag, 0, eskAndTag.length - tagLen); - byte[] tag = Arrays.copyOfRange(eskAndTag, esk.length, eskAndTag.length); - - return SymmetricKeyEncSessionPacket.createV6Packet(kekAlgorithm, aeadAlgorithm, iv, s2k, esk, tag); - } - /** - * Generate a V4 SKESK packet. + * Generates a version 4 Symmetric-Key-Encrypted-Session-Key (SKESK) packet, encoding the encrypted + * session-key for this method. + * SKESKv4 packets are used by Symmetrically-Encrypted-Integrity-Protected-Data (SEIPD) packets + * of version 1, or by (deprecated) Symmetrically-Encrypted-Data (SED) packets. + *

      + * Generates a version 5 Symmetric-Key-Encrypted-Session-Key (SKESK) packet, encoding the encrypted + * session-key for this method. + * SKESKv5 packets are used with {@link org.bouncycastle.bcpg.AEADEncDataPacket OCB-Encrypted Data (OED) packets} + * only. + * AEAD algorithm ID (MUST be {@link org.bouncycastle.bcpg.AEADAlgorithmTags#OCB}) + *

      + * Generates a version 6 Symmetric-Key-Encrypted-Session-Key (SKESK) packet, encoding the encrypted + * session-key for this method. + * SKESKv6 packets are used with Symmetrically-Encrypted Integrity-Protected Data (SEIPD) packets of + * version 2 only. + * A SKESKv6 packet MUST NOT precede a SEIPDv1, OED or SED packet. * - * @param encAlgorithm the {@link SymmetricKeyAlgorithmTags encryption algorithm} being used - * @param sessionInfo session data generated by the encrypted data generator. - * @return v4 SKESK packet - * @throws PGPException + * @param sessionKey session data generated by the encrypted data generator. + * @return a packet encoding the provided information and the configuration of this instance. + * @throws PGPException if an error occurs constructing the packet. + * @see + * RFC9580 - Symmetric-Key Encrypted Session-Key Packet version 4 + * @see + * LibrePGP - Symmetric-Key Encrypted Session-Key Packet version 5 + * @see + * RFC9580 - Symmetric-Key Encrypted Session-Key Packet version 6 */ - public ContainedPacket generate(int encAlgorithm, byte[] sessionInfo) + public ContainedPacket generate(PGPDataEncryptorBuilder dataEncryptorBuilder, byte[] sessionKey) throws PGPException { - if (sessionInfo == null) + int kekAlgorithm = getSessionKeyWrapperAlgorithm(dataEncryptorBuilder.getAlgorithm()); + if (dataEncryptorBuilder.getAeadAlgorithm() <= 0) { - return SymmetricKeyEncSessionPacket.createV4Packet(encAlgorithm, s2k, null); + if (sessionKey == null) + { + return SymmetricKeyEncSessionPacket.createV4Packet(kekAlgorithm, s2k, null); + } + + byte[] key = getKey(kekAlgorithm); + + return SymmetricKeyEncSessionPacket.createV4Packet(kekAlgorithm, s2k, encryptSessionInfo(kekAlgorithm, key, + Arrays.prepend(sessionKey, (byte)dataEncryptorBuilder.getAlgorithm()))); } + else + { + int aeadAlgorithm = dataEncryptorBuilder.getAeadAlgorithm(); + int version = dataEncryptorBuilder.isV5StyleAEAD() ? SymmetricKeyEncSessionPacket.VERSION_5 : SymmetricKeyEncSessionPacket.VERSION_6; + byte[] ikm = getKey(kekAlgorithm); + byte[] info = new byte[]{ + (byte)0xC3, + (byte)version, + (byte)kekAlgorithm, + (byte)aeadAlgorithm + }; + + if (version == 6) + { + ikm = generateV6KEK(kekAlgorithm, ikm, info); // ikm is kek + } - byte[] key = getKey(encAlgorithm); - // - // the passed in session info has the an RSA/ElGamal checksum added to it, for PBE this is not included. - // - byte[] nSessionInfo = new byte[sessionInfo.length - 2]; + byte[] iv = new byte[AEADUtils.getIVLength(aeadAlgorithm)]; + random.nextBytes(iv); - System.arraycopy(sessionInfo, 0, nSessionInfo, 0, nSessionInfo.length); + int tagLen = AEADUtils.getAuthTagLength(aeadAlgorithm); + byte[] eskAndTag = getEskAndTag(kekAlgorithm, aeadAlgorithm, sessionKey, ikm, iv, info); + byte[] esk = Arrays.copyOfRange(eskAndTag, 0, eskAndTag.length - tagLen); + byte[] tag = Arrays.copyOfRange(eskAndTag, esk.length, eskAndTag.length); - return SymmetricKeyEncSessionPacket.createV4Packet(encAlgorithm, s2k, encryptSessionInfo(encAlgorithm, key, nSessionInfo)); + if (version == SymmetricKeyEncSessionPacket.VERSION_5) + { + return SymmetricKeyEncSessionPacket.createV5Packet(kekAlgorithm, aeadAlgorithm, iv, s2k, esk, tag); + } + else + { + return SymmetricKeyEncSessionPacket.createV6Packet(kekAlgorithm, aeadAlgorithm, iv, s2k, esk, tag); + } + } } abstract protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] sessionInfo) throws PGPException; - abstract protected byte[] getEskAndTag(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo, byte[] key, byte[] iv, byte[] info) + abstract protected byte[] getEskAndTag(int kekAlgorithm, int aeadAlgorithm, byte[] sessionKey, byte[] key, byte[] iv, byte[] info) throws PGPException; abstract protected byte[] generateV6KEK(int kekAlgorithm, byte[] ikm, byte[] info) diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptor.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptor.java index 290fa1ec0d..c4cfbc09f1 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptor.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptor.java @@ -28,4 +28,15 @@ public byte[] makeKeyFromPassPhrase(int keyAlgorithm, S2K s2k) public abstract byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen) throws PGPException; + + public abstract byte[] recoverKeyData( + int encAlgorithm, + int aeadAlgorithm, + byte[] s2kKey, + byte[] iv, + int packetTag, + int keyVersion, + byte[] keyData, + byte[] pubkeyData) + throws PGPException; } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptorBuilder.java new file mode 100644 index 0000000000..b19389b50e --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptorBuilder.java @@ -0,0 +1,9 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.openpgp.PGPException; + +public interface PBESecretKeyDecryptorBuilder +{ + PBESecretKeyDecryptor build(char[] passphrase) + throws PGPException; +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptorBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptorBuilderProvider.java new file mode 100644 index 0000000000..e94ddb551b --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyDecryptorBuilderProvider.java @@ -0,0 +1,15 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.openpgp.PGPException; + +/** + * Provider for {@link PBESecretKeyDecryptorBuilder} instances. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation of {@link PBESecretKeyDecryptorBuilder} (builder for objects that can unlock encrypted + * secret keys) to return. + */ +public interface PBESecretKeyDecryptorBuilderProvider +{ + PBESecretKeyDecryptorBuilder provide() + throws PGPException; +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptor.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptor.java index 02edcf5ede..ee4678cca7 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptor.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptor.java @@ -5,9 +5,56 @@ import org.bouncycastle.bcpg.S2K; import org.bouncycastle.openpgp.PGPException; +/** + * Class responsible for encrypting secret key material or data packets using a passphrase. + *

      + * RFC9580 recommends the following S2K specifiers + usages: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
      S2K SpecifierS2K UsageNote
      {@link S2K#ARGON_2}{@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_AEAD}RECOMMENDED; Argon2 MUST be used with AEAD
      {@link S2K#SALTED_AND_ITERATED}{@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_SHA1}MAY be used if Argon2 is not available; Take care to use high octet count + strong passphrase
      none{@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_NONE}Unprotected
      + *

      + * Additionally, implementations MAY use the following combinations with caution: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
      S2K SpecifierS2K UsageNote
      {@link S2K#SALTED_AND_ITERATED}{@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_AEAD}Does not provide memory hardness
      {@link S2K#SIMPLE}{@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_SHA1}Only for reading secret keys in backwards compatibility mode
      + */ public abstract class PBESecretKeyEncryptor { protected int encAlgorithm; + protected int aeadAlgorithm; protected char[] passPhrase; protected PGPDigestCalculator s2kDigestCalculator; protected int s2kCount; @@ -15,6 +62,15 @@ public abstract class PBESecretKeyEncryptor protected SecureRandom random; + protected PBESecretKeyEncryptor(int encAlgorithm, int aeadAlgorithm, S2K.Argon2Params argon2Params, SecureRandom random, char[] passPhrase) + { + this.encAlgorithm = encAlgorithm; + this.aeadAlgorithm = aeadAlgorithm; + this.passPhrase = passPhrase; + this.s2k = S2K.argon2S2K(argon2Params); + this.random = random; + } + protected PBESecretKeyEncryptor(int encAlgorithm, PGPDigestCalculator s2kDigestCalculator, SecureRandom random, char[] passPhrase) { this(encAlgorithm, s2kDigestCalculator, 0x60, random, passPhrase); @@ -40,6 +96,11 @@ public int getAlgorithm() return encAlgorithm; } + public int getAeadAlgorithm() + { + return aeadAlgorithm; + } + public int getHashAlgorithm() { if (s2kDigestCalculator != null) @@ -65,8 +126,8 @@ public S2K getS2K() * Key encryption method invoked for V4 keys and greater. * * @param keyData raw key data - * @param keyOff offset into raw key data - * @param keyLen length of key data to use. + * @param keyOff offset into raw key data + * @param keyLen length of key data to use. * @return an encryption of the passed in keyData. * @throws PGPException on error in the underlying encryption process. */ diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptorFactory.java new file mode 100644 index 0000000000..89f50b98c6 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PBESecretKeyEncryptorFactory.java @@ -0,0 +1,21 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.bcpg.PublicKeyPacket; + +/** + * Factory class for password-based secret key encryptors. + * A concrete implementation of this class can not only choose the cryptographic backend (e.g. BC, JCA/JCE), + * but also, whether to use AEAD (RFC9580) or classic CFB (RFC4880). + */ +public interface PBESecretKeyEncryptorFactory +{ + + /** + * Build a new {@link PBESecretKeyEncryptor} instance from the given passphrase and public key packet. + * + * @param passphrase passphrase + * @param pubKeyPacket public-key packet of the key to protect (needed for AEAD) + * @return key encryptor + */ + PBESecretKeyEncryptor build(char[] passphrase, PublicKeyPacket pubKeyPacket); +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPAEADDataEncryptor.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPAEADDataEncryptor.java index a2985263f3..6d791c992e 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPAEADDataEncryptor.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPAEADDataEncryptor.java @@ -4,8 +4,7 @@ /** * A data encryptor, using AEAD. * There are two different flavours of AEAD encryption used with OpenPGP. - * OpenPGP v5 AEAD is slightly different from v6 AEAD. - *

      + * LibrePGP (v5) AEAD is slightly different from RFC9580 (v6) AEAD. * {@link PGPAEADDataEncryptor} instances are generally not constructed directly, but obtained from a * {@link PGPDataEncryptorBuilder}. *

      diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilder.java index 1ab0c0d141..5bd5db2c6a 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilder.java @@ -3,6 +3,11 @@ import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPrivateKey; +/** + * Builder for {@link PGPContentSigner} objects. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation to use for the {@link PGPContentSigner}. + */ public interface PGPContentSignerBuilder { PGPContentSigner build(final int signatureType, final PGPPrivateKey privateKey) diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilderProvider.java new file mode 100644 index 0000000000..154006b961 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentSignerBuilderProvider.java @@ -0,0 +1,30 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.openpgp.PGPPublicKey; + +/** + * Provider class for {@link PGPContentSignerBuilder} instances. + * Concrete implementations of this class can choose the cryptographic backend (BC, JCA/JCE). + */ +public abstract class PGPContentSignerBuilderProvider +{ + protected final int hashAlgorithmId; + + /** + * Constructor. + * + * @param hashAlgorithmId ID of the hash algorithm the {@link PGPContentSignerBuilder} shall use. + */ + public PGPContentSignerBuilderProvider(int hashAlgorithmId) + { + this.hashAlgorithmId = hashAlgorithmId; + } + + /** + * Return a new instance of the {@link PGPContentSignerBuilder} for the given signing key. + * + * @param signingKey public part of the signing key + * @return content signer builder + */ + public abstract PGPContentSignerBuilder get(PGPPublicKey signingKey); +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentVerifierBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentVerifierBuilderProvider.java index b501047252..b0d088ad62 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentVerifierBuilderProvider.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPContentVerifierBuilderProvider.java @@ -2,6 +2,12 @@ import org.bouncycastle.openpgp.PGPException; +/** + * Provider for {@link PGPContentVerifierBuilder} instances. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation of {@link PGPContentVerifierBuilder} (builder for objects check signatures for correctness) + * to provide. + */ public interface PGPContentVerifierBuilderProvider { PGPContentVerifierBuilder get(int keyAlgorithm, int hashAlgorithm) diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPDigestCalculatorProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPDigestCalculatorProvider.java index dcfce65c5b..c29afd7df6 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPDigestCalculatorProvider.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPDigestCalculatorProvider.java @@ -5,6 +5,8 @@ /** * A factory for digest algorithms. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation to use for calculating PGP digests. */ public interface PGPDigestCalculatorProvider { diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyConverter.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyConverter.java index ccdea777b4..f4b21852e9 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyConverter.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyConverter.java @@ -25,7 +25,8 @@ protected PGPKeyConverter() } /** - * Reference: RFC Draft-ietf-openpgp-crypto-refresh-13 + * Reference: + * RFC9580 - OpenPGP *

      * This class provides information about the recommended algorithms to use * depending on the key version and curve type in OpenPGP keys. @@ -74,6 +75,11 @@ protected PGPKeyConverter() * SHA2-256 * AES-128 * + * + * Curve448Legacy (not in RFC Draft) + * SHA2-512 + * AES-256 + * * */ protected PGPKdfParameters implGetKdfParameters(ASN1ObjectIdentifier curveID, PGPAlgorithmParameters algorithmParameters) @@ -89,7 +95,8 @@ else if (curveID.equals(SECObjectIdentifiers.secp384r1) || curveID.equals(TeleTr { return new PGPKdfParameters(HashAlgorithmTags.SHA384, SymmetricKeyAlgorithmTags.AES_192); } - else if (curveID.equals(SECObjectIdentifiers.secp521r1) || curveID.equals(TeleTrusTObjectIdentifiers.brainpoolP512r1)) + else if (curveID.equals(SECObjectIdentifiers.secp521r1) || curveID.equals(TeleTrusTObjectIdentifiers.brainpoolP512r1) + || curveID.equals(EdECObjectIdentifiers.id_X448)) { return new PGPKdfParameters(HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyEncryptionMethodGenerator.java index ece3ed58d7..28fc890a29 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyEncryptionMethodGenerator.java @@ -7,14 +7,9 @@ /** * An encryption method that can be applied to encrypt data in a {@link PGPEncryptedDataGenerator}. */ -public abstract class PGPKeyEncryptionMethodGenerator +public interface PGPKeyEncryptionMethodGenerator { - public abstract ContainedPacket generate(int encAlgorithm, byte[] sessionInfo) - throws PGPException; - - public abstract ContainedPacket generateV5(int encAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException; - public abstract ContainedPacket generateV6(int encAlgorithm, int aeadAlgorithm, byte[] sessionInfo) + ContainedPacket generate(PGPDataEncryptorBuilder dataEncryptorBuilder, byte[] sessionKey) throws PGPException; } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyPairGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyPairGenerator.java new file mode 100644 index 0000000000..2dc54f5c42 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyPairGenerator.java @@ -0,0 +1,293 @@ +package org.bouncycastle.openpgp.operator; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.sec.SECObjectIdentifiers; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Date; + +public abstract class PGPKeyPairGenerator +{ + + protected final Date creationTime; + protected final int version; + protected SecureRandom random; + protected final KeyFingerPrintCalculator fingerPrintCalculator; + + /** + * Create an instance of the key pair generator. + * + * @param version public key version ({@link org.bouncycastle.bcpg.PublicKeyPacket#VERSION_4} + * or {@link org.bouncycastle.bcpg.PublicKeyPacket#VERSION_6}). + * @param creationTime key creation time + * @param random secure random number generator + */ + public PGPKeyPairGenerator(int version, + Date creationTime, + SecureRandom random, + KeyFingerPrintCalculator fingerPrintCalculator) + { + this.creationTime = new Date((creationTime.getTime() / 1000) * 1000); + this.version = version; + this.random = random; + this.fingerPrintCalculator = fingerPrintCalculator; + } + + /** + * Generate a primary key. + * A primary key MUST use a signing-capable public key algorithm. + * + * @return primary key pair + * @throws PGPException if the key pair cannot be generated + */ + public PGPKeyPair generatePrimaryKey() + throws PGPException + { + return generateEd25519KeyPair(); + } + + /** + * Generate an encryption subkey. + * An encryption subkey MUST use an encryption-capable public key algorithm. + * + * @return encryption subkey pair + * @throws PGPException if the key pair cannot be generated + */ + public PGPKeyPair generateEncryptionSubkey() + throws PGPException + { + return generateX25519KeyPair().asSubkey(fingerPrintCalculator); + } + + /** + * Generate a signing subkey. + * A signing subkey MUST use a signing-capable public key algorithm. + * + * @return signing subkey pair + * @throws PGPException if the key pair cannot be generated + */ + public PGPKeyPair generateSigningSubkey() + throws PGPException + { + return generateEd25519KeyPair().asSubkey(fingerPrintCalculator); + } + + /** + * Generate a RSA key pair with the given bit-strength. + * It is recommended to use at least 2048 bits or more. + * The key will be generated over the default exponent

      65537
      . + * RSA keys are deprecated for OpenPGP v6. + * + * @param bitStrength strength of the key pair in bits + * @return rsa key pair + * @throws PGPException if the key pair cannot be generated + */ + public PGPKeyPair generateRsaKeyPair(int bitStrength) + throws PGPException + { + return generateRsaKeyPair(BigInteger.valueOf(0x10001), bitStrength); + } + + /** + * Generate a RSA key pair with the given bit-strength over a custom exponent. + * It is recommended to use at least 2048 bits or more. + * RSA keys are deprecated for OpenPGP v6. + * + * @param exponent RSA exponent
      e
      + * @param bitStrength strength of the key pair in bits + * @return rsa key pair + * @throws PGPException if the key pair cannot be generated + */ + public abstract PGPKeyPair generateRsaKeyPair(BigInteger exponent, int bitStrength) + throws PGPException; + + /** + * Generate an elliptic curve signing key over the twisted Edwards curve25519. + * The key will use {@link PublicKeyAlgorithmTags#Ed25519} which was introduced with RFC9580. + * For legacy Ed25519 keys use {@link #generateLegacyEd25519KeyPair()}. + * + * @return Ed25519 key pair + * @throws PGPException if the key pair cannot be generated + * @see + * RFC9580 - Public Key Algorithms + */ + public abstract PGPKeyPair generateEd25519KeyPair() + throws PGPException; + + /** + * Generate an elliptic curve signing key over the twisted Edwards curve448. + * The key will use {@link PublicKeyAlgorithmTags#Ed448} which was introduced with RFC9580. + * + * @return Ed448 signing key pair + * @throws PGPException if the key pair cannot be generated + * @see + * RFC9580 - Public Key Algorithms + */ + public abstract PGPKeyPair generateEd448KeyPair() + throws PGPException; + + /** + * Generate an elliptic curve Diffie-Hellman encryption key over curve25519. + * THe key will use {@link PublicKeyAlgorithmTags#X25519} which was introduced with RFC9580. + * For legacy X25519 keys use {@link #generateLegacyX25519KeyPair()} instead. + * + * @return X25519 encryption key pair + * @throws PGPException if the key pair cannot be generated + * @see + * RFC9580 - Public Key Algorithms + */ + public abstract PGPKeyPair generateX25519KeyPair() + throws PGPException; + + /** + * Generate an elliptic curve Diffie-Hellman encryption key over curve448. + * THe key will use {@link PublicKeyAlgorithmTags#X448} which was introduced with RFC9580. + * + * @return X448 encryption key pair + * @throws PGPException if the key pair cannot be generated + * @see + * RFC9580 - Public Key Algorithms + */ + public abstract PGPKeyPair generateX448KeyPair() + throws PGPException; + + /** + * Generate a legacy elliptic curve signing key pair over the twisted Edwards curve25519. + * Legacy keys have good application support, but MUST NOT be used as OpenPGP v6 keys. + * The key will use {@link PublicKeyAlgorithmTags#EDDSA_LEGACY} as algorithm ID. + * For OpenPGP v6 (RFC9580) use {@link #generateEd25519KeyPair()} instead. + * + * @return legacy Ed25519 key pair + * @throws PGPException if the key pair cannot be generated + * @see + * Legacy Draft: EdDSA for OpenPGP + */ + public abstract PGPKeyPair generateLegacyEd25519KeyPair() + throws PGPException; + + /** + * Generate a legacy elliptic curve Diffie-Hellman encryption key pair over curve25519. + * Legacy keys have good application support, but MUST NOT be used as OpenPGP v6 keys. + * The key will use {@link PublicKeyAlgorithmTags#ECDH} as algorithm ID. + * For OpenPGP v6 (RFC9580) use {@link #generateX25519KeyPair()} instead. + * + * @return legacy X25519 key pair + * @throws PGPException if the key pair cannot be generated + */ + public abstract PGPKeyPair generateLegacyX25519KeyPair() + throws PGPException; + + /** + * Generate an ECDH elliptic curve encryption key over the NIST p-256 curve. + * + * @return NIST p-256 ECDSA encryption key pair + * @throws PGPException if the key pair cannot be generated + * + * @see + * RFC6637 - Elliptic Curve Cryptography in OpenPGP + */ + public PGPKeyPair generateNistP256ECDHKeyPair() + throws PGPException + { + return generateECDHKeyPair(SECObjectIdentifiers.secp256r1); + } + + /** + * Generate an ECDH elliptic curve encryption key over the NIST p-384 curve. + * + * @return NIST p-384 ECDSA encryption key pair + * @throws PGPException if the key pair cannot be generated + * + * @see + * RFC6637 - Elliptic Curve Cryptography in OpenPGP + */ + public PGPKeyPair generateNistP384ECDHKeyPair() + throws PGPException + { + return generateECDHKeyPair(SECObjectIdentifiers.secp384r1); + } + + /** + * Generate an ECDH elliptic curve encryption key over the NIST p-521 curve. + * + * @return NIST p-521 ECDSA encryption key pair + * @throws PGPException if the key pair cannot be generated + * + * @see + * RFC6637 - Elliptic Curve Cryptography in OpenPGP + */ + public PGPKeyPair generateNistP521ECDHKeyPair() + throws PGPException + { + return generateECDHKeyPair(SECObjectIdentifiers.secp521r1); + } + + /** + * Generate an ECDSA elliptic curve signing key over the NIST p-256 curve. + * + * @return NIST p-256 ECDSA signing key pair + * @throws PGPException if the key pair cannot be generated + * + * @see + * RFC6637 - Elliptic Curve Cryptography in OpenPGP + */ + public PGPKeyPair generateNistP256ECDSAKeyPair() + throws PGPException + { + return generateECDSAKeyPair(SECObjectIdentifiers.secp256r1); + } + + /** + * Generate an ECDSA elliptic curve signing key over the NIST p-384 curve. + * + * @return NIST p-384 ECDSA signing key pair + * @throws PGPException if the key pair cannot be generated + * + * @see + * RFC6637 - Elliptic Curve Cryptography in OpenPGP + */ + public PGPKeyPair generateNistP384ECDSAKeyPair() + throws PGPException + { + return generateECDSAKeyPair(SECObjectIdentifiers.secp384r1); + } + + /** + * Generate an ECDSA elliptic curve signing key over the NIST p-521 curve. + * + * @return NIST p-521 ECDSA signing key pair + * @throws PGPException if the key pair cannot be generated + * + * @see + * RFC6637 - Elliptic Curve Cryptography in OpenPGP + */ + public PGPKeyPair generateNistP521ECDSAKeyPair() + throws PGPException + { + return generateECDSAKeyPair(SECObjectIdentifiers.secp521r1); + } + + /** + * Generate an elliptic curve Diffie-Hellman encryption key pair over the curve identified by the given OID. + * + * @param curveOID OID of the elliptic curve + * @return PGP key pair + * @throws PGPException if the key pair cannot be generated + */ + public abstract PGPKeyPair generateECDHKeyPair(ASN1ObjectIdentifier curveOID) + throws PGPException; + + /** + * Generate an elliptic curve signing key over the curve identified by the given OID. + * + * @param curveOID OID of the elliptic curve + * @return PGP key pair + * @throws PGPException if the key pair cannot be generated + */ + public abstract PGPKeyPair generateECDSAKeyPair(ASN1ObjectIdentifier curveOID) + throws PGPException; +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyPairGeneratorProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyPairGeneratorProvider.java new file mode 100644 index 0000000000..9b403f9334 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPKeyPairGeneratorProvider.java @@ -0,0 +1,8 @@ +package org.bouncycastle.openpgp.operator; + +import java.util.Date; + +public abstract class PGPKeyPairGeneratorProvider +{ + public abstract PGPKeyPairGenerator get(int version, Date creationTime); +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPUtil.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPUtil.java index 8d8e23b0d5..2d77e5d9a1 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPUtil.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PGPUtil.java @@ -94,6 +94,7 @@ else if (s2k.getHashAlgorithm() != digestCalculator.getAlgorithm()) try { + byte[] iv = s2k != null? s2k.getIV() : null; while (generatedBytes < keyBytes.length) { if (s2k != null) @@ -103,8 +104,6 @@ else if (s2k.getHashAlgorithm() != digestCalculator.getAlgorithm()) dOut.write(0); } - byte[] iv = s2k.getIV(); - switch (s2k.getType()) { case S2K.SIMPLE: diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyDataDecryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyDataDecryptorFactory.java index 1d358ff4e2..ede6f15f40 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyDataDecryptorFactory.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyDataDecryptorFactory.java @@ -1,10 +1,59 @@ package org.bouncycastle.openpgp.operator; +import org.bouncycastle.bcpg.InputStreamPacket; +import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; import org.bouncycastle.openpgp.PGPException; +/** + * Factory for public-key based {@link PGPDataDecryptor PGPDataDecryptors}. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation to use to decrypt OpenPGP messages that were encrypted to a public-key. + */ public interface PublicKeyDataDecryptorFactory extends PGPDataDecryptorFactory { + /** + * Recover the plain session info by decrypting the encrypted session key. + * The session info ALWAYS has the symmetric algorithm ID prefixed, so the return value is: + *
      [sym-alg][session-key][checksum]?
      + * + * @param pkesk public-key encrypted session-key packet + * @param encData encrypted data (sed/seipd/oed) packet + * @return decrypted session info + * @throws PGPException + */ + byte[] recoverSessionData(PublicKeyEncSessionPacket pkesk, InputStreamPacket encData) + throws PGPException; + + /** + * Recover the plain session info by decrypting the encrypted session key. + * This method returns the decrypted session info as-is (without prefixing missing cipher algorithm), + * so the return value is: + *
      [sym-alg]?[session-key][checksum]?
      + * + * @deprecated use {@link #recoverSessionData(PublicKeyEncSessionPacket, InputStreamPacket)} instead. + * @param keyAlgorithm public key algorithm + * @param secKeyData encrypted session key data + * @return decrypted session info + * @throws PGPException + */ byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + throws PGPException; + + /** + * Recover the plain session info by decrypting the encrypted session key. + * This method returns the decrypted session info as-is (without prefixing missing cipher algorithm), + * so the return value is: + *
      [sym-alg]?[session-key][checksum]?
      + * + * @deprecated use {@link #recoverSessionData(PublicKeyEncSessionPacket, InputStreamPacket)} instead. + * @param keyAlgorithm public key algorithm + * @param secKeyData encrypted session key data + * @param pkeskVersion version of the PKESK packet + * @return decrypted session info + * @throws PGPException + */ + byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData, int pkeskVersion) throws PGPException; + } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyKeyEncryptionMethodGenerator.java index 0d9b46ca6a..4893e7fe36 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/PublicKeyKeyEncryptionMethodGenerator.java @@ -11,11 +11,21 @@ import java.io.IOException; import java.math.BigInteger; +/** + * Abstract generator class for encryption methods that produce PKESK (public-key encrypted session key) packets. + * PKESKs are used when encrypting a message for a recipients public key. + * The purpose of this class is to allow subclasses to decide, which implementation to use. + */ public abstract class PublicKeyKeyEncryptionMethodGenerator - extends PGPKeyEncryptionMethodGenerator + implements PGPKeyEncryptionMethodGenerator { public static final String SESSION_KEY_OBFUSCATION_PROPERTY = "org.bouncycastle.openpgp.session_key_obfuscation"; + public static final long WILDCARD_KEYID = 0L; + /** + * @deprecated use WILDCARD_KEYID + */ public static final long WILDCARD = 0L; + public static final byte[] WILDCARD_FINGERPRINT = new byte[0]; private static boolean getSessionKeyObfuscationDefault() { @@ -23,10 +33,10 @@ private static boolean getSessionKeyObfuscationDefault() return !Properties.isOverrideSetTo(SESSION_KEY_OBFUSCATION_PROPERTY, false); } - private PGPPublicKey pubKey; + private final PGPPublicKey pubKey; protected boolean sessionKeyObfuscation; - protected boolean useWildcardKeyID; + protected boolean useWildcardRecipient; protected PublicKeyKeyEncryptionMethodGenerator( PGPPublicKey pubKey) @@ -62,7 +72,8 @@ protected PublicKeyKeyEncryptionMethodGenerator( /** * Controls whether to obfuscate the size of ECDH session keys using extra padding where necessary. *

      - * The default behaviour can be configured using the system property "", or else it will default to enabled. + * The default behaviour can be configured using the system property + * "org.bouncycastle.openpgp.session_key_obfuscation", or else it will default to enabled. *

      * * @return the current generator. @@ -75,19 +86,32 @@ public PublicKeyKeyEncryptionMethodGenerator setSessionKeyObfuscation(boolean en } /** - * Controls whether the recipient key ID is hidden (replaced by a wildcard ID
      0
      ). + * Controls whether the recipient key ID/fingerprint is hidden (replaced by a wildcard value). * * @param enabled boolean * @return this + * @deprecated use {@link #setUseWildcardRecipient(boolean)} instead + * TODO: Remove in a future release */ + @Deprecated public PublicKeyKeyEncryptionMethodGenerator setUseWildcardKeyID(boolean enabled) { - this.useWildcardKeyID = enabled; + return setUseWildcardRecipient(enabled); + } + /** + * Controls whether the recipient key ID/fingerprint is hidden (replaced by a wildcard value). + * + * @param enabled boolean + * @return this + */ + public PublicKeyKeyEncryptionMethodGenerator setUseWildcardRecipient(boolean enabled) + { + this.useWildcardRecipient = enabled; return this; } - public byte[][] processSessionInfo( + public byte[][] encodeEncryptedSessionInfo( byte[] encryptedSessionInfo) throws PGPException { @@ -140,59 +164,130 @@ private byte[] convertToEncodedMPI(byte[] encryptedSessionInfo) } } - public ContainedPacket generate(int encAlgorithm, byte[] sessionInfo) + /** + * Generate a Public-Key Encrypted Session-Key (PKESK) packet of version 3. + * PKESKv3 packets are used with Symmetrically-Encrypted-Integrity-Protected Data (SEIPD) packets of + * version 1 or with Symmetrically-Encrypted Data (SED) packets and MUST NOT be used with SEIPDv2 packets. + * PKESKv3 packets are used with keys that do not support {@link org.bouncycastle.bcpg.sig.Features#FEATURE_SEIPD_V2} + * or as a fallback. + *

      + * Generate a Public-Key Encrypted Session-Key (PKESK) packet of version 6. + * PKESKv6 packets are used with Symmetrically-Encrypted Integrity-Protected Data (SEIPD) packets + * of version 2 only. + * PKESKv6 packets are used with keys that support {@link org.bouncycastle.bcpg.sig.Features#FEATURE_SEIPD_V2}. + * + * @param sessionKey session-key algorithm id + session-key + checksum + * @return PKESKv6 or v3 packet + * @throws PGPException if the PKESK packet cannot be generated + * @see + * RFC9580 - Version 6 Public Key Encrypted Session Key Packet + * @see + * RFC9580 - Version 3 Public Key Encrypted Session Key Packet + */ + public ContainedPacket generate(PGPDataEncryptorBuilder dataEncryptorBuilder, byte[] sessionKey) throws PGPException { - long keyId; - if (useWildcardKeyID) + if (dataEncryptorBuilder.getAeadAlgorithm() <= 0 || dataEncryptorBuilder.isV5StyleAEAD()) { - keyId = WILDCARD; + long keyId; + if (useWildcardRecipient) + { + keyId = WILDCARD_KEYID; + } + else + { + keyId = pubKey.getKeyID(); + } + byte[] encryptedSessionInfo = encryptSessionInfo(pubKey, sessionKey, (byte)dataEncryptorBuilder.getAlgorithm(), true); + byte[][] encodedEncSessionInfo = encodeEncryptedSessionInfo(encryptedSessionInfo); + return PublicKeyEncSessionPacket.createV3PKESKPacket(keyId, pubKey.getAlgorithm(), encodedEncSessionInfo); } else { - keyId = pubKey.getKeyID(); + byte[] keyFingerprint; + int keyVersion; + if (useWildcardRecipient) + { + keyFingerprint = WILDCARD_FINGERPRINT; + keyVersion = 0; + } + else + { + keyFingerprint = pubKey.getFingerprint(); + keyVersion = pubKey.getVersion(); + } + // In V6, do not include the symmetric-key algorithm in the session-info + + byte[] encryptedSessionInfo = encryptSessionInfo(pubKey, sessionKey, (byte)dataEncryptorBuilder.getAlgorithm(), false); + byte[][] encodedEncSessionInfo = encodeEncryptedSessionInfo(encryptedSessionInfo); + return PublicKeyEncSessionPacket.createV6PKESKPacket(keyVersion, keyFingerprint, pubKey.getAlgorithm(), encodedEncSessionInfo); } - return PublicKeyEncSessionPacket.createV3PKESKPacket(keyId, pubKey.getAlgorithm(), processSessionInfo(encryptSessionInfo(pubKey, sessionInfo))); } - @Override - public ContainedPacket generateV5(int encAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException + protected byte[] createSessionInfo( + byte algorithm, + byte[] keyBytes) { - // TODO: Implement - return null; + byte[] sessionInfo; + if (algorithm != 0) + { + sessionInfo = new byte[keyBytes.length + 3]; + sessionInfo[0] = algorithm; + System.arraycopy(keyBytes, 0, sessionInfo, 1, keyBytes.length); + addCheckSum(sessionInfo, 1); + } + else + { + sessionInfo = new byte[keyBytes.length + 2]; + System.arraycopy(keyBytes, 0, sessionInfo, 0, keyBytes.length); + addCheckSum(sessionInfo, 0); + } + return sessionInfo; } - @Override - public ContainedPacket generateV6(int encAlgorithm, int aeadAlgorithm, byte[] sessionInfo) - throws PGPException + private void addCheckSum(byte[] sessionInfo, int pos) { - // TODO: Implement - return null; - } + int check = 0; - abstract protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo) - throws PGPException; - - protected static byte[] getSessionInfo(byte[] ephPubEncoding, byte[] c) - throws IOException - { - byte[] VB = new MPInteger(new BigInteger(1, ephPubEncoding)).getEncoded(); + for (int i = pos; i != sessionInfo.length - 2; i++) + { + check += sessionInfo[i] & 0xff; + } - byte[] rv = new byte[VB.length + 1 + c.length]; - System.arraycopy(VB, 0, rv, 0, VB.length); - rv[VB.length] = (byte)c.length; - System.arraycopy(c, 0, rv, VB.length + 1, c.length); - return rv; + sessionInfo[sessionInfo.length - 2] = (byte)(check >> 8); + sessionInfo[sessionInfo.length - 1] = (byte)(check); } - protected static byte[] getSessionInfo(byte[] VB, int sysmmetricKeyAlgorithm, byte[] c) + /** + * Encrypt a session key using the recipients public key. + * + * @param pubKey recipients public key + * @param sessionKey session-key + * @param symAlgId for v3: session key algorithm ID; for v6: 0 + * @return encrypted session info + * @throws PGPException + */ + protected abstract byte[] encryptSessionInfo(PGPPublicKey pubKey, + byte[] sessionKey, + byte symAlgId, + boolean isV3) + throws PGPException; + + protected static byte[] getSessionInfo(byte[] ephPubEncoding, byte optSymKeyAlgorithm, byte[] wrappedSessionKey) { - byte[] rv = new byte[VB.length + 2 + c.length]; - System.arraycopy(VB, 0, rv, 0, VB.length); - rv[VB.length] = (byte)(c.length + 1); - rv[VB.length + 1] = (byte)sysmmetricKeyAlgorithm; - System.arraycopy(c, 0, rv, VB.length + 2, c.length); - return rv; + int len = ephPubEncoding.length + wrappedSessionKey.length + (optSymKeyAlgorithm == 0 ? 1 : 2); + byte[] out = new byte[len]; + // ephemeral pub key + System.arraycopy(ephPubEncoding, 0, out, 0, ephPubEncoding.length); + // len of two/one next fields + out[ephPubEncoding.length] = (byte)(len - ephPubEncoding.length - 1); + // sym key alg + if (optSymKeyAlgorithm != 0) + { + out[ephPubEncoding.length + 1] = optSymKeyAlgorithm; + } + // wrapped session key + System.arraycopy(wrappedSessionKey, 0, out, len - wrappedSessionKey.length, wrappedSessionKey.length); + return out; } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/RFC6637Utils.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/RFC6637Utils.java index 4132038a39..416ac0459f 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/RFC6637Utils.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/RFC6637Utils.java @@ -4,6 +4,7 @@ import java.io.IOException; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.ntt.NTTObjectIdentifiers; import org.bouncycastle.bcpg.ECDHPublicBCPGKey; @@ -37,14 +38,15 @@ else if (pubKeyData.getKey() instanceof X448PublicBCPGKey) return "X448withSHA512CKDF"; } ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)pubKeyData.getKey(); + String curve = ecKey.getCurveOID().equals(EdECObjectIdentifiers.id_X448) ? "X448" : "X25519"; switch (ecKey.getHashAlgorithm()) { case HashAlgorithmTags.SHA256: - return "X25519withSHA256CKDF"; + return curve + "withSHA256CKDF"; case HashAlgorithmTags.SHA384: - return "X25519withSHA384CKDF"; + return curve + "withSHA384CKDF"; case HashAlgorithmTags.SHA512: - return "X25519withSHA512CKDF"; + return curve + "withSHA512CKDF"; default: throw new IllegalArgumentException("Unknown hash algorithm specified: " + ecKey.getHashAlgorithm()); } @@ -113,8 +115,15 @@ public static byte[] createUserKeyingMaterial(PublicKeyPacket pubKeyData, KeyFin pOut.write(ecKey.getHashAlgorithm()); pOut.write(ecKey.getSymmetricKeyAlgorithm()); pOut.write(ANONYMOUS_SENDER); - pOut.write(fingerPrintCalculator.calculateFingerprint(pubKeyData)); - + byte[] fp = fingerPrintCalculator.calculateFingerprint(pubKeyData); + if (pubKeyData.getVersion() == PublicKeyPacket.LIBREPGP_5) + { + pOut.write(fp, 0, 20); + } + else + { + pOut.write(fp); + } return pOut.toByteArray(); } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/SessionKeyDataDecryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/SessionKeyDataDecryptorFactory.java index e8f3f75917..8cff94ec4f 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/SessionKeyDataDecryptorFactory.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/SessionKeyDataDecryptorFactory.java @@ -2,6 +2,12 @@ import org.bouncycastle.openpgp.PGPSessionKey; +/** + * Factory for {@link PGPDataDecryptor} objects that use a {@link PGPSessionKey} to decrypt the content of an + * OpenPGP message. + * The purpose of this class is to act as an abstract factory, whose subclasses can decide, which concrete + * implementation to use for message decryption. + */ public interface SessionKeyDataDecryptorFactory extends PGPDataDecryptorFactory { diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorBuilder.java new file mode 100644 index 0000000000..0cc109e5f5 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorBuilder.java @@ -0,0 +1,77 @@ +package org.bouncycastle.openpgp.operator.bc; + +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.bcpg.AEADUtils; +import org.bouncycastle.bcpg.PacketTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.AEADSecretKeyEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; + +public class BcAEADSecretKeyEncryptorBuilder + implements AEADSecretKeyEncryptorBuilder +{ + private int aeadAlgorithm; + private int symmetricAlgorithm; + private S2K.Argon2Params argon2Params; + private SecureRandom random = new SecureRandom(); + + public BcAEADSecretKeyEncryptorBuilder(int aeadAlgorithm, int symmetricAlgorithm, S2K.Argon2Params argon2Params) + { + this.aeadAlgorithm = aeadAlgorithm; + this.symmetricAlgorithm = symmetricAlgorithm; + this.argon2Params = argon2Params; + } + + public BcAEADSecretKeyEncryptorBuilder setSecureRandom(SecureRandom random) + { + this.random = random; + return this; + } + + public PBESecretKeyEncryptor build(char[] passphrase, final PublicKeyPacket pubKey) + { + return new PBESecretKeyEncryptor(symmetricAlgorithm, aeadAlgorithm, argon2Params, random, passphrase) + { + private byte[] iv; + + { + iv = new byte[AEADUtils.getIVLength(aeadAlgorithm)]; + random.nextBytes(iv); + } + + @Override + public byte[] encryptKeyData(byte[] key, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + try + { + return BcAEADUtil.processAeadKeyData(true, + encAlgorithm, + aeadAlgorithm, + getKey(), + getCipherIV(), + pubKey.getPacketTag() == PacketTags.PUBLIC_KEY ? PacketTags.SECRET_KEY : PacketTags.SECRET_SUBKEY, + pubKey.getVersion(), + keyData, + keyOff, + keyLen, + pubKey.getEncodedContents()); + } + catch (IOException e) + { + throw new PGPException("Exception AEAD protecting private key material", e); + } + } + + @Override + public byte[] getCipherIV() + { + return iv; + } + }; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorFactory.java new file mode 100644 index 0000000000..3fa0dc0b27 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorFactory.java @@ -0,0 +1,34 @@ +package org.bouncycastle.openpgp.operator.bc; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; + +/** + * Return a factory for {@link PBESecretKeyEncryptor} instances which protect the secret key material by deriving + * a key-encryption-key using {@link org.bouncycastle.bcpg.S2K#ARGON_2} S2K and apply + * that key using {@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_AEAD}. + *

      + * This particular factory uses OCB + AES256 for secret key protection and requires 64MiB of RAM + * for the Argon2 key derivation (see {@link S2K.Argon2Params#memoryConstrainedParameters()}). + */ +public class BcAEADSecretKeyEncryptorFactory + implements PBESecretKeyEncryptorFactory +{ + @Override + public PBESecretKeyEncryptor build(char[] passphrase, PublicKeyPacket pubKeyPacket) + { + if (passphrase == null) + { + return null; + } + return new org.bouncycastle.openpgp.operator.bc.BcAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, + SymmetricKeyAlgorithmTags.AES_256, + S2K.Argon2Params.memoryConstrainedParameters()) + .build(passphrase, pubKeyPacket); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADUtil.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADUtil.java index f2cb8c4baf..a348c7b4ee 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADUtil.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcAEADUtil.java @@ -34,6 +34,9 @@ public class BcAEADUtil { + final static String RecoverAEADEncryptedSessionDataErrorMessage = "Exception recovering session info"; + private final static String ProcessAeadKeyDataErrorMessage = "Exception recovering AEAD protected private key material"; + final static String GetEskAndTagErrorMessage = "cannot encrypt session info"; /** * Generate a nonce by xor-ing the given iv with the chunk index. * @@ -91,21 +94,25 @@ protected static long getChunkLength(int chunkSize) * @param salt salt * @param hkdfInfo HKDF info * @return message key and separate IV - * @throws PGPException */ static byte[][] deriveMessageKeyAndIv(int aeadAlgo, int cipherAlgo, byte[] sessionKey, byte[] salt, byte[] hkdfInfo) - throws PGPException + { + int keyLen = SymmetricKeyUtils.getKeyLengthInOctets(cipherAlgo); + int ivLen = AEADUtils.getIVLength(aeadAlgo); + byte[] messageKeyAndIv = generateHKDFBytes(sessionKey, salt, hkdfInfo, keyLen + ivLen - 8); + + return new byte[][]{Arrays.copyOfRange(messageKeyAndIv, 0, keyLen), Arrays.copyOfRange(messageKeyAndIv, keyLen, keyLen + ivLen)}; + } + + static byte[] generateHKDFBytes(byte[] sessionKey, byte[] salt, byte[] hkdfInfo, int len) { HKDFParameters hkdfParameters = new HKDFParameters(sessionKey, salt, hkdfInfo); HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); hkdfGen.init(hkdfParameters); - int keyLen = SymmetricKeyUtils.getKeyLengthInOctets(cipherAlgo); - int ivLen = AEADUtils.getIVLength(aeadAlgo); - byte[] messageKeyAndIv = new byte[keyLen + ivLen - 8]; + byte[] messageKeyAndIv = new byte[len]; hkdfGen.generateBytes(messageKeyAndIv, 0, messageKeyAndIv.length); - - return new byte[][]{Arrays.copyOfRange(messageKeyAndIv, 0, keyLen), Arrays.copyOfRange(messageKeyAndIv, keyLen, keyLen + ivLen)}; + return messageKeyAndIv; } public static AEADBlockCipher createAEADCipher(int encAlgorithm, int aeadAlgorithm) @@ -271,6 +278,45 @@ public PGPDigestCalculator getIntegrityCalculator() }; } + static byte[] processAEADData(boolean forEncryption, int encAlgorithm, int aeadAlgorithm, byte[] key, byte[] iv, byte[] aad, byte[] msg, int off, int len, String errorMessage) + throws PGPException + { + AEADBlockCipher cipher = createAEADCipher(encAlgorithm, aeadAlgorithm); + try + { + return processAEADData(forEncryption, cipher, new KeyParameter(key), iv, aad, msg, off, len); + } + catch (InvalidCipherTextException e) + { + throw new PGPException(errorMessage, e); + } + } + + static byte[] processAEADData(boolean forEncryption, AEADBlockCipher cipher, KeyParameter key, byte[] iv, byte[] aad, byte[] msg, int off, int msgLen) + throws InvalidCipherTextException + { + cipher.init(forEncryption, new AEADParameters(key, 128, iv, aad)); + int dataLen = cipher.getOutputSize(msgLen); + byte[] data = new byte[dataLen]; + dataLen = cipher.processBytes(msg, off, msgLen, data, 0); + cipher.doFinal(data, dataLen); + return data; + } + + static byte[] processAeadKeyData(boolean forEncryption, int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, + int packetTag, int keyVersion, byte[] keyData, int keyOff, int keyLen, byte[] pubkeyData) + throws PGPException + { + byte[] key = generateHKDFBytes(s2kKey, + null, + new byte[]{ + (byte)(0xC0 | packetTag), (byte)keyVersion, (byte)encAlgorithm, (byte)aeadAlgorithm + }, + SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)); + byte[] aad = Arrays.prepend(pubkeyData, (byte)(0xC0 | packetTag)); + return processAEADData(forEncryption, encAlgorithm, aeadAlgorithm, key, iv, aad, keyData, keyOff, keyLen, ProcessAeadKeyDataErrorMessage); + } + protected static class PGPAeadInputStream extends InputStream { @@ -418,16 +464,10 @@ private byte[] readBlock() xorChunkId(adata, chunkIndex); } - byte[] decData = new byte[dataLen]; + byte[] decData; try { - c.init(false, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex))); // always full tag. - - c.processAADBytes(adata, 0, adata.length); - - int len = c.processBytes(buf, 0, dataLen + tagLen, decData, 0); - - c.doFinal(decData, len); + decData = processAEADData(false, c, secretKey, getNonce(iv, chunkIndex), adata, buf, 0, dataLen + tagLen); } catch (InvalidCipherTextException e) { @@ -445,9 +485,8 @@ private byte[] readBlock() try { - c.init(false, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex))); // always full tag. + c.init(false, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex), adata)); // always full tag. - c.processAADBytes(adata, 0, adata.length); if (isV5StyleAEAD) { c.processAADBytes(Pack.longToBigEndian(totalBytes), 0, 8); @@ -621,8 +660,7 @@ private void writeBlock() try { - c.init(true, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex))); // always full tag. - c.processAADBytes(adata, 0, adata.length); + c.init(true, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex), adata)); // always full tag. int len = c.processBytes(data, 0, dataOff, data, 0); out.write(data, 0, len); @@ -651,8 +689,8 @@ private void finish() byte[] adata = PGPAeadInputStream.getAdata(v5StyleAEAD, aaData, chunkIndex, totalBytes); try { - c.init(true, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex))); // always full tag. - c.processAADBytes(adata, 0, adata.length); + c.init(true, new AEADParameters(secretKey, 128, getNonce(iv, chunkIndex), adata)); // always full tag. + if (v5StyleAEAD) { c.processAADBytes(Pack.longToBigEndian(totalBytes), 0, 8); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcCFBSecretKeyEncryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcCFBSecretKeyEncryptorFactory.java new file mode 100644 index 0000000000..ccde1f85fa --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcCFBSecretKeyEncryptorFactory.java @@ -0,0 +1,55 @@ +package org.bouncycastle.openpgp.operator.bc; + +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; +import org.bouncycastle.openpgp.operator.PGPDigestCalculator; + +/** + * Return a factory for {@link PBESecretKeyEncryptor} instances which protect the secret key material by deriving + * a key-encryption-key using {@link org.bouncycastle.bcpg.S2K#SALTED_AND_ITERATED} S2K and apply + * that key using {@link org.bouncycastle.bcpg.SecretKeyPacket#USAGE_SHA1} (CFB mode). + *

      + * This particular factory derives a key-encryption-key via salted+iterated S2K derivation using SHA256 + * and uses AES256 for secret key protection. + */ +public class BcCFBSecretKeyEncryptorFactory + implements PBESecretKeyEncryptorFactory +{ + private final int symmetricKeyAlgorithm; + private final int iterationCount; + + public BcCFBSecretKeyEncryptorFactory(int symmetricKeyAlgorithm, + int iterationCount) + { + this.symmetricKeyAlgorithm = symmetricKeyAlgorithm; + this.iterationCount = iterationCount; + } + + @Override + public PBESecretKeyEncryptor build(char[] passphrase, PublicKeyPacket pubKeyPacket) + { + if (passphrase == null) + { + return null; + } + + PGPDigestCalculator checksumCalc; + try + { + checksumCalc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256); + } + catch (PGPException e) + { + throw new RuntimeException(e); // Does not happen in practice + } + + return new BcPBESecretKeyEncryptorBuilder( + symmetricKeyAlgorithm, + checksumCalc, + iterationCount) // MAX iteration count + .build(passphrase); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcImplProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcImplProvider.java index 02d456ea17..ee940d1d40 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcImplProvider.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcImplProvider.java @@ -33,6 +33,8 @@ import org.bouncycastle.crypto.engines.RFC3394WrapEngine; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.engines.TwofishEngine; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; import org.bouncycastle.crypto.signers.DSADigestSigner; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.crypto.signers.ECDSASigner; @@ -96,6 +98,11 @@ static Signer createSigner(int keyAlgorithm, int hashAlgorithm, CipherParameters case PublicKeyAlgorithmTags.ECDSA: return new DSADigestSigner(new ECDSASigner(), createDigest(hashAlgorithm)); case PublicKeyAlgorithmTags.EDDSA_LEGACY: + if (keyParam instanceof Ed25519PrivateKeyParameters || keyParam instanceof Ed25519PublicKeyParameters) + { + return new EdDsaSigner(new Ed25519Signer(), createDigest(hashAlgorithm)); + } + return new EdDsaSigner(new Ed448Signer(new byte[0]), createDigest(hashAlgorithm)); case PublicKeyAlgorithmTags.Ed25519: return new EdDsaSigner(new Ed25519Signer(), createDigest(hashAlgorithm)); case PublicKeyAlgorithmTags.Ed448: diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcKeyFingerprintCalculator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcKeyFingerprintCalculator.java index 11ec4901a2..9a4c7e2c07 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcKeyFingerprintCalculator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcKeyFingerprintCalculator.java @@ -23,7 +23,7 @@ public byte[] calculateFingerprint(PublicKeyPacket publicPk) BCPGKey key = publicPk.getKey(); Digest digest; - if (publicPk.getVersion() <= 3) + if (publicPk.getVersion() <= PublicKeyPacket.VERSION_3) { RSAPublicBCPGKey rK = (RSAPublicBCPGKey)key; @@ -42,7 +42,7 @@ public byte[] calculateFingerprint(PublicKeyPacket publicPk) throw new PGPException("can't encode key components: " + e.getMessage(), e); } } - else if (publicPk.getVersion() == 4) + else if (publicPk.getVersion() == PublicKeyPacket.VERSION_4) { try { @@ -60,14 +60,14 @@ else if (publicPk.getVersion() == 4) throw new PGPException("can't encode key components: " + e.getMessage(), e); } } - else if (publicPk.getVersion() == 6) + else if (publicPk.getVersion() == PublicKeyPacket.LIBREPGP_5 || publicPk.getVersion() == PublicKeyPacket.VERSION_6) { try { byte[] kBytes = publicPk.getEncodedContents(); digest = new SHA256Digest(); - digest.update((byte)0x9b); + digest.update((byte) (publicPk.getVersion() == PublicKeyPacket.VERSION_6 ? 0x9b : 0x9a)); digest.update((byte)(kBytes.length >> 24)); digest.update((byte)(kBytes.length >> 16)); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEDataDecryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEDataDecryptorFactory.java index 3dca31d018..ffc3dccb25 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEDataDecryptorFactory.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEDataDecryptorFactory.java @@ -5,20 +5,14 @@ import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket; import org.bouncycastle.bcpg.SymmetricKeyUtils; +import org.bouncycastle.bcpg.UnsupportedPacketVersionException; import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.BufferedBlockCipher; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.engines.CamelliaEngine; -import org.bouncycastle.crypto.generators.HKDFBytesGenerator; -import org.bouncycastle.crypto.modes.AEADBlockCipher; -import org.bouncycastle.crypto.params.AEADParameters; -import org.bouncycastle.crypto.params.HKDFParameters; -import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPSessionKey; import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory; import org.bouncycastle.openpgp.operator.PGPDataDecryptor; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.util.Arrays; /** * A {@link PBEDataDecryptorFactory} for handling PBE decryption operations using the Bouncy Castle @@ -33,7 +27,7 @@ public class BcPBEDataDecryptorFactory * @param pass the passphrase to use as the primary source of key material. * @param calculatorProvider a digest calculator provider to provide calculators to support the key generation calculation required. */ - public BcPBEDataDecryptorFactory(char[] pass, BcPGPDigestCalculatorProvider calculatorProvider) + public BcPBEDataDecryptorFactory(char[] pass, PGPDigestCalculatorProvider calculatorProvider) { super(pass, calculatorProvider); } @@ -57,15 +51,7 @@ public byte[] recoverSessionData(int keyAlgorithm, byte[] key, byte[] secKeyData if (secKeyData != null && secKeyData.length > 0) { BlockCipher engine = BcImplProvider.createBlockCipher(keyAlgorithm); - BufferedBlockCipher cipher = BcUtil.createSymmetricKeyWrapper(false, engine, key, new byte[engine.getBlockSize()]); - - byte[] out = new byte[secKeyData.length]; - - int len = cipher.processBytes(secKeyData, 0, secKeyData.length, out, 0); - - len += cipher.doFinal(out, len); - - return out; + return BcUtil.processBufferedBlockCipher(false, engine, key, new byte[engine.getBlockSize()], secKeyData, 0, secKeyData.length); } else { @@ -93,42 +79,30 @@ public byte[] recoverAEADEncryptedSessionData(SymmetricKeyEncSessionPacket keyDa } byte[] hkdfInfo = keyData.getAAData(); // Between v5 and v6, these bytes differ - int kekLen = SymmetricKeyUtils.getKeyLengthInOctets(keyData.getEncAlgorithm()); - byte[] kek = new byte[kekLen]; - // HKDF - // secretKey := HKDF_sha256(ikm, hkdfInfo).generate() - HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); - hkdfGen.init(new HKDFParameters(ikm, null, hkdfInfo)); - hkdfGen.generateBytes(kek, 0, kek.length); - final KeyParameter secretKey = new KeyParameter(kek); - - // AEAD - AEADBlockCipher aead = BcAEADUtil.createAEADCipher(keyData.getEncAlgorithm(), keyData.getAeadAlgorithm()); - int aeadMacLen = 128; - byte[] authTag = keyData.getAuthTag(); - byte[] aeadIv = keyData.getIv(); - byte[] encSessionKey = keyData.getSecKeyData(); - - // sessionData := AEAD(secretKey).decrypt(encSessionKey || authTag) - AEADParameters parameters = new AEADParameters(secretKey, - aeadMacLen, aeadIv, keyData.getAAData()); - aead.init(false, parameters); - int sessionKeyLen = aead.getOutputSize(encSessionKey.length + authTag.length); - byte[] sessionData = new byte[sessionKeyLen]; - int dataLen = aead.processBytes(encSessionKey, 0, encSessionKey.length, sessionData, 0); - dataLen += aead.processBytes(authTag, 0, authTag.length, sessionData, dataLen); - - try + byte[] kek; + if (keyData.getVersion() == SymmetricKeyEncSessionPacket.VERSION_5) { - aead.doFinal(sessionData, dataLen); + kek = ikm; } - catch (InvalidCipherTextException e) + else if (keyData.getVersion() == SymmetricKeyEncSessionPacket.VERSION_6) { - throw new PGPException("Exception recovering session info", e); + // HKDF + // secretKey := HKDF_sha256(ikm, hkdfInfo).generate() + int kekLen = SymmetricKeyUtils.getKeyLengthInOctets(keyData.getEncAlgorithm()); + kek = BcAEADUtil.generateHKDFBytes(ikm, null, hkdfInfo, kekLen); + } + else + { + throw new UnsupportedPacketVersionException("Unsupported SKESK packet version encountered: " + keyData.getVersion()); } - return sessionData; + // AEAD + // sessionData := AEAD(secretKey).decrypt(encSessionKey || authTag) + byte[] data = Arrays.concatenate(keyData.getSecKeyData(), keyData.getAuthTag()); + return BcAEADUtil.processAEADData(false, keyData.getEncAlgorithm(), keyData.getAeadAlgorithm(), kek, + keyData.getIv(), keyData.getAAData(), data, 0, data.length, + BcAEADUtil.RecoverAEADEncryptedSessionDataErrorMessage); } // OpenPGP v4 @@ -156,4 +130,4 @@ public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket seipd, P { return BcAEADUtil.createOpenPgpV6DataDecryptor(seipd, sessionKey); } -} +} \ No newline at end of file diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEKeyEncryptionMethodGenerator.java index 986fbcdfaf..76c08ba21a 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBEKeyEncryptionMethodGenerator.java @@ -5,15 +5,7 @@ import org.bouncycastle.bcpg.S2K; import org.bouncycastle.bcpg.SymmetricKeyUtils; import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.engines.CamelliaEngine; -import org.bouncycastle.crypto.generators.HKDFBytesGenerator; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.AEADParameters; -import org.bouncycastle.crypto.params.HKDFParameters; -import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator; import org.bouncycastle.openpgp.operator.PGPDigestCalculator; @@ -96,15 +88,7 @@ protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] session try { BlockCipher engine = BcImplProvider.createBlockCipher(encAlgorithm); - BufferedBlockCipher cipher = BcUtil.createSymmetricKeyWrapper(true, engine, key, new byte[engine.getBlockSize()]); - - byte[] out = new byte[sessionInfo.length]; - - int len = cipher.processBytes(sessionInfo, 0, sessionInfo.length, out, 0); - - len += cipher.doFinal(out, len); - - return out; + return BcUtil.processBufferedBlockCipher(true, engine, key, new byte[engine.getBlockSize()], sessionInfo, 0, sessionInfo.length); } catch (InvalidCipherTextException e) { @@ -113,36 +97,13 @@ protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] session } protected byte[] generateV6KEK(int kekAlgorithm, byte[] ikm, byte[] info) - throws PGPException { - HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest()); - hkdf.init(new HKDFParameters(ikm, null, info)); - - int kekLen = SymmetricKeyUtils.getKeyLengthInOctets(kekAlgorithm); - byte[] kek = new byte[kekLen]; - hkdf.generateBytes(kek, 0, kek.length); - return kek; + return BcAEADUtil.generateHKDFBytes(ikm, null, info, SymmetricKeyUtils.getKeyLengthInOctets(kekAlgorithm)); } - protected byte[] getEskAndTag(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo, byte[] key, byte[] iv, byte[] info) + protected byte[] getEskAndTag(int kekAlgorithm, int aeadAlgorithm, byte[] sessionKey, byte[] key, byte[] iv, byte[] info) throws PGPException { - byte[] sessionKey = new byte[sessionInfo.length - 3]; - System.arraycopy(sessionInfo, 1, sessionKey, 0, sessionKey.length); - - AEADCipher aeadCipher = BcAEADUtil.createAEADCipher(kekAlgorithm, aeadAlgorithm); - aeadCipher.init(true, new AEADParameters(new KeyParameter(key), 128, iv, info)); - int outLen = aeadCipher.getOutputSize(sessionKey.length); - byte[] eskAndTag = new byte[outLen]; - int len = aeadCipher.processBytes(sessionKey, 0, sessionKey.length, eskAndTag, 0); - try - { - len += aeadCipher.doFinal(eskAndTag, len); - } - catch (InvalidCipherTextException e) - { - throw new PGPException("cannot encrypt session info", e); - } - return eskAndTag; + return BcAEADUtil.processAEADData(true, kekAlgorithm, aeadAlgorithm, key, iv, info, sessionKey, 0, sessionKey.length, BcAEADUtil.GetEskAndTagErrorMessage); } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilder.java index decf032fcb..d95754c7df 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilder.java @@ -1,12 +1,13 @@ package org.bouncycastle.openpgp.operator.bc; -import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilder; import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; public class BcPBESecretKeyDecryptorBuilder + implements PBESecretKeyDecryptorBuilder { private PGPDigestCalculatorProvider calculatorProvider; @@ -24,20 +25,19 @@ public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] key { try { - BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv); - - byte[] out = new byte[keyLen]; - int outLen = c.processBytes(keyData, keyOff, keyLen, out, 0); - - outLen += c.doFinal(out, outLen); - - return out; + return BcUtil.processBufferedBlockCipher(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv, keyData, keyOff, keyLen); } catch (InvalidCipherTextException e) { throw new PGPException("decryption failed: " + e.getMessage(), e); } } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) throws PGPException + { + return BcAEADUtil.processAeadKeyData(false, encAlgorithm, aeadAlgorithm, s2kKey, iv, packetTag, keyVersion, keyData, 0, keyData.length, pubkeyData); + } }; } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilderProvider.java new file mode 100644 index 0000000000..532ca3bced --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyDecryptorBuilderProvider.java @@ -0,0 +1,14 @@ +package org.bouncycastle.openpgp.operator.bc; + +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilder; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilderProvider; + +public class BcPBESecretKeyDecryptorBuilderProvider + implements PBESecretKeyDecryptorBuilderProvider +{ + @Override + public PBESecretKeyDecryptorBuilder provide() + { + return new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyEncryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyEncryptorBuilder.java index 2258484e63..b4353d82dd 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyEncryptorBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPBESecretKeyEncryptorBuilder.java @@ -3,7 +3,6 @@ import java.security.SecureRandom; import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; @@ -117,15 +116,7 @@ public byte[] encryptKeyData(byte[] key, byte[] iv, byte[] keyData, int keyOff, this.random.nextBytes(iv); } - - BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(true, engine, key, iv); - - byte[] out = new byte[keyLen]; - int outLen = c.processBytes(keyData, keyOff, keyLen, out, 0); - - outLen += c.doFinal(out, outLen); - - return out; + return BcUtil.processBufferedBlockCipher(true, engine, key, iv, keyData, keyOff, keyLen); } catch (InvalidCipherTextException e) { diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPContentSignerBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPContentSignerBuilderProvider.java new file mode 100644 index 0000000000..c972b4fd3d --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPContentSignerBuilderProvider.java @@ -0,0 +1,21 @@ +package org.bouncycastle.openpgp.operator.bc; + +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilderProvider; + +public class BcPGPContentSignerBuilderProvider + extends PGPContentSignerBuilderProvider +{ + + public BcPGPContentSignerBuilderProvider(int hashAlgorithmId) + { + super(hashAlgorithmId); + } + + @Override + public PGPContentSignerBuilder get(PGPPublicKey signingKey) + { + return new BcPGPContentSignerBuilder(signingKey.getAlgorithm(), hashAlgorithmId); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyConverter.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyConverter.java index 23ab52f0e4..a64e782912 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyConverter.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyConverter.java @@ -81,7 +81,7 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pubKey, AsymmetricKeyParamete } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -91,13 +91,34 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pubKey, AsymmetricKeyParamete * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PGPAlgorithmParameters, AsymmetricKeyParameter, Date)} instead */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, AsymmetricKeyParameter pubKey, Date time) throws PGPException + { + return getPGPPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, time); + } + + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, AsymmetricKeyParameter pubKey, Date time) + throws PGPException { BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey); - return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), new BcKeyFingerprintCalculator()); + return new PGPPublicKey(new PublicKeyPacket(version, algorithm, time, bcpgKey), new BcKeyFingerprintCalculator()); } public AsymmetricKeyParameter getPrivateKey(PGPPrivateKey privKey) @@ -122,40 +143,58 @@ public AsymmetricKeyParameter getPrivateKey(PGPPrivateKey privKey) { ECDHPublicBCPGKey ecdhPub = (ECDHPublicBCPGKey)pubPk.getKey(); - if (CryptlibObjectIdentifiers.curvey25519.equals(ecdhPub.getCurveOID())) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (BcUtil.isX25519(ecdhPub.getCurveOID())) { return PrivateKeyFactory.createKey(getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX())))); } + // Legacy X448 (1.3.101.111) + else if (EdECObjectIdentifiers.id_X448.equals(ecdhPub.getCurveOID())) + { + return PrivateKeyFactory.createKey(getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX())))); + } + // NIST, Brainpool etc. else { return implGetPrivateKeyEC(ecdhPub, (ECSecretBCPGKey)privPk); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return PrivateKeyFactory.createKey(getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, X25519SecretBCPGKey.LENGTH, - Arrays.reverseInPlace(privPk.getEncoded()))); + privPk.getEncoded())); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return PrivateKeyFactory.createKey(getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, X448SecretBCPGKey.LENGTH, - Arrays.reverseInPlace(privPk.getEncoded()))); + privPk.getEncoded())); } case PublicKeyAlgorithmTags.ECDSA: - return implGetPrivateKeyEC((ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); + { + return implGetPrivateKeyEC((ECDSAPublicBCPGKey) pubPk.getKey(), (ECSecretBCPGKey) privPk); + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { + // Legacy Ed448 (1.3.101.113) if (((EdDSAPublicBCPGKey)pubPk.getKey()).getCurveOID().equals(EdECObjectIdentifiers.id_Ed448)) { return implGetPrivateKeyPKCS8(EdECObjectIdentifiers.id_Ed448, Ed448.SECRET_KEY_SIZE, privPk); } + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) return implGetPrivateKeyPKCS8(EdECObjectIdentifiers.id_Ed25519, Ed25519.SECRET_KEY_SIZE, privPk); } + // Modern Ed22519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return PrivateKeyFactory.createKey(getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded())); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return PrivateKeyFactory.createKey(getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, Ed448SecretBCPGKey.LENGTH, privPk.getEncoded())); @@ -178,7 +217,7 @@ public AsymmetricKeyParameter getPrivateKey(PGPPrivateKey privKey) rsaPriv.getPrimeExponentQ(), rsaPriv.getCrtCoefficient()); } default: - throw new PGPException("unknown public key algorithm encountered"); + throw new PGPException("unknown public key algorithm encountered: " + pubPk.getAlgorithm()); } } catch (PGPException e) @@ -209,7 +248,9 @@ public AsymmetricKeyParameter getPublicKey(PGPPublicKey publicKey) { ECDHPublicBCPGKey ecdhK = (ECDHPublicBCPGKey)publicPk.getKey(); - if (ecdhK.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (BcUtil.isX25519(ecdhK.getCurveOID())) { byte[] pEnc = BigIntegers.asUnsignedByteArray(ecdhK.getEncodedPoint()); // skip the 0x40 header byte. @@ -219,22 +260,37 @@ public AsymmetricKeyParameter getPublicKey(PGPPublicKey publicKey) } return implGetPublicKeyX509(EdECObjectIdentifiers.id_X25519, pEnc, 1); } + // Legacy X448 (1.3.101.111) + else if (ecdhK.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(ecdhK.getEncodedPoint()); + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid X448 public key"); + } + return implGetPublicKeyX509(EdECObjectIdentifiers.id_X448, pEnc, 1); + } else { return implGetPublicKeyEC(ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return implGetPublicKeyX509((X25519PublicBCPGKey)publicPk.getKey(), EdECObjectIdentifiers.id_X25519); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return implGetPublicKeyX509((X448PublicBCPGKey)publicPk.getKey(), EdECObjectIdentifiers.id_X448); } case PublicKeyAlgorithmTags.ECDSA: + { return implGetPublicKeyEC((ECDSAPublicBCPGKey)publicPk.getKey()); - + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { EdDSAPublicBCPGKey eddsaK = (EdDSAPublicBCPGKey)publicPk.getKey(); @@ -246,29 +302,35 @@ public AsymmetricKeyParameter getPublicKey(PGPPublicKey publicKey) throw new IllegalArgumentException("Invalid EdDSA public key"); } - if (pEnc[0] == 0x40 && !eddsaK.getCurveOID().equals(EdECObjectIdentifiers.id_Ed448)) + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (!eddsaK.getCurveOID().equals(EdECObjectIdentifiers.id_Ed448)) { - return implGetPublicKeyX509(EdECObjectIdentifiers.id_Ed25519, pEnc, 1); + return implGetPublicKeyX509(EdECObjectIdentifiers.id_Ed25519, pEnc, pEnc[0] == 0x40 ? 1 : 0); } - else if (eddsaK.getCurveOID().equals(EdECObjectIdentifiers.id_Ed448)) + // Legacy Ed448 (1.3.101.113) + if (eddsaK.getCurveOID().equals(EdECObjectIdentifiers.id_Ed448)) { - return implGetPublicKeyX509(EdECObjectIdentifiers.id_Ed448, pEnc, 0); + return implGetPublicKeyX509(EdECObjectIdentifiers.id_Ed448, pEnc, pEnc[0] == 0x40 ? 1 : 0); } throw new IllegalArgumentException("Invalid EdDSA public key"); } + // Modern Ed22519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return implGetPublicKeyX509((Ed25519PublicBCPGKey)publicPk.getKey(), EdECObjectIdentifiers.id_Ed25519); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return implGetPublicKeyX509((Ed448PublicBCPGKey)publicPk.getKey(), EdECObjectIdentifiers.id_Ed448); } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: - ElGamalPublicBCPGKey elK = (ElGamalPublicBCPGKey)publicPk.getKey(); + { + ElGamalPublicBCPGKey elK = (ElGamalPublicBCPGKey) publicPk.getKey(); return new ElGamalPublicKeyParameters(elK.getY(), new ElGamalParameters(elK.getP(), elK.getG())); + } case PublicKeyAlgorithmTags.RSA_ENCRYPT: case PublicKeyAlgorithmTags.RSA_GENERAL: @@ -279,7 +341,7 @@ else if (eddsaK.getCurveOID().equals(EdECObjectIdentifiers.id_Ed448)) } default: - throw new PGPException("unknown public key algorithm encountered"); + throw new PGPException("unknown public key algorithm encountered: " + publicKey.getAlgorithm()); } } catch (PGPException e) @@ -304,37 +366,59 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pubKey, AsymmetricKeyParameter pr } case PublicKeyAlgorithmTags.ECDH: { + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 if (privKey instanceof X25519PrivateKeyParameters) { return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverseInPlace(((X25519PrivateKeyParameters)privKey).getEncoded()))); } + // Legacy X448 (1.3.101.111) + else if (privKey instanceof X448PrivateKeyParameters) + { + return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverseInPlace(((X448PrivateKeyParameters)privKey).getEncoded()))); + } + // NIST, Brainpool etc. else { ECPrivateKeyParameters ecK = (ECPrivateKeyParameters)privKey; return new ECSecretBCPGKey(ecK.getD()); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { - return new X25519SecretBCPGKey(Arrays.reverseInPlace(((X25519PrivateKeyParameters)privKey).getEncoded())); + return new X25519SecretBCPGKey(((X25519PrivateKeyParameters)privKey).getEncoded()); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { - return new X448SecretBCPGKey(Arrays.reverseInPlace(((X448PrivateKeyParameters)privKey).getEncoded())); + return new X448SecretBCPGKey(((X448PrivateKeyParameters)privKey).getEncoded()); } case PublicKeyAlgorithmTags.ECDSA: { ECPrivateKeyParameters ecK = (ECPrivateKeyParameters)privKey; return new ECSecretBCPGKey(ecK.getD()); } + // Legacy EdDSA case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return new EdSecretBCPGKey(new BigInteger(1, ((Ed25519PrivateKeyParameters)privKey).getEncoded())); + // Legacy Ed25519 (1.3.101.112 & 1.3.6.1.4.1.11591.15.1) + if (privKey instanceof Ed25519PrivateKeyParameters) + { + return new EdSecretBCPGKey(new BigInteger(1, ((Ed25519PrivateKeyParameters)privKey).getEncoded())); + } + // Legacy Ed448 (1.3.101.113) + else + { + return new EdSecretBCPGKey(new BigInteger(1, ((Ed448PrivateKeyParameters) privKey).getEncoded())); + } } + // Modern Ed22519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return new Ed25519SecretBCPGKey(((Ed25519PrivateKeyParameters)privKey).getEncoded()); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return new Ed448SecretBCPGKey(((Ed448PrivateKeyParameters)privKey).getEncoded()); @@ -354,98 +438,133 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pubKey, AsymmetricKeyParameter pr } default: - throw new PGPException("unknown key class"); + throw new PGPException("unknown public key algorithm encountered: " + pubKey.getAlgorithm()); } } private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, AsymmetricKeyParameter pubKey) throws PGPException { - if (pubKey instanceof RSAKeyParameters) + switch (algorithm) { - RSAKeyParameters rK = (RSAKeyParameters)pubKey; - return new RSAPublicBCPGKey(rK.getModulus(), rK.getExponent()); - } - else if (pubKey instanceof DSAPublicKeyParameters) - { - DSAPublicKeyParameters dK = (DSAPublicKeyParameters)pubKey; - DSAParameters dP = dK.getParameters(); - return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); - } - else if (pubKey instanceof ElGamalPublicKeyParameters) - { - ElGamalPublicKeyParameters eK = (ElGamalPublicKeyParameters)pubKey; - ElGamalParameters eS = eK.getParameters(); - return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); - } - else if (pubKey instanceof ECPublicKeyParameters) - { - ECPublicKeyParameters ecK = (ECPublicKeyParameters)pubKey; + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAKeyParameters rK = (RSAKeyParameters)pubKey; + return new RSAPublicBCPGKey(rK.getModulus(), rK.getExponent()); + } + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicKeyParameters dK = (DSAPublicKeyParameters)pubKey; + DSAParameters dP = dK.getParameters(); + return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + ElGamalPublicKeyParameters eK = (ElGamalPublicKeyParameters)pubKey; + ElGamalParameters eS = eK.getParameters(); + return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); + } + // NIST, Brainpool, Legacy X25519, Legacy X448 + case PublicKeyAlgorithmTags.ECDH: + { + // Legacy X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + if (pubKey instanceof X25519PublicKeyParameters) + { + byte[] pointEnc = new byte[1 + X25519PublicKeyParameters.KEY_SIZE]; + pointEnc[0] = 0x40; + ((X25519PublicKeyParameters)pubKey).encode(pointEnc, 1); - // TODO Should we have a way to recognize named curves when the name is missing? - ECNamedDomainParameters parameters = (ECNamedDomainParameters)ecK.getParameters(); + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); - if (algorithm == PGPPublicKey.ECDH) - { + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, pointEnc), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + if (pubKey instanceof X448PublicKeyParameters) + { + byte[] pointEnc = new byte[1 + X448PublicKeyParameters.KEY_SIZE]; + pointEnc[0] = 0x40; + ((X448PublicKeyParameters)pubKey).encode(pointEnc, 1); + + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, pointEnc), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // NIST, Brainpool etc. + ECPublicKeyParameters ecK = (ECPublicKeyParameters)pubKey; + ECNamedDomainParameters parameters = (ECNamedDomainParameters)ecK.getParameters(); PGPKdfParameters kdfParams = implGetKdfParameters(parameters.getName(), algorithmParameters); return new ECDHPublicBCPGKey(parameters.getName(), ecK.getQ(), kdfParams.getHashAlgorithm(), - kdfParams.getSymmetricWrapAlgorithm()); + kdfParams.getSymmetricWrapAlgorithm()); } - else if (algorithm == PGPPublicKey.ECDSA) + case PublicKeyAlgorithmTags.ECDSA: { + ECPublicKeyParameters ecK = (ECPublicKeyParameters)pubKey; + ECNamedDomainParameters parameters = (ECNamedDomainParameters)ecK.getParameters(); return new ECDSAPublicBCPGKey(parameters.getName(), ecK.getQ()); } - else + // Legacy Ed255519, Legacy Ed448 + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - throw new PGPException("unknown EC algorithm"); + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (pubKey instanceof Ed25519PublicKeyParameters) + { + byte[] pointEnc = new byte[1 + Ed25519PublicKeyParameters.KEY_SIZE]; + pointEnc[0] = 0x40; + ((Ed25519PublicKeyParameters)pubKey).encode(pointEnc, 1); + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, pointEnc)); + } + // Legacy Ed448 (1.3.101.113) + else if (pubKey instanceof Ed448PublicKeyParameters) + { + byte[] pointEnc = new byte[1 + Ed448PublicKeyParameters.KEY_SIZE]; + pointEnc[0] = 0x40; + ((Ed448PublicKeyParameters)pubKey).encode(pointEnc, 1); + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, pointEnc)); + } + else + { + throw new PGPException("Unknown LegacyEdDSA key type: " + pubKey.getClass().getName()); + } + } + // Modern Ed22519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + byte[] pointEnc = new byte[Ed25519PublicKeyParameters.KEY_SIZE]; + ((Ed25519PublicKeyParameters)pubKey).encode(pointEnc, 0); + return new Ed25519PublicBCPGKey(pointEnc); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + byte[] pointEnc = new byte[Ed448PublicKeyParameters.KEY_SIZE]; + ((Ed448PublicKeyParameters)pubKey).encode(pointEnc, 0); + return new Ed448PublicBCPGKey(pointEnc); + } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + byte[] pointEnc = new byte[X25519PublicKeyParameters.KEY_SIZE]; + ((X25519PublicKeyParameters)pubKey).encode(pointEnc, 0); + return new X25519PublicBCPGKey(pointEnc); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + byte[] pointEnc = new byte[X448PublicKeyParameters.KEY_SIZE]; + ((X448PublicKeyParameters)pubKey).encode(pointEnc, 0); + return new X448PublicBCPGKey(pointEnc); } - } - else if (algorithm == PublicKeyAlgorithmTags.Ed25519) - { - byte[] pointEnc = new byte[Ed25519PublicKeyParameters.KEY_SIZE]; - ((Ed25519PublicKeyParameters)pubKey).encode(pointEnc, 0); - return new Ed25519PublicBCPGKey(pointEnc); - } - else if (pubKey instanceof Ed25519PublicKeyParameters) - { - byte[] pointEnc = new byte[1 + Ed25519PublicKeyParameters.KEY_SIZE]; - pointEnc[0] = 0x40; - ((Ed25519PublicKeyParameters)pubKey).encode(pointEnc, 1); - return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, pointEnc)); - } - else if (pubKey instanceof Ed448PublicKeyParameters) - { - byte[] pointEnc = new byte[Ed448PublicKeyParameters.KEY_SIZE]; - ((Ed448PublicKeyParameters)pubKey).encode(pointEnc, 0); - return new Ed448PublicBCPGKey(pointEnc); - } - else if (algorithm == PublicKeyAlgorithmTags.X25519) - { - byte[] pointEnc = new byte[X25519PublicKeyParameters.KEY_SIZE]; - ((X25519PublicKeyParameters)pubKey).encode(pointEnc, 0); - return new X25519PublicBCPGKey(pointEnc); - } - else if (pubKey instanceof X25519PublicKeyParameters) - { - byte[] pointEnc = new byte[1 + X25519PublicKeyParameters.KEY_SIZE]; - pointEnc[0] = 0x40; - ((X25519PublicKeyParameters)pubKey).encode(pointEnc, 1); - - PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); - return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, pointEnc), - kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); - } - else if (pubKey instanceof X448PublicKeyParameters) - { - byte[] pointEnc = new byte[X448PublicKeyParameters.KEY_SIZE]; - ((X448PublicKeyParameters)pubKey).encode(pointEnc, 0); - return new X448PublicBCPGKey(pointEnc); - } - else - { - throw new PGPException("unknown key class"); + default: + { + throw new PGPException("unknown public key algorithm encountered: " + algorithm); + } } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPair.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPair.java index e5b085364b..f1f23a6976 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPair.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPair.java @@ -2,6 +2,7 @@ import java.util.Date; +import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.openpgp.PGPAlgorithmParameters; @@ -13,10 +14,17 @@ public class BcPGPKeyPair extends PGPKeyPair { + @Deprecated private static PGPPublicKey getPublicKey(int algorithm, PGPAlgorithmParameters parameters, AsymmetricKeyParameter pubKey, Date date) throws PGPException { - return new BcPGPKeyConverter().getPGPPublicKey(algorithm, parameters, pubKey, date); + return getPublicKey(PublicKeyPacket.VERSION_4, algorithm, parameters, pubKey, date); + } + + private static PGPPublicKey getPublicKey(int version, int algorithm, PGPAlgorithmParameters parameters, AsymmetricKeyParameter pubKey, Date date) + throws PGPException + { + return new BcPGPKeyConverter().getPGPPublicKey(version, algorithm, parameters, pubKey, date); } private static PGPPrivateKey getPrivateKey(PGPPublicKey pub, AsymmetricKeyParameter privKey) @@ -25,17 +33,31 @@ private static PGPPrivateKey getPrivateKey(PGPPublicKey pub, AsymmetricKeyParame return new BcPGPKeyConverter().getPGPPrivateKey(pub, privKey); } + @Deprecated public BcPGPKeyPair(int algorithm, AsymmetricCipherKeyPair keyPair, Date date) throws PGPException { - this.pub = getPublicKey(algorithm, null, keyPair.getPublic(), date); + this(PublicKeyPacket.VERSION_4, algorithm, keyPair, date); + } + + public BcPGPKeyPair(int version, int algorithm, AsymmetricCipherKeyPair keyPair, Date date) + throws PGPException + { + this.pub = getPublicKey(version, algorithm, null, keyPair.getPublic(), date); this.priv = getPrivateKey(this.pub, keyPair.getPrivate()); } + @Deprecated public BcPGPKeyPair(int algorithm, PGPAlgorithmParameters parameters, AsymmetricCipherKeyPair keyPair, Date date) throws PGPException { - this.pub = getPublicKey(algorithm, parameters, keyPair.getPublic(), date); + this(PublicKeyPacket.VERSION_4, algorithm, parameters, keyPair, date); + } + + public BcPGPKeyPair(int version, int algorithm, PGPAlgorithmParameters parameters, AsymmetricCipherKeyPair keyPair, Date date) + throws PGPException + { + this.pub = getPublicKey(version, algorithm, parameters, keyPair.getPublic(), date); this.priv = getPrivateKey(this.pub, keyPair.getPrivate()); } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPairGeneratorProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPairGeneratorProvider.java new file mode 100644 index 0000000000..45ab6a85e4 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPGPKeyPairGeneratorProvider.java @@ -0,0 +1,178 @@ +package org.bouncycastle.openpgp.operator.bc; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.ec.CustomNamedCurves; +import org.bouncycastle.crypto.generators.ECKeyPairGenerator; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; +import org.bouncycastle.crypto.generators.Ed448KeyPairGenerator; +import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; +import org.bouncycastle.crypto.generators.X448KeyPairGenerator; +import org.bouncycastle.crypto.params.ECKeyGenerationParameters; +import org.bouncycastle.crypto.params.ECNamedDomainParameters; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; +import org.bouncycastle.crypto.params.Ed448KeyGenerationParameters; +import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.crypto.params.X448KeyGenerationParameters; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; +import org.bouncycastle.openpgp.operator.PGPKeyPairGeneratorProvider; + +public class BcPGPKeyPairGeneratorProvider + extends PGPKeyPairGeneratorProvider +{ + private SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + + @Override + public PGPKeyPairGenerator get(int version, Date creationTime) + { + return new BcPGPKeyPairGenerator(version, creationTime, random); + } + + public BcPGPKeyPairGeneratorProvider setSecureRandom(SecureRandom random) + { + this.random = random; + return this; + } + + private static class BcPGPKeyPairGenerator + extends PGPKeyPairGenerator + { + + public BcPGPKeyPairGenerator(int version, Date creationTime, SecureRandom random) + { + super(version, creationTime, random, new BcKeyFingerprintCalculator()); + } + + @Override + public PGPKeyPair generateRsaKeyPair(BigInteger exponent, int bitStrength) + throws PGPException + { + RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); + gen.init(new RSAKeyGenerationParameters(exponent, random, bitStrength, 100)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.RSA_GENERAL, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateEd25519KeyPair() + throws PGPException + { + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateEd448KeyPair() + throws PGPException + { + Ed448KeyPairGenerator gen = new Ed448KeyPairGenerator(); + gen.init(new Ed448KeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.Ed448, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateX25519KeyPair() + throws PGPException + { + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.X25519, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateX448KeyPair() + throws PGPException + { + X448KeyPairGenerator gen = new X448KeyPairGenerator(); + gen.init(new X448KeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.X448, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateLegacyEd25519KeyPair() + throws PGPException + { + if (version == PublicKeyPacket.VERSION_6) + { + throw new PGPException("An implementation MUST NOT generate a v6 LegacyEd25519 key pair."); + } + + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.EDDSA_LEGACY, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateLegacyX25519KeyPair() + throws PGPException + { + if (version == PublicKeyPacket.VERSION_6) + { + throw new PGPException("An implementation MUST NOT generate a v6 LegacyX25519 key pair."); + } + + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(random)); + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.ECDH, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateECDHKeyPair(ASN1ObjectIdentifier curveOID) + throws PGPException + { + ECKeyPairGenerator gen = new ECKeyPairGenerator(); + gen.init(new ECKeyGenerationParameters( + new ECNamedDomainParameters(curveOID, getNamedCurveByOid(curveOID)), + CryptoServicesRegistrar.getSecureRandom())); + + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.ECDH, keyPair, creationTime); + } + + @Override + public PGPKeyPair generateECDSAKeyPair(ASN1ObjectIdentifier curveOID) + throws PGPException + { + ECKeyPairGenerator gen = new ECKeyPairGenerator(); + gen.init(new ECKeyGenerationParameters( + new ECNamedDomainParameters(curveOID, getNamedCurveByOid(curveOID)), + CryptoServicesRegistrar.getSecureRandom())); + + AsymmetricCipherKeyPair keyPair = gen.generateKeyPair(); + return new BcPGPKeyPair(version, PublicKeyAlgorithmTags.ECDSA, keyPair, creationTime); + } + } + + private static X9ECParameters getNamedCurveByOid( + ASN1ObjectIdentifier oid) + { + X9ECParameters params = CustomNamedCurves.getByOID(oid); + + if (params == null) + { + params = ECNamedCurveTable.getByOID(oid); + } + + return params; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyDataDecryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyDataDecryptorFactory.java index 6734eafdc0..a407e38710 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyDataDecryptorFactory.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyDataDecryptorFactory.java @@ -1,9 +1,9 @@ package org.bouncycastle.openpgp.operator.bc; import java.io.IOException; -import java.math.BigInteger; import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.bcpg.AEADEncDataPacket; import org.bouncycastle.bcpg.ECDHPublicBCPGKey; import org.bouncycastle.bcpg.HashAlgorithmTags; @@ -12,12 +12,12 @@ import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.X25519PublicBCPGKey; import org.bouncycastle.bcpg.X448PublicBCPGKey; -import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedAsymmetricBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.RawAgreement; import org.bouncycastle.crypto.Wrapper; +import org.bouncycastle.crypto.agreement.BasicRawAgreement; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.agreement.X25519Agreement; import org.bouncycastle.crypto.agreement.X448Agreement; @@ -32,18 +32,17 @@ import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.operator.AbstractPublicKeyDataDecryptorFactory; import org.bouncycastle.openpgp.operator.PGPDataDecryptor; import org.bouncycastle.openpgp.operator.PGPPad; -import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; import org.bouncycastle.openpgp.operator.RFC6637Utils; import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.BigIntegers; /** * A decryptor factory for handling public key decryption operations. */ public class BcPublicKeyDataDecryptorFactory - implements PublicKeyDataDecryptorFactory + extends AbstractPublicKeyDataDecryptorFactory { private static final BcPGPKeyConverter KEY_CONVERTER = new BcPGPKeyConverter(); @@ -55,7 +54,7 @@ public BcPublicKeyDataDecryptorFactory(PGPPrivateKey pgpPrivKey) } @Override - public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData, int pkeskVersion) throws PGPException { try @@ -65,7 +64,7 @@ public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) if (keyAlgorithm == PublicKeyAlgorithmTags.X25519) { return getSessionData(secKeyData[0], privKey, X25519PublicBCPGKey.LENGTH, HashAlgorithmTags.SHA256, - SymmetricKeyAlgorithmTags.AES_128, new X25519Agreement(), "X25519", new PublicKeyParametersOperation() + SymmetricKeyAlgorithmTags.AES_128, new X25519Agreement(), "X25519", containsSKAlg(pkeskVersion), new PublicKeyParametersOperation() { @Override public AsymmetricKeyParameter getPublicKeyParameters(byte[] pEnc, int pEncOff) @@ -77,7 +76,7 @@ public AsymmetricKeyParameter getPublicKeyParameters(byte[] pEnc, int pEncOff) else if (keyAlgorithm == PublicKeyAlgorithmTags.X448) { return getSessionData(secKeyData[0], privKey, X448PublicBCPGKey.LENGTH, HashAlgorithmTags.SHA512, - SymmetricKeyAlgorithmTags.AES_256, new X448Agreement(), "X448", new PublicKeyParametersOperation() + SymmetricKeyAlgorithmTags.AES_256, new X448Agreement(), "X448", containsSKAlg(pkeskVersion), new PublicKeyParametersOperation() { @Override public AsymmetricKeyParameter getPublicKeyParameters(byte[] pEnc, int pEncOff) @@ -88,114 +87,141 @@ public AsymmetricKeyParameter getPublicKeyParameters(byte[] pEnc, int pEncOff) } else if (keyAlgorithm == PublicKeyAlgorithmTags.ECDH) { - byte[] enc = secKeyData[0]; - byte[] pEnc; - byte[] keyEnc; - int pLen = ((((enc[0] & 0xff) << 8) + (enc[1] & 0xff)) + 7) / 8; - assertOutOfRange(2 + pLen + 1, enc); - - pEnc = new byte[pLen]; - System.arraycopy(enc, 2, pEnc, 0, pLen); - - int keyLen = enc[pLen + 2] & 0xff; - assertOutOfRange(2 + pLen + 1 + keyLen, enc); - - keyEnc = new byte[keyLen]; - System.arraycopy(enc, 2 + pLen + 1, keyEnc, 0, keyLen); - - byte[] secret; - RFC6637KDFCalculator rfc6637KDFCalculator; - byte[] userKeyingMaterial; - int symmetricKeyAlgorithm, hashAlgorithm; - - ECDHPublicBCPGKey ecPubKey = (ECDHPublicBCPGKey)pgpPrivKey.getPublicKeyPacket().getKey(); - // XDH - if (ecPubKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) - { - if (pEnc.length != 1 + X25519PublicKeyParameters.KEY_SIZE || 0x40 != pEnc[0]) - { - throw new IllegalArgumentException("Invalid Curve25519 public key"); - } - // skip the 0x40 header byte. - secret = BcUtil.getSecret(new X25519Agreement(), privKey, new X25519PublicKeyParameters(pEnc, 1)); - } - else - { - ECDomainParameters ecParameters = ((ECPrivateKeyParameters)privKey).getParameters(); - - ECPublicKeyParameters ephPub = new ECPublicKeyParameters(ecParameters.getCurve().decodePoint(pEnc), - ecParameters); - - ECDHBasicAgreement agreement = new ECDHBasicAgreement(); - agreement.init(privKey); - BigInteger S = agreement.calculateAgreement(ephPub); - secret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), S); - } - hashAlgorithm = ecPubKey.getHashAlgorithm(); - symmetricKeyAlgorithm = ecPubKey.getSymmetricKeyAlgorithm(); - userKeyingMaterial = RFC6637Utils.createUserKeyingMaterial(pgpPrivKey.getPublicKeyPacket(), new BcKeyFingerprintCalculator()); - rfc6637KDFCalculator = new RFC6637KDFCalculator(new BcPGPDigestCalculatorProvider().get(hashAlgorithm), symmetricKeyAlgorithm); - KeyParameter key = new KeyParameter(rfc6637KDFCalculator.createKey(secret, userKeyingMaterial)); - - return PGPPad.unpadSessionData(unwrapSessionData(keyEnc, symmetricKeyAlgorithm, key)); + return recoverECDHSessionData(secKeyData, privKey); + } + else if (keyAlgorithm == PublicKeyAlgorithmTags.RSA_ENCRYPT || + keyAlgorithm == PublicKeyAlgorithmTags.RSA_GENERAL) + { + return recoverRSASessionData(keyAlgorithm, secKeyData, privKey); } else { - AsymmetricBlockCipher c = BcImplProvider.createPublicKeyCipher(keyAlgorithm); + return recoverElgamalSessionData(keyAlgorithm, secKeyData, privKey); + } + } + catch (IOException e) + { + throw new PGPException("exception creating user keying material: " + e.getMessage(), e); + } + catch (InvalidCipherTextException e) + { + throw new PGPException("exception decrypting session info: " + e.getMessage(), e); + } + } - BufferedAsymmetricBlockCipher c1 = new BufferedAsymmetricBlockCipher(c); + private byte[] recoverElgamalSessionData(int keyAlgorithm, + byte[][] secKeyData, + AsymmetricKeyParameter privKey) + throws PGPException, InvalidCipherTextException + { + BufferedAsymmetricBlockCipher c1 = getBufferedAsymmetricBlockCipher(keyAlgorithm, privKey); - c1.init(false, privKey); + ElGamalPrivateKeyParameters parms = (ElGamalPrivateKeyParameters) privKey; + int size = (parms.getParameters().getP().bitLength() + 7) / 8; + byte[] tmp = new byte[size]; - if (keyAlgorithm == PublicKeyAlgorithmTags.RSA_ENCRYPT - || keyAlgorithm == PublicKeyAlgorithmTags.RSA_GENERAL) - { - byte[] bi = secKeyData[0]; + byte[] bi = secKeyData[0]; // encoded MPI + processEncodedMpi(c1, size, tmp, bi); - c1.processBytes(bi, 2, bi.length - 2); - } - else - { - ElGamalPrivateKeyParameters parms = (ElGamalPrivateKeyParameters)privKey; - int size = (parms.getParameters().getP().bitLength() + 7) / 8; - byte[] tmp = new byte[size]; + bi = secKeyData[1]; // encoded MPI + Arrays.fill(tmp, (byte)0); - byte[] bi = secKeyData[0]; // encoded MPI - if (bi.length - 2 > size) // leading Zero? Shouldn't happen but... - { - c1.processBytes(bi, 3, bi.length - 3); - } - else - { - System.arraycopy(bi, 2, tmp, tmp.length - (bi.length - 2), bi.length - 2); - c1.processBytes(tmp, 0, tmp.length); - } + processEncodedMpi(c1, size, tmp, bi); - bi = secKeyData[1]; // encoded MPI - Arrays.fill(tmp, (byte)0); + return c1.doFinal(); + } - if (bi.length - 2 > size) // leading Zero? Shouldn't happen but... - { - c1.processBytes(bi, 3, bi.length - 3); - } - else - { - System.arraycopy(bi, 2, tmp, tmp.length - (bi.length - 2), bi.length - 2); - c1.processBytes(tmp, 0, tmp.length); - } - } + private byte[] recoverRSASessionData(int keyAlgorithm, + byte[][] secKeyData, + AsymmetricKeyParameter privKey) + throws PGPException, InvalidCipherTextException + { + BufferedAsymmetricBlockCipher c1 = getBufferedAsymmetricBlockCipher(keyAlgorithm, privKey); + byte[] bi = secKeyData[0]; + c1.processBytes(bi, 2, bi.length - 2); + return c1.doFinal(); + } + + private static BufferedAsymmetricBlockCipher getBufferedAsymmetricBlockCipher(int keyAlgorithm, AsymmetricKeyParameter privKey) + throws PGPException + { + BufferedAsymmetricBlockCipher c1 = new BufferedAsymmetricBlockCipher(BcImplProvider.createPublicKeyCipher(keyAlgorithm)); + c1.init(false, privKey); + return c1; + } - return c1.doFinal(); + private void processEncodedMpi(BufferedAsymmetricBlockCipher c1, int size, byte[] tmp, byte[] bi) + { + if (bi.length - 2 > size) // leading Zero? Shouldn't happen but... + { + c1.processBytes(bi, 3, bi.length - 3); + } + else + { + System.arraycopy(bi, 2, tmp, tmp.length - (bi.length - 2), bi.length - 2); + c1.processBytes(tmp, 0, tmp.length); + } + } + + private byte[] recoverECDHSessionData(byte[][] secKeyData, + AsymmetricKeyParameter privKey) + throws PGPException, IOException, InvalidCipherTextException + { + byte[] enc = secKeyData[0]; + byte[] pEnc; + byte[] keyEnc; + int pLen = ((((enc[0] & 0xff) << 8) + (enc[1] & 0xff)) + 7) / 8; + checkRange(2 + pLen + 1, enc); + + pEnc = new byte[pLen]; + System.arraycopy(enc, 2, pEnc, 0, pLen); + + int keyLen = enc[pLen + 2] & 0xff; + checkRange(2 + pLen + 1 + keyLen, enc); + + keyEnc = new byte[keyLen]; + System.arraycopy(enc, 2 + pLen + 1, keyEnc, 0, keyLen); + + byte[] secret; + RFC6637KDFCalculator rfc6637KDFCalculator; + byte[] userKeyingMaterial; + int symmetricKeyAlgorithm, hashAlgorithm; + + ECDHPublicBCPGKey ecPubKey = (ECDHPublicBCPGKey)pgpPrivKey.getPublicKeyPacket().getKey(); + // XDH + if (ecPubKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + { + if (pEnc.length != 1 + X25519PublicKeyParameters.KEY_SIZE || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid Curve25519 public key"); } + // skip the 0x40 header byte. + secret = BcUtil.getSecret(new X25519Agreement(), privKey, new X25519PublicKeyParameters(pEnc, 1)); } - catch (IOException e) + else if (ecPubKey.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) { - throw new PGPException("exception creating user keying material: " + e.getMessage(), e); + if (pEnc.length != 1 + X448PublicKeyParameters.KEY_SIZE || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid Curve448 public key"); + } + // skip the 0x40 header byte. + secret = BcUtil.getSecret(new X448Agreement(), privKey, new X448PublicKeyParameters(pEnc, 1)); } - catch (InvalidCipherTextException e) + else { - throw new PGPException("exception decrypting session info: " + e.getMessage(), e); + ECDomainParameters ecParameters = ((ECPrivateKeyParameters)privKey).getParameters(); + ECPublicKeyParameters ephPub = new ECPublicKeyParameters(ecParameters.getCurve().decodePoint(pEnc), + ecParameters); + + secret = BcUtil.getSecret(new BasicRawAgreement(new ECDHBasicAgreement()), privKey, ephPub); } + hashAlgorithm = ecPubKey.getHashAlgorithm(); + symmetricKeyAlgorithm = ecPubKey.getSymmetricKeyAlgorithm(); + userKeyingMaterial = RFC6637Utils.createUserKeyingMaterial(pgpPrivKey.getPublicKeyPacket(), new BcKeyFingerprintCalculator()); + rfc6637KDFCalculator = new RFC6637KDFCalculator(new BcPGPDigestCalculatorProvider().get(hashAlgorithm), symmetricKeyAlgorithm); + KeyParameter key = new KeyParameter(rfc6637KDFCalculator.createKey(secret, userKeyingMaterial)); + + return PGPPad.unpadSessionData(unwrapSessionData(keyEnc, symmetricKeyAlgorithm, key)); } // OpenPGP v4 @@ -231,21 +257,27 @@ private interface PublicKeyParametersOperation } private byte[] getSessionData(byte[] enc, AsymmetricKeyParameter privKey, int pLen, int hashAlgorithm, int symmetricKeyAlgorithm, - RawAgreement agreement, String algorithmName, PublicKeyParametersOperation pkp) + RawAgreement agreement, String algorithmName, boolean includesSesKeyAlg, PublicKeyParametersOperation pkp) throws PGPException, InvalidCipherTextException { - byte[] pEnc = new byte[pLen]; - byte[] keyEnc; - System.arraycopy(enc, 0, pEnc, 0, pLen); - int keyLen = enc[pLen] & 0xff; - assertOutOfRange(pLen + 1 + keyLen, enc); - keyEnc = new byte[keyLen - 1]; - System.arraycopy(enc, pLen + 2, keyEnc, 0, keyEnc.length); - byte[] secret = BcUtil.getSecret(agreement, privKey, pkp.getPublicKeyParameters(pEnc, 0)); - KeyParameter key = new KeyParameter(RFC6637KDFCalculator.createKey(hashAlgorithm, symmetricKeyAlgorithm, - Arrays.concatenate(pEnc, pgpPrivKey.getPublicKeyPacket().getKey().getEncoded(), secret), "OpenPGP " + algorithmName)); - - return Arrays.concatenate(new byte[]{enc[pLen + 1]}, unwrapSessionData(keyEnc, symmetricKeyAlgorithm, key)); + byte[] ephemeralKey = Arrays.copyOf(enc, pLen); + + // size of following fields + int size = enc[pLen] & 0xff; + checkRange(pLen + 1 + size, enc); + + // encrypted session key + int sesKeyLen = size - (includesSesKeyAlg ? 1 : 0); + int sesKeyOff = pLen + 1 + (includesSesKeyAlg ? 1 : 0); + byte[] keyEnc = Arrays.copyOfRange(enc, sesKeyOff, sesKeyOff + sesKeyLen); + + byte[] secret = BcUtil.getSecret(agreement, privKey, pkp.getPublicKeyParameters(ephemeralKey, 0)); + + byte[] hkdfOut = RFC6637KDFCalculator.createKey(hashAlgorithm, symmetricKeyAlgorithm, + Arrays.concatenate(ephemeralKey, pgpPrivKey.getPublicKeyPacket().getKey().getEncoded(), secret), + "OpenPGP " + algorithmName); + + return unwrapSessionData(keyEnc, SymmetricKeyAlgorithmTags.AES_128, new KeyParameter(hkdfOut)); } private static byte[] unwrapSessionData(byte[] keyEnc, int symmetricKeyAlgorithm, KeyParameter key) @@ -255,13 +287,4 @@ private static byte[] unwrapSessionData(byte[] keyEnc, int symmetricKeyAlgorithm c.init(false, key); return c.unwrap(keyEnc, 0, keyEnc.length); } - - private static void assertOutOfRange(int pLen, byte[] enc) - throws PGPException - { - if (pLen > enc.length) - { - throw new PGPException("encoded length out of range"); - } - } } \ No newline at end of file diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java index 7d8d63825d..ea70b108f1 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java @@ -4,19 +4,20 @@ import java.math.BigInteger; import java.security.SecureRandom; -import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.bcpg.ECDHPublicBCPGKey; import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.MPInteger; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyGenerationParameters; import org.bouncycastle.crypto.RawAgreement; import org.bouncycastle.crypto.Wrapper; +import org.bouncycastle.crypto.agreement.BasicRawAgreement; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.agreement.X25519Agreement; import org.bouncycastle.crypto.agreement.X448Agreement; @@ -38,7 +39,6 @@ import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; import org.bouncycastle.openpgp.operator.RFC6637Utils; import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.BigIntegers; /** * A method generator for supporting public key based encryption operations. @@ -74,18 +74,24 @@ public BcPublicKeyKeyEncryptionMethodGenerator setSecureRandom(SecureRandom rand return this; } - protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo) + @Override + protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionKey, byte symAlgId, boolean isV3) throws PGPException { try { AsymmetricKeyParameter cryptoPublicKey = keyConverter.getPublicKey(pubKey); PublicKeyPacket pubKeyPacket = pubKey.getPublicKeyPacket(); + + // ECDH if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ECDH) { ECDHPublicBCPGKey ecPubKey = (ECDHPublicBCPGKey)pubKeyPacket.getKey(); + byte[] sessionInfo = createSessionInfo(isV3 ? symAlgId : (byte)0, sessionKey); byte[] userKeyingMaterial = RFC6637Utils.createUserKeyingMaterial(pubKeyPacket, new BcKeyFingerprintCalculator()); - if (ecPubKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + + // Legacy X25519 + if (BcUtil.isX25519(ecPubKey.getCurveOID())) { AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(new X25519KeyPairGenerator(), new X25519KeyGenerationParameters(random)); @@ -94,26 +100,41 @@ protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo) byte[] ephPubEncoding = new byte[1 + X25519PublicKeyParameters.KEY_SIZE]; ephPubEncoding[0] = X_HDR; ((X25519PublicKeyParameters)ephKp.getPublic()).encode(ephPubEncoding, 1); - return encryptSessionInfo(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); + return encryptSessionInfoWithECDHKey(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); + } + + // LegacyX448 + else if (ecPubKey.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(new X448KeyPairGenerator(), new X448KeyGenerationParameters(random)); + + byte[] secret = BcUtil.getSecret(new X448Agreement(), ephKp.getPrivate(), cryptoPublicKey); + + byte[] ephPubEncoding = new byte[1 + X448PublicKeyParameters.KEY_SIZE]; + ephPubEncoding[0] = X_HDR; + ((X448PublicKeyParameters)ephKp.getPublic()).encode(ephPubEncoding, 1); + return encryptSessionInfoWithECDHKey(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); } + + // Other ECDH curves else { AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(new ECKeyPairGenerator(), new ECKeyGenerationParameters(((ECPublicKeyParameters)cryptoPublicKey).getParameters(), random)); - ECDHBasicAgreement agreement = new ECDHBasicAgreement(); - agreement.init(ephKp.getPrivate()); - BigInteger S = agreement.calculateAgreement(cryptoPublicKey); - byte[] secret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), S); + byte[] secret = BcUtil.getSecret(new BasicRawAgreement(new ECDHBasicAgreement()), + ephKp.getPrivate(), cryptoPublicKey); byte[] ephPubEncoding = ((ECPublicKeyParameters)ephKp.getPublic()).getQ().getEncoded(false); - return encryptSessionInfo(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); + return encryptSessionInfoWithECDHKey(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); } } + + // X25519 else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X25519) { - return encryptSessionInfo(pubKeyPacket, sessionInfo, HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128, "X25519", + return encryptSessionInfoWithX25519X448Key(pubKeyPacket, sessionKey, HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128, "X25519", new X25519KeyPairGenerator(), new X25519KeyGenerationParameters(random), new X25519Agreement(), cryptoPublicKey, X25519PublicKeyParameters.KEY_SIZE, new EphPubEncodingOperation() { @@ -122,11 +143,14 @@ public void getEphPubEncoding(AsymmetricKeyParameter publicKey, byte[] ephPubEnc { ((X25519PublicKeyParameters)publicKey).encode(ephPubEncoding, 0); } - }); + }, + isV3 ? symAlgId : (byte)0); } + + // X448 else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X448) { - return encryptSessionInfo(pubKeyPacket, sessionInfo, HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256, "X448", + return encryptSessionInfoWithX25519X448Key(pubKeyPacket, sessionKey, HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256, "X448", new X448KeyPairGenerator(), new X448KeyGenerationParameters(random), new X448Agreement(), cryptoPublicKey, X448PublicKeyParameters.KEY_SIZE, new EphPubEncodingOperation() { @@ -135,13 +159,17 @@ public void getEphPubEncoding(AsymmetricKeyParameter publicKey, byte[] ephPubEnc { ((X448PublicKeyParameters)publicKey).encode(ephPubEncoding, 0); } - }); + }, + isV3 ? symAlgId : (byte)0); } + + // RSA / ElGamal etc. else { AsymmetricBlockCipher c = BcImplProvider.createPublicKeyCipher(pubKey.getAlgorithm()); c.init(true, new ParametersWithRandom(cryptoPublicKey, random)); + byte[] sessionInfo = createSessionInfo(isV3 ? symAlgId : (byte)0, sessionKey); return c.processBlock(sessionInfo, 0, sessionInfo.length); } @@ -158,23 +186,56 @@ private interface EphPubEncodingOperation void getEphPubEncoding(AsymmetricKeyParameter publicKey, byte[] ephPubEncoding); } - private byte[] encryptSessionInfo(byte[] sessionInfo, byte[] secret, - byte[] userKeyingMaterial, byte[] ephPubEncoding, int hashAlgorithm, int symmetricKeyAlgorithm) + /** + * Encrypt the session info. + * + * @param sessionInfo sym alg ID (if v3 PKESK) + session key + 2 octets checksum + * @param secret shared secret + * @param userKeyingMaterial UKM + * @param ephPubEncoding ephemeral public key encoding + * @param hashAlgorithm hash algorithm + * @param symmetricKeyAlgorithm symmetric key algorithm + * @return encrypted session key + * @throws IOException + * @throws PGPException + * @see + * Session-Key Encryption using ECDH + */ + private byte[] encryptSessionInfoWithECDHKey(byte[] sessionInfo, + byte[] secret, + byte[] userKeyingMaterial, + byte[] ephPubEncoding, + int hashAlgorithm, + int symmetricKeyAlgorithm) throws IOException, PGPException { + // Prepare shared-secret public key RFC6637KDFCalculator rfc6637KDFCalculator = new RFC6637KDFCalculator( new BcPGPDigestCalculatorProvider().get(hashAlgorithm), symmetricKeyAlgorithm); KeyParameter key = new KeyParameter(rfc6637KDFCalculator.createKey(secret, userKeyingMaterial)); + // session info is padded to an 8-octet granularity using the method described in RFC8018. byte[] paddedSessionData = PGPPad.padSessionData(sessionInfo, sessionKeyObfuscation); - return getSessionInfo(ephPubEncoding, getWrapper(symmetricKeyAlgorithm, key, paddedSessionData)); + // wrap the padded session info using the shared-secret public key + // https://www.rfc-editor.org/rfc/rfc9580.html#section-11.5-16 + return getSessionInfo(new MPInteger(new BigInteger(1, ephPubEncoding)).getEncoded(), (byte) 0, + getWrapper(symmetricKeyAlgorithm, key, paddedSessionData)); } - private byte[] encryptSessionInfo(PublicKeyPacket pubKeyPacket, byte[] sessionInfo, int hashAlgorithm, int symmetricKeyAlgorithm, String algorithmName, - AsymmetricCipherKeyPairGenerator gen, KeyGenerationParameters parameters, RawAgreement agreement, AsymmetricKeyParameter cryptoPublicKey, - int keySize, EphPubEncodingOperation ephPubEncodingOperation) - throws PGPException, IOException + private byte[] encryptSessionInfoWithX25519X448Key(PublicKeyPacket pubKeyPacket, + byte[] sessionKey, + int hashAlgorithm, + int symmetricKeyAlgorithm, + String algorithmName, + AsymmetricCipherKeyPairGenerator gen, + KeyGenerationParameters parameters, + RawAgreement agreement, + AsymmetricKeyParameter cryptoPublicKey, + int keySize, + EphPubEncodingOperation ephPubEncodingOperation, + byte optSymAlgId) + throws PGPException { AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(gen, parameters); byte[] secret = BcUtil.getSecret(agreement, ephKp.getPrivate(), cryptoPublicKey); @@ -182,11 +243,8 @@ private byte[] encryptSessionInfo(PublicKeyPacket pubKeyPacket, byte[] sessionIn ephPubEncodingOperation.getEphPubEncoding(ephKp.getPublic(), ephPubEncoding); KeyParameter key = new KeyParameter(RFC6637KDFCalculator.createKey(hashAlgorithm, symmetricKeyAlgorithm, Arrays.concatenate(ephPubEncoding, pubKeyPacket.getKey().getEncoded(), secret), "OpenPGP " + algorithmName)); - //No checksum and padding - byte[] sessionData = new byte[sessionInfo.length - 3]; - System.arraycopy(sessionInfo, 1, sessionData, 0, sessionData.length); - return getSessionInfo(ephPubEncoding, sessionInfo[0], getWrapper(symmetricKeyAlgorithm, key, sessionData)); + return getSessionInfo(ephPubEncoding, optSymAlgId, getWrapper(symmetricKeyAlgorithm, key, sessionKey)); } private byte[] getWrapper(int symmetricKeyAlgorithm, KeyParameter key, byte[] sessionData) diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcUtil.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcUtil.java index 9a4af7103c..a0257f6a81 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcUtil.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcUtil.java @@ -4,6 +4,8 @@ import java.math.BigInteger; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.bcpg.AEADEncDataPacket; @@ -11,6 +13,7 @@ import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DefaultBufferedBlockCipher; +import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.RawAgreement; import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.crypto.io.CipherInputStream; @@ -100,6 +103,21 @@ public static BufferedBlockCipher createSymmetricKeyWrapper(boolean forEncryptio return c; } + static byte[] processBufferedBlockCipher(boolean forEncryption, BlockCipher engine, byte[] key, byte[] iv, byte[] msg, int msgOff, int msgLen) + throws InvalidCipherTextException + + { + BufferedBlockCipher cipher = BcUtil.createSymmetricKeyWrapper(forEncryption, engine, key, iv); + + byte[] out = new byte[msgLen]; + + int len = cipher.processBytes(msg, msgOff, msgLen, out, 0); + + len += cipher.doFinal(out, len); + + return out; + } + static X9ECParameters getX9Parameters(ASN1ObjectIdentifier curveOID) { X9ECParameters x9 = CustomNamedCurves.getByOID(curveOID); @@ -125,4 +143,9 @@ static byte[] getSecret(RawAgreement agreement, AsymmetricKeyParameter privKey, agreement.calculateAgreement(ephPub, secret, 0); return secret; } + + static boolean isX25519(ASN1ObjectIdentifier curveID) + { + return curveID.equals(CryptlibObjectIdentifiers.curvey25519) || curveID.equals(EdECObjectIdentifiers.id_X25519); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/RFC6637KDFCalculator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/RFC6637KDFCalculator.java index 8da21226e5..f0692a3965 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/RFC6637KDFCalculator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/RFC6637KDFCalculator.java @@ -53,7 +53,7 @@ public byte[] createKey(byte[] secret, byte[] userKeyingMaterial) * Creates a session key for X25519 or X448 encryption based on the provided algorithm and key algorithm. *

      * The method follows the specifications outlined in the OpenPGP standards, specifically sections 5.1.6 and 5.1.7 - * of draft-ietf-openpgp-crypto-refresh-13. + * of rfc9580. * * @param algorithm The algorithm to use for key derivation, such as SHA256 or SHA512. * @param keyAlgorithm The key algorithm identifier, representing AES-128 or AES-256. @@ -65,7 +65,7 @@ public byte[] createKey(byte[] secret, byte[] userKeyingMaterial) * For X448, use "OpenPGP X448". * @return The derived key for encryption. * @throws PGPException If an error occurs during key derivation. - * @see draft-ietf-openpgp-crypto-refresh-13 + * @see rfc9580 - OpenPGP */ public static byte[] createKey(int algorithm, int keyAlgorithm, byte[] prepend, String info) throws PGPException diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/package-info.java new file mode 100644 index 0000000000..8be217659a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/bc/package-info.java @@ -0,0 +1,7 @@ +/** + * BC lightweight operators for dealing with OpenPGP objects. + *

      + * These provide the actual support for encryption and decryption required for the high level OpenPGP classes. + *

      + */ +package org.bouncycastle.openpgp.operator.bc; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorBuilder.java new file mode 100644 index 0000000000..e9112267e8 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorBuilder.java @@ -0,0 +1,96 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.security.Provider; +import java.security.SecureRandom; + +import javax.crypto.Cipher; + +import org.bouncycastle.bcpg.AEADUtils; +import org.bouncycastle.bcpg.PacketTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.AEADSecretKeyEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; + +public class JcaAEADSecretKeyEncryptorBuilder + implements AEADSecretKeyEncryptorBuilder +{ + private int aeadAlgorithm; + private int symmetricAlgorithm; + private S2K.Argon2Params argon2Params; + + private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); + private JceAEADUtil aeadUtil = new JceAEADUtil(helper); + + public JcaAEADSecretKeyEncryptorBuilder(int aeadAlgorithm, int symmetricAlgorithm, S2K.Argon2Params argon2Params) + { + this.aeadAlgorithm = aeadAlgorithm; + this.symmetricAlgorithm = symmetricAlgorithm; + this.argon2Params = argon2Params; + } + + public JcaAEADSecretKeyEncryptorBuilder setProvider(Provider provider) + { + this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + this.aeadUtil = new JceAEADUtil(helper); + + return this; + } + + public JcaAEADSecretKeyEncryptorBuilder setProvider(String providerName) + { + this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + this.aeadUtil = new JceAEADUtil(helper); + + return this; + } + + public PBESecretKeyEncryptor build(char[] passphrase, final PublicKeyPacket pubKey) + { + return new PBESecretKeyEncryptor(symmetricAlgorithm, aeadAlgorithm, argon2Params, new SecureRandom(), passphrase) + { + private byte[] iv; + + { + iv = new byte[AEADUtils.getIVLength(aeadAlgorithm)]; + random.nextBytes(iv); + } + + @Override + public byte[] encryptKeyData(byte[] key, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + try + { + return JceAEADUtil.processAeadKeyData( + aeadUtil, + Cipher.ENCRYPT_MODE, + encAlgorithm, + aeadAlgorithm, + getKey(), + iv, + pubKey.getPacketTag() == PacketTags.PUBLIC_KEY ? PacketTags.SECRET_KEY : PacketTags.SECRET_SUBKEY, + pubKey.getVersion(), + keyData, + keyOff, + keyLen, + pubKey.getEncodedContents()); + } + catch (Exception e) + { + throw new PGPException("Exception AEAD protecting private key material", e); + } + } + + @Override + public byte[] getCipherIV() + { + return iv; + } + }; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorFactory.java new file mode 100644 index 0000000000..199c2af3b1 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorFactory.java @@ -0,0 +1,35 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; + +import java.security.Provider; + +public class JcaAEADSecretKeyEncryptorFactory + implements PBESecretKeyEncryptorFactory +{ + private JcaAEADSecretKeyEncryptorBuilder builder = new JcaAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, + SymmetricKeyAlgorithmTags.AES_256, + S2K.Argon2Params.memoryConstrainedParameters()); + + public JcaAEADSecretKeyEncryptorFactory setProvider(Provider provider) + { + builder.setProvider(provider); + return this; + } + + @Override + public PBESecretKeyEncryptor build(char[] passphrase, PublicKeyPacket pubKeyPacket) + { + if (passphrase == null) + { + return null; + } + return builder.build(passphrase, pubKeyPacket); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaCFBSecretKeyEncryptorFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaCFBSecretKeyEncryptorFactory.java new file mode 100644 index 0000000000..c8a576b7fe --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaCFBSecretKeyEncryptorFactory.java @@ -0,0 +1,56 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptorFactory; + +import java.security.Provider; + +public class JcaCFBSecretKeyEncryptorFactory + implements PBESecretKeyEncryptorFactory +{ + private final int symmetricKeyAlgorithm; + private final int iterationCount; + private JcaPGPDigestCalculatorProviderBuilder digestCalcProviderBuilder = + new JcaPGPDigestCalculatorProviderBuilder(); + private JcePBESecretKeyEncryptorBuilder encBuilder; + + public JcaCFBSecretKeyEncryptorFactory(int symmetricKeyAlgorithm, int iterationCount) + throws PGPException + { + this.symmetricKeyAlgorithm = symmetricKeyAlgorithm; + this.iterationCount = iterationCount; + encBuilder = builder(); + } + + public JcaCFBSecretKeyEncryptorFactory setProvider(Provider provider) + throws PGPException + { + digestCalcProviderBuilder.setProvider(provider); + encBuilder = builder(); + return this; + } + + private JcePBESecretKeyEncryptorBuilder builder() + throws PGPException + { + return new JcePBESecretKeyEncryptorBuilder( + symmetricKeyAlgorithm, + digestCalcProviderBuilder.build().get(HashAlgorithmTags.SHA1), + iterationCount + ); + } + + @Override + public PBESecretKeyEncryptor build(char[] passphrase, PublicKeyPacket pubKeyPacket) + { + if (passphrase == null) + { + return null; + } + return encBuilder.build(passphrase); + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java index 8d1a75b737..51b944e3ff 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java @@ -12,6 +12,8 @@ import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.bcpg.PublicKeyPacket; @@ -68,7 +70,7 @@ static X9ECParameters getX9Parameters(ASN1ObjectIdentifier curveOID) static HybridValueParameterSpec getHybridValueParameterSpecWithPrepend(byte[] ephmeralPublicKey, PublicKeyPacket pkp, String algorithmName) throws IOException { - return new HybridValueParameterSpec(Arrays.concatenate(ephmeralPublicKey, pkp.getEncoded()), true, new UserKeyingMaterialSpec(Strings.toByteArray("OpenPGP " + algorithmName))); + return new HybridValueParameterSpec(Arrays.concatenate(ephmeralPublicKey, pkp.getKey().getEncoded()), true, new UserKeyingMaterialSpec(Strings.toByteArray("OpenPGP " + algorithmName))); } static Key getSecret(OperatorHelper helper, PublicKey cryptoPublicKey, String keyEncryptionOID, String agreementName, AlgorithmParameterSpec ukmSpec, Key privKey) @@ -79,4 +81,9 @@ static Key getSecret(OperatorHelper helper, PublicKey cryptoPublicKey, String ke agreement.doPhase(cryptoPublicKey, true); return agreement.generateSecret(keyEncryptionOID); } + + static boolean isX25519(ASN1ObjectIdentifier curveID) + { + return curveID.equals(CryptlibObjectIdentifiers.curvey25519) || curveID.equals(EdECObjectIdentifiers.id_X25519); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java index fab2ba5d9d..ba57198af1 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java @@ -1,6 +1,7 @@ package org.bouncycastle.openpgp.operator.jcajce; import java.io.IOException; +import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; @@ -63,7 +64,7 @@ public byte[] calculateFingerprint(PublicKeyPacket publicPk) { BCPGKey key = publicPk.getKey(); - if (publicPk.getVersion() <= 3) + if (publicPk.getVersion() <= PublicKeyPacket.VERSION_3) { RSAPublicBCPGKey rK = (RSAPublicBCPGKey)key; @@ -79,11 +80,7 @@ public byte[] calculateFingerprint(PublicKeyPacket publicPk) return digest.digest(); } - catch (NoSuchAlgorithmException e) - { - throw new PGPException("can't find MD5", e); - } - catch (NoSuchProviderException e) + catch (GeneralSecurityException e) { throw new PGPException("can't find MD5", e); } @@ -92,7 +89,7 @@ public byte[] calculateFingerprint(PublicKeyPacket publicPk) throw new PGPException("can't encode key components: " + e.getMessage(), e); } } - else if (publicPk.getVersion() == 4) + else if (publicPk.getVersion() == PublicKeyPacket.VERSION_4) { try { @@ -107,11 +104,7 @@ else if (publicPk.getVersion() == 4) return digest.digest(); } - catch (NoSuchAlgorithmException e) - { - throw new PGPException("can't find SHA1", e); - } - catch (NoSuchProviderException e) + catch (GeneralSecurityException e) { throw new PGPException("can't find SHA1", e); } @@ -120,7 +113,7 @@ else if (publicPk.getVersion() == 4) throw new PGPException("can't encode key components: " + e.getMessage(), e); } } - else if (publicPk.getVersion() == 6) + else if (publicPk.getVersion() == PublicKeyPacket.LIBREPGP_5 || publicPk.getVersion() == PublicKeyPacket.VERSION_6) { try { @@ -128,7 +121,7 @@ else if (publicPk.getVersion() == 6) MessageDigest digest = helper.createMessageDigest("SHA-256"); - digest.update((byte)0x9b); + digest.update((byte) (publicPk.getVersion() == PublicKeyPacket.VERSION_6 ? 0x9b : 0x9a)); digest.update((byte)(kBytes.length >> 24)); digest.update((byte)(kBytes.length >> 16)); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilder.java index de028e85cc..46968de581 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilder.java @@ -95,7 +95,16 @@ public PGPContentSigner build(final int signatureType, final long keyID, final P final PGPDigestCalculator digestCalculator = digestCalculatorProviderBuilder.build().get(hashAlgorithm); final PGPDigestCalculator edDigestCalculator = digestCalculatorProviderBuilder.build().get(hashAlgorithm); final Signature signature; - signature = helper.createSignature(keyAlgorithm, hashAlgorithm); + + if (keyAlgorithm == PublicKeyAlgorithmTags.EDDSA_LEGACY && privateKey.getAlgorithm().equals("Ed448")) + { + signature = helper.createSignature("Ed448"); + } + else + { + signature = helper.createSignature(keyAlgorithm, hashAlgorithm); + } + try { diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilderProvider.java new file mode 100644 index 0000000000..bf2a725d20 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentSignerBuilderProvider.java @@ -0,0 +1,61 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilderProvider; + +import java.security.Provider; +import java.security.SecureRandom; + +public class JcaPGPContentSignerBuilderProvider + extends PGPContentSignerBuilderProvider +{ + private Provider digestProvider; + private Provider securityProvider; + private SecureRandom secureRandom; + + public JcaPGPContentSignerBuilderProvider(int hashAlgorithmId) + { + super(hashAlgorithmId); + } + + public JcaPGPContentSignerBuilderProvider setDigestProvider(Provider provider) + { + this.digestProvider = provider; + return this; + } + + public JcaPGPContentSignerBuilderProvider setSecurityProvider(Provider provider) + { + this.securityProvider = provider; + return this; + } + + public JcaPGPContentSignerBuilderProvider setSecureRandom(SecureRandom random) + { + this.secureRandom = random; + return this; + } + + @Override + public PGPContentSignerBuilder get(PGPPublicKey signingKey) + { + JcaPGPContentSignerBuilder builder = new JcaPGPContentSignerBuilder( + signingKey.getAlgorithm(), hashAlgorithmId); + if (digestProvider != null) + { + builder.setDigestProvider(digestProvider); + } + + if (securityProvider != null) + { + builder.setProvider(securityProvider); + } + + if (secureRandom != null) + { + builder.setSecureRandom(secureRandom); + } + return builder; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentVerifierBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentVerifierBuilderProvider.java index de459a43ac..73f33ec310 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentVerifierBuilderProvider.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPContentVerifierBuilderProvider.java @@ -8,8 +8,6 @@ import java.security.SignatureException; import java.security.interfaces.RSAPublicKey; -import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; -import org.bouncycastle.bcpg.EdDSAPublicBCPGKey; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.jcajce.io.OutputStreamFactory; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; @@ -73,11 +71,19 @@ public JcaPGPContentVerifierBuilder(int keyAlgorithm, int hashAlgorithm) public PGPContentVerifier build(final PGPPublicKey publicKey) throws PGPException { - final Signature signature = helper.createSignature(keyAlgorithm, hashAlgorithm); - final PGPDigestCalculator digestCalculator = digestCalculatorProviderBuilder.build().get(hashAlgorithm); final PublicKey jcaKey = keyConverter.getPublicKey(publicKey); + final Signature signature; + if (keyAlgorithm == PublicKeyAlgorithmTags.EDDSA_LEGACY && jcaKey.getAlgorithm().equals("Ed448")) + { + signature = helper.createSignature(PublicKeyAlgorithmTags.Ed448, hashAlgorithm); + } + else + { + signature = helper.createSignature(keyAlgorithm, hashAlgorithm); + } + try { signature.initVerify(jcaKey); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java index 66e0179a34..28cd4bb57f 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java @@ -5,8 +5,6 @@ import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; @@ -14,22 +12,20 @@ import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; -import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPrivateKeySpec; import java.security.spec.ECPublicKeySpec; -import java.security.spec.InvalidParameterSpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Date; +import java.util.Enumeration; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; @@ -37,6 +33,7 @@ import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.DHPublicKeySpec; +import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DEROctetString; @@ -47,9 +44,11 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ECParametersHolder; import org.bouncycastle.asn1.x9.X9ECPoint; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.bcpg.BCPGKey; import org.bouncycastle.bcpg.DSAPublicBCPGKey; import org.bouncycastle.bcpg.DSASecretBCPGKey; @@ -73,13 +72,16 @@ import org.bouncycastle.bcpg.X25519SecretBCPGKey; import org.bouncycastle.bcpg.X448PublicBCPGKey; import org.bouncycastle.bcpg.X448SecretBCPGKey; +import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; - import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; import org.bouncycastle.math.ec.rfc8032.Ed25519; +import org.bouncycastle.math.ec.rfc8032.Ed448; import org.bouncycastle.openpgp.PGPAlgorithmParameters; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKdfParameters; @@ -127,7 +129,7 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -138,17 +140,39 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PGPAlgorithmParameters, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) throws PGPException + { + return getPGPPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, time); + } + + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param algorithmParameters additional parameters to be stored against the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + throws PGPException { BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey); - return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), fingerPrintCalculator); + return new PGPPublicKey(new PublicKeyPacket(version, algorithm, time, bcpgKey), fingerPrintCalculator); } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -158,13 +182,34 @@ public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algori * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PublicKey pubKey, Date time) throws PGPException { return getPGPPublicKey(algorithm, null, pubKey, time); } + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(version, algorithm, null, pubKey, time); + } + public PrivateKey getPrivateKey(PGPPrivateKey privKey) throws PGPException { @@ -194,45 +239,133 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) ECDHPublicBCPGKey ecdhPub = (ECDHPublicBCPGKey)pubPk.getKey(); ECSecretBCPGKey ecdhK = (ECSecretBCPGKey)privPk; - if (CryptlibObjectIdentifiers.curvey25519.equals(ecdhPub.getCurveOID())) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhPub.getCurveOID())) { // 'reverse' because the native format for X25519 private keys is little-endian - return implGeneratePrivate("XDH", () -> getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, - Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX())))); + return implGeneratePrivate("XDH", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } + }); } + // Legacy X448 (1.3.101.111) + else if (EdECObjectIdentifiers.id_X448.equals(ecdhPub.getCurveOID())) + { + // 'reverse' because the native format for X448 private keys is little-endian (?) + return implGeneratePrivate("XDH", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } + }); + } + // Brainpool, NIST etc. else { return implGetPrivateKeyEC("ECDH", ecdhPub, ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { - return implGeneratePrivate("XDH", () -> getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, - X25519SecretBCPGKey.LENGTH, Arrays.reverseInPlace(privPk.getEncoded()))); + return implGeneratePrivate("XDH", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + X25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { - return implGeneratePrivate("XDH", () -> getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, - X448SecretBCPGKey.LENGTH, Arrays.reverseInPlace(privPk.getEncoded()))); + return implGeneratePrivate("XDH", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + X448SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); } case PublicKeyAlgorithmTags.ECDSA: { - return implGetPrivateKeyEC("ECDSA", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); + return implGetPrivateKeyEC("EC", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return implGeneratePrivate("EdDSA", () -> getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, - BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX()))); + EdDSAPublicBCPGKey eddsaPub = (EdDSAPublicBCPGKey)pubPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaPub.getCurveOID())) + { + return implGeneratePrivate("EdDSA", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + BigIntegers.asUnsignedByteArray(Ed448.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 + return implGeneratePrivate("EdDSA", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { - return implGeneratePrivate("EdDSA", () -> getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, - Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded())); + return implGeneratePrivate("EdDSA", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { - return implGeneratePrivate("EdDSA", () -> getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, - Ed448SecretBCPGKey.LENGTH, privPk.getEncoded())); + return implGeneratePrivate("EdDSA", new Operation() + { + @Override + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: @@ -289,47 +422,63 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) { ECDHPublicBCPGKey ecdhK = (ECDHPublicBCPGKey)publicPk.getKey(); - if (ecdhK.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhK.getCurveOID())) { return get25519PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X25519, "XDH", "Curve"); } + // Legacy X448 (1.3.101.111) + else if (ecdhK.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + return get448PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X448, "XDH", "Curve"); + } + // Brainpool, NIST etc. else { return implGetPublicKeyEC("ECDH", ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X25519, "XDH"); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X448, "XDH"); } case PublicKeyAlgorithmTags.ECDSA: - return implGetPublicKeyEC("ECDSA", (ECDSAPublicBCPGKey)publicPk.getKey()); - - case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return get25519PublicKey(((EdDSAPublicBCPGKey)publicPk.getKey()).getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); + return implGetPublicKeyEC("EC", (ECDSAPublicBCPGKey)publicPk.getKey()); } - case PublicKeyAlgorithmTags.Ed25519: + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - BCPGKey key = publicPk.getKey(); - if (key instanceof Ed25519PublicBCPGKey) + EdDSAPublicBCPGKey eddsaKey = (EdDSAPublicBCPGKey)publicPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaKey.getCurveOID())) { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(new BigInteger(1, publicPk.getKey().getEncoded())), - 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + return get448PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed448, "EdDSA", "Ed"); } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 else { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(((EdDSAPublicBCPGKey)publicPk.getKey()).getEncodedPoint()), - 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + return get25519PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); } } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(new BigInteger(1, publicPk.getKey().getEncoded())), + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_Ed448, "EdDSA"); } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: @@ -363,12 +512,12 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) } } - private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid, X9ECParameters x9Params) - throws InvalidParameterSpecException, NoSuchProviderException, NoSuchAlgorithmException + private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid) + throws IOException, GeneralSecurityException { AlgorithmParameters params = helper.createAlgorithmParameters("EC"); - params.init(new ECGenParameterSpec(ECNamedCurveTable.getName(curveOid))); + params.init(new X962Parameters(curveOid).getEncoded()); return params.getParameterSpec(ECParameterSpec.class); } @@ -380,7 +529,6 @@ private BCPGKey getPrivateBCPGKey(PrivateKey privKey, BCPGKeyOperation operation try { - // 'reverse' because the native format for X25519 private keys is little-endian return operation.getBCPGKey(ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets()); } catch (IOException e) @@ -409,35 +557,80 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) } else { - // 'reverse' because the native format for X25519 private keys is little-endian - return getPrivateBCPGKey(privKey, (pInfoEncoded) -> new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(pInfoEncoded)))); + // 'reverse' because the native format for X25519,X448 private keys is little-endian + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(key))); + } + }); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { - // 'reverse' because the native format for X25519 private keys is little-endian - return getPrivateBCPGKey(privKey, (pInfoEncoded) -> new X25519SecretBCPGKey(Arrays.reverse(pInfoEncoded))); + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519SecretBCPGKey(key); + } + }); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { - // 'reverse' because the native format for X448 private keys is little-endian - return getPrivateBCPGKey(privKey, (pInfoEncoded) -> new X448SecretBCPGKey(Arrays.reverse(pInfoEncoded))); + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new X448SecretBCPGKey(key); + } + }); } case PublicKeyAlgorithmTags.ECDSA: { return new ECSecretBCPGKey(((ECPrivateKey)privKey).getS()); } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return getPrivateBCPGKey(privKey, (pInfoEncoded) -> new EdSecretBCPGKey(new BigInteger(1, pInfoEncoded))); + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new EdSecretBCPGKey(new BigInteger(1, key)); + } + }); } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { - return getPrivateBCPGKey(privKey, Ed25519SecretBCPGKey::new); + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519SecretBCPGKey(key); + } + }); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { - return getPrivateBCPGKey(privKey, Ed448SecretBCPGKey::new); + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448SecretBCPGKey(key); + } + }); } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: @@ -453,36 +646,102 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) return new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ()); } default: - throw new PGPException("unknown key class"); + throw new PGPException("unknown public key algorithm encountered: " + pub.getAlgorithm()); } } private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey) throws PGPException { - if (pubKey instanceof RSAPublicKey) + switch (algorithm) + { + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_SIGN: { RSAPublicKey rK = (RSAPublicKey)pubKey; return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); } - else if (pubKey instanceof DSAPublicKey) + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + DHPublicKey egK = (DHPublicKey)pubKey; + return new ElGamalPublicBCPGKey(egK.getParams().getP(), egK.getParams().getG(), egK.getY()); + } + case PublicKeyAlgorithmTags.DSA: { DSAPublicKey dK = (DSAPublicKey)pubKey; DSAParams dP = dK.getParams(); return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); } - else if (pubKey instanceof DHPublicKey) + + case PublicKeyAlgorithmTags.DIFFIE_HELLMAN: { DHPublicKey eK = (DHPublicKey)pubKey; DHParameterSpec eS = eK.getParams(); return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); } - else if (pubKey instanceof ECPublicKey) + + case PublicKeyAlgorithmTags.ECDH: + case PublicKeyAlgorithmTags.ECDSA: { SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); // TODO: should probably match curve by comparison as well - ASN1ObjectIdentifier curveOid = ASN1ObjectIdentifier.getInstance(keyInfo.getAlgorithm().getParameters()); + ASN1Encodable enc = keyInfo.getAlgorithm().getAlgorithm(); + ASN1ObjectIdentifier curveOid; + curveOid = ASN1ObjectIdentifier.getInstance(enc); + + // BCECPublicKey uses explicit parameter encoding, so we need to find the named curve manually + if (X9ObjectIdentifiers.id_ecPublicKey.equals(curveOid)) + { + enc = getNamedCurveOID(X962Parameters.getInstance(keyInfo.getAlgorithm().getParameters())); + ASN1ObjectIdentifier nCurveOid = ASN1ObjectIdentifier.getInstance(enc); + if (nCurveOid != null) + { + curveOid = nCurveOid; + } + } + + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + if (pubKey.getAlgorithm().regionMatches(true, 0, "X4", 0, 2)) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // sun.security.ec.XDHPublicKeyImpl returns "XDH" for getAlgorithm() + // In this case we need to determine the curve by looking at the length of the encoding :/ + else if (pubKey.getAlgorithm().regionMatches(true, 0, "XDH", 0, 3)) + { + // Legacy X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + if (X25519.SCALAR_SIZE + 12 == pubKey.getEncoded().length) // + 12 for some reason + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + else + { + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + } X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); @@ -491,51 +750,132 @@ else if (pubKey instanceof ECPublicKey) if (algorithm == PGPPublicKey.ECDH) { + PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); } - else if (algorithm == PGPPublicKey.ECDSA) + else { return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); } + } + + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) + { + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + // Legacy Ed448 (1.3.101.113) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED4", 0, 3)) + { + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + // Manual matching on curve encoding length else { - throw new PGPException("unknown EC algorithm"); + // sun.security.ec.ed.EdDSAPublicKeyImpl returns "EdDSA" for getAlgorithm() + // if algorithm is just EdDSA, we need to detect the curve based on encoding length :/ + if (pubKey.getEncoded().length == 12 + Ed25519.PUBLIC_KEY_SIZE) // +12 for some reason + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + else + { + // Legacy Ed448 (1.3.101.113) + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } } } - else if (algorithm == PGPPublicKey.Ed25519) + + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: { - return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, Ed25519PublicBCPGKey::new); + return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519PublicBCPGKey(key); + } + }); } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) + + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: { - return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448PublicBCPGKey(key); + } + }); } - else if (algorithm == PGPPublicKey.X25519) + + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: { - return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, X25519PublicBCPGKey::new); + return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519PublicBCPGKey(key); + } + }); } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: { - PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + @Override + public BCPGKey getBCPGKey(byte[] key) + { + return new X448PublicBCPGKey(key); + } + }); + } - return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), - kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + default: + throw new PGPException("unknown public key algorithm encountered: " + algorithm); } - else if (algorithm == PGPPublicKey.Ed448) + } + + private ASN1Encodable getNamedCurveOID(X962Parameters ecParams) + { + ECCurve curve = null; + if (ecParams.isNamedCurve()) { - return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, Ed448PublicBCPGKey::new); + return ASN1ObjectIdentifier.getInstance(ecParams.getParameters()); } - else if (algorithm == PGPPublicKey.X448) + else if (ecParams.isImplicitlyCA()) { - return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, X448PublicBCPGKey::new); + curve = ((X9ECParameters)CryptoServicesRegistrar.getProperty(CryptoServicesRegistrar.Property.EC_IMPLICITLY_CA)).getCurve(); } else { - throw new PGPException("unknown key class"); + curve = X9ECParameters.getInstance(ecParams.getParameters()).getCurve(); + } + + // Iterate through all registered curves to find applicable OID + Enumeration names = ECNamedCurveTable.getNames(); + while (names.hasMoreElements()) + { + String name = (String)names.nextElement(); + X9ECParameters parms = ECNamedCurveTable.getByName(name); + if (curve.equals(parms.getCurve())) + { + return ECNamedCurveTable.getOID(name); + } } + return null; } @FunctionalInterface @@ -546,34 +886,35 @@ private interface BCPGKeyOperation private BCPGKey getPublicBCPGKey(PublicKey pubKey, int keySize, BCPGKeyOperation operation) { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); byte[] pointEnc = new byte[keySize]; - - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 0, pointEnc.length); + // refer to getPointEncUncompressed + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length, pubInfo.length); return operation.getBCPGKey(pointEnc); } private byte[] getPointEncUncompressed(PublicKey pubKey, int publicKeySize) { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); byte[] pointEnc = new byte[1 + publicKeySize]; pointEnc[0] = 0x40; - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 1, pointEnc.length - 1); + //offset with pointEnc.length - pubInfo.length to avoid leading zero issue + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length, pubInfo.length); return pointEnc; } @FunctionalInterface private interface Operation { - PrivateKeyInfo getPrivateKeyInfo() + PrivateKeyInfo getPrivateKeyInfos() throws IOException; } private PrivateKey implGeneratePrivate(String keyAlgorithm, Operation operation) throws GeneralSecurityException, PGPException, IOException { - PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(operation.getPrivateKeyInfo().getEncoded()); + PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(operation.getPrivateKeyInfos().getEncoded()); KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); return keyFactory.generatePrivate(pkcs8Spec); } @@ -600,10 +941,10 @@ private PublicKey implGetPublicKeyX509(byte[] pEnc, int pEncOff, ASN1ObjectIdent } private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) - throws GeneralSecurityException, PGPException + throws GeneralSecurityException, PGPException, IOException { ASN1ObjectIdentifier curveOid = ecPub.getCurveOID(); - ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid, JcaJcePGPUtil.getX9Parameters(curveOid))); + ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid)); return implGeneratePrivate(keyAlgorithm, ecPrivSpec); } @@ -617,7 +958,7 @@ private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) new java.security.spec.ECPoint( ecPubPoint.getAffineXCoord().toBigInteger(), ecPubPoint.getAffineYCoord().toBigInteger()), - getECParameterSpec(curveOID, x9Params)); + getECParameterSpec(curveOID)); return implGeneratePublic(keyAlgorithm, ecPubSpec); } @@ -633,4 +974,17 @@ private PublicKey get25519PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm } return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); } + + private PublicKey get448PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "448 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPair.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPair.java index 6bf5d3dfc2..86f8f8d75c 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPair.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPair.java @@ -5,6 +5,7 @@ import java.security.PublicKey; import java.util.Date; +import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.openpgp.PGPAlgorithmParameters; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKeyPair; @@ -17,16 +18,30 @@ public class JcaPGPKeyPair extends PGPKeyPair { + @Deprecated private static PGPPublicKey getPublicKey(int algorithm, PublicKey pubKey, Date date) throws PGPException { - return new JcaPGPKeyConverter().getPGPPublicKey(algorithm, pubKey, date); + return getPublicKey(PublicKeyPacket.VERSION_4, algorithm, pubKey, date); } + private static PGPPublicKey getPublicKey(int version, int algorithm, PublicKey pubKey, Date date) + throws PGPException + { + return new JcaPGPKeyConverter().getPGPPublicKey(version, algorithm, pubKey, date); + } + + @Deprecated private static PGPPublicKey getPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date date) throws PGPException { - return new JcaPGPKeyConverter().getPGPPublicKey(algorithm, algorithmParameters, pubKey, date); + return getPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, date); + } + + private static PGPPublicKey getPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date date) + throws PGPException + { + return new JcaPGPKeyConverter().getPGPPublicKey(version, algorithm, algorithmParameters, pubKey, date); } private static PGPPrivateKey getPrivateKey(PGPPublicKey pub, PrivateKey privKey) @@ -36,33 +51,68 @@ private static PGPPrivateKey getPrivateKey(PGPPublicKey pub, PrivateKey privKey) } /** - * Construct PGP key pair from a JCA/JCE key pair. + * Construct version 4 PGP key pair from a JCA/JCE key pair. * * @param algorithm the PGP algorithm the key is for. * @param keyPair the public/private key pair to convert. * @param date the creation date to associate with the key pair. * @throws PGPException if conversion fails. + * @deprecated use versioned {@link #JcaPGPKeyPair(int, int, KeyPair, Date)} instead */ + @Deprecated public JcaPGPKeyPair(int algorithm, KeyPair keyPair, Date date) throws PGPException { - this.pub = getPublicKey(algorithm, keyPair.getPublic(), date); - this.priv = getPrivateKey(this.pub, keyPair.getPrivate()); + this(PublicKeyPacket.VERSION_4, algorithm, keyPair, date); } /** * Construct PGP key pair from a JCA/JCE key pair. * + * @param version key version. + * @param algorithm the PGP algorithm the key is for. + * @param keyPair the public/private key pair to convert. + * @param date the creation date to associate with the key pair. + * @throws PGPException if conversion fails. + */ + public JcaPGPKeyPair(int version, int algorithm, KeyPair keyPair, Date date) + throws PGPException + { + this.pub = getPublicKey(version, algorithm, keyPair.getPublic(), date); + this.priv = getPrivateKey(this.pub, keyPair.getPrivate()); + } + + /** + * Construct version 4 PGP key pair from a JCA/JCE key pair. + * * @param algorithm the PGP algorithm the key is for. * @param parameters additional parameters to be stored against the public key. * @param keyPair the public/private key pair to convert. * @param date the creation date to associate with the key pair. * @throws PGPException if conversion fails. + * @deprecated use versioned {@link #JcaPGPKeyPair(int, int, PGPAlgorithmParameters, KeyPair, Date)} instead */ + @Deprecated public JcaPGPKeyPair(int algorithm, PGPAlgorithmParameters parameters, KeyPair keyPair, Date date) throws PGPException { - this.pub = getPublicKey(algorithm, parameters, keyPair.getPublic(), date); + this(PublicKeyPacket.VERSION_4, algorithm, parameters, keyPair, date); + } + + /** + * Construct PGP key pair from a JCA/JCE key pair. + * + * @param version key version. + * @param algorithm the PGP algorithm the key is for. + * @param parameters additional parameters to be stored against the public key. + * @param keyPair the public/private key pair to convert. + * @param date the creation date to associate with the key pair. + * @throws PGPException if conversion fails. + */ + public JcaPGPKeyPair(int version, int algorithm, PGPAlgorithmParameters parameters, KeyPair keyPair, Date date) + throws PGPException + { + this.pub = getPublicKey(version, algorithm, parameters, keyPair.getPublic(), date); this.priv = getPrivateKey(this.pub, keyPair.getPrivate()); } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPairGeneratorProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPairGeneratorProvider.java new file mode 100644 index 0000000000..bb69846cc0 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyPairGeneratorProvider.java @@ -0,0 +1,255 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jcajce.spec.XDHParameterSpec; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; +import org.bouncycastle.openpgp.operator.PGPKeyPairGeneratorProvider; + +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.spec.RSAKeyGenParameterSpec; +import java.util.Date; + +public class JcaPGPKeyPairGeneratorProvider + extends PGPKeyPairGeneratorProvider +{ + + private OperatorHelper helper; + private SecureRandom secureRandom = CryptoServicesRegistrar.getSecureRandom(); + + public JcaPGPKeyPairGeneratorProvider() + { + this.helper = new OperatorHelper(new DefaultJcaJceHelper()); + } + + + /** + * Set the provider object to use for creating cryptographic primitives in the resulting factory the builder produces. + * + * @param provider provider object for cryptographic primitives. + * @return the current builder. + */ + public JcaPGPKeyPairGeneratorProvider setProvider(Provider provider) + { + this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + return this; + } + + /** + * Set the provider name to use for creating cryptographic primitives in the resulting factory the builder produces. + * + * @param providerName the name of the provider to reference for cryptographic primitives. + * @return the current builder. + */ + public JcaPGPKeyPairGeneratorProvider setProvider(String providerName) + { + this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + return this; + } + + public JcaPGPKeyPairGeneratorProvider setSecureRandom(SecureRandom random) + { + this.secureRandom = random; + return this; + } + + + @Override + public PGPKeyPairGenerator get(int version, Date creationTime) + { + return new JcaPGPKeyPairGenerator(version, creationTime, helper, secureRandom); + } + + private static class JcaPGPKeyPairGenerator + extends PGPKeyPairGenerator + { + + private final OperatorHelper helper; + + public JcaPGPKeyPairGenerator(int version, Date creationTime, OperatorHelper helper, SecureRandom random) + { + super(version, creationTime, random, new JcaKeyFingerprintCalculator()); + this.helper = helper; + } + + @Override + public PGPKeyPair generateRsaKeyPair(BigInteger exponent, int bitStrength) + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("RSA"); + gen.initialize(new RSAKeyGenParameterSpec(bitStrength, exponent)); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.RSA_GENERAL, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate RSA key pair", e); + } + } + + @Override + public PGPKeyPair generateEd25519KeyPair() + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("EDDSA"); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate Ed25519 key pair", e); + } + } + + @Override + public PGPKeyPair generateEd448KeyPair() + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("EDDSA"); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.Ed448, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate Ed448 key pair", e); + } + } + + @Override + public PGPKeyPair generateX25519KeyPair() + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("XDH"); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.X25519, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate X25519 key pair", e); + } + } + + @Override + public PGPKeyPair generateX448KeyPair() + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("XDH"); + gen.initialize(new XDHParameterSpec("X448")); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.X448, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate X448 key pair", e); + } + } + + @Override + public PGPKeyPair generateLegacyEd25519KeyPair() + throws PGPException + { + if (version == PublicKeyPacket.VERSION_6) + { + throw new PGPException("An implementation MUST NOT generate a v6 LegacyEd25519 key pair."); + } + + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("EDDSA"); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.EDDSA_LEGACY, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate LegacyEd25519 key pair."); + } + } + + @Override + public PGPKeyPair generateLegacyX25519KeyPair() + throws PGPException + { + if (version == PublicKeyPacket.VERSION_6) + { + throw new PGPException("An implementation MUST NOT generate a v6 LegacyX25519 key pair."); + } + + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("XDH"); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.ECDH, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate LegacyX25519 key pair.", e); + } + } + + @Override + public PGPKeyPair generateECDHKeyPair(ASN1ObjectIdentifier curveOID) + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("ECDH"); + String curveName = ECUtil.getCurveName(curveOID); + gen.initialize(new ECNamedCurveGenParameterSpec(curveName)); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.ECDH, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate ECDH key pair.", e); + } + } + + @Override + public PGPKeyPair generateECDSAKeyPair(ASN1ObjectIdentifier curveOID) + throws PGPException + { + try + { + KeyPairGenerator gen = helper.createKeyPairGenerator("ECDSA"); + String curveName = ECUtil.getCurveName(curveOID); + gen.initialize(new ECNamedCurveGenParameterSpec(curveName)); + KeyPair keyPair = gen.generateKeyPair(); + return new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.ECDSA, keyPair, creationTime); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Cannot generate ECDSA key pair.", e); + } + } + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java index 8d5024eab5..66ca662fe7 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java @@ -99,17 +99,23 @@ protected static long getChunkLength(int chunkSize) static byte[][] deriveMessageKeyAndIv(int aeadAlgo, int cipherAlgo, byte[] sessionKey, byte[] salt, byte[] hkdfInfo) throws PGPException { - // TODO: needs to be JCA based. KeyGenerator? + // TODO: needs to be JCA based. KeyGenerator + int keyLen = SymmetricKeyUtils.getKeyLengthInOctets(cipherAlgo); + int ivLen = AEADUtils.getIVLength(aeadAlgo); + byte[] messageKeyAndIv = generateHKDFBytes(sessionKey, salt, hkdfInfo, keyLen + ivLen - 8); + + return new byte[][]{Arrays.copyOfRange(messageKeyAndIv, 0, keyLen), Arrays.copyOfRange(messageKeyAndIv, keyLen, keyLen + ivLen)}; + } + + static byte[] generateHKDFBytes(byte[] sessionKey, byte[] salt, byte[] hkdfInfo, int len) + { HKDFParameters hkdfParameters = new HKDFParameters(sessionKey, salt, hkdfInfo); HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); hkdfGen.init(hkdfParameters); - int keyLen = SymmetricKeyUtils.getKeyLengthInOctets(cipherAlgo); - int ivLen = AEADUtils.getIVLength(aeadAlgo); - byte[] messageKeyAndIv = new byte[keyLen + ivLen - 8]; + byte[] messageKeyAndIv = new byte[len]; hkdfGen.generateBytes(messageKeyAndIv, 0, messageKeyAndIv.length); - - return new byte[][]{Arrays.copyOfRange(messageKeyAndIv, 0, keyLen), Arrays.copyOfRange(messageKeyAndIv, keyLen, keyLen + ivLen)}; + return messageKeyAndIv; } /** @@ -270,6 +276,29 @@ Cipher createAEADCipher(int encAlgorithm, int aeadAlgorithm) return helper.createCipher(cName); } + static byte[] processAeadKeyData(JceAEADUtil aeadUtil, int mode, int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, int keyOff, int keyLen, byte[] pubkeyData) + throws PGPException + { + // TODO: Replace HDKF code with JCE based implementation + byte[] key = generateHKDFBytes(s2kKey, null, + new byte[]{(byte)(0xC0 | packetTag), (byte)keyVersion, (byte)encAlgorithm, (byte)aeadAlgorithm}, + SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)); + + try + { + byte[] aad = Arrays.prepend(pubkeyData, (byte)(0xC0 | packetTag)); + SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm)); + final Cipher c = aeadUtil.createAEADCipher(encAlgorithm, aeadAlgorithm); + + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, mode, iv, 128, aad); + return c.doFinal(keyData, keyOff, keyLen); + } + catch (GeneralSecurityException e) + { + throw new PGPException("Exception recovering AEAD protected private key material", e); + } + } + static class PGPAeadInputStream extends InputStream { diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEDataDecryptorFactoryBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEDataDecryptorFactoryBuilder.java index 8687678369..74f69dc398 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEDataDecryptorFactoryBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEDataDecryptorFactoryBuilder.java @@ -12,9 +12,7 @@ import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket; import org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket; import org.bouncycastle.bcpg.SymmetricKeyUtils; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.generators.HKDFBytesGenerator; -import org.bouncycastle.crypto.params.HKDFParameters; +import org.bouncycastle.bcpg.UnsupportedPacketVersionException; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; @@ -143,15 +141,24 @@ public byte[] recoverAEADEncryptedSessionData(SymmetricKeyEncSessionPacket keyDa } byte[] hkdfInfo = keyData.getAAData(); // between v5 and v6, these bytes differ - int kekLen = SymmetricKeyUtils.getKeyLengthInOctets(keyData.getEncAlgorithm()); - byte[] kek = new byte[kekLen]; - // HKDF - // secretKey := HKDF_sha256(ikm, hkdfInfo).generate() - HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); // SHA256 is fixed - hkdfGen.init(new HKDFParameters(ikm, null, hkdfInfo)); - hkdfGen.generateBytes(kek, 0, kek.length); - final SecretKey secretKey = new SecretKeySpec(kek, PGPUtil.getSymmetricCipherName(keyData.getEncAlgorithm())); + SecretKey secretKey; + if (keyData.getVersion() == SymmetricKeyEncSessionPacket.VERSION_5) + { + secretKey = new SecretKeySpec(ikm, PGPUtil.getSymmetricCipherName(keyData.getEncAlgorithm())); + } + else if (keyData.getVersion() == SymmetricKeyEncSessionPacket.VERSION_6) + { + // HKDF + // secretKey := HKDF_sha256(ikm, hkdfInfo).generate() + int kekLen = SymmetricKeyUtils.getKeyLengthInOctets(keyData.getEncAlgorithm()); + byte[] kek = JceAEADUtil.generateHKDFBytes(ikm, null, hkdfInfo, kekLen); + secretKey = new SecretKeySpec(kek, PGPUtil.getSymmetricCipherName(keyData.getEncAlgorithm())); + } + else + { + throw new UnsupportedPacketVersionException("Unsupported SKESK packet version encountered: " + keyData.getVersion()); + } // AEAD Cipher aead = aeadHelper.createAEADCipher(keyData.getEncAlgorithm(), keyData.getAeadAlgorithm()); @@ -207,4 +214,4 @@ public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket seipd, P } }; } -} +} \ No newline at end of file diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEKeyEncryptionMethodGenerator.java index 478bbc7432..bcb5a5df55 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEKeyEncryptionMethodGenerator.java @@ -1,5 +1,6 @@ package org.bouncycastle.openpgp.operator.jcajce; +import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Provider; @@ -12,15 +13,11 @@ import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; +import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.SymmetricKeyUtils; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.generators.HKDFBytesGenerator; -import org.bouncycastle.crypto.modes.AEADCipher; -import org.bouncycastle.crypto.params.AEADParameters; -import org.bouncycastle.crypto.params.HKDFParameters; -import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.jcajce.spec.AEADParameterSpec; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; @@ -28,7 +25,6 @@ import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator; import org.bouncycastle.openpgp.operator.PGPDigestCalculator; -import org.bouncycastle.openpgp.operator.bc.BcAEADUtil; /** * JCE based generator for password based encryption (PBE) data protection methods. @@ -86,6 +82,11 @@ public JcePBEKeyEncryptionMethodGenerator(char[] passPhrase, int s2kCount) super(passPhrase, new SHA1PGPDigestCalculator(), s2kCount); } + public JcePBEKeyEncryptionMethodGenerator(char[] passPhrase, S2K.Argon2Params params) + { + super(passPhrase, params); + } + /** * Sets the JCE provider to source cryptographic primitives from. * @@ -150,36 +151,74 @@ protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] session } protected byte[] generateV6KEK(int kekAlgorithm, byte[] ikm, byte[] info) - throws PGPException - { - HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest()); - hkdf.init(new HKDFParameters(ikm, null, info)); - - int kekLen = SymmetricKeyUtils.getKeyLengthInOctets(kekAlgorithm); - byte[] kek = new byte[kekLen]; - hkdf.generateBytes(kek, 0, kek.length); - return kek; - } - - protected byte[] getEskAndTag(int kekAlgorithm, int aeadAlgorithm, byte[] sessionInfo, byte[] key, byte[] iv, byte[] info) - throws PGPException - { - byte[] sessionKey = new byte[sessionInfo.length - 3]; - System.arraycopy(sessionInfo, 1, sessionKey, 0, sessionKey.length); - - AEADCipher aeadCipher = BcAEADUtil.createAEADCipher(kekAlgorithm, aeadAlgorithm); - aeadCipher.init(true, new AEADParameters(new KeyParameter(key), 128, iv, info)); - int outLen = aeadCipher.getOutputSize(sessionKey.length); - byte[] eskAndTag = new byte[outLen]; - int len = aeadCipher.processBytes(sessionKey, 0, sessionKey.length, eskAndTag, 0); - try - { - len += aeadCipher.doFinal(eskAndTag, len); - } - catch (InvalidCipherTextException e) - { - throw new PGPException("cannot encrypt session info", e); - } - return eskAndTag; - } + { + return JceAEADUtil.generateHKDFBytes(ikm, null, info, SymmetricKeyUtils.getKeyLengthInOctets(kekAlgorithm)); + } + + protected byte[] getEskAndTag(int kekAlgorithm, int aeadAlgorithm, byte[] sessionKey, byte[] key, byte[] iv, byte[] info) + throws PGPException + { + String algorithm = getBaseAEADAlgorithm(kekAlgorithm); + + Cipher aeadCipher = createAEADCipher(algorithm, aeadAlgorithm); + + try + { + aeadCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm), new AEADParameterSpec(iv, 128, info)); + int outLen = aeadCipher.getOutputSize(sessionKey.length); + byte[] eskAndTag = new byte[outLen]; + + int len = aeadCipher.update(sessionKey, 0, sessionKey.length, eskAndTag, 0); + + len += aeadCipher.doFinal(eskAndTag, len); + + if (len < eskAndTag.length) + { + byte[] rv = new byte[len]; + System.arraycopy(eskAndTag, 0, rv, 0, len); + return rv; + } + + return eskAndTag; + } + catch (GeneralSecurityException e) + { + throw new PGPException("cannot encrypt session info", e); + } + } + + private static String getBaseAEADAlgorithm(int encAlgorithm) + throws PGPException + { + if (encAlgorithm == SymmetricKeyAlgorithmTags.AES_128 + || encAlgorithm == SymmetricKeyAlgorithmTags.AES_192 + || encAlgorithm == SymmetricKeyAlgorithmTags.AES_256) + { + return "AES"; + } + else if (encAlgorithm == SymmetricKeyAlgorithmTags.CAMELLIA_128 + || encAlgorithm == SymmetricKeyAlgorithmTags.CAMELLIA_192 + || encAlgorithm == SymmetricKeyAlgorithmTags.CAMELLIA_256) + { + return "Camellia"; + } + throw new PGPException("AEAD only supported for AES and Camellia based algorithms"); + } + + private Cipher createAEADCipher(String algorithm, int aeadAlgorithm) + throws PGPException + { + // Block Cipher must work on 16 byte blocks + switch (aeadAlgorithm) + { + case AEADAlgorithmTags.EAX: + return helper.createCipher(algorithm + "/EAX/NoPadding"); + case AEADAlgorithmTags.OCB: + return helper.createCipher(algorithm + "/OCB/NoPadding"); + case AEADAlgorithmTags.GCM: + return helper.createCipher(algorithm + "/GCM/NoPadding"); + default: + throw new PGPException("unrecognised AEAD algorithm: " + aeadAlgorithm); + } + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java index 40f3f9efef..0f6f4c5f0e 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java @@ -27,6 +27,7 @@ public class JcePBEProtectionRemoverFactory private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); private PGPDigestCalculatorProvider calculatorProvider; + private JceAEADUtil aeadUtil = new JceAEADUtil(helper); private JcaPGPDigestCalculatorProviderBuilder calculatorProviderBuilder; @@ -45,6 +46,7 @@ public JcePBEProtectionRemoverFactory(char[] passPhrase, PGPDigestCalculatorProv public JcePBEProtectionRemoverFactory setProvider(Provider provider) { this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + this.aeadUtil = new JceAEADUtil(helper); if (calculatorProviderBuilder != null) { @@ -57,6 +59,7 @@ public JcePBEProtectionRemoverFactory setProvider(Provider provider) public JcePBEProtectionRemoverFactory setProvider(String providerName) { this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + this.aeadUtil = new JceAEADUtil(helper); if (calculatorProviderBuilder != null) { @@ -105,6 +108,13 @@ public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] aad throw new PGPException("invalid key: " + e.getMessage(), e); } } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) + throws PGPException + { + return JceAEADUtil.processAeadKeyData(aeadUtil, Cipher.DECRYPT_MODE, encAlgorithm, aeadAlgorithm, s2kKey, iv, packetTag, keyVersion, keyData, 0, keyData.length, pubkeyData); + } }; } else @@ -138,6 +148,13 @@ public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] key throw new PGPException("invalid key: " + e.getMessage(), e); } } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) + throws PGPException + { + return JceAEADUtil.processAeadKeyData(aeadUtil, Cipher.DECRYPT_MODE, encAlgorithm, aeadAlgorithm, s2kKey, iv, packetTag, keyVersion, keyData, 0, keyData.length, pubkeyData); + } }; } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java index 2defaea635..d08c9fc190 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java @@ -15,12 +15,15 @@ import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilder; import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; public class JcePBESecretKeyDecryptorBuilder + implements PBESecretKeyDecryptorBuilder { private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); private PGPDigestCalculatorProvider calculatorProvider; + private JceAEADUtil aeadUtil = new JceAEADUtil(helper); private JcaPGPDigestCalculatorProviderBuilder calculatorProviderBuilder; @@ -37,6 +40,7 @@ public JcePBESecretKeyDecryptorBuilder(PGPDigestCalculatorProvider calculatorPro public JcePBESecretKeyDecryptorBuilder setProvider(Provider provider) { this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + this.aeadUtil = new JceAEADUtil(helper); if (calculatorProviderBuilder != null) { @@ -49,6 +53,7 @@ public JcePBESecretKeyDecryptorBuilder setProvider(Provider provider) public JcePBESecretKeyDecryptorBuilder setProvider(String providerName) { this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + this.aeadUtil = new JceAEADUtil(helper); if (calculatorProviderBuilder != null) { @@ -96,6 +101,13 @@ public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] key throw new PGPException("invalid key: " + e.getMessage(), e); } } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) + throws PGPException + { + return JceAEADUtil.processAeadKeyData(aeadUtil, Cipher.DECRYPT_MODE, encAlgorithm, aeadAlgorithm, s2kKey, iv, packetTag, keyVersion, keyData, 0, keyData.length, pubkeyData); + } }; } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilderProvider.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilderProvider.java new file mode 100644 index 0000000000..8818fdf969 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilderProvider.java @@ -0,0 +1,37 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.security.Provider; + +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilder; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptorBuilderProvider; + +public class JcePBESecretKeyDecryptorBuilderProvider + implements PBESecretKeyDecryptorBuilderProvider +{ + private final JcaPGPDigestCalculatorProviderBuilder digestCalculatorProviderBuilder; + private Provider provider; + + public JcePBESecretKeyDecryptorBuilderProvider(JcaPGPDigestCalculatorProviderBuilder digestCalculatorProviderBuilder) + { + this.digestCalculatorProviderBuilder = digestCalculatorProviderBuilder; + } + + public JcePBESecretKeyDecryptorBuilderProvider setProvider(Provider provider) + { + this.provider = provider; + return this; + } + + @Override + public PBESecretKeyDecryptorBuilder provide() + throws PGPException + { + JcePBESecretKeyDecryptorBuilder b = new JcePBESecretKeyDecryptorBuilder(digestCalculatorProviderBuilder.build()); + if (provider != null) + { + b.setProvider(provider); + } + return b; + } +} diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java index 691575e272..97cd99be06 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java @@ -17,7 +17,6 @@ import javax.crypto.interfaces.DHKey; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; @@ -31,7 +30,6 @@ import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.X25519PublicBCPGKey; import org.bouncycastle.bcpg.X448PublicBCPGKey; -import org.bouncycastle.crypto.params.X25519PublicKeyParameters; import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; @@ -41,6 +39,7 @@ import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.operator.AbstractPublicKeyDataDecryptorFactory; import org.bouncycastle.openpgp.operator.PGPDataDecryptor; import org.bouncycastle.openpgp.operator.PGPPad; import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; @@ -129,12 +128,12 @@ else if (key instanceof RSAKey) public PublicKeyDataDecryptorFactory build(final PrivateKey privKey) { - return new PublicKeyDataDecryptorFactory() + return new AbstractPublicKeyDataDecryptorFactory() { final int expectedPayLoadSize = getExpectedPayloadSize(privKey); @Override - public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData, int pkeskVersion) throws PGPException { if (keyAlgorithm == PublicKeyAlgorithmTags.ECDH || keyAlgorithm == PublicKeyAlgorithmTags.X25519 || keyAlgorithm == PublicKeyAlgorithmTags.X448) @@ -172,12 +171,13 @@ public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket seipd, P public PublicKeyDataDecryptorFactory build(final PGPPrivateKey privKey) { - return new PublicKeyDataDecryptorFactory() + return new AbstractPublicKeyDataDecryptorFactory() { @Override - public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData, int pkeskVersion) throws PGPException { + boolean containsSKAlg = containsSKAlg(pkeskVersion); if (keyAlgorithm == PublicKeyAlgorithmTags.ECDH) { return decryptSessionData(keyConverter, privKey, secKeyData); @@ -185,12 +185,12 @@ public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) else if (keyAlgorithm == PublicKeyAlgorithmTags.X25519) { return decryptSessionData(keyConverter, privKey, secKeyData[0], X25519PublicBCPGKey.LENGTH, "X25519withSHA256HKDF", - SymmetricKeyAlgorithmTags.AES_128, EdECObjectIdentifiers.id_X25519, "X25519"); + SymmetricKeyAlgorithmTags.AES_128, EdECObjectIdentifiers.id_X25519, "X25519", containsSKAlg); } else if (keyAlgorithm == PublicKeyAlgorithmTags.X448) { return decryptSessionData(keyConverter, privKey, secKeyData[0], X448PublicBCPGKey.LENGTH, "X448withSHA512HKDF", - SymmetricKeyAlgorithmTags.AES_256, EdECObjectIdentifiers.id_X448, "X448"); + SymmetricKeyAlgorithmTags.AES_256, EdECObjectIdentifiers.id_X448, "X448", containsSKAlg); } PrivateKey jcePrivKey = keyConverter.getPrivateKey(privKey); int expectedPayLoadSize = getExpectedPayloadSize(jcePrivKey); @@ -224,6 +224,14 @@ public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket seipd, P }; } + /** + * Decrypt ECDH encrypted session keys. + * @param converter key converter + * @param privKey our private key + * @param secKeyData encrypted session key + * @return decrypted session key + * @throws PGPException + */ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey privKey, byte[][] secKeyData) throws PGPException { @@ -235,18 +243,12 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr byte[] keyEnc; pLen = ((((enc[0] & 0xff) << 8) + (enc[1] & 0xff)) + 7) / 8; - if ((2 + pLen + 1) > enc.length) - { - throw new PGPException("encoded length out of range"); - } + checkRange(2 + pLen + 1, enc); pEnc = new byte[pLen]; System.arraycopy(enc, 2, pEnc, 0, pLen); int keyLen = enc[pLen + 2] & 0xff; - if ((2 + pLen + 1 + keyLen) > enc.length) - { - throw new PGPException("encoded length out of range"); - } + checkRange(2 + pLen + 1 + keyLen, enc); keyEnc = new byte[keyLen]; System.arraycopy(enc, 2 + pLen + 1, keyEnc, 0, keyLen); @@ -257,7 +259,7 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr String agreementName; ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)pubKeyData.getKey(); // XDH - if (ecKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + if (JcaJcePGPUtil.isX25519(ecKey.getCurveOID())) { agreementName = RFC6637Utils.getXDHAlgorithm(pubKeyData); if (pEnc.length != (1 + X25519PublicBCPGKey.LENGTH) || 0x40 != pEnc[0]) @@ -266,6 +268,15 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr } publicKey = getPublicKey(pEnc, EdECObjectIdentifiers.id_X25519, 1); } + else if (ecKey.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + agreementName = RFC6637Utils.getXDHAlgorithm(pubKeyData); + if (pEnc.length != (1 + X448PublicBCPGKey.LENGTH) || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid Curve25519 public key"); + } + publicKey = getPublicKey(pEnc, EdECObjectIdentifiers.id_X448, 1); + } else { X9ECParametersHolder x9Params = ECNamedCurveTable.getByOIDLazy(ecKey.getCurveOID()); @@ -273,7 +284,7 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr agreementName = RFC6637Utils.getAgreementAlgorithm(pubKeyData); - publicKey = converter.getPublicKey(new PGPPublicKey(new PublicKeyPacket(PublicKeyAlgorithmTags.ECDH, new Date(), + publicKey = converter.getPublicKey(new PGPPublicKey(new PublicKeyPacket(pubKeyData.getVersion(), PublicKeyAlgorithmTags.ECDH, new Date(), new ECDHPublicBCPGKey(ecKey.getCurveOID(), publicPoint, ecKey.getHashAlgorithm(), ecKey.getSymmetricKeyAlgorithm())), fingerprintCalculator)); } byte[] userKeyingMaterial = RFC6637Utils.createUserKeyingMaterial(pubKeyData, fingerprintCalculator); @@ -288,26 +299,42 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr } } + /** + * Decrypt X25519 / X448 encrypted session keys. + * @param converter key converter + * @param privKey our private key + * @param enc encrypted session key + * @param pLen Key length + * @param agreementAlgorithm agreement algorithm + * @param symmetricKeyAlgorithm wrapping algorithm + * @param algorithmIdentifier ephemeral key algorithm identifier + * @param algorithmName public key algorithm name + * @param containsSKAlg whether the PKESK packet is version 3 + * @return decrypted session data + * @throws PGPException + */ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey privKey, byte[] enc, int pLen, String agreementAlgorithm, - int symmetricKeyAlgorithm, ASN1ObjectIdentifier algprithmIdentifier, String algorithmName) + int symmetricKeyAlgorithm, ASN1ObjectIdentifier algorithmIdentifier, String algorithmName, boolean containsSKAlg) throws PGPException { try { - byte[] pEnc = new byte[pLen]; - System.arraycopy(enc, 0, pEnc, 0, pLen); - int keyLen = enc[pLen] & 0xff; - if ((pLen + 1 + keyLen) > enc.length) - { - throw new PGPException("encoded length out of range"); - } - byte[] keyEnc = new byte[keyLen - 1]; - System.arraycopy(enc, pLen + 2, keyEnc, 0, keyEnc.length); - PublicKey publicKey = getPublicKey(pEnc, algprithmIdentifier, 0); - Key paddedSessionKey = getSessionKey(converter, privKey, agreementAlgorithm, publicKey, symmetricKeyAlgorithm, keyEnc, - JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(pEnc, privKey.getPublicKeyPacket(), algorithmName)); - symmetricKeyAlgorithm = enc[pLen + 1] & 0xff; - return Arrays.concatenate(new byte[]{(byte)symmetricKeyAlgorithm}, paddedSessionKey.getEncoded()); + // ephemeral key (32 / 56 octets) + byte[] ephemeralKey = Arrays.copyOf(enc, pLen); + + int size = enc[pLen] & 0xff; + + checkRange(pLen + 1 + size, enc); + + // encrypted session key + int sesKeyLen = size - (containsSKAlg ? 1 : 0); + int sesKeyOff = pLen + 1 + (containsSKAlg ? 1 : 0); + byte[] keyEnc = Arrays.copyOfRange(enc, sesKeyOff, sesKeyOff + sesKeyLen); + + PublicKey ephemeralPubKey = getPublicKey(ephemeralKey, algorithmIdentifier, 0); + Key paddedSessionKey = getSessionKey(converter, privKey, agreementAlgorithm, ephemeralPubKey, symmetricKeyAlgorithm, keyEnc, + JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(ephemeralKey, privKey.getPublicKeyPacket(), algorithmName)); + return paddedSessionKey.getEncoded(); } catch (Exception e) { @@ -320,7 +347,7 @@ private Key getSessionKey(JcaPGPKeyConverter converter, PGPPrivateKey privKey, S throws PGPException, GeneralSecurityException { PrivateKey privateKey = converter.getPrivateKey(privKey); - Key key = JcaJcePGPUtil.getSecret(helper, publicKey, RFC6637Utils.getKeyEncryptionOID(symmetricKeyAlgorithm).getId(), agreementName, ukms, privateKey); + Key key = JcaJcePGPUtil.getSecret(helper, publicKey, RFC6637Utils.getKeyEncryptionOID(symmetricKeyAlgorithm).getId(), agreementName, ukms, privateKey); Cipher c = helper.createKeyWrapper(symmetricKeyAlgorithm); c.init(Cipher.UNWRAP_MODE, key); return c.unwrap(keyEnc, "Session", Cipher.SECRET_KEY); @@ -358,6 +385,15 @@ private void updateWithMPI(Cipher c, int expectedPayloadSize, byte[] encMPI) } } + /** + * Decrypt RSA / Elgamal encrypted session keys. + * @param keyAlgorithm public key algorithm + * @param privKey our private key + * @param expectedPayloadSize payload size + * @param secKeyData ESK data + * @return session data + * @throws PGPException + */ private byte[] decryptSessionData(int keyAlgorithm, PrivateKey privKey, int expectedPayloadSize, byte[][] secKeyData) throws PGPException { @@ -393,4 +429,13 @@ private byte[] decryptSessionData(int keyAlgorithm, PrivateKey privKey, int expe throw new PGPException("exception decrypting session data", e); } } + + private static void checkRange(int pLen, byte[] enc) + throws PGPException + { + if (pLen > enc.length) + { + throw new PGPException("encoded length out of range"); + } + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java index 72bb0cb56c..e64c7e6e6d 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java @@ -1,6 +1,7 @@ package org.bouncycastle.openpgp.operator.jcajce; import java.io.IOException; +import java.math.BigInteger; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; @@ -17,11 +18,12 @@ import javax.crypto.IllegalBlockSizeException; import javax.crypto.spec.SecretKeySpec; -import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.bcpg.ECDHPublicBCPGKey; +import org.bouncycastle.bcpg.MPInteger; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; @@ -88,60 +90,100 @@ public JcePublicKeyKeyEncryptionMethodGenerator setSecureRandom(SecureRandom ran return this; } - protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo) + protected byte[] encryptSessionInfo(PGPPublicKey pubKey, + byte[] sessionKey, + byte optSymAlgId, + boolean isV3) throws PGPException { try { PublicKey cryptoPublicKey = keyConverter.getPublicKey(pubKey); + // ECDH if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ECDH) { - ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)pubKey.getPublicKeyPacket().getKey(); + byte[] sessionInfo = createSessionInfo(isV3 ? optSymAlgId : (byte)0, sessionKey); + final ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)pubKey.getPublicKeyPacket().getKey(); String keyEncryptionOID = RFC6637Utils.getKeyEncryptionOID(ecKey.getSymmetricKeyAlgorithm()).getId(); PublicKeyPacket pubKeyPacket = pubKey.getPublicKeyPacket(); - if (ecKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + + // Legacy X25519 + if (JcaJcePGPUtil.isX25519(ecKey.getCurveOID())) { - return getEncryptSessionInfo(pubKeyPacket, "X25519", cryptoPublicKey, keyEncryptionOID, - ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getXDHAlgorithm(pubKeyPacket), - (kpGen) -> kpGen.initialize(255, random), - (ephPubEncoding) -> Arrays.prepend(ephPubEncoding, X_HDR)); + return encryptSessionInfoWithECDHKey(getKeyPair("X25519",255),pubKeyPacket, cryptoPublicKey, keyEncryptionOID, + ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getXDHAlgorithm(pubKeyPacket), optSymAlgId, + new EphPubEncoding() + { + @Override + public byte[] getEphPubEncoding(byte[] publicKeyData) + { + return Arrays.prepend(publicKeyData, X_HDR); + } + }); } - else + + // Legacy X448 + else if (ecKey.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) { - return getEncryptSessionInfo(pubKeyPacket, "EC", cryptoPublicKey, keyEncryptionOID, - ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getAgreementAlgorithm(pubKeyPacket), - (kpGen) -> + return encryptSessionInfoWithECDHKey(getKeyPair("X448",448), pubKeyPacket, cryptoPublicKey, keyEncryptionOID, + ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getXDHAlgorithm(pubKeyPacket), optSymAlgId, + new EphPubEncoding() { - AlgorithmParameters ecAlgParams = helper.createAlgorithmParameters("EC"); - ecAlgParams.init(new X962Parameters(ecKey.getCurveOID()).getEncoded()); - kpGen.initialize(ecAlgParams.getParameterSpec(AlgorithmParameterSpec.class), random); - }, (ephPubEncoding) -> + @Override + public byte[] getEphPubEncoding(byte[] publicKeyData) + { + return Arrays.prepend(publicKeyData, X_HDR); + } + }); + } + + // Other ECDH curves + else + { + KeyPairGenerator kpGen = helper.createKeyPairGenerator("EC"); + AlgorithmParameters ecAlgParams = helper.createAlgorithmParameters("EC"); + ecAlgParams.init(new X962Parameters(ecKey.getCurveOID()).getEncoded()); + kpGen.initialize(ecAlgParams.getParameterSpec(AlgorithmParameterSpec.class), random); + KeyPair ephKP = kpGen.generateKeyPair(); + return encryptSessionInfoWithECDHKey(ephKP, pubKeyPacket, cryptoPublicKey, keyEncryptionOID, + ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getAgreementAlgorithm(pubKeyPacket), optSymAlgId, + new EphPubEncoding() { - if (null == ephPubEncoding || ephPubEncoding.length < 1 || ephPubEncoding[0] != 0x04) + @Override + public byte[] getEphPubEncoding(byte[] ephPubEncoding) { - ephPubEncoding = JcaJcePGPUtil.getX9Parameters(ecKey.getCurveOID()).getCurve().decodePoint(ephPubEncoding).getEncoded(false); + if (null == ephPubEncoding || ephPubEncoding.length < 1 || ephPubEncoding[0] != 0x04) + { + ephPubEncoding = JcaJcePGPUtil.getX9Parameters(ecKey.getCurveOID()).getCurve().decodePoint(ephPubEncoding).getEncoded(false); + } + return ephPubEncoding; } - return ephPubEncoding; }); } } + + // X25519 else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X25519) { - return getEncryptSessionInfo(pubKey, "X25519", cryptoPublicKey, NISTObjectIdentifiers.id_aes128_wrap.getId(), - SymmetricKeyAlgorithmTags.AES_128, sessionInfo, "X25519withSHA256HKDF", 255); + return encryptSessionInfoWithX25519X448Key(pubKey, "X25519", cryptoPublicKey, NISTObjectIdentifiers.id_aes128_wrap.getId(), + SymmetricKeyAlgorithmTags.AES_128, sessionKey, "X25519withSHA256HKDF", 255, optSymAlgId, isV3); } + + // X448 else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X448) { - return getEncryptSessionInfo(pubKey, "X448", cryptoPublicKey, NISTObjectIdentifiers.id_aes256_wrap.getId(), - SymmetricKeyAlgorithmTags.AES_256, sessionInfo, "X448withSHA512HKDF", 448); + return encryptSessionInfoWithX25519X448Key(pubKey, "X448", cryptoPublicKey, NISTObjectIdentifiers.id_aes256_wrap.getId(), + SymmetricKeyAlgorithmTags.AES_256, sessionKey, "X448withSHA512HKDF", 448, optSymAlgId, isV3); } + + // RSA / ElGamal etc. else { Cipher c = helper.createPublicKeyCipher(pubKey.getAlgorithm()); c.init(Cipher.ENCRYPT_MODE, cryptoPublicKey, random); - + byte[] sessionInfo = createSessionInfo(isV3 ? optSymAlgId : (byte)0, sessionKey); return c.doFinal(sessionInfo); } } @@ -167,34 +209,31 @@ else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X448) } } - @FunctionalInterface - private interface KeyPairGeneratorOperation - { - void initialize(KeyPairGenerator kpGen) - throws GeneralSecurityException, IOException; - } - @FunctionalInterface private interface EphPubEncoding { byte[] getEphPubEncoding(byte[] publicKeyData); } - private byte[] getEncryptSessionInfo(PublicKeyPacket pubKeyPacket, String algorithmName, PublicKey cryptoPublicKey, String keyEncryptionOID, - int symmetricKeyAlgorithm, byte[] sessionInfo, String agreementName, KeyPairGeneratorOperation kpOperation, - EphPubEncoding getEncoding) + private byte[] encryptSessionInfoWithECDHKey(KeyPair ephKP, PublicKeyPacket pubKeyPacket, PublicKey cryptoPublicKey, String keyEncryptionOID, + int symmetricKeyAlgorithm, byte[] sessionInfo, String agreementName, byte symAlgId, + EphPubEncoding getEncoding) throws GeneralSecurityException, IOException, PGPException { - KeyPairGenerator kpGen = helper.createKeyPairGenerator(algorithmName); - kpOperation.initialize(kpGen); - KeyPair ephKP = kpGen.generateKeyPair(); + // Prepare shared-secret public key UserKeyingMaterialSpec ukmSpec = new UserKeyingMaterialSpec(RFC6637Utils.createUserKeyingMaterial(pubKeyPacket, new JcaKeyFingerprintCalculator())); Key secret = JcaJcePGPUtil.getSecret(helper, cryptoPublicKey, keyEncryptionOID, agreementName, ukmSpec, ephKP.getPrivate()); + byte[] ephPubEncoding = getEncoding.getEphPubEncoding(SubjectPublicKeyInfo.getInstance(ephKP.getPublic().getEncoded()).getPublicKeyData().getBytes()); + + // session info is padded to 8-octet granulatiry using the method described in RFC8018. byte[] paddedSessionData = PGPPad.padSessionData(sessionInfo, sessionKeyObfuscation); - return getSessionInfo(ephPubEncoding, getWrapper(symmetricKeyAlgorithm, sessionInfo, secret, paddedSessionData)); + // wrap the padded session info using the shared-secret public key + // https://www.rfc-editor.org/rfc/rfc9580.html#section-11.5-16 + return getSessionInfo(new MPInteger(new BigInteger(1, ephPubEncoding)).getEncoded(), + (byte)0, getWrapper(symmetricKeyAlgorithm, symAlgId, secret, paddedSessionData)); } /** @@ -206,29 +245,31 @@ private byte[] getEncryptSessionInfo(PublicKeyPacket pubKeyPacket, String algori * algorithm used MUST be AES-128, AES-192 or AES-256 (algorithm ID 7, 8 * or 9). */ - private byte[] getEncryptSessionInfo(PGPPublicKey pgpPublicKey, String algorithmName, PublicKey cryptoPublicKey, String keyEncryptionOID, - int symmetricKeyAlgorithm, byte[] sessionInfo, String agreementAlgorithmName, int keySize) + private byte[] encryptSessionInfoWithX25519X448Key(PGPPublicKey pgpPublicKey, String algorithmName, PublicKey cryptoPublicKey, String keyEncryptionOID, + int symmetricKeyAlgorithm, byte[] sessionKey, String agreementAlgorithmName, int keySize, + byte optSymAlgId, boolean isV3) throws GeneralSecurityException, IOException, PGPException { - KeyPairGenerator kpGen = helper.createKeyPairGenerator(algorithmName); - kpGen.initialize(keySize, random); - KeyPair ephKP = kpGen.generateKeyPair(); - + KeyPair ephKP = getKeyPair(algorithmName, keySize); byte[] ephPubEncoding = SubjectPublicKeyInfo.getInstance(ephKP.getPublic().getEncoded()).getPublicKeyData().getBytes(); HybridValueParameterSpec ukmSpec = JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(ephPubEncoding, pgpPublicKey.getPublicKeyPacket(), algorithmName); Key secret = JcaJcePGPUtil.getSecret(helper, cryptoPublicKey, keyEncryptionOID, agreementAlgorithmName, ukmSpec, ephKP.getPrivate()); - //No checksum or padding - byte[] sessionData = new byte[sessionInfo.length - 3]; - System.arraycopy(sessionInfo, 1, sessionData, 0, sessionData.length); + return getSessionInfo(ephPubEncoding, isV3 ? optSymAlgId : (byte)0, getWrapper(symmetricKeyAlgorithm, optSymAlgId, secret, sessionKey)); + } - return getSessionInfo(ephPubEncoding, sessionInfo[0], getWrapper(symmetricKeyAlgorithm, sessionInfo, secret, sessionData)); + private KeyPair getKeyPair(String algorithmName, int keySize) + throws GeneralSecurityException + { + KeyPairGenerator kpGen = helper.createKeyPairGenerator(algorithmName); + kpGen.initialize(keySize, random); + return kpGen.generateKeyPair(); } - private byte[] getWrapper(int symmetricKeyAlgorithm, byte[] sessionInfo, Key secret, byte[] sessionData) + private byte[] getWrapper(int symmetricKeyAlgorithm, byte optSymAlgId, Key secret, byte[] sessionData) throws PGPException, InvalidKeyException, IllegalBlockSizeException { Cipher c = helper.createKeyWrapper(symmetricKeyAlgorithm); c.init(Cipher.WRAP_MODE, secret, random); - return c.wrap(new SecretKeySpec(sessionData, PGPUtil.getSymmetricCipherName(sessionInfo[0]))); + return c.wrap(new SecretKeySpec(sessionData, PGPUtil.getSymmetricCipherName(optSymAlgId))); } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java index 5230523931..319c6164b9 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java @@ -48,7 +48,8 @@ MessageDigest createDigest(int algorithm) } catch (NoSuchAlgorithmException e) { - if (algorithm >= HashAlgorithmTags.SHA256 && algorithm <= HashAlgorithmTags.SHA224) + if (algorithm == HashAlgorithmTags.SHA1 + || (algorithm >= HashAlgorithmTags.SHA256 && algorithm <= HashAlgorithmTags.SHA224)) { dig = helper.createMessageDigest("SHA-" + digestName.substring(3)); } @@ -202,7 +203,7 @@ Cipher createKeyWrapper(int encAlgorithm) } } - private Signature createSignature(String cipherName) + Signature createSignature(String cipherName) throws PGPException { try @@ -248,6 +249,7 @@ public Signature createSignature(int keyAlgorithm, int hashAlgorithm) return createSignature(PGPUtil.getDigestName(hashAlgorithm) + "with" + encAlg); } + public AlgorithmParameters createAlgorithmParameters(String algorithm) throws NoSuchProviderException, NoSuchAlgorithmException { diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/package-info.java new file mode 100644 index 0000000000..76cbb11982 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/package-info.java @@ -0,0 +1,7 @@ +/** + * JCA/JCE based operators for dealing with OpenPGP objects. + *

      + * These provide the actual support for encryption and decryption required for the high level OpenPGP classes. + *

      + */ +package org.bouncycastle.openpgp.operator.jcajce; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/operator/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/operator/package-info.java new file mode 100644 index 0000000000..b8cdb81be8 --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/operator/package-info.java @@ -0,0 +1,7 @@ +/** + * Interfaces and abstract classes to provide the framework to support operations on the OpenPGP high level classes. + *

      + * For examples of actual implementations see the org.bouncycastle.openpgp.operator.bc and org.bouncycastle.openpgp.operator.jcajce packages. + *

      + */ +package org.bouncycastle.openpgp.operator; diff --git a/pg/src/main/java/org/bouncycastle/openpgp/package-info.java b/pg/src/main/java/org/bouncycastle/openpgp/package-info.java new file mode 100644 index 0000000000..177c400e5a --- /dev/null +++ b/pg/src/main/java/org/bouncycastle/openpgp/package-info.java @@ -0,0 +1,15 @@ +/** + * High level classes for dealing with OpenPGP objects. + *

      + * Note: These are based on the org.bouncycastle.bcpg classes and use a streaming + * model, so for some objects which have an input stream associated it is necessary + * to read to the end of the input stream on the object before trying to read + * another object from the orginal input stream. + *

      + * A word on key ring files. For the purpose of this package a PGP key ring is a master key and + * a collection of sub-keys associated with it. These public and secret key rings are handled by + * the PGPPublicKey ring class and the PGPSecretKeyRing class respectively. In the case where + * you are trying to read an key file which has multiple key rings in it, use PGPSecretKeyRingCollection + * for the secret key file and PGPPublicKeyRingCollection for the public key file. + */ +package org.bouncycastle.openpgp; diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/PGPPadding.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/PGPPadding.java new file mode 100644 index 0000000000..ee99b7ab5d --- /dev/null +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/PGPPadding.java @@ -0,0 +1,137 @@ +package org.bouncycastle.openpgp; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.security.SecureRandom; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.Packet; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PaddingPacket; +import org.bouncycastle.crypto.CryptoServicesRegistrar; + +/** + * The PGPPadding contains random data, and can be used to defend against traffic analysis on version 2 SEIPD messages + * and Transferable Public Keys. + *

      + * Such a padding packet MUST be ignored when received. + */ +public class PGPPadding +{ + private PaddingPacket p; + + /** + * Minimum random padding length in octets. + * Chosen totally arbitrarily. + */ + public static final int MIN_PADDING_LEN = 16; + + /** + * Maximum random padding length. + * Chosen somewhat arbitrarily, as SSH also uses max 255 bytes for random padding. + * + * @see + * rfc4253 - Binary Packet Protocol + */ + public static final int MAX_PADDING_LEN = 255; + + /** + * Default constructor. + * + * @param in packet input stream + * @throws IOException + */ + public PGPPadding( + BCPGInputStream in) + throws IOException + { + Packet packet = in.readPacket(); + if (!(packet instanceof PaddingPacket)) + { + throw new IOException("unexpected packet in stream: " + packet); + } + p = (PaddingPacket)packet; + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of n random bytes, where n is a number between (inclusive) {@link #MIN_PADDING_LEN} + * and {@link #MAX_PADDING_LEN}. + */ + public PGPPadding() + { + this(CryptoServicesRegistrar.getSecureRandom()); + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of n random bytes, where n is a number between (inclusive) {@link #MIN_PADDING_LEN} + * and {@link #MAX_PADDING_LEN}. + * + * @param random random number generator instance + */ + public PGPPadding(SecureRandom random) + { + this(MIN_PADDING_LEN + padLen(random), random); + } + + private static int padLen(SecureRandom random) + { + return random.nextInt() % (MAX_PADDING_LEN - MIN_PADDING_LEN + 1); + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of

      len
      random bytes. + */ + public PGPPadding(int len) + { + this(len, CryptoServicesRegistrar.getSecureRandom()); + } + + /** + * Generate a new, random {@link PGPPadding} object. + * The padding consists of
      len
      random bytes. + * + * @param len number of random octets + * @param random random number generator instance + */ + public PGPPadding(int len, SecureRandom random) + { + this.p = new PaddingPacket(len, random); + } + + /** + * Return the padding octets as a byte array. + * @return padding octets + */ + public byte[] getPadding() + { + return p.getPadding(); + } + + public void encode(OutputStream outStream) + throws IOException + { + BCPGOutputStream pOut = BCPGOutputStream.wrap(outStream); + p.encode(pOut); + } + + public byte[] getEncoded() + throws IOException + { + return getEncoded(PacketFormat.ROUNDTRIP); + } + + public byte[] getEncoded(PacketFormat format) + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, format); + encode(pOut); + pOut.close(); + return bOut.toByteArray(); + } +} diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java index ff57c65240..0324b121e6 100644 --- a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaJcePGPUtil.java @@ -3,8 +3,6 @@ import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; import java.security.Key; import java.security.PublicKey; import java.security.spec.AlgorithmParameterSpec; @@ -14,6 +12,8 @@ import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.bcpg.PublicKeyPacket; @@ -70,7 +70,7 @@ static X9ECParameters getX9Parameters(ASN1ObjectIdentifier curveOID) static HybridValueParameterSpec getHybridValueParameterSpecWithPrepend(byte[] ephmeralPublicKey, PublicKeyPacket pkp, String algorithmName) throws IOException { - return new HybridValueParameterSpec(Arrays.concatenate(ephmeralPublicKey, pkp.getEncoded()), true, new UserKeyingMaterialSpec(Strings.toByteArray("OpenPGP " + algorithmName))); + return new HybridValueParameterSpec(Arrays.concatenate(ephmeralPublicKey, pkp.getKey().getEncoded()), true, new UserKeyingMaterialSpec(Strings.toByteArray("OpenPGP " + algorithmName))); } static Key getSecret(OperatorHelper helper, PublicKey cryptoPublicKey, String keyEncryptionOID, String agreementName, AlgorithmParameterSpec ukmSpec, Key privKey) @@ -83,13 +83,14 @@ static Key getSecret(OperatorHelper helper, PublicKey cryptoPublicKey, String ke agreement.doPhase(cryptoPublicKey, true); return agreement.generateSecret(keyEncryptionOID); } - catch (InvalidKeyException e) - { - throw new GeneralSecurityException(e.toString()); - } - catch (NoSuchAlgorithmException e) + catch (Exception e) { throw new GeneralSecurityException(e.toString()); } } + + static boolean isX25519(ASN1ObjectIdentifier curveID) + { + return curveID.equals(CryptlibObjectIdentifiers.curvey25519) || curveID.equals(EdECObjectIdentifiers.id_X25519); + } } diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java new file mode 100644 index 0000000000..56cdf8ee03 --- /dev/null +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaKeyFingerprintCalculator.java @@ -0,0 +1,153 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Provider; + +import org.bouncycastle.bcpg.BCPGKey; +import org.bouncycastle.bcpg.MPInteger; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.RSAPublicBCPGKey; +import org.bouncycastle.bcpg.UnsupportedPacketVersionException; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.JcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; + +public class JcaKeyFingerprintCalculator + implements KeyFingerPrintCalculator +{ + private final JcaJceHelper helper; + + /** + * Base Constructor - use the JCA defaults. + */ + public JcaKeyFingerprintCalculator() + { + this(new DefaultJcaJceHelper()); + } + + private JcaKeyFingerprintCalculator(JcaJceHelper helper) + { + this.helper = helper; + } + + /** + * Sets the provider to use to obtain cryptographic primitives. + * + * @param provider the JCA provider to use. + * @return a new JceKeyFingerprintCalculator supported by the passed in provider. + */ + public JcaKeyFingerprintCalculator setProvider(Provider provider) + { + return new JcaKeyFingerprintCalculator(new ProviderJcaJceHelper(provider)); + } + + /** + * Sets the provider to use to obtain cryptographic primitives. + * + * @param providerName the name of the JCA provider to use. + * @return a new JceKeyFingerprintCalculator supported by the passed in named provider. + */ + public JcaKeyFingerprintCalculator setProvider(String providerName) + { + return new JcaKeyFingerprintCalculator(new NamedJcaJceHelper(providerName)); + } + + public byte[] calculateFingerprint(PublicKeyPacket publicPk) + throws PGPException + { + BCPGKey key = publicPk.getKey(); + + if (publicPk.getVersion() <= PublicKeyPacket.VERSION_3) + { + RSAPublicBCPGKey rK = (RSAPublicBCPGKey)key; + + try + { + MessageDigest digest = helper.createMessageDigest("MD5"); + + byte[] bytes = new MPInteger(rK.getModulus()).getEncoded(); + digest.update(bytes, 2, bytes.length - 2); + + bytes = new MPInteger(rK.getPublicExponent()).getEncoded(); + digest.update(bytes, 2, bytes.length - 2); + + return digest.digest(); + } + catch (IOException e) + { + throw new PGPException("can't encode key components: " + e.getMessage(), e); + } + catch (Exception e) + { + throw new PGPException("can't find MD5", e); + } + } + else if (publicPk.getVersion() == PublicKeyPacket.VERSION_4) + { + try + { + byte[] kBytes = publicPk.getEncodedContents(); + + MessageDigest digest = helper.createMessageDigest("SHA1"); + + digest.update((byte)0x99); + digest.update((byte)(kBytes.length >> 8)); + digest.update((byte)kBytes.length); + digest.update(kBytes); + + return digest.digest(); + } + catch (IOException e) + { + throw new PGPException("can't encode key components: " + e.getMessage(), e); + } + catch (Exception e) + { + throw new PGPException("can't find SHA1", e); + } + } + else if (publicPk.getVersion() == PublicKeyPacket.LIBREPGP_5 || publicPk.getVersion() == PublicKeyPacket.VERSION_6) + { + try + { + byte[] kBytes = publicPk.getEncodedContents(); + + MessageDigest digest = helper.createMessageDigest("SHA-256"); + + digest.update((byte) (publicPk.getVersion() == PublicKeyPacket.VERSION_6 ? 0x9b : 0x9a)); + + digest.update((byte)(kBytes.length >> 24)); + digest.update((byte)(kBytes.length >> 16)); + digest.update((byte)(kBytes.length >> 8)); + digest.update((byte)kBytes.length); + + digest.update(kBytes); + + return digest.digest(); + } + catch (NoSuchAlgorithmException e) + { + throw new PGPException("can't find SHA-256", e); + } + catch (NoSuchProviderException e) + { + throw new PGPException("can't find SHA-256", e); + } + catch (IOException e) + { + throw new PGPException("can't encode key components: " + e.getMessage(), e); + } + } + else + { + throw new UnsupportedPacketVersionException("Unsupported PGP key version: " + publicPk.getVersion()); + } + } +} diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java index f395725057..b82ce38b1f 100644 --- a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java @@ -5,8 +5,6 @@ import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; @@ -14,7 +12,6 @@ import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import org.bouncycastle.jce.interfaces.ECPrivateKey; -import org.bouncycastle.jce.interfaces.ECPublicKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPrivateKeySpec; @@ -22,13 +19,13 @@ import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; -import java.security.spec.InvalidParameterSpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Date; +import java.util.Enumeration; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; @@ -36,6 +33,7 @@ import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.DHPublicKeySpec; +import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DEROctetString; @@ -46,9 +44,11 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ECParametersHolder; import org.bouncycastle.asn1.x9.X9ECPoint; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.bcpg.BCPGKey; import org.bouncycastle.bcpg.DSAPublicBCPGKey; import org.bouncycastle.bcpg.DSASecretBCPGKey; @@ -56,33 +56,44 @@ import org.bouncycastle.bcpg.ECDSAPublicBCPGKey; import org.bouncycastle.bcpg.ECPublicBCPGKey; import org.bouncycastle.bcpg.ECSecretBCPGKey; +import org.bouncycastle.bcpg.Ed25519PublicBCPGKey; +import org.bouncycastle.bcpg.Ed25519SecretBCPGKey; +import org.bouncycastle.bcpg.Ed448PublicBCPGKey; +import org.bouncycastle.bcpg.Ed448SecretBCPGKey; import org.bouncycastle.bcpg.EdDSAPublicBCPGKey; import org.bouncycastle.bcpg.EdSecretBCPGKey; import org.bouncycastle.bcpg.ElGamalPublicBCPGKey; import org.bouncycastle.bcpg.ElGamalSecretBCPGKey; -import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.RSAPublicBCPGKey; import org.bouncycastle.bcpg.RSASecretBCPGKey; -import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; -import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; -import org.bouncycastle.crypto.params.X25519PublicKeyParameters; +import org.bouncycastle.bcpg.X25519PublicBCPGKey; +import org.bouncycastle.bcpg.X25519SecretBCPGKey; +import org.bouncycastle.bcpg.X448PublicBCPGKey; +import org.bouncycastle.bcpg.X448SecretBCPGKey; +import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; +import org.bouncycastle.math.ec.rfc8032.Ed25519; +import org.bouncycastle.math.ec.rfc8032.Ed448; import org.bouncycastle.openpgp.PGPAlgorithmParameters; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKdfParameters; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; +import org.bouncycastle.openpgp.operator.PGPKeyConverter; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; public class JcaPGPKeyConverter + extends PGPKeyConverter { private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); private KeyFingerPrintCalculator fingerPrintCalculator = new JcaKeyFingerprintCalculator(); @@ -104,8 +115,8 @@ public JcaPGPKeyConverter setProvider(String providerName) /** * Convert a PrivateKey into a PGPPrivateKey. * - * @param pub the corresponding PGPPublicKey to privKey. - * @param privKey the private key for the key in pub. + * @param pub the corresponding PGPPublicKey to privKey. + * @param privKey the private key for the key in pub. * @return a PGPPrivateKey * @throws PGPException */ @@ -118,23 +129,24 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. *

      - * @param algorithm asymmetric algorithm type representing the public key. + * + * @param algorithm asymmetric algorithm type representing the public key. * @param algorithmParameters additional parameters to be stored against the public key. - * @param pubKey actual public key to associate. - * @param time date of creation. + * @param pubKey actual public key to associate. + * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PGPAlgorithmParameters, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) throws PGPException { - BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey, time); - - return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), fingerPrintCalculator); + return getPGPPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, time); } /** @@ -143,17 +155,73 @@ public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algori * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param algorithmParameters additional parameters to be stored against the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + throws PGPException + { + BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey); + + return new PGPPublicKey(new PublicKeyPacket(version, algorithm, time, bcpgKey), fingerPrintCalculator); + } + + /** + * Create a version 4 PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * * @param algorithm asymmetric algorithm type representing the public key. * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PublicKey pubKey, Date time) throws PGPException { return getPGPPublicKey(algorithm, null, pubKey, time); } + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(version, algorithm, null, pubKey, time); + } + + public PrivateKeyInfo getPrivateKeyInfo(ASN1ObjectIdentifier oid, int keySize, byte[] enc) + throws IOException + { + return super.getPrivateKeyInfo(oid, keySize, enc); + } + + public PrivateKeyInfo getPrivateKeyInfo(ASN1ObjectIdentifier oid, byte[] enc) + throws IOException + { + return super.getPrivateKeyInfo(oid, enc); + } + public PrivateKey getPrivateKey(PGPPrivateKey privKey) throws PGPException { @@ -162,8 +230,8 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) return ((JcaPGPPrivateKey)privKey).getPrivateKey(); } - PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); - BCPGKey privPk = privKey.getPrivateKeyDataPacket(); + final PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); + final BCPGKey privPk = privKey.getPrivateKeyDataPacket(); try { @@ -183,31 +251,127 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) ECDHPublicBCPGKey ecdhPub = (ECDHPublicBCPGKey)pubPk.getKey(); ECSecretBCPGKey ecdhK = (ECSecretBCPGKey)privPk; - if (CryptlibObjectIdentifiers.curvey25519.equals(ecdhPub.getCurveOID())) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhPub.getCurveOID())) { // 'reverse' because the native format for X25519 private keys is little-endian - return implGetPrivateKeyPKCS8("XDH", new PrivateKeyInfo( - new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), - new DEROctetString(Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(ecdhK.getX()))))); + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } + }); + } + // Legacy X448 (1.3.101.111) + else if (EdECObjectIdentifiers.id_X448.equals(ecdhPub.getCurveOID())) + { + // 'reverse' because the native format for X448 private keys is little-endian (?) + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + + } + }); } + // Brainpool, NIST etc. else { return implGetPrivateKeyEC("ECDH", ecdhPub, ecdhK); } } - + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + X25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + X448SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } case PublicKeyAlgorithmTags.ECDSA: - return implGetPrivateKeyEC("ECDSA", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); - - case PublicKeyAlgorithmTags.EDDSA: { - EdSecretBCPGKey eddsaK = (EdSecretBCPGKey)privPk; - - return implGetPrivateKeyPKCS8("EdDSA", new PrivateKeyInfo( - new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), - new DEROctetString(BigIntegers.asUnsignedByteArray(eddsaK.getX())))); + return implGetPrivateKeyEC("EC", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + EdDSAPublicBCPGKey eddsaPub = (EdDSAPublicBCPGKey) pubPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaPub.getCurveOID())) + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + BigIntegers.asUnsignedByteArray(Ed448.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); } - case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: { @@ -230,7 +394,7 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) } default: - throw new PGPException("unknown public key algorithm encountered"); + throw new PGPException("unknown public key algorithm encountered: " + pubPk.getAlgorithm()); } } catch (PGPException e) @@ -263,46 +427,65 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) { ECDHPublicBCPGKey ecdhK = (ECDHPublicBCPGKey)publicPk.getKey(); - if (ecdhK.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhK.getCurveOID())) { - byte[] pEnc = BigIntegers.asUnsignedByteArray(ecdhK.getEncodedPoint()); - - // skip the 0x40 header byte. - if (pEnc.length < 1 || 0x40 != pEnc[0]) - { - throw new IllegalArgumentException("Invalid Curve25519 public key"); - } - - return implGetPublicKeyX509("XDH", new SubjectPublicKeyInfo( - new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), - Arrays.copyOfRange(pEnc, 1, pEnc.length))); + return get25519PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X25519, "XDH", "Curve"); } + // Legacy X448 (1.3.101.111) + else if (ecdhK.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + return get448PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X448, "XDH", "Curve"); + } + // Brainpool, NIST etc. else { return implGetPublicKeyEC("ECDH", ecdhK); } } - + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X25519, "XDH"); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X448, "XDH"); + } case PublicKeyAlgorithmTags.ECDSA: - return implGetPublicKeyEC("ECDSA", (ECDSAPublicBCPGKey)publicPk.getKey()); - - case PublicKeyAlgorithmTags.EDDSA: { - EdDSAPublicBCPGKey eddsaK = (EdDSAPublicBCPGKey)publicPk.getKey(); - - byte[] pEnc = BigIntegers.asUnsignedByteArray(eddsaK.getEncodedPoint()); - - // skip the 0x40 header byte. - if (pEnc.length < 1 || 0x40 != pEnc[0]) + return implGetPublicKeyEC("EC", (ECDSAPublicBCPGKey) publicPk.getKey()); + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + EdDSAPublicBCPGKey eddsaKey = (EdDSAPublicBCPGKey) publicPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaKey.getCurveOID())) { - throw new IllegalArgumentException("Invalid Ed25519 public key"); + return get448PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed448, "EdDSA", "Ed"); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 + else + { + return get25519PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); } - - return implGetPublicKeyX509("EdDSA", new SubjectPublicKeyInfo( - new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), - Arrays.copyOfRange(pEnc, 1, pEnc.length))); } - + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed448, "EdDSA"); + } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: { @@ -321,7 +504,7 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) } default: - throw new PGPException("unknown public key algorithm encountered"); + throw new PGPException("unknown public key algorithm encountered: " + publicPk.getAlgorithm()); } } catch (PGPException e) @@ -335,32 +518,38 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) } private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid) - throws GeneralSecurityException, InvalidParameterSpecException + throws IOException, GeneralSecurityException { try { - return getECParameterSpec(curveOid, JcaJcePGPUtil.getX9Parameters(curveOid)); + AlgorithmParameters params = helper.createAlgorithmParameters("EC"); + + params.init(new X962Parameters(curveOid).getEncoded()); + + return (org.bouncycastle.jce.spec.ECParameterSpec)params.getParameterSpec(ECParameterSpec.class); + } + catch (IOException e) + { + throw e; } catch (Exception e) { - throw new GeneralSecurityException(e.getMessage()); + throw new GeneralSecurityException(e.toString()); } } - private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid, X9ECParameters x9Params) - throws InvalidParameterSpecException, GeneralSecurityException + private BCPGKey getPrivateBCPGKey(PrivateKey privKey, BCPGKeyOperation operation) + throws PGPException { + PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(privKey.getEncoded()); + try { - AlgorithmParameters params = helper.createAlgorithmParameters("EC"); - - params.init(new ECNamedCurveGenParameterSpec(ECNamedCurveTable.getName(curveOid))); - - return (ECParameterSpec)params.getParameterSpec(ECParameterSpec.class); + return operation.getBCPGKey(ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets()); } - catch (Exception e) + catch (IOException e) { - throw new GeneralSecurityException(e.getMessage()); + throw new PGPException(e.getMessage(), e); } } @@ -384,49 +573,81 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) } else { - PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(privKey.getEncoded()); - - try + // 'reverse' because the native format for X25519,X448 private keys is little-endian + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - // 'reverse' because the native format for X25519 private keys is little-endian - return new ECSecretBCPGKey(new BigInteger(1, - Arrays.reverse(ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets()))); + public BCPGKey getBCPGKey(byte[] key) + { + return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(key))); + } + }); + } + } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519SecretBCPGKey(key); } - catch (IOException e) + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) { - throw new PGPException(e.getMessage(), e); + return new X448SecretBCPGKey(key); } - } + }); } - case PublicKeyAlgorithmTags.ECDSA: { - ECPrivateKey ecK = (ECPrivateKey)privKey; - return new ECSecretBCPGKey(ecK.getD()); + return new ECSecretBCPGKey(((ECPrivateKey)privKey).getD()); } - - case PublicKeyAlgorithmTags.EDDSA: + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(privKey.getEncoded()); - - try + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - return new EdSecretBCPGKey( - new BigInteger(1, ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets())); - } - catch (IOException e) + public BCPGKey getBCPGKey(byte[] key) + { + return new EdSecretBCPGKey(new BigInteger(1, key)); + } + }); + } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - throw new PGPException(e.getMessage(), e); - } + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519SecretBCPGKey(key); + } + }); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448SecretBCPGKey(key); + } + }); } - case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: { DHPrivateKey esK = (DHPrivateKey)privKey; return new ElGamalSecretBCPGKey(esK.getX()); } - case PublicKeyAlgorithmTags.RSA_ENCRYPT: case PublicKeyAlgorithmTags.RSA_GENERAL: case PublicKeyAlgorithmTags.RSA_SIGN: @@ -434,127 +655,377 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) RSAPrivateCrtKey rsK = (RSAPrivateCrtKey)privKey; return new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ()); } - default: - throw new PGPException("unknown key class"); + throw new PGPException("unknown public key algorithm encountered: " + pub.getAlgorithm()); } } - private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey) throws PGPException { - if (pubKey instanceof RSAPublicKey) - { - RSAPublicKey rK = (RSAPublicKey)pubKey; - return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); - } - else if (pubKey instanceof DSAPublicKey) - { - DSAPublicKey dK = (DSAPublicKey)pubKey; - DSAParams dP = dK.getParams(); - return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); - } - else if (pubKey instanceof DHPublicKey) - { - DHPublicKey eK = (DHPublicKey)pubKey; - DHParameterSpec eS = eK.getParams(); - return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); - } - else if (pubKey instanceof ECPublicKey) + switch (algorithm) { - SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPublicKey rK = (RSAPublicKey) pubKey; + return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + DHPublicKey egK = (DHPublicKey) pubKey; + return new ElGamalPublicBCPGKey(egK.getParams().getP(), egK.getParams().getG(), egK.getY()); + } + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicKey dK = (DSAPublicKey) pubKey; + DSAParams dP = dK.getParams(); + return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); + } + + case PublicKeyAlgorithmTags.DIFFIE_HELLMAN: + { + DHPublicKey eK = (DHPublicKey) pubKey; + DHParameterSpec eS = eK.getParams(); + return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); + } + + case PublicKeyAlgorithmTags.ECDH: + case PublicKeyAlgorithmTags.ECDSA: + { + SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + + // TODO: should probably match curve by comparison as well + ASN1Encodable enc = keyInfo.getAlgorithm().getAlgorithm(); + ASN1ObjectIdentifier curveOid; + curveOid = ASN1ObjectIdentifier.getInstance(enc); + + // BCECPublicKey uses explicit parameter encoding, so we need to find the named curve manually + if (X9ObjectIdentifiers.id_ecPublicKey.equals(curveOid)) + { + enc = getNamedCurveOID(X962Parameters.getInstance(keyInfo.getAlgorithm().getParameters())); + ASN1ObjectIdentifier nCurveOid = ASN1ObjectIdentifier.getInstance(enc); + if (nCurveOid != null) + { + curveOid = nCurveOid; + } + } + + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + if (pubKey.getAlgorithm().regionMatches(true, 0, "X4", 0, 2)) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // sun.security.ec.XDHPublicKeyImpl returns "XDH" for getAlgorithm() + // In this case we need to determine the curve by looking at the length of the encoding :/ + else if (pubKey.getAlgorithm().regionMatches(true, 0, "XDH", 0, 3)) + { + // Legacy X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + if (X25519.SCALAR_SIZE + 12 == pubKey.getEncoded().length) // + 12 for some reason + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + else + { + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + } + + X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + + ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); + X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); - // TODO: should probably match curve by comparison as well - ASN1ObjectIdentifier curveOid = ASN1ObjectIdentifier.getInstance(keyInfo.getAlgorithm().getParameters()); + if (algorithm == PGPPublicKey.ECDH) + { - X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); - ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); - X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); + return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), + kdfParams.getSymmetricWrapAlgorithm()); + } + else + { + return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + } + } - if (algorithm == PGPPublicKey.ECDH) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - PGPKdfParameters kdfParams = (PGPKdfParameters)algorithmParameters; - if (kdfParams == null) + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) + { + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + // Legacy Ed448 (1.3.101.113) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED4", 0, 3)) + { + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + // Manual matching on curve encoding length + else { - // We default to these as they are specified as mandatory in RFC 6631. - kdfParams = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + // sun.security.ec.ed.EdDSAPublicKeyImpl returns "EdDSA" for getAlgorithm() + // if algorithm is just EdDSA, we need to detect the curve based on encoding length :/ + if (pubKey.getEncoded().length == 12 + Ed25519.PUBLIC_KEY_SIZE) // +12 for some reason + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + else + { + // Legacy Ed448 (1.3.101.113) + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } } - return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), - kdfParams.getSymmetricWrapAlgorithm()); } - else if (algorithm == PGPPublicKey.ECDSA) + + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: { - return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519PublicBCPGKey(key); + } + }); } - else + + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: { - throw new PGPException("unknown EC algorithm"); + return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448PublicBCPGKey(key); + } + }); } - } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) - { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); - byte[] pointEnc = new byte[1 + Ed25519PublicKeyParameters.KEY_SIZE]; - pointEnc[0] = 0x40; - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 1, pointEnc.length - 1); + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519PublicBCPGKey(key); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X448PublicBCPGKey(key); + } + }); + } - return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, pointEnc)); + default: + throw new PGPException("unknown public key algorithm encountered: " + algorithm); } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) - { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); - byte[] pointEnc = new byte[1 + X25519PublicKeyParameters.KEY_SIZE]; + } - pointEnc[0] = 0x40; - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 1, pointEnc.length - 1); + private ASN1Encodable getNamedCurveOID(X962Parameters ecParams) + { + ECCurve curve = null; + if (ecParams.isNamedCurve()) + { + return ASN1ObjectIdentifier.getInstance(ecParams.getParameters()); + } + else if (ecParams.isImplicitlyCA()) + { + curve = ((X9ECParameters)CryptoServicesRegistrar.getProperty(CryptoServicesRegistrar.Property.EC_IMPLICITLY_CA)).getCurve(); + } + else + { + curve = X9ECParameters.getInstance(ecParams.getParameters()).getCurve(); + } - PGPKdfParameters kdfParams = (PGPKdfParameters)algorithmParameters; - if (kdfParams == null) + // Iterate through all registered curves to find applicable OID + Enumeration names = ECNamedCurveTable.getNames(); + while (names.hasMoreElements()) + { + String name = (String)names.nextElement(); + X9ECParameters parms = ECNamedCurveTable.getByName(name); + if (curve.equals(parms.getCurve())) { - // We default to these as they are specified as mandatory in RFC 6631. - kdfParams = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + return ECNamedCurveTable.getOID(name); } - return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, pointEnc), - kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); } - else + return null; + } + + @FunctionalInterface + private interface BCPGKeyOperation + { + BCPGKey getBCPGKey(byte[] key); + } + + private BCPGKey getPublicBCPGKey(PublicKey pubKey, int keySize, BCPGKeyOperation operation) + { + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); + byte[] pointEnc = new byte[keySize]; + // refer to getPointEncUncompressed + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); + return operation.getBCPGKey(pointEnc); + } + + private byte[] getPointEncUncompressed(PublicKey pubKey, int publicKeySize) + { + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); + byte[] pointEnc = new byte[1 + publicKeySize]; + + pointEnc[0] = 0x40; + //offset with pointEnc.length - pubInfo.length to avoid leading zero issue + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); + return pointEnc; + } + + @FunctionalInterface + private interface Operation + { + PrivateKeyInfo getPrivateKeyInfos() + throws IOException; + } + + private PrivateKey implGeneratePrivate(String keyAlgorithm, Operation operation) + throws GeneralSecurityException, PGPException, IOException + { + try + { + PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(operation.getPrivateKeyInfos().getEncoded()); + KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); + return keyFactory.generatePrivate(pkcs8Spec); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) { - throw new PGPException("unknown key class"); + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); } } private PrivateKey implGeneratePrivate(String keyAlgorithm, KeySpec keySpec) throws GeneralSecurityException, PGPException { + try + { KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); return keyFactory.generatePrivate(keySpec); + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } private PublicKey implGeneratePublic(String keyAlgorithm, KeySpec keySpec) throws GeneralSecurityException, PGPException { + try + { KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); return keyFactory.generatePublic(keySpec); + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } - private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) - throws GeneralSecurityException, PGPException + private PublicKey implGetPublicKeyX509(byte[] pEnc, int pEncOff, ASN1ObjectIdentifier algorithm, String keyAlgorithm) + throws IOException, PGPException, GeneralSecurityException { - ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(ecPub.getCurveOID())); - return implGeneratePrivate(keyAlgorithm, ecPrivSpec); + try + { + return implGeneratePublic(keyAlgorithm, new X509EncodedKeySpec(new SubjectPublicKeyInfo( + new AlgorithmIdentifier(algorithm), Arrays.copyOfRange(pEnc, pEncOff, pEnc.length)).getEncoded())); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } - private PrivateKey implGetPrivateKeyPKCS8(String keyAlgorithm, PrivateKeyInfo privateKeyInfo) - throws GeneralSecurityException, IOException, PGPException + private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) + throws GeneralSecurityException, PGPException, IOException { - PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()); - return implGeneratePrivate(keyAlgorithm, pkcs8Spec); + try + { + ASN1ObjectIdentifier curveOid = ecPub.getCurveOID(); + ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid)); + return implGeneratePrivate(keyAlgorithm, ecPrivSpec); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } - private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) throws GeneralSecurityException, IOException, PGPException + private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) + throws GeneralSecurityException, IOException, PGPException { + try + { ASN1ObjectIdentifier curveOID = ecPub.getCurveOID(); X9ECParameters x9Params = JcaJcePGPUtil.getX9Parameters(curveOID); ECPoint ecPubPoint = JcaJcePGPUtil.decodePoint(ecPub.getEncodedPoint(), x9Params.getCurve()); @@ -562,14 +1033,76 @@ private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) x9Params.getCurve().createPoint( ecPubPoint.getAffineXCoord().toBigInteger(), ecPubPoint.getAffineYCoord().toBigInteger()), - getECParameterSpec(curveOID, x9Params)); + getECParameterSpec(curveOID)); return implGeneratePublic(keyAlgorithm, ecPubSpec); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } - private PublicKey implGetPublicKeyX509(String keyAlgorithm, SubjectPublicKeyInfo subjectPublicKeyInfo) - throws GeneralSecurityException, IOException, PGPException + private PublicKey get25519PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException { - X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(subjectPublicKeyInfo.getEncoded()); - return implGeneratePublic(keyAlgorithm, x509Spec); + try + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "25519 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } + } + + private PublicKey get448PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException + { + try + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "448 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } } diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java index cb1936c4ac..7541cc3089 100644 --- a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JceAEADUtil.java @@ -99,19 +99,25 @@ protected static long getChunkLength(int chunkSize) static byte[][] deriveMessageKeyAndIv(int aeadAlgo, int cipherAlgo, byte[] sessionKey, byte[] salt, byte[] hkdfInfo) throws PGPException { - // TODO: needs to be JCA based. KeyGenerator? + // TODO: needs to be JCA based. KeyGenerator + int keyLen = SymmetricKeyUtils.getKeyLengthInOctets(cipherAlgo); + int ivLen = AEADUtils.getIVLength(aeadAlgo); + byte[] messageKeyAndIv = generateHKDFBytes(sessionKey, salt, hkdfInfo, keyLen + ivLen - 8); + + return new byte[][]{Arrays.copyOfRange(messageKeyAndIv, 0, keyLen), Arrays.copyOfRange(messageKeyAndIv, keyLen, keyLen + ivLen)}; + } + + static byte[] generateHKDFBytes(byte[] sessionKey, byte[] salt, byte[] hkdfInfo, int len) + { HKDFParameters hkdfParameters = new HKDFParameters(sessionKey, salt, hkdfInfo); HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); hkdfGen.init(hkdfParameters); - int keyLen = SymmetricKeyUtils.getKeyLengthInOctets(cipherAlgo); - int ivLen = AEADUtils.getIVLength(aeadAlgo); - byte[] messageKeyAndIv = new byte[keyLen + ivLen - 8]; + byte[] messageKeyAndIv = new byte[len]; hkdfGen.generateBytes(messageKeyAndIv, 0, messageKeyAndIv.length); - - return new byte[][] { Arrays.copyOfRange(messageKeyAndIv, 0, keyLen), Arrays.copyOfRange(messageKeyAndIv, keyLen, keyLen + ivLen) }; + return messageKeyAndIv; } - + /** * Create a {@link PGPDataDecryptor} for decrypting AEAD encrypted OpenPGP v5 data packets. * @@ -239,10 +245,13 @@ Cipher createAEADCipher(int encAlgorithm, int aeadAlgorithm) { if (encAlgorithm != SymmetricKeyAlgorithmTags.AES_128 && encAlgorithm != SymmetricKeyAlgorithmTags.AES_192 - && encAlgorithm != SymmetricKeyAlgorithmTags.AES_256) + && encAlgorithm != SymmetricKeyAlgorithmTags.AES_256 + && encAlgorithm != SymmetricKeyAlgorithmTags.CAMELLIA_128 + && encAlgorithm != SymmetricKeyAlgorithmTags.CAMELLIA_192 + && encAlgorithm != SymmetricKeyAlgorithmTags.CAMELLIA_256) { // Block Cipher must work on 16 byte blocks - throw new PGPException("AEAD only supported for AES based algorithms"); + throw new PGPException("AEAD only supported for AES and Camellia" + " based algorithms"); } String mode; @@ -267,7 +276,6 @@ Cipher createAEADCipher(int encAlgorithm, int aeadAlgorithm) return helper.createCipher(cName); } - static class PGPAeadInputStream extends InputStream { @@ -417,7 +425,7 @@ private byte[] readBlock() byte[] decData; try { - JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.DECRYPT_MODE, getNonce(iv, chunkIndex), 128, adata); + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.DECRYPT_MODE, getNonce(iv, chunkIndex), 128, adata); decData = c.doFinal(buf, 0, dataLen + aeadTagLength); } @@ -433,18 +441,7 @@ private byte[] readBlock() if (dataLen != chunkLength) // it's our last block { - if (v5StyleAEAD) - { - adata = new byte[13]; - System.arraycopy(aaData, 0, adata, 0, aaData.length); - xorChunkId(adata, chunkIndex); - } - else - { - adata = new byte[aaData.length + 8]; - System.arraycopy(aaData, 0, adata, 0, aaData.length); - System.arraycopy(Pack.longToBigEndian(totalBytes), 0, adata, aaData.length, 8); - } + adata = PGPAeadOutputStream.getAdata(v5StyleAEAD, aaData, chunkIndex, totalBytes); try { if (v5StyleAEAD) @@ -491,7 +488,7 @@ static class PGPAeadOutputStream /** * OutputStream for AEAD encryption. * - * @param isV5AEAD isV5AEAD of AEAD (OpenPGP v5 or v6) + * @param isV5AEAD isV5AEAD of AEAD (OpenPGP v5 or v6) * @param out underlying OutputStream * @param c AEAD cipher * @param secretKey secret key @@ -612,14 +609,10 @@ private void writeBlock() try { - JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.ENCRYPT_MODE, getNonce(iv, chunkIndex), 128, adata); + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.ENCRYPT_MODE, getNonce(iv, chunkIndex), 128, adata); out.write(c.doFinal(data, 0, dataOff)); } - catch (IOException e) - { - throw e; - } catch (Exception e) { throw new IOException("exception processing chunk " + chunkIndex + ": " + e.getMessage()); @@ -638,19 +631,7 @@ private void finish() writeBlock(); } - byte[] adata; - if (isV5AEAD) - { - adata = new byte[13]; - System.arraycopy(aaData, 0, adata, 0, aaData.length); - xorChunkId(adata, chunkIndex); - } - else - { - adata = new byte[aaData.length + 8]; - System.arraycopy(aaData, 0, adata, 0, aaData.length); - System.arraycopy(Pack.longToBigEndian(totalBytes), 0, adata, aaData.length, 8); - } + byte[] adata = getAdata(isV5AEAD, aaData, chunkIndex, totalBytes); try { @@ -665,15 +646,29 @@ private void finish() out.write(c.doFinal(aaData, 0, 0)); // output final tag } - catch (IOException e) - { - throw e; - } catch (Exception e) { throw new IOException("exception processing final tag: " + e.getMessage()); } out.close(); } + + private static byte[] getAdata(boolean isV5AEAD, byte[] aaData, long chunkIndex, long totalBytes) + { + byte[] adata; + if (isV5AEAD) + { + adata = new byte[13]; + System.arraycopy(aaData, 0, adata, 0, aaData.length); + xorChunkId(adata, chunkIndex); + } + else + { + adata = new byte[aaData.length + 8]; + System.arraycopy(aaData, 0, adata, 0, aaData.length); + System.arraycopy(Pack.longToBigEndian(totalBytes), 0, adata, aaData.length, 8); + } + return adata; + } } } diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java new file mode 100644 index 0000000000..69d6587415 --- /dev/null +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePBEProtectionRemoverFactory.java @@ -0,0 +1,216 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Provider; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.bcpg.SymmetricKeyUtils; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.generators.HKDFBytesGenerator; +import org.bouncycastle.crypto.params.HKDFParameters; +import org.bouncycastle.jcajce.spec.AEADParameterSpec; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.openpgp.operator.PBEProtectionRemoverFactory; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.PGPSecretKeyDecryptorWithAAD; +import org.bouncycastle.util.Arrays; + +public class JcePBEProtectionRemoverFactory + implements PBEProtectionRemoverFactory +{ + private final char[] passPhrase; + + private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); + private PGPDigestCalculatorProvider calculatorProvider; + private JceAEADUtil aeadUtil = new JceAEADUtil(helper); + + private JcaPGPDigestCalculatorProviderBuilder calculatorProviderBuilder; + + public JcePBEProtectionRemoverFactory(char[] passPhrase) + { + this.passPhrase = passPhrase; + this.calculatorProviderBuilder = new JcaPGPDigestCalculatorProviderBuilder(); + } + + public JcePBEProtectionRemoverFactory(char[] passPhrase, PGPDigestCalculatorProvider calculatorProvider) + { + this.passPhrase = passPhrase; + this.calculatorProvider = calculatorProvider; + } + + public JcePBEProtectionRemoverFactory setProvider(Provider provider) + { + this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + this.aeadUtil = new JceAEADUtil(helper); + + if (calculatorProviderBuilder != null) + { + calculatorProviderBuilder.setProvider(provider); + } + + return this; + } + + public JcePBEProtectionRemoverFactory setProvider(String providerName) + { + this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + this.aeadUtil = new JceAEADUtil(helper); + + if (calculatorProviderBuilder != null) + { + calculatorProviderBuilder.setProvider(providerName); + } + + return this; + } + + public PBESecretKeyDecryptor createDecryptor(String protection) + throws PGPException + { + if (calculatorProvider == null) + { + calculatorProvider = calculatorProviderBuilder.build(); + } + + if (protection.indexOf("ocb") >= 0) + { + return new PGPSecretKeyDecryptorWithAAD(passPhrase, calculatorProvider) + { + public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] aad, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + try + { + Cipher c; + c = helper.createCipher(PGPUtil.getSymmetricCipherName(encAlgorithm) + "/OCB/NoPadding"); + c.init(Cipher.DECRYPT_MODE, JcaJcePGPUtil.makeSymmetricKey(encAlgorithm, key), new AEADParameterSpec(iv, 128, aad)); + return c.doFinal(keyData, keyOff, keyLen); + } + catch (IllegalBlockSizeException e) + { + throw new PGPException("illegal block size: " + e.getMessage(), e); + } + catch (BadPaddingException e) + { + throw new PGPException("bad padding: " + e.getMessage(), e); + } + catch (InvalidAlgorithmParameterException e) + { + throw new PGPException("invalid parameter: " + e.getMessage(), e); + } + catch (InvalidKeyException e) + { + throw new PGPException("invalid key: " + e.getMessage(), e); + } + } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) + throws PGPException + { + byte[] hkdfInfo = new byte[] { + (byte) (0xC0 | packetTag), (byte) keyVersion, (byte) encAlgorithm, (byte) aeadAlgorithm + }; + // TODO: Replace HDKF code with JCE based implementation + HKDFParameters hkdfParameters = new HKDFParameters(s2kKey, null, hkdfInfo); + HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); + hkdfGen.init(hkdfParameters); + byte[] key = new byte[SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)]; + hkdfGen.generateBytes(key, 0, key.length); + + byte[] aad = Arrays.prepend(pubkeyData, (byte) (0xC0 | packetTag)); + + SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm)); + final Cipher c = aeadUtil.createAEADCipher(encAlgorithm, aeadAlgorithm); + try + { + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.DECRYPT_MODE, iv, 128, aad); + byte[] data = c.doFinal(keyData); + return data; + } + catch (Exception e) + { + throw new PGPException("Cannot extract AEAD protected secret key material", e); + } + } + }; + } + else + { + return new PBESecretKeyDecryptor(passPhrase, calculatorProvider) + { + public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + try + { + Cipher c; + c = helper.createCipher(PGPUtil.getSymmetricCipherName(encAlgorithm) + "/CBC/NoPadding"); + c.init(Cipher.DECRYPT_MODE, JcaJcePGPUtil.makeSymmetricKey(encAlgorithm, key), new IvParameterSpec(iv)); + return c.doFinal(keyData, keyOff, keyLen); + } + catch (IllegalBlockSizeException e) + { + throw new PGPException("illegal block size: " + e.getMessage(), e); + } + catch (BadPaddingException e) + { + throw new PGPException("bad padding: " + e.getMessage(), e); + } + catch (InvalidAlgorithmParameterException e) + { + throw new PGPException("invalid parameter: " + e.getMessage(), e); + } + catch (InvalidKeyException e) + { + throw new PGPException("invalid key: " + e.getMessage(), e); + } + } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) + throws PGPException + { + byte[] hkdfInfo = new byte[] { + (byte) (0xC0 | packetTag), (byte) keyVersion, (byte) encAlgorithm, (byte) aeadAlgorithm + }; + // TODO: Replace HDKF code with JCE based implementation + HKDFParameters hkdfParameters = new HKDFParameters(s2kKey, null, hkdfInfo); + HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); + hkdfGen.init(hkdfParameters); + byte[] key = new byte[SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)]; + hkdfGen.generateBytes(key, 0, key.length); + + byte[] aad = Arrays.prepend(pubkeyData, (byte) (0xC0 | packetTag)); + + SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm)); + final Cipher c = aeadUtil.createAEADCipher(encAlgorithm, aeadAlgorithm); + try + { + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.DECRYPT_MODE, iv, 128, aad); + byte[] data = c.doFinal(keyData); + return data; + } + catch (Exception e) + { + throw new PGPException("Cannot extract AEAD protected secret key material", e); + } + } + }; + + } + } +} diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java new file mode 100644 index 0000000000..c76d278234 --- /dev/null +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePBESecretKeyDecryptorBuilder.java @@ -0,0 +1,142 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Provider; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.bcpg.SymmetricKeyUtils; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.generators.HKDFBytesGenerator; +import org.bouncycastle.crypto.params.HKDFParameters; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.util.Arrays; + +public class JcePBESecretKeyDecryptorBuilder +{ + private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); + private PGPDigestCalculatorProvider calculatorProvider; + private JceAEADUtil aeadUtil = new JceAEADUtil(helper); + + private JcaPGPDigestCalculatorProviderBuilder calculatorProviderBuilder; + + public JcePBESecretKeyDecryptorBuilder() + { + this.calculatorProviderBuilder = new JcaPGPDigestCalculatorProviderBuilder(); + } + + public JcePBESecretKeyDecryptorBuilder(PGPDigestCalculatorProvider calculatorProvider) + { + this.calculatorProvider = calculatorProvider; + } + + public JcePBESecretKeyDecryptorBuilder setProvider(Provider provider) + { + this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + this.aeadUtil = new JceAEADUtil(helper); + + if (calculatorProviderBuilder != null) + { + calculatorProviderBuilder.setProvider(provider); + } + + return this; + } + + public JcePBESecretKeyDecryptorBuilder setProvider(String providerName) + { + this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + this.aeadUtil = new JceAEADUtil(helper); + + if (calculatorProviderBuilder != null) + { + calculatorProviderBuilder.setProvider(providerName); + } + + return this; + } + + public PBESecretKeyDecryptor build(char[] passPhrase) + throws PGPException + { + if (calculatorProvider == null) + { + calculatorProvider = calculatorProviderBuilder.build(); + } + + return new PBESecretKeyDecryptor(passPhrase, calculatorProvider) + { + public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + try + { + Cipher c = helper.createCipher(PGPUtil.getSymmetricCipherName(encAlgorithm) + "/CFB/NoPadding"); + + c.init(Cipher.DECRYPT_MODE, JcaJcePGPUtil.makeSymmetricKey(encAlgorithm, key), new IvParameterSpec(iv)); + + return c.doFinal(keyData, keyOff, keyLen); + } + catch (IllegalBlockSizeException e) + { + throw new PGPException("illegal block size: " + e.getMessage(), e); + } + catch (BadPaddingException e) + { + throw new PGPException("bad padding: " + e.getMessage(), e); + } + catch (InvalidAlgorithmParameterException e) + { + throw new PGPException("invalid parameter: " + e.getMessage(), e); + } + catch (InvalidKeyException e) + { + throw new PGPException("invalid key: " + e.getMessage(), e); + } + } + + @Override + public byte[] recoverKeyData(int encAlgorithm, int aeadAlgorithm, byte[] s2kKey, byte[] iv, int packetTag, int keyVersion, byte[] keyData, byte[] pubkeyData) + throws PGPException + { + byte[] hkdfInfo = new byte[] { + (byte) (0xC0 | packetTag), (byte) keyVersion, (byte) encAlgorithm, (byte) aeadAlgorithm + }; + // TODO: Replace HDKF code with JCE based implementation + HKDFParameters hkdfParameters = new HKDFParameters(s2kKey, null, hkdfInfo); + HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); + hkdfGen.init(hkdfParameters); + byte[] key = new byte[SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)]; + hkdfGen.generateBytes(key, 0, key.length); + + byte[] aad = Arrays.prepend(pubkeyData, (byte) (0xC0 | packetTag)); + + SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm)); + final Cipher c = aeadUtil.createAEADCipher(encAlgorithm, aeadAlgorithm); + try + { + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.DECRYPT_MODE, iv, 128, aad); + byte[] data = c.doFinal(keyData); + return data; + } + catch (Exception e) + { + throw new PGPException("Cannot extract AEAD protected secret key material", e); + } + } + }; + } +} diff --git a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java index f99ac79e98..4214f472ec 100644 --- a/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java +++ b/pg/src/main/jdk1.1/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyDataDecryptorFactoryBuilder.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; import java.security.Key; import java.security.KeyFactory; import java.security.PrivateKey; @@ -18,7 +17,6 @@ import javax.crypto.interfaces.DHKey; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; @@ -32,7 +30,6 @@ import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.X25519PublicBCPGKey; import org.bouncycastle.bcpg.X448PublicBCPGKey; -import org.bouncycastle.crypto.params.X25519PublicKeyParameters; import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; @@ -42,6 +39,7 @@ import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.operator.AbstractPublicKeyDataDecryptorFactory; import org.bouncycastle.openpgp.operator.PGPDataDecryptor; import org.bouncycastle.openpgp.operator.PGPPad; import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; @@ -130,12 +128,12 @@ else if (key instanceof RSAKey) public PublicKeyDataDecryptorFactory build(final PrivateKey privKey) { - return new PublicKeyDataDecryptorFactory() + return new AbstractPublicKeyDataDecryptorFactory() { final int expectedPayLoadSize = getExpectedPayloadSize(privKey); @Override - public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData, int pkeskVersion) throws PGPException { if (keyAlgorithm == PublicKeyAlgorithmTags.ECDH || keyAlgorithm == PublicKeyAlgorithmTags.X25519 || keyAlgorithm == PublicKeyAlgorithmTags.X448) @@ -173,12 +171,13 @@ public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket seipd, P public PublicKeyDataDecryptorFactory build(final PGPPrivateKey privKey) { - return new PublicKeyDataDecryptorFactory() + return new AbstractPublicKeyDataDecryptorFactory() { @Override - public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) + public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData, int pkeskVersion) throws PGPException { + boolean containsSKAlg = containsSKAlg(pkeskVersion); if (keyAlgorithm == PublicKeyAlgorithmTags.ECDH) { return decryptSessionData(keyConverter, privKey, secKeyData); @@ -186,12 +185,12 @@ public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData) else if (keyAlgorithm == PublicKeyAlgorithmTags.X25519) { return decryptSessionData(keyConverter, privKey, secKeyData[0], X25519PublicBCPGKey.LENGTH, "X25519withSHA256HKDF", - SymmetricKeyAlgorithmTags.AES_128, EdECObjectIdentifiers.id_X25519, "X25519"); + SymmetricKeyAlgorithmTags.AES_128, EdECObjectIdentifiers.id_X25519, "X25519", containsSKAlg); } else if (keyAlgorithm == PublicKeyAlgorithmTags.X448) { return decryptSessionData(keyConverter, privKey, secKeyData[0], X448PublicBCPGKey.LENGTH, "X448withSHA512HKDF", - SymmetricKeyAlgorithmTags.AES_256, EdECObjectIdentifiers.id_X448, "X448"); + SymmetricKeyAlgorithmTags.AES_256, EdECObjectIdentifiers.id_X448, "X448", containsSKAlg); } PrivateKey jcePrivKey = keyConverter.getPrivateKey(privKey); int expectedPayLoadSize = getExpectedPayloadSize(jcePrivKey); @@ -225,6 +224,14 @@ public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket seipd, P }; } + /** + * Decrypt ECDH encrypted session keys. + * @param converter key converter + * @param privKey our private key + * @param secKeyData encrypted session key + * @return decrypted session key + * @throws PGPException + */ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey privKey, byte[][] secKeyData) throws PGPException { @@ -236,18 +243,12 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr byte[] keyEnc; pLen = ((((enc[0] & 0xff) << 8) + (enc[1] & 0xff)) + 7) / 8; - if ((2 + pLen + 1) > enc.length) - { - throw new PGPException("encoded length out of range"); - } + checkRange(2 + pLen + 1, enc); pEnc = new byte[pLen]; System.arraycopy(enc, 2, pEnc, 0, pLen); int keyLen = enc[pLen + 2] & 0xff; - if ((2 + pLen + 1 + keyLen) > enc.length) - { - throw new PGPException("encoded length out of range"); - } + checkRange(2 + pLen + 1 + keyLen, enc); keyEnc = new byte[keyLen]; System.arraycopy(enc, 2 + pLen + 1, keyEnc, 0, keyLen); @@ -258,15 +259,24 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr String agreementName; ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)pubKeyData.getKey(); // XDH - if (ecKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + if (JcaJcePGPUtil.isX25519(ecKey.getCurveOID())) { agreementName = RFC6637Utils.getXDHAlgorithm(pubKeyData); - if (pEnc.length != (1 + X25519PublicKeyParameters.KEY_SIZE) || 0x40 != pEnc[0]) + if (pEnc.length != (1 + X25519PublicBCPGKey.LENGTH) || 0x40 != pEnc[0]) { throw new IllegalArgumentException("Invalid Curve25519 public key"); } publicKey = getPublicKey(pEnc, EdECObjectIdentifiers.id_X25519, 1); } + else if (ecKey.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + agreementName = RFC6637Utils.getXDHAlgorithm(pubKeyData); + if (pEnc.length != (1 + X448PublicBCPGKey.LENGTH) || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid Curve25519 public key"); + } + publicKey = getPublicKey(pEnc, EdECObjectIdentifiers.id_X448, 1); + } else { X9ECParametersHolder x9Params = ECNamedCurveTable.getByOIDLazy(ecKey.getCurveOID()); @@ -274,7 +284,7 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr agreementName = RFC6637Utils.getAgreementAlgorithm(pubKeyData); - publicKey = converter.getPublicKey(new PGPPublicKey(new PublicKeyPacket(PublicKeyAlgorithmTags.ECDH, new Date(), + publicKey = converter.getPublicKey(new PGPPublicKey(new PublicKeyPacket(pubKeyData.getVersion(), PublicKeyAlgorithmTags.ECDH, new Date(), new ECDHPublicBCPGKey(ecKey.getCurveOID(), publicPoint, ecKey.getHashAlgorithm(), ecKey.getSymmetricKeyAlgorithm())), fingerprintCalculator)); } byte[] userKeyingMaterial = RFC6637Utils.createUserKeyingMaterial(pubKeyData, fingerprintCalculator); @@ -289,26 +299,42 @@ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey pr } } + /** + * Decrypt X25519 / X448 encrypted session keys. + * @param converter key converter + * @param privKey our private key + * @param enc encrypted session key + * @param pLen Key length + * @param agreementAlgorithm agreement algorithm + * @param symmetricKeyAlgorithm wrapping algorithm + * @param algorithmIdentifier ephemeral key algorithm identifier + * @param algorithmName public key algorithm name + * @param containsSKAlg whether the PKESK packet is version 3 + * @return decrypted session data + * @throws PGPException + */ private byte[] decryptSessionData(JcaPGPKeyConverter converter, PGPPrivateKey privKey, byte[] enc, int pLen, String agreementAlgorithm, - int symmetricKeyAlgorithm, ASN1ObjectIdentifier algprithmIdentifier, String algorithmName) + int symmetricKeyAlgorithm, ASN1ObjectIdentifier algorithmIdentifier, String algorithmName, boolean containsSKAlg) throws PGPException { try { - byte[] pEnc = new byte[pLen]; - System.arraycopy(enc, 0, pEnc, 0, pLen); - int keyLen = enc[pLen] & 0xff; - if ((pLen + 1 + keyLen) > enc.length) - { - throw new PGPException("encoded length out of range"); - } - byte[] keyEnc = new byte[keyLen - 1]; - System.arraycopy(enc, pLen + 2, keyEnc, 0, keyEnc.length); - PublicKey publicKey = getPublicKey(pEnc, algprithmIdentifier, 0); - Key paddedSessionKey = getSessionKey(converter, privKey, agreementAlgorithm, publicKey, symmetricKeyAlgorithm, keyEnc, - JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(pEnc, privKey.getPublicKeyPacket(), algorithmName)); - symmetricKeyAlgorithm = enc[pLen + 1] & 0xff; - return Arrays.concatenate(new byte[]{(byte)symmetricKeyAlgorithm}, paddedSessionKey.getEncoded()); + // ephemeral key (32 / 56 octets) + byte[] ephemeralKey = Arrays.copyOf(enc, pLen); + + int size = enc[pLen] & 0xff; + + checkRange(pLen + 1 + size, enc); + + // encrypted session key + int sesKeyLen = size - (containsSKAlg ? 1 : 0); + int sesKeyOff = pLen + 1 + (containsSKAlg ? 1 : 0); + byte[] keyEnc = Arrays.copyOfRange(enc, sesKeyOff, sesKeyOff + sesKeyLen); + + PublicKey ephemeralPubKey = getPublicKey(ephemeralKey, algorithmIdentifier, 0); + Key paddedSessionKey = getSessionKey(converter, privKey, agreementAlgorithm, ephemeralPubKey, symmetricKeyAlgorithm, keyEnc, + JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(ephemeralKey, privKey.getPublicKeyPacket(), algorithmName)); + return paddedSessionKey.getEncoded(); } catch (Exception e) { @@ -323,16 +349,16 @@ private Key getSessionKey(JcaPGPKeyConverter converter, PGPPrivateKey privKey, S try { PrivateKey privateKey = converter.getPrivateKey(privKey); - Key key = JcaJcePGPUtil.getSecret(helper, publicKey, RFC6637Utils.getKeyEncryptionOID(symmetricKeyAlgorithm).getId(), agreementName, ukms, privateKey); + Key key = JcaJcePGPUtil.getSecret(helper, publicKey, RFC6637Utils.getKeyEncryptionOID(symmetricKeyAlgorithm).getId(), agreementName, ukms, privateKey); Cipher c = helper.createKeyWrapper(symmetricKeyAlgorithm); c.init(Cipher.UNWRAP_MODE, key); return c.unwrap(keyEnc, "Session", Cipher.SECRET_KEY); } - catch(InvalidKeyException e) + catch (PGPException e) { - throw new GeneralSecurityException(e.toString()); + throw e; } - catch(NoSuchAlgorithmException e) + catch (Exception e) { throw new GeneralSecurityException(e.toString()); } @@ -341,10 +367,25 @@ private Key getSessionKey(JcaPGPKeyConverter converter, PGPPrivateKey privKey, S private PublicKey getPublicKey(byte[] pEnc, ASN1ObjectIdentifier algprithmIdentifier, int pEncOff) throws PGPException, GeneralSecurityException, IOException { + try + { KeyFactory keyFact = helper.createKeyFactory("XDH"); return keyFact.generatePublic(new X509EncodedKeySpec(new SubjectPublicKeyInfo( new AlgorithmIdentifier(algprithmIdentifier), Arrays.copyOfRange(pEnc, pEncOff, pEnc.length)).getEncoded())); + } + catch (IOException e) + { + throw e; + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new GeneralSecurityException(e.toString()); + } } private void updateWithMPI(Cipher c, int expectedPayloadSize, byte[] encMPI) @@ -370,6 +411,15 @@ private void updateWithMPI(Cipher c, int expectedPayloadSize, byte[] encMPI) } } + /** + * Decrypt RSA / Elgamal encrypted session keys. + * @param keyAlgorithm public key algorithm + * @param privKey our private key + * @param expectedPayloadSize payload size + * @param secKeyData ESK data + * @return session data + * @throws PGPException + */ private byte[] decryptSessionData(int keyAlgorithm, PrivateKey privKey, int expectedPayloadSize, byte[][] secKeyData) throws PGPException { @@ -405,4 +455,13 @@ private byte[] decryptSessionData(int keyAlgorithm, PrivateKey privKey, int expe throw new PGPException("exception decrypting session data", e); } } + + private static void checkRange(int pLen, byte[] enc) + throws PGPException + { + if (pLen > enc.length) + { + throw new PGPException("encoded length out of range"); + } + } } diff --git a/pg/src/main/jdk1.2/org/bouncycastle/openpgp/operator/PGPKeyConverter.java b/pg/src/main/jdk1.2/org/bouncycastle/openpgp/operator/PGPKeyConverter.java new file mode 100644 index 0000000000..e44cd5fe04 --- /dev/null +++ b/pg/src/main/jdk1.2/org/bouncycastle/openpgp/operator/PGPKeyConverter.java @@ -0,0 +1,123 @@ +package org.bouncycastle.openpgp.operator; + +import java.io.IOException; +import java.math.BigInteger; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.sec.SECObjectIdentifiers; +import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.PGPAlgorithmParameters; +import org.bouncycastle.openpgp.PGPKdfParameters; +import org.bouncycastle.util.BigIntegers; + +public abstract class PGPKeyConverter +{ + protected PGPKeyConverter() + { + + } + + /** + * Reference: + * RFC9580 - OpenPGP + *

      + * This class provides information about the recommended algorithms to use + * depending on the key version and curve type in OpenPGP keys. + * + *

      + * For OpenPGP keys using the specified curves, the following algorithms are recommended: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
      Recommended Algorithms for OpenPGP Keys
      CurveHash AlgorithmSymmetric Algorithm
      NIST P-256SHA2-256AES-128
      NIST P-384SHA2-384AES-192
      NIST P-521SHA2-512AES-256
      brainpoolP256r1SHA2-256AES-128
      brainpoolP384r1SHA2-384AES-192
      brainpoolP512r1SHA2-512AES-256
      Curve25519LegacySHA2-256AES-128
      Curve448Legacy (not in RFC Draft)SHA2-512AES-256
      + */ + protected PGPKdfParameters implGetKdfParameters(ASN1ObjectIdentifier curveID, PGPAlgorithmParameters algorithmParameters) + { + if (null == algorithmParameters) + { + if (curveID.equals(SECObjectIdentifiers.secp256r1) || curveID.equals(TeleTrusTObjectIdentifiers.brainpoolP256r1) + || curveID.equals(CryptlibObjectIdentifiers.curvey25519) || curveID.equals(EdECObjectIdentifiers.id_X25519)) + { + return new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + } + else if (curveID.equals(SECObjectIdentifiers.secp384r1) || curveID.equals(TeleTrusTObjectIdentifiers.brainpoolP384r1)) + { + return new PGPKdfParameters(HashAlgorithmTags.SHA384, SymmetricKeyAlgorithmTags.AES_192); + } + else if (curveID.equals(SECObjectIdentifiers.secp521r1) || curveID.equals(TeleTrusTObjectIdentifiers.brainpoolP512r1) + || curveID.equals(EdECObjectIdentifiers.id_X448)) + { + return new PGPKdfParameters(HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); + } + else + { + throw new IllegalArgumentException("unknown curve"); + } + } + return (PGPKdfParameters)algorithmParameters; + } + + public PrivateKeyInfo getPrivateKeyInfo(ASN1ObjectIdentifier algorithm, int keySize, byte[] key) + throws IOException + { + return (new PrivateKeyInfo(new AlgorithmIdentifier(algorithm), + new DEROctetString(BigIntegers.asUnsignedByteArray(keySize, new BigInteger(1, key))))); + } + + public PrivateKeyInfo getPrivateKeyInfo(ASN1ObjectIdentifier algorithm, byte[] key) + throws IOException + { + return (new PrivateKeyInfo(new AlgorithmIdentifier(algorithm), new DEROctetString(key))); + } +} diff --git a/pg/src/main/jdk1.2/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java b/pg/src/main/jdk1.2/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java new file mode 100644 index 0000000000..4e58e334b7 --- /dev/null +++ b/pg/src/main/jdk1.2/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java @@ -0,0 +1,973 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.PublicKey; +import java.security.interfaces.DSAParams; +import java.security.interfaces.DSAPrivateKey; +import java.security.interfaces.DSAPublicKey; +import org.bouncycastle.jce.interfaces.ECPrivateKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.DSAPrivateKeySpec; +import java.security.spec.DSAPublicKeySpec; +import org.bouncycastle.jce.spec.ECParameterSpec; +import org.bouncycastle.jce.spec.ECPrivateKeySpec; +import org.bouncycastle.jce.spec.ECPublicKeySpec; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Date; +import java.util.Enumeration; + +import javax.crypto.interfaces.DHPrivateKey; +import javax.crypto.interfaces.DHPublicKey; +import javax.crypto.spec.DHParameterSpec; +import javax.crypto.spec.DHPrivateKeySpec; +import javax.crypto.spec.DHPublicKeySpec; + +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; +import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; +import org.bouncycastle.asn1.gnu.GNUObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X962Parameters; +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.asn1.x9.X9ECParametersHolder; +import org.bouncycastle.asn1.x9.X9ECPoint; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.bcpg.BCPGKey; +import org.bouncycastle.bcpg.DSAPublicBCPGKey; +import org.bouncycastle.bcpg.DSASecretBCPGKey; +import org.bouncycastle.bcpg.ECDHPublicBCPGKey; +import org.bouncycastle.bcpg.ECDSAPublicBCPGKey; +import org.bouncycastle.bcpg.ECPublicBCPGKey; +import org.bouncycastle.bcpg.ECSecretBCPGKey; +import org.bouncycastle.bcpg.Ed25519PublicBCPGKey; +import org.bouncycastle.bcpg.Ed25519SecretBCPGKey; +import org.bouncycastle.bcpg.Ed448PublicBCPGKey; +import org.bouncycastle.bcpg.Ed448SecretBCPGKey; +import org.bouncycastle.bcpg.EdDSAPublicBCPGKey; +import org.bouncycastle.bcpg.EdSecretBCPGKey; +import org.bouncycastle.bcpg.ElGamalPublicBCPGKey; +import org.bouncycastle.bcpg.ElGamalSecretBCPGKey; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.RSAPublicBCPGKey; +import org.bouncycastle.bcpg.RSASecretBCPGKey; +import org.bouncycastle.bcpg.X25519PublicBCPGKey; +import org.bouncycastle.bcpg.X25519SecretBCPGKey; +import org.bouncycastle.bcpg.X448PublicBCPGKey; +import org.bouncycastle.bcpg.X448SecretBCPGKey; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; +import org.bouncycastle.math.ec.rfc8032.Ed25519; +import org.bouncycastle.math.ec.rfc8032.Ed448; +import org.bouncycastle.openpgp.PGPAlgorithmParameters; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKdfParameters; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; +import org.bouncycastle.openpgp.operator.PGPKeyConverter; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.BigIntegers; + +public class JcaPGPKeyConverter + extends PGPKeyConverter +{ + private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); + private KeyFingerPrintCalculator fingerPrintCalculator = new JcaKeyFingerprintCalculator(); + + public JcaPGPKeyConverter setProvider(Provider provider) + { + this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + + return this; + } + + public JcaPGPKeyConverter setProvider(String providerName) + { + this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + + return this; + } + + /** + * Convert a PrivateKey into a PGPPrivateKey. + * + * @param pub the corresponding PGPPublicKey to privKey. + * @param privKey the private key for the key in pub. + * @return a PGPPrivateKey + * @throws PGPException + */ + public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) + throws PGPException + { + BCPGKey privPk = getPrivateBCPGKey(pub, privKey); + + return new PGPPrivateKey(pub.getKeyID(), pub.getPublicKeyPacket(), privPk); + } + + /** + * Create a version 4 PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param algorithm asymmetric algorithm type representing the public key. + * @param algorithmParameters additional parameters to be stored against the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PGPAlgorithmParameters, PublicKey, Date)} instead. + */ + @Deprecated + public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, time); + } + + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param algorithmParameters additional parameters to be stored against the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + throws PGPException + { + BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey); + + return new PGPPublicKey(new PublicKeyPacket(version, algorithm, time, bcpgKey), fingerPrintCalculator); + } + + /** + * Create a version 4 PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PublicKey, Date)} instead. + */ + @Deprecated + public PGPPublicKey getPGPPublicKey(int algorithm, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(algorithm, null, pubKey, time); + } + + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(version, algorithm, null, pubKey, time); + } + + public PrivateKey getPrivateKey(PGPPrivateKey privKey) + throws PGPException + { + if (privKey instanceof JcaPGPPrivateKey) + { + return ((JcaPGPPrivateKey)privKey).getPrivateKey(); + } + + final PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); + final BCPGKey privPk = privKey.getPrivateKeyDataPacket(); + + try + { + switch (pubPk.getAlgorithm()) + { + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicBCPGKey dsaPub = (DSAPublicBCPGKey)pubPk.getKey(); + DSASecretBCPGKey dsaPriv = (DSASecretBCPGKey)privPk; + DSAPrivateKeySpec dsaPrivSpec = new DSAPrivateKeySpec(dsaPriv.getX(), dsaPub.getP(), dsaPub.getQ(), + dsaPub.getG()); + return implGeneratePrivate("DSA", dsaPrivSpec); + } + + case PublicKeyAlgorithmTags.ECDH: + { + ECDHPublicBCPGKey ecdhPub = (ECDHPublicBCPGKey)pubPk.getKey(); + ECSecretBCPGKey ecdhK = (ECSecretBCPGKey)privPk; + + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhPub.getCurveOID())) + { + // 'reverse' because the native format for X25519 private keys is little-endian + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } + }); + } + // Legacy X448 (1.3.101.111) + else if (EdECObjectIdentifiers.id_X448.equals(ecdhPub.getCurveOID())) + { + // 'reverse' because the native format for X448 private keys is little-endian (?) + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + + } + }); + } + // Brainpool, NIST etc. + else + { + return implGetPrivateKeyEC("ECDH", ecdhPub, ecdhK); + } + } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + X25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + X448SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } + case PublicKeyAlgorithmTags.ECDSA: + { + return implGetPrivateKeyEC("EC", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + EdDSAPublicBCPGKey eddsaPub = (EdDSAPublicBCPGKey) pubPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaPub.getCurveOID())) + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + BigIntegers.asUnsignedByteArray(Ed448.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); + } + }); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + ElGamalPublicBCPGKey elPub = (ElGamalPublicBCPGKey)pubPk.getKey(); + ElGamalSecretBCPGKey elPriv = (ElGamalSecretBCPGKey)privPk; + DHPrivateKeySpec elSpec = new DHPrivateKeySpec(elPriv.getX(), elPub.getP(), elPub.getG()); + return implGeneratePrivate("ElGamal", elSpec); + } + + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPublicBCPGKey rsaPub = (RSAPublicBCPGKey)pubPk.getKey(); + RSASecretBCPGKey rsaPriv = (RSASecretBCPGKey)privPk; + RSAPrivateCrtKeySpec rsaPrivSpec = new RSAPrivateCrtKeySpec(rsaPriv.getModulus(), + rsaPub.getPublicExponent(), rsaPriv.getPrivateExponent(), rsaPriv.getPrimeP(), rsaPriv.getPrimeQ(), + rsaPriv.getPrimeExponentP(), rsaPriv.getPrimeExponentQ(), rsaPriv.getCrtCoefficient()); + return implGeneratePrivate("RSA", rsaPrivSpec); + } + + default: + throw new PGPException("unknown public key algorithm encountered: " + pubPk.getAlgorithm()); + } + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new PGPException("Exception constructing key", e); + } + } + + public PublicKey getPublicKey(PGPPublicKey publicKey) + throws PGPException + { + PublicKeyPacket publicPk = publicKey.getPublicKeyPacket(); + + try + { + switch (publicPk.getAlgorithm()) + { + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicBCPGKey dsaK = (DSAPublicBCPGKey)publicPk.getKey(); + DSAPublicKeySpec dsaSpec = new DSAPublicKeySpec(dsaK.getY(), dsaK.getP(), dsaK.getQ(), dsaK.getG()); + return implGeneratePublic("DSA", dsaSpec); + } + + case PublicKeyAlgorithmTags.ECDH: + { + ECDHPublicBCPGKey ecdhK = (ECDHPublicBCPGKey)publicPk.getKey(); + + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhK.getCurveOID())) + { + return get25519PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X25519, "XDH", "Curve"); + } + // Legacy X448 (1.3.101.111) + else if (ecdhK.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + return get448PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X448, "XDH", "Curve"); + } + // Brainpool, NIST etc. + else + { + return implGetPublicKeyEC("ECDH", ecdhK); + } + } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X25519, "XDH"); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X448, "XDH"); + } + case PublicKeyAlgorithmTags.ECDSA: + { + return implGetPublicKeyEC("EC", (ECDSAPublicBCPGKey) publicPk.getKey()); + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + EdDSAPublicBCPGKey eddsaKey = (EdDSAPublicBCPGKey) publicPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaKey.getCurveOID())) + { + return get448PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed448, "EdDSA", "Ed"); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 + else + { + return get25519PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); + } + } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed448, "EdDSA"); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + ElGamalPublicBCPGKey elK = (ElGamalPublicBCPGKey)publicPk.getKey(); + DHPublicKeySpec elSpec = new DHPublicKeySpec(elK.getY(), elK.getP(), elK.getG()); + return implGeneratePublic("ElGamal", elSpec); + } + + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPublicBCPGKey rsaK = (RSAPublicBCPGKey)publicPk.getKey(); + RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsaK.getModulus(), rsaK.getPublicExponent()); + return implGeneratePublic("RSA", rsaSpec); + } + + default: + throw new PGPException("unknown public key algorithm encountered: " + publicPk.getAlgorithm()); + } + } + catch (PGPException e) + { + throw e; + } + catch (Exception e) + { + throw new PGPException("exception constructing public key", e); + } + } + + private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid) + throws IOException, GeneralSecurityException + { + AlgorithmParameters params = helper.createAlgorithmParameters("EC"); + + params.init(new X962Parameters(curveOid).getEncoded()); + + return (org.bouncycastle.jce.spec.ECParameterSpec)params.getParameterSpec(ECParameterSpec.class); + } + + private BCPGKey getPrivateBCPGKey(PrivateKey privKey, BCPGKeyOperation operation) + throws PGPException + { + PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(privKey.getEncoded()); + + try + { + return operation.getBCPGKey(ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets()); + } + catch (IOException e) + { + throw new PGPException(e.getMessage(), e); + } + } + + private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) + throws PGPException + { + switch (pub.getAlgorithm()) + { + case PublicKeyAlgorithmTags.DSA: + { + DSAPrivateKey dsK = (DSAPrivateKey)privKey; + return new DSASecretBCPGKey(dsK.getX()); + } + + case PublicKeyAlgorithmTags.ECDH: + { + if (privKey instanceof ECPrivateKey) + { + ECPrivateKey ecK = (ECPrivateKey)privKey; + return new ECSecretBCPGKey(ecK.getD()); + } + else + { + // 'reverse' because the native format for X25519,X448 private keys is little-endian + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(key))); + } + }); + } + } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519SecretBCPGKey(key); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X448SecretBCPGKey(key); + } + }); + } + case PublicKeyAlgorithmTags.ECDSA: + { + return new ECSecretBCPGKey(((ECPrivateKey)privKey).getD()); + } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new EdSecretBCPGKey(new BigInteger(1, key)); + } + }); + } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519SecretBCPGKey(key); + } + }); + } + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return getPrivateBCPGKey(privKey, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448SecretBCPGKey(key); + } + }); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + DHPrivateKey esK = (DHPrivateKey)privKey; + return new ElGamalSecretBCPGKey(esK.getX()); + } + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPrivateCrtKey rsK = (RSAPrivateCrtKey)privKey; + return new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ()); + } + default: + throw new PGPException("unknown public key algorithm encountered: " + pub.getAlgorithm()); + } + } + + private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey) + throws PGPException + { + switch (algorithm) + { + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPublicKey rK = (RSAPublicKey) pubKey; + return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + DHPublicKey egK = (DHPublicKey) pubKey; + return new ElGamalPublicBCPGKey(egK.getParams().getP(), egK.getParams().getG(), egK.getY()); + } + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicKey dK = (DSAPublicKey) pubKey; + DSAParams dP = dK.getParams(); + return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); + } + + case PublicKeyAlgorithmTags.DIFFIE_HELLMAN: + { + DHPublicKey eK = (DHPublicKey) pubKey; + DHParameterSpec eS = eK.getParams(); + return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); + } + + case PublicKeyAlgorithmTags.ECDH: + case PublicKeyAlgorithmTags.ECDSA: + { + SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + + // TODO: should probably match curve by comparison as well + ASN1Encodable enc = keyInfo.getAlgorithm().getAlgorithm(); + ASN1ObjectIdentifier curveOid; + curveOid = ASN1ObjectIdentifier.getInstance(enc); + + // BCECPublicKey uses explicit parameter encoding, so we need to find the named curve manually + if (X9ObjectIdentifiers.id_ecPublicKey.equals(curveOid)) + { + enc = getNamedCurveOID(X962Parameters.getInstance(keyInfo.getAlgorithm().getParameters())); + ASN1ObjectIdentifier nCurveOid = ASN1ObjectIdentifier.getInstance(enc); + if (nCurveOid != null) + { + curveOid = nCurveOid; + } + } + + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + if (pubKey.getAlgorithm().regionMatches(true, 0, "X4", 0, 2)) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // sun.security.ec.XDHPublicKeyImpl returns "XDH" for getAlgorithm() + // In this case we need to determine the curve by looking at the length of the encoding :/ + else if (pubKey.getAlgorithm().regionMatches(true, 0, "XDH", 0, 3)) + { + // Legacy X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + if (X25519.SCALAR_SIZE + 12 == pubKey.getEncoded().length) // + 12 for some reason + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + else + { + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + } + + X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + + ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); + X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); + + if (algorithm == PGPPublicKey.ECDH) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); + + return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), + kdfParams.getSymmetricWrapAlgorithm()); + } + else + { + return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + } + } + + case PublicKeyAlgorithmTags.EDDSA_LEGACY: + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) + { + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + // Legacy Ed448 (1.3.101.113) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED4", 0, 3)) + { + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + // Manual matching on curve encoding length + else + { + // sun.security.ec.ed.EdDSAPublicKeyImpl returns "EdDSA" for getAlgorithm() + // if algorithm is just EdDSA, we need to detect the curve based on encoding length :/ + if (pubKey.getEncoded().length == 12 + Ed25519.PUBLIC_KEY_SIZE) // +12 for some reason + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + else + { + // Legacy Ed448 (1.3.101.113) + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + } + } + + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519PublicBCPGKey(key); + } + }); + } + + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: + { + return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448PublicBCPGKey(key); + } + }); + } + + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: + { + return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519PublicBCPGKey(key); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X448PublicBCPGKey(key); + } + }); + } + + default: + throw new PGPException("unknown public key algorithm encountered: " + algorithm); + } + } + + private ASN1Encodable getNamedCurveOID(X962Parameters ecParams) + { + ECCurve curve = null; + if (ecParams.isNamedCurve()) + { + return ASN1ObjectIdentifier.getInstance(ecParams.getParameters()); + } + else if (ecParams.isImplicitlyCA()) + { + curve = ((X9ECParameters)CryptoServicesRegistrar.getProperty(CryptoServicesRegistrar.Property.EC_IMPLICITLY_CA)).getCurve(); + } + else + { + curve = X9ECParameters.getInstance(ecParams.getParameters()).getCurve(); + } + + // Iterate through all registered curves to find applicable OID + Enumeration names = ECNamedCurveTable.getNames(); + while (names.hasMoreElements()) + { + String name = (String)names.nextElement(); + X9ECParameters parms = ECNamedCurveTable.getByName(name); + if (curve.equals(parms.getCurve())) + { + return ECNamedCurveTable.getOID(name); + } + } + return null; + } + + @FunctionalInterface + private interface BCPGKeyOperation + { + BCPGKey getBCPGKey(byte[] key); + } + + private BCPGKey getPublicBCPGKey(PublicKey pubKey, int keySize, BCPGKeyOperation operation) + { + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); + byte[] pointEnc = new byte[keySize]; + // refer to getPointEncUncompressed + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); + return operation.getBCPGKey(pointEnc); + } + + private byte[] getPointEncUncompressed(PublicKey pubKey, int publicKeySize) + { + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); + byte[] pointEnc = new byte[1 + publicKeySize]; + + pointEnc[0] = 0x40; + //offset with pointEnc.length - pubInfo.length to avoid leading zero issue + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); + return pointEnc; + } + + @FunctionalInterface + private interface Operation + { + PrivateKeyInfo getPrivateKeyInfos() + throws IOException; + } + + private PrivateKey implGeneratePrivate(String keyAlgorithm, Operation operation) + throws GeneralSecurityException, PGPException, IOException + { + PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(operation.getPrivateKeyInfos().getEncoded()); + KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); + return keyFactory.generatePrivate(pkcs8Spec); + } + + private PrivateKey implGeneratePrivate(String keyAlgorithm, KeySpec keySpec) + throws GeneralSecurityException, PGPException + { + KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); + return keyFactory.generatePrivate(keySpec); + } + + private PublicKey implGeneratePublic(String keyAlgorithm, KeySpec keySpec) + throws GeneralSecurityException, PGPException + { + KeyFactory keyFactory = helper.createKeyFactory(keyAlgorithm); + return keyFactory.generatePublic(keySpec); + } + + private PublicKey implGetPublicKeyX509(byte[] pEnc, int pEncOff, ASN1ObjectIdentifier algorithm, String keyAlgorithm) + throws IOException, PGPException, GeneralSecurityException + { + return implGeneratePublic(keyAlgorithm, new X509EncodedKeySpec(new SubjectPublicKeyInfo( + new AlgorithmIdentifier(algorithm), Arrays.copyOfRange(pEnc, pEncOff, pEnc.length)).getEncoded())); + } + + private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) + throws GeneralSecurityException, PGPException, IOException + { + ASN1ObjectIdentifier curveOid = ecPub.getCurveOID(); + ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid)); + return implGeneratePrivate(keyAlgorithm, ecPrivSpec); + } + + private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) + throws GeneralSecurityException, IOException, PGPException + { + ASN1ObjectIdentifier curveOID = ecPub.getCurveOID(); + X9ECParameters x9Params = JcaJcePGPUtil.getX9Parameters(curveOID); + ECPoint ecPubPoint = JcaJcePGPUtil.decodePoint(ecPub.getEncodedPoint(), x9Params.getCurve()); + ECPublicKeySpec ecPubSpec = new ECPublicKeySpec( + x9Params.getCurve().createPoint( + ecPubPoint.getAffineXCoord().toBigInteger(), + ecPubPoint.getAffineYCoord().toBigInteger()), + getECParameterSpec(curveOID)); + return implGeneratePublic(keyAlgorithm, ecPubSpec); + } + + private PublicKey get25519PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "25519 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } + + private PublicKey get448PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "448 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } +} diff --git a/pg/src/main/jdk1.3/org/bouncycastle/bcpg/StreamUtil.java b/pg/src/main/jdk1.3/org/bouncycastle/bcpg/StreamUtil.java index 147669f33f..8cb743f043 100644 --- a/pg/src/main/jdk1.3/org/bouncycastle/bcpg/StreamUtil.java +++ b/pg/src/main/jdk1.3/org/bouncycastle/bcpg/StreamUtil.java @@ -1,90 +1,199 @@ package org.bouncycastle.bcpg; import java.io.ByteArrayInputStream; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.bouncycastle.util.Arrays; + class StreamUtil { + private static final long MAX_MEMORY = Integer.MAX_VALUE; + /** - * Find out possible longest length... + * Find out possible longest length, capped by available memory. * * @param in input stream of interest * @return length calculation or MAX_VALUE. */ static int findLimit(InputStream in) { + // TODO: this can obviously be improved. if (in instanceof ByteArrayInputStream) { return ((ByteArrayInputStream)in).available(); } - return Integer.MAX_VALUE; + if (MAX_MEMORY > Integer.MAX_VALUE) + { + return Integer.MAX_VALUE; + } + + return (int)MAX_MEMORY; + } + + static void writeNewPacketLength(OutputStream out, long bodyLen) + throws IOException + { + if (bodyLen < 192) + { + out.write((byte)bodyLen); + } + else if (bodyLen <= 8383) + { + bodyLen -= 192; + + out.write((byte)(((bodyLen >> 8) & 0xff) + 192)); + out.write((byte)bodyLen); + } + else + { + out.write(0xff); + writeBodyLen(out, bodyLen); + } + } + + static void writeBodyLen(OutputStream out, long bodyLen) + throws IOException + { + out.write((byte)(bodyLen >> 24)); + out.write((byte)(bodyLen >> 16)); + out.write((byte)(bodyLen >> 8)); + out.write((byte)bodyLen); + } + + static void writeKeyID(BCPGOutputStream pOut, long keyID) + throws IOException + { + pOut.write((byte)(keyID >> 56)); + pOut.write((byte)(keyID >> 48)); + pOut.write((byte)(keyID >> 40)); + pOut.write((byte)(keyID >> 32)); + pOut.write((byte)(keyID >> 24)); + pOut.write((byte)(keyID >> 16)); + pOut.write((byte)(keyID >> 8)); + pOut.write((byte)(keyID)); + } + + static long readKeyID(BCPGInputStream in) + throws IOException + { + long keyID = (long)in.read() << 56; + keyID |= (long)in.read() << 48; + keyID |= (long)in.read() << 40; + keyID |= (long)in.read() << 32; + keyID |= (long)in.read() << 24; + keyID |= (long)in.read() << 16; + keyID |= (long)in.read() << 8; + return keyID | in.read(); + } + + static void writeTime(BCPGOutputStream pOut, long time) + throws IOException + { + StreamUtil.write4OctetLength(pOut, (int)time); + } + + static long readTime(BCPGInputStream in) + throws IOException + { + return (long)read4OctetLength(in) * 1000L; + } + + static void write2OctetLength(OutputStream pOut, int len) + throws IOException + { + pOut.write(len >> 8); + pOut.write(len); + } + + static int read2OctetLength(InputStream in) + throws IOException + { + return (in.read() << 8) | in.read(); + } + + static void write4OctetLength(OutputStream pOut, int len) + throws IOException + { + pOut.write(len >> 24); + pOut.write(len >> 16); + pOut.write(len >> 8); + pOut.write(len); + } + + static int read4OctetLength(InputStream in) + throws IOException + { + return (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); + } + + static int flag_eof = 0; + static int flag_isLongLength = 1; + static int flag_partial = 2; + /** + * Note: flags is an array of three boolean values: + * flags[0] indicates l is negative, flag for eof + * flags[1] indicates (is)longLength = true + * flags[2] indicate partial = true + */ + static int readBodyLen(InputStream in, boolean[] flags) + throws IOException + { + Arrays.fill(flags, false); + int l = in.read(); + int bodyLen = -1; + if (l < 0) + { + flags[flag_eof] = true; + } + if (l < 192) + { + bodyLen = l; + } + else if (l <= 223) + { + bodyLen = ((l - 192) << 8) + (in.read()) + 192; + } + else if (l == 255) + { + flags[flag_isLongLength] = true; + bodyLen = StreamUtil.read4OctetLength(in); + } + else + { + flags[flag_partial] = true; + bodyLen = 1 << (l & 0x1f); + } + return bodyLen; + } + + static void write8OctetLength(OutputStream pOut, long len) + throws IOException + { + pOut.write((int) (len >> 56)); + pOut.write((int) (len >> 48)); + pOut.write((int) (len >> 40)); + pOut.write((int) (len >> 32)); + pOut.write((int) (len >> 24)); + pOut.write((int) (len >> 16)); + pOut.write((int) (len >> 8)); + pOut.write((int) len); + } + + static long read8OctetLength(InputStream in) + throws IOException + { + return ((long) in.read() << 56) | + ((long) in.read() << 48) | + ((long) in.read() << 40) | + ((long) in.read() << 32) | + ((long) in.read() << 24) | + ((long) in.read() << 16) | + ((long) in.read() << 8) | + ((long) in.read()); } - static void writeNewPacketLength(OutputStream out, long bodyLen) - throws IOException - { - if (bodyLen < 192) - { - out.write((byte)bodyLen); - } - else if (bodyLen <= 8383) - { - bodyLen -= 192; - - out.write((byte)(((bodyLen >> 8) & 0xff) + 192)); - out.write((byte)bodyLen); - } - else - { - out.write(0xff); - writeBodyLen(out, bodyLen); - } - } - - static void writeBodyLen(OutputStream out, long bodyLen) - throws IOException - { - out.write((byte)(bodyLen >> 24)); - out.write((byte)(bodyLen >> 16)); - out.write((byte)(bodyLen >> 8)); - out.write((byte)bodyLen); - } - - static void writeKeyID(BCPGOutputStream pOut, long keyID) - throws IOException - { - pOut.write((byte)(keyID >> 56)); - pOut.write((byte)(keyID >> 48)); - pOut.write((byte)(keyID >> 40)); - pOut.write((byte)(keyID >> 32)); - pOut.write((byte)(keyID >> 24)); - pOut.write((byte)(keyID >> 16)); - pOut.write((byte)(keyID >> 8)); - pOut.write((byte)(keyID)); - } - - static long readKeyID(BCPGInputStream in) - throws IOException - { - long keyID = (long)in.read() << 56; - keyID |= (long)in.read() << 48; - keyID |= (long)in.read() << 40; - keyID |= (long)in.read() << 32; - keyID |= (long)in.read() << 24; - keyID |= (long)in.read() << 16; - keyID |= (long)in.read() << 8; - return keyID | in.read(); - } - - static void writeTime(BCPGOutputStream pOut, long time) - throws IOException - { - pOut.write((byte)(time >> 24)); - pOut.write((byte)(time >> 16)); - pOut.write((byte)(time >> 8)); - pOut.write((byte)time); - } } diff --git a/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPPublicKeyRing.java b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPPublicKeyRing.java index 925c05a17f..c4291d83cc 100644 --- a/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPPublicKeyRing.java +++ b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPPublicKeyRing.java @@ -23,7 +23,6 @@ import org.bouncycastle.bcpg.TrustPacket; import org.bouncycastle.bcpg.UserDataPacket; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; -import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Iterable; import org.bouncycastle.util.Longs; @@ -184,7 +183,7 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) { PGPPublicKey k = (PGPPublicKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getFingerprint())) + if (k.hasFingerprint(fingerprint)) { return k; } @@ -468,7 +467,7 @@ public static PGPPublicKeyRing join( boolean allowSubkeySigsOnNonSubkey) throws PGPException { - if (!Arrays.areEqual(first.getPublicKey().getFingerprint(), second.getPublicKey().getFingerprint())) + if (!second.getPublicKey().hasFingerprint(first.getPublicKey().getFingerprint())) { throw new IllegalArgumentException("Cannot merge certificates with differing primary keys."); } diff --git a/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPSecretKeyRing.java b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPSecretKeyRing.java index 163c36f01a..da15cb3f1a 100644 --- a/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPSecretKeyRing.java +++ b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/PGPSecretKeyRing.java @@ -24,7 +24,6 @@ import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; -import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Iterable; /** @@ -246,7 +245,7 @@ public PGPPublicKey getPublicKey(byte[] fingerprint) { PGPPublicKey k = (PGPPublicKey)extraPubKeys.get(i); - if (Arrays.areEqual(fingerprint, k.getFingerprint())) + if (k.hasFingerprint(fingerprint)) { return k; } @@ -356,7 +355,7 @@ public PGPSecretKey getSecretKey(byte[] fingerprint) { PGPSecretKey k = (PGPSecretKey)keys.get(i); - if (Arrays.areEqual(fingerprint, k.getPublicKey().getFingerprint())) + if (k.getPublicKey().hasFingerprint(fingerprint)) { return k; } diff --git a/pg/src/main/jdk1.3/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorBuilder.java b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorBuilder.java new file mode 100644 index 0000000000..bb11c87979 --- /dev/null +++ b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/operator/bc/BcAEADSecretKeyEncryptorBuilder.java @@ -0,0 +1,103 @@ +package org.bouncycastle.openpgp.operator.bc; + +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.bcpg.AEADUtils; +import org.bouncycastle.bcpg.PacketTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyUtils; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.generators.HKDFBytesGenerator; +import org.bouncycastle.crypto.modes.AEADBlockCipher; +import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.HKDFParameters; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.util.Arrays; + +public class BcAEADSecretKeyEncryptorBuilder +{ + + private int aeadAlgorithm; + private int symmetricAlgorithm; + private S2K.Argon2Params argon2Params; + + public BcAEADSecretKeyEncryptorBuilder(int aeadAlgorithm, int symmetricAlgorithm, S2K.Argon2Params argon2Params) + { + this.aeadAlgorithm = aeadAlgorithm; + this.symmetricAlgorithm = symmetricAlgorithm; + this.argon2Params = argon2Params; + } + + public PBESecretKeyEncryptor build(char[] passphrase, final PublicKeyPacket pubKey) + { + return new PBESecretKeyEncryptor(symmetricAlgorithm, aeadAlgorithm, argon2Params, new SecureRandom(), passphrase) + { + private byte[] iv; + + { + iv = new byte[AEADUtils.getIVLength(this.aeadAlgorithm)]; + random.nextBytes(iv); + } + + @Override + public byte[] encryptKeyData(byte[] key, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + int packetTag = pubKey.getPacketTag() == PacketTags.PUBLIC_KEY ? PacketTags.SECRET_KEY : PacketTags.SECRET_SUBKEY; + byte[] hkdfInfo = new byte[] { + (byte) (0xC0 | packetTag), + (byte) pubKey.getVersion(), + (byte) symmetricAlgorithm, + (byte) this.aeadAlgorithm + }; + + HKDFParameters hkdfParameters = new HKDFParameters( + getKey(), + null, + hkdfInfo); + + HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); + hkdfGen.init(hkdfParameters); + key = new byte[SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)]; + hkdfGen.generateBytes(key, 0, key.length); + + try + { + byte[] aad = Arrays.prepend(pubKey.getEncodedContents(), (byte) (0xC0 | packetTag)); + AEADBlockCipher cipher = BcAEADUtil.createAEADCipher(encAlgorithm, this.aeadAlgorithm); + cipher.init(true, new AEADParameters( + new KeyParameter(key), + 128, + getCipherIV(), + aad + )); + int dataLen = cipher.getOutputSize(keyData.length); + byte[] encKey = new byte[dataLen]; + dataLen = cipher.processBytes(keyData, 0, keyData.length, encKey, 0); + + cipher.doFinal(encKey, dataLen); + return encKey; + } + catch (IOException e) + { + throw new PGPException("Exception AEAD protecting private key material", e); + } + catch (InvalidCipherTextException e) + { + throw new PGPException("Exception AEAD protecting private key material", e); + } + } + + @Override + public byte[] getCipherIV() + { + return iv; + } + }; + } +} diff --git a/pg/src/main/jdk1.3/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorBuilder.java b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorBuilder.java new file mode 100644 index 0000000000..a7e2a22f3a --- /dev/null +++ b/pg/src/main/jdk1.3/org/bouncycastle/openpgp/operator/jcajce/JcaAEADSecretKeyEncryptorBuilder.java @@ -0,0 +1,114 @@ +package org.bouncycastle.openpgp.operator.jcajce; + +import java.security.Provider; +import java.security.SecureRandom; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.bcpg.AEADUtils; +import org.bouncycastle.bcpg.PacketTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SymmetricKeyUtils; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.generators.HKDFBytesGenerator; +import org.bouncycastle.crypto.params.HKDFParameters; +import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; +import org.bouncycastle.jcajce.util.NamedJcaJceHelper; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.util.Arrays; + +public class JcaAEADSecretKeyEncryptorBuilder +{ + private int aeadAlgorithm; + private int symmetricAlgorithm; + private S2K.Argon2Params argon2Params; + + private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); + private JceAEADUtil aeadUtil = new JceAEADUtil(helper); + + public JcaAEADSecretKeyEncryptorBuilder(int aeadAlgorithm, int symmetricAlgorithm, S2K.Argon2Params argon2Params) + { + this.aeadAlgorithm = aeadAlgorithm; + this.symmetricAlgorithm = symmetricAlgorithm; + this.argon2Params = argon2Params; + } + + public JcaAEADSecretKeyEncryptorBuilder setProvider(Provider provider) + { + this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); + this.aeadUtil = new JceAEADUtil(helper); + + return this; + } + + public JcaAEADSecretKeyEncryptorBuilder setProvider(String providerName) + { + this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); + this.aeadUtil = new JceAEADUtil(helper); + + return this; + } + + public PBESecretKeyEncryptor build(char[] passphrase, final PublicKeyPacket pubKey) + { + return new PBESecretKeyEncryptor(symmetricAlgorithm, aeadAlgorithm, argon2Params, new SecureRandom(), passphrase) + { + private byte[] iv; + + { + iv = new byte[AEADUtils.getIVLength(this.aeadAlgorithm)]; + random.nextBytes(iv); + } + + @Override + public byte[] encryptKeyData(byte[] key, byte[] keyData, int keyOff, int keyLen) + throws PGPException + { + int packetTag = pubKey.getPacketTag() == PacketTags.PUBLIC_KEY ? PacketTags.SECRET_KEY : PacketTags.SECRET_SUBKEY; + byte[] hkdfInfo = new byte[] { + (byte) (0xC0 | packetTag), + (byte) pubKey.getVersion(), + (byte) symmetricAlgorithm, + (byte) this.aeadAlgorithm + }; + + HKDFParameters hkdfParameters = new HKDFParameters( + getKey(), + null, + hkdfInfo); + + HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA256Digest()); + hkdfGen.init(hkdfParameters); + key = new byte[SymmetricKeyUtils.getKeyLengthInOctets(encAlgorithm)]; + hkdfGen.generateBytes(key, 0, key.length); + + try + { + byte[] aad = Arrays.prepend(pubKey.getEncodedContents(), (byte) (0xC0 | packetTag)); + SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm)); + final Cipher c = aeadUtil.createAEADCipher(encAlgorithm, this.aeadAlgorithm); + + JceAEADCipherUtil.setUpAeadCipher(c, secretKey, Cipher.ENCRYPT_MODE, iv, 128, aad); + byte[] data = c.doFinal(keyData, keyOff, keyLen); + return data; + } + catch (Exception e) + { + throw new PGPException("Exception AEAD protecting private key material", e); + } + } + + @Override + public byte[] getCipherIV() + { + return iv; + } + }; + } +} diff --git a/pg/src/main/jdk1.4/org/bouncycastle/bcpg/PacketFormat.java b/pg/src/main/jdk1.4/org/bouncycastle/bcpg/PacketFormat.java new file mode 100644 index 0000000000..6458baa5a4 --- /dev/null +++ b/pg/src/main/jdk1.4/org/bouncycastle/bcpg/PacketFormat.java @@ -0,0 +1,33 @@ +package org.bouncycastle.bcpg; + +/** + * OpenPGP Packet Header Length Format. + * + * @see + * OpenPGP Packet Headers + */ +public class PacketFormat +{ + /** + * Always use the old (legacy) packet format. + */ + public static final PacketFormat LEGACY = new PacketFormat(0); + + /** + * Always use the current (new) packet format. + */ + public static final PacketFormat CURRENT = new PacketFormat(1); + + /** + * Let the individual packet decide the format (see {@link Packet#hasNewPacketFormat()}). + * This allows to round-trip packets without changing the packet format. + */ + public static final PacketFormat ROUNDTRIP = new PacketFormat(2); + + private final int ord; + + private PacketFormat(int ord) + { + this.ord = ord; + } +} diff --git a/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java b/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java index 163fadd9b0..4e58e334b7 100644 --- a/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java +++ b/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java @@ -5,36 +5,27 @@ import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; - import org.bouncycastle.jce.interfaces.ECPrivateKey; -import org.bouncycastle.jce.interfaces.ECPublicKey; - import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; - -import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; -import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; - -import java.security.spec.InvalidParameterSpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Date; +import java.util.Enumeration; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; @@ -42,6 +33,7 @@ import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.DHPublicKeySpec; +import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DEROctetString; @@ -52,9 +44,11 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ECParametersHolder; import org.bouncycastle.asn1.x9.X9ECPoint; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.bcpg.BCPGKey; import org.bouncycastle.bcpg.DSAPublicBCPGKey; import org.bouncycastle.bcpg.DSASecretBCPGKey; @@ -78,13 +72,16 @@ import org.bouncycastle.bcpg.X25519SecretBCPGKey; import org.bouncycastle.bcpg.X448PublicBCPGKey; import org.bouncycastle.bcpg.X448SecretBCPGKey; +import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; - import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; import org.bouncycastle.math.ec.rfc8032.Ed25519; +import org.bouncycastle.math.ec.rfc8032.Ed448; import org.bouncycastle.openpgp.PGPAlgorithmParameters; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKdfParameters; @@ -132,7 +129,7 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -143,17 +140,39 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PGPAlgorithmParameters, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) throws PGPException + { + return getPGPPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, time); + } + + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param algorithmParameters additional parameters to be stored against the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + throws PGPException { BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey); - return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), fingerPrintCalculator); + return new PGPPublicKey(new PublicKeyPacket(version, algorithm, time, bcpgKey), fingerPrintCalculator); } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -163,13 +182,34 @@ public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algori * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PublicKey pubKey, Date time) throws PGPException { return getPGPPublicKey(algorithm, null, pubKey, time); } + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(version, algorithm, null, pubKey, time); + } + public PrivateKey getPrivateKey(PGPPrivateKey privKey) throws PGPException { @@ -178,7 +218,7 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) return ((JcaPGPPrivateKey)privKey).getPrivateKey(); } - PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); + final PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); final BCPGKey privPk = privKey.getPrivateKeyDataPacket(); try @@ -199,91 +239,124 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) ECDHPublicBCPGKey ecdhPub = (ECDHPublicBCPGKey)pubPk.getKey(); ECSecretBCPGKey ecdhK = (ECSecretBCPGKey)privPk; - if (CryptlibObjectIdentifiers.curvey25519.equals(ecdhPub.getCurveOID())) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhPub.getCurveOID())) { // 'reverse' because the native format for X25519 private keys is little-endian return implGeneratePrivate("XDH", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { - return JcaPGPKeyConverter.this.getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, - Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } + }); + } + // Legacy X448 (1.3.101.111) + else if (EdECObjectIdentifiers.id_X448.equals(ecdhPub.getCurveOID())) + { + // 'reverse' because the native format for X448 private keys is little-endian (?) + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } }); } + // Brainpool, NIST etc. else { return implGetPrivateKeyEC("ECDH", ecdhPub, ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return implGeneratePrivate("XDH", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { - return JcaPGPKeyConverter.this.getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, - X25519SecretBCPGKey.LENGTH, Arrays.reverseInPlace(privPk.getEncoded())); + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, + X25519SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return implGeneratePrivate("XDH", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { - return JcaPGPKeyConverter.this.getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, - X448SecretBCPGKey.LENGTH, Arrays.reverseInPlace(privPk.getEncoded())); + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + X448SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } case PublicKeyAlgorithmTags.ECDSA: { - return implGetPrivateKeyEC("ECDSA", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); + return implGetPrivateKeyEC("EC", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { + EdDSAPublicBCPGKey eddsaPub = (EdDSAPublicBCPGKey) pubPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaPub.getCurveOID())) + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + BigIntegers.asUnsignedByteArray(Ed448.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 return implGeneratePrivate("EdDSA", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { - return JcaPGPKeyConverter.this.getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, - BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); } }); } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return implGeneratePrivate("EdDSA", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { - return JcaPGPKeyConverter.this.getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, - Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, + Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return implGeneratePrivate("EdDSA", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { - return JcaPGPKeyConverter.this.getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, - Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } @@ -342,47 +415,63 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) { ECDHPublicBCPGKey ecdhK = (ECDHPublicBCPGKey)publicPk.getKey(); - if (ecdhK.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhK.getCurveOID())) { return get25519PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X25519, "XDH", "Curve"); } + // Legacy X448 (1.3.101.111) + else if (ecdhK.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + return get448PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X448, "XDH", "Curve"); + } + // Brainpool, NIST etc. else { return implGetPublicKeyEC("ECDH", ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X25519, "XDH"); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X448, "XDH"); } case PublicKeyAlgorithmTags.ECDSA: - return implGetPublicKeyEC("ECDSA", (ECDSAPublicBCPGKey)publicPk.getKey()); - - case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return get25519PublicKey(((EdDSAPublicBCPGKey)publicPk.getKey()).getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); + return implGetPublicKeyEC("EC", (ECDSAPublicBCPGKey) publicPk.getKey()); } - case PublicKeyAlgorithmTags.Ed25519: + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - BCPGKey key = publicPk.getKey(); - if (key instanceof Ed25519PublicBCPGKey) + EdDSAPublicBCPGKey eddsaKey = (EdDSAPublicBCPGKey) publicPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaKey.getCurveOID())) { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(new BigInteger(1, publicPk.getKey().getEncoded())), - 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + return get448PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed448, "EdDSA", "Ed"); } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 else { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(((EdDSAPublicBCPGKey)publicPk.getKey()).getEncodedPoint()), - 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + return get25519PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); } } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(new BigInteger(1, publicPk.getKey().getEncoded())), + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_Ed448, "EdDSA"); } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: @@ -417,19 +506,13 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) } private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid) - throws NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException - { - return getECParameterSpec(curveOid, JcaJcePGPUtil.getX9Parameters(curveOid)); - } - - private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid, X9ECParameters x9Params) - throws InvalidParameterSpecException, NoSuchProviderException, NoSuchAlgorithmException + throws IOException, GeneralSecurityException { AlgorithmParameters params = helper.createAlgorithmParameters("EC"); - params.init(new ECNamedCurveGenParameterSpec(ECNamedCurveTable.getName(curveOid))); + params.init(new X962Parameters(curveOid).getEncoded()); - return (ECParameterSpec)params.getParameterSpec(ECParameterSpec.class); + return (org.bouncycastle.jce.spec.ECParameterSpec)params.getParameterSpec(ECParameterSpec.class); } private BCPGKey getPrivateBCPGKey(PrivateKey privKey, BCPGKeyOperation operation) @@ -439,7 +522,6 @@ private BCPGKey getPrivateBCPGKey(PrivateKey privKey, BCPGKeyOperation operation try { - // 'reverse' because the native format for X25519 private keys is little-endian return operation.getBCPGKey(ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets()); } catch (IOException e) @@ -468,38 +550,35 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) } else { - // 'reverse' because the native format for X25519 private keys is little-endian + // 'reverse' because the native format for X25519,X448 private keys is little-endian return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(pInfoEncoded))); + return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(key))); } }); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { - // 'reverse' because the native format for X25519 private keys is little-endian return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new X25519SecretBCPGKey(Arrays.reverse(pInfoEncoded)); + return new X25519SecretBCPGKey(key); } }); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { - // 'reverse' because the native format for X448 private keys is little-endian return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new X448SecretBCPGKey(Arrays.reverse(pInfoEncoded)); + return new X448SecretBCPGKey(key); } }); } @@ -507,36 +586,36 @@ public BCPGKey getBCPGKey(byte[] pInfoEncoded) { return new ECSecretBCPGKey(((ECPrivateKey)privKey).getD()); } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new EdSecretBCPGKey(new BigInteger(1, pInfoEncoded)); + return new EdSecretBCPGKey(new BigInteger(1, key)); } }); } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new Ed25519SecretBCPGKey(pInfoEncoded); + return new Ed25519SecretBCPGKey(key); } }); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new Ed448SecretBCPGKey(pInfoEncoded); + return new Ed448SecretBCPGKey(key); } }); } @@ -554,150 +633,266 @@ public BCPGKey getBCPGKey(byte[] pInfoEncoded) return new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ()); } default: - throw new PGPException("unknown key class"); + throw new PGPException("unknown public key algorithm encountered: " + pub.getAlgorithm()); } } private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey) throws PGPException { - if (pubKey instanceof RSAPublicKey) - { - RSAPublicKey rK = (RSAPublicKey)pubKey; - return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); - } - else if (pubKey instanceof DSAPublicKey) - { - DSAPublicKey dK = (DSAPublicKey)pubKey; - DSAParams dP = dK.getParams(); - return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); - } - else if (pubKey instanceof DHPublicKey) - { - DHPublicKey eK = (DHPublicKey)pubKey; - DHParameterSpec eS = eK.getParams(); - return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); - } - else if (pubKey instanceof ECPublicKey) + switch (algorithm) { - SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPublicKey rK = (RSAPublicKey) pubKey; + return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + DHPublicKey egK = (DHPublicKey) pubKey; + return new ElGamalPublicBCPGKey(egK.getParams().getP(), egK.getParams().getG(), egK.getY()); + } + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicKey dK = (DSAPublicKey) pubKey; + DSAParams dP = dK.getParams(); + return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); + } - // TODO: should probably match curve by comparison as well - ASN1ObjectIdentifier curveOid = ASN1ObjectIdentifier.getInstance(keyInfo.getAlgorithm().getParameters()); + case PublicKeyAlgorithmTags.DIFFIE_HELLMAN: + { + DHPublicKey eK = (DHPublicKey) pubKey; + DHParameterSpec eS = eK.getParams(); + return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); + } - X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + case PublicKeyAlgorithmTags.ECDH: + case PublicKeyAlgorithmTags.ECDSA: + { + SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); - ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); - X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); + // TODO: should probably match curve by comparison as well + ASN1Encodable enc = keyInfo.getAlgorithm().getAlgorithm(); + ASN1ObjectIdentifier curveOid; + curveOid = ASN1ObjectIdentifier.getInstance(enc); - if (algorithm == PGPPublicKey.ECDH) - { - PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); + // BCECPublicKey uses explicit parameter encoding, so we need to find the named curve manually + if (X9ObjectIdentifiers.id_ecPublicKey.equals(curveOid)) + { + enc = getNamedCurveOID(X962Parameters.getInstance(keyInfo.getAlgorithm().getParameters())); + ASN1ObjectIdentifier nCurveOid = ASN1ObjectIdentifier.getInstance(enc); + if (nCurveOid != null) + { + curveOid = nCurveOid; + } + } + + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + if (pubKey.getAlgorithm().regionMatches(true, 0, "X4", 0, 2)) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // sun.security.ec.XDHPublicKeyImpl returns "XDH" for getAlgorithm() + // In this case we need to determine the curve by looking at the length of the encoding :/ + else if (pubKey.getAlgorithm().regionMatches(true, 0, "XDH", 0, 3)) + { + // Legacy X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + if (X25519.SCALAR_SIZE + 12 == pubKey.getEncoded().length) // + 12 for some reason + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + else + { + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + } + + X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + + ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); + X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); + + if (algorithm == PGPPublicKey.ECDH) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); - return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), - kdfParams.getSymmetricWrapAlgorithm()); + return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), + kdfParams.getSymmetricWrapAlgorithm()); + } + else + { + return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + } } - else if (algorithm == PGPPublicKey.ECDSA) + + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) + { + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + // Legacy Ed448 (1.3.101.113) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED4", 0, 3)) + { + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + // Manual matching on curve encoding length + else + { + // sun.security.ec.ed.EdDSAPublicKeyImpl returns "EdDSA" for getAlgorithm() + // if algorithm is just EdDSA, we need to detect the curve based on encoding length :/ + if (pubKey.getEncoded().length == 12 + Ed25519.PUBLIC_KEY_SIZE) // +12 for some reason + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + else + { + // Legacy Ed448 (1.3.101.113) + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + } } - else + + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: { - throw new PGPException("unknown EC algorithm"); + return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519PublicBCPGKey(key); + } + }); } - } - else if (algorithm == PGPPublicKey.Ed25519) - { - return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: { - @Override - public BCPGKey getBCPGKey(byte[] key) + return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() { - return new Ed25519PublicBCPGKey(key); - } - }); - } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) - { - return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); - } - else if (algorithm == PGPPublicKey.X25519) - { - return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448PublicBCPGKey(key); + } + }); + } + + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: { - @Override - public BCPGKey getBCPGKey(byte[] key) + return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() { - return new X25519PublicBCPGKey(key); - } - }); - } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) - { - PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519PublicBCPGKey(key); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X448PublicBCPGKey(key); + } + }); + } - return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), - kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + default: + throw new PGPException("unknown public key algorithm encountered: " + algorithm); } - else if (algorithm == PGPPublicKey.Ed448) + } + + private ASN1Encodable getNamedCurveOID(X962Parameters ecParams) + { + ECCurve curve = null; + if (ecParams.isNamedCurve()) { - return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() - { - @Override - public BCPGKey getBCPGKey(byte[] key) - { - return new Ed448PublicBCPGKey(key); - } - }); + return ASN1ObjectIdentifier.getInstance(ecParams.getParameters()); } - else if (algorithm == PGPPublicKey.X448) + else if (ecParams.isImplicitlyCA()) { - return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() - { - @Override - public BCPGKey getBCPGKey(byte[] key) - { - return new X448PublicBCPGKey(key); - } - }); + curve = ((X9ECParameters)CryptoServicesRegistrar.getProperty(CryptoServicesRegistrar.Property.EC_IMPLICITLY_CA)).getCurve(); } else { - throw new PGPException("unknown key class"); + curve = X9ECParameters.getInstance(ecParams.getParameters()).getCurve(); + } + + // Iterate through all registered curves to find applicable OID + Enumeration names = ECNamedCurveTable.getNames(); + while (names.hasMoreElements()) + { + String name = (String)names.nextElement(); + X9ECParameters parms = ECNamedCurveTable.getByName(name); + if (curve.equals(parms.getCurve())) + { + return ECNamedCurveTable.getOID(name); + } } + return null; } @FunctionalInterface - private static interface BCPGKeyOperation + private interface BCPGKeyOperation { BCPGKey getBCPGKey(byte[] key); } - private static interface Operation - { - PrivateKeyInfo getPrivateKeyInfos() throws IOException; - } - - private BCPGKey getPublicBCPGKey(PublicKey pubKey, int keySize, BCPGKeyOperation operation) { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); byte[] pointEnc = new byte[keySize]; - - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 0, pointEnc.length); + // refer to getPointEncUncompressed + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); return operation.getBCPGKey(pointEnc); } private byte[] getPointEncUncompressed(PublicKey pubKey, int publicKeySize) { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); byte[] pointEnc = new byte[1 + publicKeySize]; pointEnc[0] = 0x40; - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 1, pointEnc.length - 1); + //offset with pointEnc.length - pubInfo.length to avoid leading zero issue + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); return pointEnc; } + @FunctionalInterface + private interface Operation + { + PrivateKeyInfo getPrivateKeyInfos() + throws IOException; + } private PrivateKey implGeneratePrivate(String keyAlgorithm, Operation operation) throws GeneralSecurityException, PGPException, IOException @@ -721,18 +916,19 @@ private PublicKey implGeneratePublic(String keyAlgorithm, KeySpec keySpec) return keyFactory.generatePublic(keySpec); } - private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) - throws GeneralSecurityException, PGPException + private PublicKey implGetPublicKeyX509(byte[] pEnc, int pEncOff, ASN1ObjectIdentifier algorithm, String keyAlgorithm) + throws IOException, PGPException, GeneralSecurityException { - ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(ecPub.getCurveOID())); - return implGeneratePrivate(keyAlgorithm, ecPrivSpec); + return implGeneratePublic(keyAlgorithm, new X509EncodedKeySpec(new SubjectPublicKeyInfo( + new AlgorithmIdentifier(algorithm), Arrays.copyOfRange(pEnc, pEncOff, pEnc.length)).getEncoded())); } - private PrivateKey implGetPrivateKeyPKCS8(String keyAlgorithm, PrivateKeyInfo privateKeyInfo) - throws GeneralSecurityException, IOException, PGPException + private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) + throws GeneralSecurityException, PGPException, IOException { - PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()); - return implGeneratePrivate(keyAlgorithm, pkcs8Spec); + ASN1ObjectIdentifier curveOid = ecPub.getCurveOID(); + ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid)); + return implGeneratePrivate(keyAlgorithm, ecPrivSpec); } private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) @@ -745,24 +941,10 @@ private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) x9Params.getCurve().createPoint( ecPubPoint.getAffineXCoord().toBigInteger(), ecPubPoint.getAffineYCoord().toBigInteger()), - getECParameterSpec(curveOID, x9Params)); + getECParameterSpec(curveOID)); return implGeneratePublic(keyAlgorithm, ecPubSpec); } - private PublicKey implGetPublicKeyX509(byte[] pEnc, int pEncOff, ASN1ObjectIdentifier algorithm, String keyAlgorithm) - throws IOException, PGPException, GeneralSecurityException - { - return implGeneratePublic(keyAlgorithm, new X509EncodedKeySpec(new SubjectPublicKeyInfo( - new AlgorithmIdentifier(algorithm), Arrays.copyOfRange(pEnc, pEncOff, pEnc.length)).getEncoded())); - } - - private PublicKey implGetPublicKeyX509(String keyAlgorithm, SubjectPublicKeyInfo subjectPublicKeyInfo) - throws GeneralSecurityException, IOException, PGPException - { - X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(subjectPublicKeyInfo.getEncoded()); - return implGeneratePublic(keyAlgorithm, x509Spec); - } - private PublicKey get25519PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) throws PGPException, GeneralSecurityException, IOException { @@ -775,4 +957,17 @@ private PublicKey get25519PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm } return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); } + + private PublicKey get448PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "448 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } } diff --git a/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java b/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java index d6b97f042e..48b24977d9 100644 --- a/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java +++ b/pg/src/main/jdk1.4/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java @@ -306,7 +306,7 @@ Cipher createKeyWrapper(int encAlgorithm) } } - private Signature createSignature(String cipherName) + Signature createSignature(String cipherName) throws PGPException { try diff --git a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/OpenPGPDefaultPolicy.java b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/OpenPGPDefaultPolicy.java new file mode 100644 index 0000000000..7cc3d037cb --- /dev/null +++ b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/OpenPGPDefaultPolicy.java @@ -0,0 +1,479 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; + +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.sig.NotationData; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; +import org.bouncycastle.openpgp.api.util.UTCUtil; + +public class OpenPGPDefaultPolicy + implements OpenPGPPolicy +{ + private final Map documentHashAlgorithmCutoffDates = new HashMap(); + private final Map certificateHashAlgorithmCutoffDates = new HashMap(); + private final Map symmetricKeyAlgorithmCutoffDates = new HashMap(); + private final Map publicKeyMinimalBitStrengths = new HashMap(); + private int defaultDocumentSignatureHashAlgorithm = HashAlgorithmTags.SHA512; + private int defaultCertificationSignatureHashAlgorithm = HashAlgorithmTags.SHA512; + private int defaultSymmetricKeyAlgorithm = SymmetricKeyAlgorithmTags.AES_128; + + public OpenPGPDefaultPolicy() + { + /* + * Certification Signature Hash Algorithms + */ + setDefaultCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + // SHA-3 + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA3_512); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA3_256); + // SHA-2 + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA384); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA256); + acceptCertificationSignatureHashAlgorithm(HashAlgorithmTags.SHA224); + // SHA-1 + acceptCertificationSignatureHashAlgorithmUntil(HashAlgorithmTags.SHA1, UTCUtil.parse("2023-02-01 00:00:00 UTC")); + + acceptCertificationSignatureHashAlgorithmUntil(HashAlgorithmTags.RIPEMD160, UTCUtil.parse("2023-02-01 00:00:00 UTC")); + acceptCertificationSignatureHashAlgorithmUntil(HashAlgorithmTags.MD5, UTCUtil.parse("1997-02-01 00:00:00 UTC")); + + /* + * Document Signature Hash Algorithms + */ + setDefaultDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + // SHA-3 + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA3_512); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA3_256); + // SHA-2 + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA512); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA384); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA256); + acceptDocumentSignatureHashAlgorithm(HashAlgorithmTags.SHA224); + + /* + * Symmetric Key Algorithms + */ + setDefaultSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_128); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_256); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_192); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.AES_128); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.TWOFISH); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.CAMELLIA_256); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.CAMELLIA_192); + acceptSymmetricKeyAlgorithm(SymmetricKeyAlgorithmTags.CAMELLIA_128); + + /* + * Public Key Algorithms and key strengths + */ + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.RSA_GENERAL, 2000); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.RSA_ENCRYPT, 2000); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.RSA_SIGN, 2000); + + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.ECDSA, 250); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.EDDSA_LEGACY, 250); + acceptPublicKeyAlgorithmWithMinimalStrength(PublicKeyAlgorithmTags.ECDH, 250); + + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.X25519); + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.X448); + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.Ed25519); + acceptPublicKeyAlgorithm(PublicKeyAlgorithmTags.Ed448); + } + + /** + * Return true, if the given {@link PGPPublicKey} is an acceptable signing key. + * Note: Although signing requires a secret key, we perform checks on the public part for consistency. + * + * @param key key + * @return true if acceptable signing key + */ + public boolean isAcceptableSigningKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is an acceptable signature verification key. + * Note: The asymmetry between this and {@link #isAcceptableSigningKey(PGPPublicKey)} is useful + * to prevent creation of signatures using a legacy key, while still allowing verification of + * signatures made using the same key. + * + * @param key key + * @return true if acceptable verification key + */ + public boolean isAcceptableVerificationKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable for encrypting messages. + * + * @param key key + * @return true if acceptable encryption key + */ + public boolean isAcceptableEncryptionKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable for decrypting messages. + * Note: Although decryption requires a secret key, we perform checks on the public part for consistency. + * The asymmetry between this and {@link #isAcceptableEncryptionKey(PGPPublicKey)} is useful + * to prevent creation of new encrypted messages using a legacy key, while still allowing decryption + * of existing messages using the same key. + * + * @param key key + * @return true if acceptable decryption key + */ + public boolean isAcceptableDecryptionKey(PGPPublicKey key) + { + return isAcceptablePublicKey(key); + } + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable. + * + * @param key key + * @return true if acceptable key + */ + public boolean isAcceptablePublicKey(PGPPublicKey key) + { + return isAcceptablePublicKeyStrength(key.getAlgorithm(), key.getBitStrength()); + } + + /** + * Return true, if the given {@link PGPSignature} is acceptable (uses acceptable hash algorithm, + * does not contain unknown critical notations or subpackets). + * Note: A signature being acceptable does NOT mean that it is correct or valid. + * + * @param signature signature + * @return true if acceptable + */ + public boolean isAcceptableSignature(PGPSignature signature) + { + return hasAcceptableSignatureHashAlgorithm(signature) && + hasNoCriticalUnknownNotations(signature) && + hasNoCriticalUnknownSubpackets(signature); + } + + /** + * Return true, if the given {@link PGPSignature} was made using an acceptable signature hash algorithm. + * + * @param signature signature + * @return true if hash algorithm is acceptable + */ + public boolean hasAcceptableSignatureHashAlgorithm(PGPSignature signature) + { + switch (signature.getSignatureType()) + { + case PGPSignature.DEFAULT_CERTIFICATION: + case PGPSignature.NO_CERTIFICATION: + case PGPSignature.CASUAL_CERTIFICATION: + case PGPSignature.POSITIVE_CERTIFICATION: + case PGPSignature.DIRECT_KEY: + case PGPSignature.SUBKEY_BINDING: + case PGPSignature.PRIMARYKEY_BINDING: + return hasAcceptableCertificationSignatureHashAlgorithm(signature); + + case PGPSignature.CERTIFICATION_REVOCATION: + case PGPSignature.KEY_REVOCATION: + case PGPSignature.SUBKEY_REVOCATION: + return hasAcceptableRevocationSignatureHashAlgorithm(signature); + + case PGPSignature.BINARY_DOCUMENT: + case PGPSignature.CANONICAL_TEXT_DOCUMENT: + default: + return hasAcceptableDocumentSignatureHashAlgorithm(signature); + } + } + + /** + * Return true, if the {@link PGPSignature} uses an acceptable data/document signature hash algorithm. + * + * @param signature data / document signature + * @return true if hash algorithm is acceptable + */ + public boolean hasAcceptableDocumentSignatureHashAlgorithm(PGPSignature signature) + { + return isAcceptableDocumentSignatureHashAlgorithm(signature.getHashAlgorithm(), signature.getCreationTime()); + } + + /** + * Return true, if the {@link PGPSignature} uses an acceptable revocation signature hash algorithm. + * + * @param signature revocation signature + * @return true if hash algorithm is acceptable + */ + public boolean hasAcceptableRevocationSignatureHashAlgorithm(PGPSignature signature) + { + return isAcceptableRevocationSignatureHashAlgorithm(signature.getHashAlgorithm(), signature.getCreationTime()); + } + + /** + * Return true, if the {@link PGPSignature} uses an acceptable certification signature hash algorithm. + * + * @param signature certification signature + * @return true if hash algorithm is acceptable + */ + public boolean hasAcceptableCertificationSignatureHashAlgorithm(PGPSignature signature) + { + return isAcceptableCertificationSignatureHashAlgorithm(signature.getHashAlgorithm(), signature.getCreationTime()); + } + + /** + * Return true, if the hashed subpacket area of the signature does NOT contain unknown critical notations. + * + * @param signature signature + * @return true if signature is free from unknown critical notations + */ + public boolean hasNoCriticalUnknownNotations(PGPSignature signature) + { + PGPSignatureSubpacketVector hashedSubpackets = signature.getHashedSubPackets(); + if (hashedSubpackets == null) + { + return true; + } + + OpenPGPNotationRegistry registry = getNotationRegistry(); + + NotationData[] notations = hashedSubpackets.getNotationDataOccurrences(); + for (NotationData notation : notations) + { + if (notation.isCritical() && !registry.isNotationKnown(notation.getNotationName())) + { + return false; + } + } + return true; + } + + /** + * Return true, if the hashed subpacket area of the signature does NOT contain unknown critical subpackets. + * + * @param signature signature + * @return true if signature is free from unknown critical subpackets + */ + public boolean hasNoCriticalUnknownSubpackets(PGPSignature signature) + { + PGPSignatureSubpacketVector hashedSubpackets = signature.getHashedSubPackets(); + if (hashedSubpackets == null) + { + return true; + } + + for (SignatureSubpacket subpacket : hashedSubpackets.toArray()) + { + if (subpacket.isCritical() && + // only consider subpackets which are not recognized by SignatureSubpacketInputStream + subpacket.getClass().equals(SignatureSubpacket.class)) + { + if (!isKnownSignatureSubpacket(subpacket.getType())) + { + return false; + } + } + } + return true; + } + + /** + * Return true, if the given signature subpacket ID is known by the implementation. + * Note: This method is only called for subpackets not recognized by + * {@link org.bouncycastle.bcpg.SignatureSubpacketInputStream}. + * + * @param signatureSubpacketTag signature subpacket ID + * @return true if subpacket tag is known + */ + public boolean isKnownSignatureSubpacket(int signatureSubpacketTag) + { + // Overwrite this, allowing custom critical signature subpackets + return false; + } + + public OpenPGPDefaultPolicy rejectHashAlgorithm(int hashAlgorithmId) + { + certificateHashAlgorithmCutoffDates.remove(hashAlgorithmId); + documentHashAlgorithmCutoffDates.remove(hashAlgorithmId); + return this; + } + + public OpenPGPDefaultPolicy acceptCertificationSignatureHashAlgorithm(int hashAlgorithmId) + { + return acceptCertificationSignatureHashAlgorithmUntil(hashAlgorithmId, null); + } + + public OpenPGPDefaultPolicy acceptCertificationSignatureHashAlgorithmUntil(int hashAlgorithmId, Date until) + { + certificateHashAlgorithmCutoffDates.put(hashAlgorithmId, until); + return this; + } + + public OpenPGPDefaultPolicy acceptDocumentSignatureHashAlgorithm(int hashAlgorithmId) + { + return acceptDocumentSignatureHashAlgorithmUntil(hashAlgorithmId, null); + } + + public OpenPGPDefaultPolicy acceptDocumentSignatureHashAlgorithmUntil(int hashAlgorithmId, Date until) + { + documentHashAlgorithmCutoffDates.put(hashAlgorithmId, until); + return this; + } + + public OpenPGPDefaultPolicy rejectSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + symmetricKeyAlgorithmCutoffDates.remove(symmetricKeyAlgorithmId); + return this; + } + + public OpenPGPDefaultPolicy acceptSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + return acceptSymmetricKeyAlgorithmUntil(symmetricKeyAlgorithmId, null); + } + + public OpenPGPDefaultPolicy acceptSymmetricKeyAlgorithmUntil(int symmetricKeyAlgorithmId, Date until) + { + symmetricKeyAlgorithmCutoffDates.put(symmetricKeyAlgorithmId, until); + return this; + } + + public OpenPGPDefaultPolicy rejectPublicKeyAlgorithm(int publicKeyAlgorithmId) + { + publicKeyMinimalBitStrengths.remove(publicKeyAlgorithmId); + return this; + } + + public OpenPGPDefaultPolicy acceptPublicKeyAlgorithm(int publicKeyAlgorithmId) + { + publicKeyMinimalBitStrengths.put(publicKeyAlgorithmId, null); + return this; + } + + public OpenPGPDefaultPolicy acceptPublicKeyAlgorithmWithMinimalStrength(int publicKeyAlgorithmId, int minBitStrength) + { + publicKeyMinimalBitStrengths.put(publicKeyAlgorithmId, minBitStrength); + return this; + } + + @Override + public boolean isAcceptableDocumentSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime) + { + return isAcceptable(hashAlgorithmId, signatureCreationTime, documentHashAlgorithmCutoffDates); + } + + @Override + public boolean isAcceptableRevocationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime) + { + return isAcceptable(hashAlgorithmId, signatureCreationTime, certificateHashAlgorithmCutoffDates); + } + + @Override + public boolean isAcceptableCertificationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime) + { + return isAcceptable(hashAlgorithmId, signatureCreationTime, certificateHashAlgorithmCutoffDates); + } + + @Override + public int getDefaultCertificationSignatureHashAlgorithm() + { + return defaultCertificationSignatureHashAlgorithm; + } + + public OpenPGPDefaultPolicy setDefaultCertificationSignatureHashAlgorithm(int hashAlgorithmId) + { + defaultCertificationSignatureHashAlgorithm = hashAlgorithmId; + return this; + } + + @Override + public int getDefaultDocumentSignatureHashAlgorithm() + { + return defaultDocumentSignatureHashAlgorithm; + } + + public OpenPGPDefaultPolicy setDefaultDocumentSignatureHashAlgorithm(int hashAlgorithmId) + { + defaultDocumentSignatureHashAlgorithm = hashAlgorithmId; + return this; + } + + @Override + public boolean isAcceptableSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + return isAcceptable(symmetricKeyAlgorithmId, symmetricKeyAlgorithmCutoffDates); + } + + @Override + public int getDefaultSymmetricKeyAlgorithm() + { + return defaultSymmetricKeyAlgorithm; + } + + public OpenPGPDefaultPolicy setDefaultSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId) + { + defaultSymmetricKeyAlgorithm = symmetricKeyAlgorithmId; + return this; + } + + @Override + public boolean isAcceptablePublicKeyStrength(int publicKeyAlgorithmId, int bitStrength) + { + return isAcceptable(publicKeyAlgorithmId, bitStrength, publicKeyMinimalBitStrengths); + } + + @Override + public OpenPGPNotationRegistry getNotationRegistry() + { + return null; + } + + private boolean isAcceptable(int algorithmId, Date usageDate, Map cutoffTable) + { + if (!cutoffTable.containsKey(algorithmId)) + { + // algorithm is not listed in the map at all + return false; + } + + Date cutoffDate = cutoffTable.get(algorithmId); + if (cutoffDate == null) + { + // no cutoff date given -> algorithm is acceptable indefinitely + return true; + } + + return usageDate.before(cutoffDate); + } + + private boolean isAcceptable(int algorithmId, Map cutoffTable) + { + return cutoffTable.containsKey(algorithmId); + } + + private boolean isAcceptable(int algorithmId, int bitStrength, Map minBitStrengths) + { + if (!minBitStrengths.containsKey(algorithmId)) + { + // algorithm is not listed in the map at all + return false; + } + + Integer minBitStrength = minBitStrengths.get(algorithmId); + if (minBitStrength == null) + { + // no minimal bit strength defined -> accept all strengths + return true; + } + + return bitStrength >= minBitStrength; + } +} diff --git a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/OpenPGPPolicy.java b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/OpenPGPPolicy.java new file mode 100644 index 0000000000..9a9d1d4c27 --- /dev/null +++ b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/OpenPGPPolicy.java @@ -0,0 +1,228 @@ +package org.bouncycastle.openpgp.api; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.sig.NotationData; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; + +/** + * Policy for OpenPGP algorithms and features. + */ +public interface OpenPGPPolicy +{ + /** + * Return true, if the given {@link PGPPublicKey} is an acceptable signing key. + * Note: Although signing requires a secret key, we perform checks on the public part for consistency. + * + * @param key key + * @return true if acceptable signing key + */ + boolean isAcceptableSigningKey(PGPPublicKey key); + + /** + * Return true, if the given {@link PGPPublicKey} is an acceptable signature verification key. + * Note: The asymmetry between this and {@link #isAcceptableSigningKey(PGPPublicKey)} is useful + * to prevent creation of signatures using a legacy key, while still allowing verification of + * signatures made using the same key. + * + * @param key key + * @return true if acceptable verification key + */ + boolean isAcceptableVerificationKey(PGPPublicKey key); + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable for encrypting messages. + * + * @param key key + * @return true if acceptable encryption key + */ + boolean isAcceptableEncryptionKey(PGPPublicKey key); + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable for decrypting messages. + * Note: Although decryption requires a secret key, we perform checks on the public part for consistency. + * The asymmetry between this and {@link #isAcceptableEncryptionKey(PGPPublicKey)} is useful + * to prevent creation of new encrypted messages using a legacy key, while still allowing decryption + * of existing messages using the same key. + * + * @param key key + * @return true if acceptable decryption key + */ + boolean isAcceptableDecryptionKey(PGPPublicKey key); + + /** + * Return true, if the given {@link PGPPublicKey} is acceptable. + * + * @param key key + * @return true if acceptable key + */ + boolean isAcceptablePublicKey(PGPPublicKey key); + + /** + * Return true, if the given {@link PGPSignature} is acceptable (uses acceptable hash algorithm, + * does not contain unknown critical notations or subpackets). + * Note: A signature being acceptable does NOT mean that it is correct or valid. + * + * @param signature signature + * @return true if acceptable + */ + boolean isAcceptableSignature(PGPSignature signature); + + /** + * Return true, if the given {@link PGPSignature} was made using an acceptable signature hash algorithm. + * + * @param signature signature + * @return true if hash algorithm is acceptable + */ + boolean hasAcceptableSignatureHashAlgorithm(PGPSignature signature); + + /** + * Return true, if the {@link PGPSignature} uses an acceptable data/document signature hash algorithm. + * + * @param signature data / document signature + * @return true if hash algorithm is acceptable + */ + boolean hasAcceptableDocumentSignatureHashAlgorithm(PGPSignature signature); + + /** + * Return true, if the {@link PGPSignature} uses an acceptable revocation signature hash algorithm. + * + * @param signature revocation signature + * @return true if hash algorithm is acceptable + */ + boolean hasAcceptableRevocationSignatureHashAlgorithm(PGPSignature signature); + + /** + * Return true, if the {@link PGPSignature} uses an acceptable certification signature hash algorithm. + * + * @param signature certification signature + * @return true if hash algorithm is acceptable + */ + boolean hasAcceptableCertificationSignatureHashAlgorithm(PGPSignature signature); + + /** + * Return true, if the hashed subpacket area of the signature does NOT contain unknown critical notations. + * @param signature signature + * @return true if signature is free from unknown critical notations + */ + boolean hasNoCriticalUnknownNotations(PGPSignature signature); + + /** + * Return true, if the hashed subpacket area of the signature does NOT contain unknown critical subpackets. + * @param signature signature + * @return true if signature is free from unknown critical subpackets + */ + boolean hasNoCriticalUnknownSubpackets(PGPSignature signature); + + /** + * Return true, if the given signature subpacket ID is known by the implementation. + * Note: This method is only called for subpackets not recognized by + * {@link org.bouncycastle.bcpg.SignatureSubpacketInputStream}. + * + * @param signatureSubpacketTag signature subpacket ID + * @return true if subpacket tag is known + */ + boolean isKnownSignatureSubpacket(int signatureSubpacketTag); + + /** + * Return true, if the given hash algorithm is - at signature creation time - an acceptable document signature + * hash algorithm. + * + * @param hashAlgorithmId hash algorithm ID + * @param signatureCreationTime optional signature creation time + * @return true if hash algorithm is acceptable at creation time + */ + boolean isAcceptableDocumentSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime); + + /** + * Return true, if the given hash algorithm is - at signature creation time - an acceptable revocation signature + * hash algorithm. + * + * @param hashAlgorithmId hash algorithm ID + * @param signatureCreationTime optional signature creation time + * @return true if hash algorithm is acceptable at creation time + */ + boolean isAcceptableRevocationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime); + + /** + * Return true, if the given hash algorithm is - at signature creation time - an acceptable certification signature + * hash algorithm. + * + * @param hashAlgorithmId hash algorithm ID + * @param signatureCreationTime optional signature creation time + * @return true if hash algorithm is acceptable at creation time + */ + boolean isAcceptableCertificationSignatureHashAlgorithm(int hashAlgorithmId, Date signatureCreationTime); + + /** + * Return the default certification signature hash algorithm ID. + * This is used as fallback, if negotiation of a commonly supported hash algorithm fails. + * + * @return default certification signature hash algorithm ID + */ + int getDefaultCertificationSignatureHashAlgorithm(); + + /** + * Return the default document signature hash algorithm ID. + * This is used as fallback, if negotiation of a commonly supported hash algorithm fails. + * + * @return default document signature hash algorithm ID + */ + int getDefaultDocumentSignatureHashAlgorithm(); + + /** + * Return true, if the given symmetric-key algorithm is acceptable. + * + * @param symmetricKeyAlgorithmId symmetric-key algorithm + * @return true if symmetric-key algorithm is acceptable + */ + boolean isAcceptableSymmetricKeyAlgorithm(int symmetricKeyAlgorithmId); + + /** + * Return the default symmetric-key algorithm, which is used as a fallback if symmetric encryption algorithm + * negotiation fails. + * + * @return default symmetric-key algorithm + */ + int getDefaultSymmetricKeyAlgorithm(); + + /** + * Return true, if the given bitStrength is acceptable for the given public key algorithm ID. + * + * @param publicKeyAlgorithmId ID of a public key algorithm + * @param bitStrength key bit strength + * @return true if strength is acceptable + */ + boolean isAcceptablePublicKeyStrength(int publicKeyAlgorithmId, int bitStrength); + + /** + * Return the policies {@link OpenPGPNotationRegistry} containing known notation names. + * + * @return notation registry + */ + OpenPGPNotationRegistry getNotationRegistry(); + + /** + * The {@link OpenPGPNotationRegistry} can be used to register known notations, such that signatures containing + * notation instances of the same name, which are marked as critical do not invalidate the signature. + */ + class OpenPGPNotationRegistry + { + private final Set knownNotations = new HashSet(); + + public boolean isNotationKnown(String notationName) + { + return knownNotations.contains(notationName); + } + + public void addKnownNotation(String notationName) + { + this.knownNotations.add(notationName); + } + } +} diff --git a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/SignatureParameters.java b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/SignatureParameters.java new file mode 100644 index 0000000000..0c28b40b88 --- /dev/null +++ b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/api/SignatureParameters.java @@ -0,0 +1,333 @@ +package org.bouncycastle.openpgp.api; + +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.util.Arrays; + +import java.util.Date; + +/** + * Parameters for signature generation. + * Some signature builders allow the user to pass in a {@link Callback}, which can be used to modify + * {@link SignatureParameters} instances prior to signature generation. + */ +public class SignatureParameters +{ + private int signatureType; + private Date signatureCreationTime = new Date(); + private int signatureHashAlgorithmId; + private SignatureSubpacketsFunction hashedSubpacketsFunction; + private SignatureSubpacketsFunction unhashedSubpacketsFunction; + + private final int[] allowedSignatureTypes; + + private SignatureParameters(int... allowedSignatureTypes) + { + this.allowedSignatureTypes = allowedSignatureTypes; + } + + /** + * Create default signature parameters object for a direct-key signature. + * When issued as a self-signature, direct-key signatures can be used to store algorithm preferences + * on the key, which apply to the entire certificate (including all subkeys). + * When issued as a third-party signature, direct-key signatures act as delegations, with which for example the + * web-of-trust can be built. + * + * @param policy algorithm policy + * @return parameters + * @see + * OpenPGP Web-of-Trust + */ + public static SignatureParameters directKeySignature(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.DIRECT_KEY) + .setSignatureType(PGPSignature.DIRECT_KEY) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create default signature parameters for a key revocation signature. + * When issued as a self-signature, key revocation signatures can be used to revoke an entire certificate. + * To revoke only individual subkeys, see {@link #subkeyRevocation(OpenPGPPolicy)} instead. + * When issued as a third-party signature, key revocation signatures are used to revoke earlier delegation + * signatures. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters keyRevocation(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.KEY_REVOCATION) + .setSignatureType(PGPSignature.KEY_REVOCATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a certification signature. + * The default signature type is {@link PGPSignature#POSITIVE_CERTIFICATION}, but can be changed to + * {@link PGPSignature#DEFAULT_CERTIFICATION}, {@link PGPSignature#NO_CERTIFICATION}, + * {@link PGPSignature#CASUAL_CERTIFICATION}. + * When issued as a self-signature, certifications can be used to bind user-ids to the certificate. + * When issued as third-party signatures, certificates act as a statement, expressing that the issuer + * is convinced that the user-id "belongs to" the certificate. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters certification(OpenPGPPolicy policy) + { + return new SignatureParameters( + PGPSignature.DEFAULT_CERTIFICATION, + PGPSignature.NO_CERTIFICATION, + PGPSignature.CASUAL_CERTIFICATION, + PGPSignature.POSITIVE_CERTIFICATION) + .setSignatureType(PGPSignature.POSITIVE_CERTIFICATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a subkey binding signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters subkeyBinding(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.SUBKEY_BINDING) + .setSignatureType(PGPSignature.SUBKEY_BINDING) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create default signature parameters for a subkey revocation signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters subkeyRevocation(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.SUBKEY_REVOCATION) + .setSignatureType(PGPSignature.SUBKEY_REVOCATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a primary-key binding (back-sig) signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters primaryKeyBinding(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.PRIMARYKEY_BINDING) + .setSignatureType(PGPSignature.PRIMARYKEY_BINDING) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a certification-revocation signature. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters certificationRevocation(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.CERTIFICATION_REVOCATION) + .setSignatureType(PGPSignature.CERTIFICATION_REVOCATION) + .setSignatureHashAlgorithm(policy.getDefaultCertificationSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Create a default signature parameters object for a data/document signature. + * The default signature type is {@link PGPSignature#BINARY_DOCUMENT}, but can be changed to + * {@link PGPSignature#CANONICAL_TEXT_DOCUMENT}. + * + * @param policy algorithm policy + * @return parameters + */ + public static SignatureParameters dataSignature(OpenPGPPolicy policy) + { + return new SignatureParameters(PGPSignature.BINARY_DOCUMENT, PGPSignature.CANONICAL_TEXT_DOCUMENT) + .setSignatureType(PGPSignature.BINARY_DOCUMENT) + .setSignatureHashAlgorithm(policy.getDefaultDocumentSignatureHashAlgorithm()) + .setSignatureCreationTime(new Date()); + } + + /** + * Change the signature type of the signature to-be-generated to the given type. + * Depending on which factory method was used to instantiate the signature parameters object, + * only certain signature types are allowed. Passing an illegal signature type causes an + * {@link IllegalArgumentException} to be thrown. + * + * @param signatureType signature type + * @return parameters + * @throws IllegalArgumentException if an illegal signature type is passed + */ + public SignatureParameters setSignatureType(int signatureType) + { + if (!Arrays.contains(allowedSignatureTypes, signatureType)) + { + throw new IllegalArgumentException("Illegal signature type provided."); + } + + this.signatureType = signatureType; + return this; + } + + /** + * Return the signature type for the signature to-be-generated. + * + * @return signature type + */ + public int getSignatureType() + { + return signatureType; + } + + /** + * Change the creation time of the signature to-be-generated. + * + * @param signatureCreationTime signature creation time + * @return parameters + */ + public SignatureParameters setSignatureCreationTime(Date signatureCreationTime) + { + if (signatureCreationTime == null) + { + throw new NullPointerException("Signature creation time cannot be null."); + } + this.signatureCreationTime = signatureCreationTime; + return this; + } + + /** + * Return the creation time of the signature to-be-generated. + * + * @return signature creation time + */ + public Date getSignatureCreationTime() + { + return signatureCreationTime; + } + + /** + * Change the hash algorithm for the signature to-be-generated. + * + * @param signatureHashAlgorithmId signature hash algorithm id + * @return parameters + */ + public SignatureParameters setSignatureHashAlgorithm(int signatureHashAlgorithmId) + { + this.signatureHashAlgorithmId = signatureHashAlgorithmId; + return this; + } + + /** + * Return the hash algorithm id of the signature to-be-generated. + * + * @return hash algorithm id + */ + public int getSignatureHashAlgorithmId() + { + return signatureHashAlgorithmId; + } + + /** + * Set a function, which is applied to the hashed subpackets area of the signature to-be-generated. + * + * @param subpacketsFunction function to apply to the hashed signature subpackets + * @return parameters + */ + public SignatureParameters setHashedSubpacketsFunction(SignatureSubpacketsFunction subpacketsFunction) + { + this.hashedSubpacketsFunction = subpacketsFunction; + return this; + } + + /** + * Apply the hashed subpackets function set via {@link #setHashedSubpacketsFunction(SignatureSubpacketsFunction)} + * to the given hashed subpackets. + * + * @param hashedSubpackets hashed signature subpackets + * @return modified hashed subpackets + */ + PGPSignatureSubpacketGenerator applyToHashedSubpackets(PGPSignatureSubpacketGenerator hashedSubpackets) + { + if (hashedSubpacketsFunction != null) + { + return hashedSubpacketsFunction.apply(hashedSubpackets); + } + return hashedSubpackets; + } + + /** + * Set a function, which is applied to the unhashed subpackets area of the signature to-be-generated. + * + * @param subpacketsFunction function to apply to the unhashed signature subpackets + * @return parameters + */ + public SignatureParameters setUnhashedSubpacketsFunction(SignatureSubpacketsFunction subpacketsFunction) + { + this.unhashedSubpacketsFunction = subpacketsFunction; + return this; + } + + /** + * Apply the unhashed subpackets function set via {@link #setUnhashedSubpacketsFunction(SignatureSubpacketsFunction)} + * to the given unhashed subpackets. + * + * @param unhashedSubpackets unhashed signature subpackets + * @return modified unhashed subpackets + */ + PGPSignatureSubpacketGenerator applyToUnhashedSubpackets(PGPSignatureSubpacketGenerator unhashedSubpackets) + { + if (unhashedSubpacketsFunction != null) + { + return unhashedSubpacketsFunction.apply(unhashedSubpackets); + } + return unhashedSubpackets; + } + + /** + * Callback, allowing the user to modify {@link SignatureParameters} before use. + */ + public interface Callback + { + /** + * Apply custom changes to {@link SignatureParameters}. + * + * @param parameters parameters instance + * @return modified parameters, or null + */ + SignatureParameters apply(SignatureParameters parameters); + + static class Util + { + /** + * Shortcut method returning a {@link Callback} which only applies the given + * {@link SignatureSubpacketsFunction} to the hashed signature subpacket area of a signature. + * + * @param function signature subpackets function to apply to the hashed area + * @return callback + */ + public static Callback modifyHashedSubpackets(final SignatureSubpacketsFunction function) + { + return new Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + return parameters.setHashedSubpacketsFunction(function); + } + }; + } + } + } +} diff --git a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java deleted file mode 100644 index 1339e551c7..0000000000 --- a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/bc/BcPublicKeyKeyEncryptionMethodGenerator.java +++ /dev/null @@ -1,205 +0,0 @@ -package org.bouncycastle.openpgp.operator.bc; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.SecureRandom; - -import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; -import org.bouncycastle.bcpg.ECDHPublicBCPGKey; -import org.bouncycastle.bcpg.HashAlgorithmTags; -import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; -import org.bouncycastle.bcpg.PublicKeyPacket; -import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; -import org.bouncycastle.crypto.AsymmetricBlockCipher; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.KeyGenerationParameters; -import org.bouncycastle.crypto.RawAgreement; -import org.bouncycastle.crypto.Wrapper; -import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; -import org.bouncycastle.crypto.agreement.X25519Agreement; -import org.bouncycastle.crypto.agreement.X448Agreement; -import org.bouncycastle.crypto.generators.ECKeyPairGenerator; -import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; -import org.bouncycastle.crypto.generators.X448KeyPairGenerator; -import org.bouncycastle.crypto.params.AsymmetricKeyParameter; -import org.bouncycastle.crypto.params.ECKeyGenerationParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; -import org.bouncycastle.crypto.params.X25519PublicKeyParameters; -import org.bouncycastle.crypto.params.X448KeyGenerationParameters; -import org.bouncycastle.crypto.params.X448PublicKeyParameters; -import org.bouncycastle.openpgp.PGPException; -import org.bouncycastle.openpgp.PGPPublicKey; -import org.bouncycastle.openpgp.operator.PGPPad; -import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; -import org.bouncycastle.openpgp.operator.RFC6637Utils; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.BigIntegers; - -/** - * A method generator for supporting public key based encryption operations. - */ -public class BcPublicKeyKeyEncryptionMethodGenerator - extends PublicKeyKeyEncryptionMethodGenerator -{ - private static final byte X_HDR = 0x40; - - private SecureRandom random; - private BcPGPKeyConverter keyConverter = new BcPGPKeyConverter(); - - /** - * Create a public key encryption method generator with the method to be based on the passed in key. - * - * @param key the public key to use for encryption. - */ - public BcPublicKeyKeyEncryptionMethodGenerator(PGPPublicKey key) - { - super(key); - } - - /** - * Provide a user defined source of randomness. - * - * @param random the secure random to be used. - * @return the current generator. - */ - public BcPublicKeyKeyEncryptionMethodGenerator setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo) - throws PGPException - { - try - { - AsymmetricKeyParameter cryptoPublicKey = keyConverter.getPublicKey(pubKey); - PublicKeyPacket pubKeyPacket = pubKey.getPublicKeyPacket(); - if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ECDH) - { - ECDHPublicBCPGKey ecPubKey = (ECDHPublicBCPGKey)pubKeyPacket.getKey(); - byte[] userKeyingMaterial = RFC6637Utils.createUserKeyingMaterial(pubKeyPacket, new BcKeyFingerprintCalculator()); - if (ecPubKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) - { - AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(new X25519KeyPairGenerator(), new X25519KeyGenerationParameters(random)); - - byte[] secret = BcUtil.getSecret(new X25519Agreement(), ephKp.getPrivate(), cryptoPublicKey); - - byte[] ephPubEncoding = new byte[1 + X25519PublicKeyParameters.KEY_SIZE]; - ephPubEncoding[0] = X_HDR; - ((X25519PublicKeyParameters)ephKp.getPublic()).encode(ephPubEncoding, 1); - return encryptSessionInfo(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); - } - else - { - AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(new ECKeyPairGenerator(), - new ECKeyGenerationParameters(((ECPublicKeyParameters)cryptoPublicKey).getParameters(), random)); - - ECDHBasicAgreement agreement = new ECDHBasicAgreement(); - agreement.init(ephKp.getPrivate()); - BigInteger S = agreement.calculateAgreement(cryptoPublicKey); - byte[] secret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), S); - - byte[] ephPubEncoding = ((ECPublicKeyParameters)ephKp.getPublic()).getQ().getEncoded(false); - - return encryptSessionInfo(sessionInfo, secret, userKeyingMaterial, ephPubEncoding, ecPubKey.getHashAlgorithm(), ecPubKey.getSymmetricKeyAlgorithm()); - } - } - else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X25519) - { - return encryptSessionInfo(pubKeyPacket, sessionInfo, HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128, "X25519", - new X25519KeyPairGenerator(), new X25519KeyGenerationParameters(random), new X25519Agreement(), cryptoPublicKey, X25519PublicKeyParameters.KEY_SIZE, - new ephPubEncodingOperation() - { - @Override - public void getEphPubEncoding(AsymmetricKeyParameter publicKey, byte[] ephPubEncoding) - { - ((X25519PublicKeyParameters)publicKey).encode(ephPubEncoding, 0); - } - }); - } - else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X448) - { - return encryptSessionInfo(pubKeyPacket, sessionInfo, HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256, "X448", - new X448KeyPairGenerator(), new X448KeyGenerationParameters(random), new X448Agreement(), cryptoPublicKey, X448PublicKeyParameters.KEY_SIZE, - new ephPubEncodingOperation() - { - @Override - public void getEphPubEncoding(AsymmetricKeyParameter publicKey, byte[] ephPubEncoding) - { - ((X448PublicKeyParameters)publicKey).encode(ephPubEncoding, 0); - } - }); - } - else - { - AsymmetricBlockCipher c = BcImplProvider.createPublicKeyCipher(pubKey.getAlgorithm()); - - c.init(true, new ParametersWithRandom(cryptoPublicKey, random)); - - return c.processBlock(sessionInfo, 0, sessionInfo.length); - } - } - catch (Exception e) - { - throw new PGPException("exception encrypting session info: " + e.getMessage(), e); - } - } - - @FunctionalInterface - private interface ephPubEncodingOperation - { - void getEphPubEncoding(AsymmetricKeyParameter publicKey, byte[] ephPubEncoding); - } - - private byte[] encryptSessionInfo(byte[] sessionInfo, byte[] secret, - byte[] userKeyingMaterial, byte[] ephPubEncoding, int hashAlgorithm, int symmetricKeyAlgorithm) - throws IOException, PGPException - { - RFC6637KDFCalculator rfc6637KDFCalculator = new RFC6637KDFCalculator( - new BcPGPDigestCalculatorProvider().get(hashAlgorithm), symmetricKeyAlgorithm); - KeyParameter key = new KeyParameter(rfc6637KDFCalculator.createKey(secret, userKeyingMaterial)); - - byte[] paddedSessionData = PGPPad.padSessionData(sessionInfo, sessionKeyObfuscation); - - return getSessionInfo(ephPubEncoding, getWrapper(symmetricKeyAlgorithm, key, paddedSessionData)); - } - - private byte[] encryptSessionInfo(PublicKeyPacket pubKeyPacket, byte[] sessionInfo, int hashAlgorithm, int symmetricKeyAlgorithm, String algorithmName, - AsymmetricCipherKeyPairGenerator gen, KeyGenerationParameters parameters, RawAgreement agreement, AsymmetricKeyParameter cryptoPublicKey, - int keySize, ephPubEncodingOperation ephPubEncodingOperation) - throws PGPException, IOException - { - AsymmetricCipherKeyPair ephKp = getAsymmetricCipherKeyPair(gen, parameters); - byte[] secret = BcUtil.getSecret(agreement, ephKp.getPrivate(), cryptoPublicKey); - byte[] ephPubEncoding = new byte[keySize]; - ephPubEncodingOperation.getEphPubEncoding(ephKp.getPublic(), ephPubEncoding); - KeyParameter key = new KeyParameter(RFC6637KDFCalculator.createKey(hashAlgorithm, symmetricKeyAlgorithm, - Arrays.concatenate(ephPubEncoding, pubKeyPacket.getKey().getEncoded(), secret), "OpenPGP " + algorithmName)); - //No checksum and padding - byte[] sessionData = new byte[sessionInfo.length - 3]; - System.arraycopy(sessionInfo, 1, sessionData, 0, sessionData.length); - - return getSessionInfo(ephPubEncoding, sessionInfo[0], getWrapper(symmetricKeyAlgorithm, key, sessionData)); - } - - private byte[] getWrapper(int symmetricKeyAlgorithm, KeyParameter key, byte[] sessionData) - throws PGPException - { - Wrapper c = BcImplProvider.createWrapper(symmetricKeyAlgorithm); - c.init(true, new ParametersWithRandom(key, random)); - return c.wrap(sessionData, 0, sessionData.length); - } - - private AsymmetricCipherKeyPair getAsymmetricCipherKeyPair(AsymmetricCipherKeyPairGenerator gen, KeyGenerationParameters parameters) - { - gen.init(parameters); - return gen.generateKeyPair(); - } -} \ No newline at end of file diff --git a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java index fbe0038278..90c277bc5c 100644 --- a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java +++ b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.java @@ -5,8 +5,6 @@ import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; @@ -14,22 +12,20 @@ import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; -import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPrivateKeySpec; import java.security.spec.ECPublicKeySpec; -import java.security.spec.InvalidParameterSpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Date; +import java.util.Enumeration; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; @@ -37,6 +33,7 @@ import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.DHPublicKeySpec; +import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DEROctetString; @@ -47,9 +44,11 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.ECNamedCurveTable; +import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ECParametersHolder; import org.bouncycastle.asn1.x9.X9ECPoint; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.bcpg.BCPGKey; import org.bouncycastle.bcpg.DSAPublicBCPGKey; import org.bouncycastle.bcpg.DSASecretBCPGKey; @@ -73,13 +72,16 @@ import org.bouncycastle.bcpg.X25519SecretBCPGKey; import org.bouncycastle.bcpg.X448PublicBCPGKey; import org.bouncycastle.bcpg.X448SecretBCPGKey; +import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; - import org.bouncycastle.math.ec.rfc7748.X25519; +import org.bouncycastle.math.ec.rfc7748.X448; import org.bouncycastle.math.ec.rfc8032.Ed25519; +import org.bouncycastle.math.ec.rfc8032.Ed448; import org.bouncycastle.openpgp.PGPAlgorithmParameters; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKdfParameters; @@ -127,7 +129,7 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -138,17 +140,39 @@ public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pub, PrivateKey privKey) * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PGPAlgorithmParameters, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) throws PGPException + { + return getPGPPublicKey(PublicKeyPacket.VERSION_4, algorithm, algorithmParameters, pubKey, time); + } + + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param algorithmParameters additional parameters to be stored against the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey, Date time) + throws PGPException { BCPGKey bcpgKey = getPublicBCPGKey(algorithm, algorithmParameters, pubKey); - return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), fingerPrintCalculator); + return new PGPPublicKey(new PublicKeyPacket(version, algorithm, time, bcpgKey), fingerPrintCalculator); } /** - * Create a PGPPublicKey from the passed in JCA one. + * Create a version 4 PGPPublicKey from the passed in JCA one. *

      * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. @@ -158,13 +182,34 @@ public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algori * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. + * @deprecated use versioned {@link #getPGPPublicKey(int, int, PublicKey, Date)} instead. */ + @Deprecated public PGPPublicKey getPGPPublicKey(int algorithm, PublicKey pubKey, Date time) throws PGPException { return getPGPPublicKey(algorithm, null, pubKey, time); } + /** + * Create a PGPPublicKey from the passed in JCA one. + *

      + * Note: the time passed in affects the value of the key's keyID, so you probably only want + * to do this once for a JCA key, or make sure you keep track of the time you used. + *

      + * + * @param version key version. + * @param algorithm asymmetric algorithm type representing the public key. + * @param pubKey actual public key to associate. + * @param time date of creation. + * @throws PGPException on key creation problem. + */ + public PGPPublicKey getPGPPublicKey(int version, int algorithm, PublicKey pubKey, Date time) + throws PGPException + { + return getPGPPublicKey(version, algorithm, null, pubKey, time); + } + public PrivateKey getPrivateKey(PGPPrivateKey privKey) throws PGPException { @@ -173,7 +218,7 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) return ((JcaPGPPrivateKey)privKey).getPrivateKey(); } - PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); + final PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); final BCPGKey privPk = privKey.getPrivateKeyDataPacket(); try @@ -194,91 +239,126 @@ public PrivateKey getPrivateKey(PGPPrivateKey privKey) ECDHPublicBCPGKey ecdhPub = (ECDHPublicBCPGKey)pubPk.getKey(); ECSecretBCPGKey ecdhK = (ECSecretBCPGKey)privPk; - if (CryptlibObjectIdentifiers.curvey25519.equals(ecdhPub.getCurveOID())) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhPub.getCurveOID())) { // 'reverse' because the native format for X25519 private keys is little-endian return implGeneratePrivate("XDH", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, - Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } + }); + } + // Legacy X448 (1.3.101.111) + else if (EdECObjectIdentifiers.id_X448.equals(ecdhPub.getCurveOID())) + { + // 'reverse' because the native format for X448 private keys is little-endian (?) + return implGeneratePrivate("XDH", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, + Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(((ECSecretBCPGKey)privPk).getX()))); + } }); } + // Brainpool, NIST etc. else { return implGetPrivateKeyEC("ECDH", ecdhPub, ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return implGeneratePrivate("XDH", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { return getPrivateKeyInfo(EdECObjectIdentifiers.id_X25519, - X25519SecretBCPGKey.LENGTH, Arrays.reverseInPlace(privPk.getEncoded())); + X25519SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return implGeneratePrivate("XDH", new Operation() { - @Override + @java.lang.Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { return getPrivateKeyInfo(EdECObjectIdentifiers.id_X448, - X448SecretBCPGKey.LENGTH, Arrays.reverseInPlace(privPk.getEncoded())); + X448SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } case PublicKeyAlgorithmTags.ECDSA: { - return implGetPrivateKeyEC("ECDSA", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); + return implGetPrivateKeyEC("EC", (ECDSAPublicBCPGKey)pubPk.getKey(), (ECSecretBCPGKey)privPk); } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { + EdDSAPublicBCPGKey eddsaPub = (EdDSAPublicBCPGKey) pubPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaPub.getCurveOID())) + { + return implGeneratePrivate("EdDSA", new Operation() + { + public PrivateKeyInfo getPrivateKeyInfos() + throws IOException + { + return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, + BigIntegers.asUnsignedByteArray(Ed448.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + } + }); + } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 return implGeneratePrivate("EdDSA", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, - BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); + BigIntegers.asUnsignedByteArray(Ed25519.SECRET_KEY_SIZE, ((EdSecretBCPGKey)privPk).getX())); } }); } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return implGeneratePrivate("EdDSA", new Operation() { - @Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed25519, - Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); + Ed25519SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return implGeneratePrivate("EdDSA", new Operation() { - @Override + @java.lang.Override public PrivateKeyInfo getPrivateKeyInfos() throws IOException { return getPrivateKeyInfo(EdECObjectIdentifiers.id_Ed448, - Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); + Ed448SecretBCPGKey.LENGTH, privPk.getEncoded()); } }); } @@ -337,47 +417,63 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) { ECDHPublicBCPGKey ecdhK = (ECDHPublicBCPGKey)publicPk.getKey(); - if (ecdhK.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (JcaJcePGPUtil.isX25519(ecdhK.getCurveOID())) { return get25519PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X25519, "XDH", "Curve"); } + // Legacy X448 (1.3.101.111) + else if (ecdhK.getCurveOID().equals(EdECObjectIdentifiers.id_X448)) + { + return get448PublicKey(ecdhK.getEncodedPoint(), EdECObjectIdentifiers.id_X448, "XDH", "Curve"); + } + // Brainpool, NIST etc. else { return implGetPublicKeyEC("ECDH", ecdhK); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X25519, "XDH"); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_X448, "XDH"); } case PublicKeyAlgorithmTags.ECDSA: - return implGetPublicKeyEC("ECDSA", (ECDSAPublicBCPGKey)publicPk.getKey()); - - case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return get25519PublicKey(((EdDSAPublicBCPGKey)publicPk.getKey()).getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); + return implGetPublicKeyEC("EC", (ECDSAPublicBCPGKey) publicPk.getKey()); } - case PublicKeyAlgorithmTags.Ed25519: + // Legacy EdDSA (legacy Ed448, legacy Ed25519) + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - BCPGKey key = publicPk.getKey(); - if (key instanceof Ed25519PublicBCPGKey) + EdDSAPublicBCPGKey eddsaKey = (EdDSAPublicBCPGKey) publicPk.getKey(); + // Legacy Ed448 (1.3.101.113) + if (EdECObjectIdentifiers.id_Ed448.equals(eddsaKey.getCurveOID())) { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(new BigInteger(1, publicPk.getKey().getEncoded())), - 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + return get448PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed448, "EdDSA", "Ed"); } + // Legacy Ed25519 + // 1.3.6.1.4.1.11591.15.1 & 1.3.101.112 else { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(((EdDSAPublicBCPGKey)publicPk.getKey()).getEncodedPoint()), - 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + return get25519PublicKey(eddsaKey.getEncodedPoint(), EdECObjectIdentifiers.id_Ed25519, "EdDSA", "Ed"); } } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: + { + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), + 0, EdECObjectIdentifiers.id_Ed25519, "EdDSA"); + } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { - return implGetPublicKeyX509(BigIntegers.asUnsignedByteArray(new BigInteger(1, publicPk.getKey().getEncoded())), + return implGetPublicKeyX509(publicPk.getKey().getEncoded(), 0, EdECObjectIdentifiers.id_Ed448, "EdDSA"); } case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: @@ -411,12 +507,12 @@ public PublicKey getPublicKey(PGPPublicKey publicKey) } } - private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid, X9ECParameters x9Params) - throws InvalidParameterSpecException, NoSuchProviderException, NoSuchAlgorithmException + private ECParameterSpec getECParameterSpec(ASN1ObjectIdentifier curveOid) + throws IOException, GeneralSecurityException { AlgorithmParameters params = helper.createAlgorithmParameters("EC"); - params.init(new ECGenParameterSpec(ECNamedCurveTable.getName(curveOid))); + params.init(new X962Parameters(curveOid).getEncoded()); return params.getParameterSpec(ECParameterSpec.class); } @@ -428,7 +524,6 @@ private BCPGKey getPrivateBCPGKey(PrivateKey privKey, BCPGKeyOperation operation try { - // 'reverse' because the native format for X25519 private keys is little-endian return operation.getBCPGKey(ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets()); } catch (IOException e) @@ -457,38 +552,35 @@ private BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) } else { - // 'reverse' because the native format for X25519 private keys is little-endian + // 'reverse' because the native format for X25519,X448 private keys is little-endian return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(pInfoEncoded))); + return new ECSecretBCPGKey(new BigInteger(1, Arrays.reverse(key))); } }); } } + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) case PublicKeyAlgorithmTags.X25519: { - // 'reverse' because the native format for X25519 private keys is little-endian return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new X25519SecretBCPGKey(Arrays.reverse(pInfoEncoded)); + return new X25519SecretBCPGKey(key); } }); } + // Modern X448 (1.3.101.111) case PublicKeyAlgorithmTags.X448: { - // 'reverse' because the native format for X448 private keys is little-endian return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new X448SecretBCPGKey(Arrays.reverse(pInfoEncoded)); + return new X448SecretBCPGKey(key); } }); } @@ -496,36 +588,36 @@ public BCPGKey getBCPGKey(byte[] pInfoEncoded) { return new ECSecretBCPGKey(((ECPrivateKey)privKey).getS()); } + // Legacy EdDSA (legacy Ed448, legacy Ed25519) case PublicKeyAlgorithmTags.EDDSA_LEGACY: { return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new EdSecretBCPGKey(new BigInteger(1, pInfoEncoded)); + return new EdSecretBCPGKey(new BigInteger(1, key)); } }); } + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) case PublicKeyAlgorithmTags.Ed25519: { return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new Ed25519SecretBCPGKey(pInfoEncoded); + return new Ed25519SecretBCPGKey(key); } }); } + // Modern Ed448 (1.3.101.113) case PublicKeyAlgorithmTags.Ed448: { return getPrivateBCPGKey(privKey, new BCPGKeyOperation() { - @Override - public BCPGKey getBCPGKey(byte[] pInfoEncoded) + public BCPGKey getBCPGKey(byte[] key) { - return new Ed448SecretBCPGKey(pInfoEncoded); + return new Ed448SecretBCPGKey(key); } }); } @@ -543,117 +635,232 @@ public BCPGKey getBCPGKey(byte[] pInfoEncoded) return new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ()); } default: - throw new PGPException("unknown key class"); + throw new PGPException("unknown public key algorithm encountered: " + pub.getAlgorithm()); } } private BCPGKey getPublicBCPGKey(int algorithm, PGPAlgorithmParameters algorithmParameters, PublicKey pubKey) throws PGPException { - if (pubKey instanceof RSAPublicKey) - { - RSAPublicKey rK = (RSAPublicKey)pubKey; - return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); - } - else if (pubKey instanceof DSAPublicKey) + switch (algorithm) { - DSAPublicKey dK = (DSAPublicKey)pubKey; - DSAParams dP = dK.getParams(); - return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); - } - else if (pubKey instanceof DHPublicKey) - { - DHPublicKey eK = (DHPublicKey)pubKey; - DHParameterSpec eS = eK.getParams(); - return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); - } - else if (pubKey instanceof ECPublicKey) - { - SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + case PublicKeyAlgorithmTags.RSA_GENERAL: + case PublicKeyAlgorithmTags.RSA_ENCRYPT: + case PublicKeyAlgorithmTags.RSA_SIGN: + { + RSAPublicKey rK = (RSAPublicKey) pubKey; + return new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()); + } + case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: + case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: + { + DHPublicKey egK = (DHPublicKey) pubKey; + return new ElGamalPublicBCPGKey(egK.getParams().getP(), egK.getParams().getG(), egK.getY()); + } + case PublicKeyAlgorithmTags.DSA: + { + DSAPublicKey dK = (DSAPublicKey) pubKey; + DSAParams dP = dK.getParams(); + return new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); + } + + case PublicKeyAlgorithmTags.DIFFIE_HELLMAN: + { + DHPublicKey eK = (DHPublicKey) pubKey; + DHParameterSpec eS = eK.getParams(); + return new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); + } - // TODO: should probably match curve by comparison as well - ASN1ObjectIdentifier curveOid = ASN1ObjectIdentifier.getInstance(keyInfo.getAlgorithm().getParameters()); + case PublicKeyAlgorithmTags.ECDH: + case PublicKeyAlgorithmTags.ECDSA: + { + SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); - X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + // TODO: should probably match curve by comparison as well + ASN1Encodable enc = keyInfo.getAlgorithm().getAlgorithm(); + ASN1ObjectIdentifier curveOid; + curveOid = ASN1ObjectIdentifier.getInstance(enc); - ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); - X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); + // BCECPublicKey uses explicit parameter encoding, so we need to find the named curve manually + if (X9ObjectIdentifiers.id_ecPublicKey.equals(curveOid)) + { + enc = getNamedCurveOID(X962Parameters.getInstance(keyInfo.getAlgorithm().getParameters())); + ASN1ObjectIdentifier nCurveOid = ASN1ObjectIdentifier.getInstance(enc); + if (nCurveOid != null) + { + curveOid = nCurveOid; + } + } - if (algorithm == PGPPublicKey.ECDH) - { - PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); + // Legacy XDH on Curve25519 (legacy X25519) + // 1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110 + if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + if (pubKey.getAlgorithm().regionMatches(true, 0, "X4", 0, 2)) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); - return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), - kdfParams.getSymmetricWrapAlgorithm()); + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // sun.security.ec.XDHPublicKeyImpl returns "XDH" for getAlgorithm() + // In this case we need to determine the curve by looking at the length of the encoding :/ + else if (pubKey.getAlgorithm().regionMatches(true, 0, "XDH", 0, 3)) + { + // Legacy X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + if (X25519.SCALAR_SIZE + 12 == pubKey.getEncoded().length) // + 12 for some reason + { + PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + + return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + // Legacy X448 (1.3.101.111) + else + { + PGPKdfParameters kdfParams = implGetKdfParameters(EdECObjectIdentifiers.id_X448, algorithmParameters); + + return new ECDHPublicBCPGKey(EdECObjectIdentifiers.id_X448, new BigInteger(1, getPointEncUncompressed(pubKey, X448.SCALAR_SIZE)), + kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + } + } + + X9ECParametersHolder params = ECNamedCurveTable.getByOIDLazy(curveOid); + + ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); + X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); + + if (algorithm == PGPPublicKey.ECDH) + { + + PGPKdfParameters kdfParams = implGetKdfParameters(curveOid, algorithmParameters); + + return new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), + kdfParams.getSymmetricWrapAlgorithm()); + } + else + { + return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + } } - else if (algorithm == PGPPublicKey.ECDSA) + + case PublicKeyAlgorithmTags.EDDSA_LEGACY: { - return new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) + { + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + // Legacy Ed448 (1.3.101.113) + if (pubKey.getAlgorithm().regionMatches(true, 0, "ED4", 0, 3)) + { + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + // Manual matching on curve encoding length + else + { + // sun.security.ec.ed.EdDSAPublicKeyImpl returns "EdDSA" for getAlgorithm() + // if algorithm is just EdDSA, we need to detect the curve based on encoding length :/ + if (pubKey.getEncoded().length == 12 + Ed25519.PUBLIC_KEY_SIZE) // +12 for some reason + { + // Legacy Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); + } + else + { + // Legacy Ed448 (1.3.101.113) + return new EdDSAPublicBCPGKey(EdECObjectIdentifiers.id_Ed448, new BigInteger(1, getPointEncUncompressed(pubKey, Ed448.PUBLIC_KEY_SIZE))); + } + } } - else + + // Modern Ed25519 (1.3.6.1.4.1.11591.15.1 & 1.3.101.112) + case PublicKeyAlgorithmTags.Ed25519: { - throw new PGPException("unknown EC algorithm"); + return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed25519PublicBCPGKey(key); + } + }); } - } - else if (algorithm == PGPPublicKey.Ed25519) - { - return getPublicBCPGKey(pubKey, Ed25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + + // Modern Ed448 (1.3.101.113) + case PublicKeyAlgorithmTags.Ed448: { - @Override - public BCPGKey getBCPGKey(byte[] key) + return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() { - return new Ed25519PublicBCPGKey(key); - } - }); - } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "ED2", 0, 3)) - { - return new EdDSAPublicBCPGKey(GNUObjectIdentifiers.Ed25519, new BigInteger(1, getPointEncUncompressed(pubKey, Ed25519.PUBLIC_KEY_SIZE))); - } - else if (algorithm == PGPPublicKey.X25519) - { - return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() + public BCPGKey getBCPGKey(byte[] key) + { + return new Ed448PublicBCPGKey(key); + } + }); + } + + // Modern X25519 (1.3.6.1.4.1.3029.1.5.1 & 1.3.101.110) + case PublicKeyAlgorithmTags.X25519: { - @Override - public BCPGKey getBCPGKey(byte[] key) + return getPublicBCPGKey(pubKey, X25519PublicBCPGKey.LENGTH, new BCPGKeyOperation() { - return new X25519PublicBCPGKey(key); - } - }); - } - else if (pubKey.getAlgorithm().regionMatches(true, 0, "X2", 0, 2)) - { - PGPKdfParameters kdfParams = implGetKdfParameters(CryptlibObjectIdentifiers.curvey25519, algorithmParameters); + public BCPGKey getBCPGKey(byte[] key) + { + return new X25519PublicBCPGKey(key); + } + }); + } + // Modern X448 (1.3.101.111) + case PublicKeyAlgorithmTags.X448: + { + return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() + { + public BCPGKey getBCPGKey(byte[] key) + { + return new X448PublicBCPGKey(key); + } + }); + } - return new ECDHPublicBCPGKey(CryptlibObjectIdentifiers.curvey25519, new BigInteger(1, getPointEncUncompressed(pubKey, X25519.SCALAR_SIZE)), - kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); + default: + throw new PGPException("unknown public key algorithm encountered: " + algorithm); } - else if (algorithm == PGPPublicKey.Ed448) + } + + private ASN1Encodable getNamedCurveOID(X962Parameters ecParams) + { + ECCurve curve = null; + if (ecParams.isNamedCurve()) { - return getPublicBCPGKey(pubKey, Ed448PublicBCPGKey.LENGTH, new BCPGKeyOperation() - { - @Override - public BCPGKey getBCPGKey(byte[] key) - { - return new Ed448PublicBCPGKey(key); - } - }); + return ASN1ObjectIdentifier.getInstance(ecParams.getParameters()); } - else if (algorithm == PGPPublicKey.X448) + else if (ecParams.isImplicitlyCA()) { - return getPublicBCPGKey(pubKey, X448PublicBCPGKey.LENGTH, new BCPGKeyOperation() - { - @Override - public BCPGKey getBCPGKey(byte[] key) - { - return new X448PublicBCPGKey(key); - } - }); + curve = ((X9ECParameters)CryptoServicesRegistrar.getProperty(CryptoServicesRegistrar.Property.EC_IMPLICITLY_CA)).getCurve(); } else { - throw new PGPException("unknown key class"); + curve = X9ECParameters.getInstance(ecParams.getParameters()).getCurve(); + } + + // Iterate through all registered curves to find applicable OID + Enumeration names = ECNamedCurveTable.getNames(); + while (names.hasMoreElements()) + { + String name = (String)names.nextElement(); + X9ECParameters parms = ECNamedCurveTable.getByName(name); + if (curve.equals(parms.getCurve())) + { + return ECNamedCurveTable.getOID(name); + } } + return null; } @FunctionalInterface @@ -664,20 +871,21 @@ private interface BCPGKeyOperation private BCPGKey getPublicBCPGKey(PublicKey pubKey, int keySize, BCPGKeyOperation operation) { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); byte[] pointEnc = new byte[keySize]; - - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 0, pointEnc.length); + // refer to getPointEncUncompressed + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); return operation.getBCPGKey(pointEnc); } private byte[] getPointEncUncompressed(PublicKey pubKey, int publicKeySize) { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); + byte[] pubInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).getPublicKeyData().getBytes(); byte[] pointEnc = new byte[1 + publicKeySize]; pointEnc[0] = 0x40; - System.arraycopy(pubInfo.getPublicKeyData().getBytes(), 0, pointEnc, 1, pointEnc.length - 1); + //offset with pointEnc.length - pubInfo.length to avoid leading zero issue + System.arraycopy(pubInfo, 0, pointEnc, pointEnc.length - pubInfo.length , pubInfo.length); return pointEnc; } @@ -718,10 +926,10 @@ private PublicKey implGetPublicKeyX509(byte[] pEnc, int pEncOff, ASN1ObjectIdent } private PrivateKey implGetPrivateKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub, ECSecretBCPGKey ecPriv) - throws GeneralSecurityException, PGPException + throws GeneralSecurityException, PGPException, IOException { ASN1ObjectIdentifier curveOid = ecPub.getCurveOID(); - ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid, JcaJcePGPUtil.getX9Parameters(curveOid))); + ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(ecPriv.getX(), getECParameterSpec(curveOid)); return implGeneratePrivate(keyAlgorithm, ecPrivSpec); } @@ -735,7 +943,7 @@ private PublicKey implGetPublicKeyEC(String keyAlgorithm, ECPublicBCPGKey ecPub) new java.security.spec.ECPoint( ecPubPoint.getAffineXCoord().toBigInteger(), ecPubPoint.getAffineYCoord().toBigInteger()), - getECParameterSpec(curveOID, x9Params)); + getECParameterSpec(curveOID)); return implGeneratePublic(keyAlgorithm, ecPubSpec); } @@ -751,4 +959,17 @@ private PublicKey get25519PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm } return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); } + + private PublicKey get448PublicKey(BigInteger x, ASN1ObjectIdentifier algorithm, String keyAlgorithm, String name) + throws PGPException, GeneralSecurityException, IOException + { + byte[] pEnc = BigIntegers.asUnsignedByteArray(x); + + // skip the 0x40 header byte. + if (pEnc.length < 1 || 0x40 != pEnc[0]) + { + throw new IllegalArgumentException("Invalid " + name + "448 public key"); + } + return implGetPublicKeyX509(pEnc, 1, algorithm, keyAlgorithm); + } } diff --git a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java b/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java deleted file mode 100644 index 13b14e3807..0000000000 --- a/pg/src/main/jdk1.5/org/bouncycastle/openpgp/operator/jcajce/JcePublicKeyKeyEncryptionMethodGenerator.java +++ /dev/null @@ -1,259 +0,0 @@ -package org.bouncycastle.openpgp.operator.jcajce; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.spec.SecretKeySpec; - -import org.bouncycastle.asn1.cryptlib.CryptlibObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x9.X962Parameters; -import org.bouncycastle.bcpg.ECDHPublicBCPGKey; -import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; -import org.bouncycastle.bcpg.PublicKeyPacket; -import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; -import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; -import org.bouncycastle.jcajce.spec.HybridValueParameterSpec; -import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; -import org.bouncycastle.jcajce.util.NamedJcaJceHelper; -import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; -import org.bouncycastle.openpgp.PGPException; -import org.bouncycastle.openpgp.PGPPublicKey; -import org.bouncycastle.openpgp.PGPUtil; -import org.bouncycastle.openpgp.operator.PGPPad; -import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; -import org.bouncycastle.openpgp.operator.RFC6637Utils; -import org.bouncycastle.util.Arrays; - -public class JcePublicKeyKeyEncryptionMethodGenerator - extends PublicKeyKeyEncryptionMethodGenerator -{ - private static final byte X_HDR = 0x40; - - private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); - private SecureRandom random; - private JcaPGPKeyConverter keyConverter = new JcaPGPKeyConverter(); - - /** - * Create a public key encryption method generator with the method to be based on the passed in key. - * - * @param key the public key to use for encryption. - */ - public JcePublicKeyKeyEncryptionMethodGenerator(PGPPublicKey key) - { - super(key); - } - - public JcePublicKeyKeyEncryptionMethodGenerator setProvider(Provider provider) - { - this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); - - keyConverter.setProvider(provider); - - return this; - } - - public JcePublicKeyKeyEncryptionMethodGenerator setProvider(String providerName) - { - this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); - - keyConverter.setProvider(providerName); - - return this; - } - - /** - * Provide a user defined source of randomness. - * - * @param random the secure random to be used. - * @return the current generator. - */ - public JcePublicKeyKeyEncryptionMethodGenerator setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - protected byte[] encryptSessionInfo(PGPPublicKey pubKey, byte[] sessionInfo) - throws PGPException - { - try - { - PublicKey cryptoPublicKey = keyConverter.getPublicKey(pubKey); - - if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.ECDH) - { - final ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)pubKey.getPublicKeyPacket().getKey(); - String keyEncryptionOID = RFC6637Utils.getKeyEncryptionOID(ecKey.getSymmetricKeyAlgorithm()).getId(); - PublicKeyPacket pubKeyPacket = pubKey.getPublicKeyPacket(); - if (ecKey.getCurveOID().equals(CryptlibObjectIdentifiers.curvey25519)) - { - return getEncryptSessionInfo(pubKeyPacket, "X25519", cryptoPublicKey, keyEncryptionOID, - ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getXDHAlgorithm(pubKeyPacket), - new KeyPairGeneratorOperation() - { - @Override - public void initialize(KeyPairGenerator kpGen) - throws GeneralSecurityException, IOException - { - kpGen.initialize(255, random); - } - }, - new EphPubEncoding() - { - @Override - public byte[] getEphPubEncoding(byte[] ephPubEncoding) - { - return Arrays.prepend(ephPubEncoding, X_HDR); - } - }); - } - else - { - return getEncryptSessionInfo(pubKeyPacket, "EC", cryptoPublicKey, keyEncryptionOID, - ecKey.getSymmetricKeyAlgorithm(), sessionInfo, RFC6637Utils.getAgreementAlgorithm(pubKeyPacket), - new KeyPairGeneratorOperation() - { - @Override - public void initialize(KeyPairGenerator kpGen) - throws GeneralSecurityException, IOException - { - AlgorithmParameters ecAlgParams = helper.createAlgorithmParameters("EC"); - ecAlgParams.init(new X962Parameters(ecKey.getCurveOID()).getEncoded()); - kpGen.initialize(ecAlgParams.getParameterSpec(AlgorithmParameterSpec.class), random); - } - }, - new EphPubEncoding() - { - @Override - public byte[] getEphPubEncoding(byte[] ephPubEncoding) - { - if (null == ephPubEncoding || ephPubEncoding.length < 1 || ephPubEncoding[0] != 0x04) - { - ephPubEncoding = JcaJcePGPUtil.getX9Parameters(ecKey.getCurveOID()).getCurve().decodePoint(ephPubEncoding).getEncoded(false); - } - return ephPubEncoding; - } - }); - } - } - else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X25519) - { - return getEncryptSessionInfo(pubKey, "X25519", cryptoPublicKey, NISTObjectIdentifiers.id_aes128_wrap.getId(), - SymmetricKeyAlgorithmTags.AES_128, sessionInfo, "X25519withSHA256HKDF", 255); - } - else if (pubKey.getAlgorithm() == PublicKeyAlgorithmTags.X448) - { - return getEncryptSessionInfo(pubKey, "X448", cryptoPublicKey, NISTObjectIdentifiers.id_aes256_wrap.getId(), - SymmetricKeyAlgorithmTags.AES_256, sessionInfo, "X448withSHA512HKDF", 448); - } - else - { - Cipher c = helper.createPublicKeyCipher(pubKey.getAlgorithm()); - - c.init(Cipher.ENCRYPT_MODE, cryptoPublicKey, random); - - return c.doFinal(sessionInfo); - } - } - catch (IllegalBlockSizeException e) - { - throw new PGPException("illegal block size: " + e.getMessage(), e); - } - catch (BadPaddingException e) - { - throw new PGPException("bad padding: " + e.getMessage(), e); - } - catch (InvalidKeyException e) - { - throw new PGPException("key invalid: " + e.getMessage(), e); - } - catch (IOException e) - { - throw new PGPException("unable to encode MPI: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new PGPException("unable to set up ephemeral keys: " + e.getMessage(), e); - } - } - - @FunctionalInterface - private interface KeyPairGeneratorOperation - { - void initialize(KeyPairGenerator kpGen) - throws GeneralSecurityException, IOException; - } - - @FunctionalInterface - private interface EphPubEncoding - { - byte[] getEphPubEncoding(byte[] publicKeyData); - } - - private byte[] getEncryptSessionInfo(PublicKeyPacket pubKeyPacket, String algorithmName, PublicKey cryptoPublicKey, String keyEncryptionOID, - int symmetricKeyAlgorithm, byte[] sessionInfo, String agreementName, KeyPairGeneratorOperation kpOperation, - EphPubEncoding getEncoding) - throws GeneralSecurityException, IOException, PGPException - { - KeyPairGenerator kpGen = helper.createKeyPairGenerator(algorithmName); - kpOperation.initialize(kpGen); - KeyPair ephKP = kpGen.generateKeyPair(); - UserKeyingMaterialSpec ukmSpec = new UserKeyingMaterialSpec(RFC6637Utils.createUserKeyingMaterial(pubKeyPacket, - new JcaKeyFingerprintCalculator())); - Key secret = JcaJcePGPUtil.getSecret(helper, cryptoPublicKey, keyEncryptionOID, agreementName, ukmSpec, ephKP.getPrivate()); - byte[] ephPubEncoding = getEncoding.getEphPubEncoding(SubjectPublicKeyInfo.getInstance(ephKP.getPublic().getEncoded()).getPublicKeyData().getBytes()); - byte[] paddedSessionData = PGPPad.padSessionData(sessionInfo, sessionKeyObfuscation); - - return getSessionInfo(ephPubEncoding, getWrapper(symmetricKeyAlgorithm, sessionInfo, secret, paddedSessionData)); - } - - /** - * Note that unlike ECDH, no checksum or padding are appended to the - * session key before key wrapping. Finally, note that unlike the other - * public-key algorithms, in the case of a v3 PKESK packet, the - * symmetric algorithm ID is not encrypted. Instead, it is prepended to - * the encrypted session key in plaintext. In this case, the symmetric - * algorithm used MUST be AES-128, AES-192 or AES-256 (algorithm ID 7, 8 - * or 9). - */ - private byte[] getEncryptSessionInfo(PGPPublicKey pgpPublicKey, String algorithmName, PublicKey cryptoPublicKey, String keyEncryptionOID, - int symmetricKeyAlgorithm, byte[] sessionInfo, String agreementAlgorithmName, int keySize) - throws GeneralSecurityException, IOException, PGPException - { - KeyPairGenerator kpGen = helper.createKeyPairGenerator(algorithmName); - kpGen.initialize(keySize, random); - KeyPair ephKP = kpGen.generateKeyPair(); - - byte[] ephPubEncoding = SubjectPublicKeyInfo.getInstance(ephKP.getPublic().getEncoded()).getPublicKeyData().getBytes(); - HybridValueParameterSpec ukmSpec = JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(ephPubEncoding, pgpPublicKey.getPublicKeyPacket(), algorithmName); - Key secret = JcaJcePGPUtil.getSecret(helper, cryptoPublicKey, keyEncryptionOID, agreementAlgorithmName, ukmSpec, ephKP.getPrivate()); - //No checksum or padding - byte[] sessionData = new byte[sessionInfo.length - 3]; - System.arraycopy(sessionInfo, 1, sessionData, 0, sessionData.length); - - return getSessionInfo(ephPubEncoding, sessionInfo[0], getWrapper(symmetricKeyAlgorithm, sessionInfo, secret, sessionData)); - } - - private byte[] getWrapper(int symmetricKeyAlgorithm, byte[] sessionInfo, Key secret, byte[] sessionData) - throws PGPException, InvalidKeyException, IllegalBlockSizeException - { - Cipher c = helper.createKeyWrapper(symmetricKeyAlgorithm); - c.init(Cipher.WRAP_MODE, secret, random); - return c.wrap(new SecretKeySpec(sessionData, PGPUtil.getSymmetricCipherName(sessionInfo[0]))); - } -} diff --git a/pg/src/main/jdk1.9/module-info.java b/pg/src/main/jdk1.9/module-info.java index b4b68b6d85..622ea41135 100644 --- a/pg/src/main/jdk1.9/module-info.java +++ b/pg/src/main/jdk1.9/module-info.java @@ -12,6 +12,9 @@ exports org.bouncycastle.gpg.keybox; exports org.bouncycastle.gpg.keybox.bc; exports org.bouncycastle.gpg.keybox.jcajce; + exports org.bouncycastle.openpgp.api; + exports org.bouncycastle.openpgp.api.bc; + exports org.bouncycastle.openpgp.api.jcajce; exports org.bouncycastle.openpgp.bc; exports org.bouncycastle.openpgp.examples; exports org.bouncycastle.openpgp.jcajce; diff --git a/pg/src/test/j2me/org/bouncycastle/openpgp/test/BcPGPRSATest.java b/pg/src/test/j2me/org/bouncycastle/openpgp/test/BcPGPRSATest.java index b6728353d8..6798e9518c 100644 --- a/pg/src/test/j2me/org/bouncycastle/openpgp/test/BcPGPRSATest.java +++ b/pg/src/test/j2me/org/bouncycastle/openpgp/test/BcPGPRSATest.java @@ -406,7 +406,12 @@ private void fingerPrintTest() PGPPublicKey pubKey = pgpPub.getPublicKey(); - if (!areEqual(pubKey.getFingerprint(), Hex.decode("4FFB9F0884266C715D1CEAC804A3BBFA"))) + byte[] expectedVersion3 = Hex.decode("4FFB9F0884266C715D1CEAC804A3BBFA"); + if (!areEqual(pubKey.getFingerprint(), expectedVersion3)) + { + fail("version 3 fingerprint test failed"); + } + if (!pubKey.hasFingerprint(expectedVersion3)) { fail("version 3 fingerprint test failed"); } @@ -418,7 +423,12 @@ private void fingerPrintTest() pubKey = pgpPub.getPublicKey(); - if (!areEqual(pubKey.getFingerprint(), Hex.decode("3062363c1046a01a751946bb35586146fdf3f373"))) + byte[] expectedVersion4 = Hex.decode("3062363c1046a01a751946bb35586146fdf3f373"); + if (!areEqual(pubKey.getFingerprint(), expectedVersion4)) + { + fail("version 4 fingerprint test failed"); + } + if (!pubKey.hasFingerprint(expectedVersion4)) { fail("version 4 fingerprint test failed"); } diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/AbstractPacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/AbstractPacketTest.java new file mode 100644 index 0000000000..6c160d7dd9 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/AbstractPacketTest.java @@ -0,0 +1,133 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.ContainedPacket; +import org.bouncycastle.test.DumpUtil; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.test.SimpleTest; + +import java.io.IOException; + +public abstract class AbstractPacketTest + extends SimpleTest +{ + + /** + * Test, whether the first byte array and the second byte array are identical. + * If a mismatch is detected, a formatted hex dump of both arrays is printed to stdout. + * @param first first array + * @param second second array + */ + public void isEncodingEqual(byte[] first, byte[] second) + { + isEncodingEqual(null, first, second); + } + + /** + * Test, whether the first byte array and the second byte array are identical. + * If a mismatch is detected, a formatted hex dump of both arrays is printed to stdout. + * @param message error message to prepend to the hex dump + * @param first first array + * @param second second array + */ + public void isEncodingEqual(String message, byte[] first, byte[] second) + { + StringBuilder sb = new StringBuilder(); + if (message != null) + { + sb.append(message).append("\n"); + } + sb.append("Expected: \n").append(DumpUtil.hexdump(first)).append("\n"); + sb.append("Got: \n").append(DumpUtil.hexdump(second)); + + isTrue(sb.toString(), first == second || Arrays.areEqual(first, second)); + } + + /** + * Test, whether the encoding of the first and second packet are identical. + * If a mismatch is detected, a formatted hex dump of both packet encodings is printed to stdout. + * @param first first packet + * @param second second packet + */ + public void isEncodingEqual(ContainedPacket first, ContainedPacket second) + throws IOException + { + isEncodingEqual(null, first, second); + } + + /** + * Test, whether the encoding of the first and second packet are identical. + * If a mismatch is detected, a formatted hex dump of both packet encodings is printed to stdout. + * @param message error message to prepend to the hex dump + * @param first first packet + * @param second second packet + */ + public void isEncodingEqual(String message, ContainedPacket first, ContainedPacket second) + throws IOException + { + StringBuilder sb = new StringBuilder(); + if (message != null) + { + sb.append(message).append("\n"); + } + sb.append("Expected: \n").append(PacketDumpUtil.hexdump(first)).append("\n"); + sb.append("Got: \n").append(PacketDumpUtil.hexdump(second)); + isTrue(sb.toString(), first == second || Arrays.areEqual(first.getEncoded(), second.getEncoded())); + } + + /** + * Test, whether the value is false. + * @param value value + */ + public void isFalse(boolean value) + { + isFalse("Value is not false.", value); + } + + /** + * Test, whether the value is false. + * @param message custom error message + * @param value value + */ + public void isFalse(String message, boolean value) + { + isTrue(message, !value); + } + + /** + * Test, whether the value is null. + * @param value value + */ + public void isNull(Object value) + { + isNull("Value is not null.", value); + } + + /** + * Test, whether the value is null. + * @param message custom error message + * @param value value + */ + public void isNull(String message, Object value) + { + isTrue(message, value == null); + } + + /** + * Test, whether the value is not null. + * @param value value + */ + public void isNotNull(Object value) + { + isNotNull("Value is null.", value); + } + + /** + * Test, whether the value is not null. + * @param message custom error message + * @param value value + */ + public void isNotNull(String message, Object value) + { + isTrue(message, value != null); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java b/pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java new file mode 100644 index 0000000000..c278aa5871 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java @@ -0,0 +1,75 @@ +package org.bouncycastle.bcpg.test; + +import java.security.Security; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.PrintTestResult; +import org.bouncycastle.util.test.SimpleTestResult; + +public class AllTests + extends TestCase +{ + + public void testPacketParsing() + { + Security.addProvider(new BouncyCastleProvider()); + + org.bouncycastle.util.test.Test[] tests = new org.bouncycastle.util.test.Test[] + { + new SignaturePacketTest(), + new OnePassSignaturePacketTest(), + new OpenPgpMessageTest(), + new FingerprintUtilTest(), + new EncryptedMessagePacketTest(), + new TimeEncodingTest() + }; + + for (int i = 0; i != tests.length; i++) + { + SimpleTestResult result = (SimpleTestResult)tests[i].perform(); + + if (!result.isSuccessful()) + { + fail(result.toString()); + } + } + } + + + public static void main(String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("OpenPGP Packet Tests"); + + suite.addTestSuite(AllTests.class); + + return new BCPacketTests(suite); + } + + static class BCPacketTests + extends TestSetup + { + public BCPacketTests(Test test) + { + super(test); + } + + protected void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + protected void tearDown() + { + Security.removeProvider("BC"); + } + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/BCPGOutputStreamTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/BCPGOutputStreamTest.java new file mode 100644 index 0000000000..04584da4b4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/BCPGOutputStreamTest.java @@ -0,0 +1,306 @@ +package org.bouncycastle.bcpg.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.Packet; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.UserIDPacket; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.SimpleTest; + +public class BCPGOutputStreamTest + extends SimpleTest +{ + + private void testForceNewPacketFormat() + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.CURRENT); + + new UserIDPacket("Alice").encode(pOut); + new UserIDPacket("Bob").encode(pOut); + + pOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + isTrue(pIn.readPacket().hasNewPacketFormat()); + isTrue(pIn.readPacket().hasNewPacketFormat()); + } + + private void testForceOldPacketFormat() + throws IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.LEGACY); + + new UserIDPacket("Alice").encode(pOut); + new UserIDPacket("Bob").encode(pOut); + + pOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + isTrue(!pIn.readPacket().hasNewPacketFormat()); + isTrue(!pIn.readPacket().hasNewPacketFormat()); + } + + private void testRoundTripPacketFormat() + throws IOException + { + List oldPackets = new ArrayList(); + ByteArrayInputStream obIn = new ByteArrayInputStream(Hex.decode("b405416c696365b403426f62")); + BCPGInputStream opIn = new BCPGInputStream(obIn); + oldPackets.add((UserIDPacket) opIn.readPacket()); + oldPackets.add((UserIDPacket) opIn.readPacket()); + + List newPackets = new ArrayList(); + ByteArrayInputStream nbIn = new ByteArrayInputStream(Hex.decode("cd05416c696365cd03426f62")); + BCPGInputStream npIn = new BCPGInputStream(nbIn); + newPackets.add((UserIDPacket) npIn.readPacket()); + newPackets.add((UserIDPacket) npIn.readPacket()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.ROUNDTRIP); + + // Write New, Old, Old, New + pOut.writePacket((UserIDPacket)newPackets.get(0)); + pOut.writePacket((UserIDPacket)oldPackets.get(0)); + pOut.writePacket((UserIDPacket)oldPackets.get(1)); + pOut.writePacket((UserIDPacket)newPackets.get(1)); + pOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + // Test New, Old, Old, New + isTrue(pIn.readPacket().hasNewPacketFormat()); + isTrue(!pIn.readPacket().hasNewPacketFormat()); + isTrue(!pIn.readPacket().hasNewPacketFormat()); + isTrue(pIn.readPacket().hasNewPacketFormat()); + } + + private void testRoundtripMixedPacketFormats() + throws IOException + { + // Certificate with mixed new and old packet formats + // The primary key + sigs use new format + // The signing subkey + sigs use old format + // The encryption subkey + sigs use new format again + String encodedCert = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "xcTGBGYvuZUBDACyFv3LQiubgHM4eJUFnsLEei8/l4bGKdVx8hRu6N5rfcjZt3RM\n" + + "UGUi+HQDnRbUvJ5B/7qDB7Ia7bpRf7BrYmho5vqNtjpxUPs3Mct1TjqCm2yLC9zH\n" + + "+qHmGSPX4dLtSKKpXc4iBMGtFknhXKnoUovv7XZDecIIDbJhaqoFptRfqFc30SRj\n" + + "ktQcyXutcIYlhaPQ/JtJlNWfmo0+NTEjfpDOZovCzAi769QnljntkiKXxQzBihzb\n" + + "f1Ou7NzJ17m/7pJXBOTKKXboMFDc1ct6f2s2lomEhCYRPRC6eITWpXK/G7e503xS\n" + + "eaMnd29BrmbEnw6QgCjafu72t8rgD6jbj3+kaRR85AevLWrfefo9ofhUMl0DDKc+\n" + + "bhNQAMRZY9vlRdEo0pNLL9kIMzl10HL9viRXxCwp4d1chH0qLQdy8W13WrjhS0Fw\n" + + "GlEkcTt2Z/4kGmYeLvBfQqfz62owIR47otX8JU+QdTmP89SyZRyuHVwB+Pgg32oC\n" + + "1fSJUVHRCb6f1z0AEQEAAf4JAwJgAx2GH4oiN2CgjB+JAKrjlbrfjhLDN+w14SeC\n" + + "vGpP40Ay/bUFYgfvkVA3CQFMYJ4fCKluhu2cHAhzCrGCAKs42ZvkKzHuDohzEjGG\n" + + "N9IkA4y/Gv2tTewhtMALxbHtS7CCX6IBqC292mupm7ND4aULhLM4xqXKXUny543V\n" + + "hPJEuKL8D5CLRqFJPtrw/791izbdr6J+rKxYwscL5NiUJQFLVsK59+7sJvSvBK9N\n" + + "DIiFT+hRSJjb6rBrXWZK0bUCsaCLHL0k8PLPdBdzZ3YJqcaIFRd0Sq7l7Ck7RxXh\n" + + "L8tf8Swcr1UafMMYbyMJW5VtJxZStV1OgdWVatrbkW5GINlZ7pp63kIOY2GbK99H\n" + + "Q4mAQV1EpAlItF4QqkOunyGqw6aN5x9+Hoyr0O17428604wsptZstNT0wz3qGJJ/\n" + + "ye3I9xveEMhRwv1ZB3MsiiBLj5kEa2l4W6O3g/6Sdu75MGhalyi5+r41SgKkxMWI\n" + + "OCTZMWCNZ1ZR9Ehlsg5uOtNUc9RkAn9BAfBzDwBMMa8wzHKsNiaiR2Tonpm1+miB\n" + + "TtBU7RUw5CEAcGbnYmLvlxVwe7CTVezYIQIroCCqY738Y5mpOSB0UhT1JAORPCJJ\n" + + "PCWRGQ9UDm0xK/dFbbRNTJqYM2GZKOM5esnKQlxJ1t9+VoQ+mPLOPHnkmUXU8Rq8\n" + + "9c3bLogW/dsCm0j8lfV0sKsAXfuD3spHPoJwQOFwZ4kDeFjJlRTusNSgXQsRF/x4\n" + + "Wvwt+jmxRwenkeVunigqZVOhctf8ozkncpCV8tTLp8X2VrlJNx5XoggFzOwEWxJa\n" + + "mMx1gvsAlsEiTCK5g6xocULxKfBfJogUrBXZk0GUJriJzB470QMnQ49a4gGFh4w7\n" + + "Wh2/FiRRMIGTTXPFHSQ92kaWoqO1jDhM7c6HrxEETS7NrWi6TLvfYxrCZ9GlYanK\n" + + "MPDa75lVpuE95M1+dRShX13LJpSlOq8Eius/kP9W54sCT4DTIvlz08QdcaNpRN/9\n" + + "ZZGJw6gMttshvvl1eOKOjD3iW110qJtxh/W4OxgDL7R+JKKYfjc9lWMIhfy1sOQK\n" + + "cmXZVP6HVK5y+xwW8h8MTqjUznYo1Lfu6icmBm7q0/P2lSkBSQ76kSL4exgtYr4k\n" + + "XRj483ipnlUr8ue53ALXOC46NIj8wE2+LDg1rAt3AWru1fOGFMU4bol7ytBoBKmz\n" + + "Cvv/6hxDZGSR43n+FLWMd40hRjneeM+0oy/6vvU0Rsa3FdL7m+/Rui8CC4JoG/Kc\n" + + "xl3uj0OgfHvHYPjLoXOPUdPNIptwfCQ9xvEfWWJA4hcyRdToy1gjYINSmJDIhYgL\n" + + "yyFlm2GlHMKDo71TEODRwNHy61Jdikx43c0ZQWxpY2UgPGFsaWNlQGV4YW1wbGUu\n" + + "Y29tPsLA+QQTAQoAIwUCZi+5lwKbAQIeARYhBLSFPwVS++7sNFWR0nm9t4YHzlXs\n" + + "AAoJEHm9t4YHzlXs7soL/jtmG5E6helkBjFLZqBfXJUxIniEtOxT0GrePTfA7lde\n" + + "0hKDh3Wjh0+RmfnuatopWW1DRKmhnS0uAIwIewIH7rzhHG+i9OHAwZ6R61ptEKmH\n" + + "WL5JeqTNq3bLD6U6VgfrFq1DNxtfTWTPwTzSIBuGVLJjRFEqq5olH4dD6xImO7Lk\n" + + "t3KJ9Du8IdmLsoEcw0tMhd5cSbh2gE1F1CnmSufDts2coTv7B/lQTAhOFQQedMFa\n" + + "N/mKJ/v+DvRjB9nV+rYqeqweTLJ2AJcmnmDTiue74CgP2o84Cf7JEAZ83vy2hHLq\n" + + "KGvsYbQoE1oSt7vU9otGotSutrFZww8LmnkJCQwHPrNWC21CKoo/7bGo4ToDaVOw\n" + + "FEC9l2pusMaN6y9ztsq2Wz3mlQppe0kizMmkA+WM34Lu0EI3DGQvqIcIMKEg242B\n" + + "e8gV2qN7t/zMvLM34A4sDD7L1e8dKKnru0MY73TaMAw+kbRuM/DrQpT4PI1cvD4j\n" + + "xN/rVB0g4JIuVElygMLA950FhgRmL7mVAQwA2WGMqveX3ssz5tdKIP6q8krGSwsF\n" + + "CR7qBGVac5XiYaNzg6YJX+r8CiSAT+mN55t7TN9C7kND9zlssLJidKuXs87Bgwjl\n" + + "gmuO0AL9VFKTx2IkEVovwwKvozJd9vt79IKY6wJ4eqbElaBfNy2uov4kuOxcEEuY\n" + + "n7UQttW6Pp0JFP1lb+hZ524r05wYb7LGdPyz1vNPeYEg48PkcNU6Z9DXfU80JVp8\n" + + "Cy0XNxHm31ML/DgLJHIVZ0dstA2KZnWxhlKNNfdmYakGEU5QISGViReybcc3kwco\n" + + "v5agauCUWNFvLM7NYI7S1m5A0r6hWM/CtQwUgb0PIT97nEbYmIB+su+6RTLvOkMM\n" + + "3465MxjBVwwiWFpZcHiUP3q5Eelr1V75rOwII3HKSC1tfZwjWxyzdBpPZDpMIxHT\n" + + "9ldJnlLzIvUOR2pSusqnGrCeurGqNxT/b9lEifoHcDNiyo+Qj4WsOjp+I9sBkfYP\n" + + "G3Hbx/OmKvkSY4a+L53iY2H1xjAfYwySI5KBABEBAAH+CQMCYAMdhh+KIjdg8Sop\n" + + "plGYPDvXQ3N1JgtYiGXjOuvsEIuxqmY4CwtFATtqjphFPe+6GL4zS16vcGlAPwgI\n" + + "h0+aZQxPHKJcUx997zm9PFrOjnSInFraAdIvpBay+5DlicGJuARZ/8ZhNZ7qxbIT\n" + + "vi5ZVRnrPef6SO5E1zeSFodMV5FZE1fZNTeSq2AOQ/tIkMPsjK/BpKSTLSebkwii\n" + + "G3IgQEB6albQsfpKTqSCgDS9o0/b5/q+KMYtHoS0XwoE46df1wfjirz6zNY6VShd\n" + + "3MaJ+Jb1GzsRCTTedKHHnF/fU49uWs7LNRZT1PhSMBH/scL1w2u8bmdvW0i8PJaN\n" + + "bbdX/Zs2sVxfACfeUSkF6GAmqnc1+6RnZSxMjSqk/1uPhtuSUa1NsJ9UlxHIQcDp\n" + + "NGlQCrabUdhmjfZWtXCIcINXj0JPfMTNIxLC4YBSUvV+y//UEzq+LYT0tnOXeU6O\n" + + "/JCzhEoGhPvboFfv8p3fPVvvLFseONZuX3d9WzbAQiCpCXlP4+Ro0OFw32JGTZLq\n" + + "mi6eiJceAJ4sza4V/DeaDovJ62RJHzJOtb8+cOFyo+/8m46YMF07X2AwdjE8Az69\n" + + "td1N79S9eqtYjV1VWrrf94fpeUGV4UD1ugt/UalGbGm4IQFTGZGb0vinImLoM7ts\n" + + "84BneaosoYh/62bA5OzIF9xqHjFQ9XiNjwODFpiIZl3twL7DVDWf9Paq9ki1mv2D\n" + + "pan8sJtsZYj0j0D+V9nDk5LSBiMnb+qaagq/Wt648eqaxGP1gb5B/w9rrYiF0/TX\n" + + "H5q/qzHxh9j8sPEAM3R7Y9+IL1RgF0/3VgBx52/eJxVvb9FUZOoF7cvrESAFDqSo\n" + + "p3/pN07kMN3fHNIFpQGbsC6ECmEatPnANJH0InDnPERTGasiCtshdzx8bTLIdh95\n" + + "3hTJuv6ML8+PP9Jp4eLiAkinW+leBEyFgpYMFBdSifQ5R/jU7n/6IcW/4u5t66if\n" + + "RFnE0N2hpMUQPTl5hZH5TY9AU55MZCLzvDbYW/cXmIuBuRNVfaLIWSKp8UxFwZfk\n" + + "zki8N+EUPeB1dPaFapuArvpmSAl7uLzNYAb7X4Tf29VBlz2zRhh2dMAOtzX+55YX\n" + + "nNE2gEiGP1FAA00l/nIKWIHf0u6zMO0jj6soSwsan9VfoyK9jc7qDObPrW0v0lsK\n" + + "0CknbavMkrS+DdhTWAzYhvdSUZV80H/lRUwrTyCpaiRuuDu+kZOScTH1JsFkDEix\n" + + "NypeMhSIh5Izzf0njazQSxzoI6XcEJLukFPONvZ0oTsXF1j0IITFboWjQpuUJ/kg\n" + + "ZGBuBlllk2gD7t3H8r1zRiKkHaw9Nr4Fr4r5wNJVfVKrnQkuQBJneP2JA1UEGAEK\n" + + "Ab8FAmYvuZcCmwIWIQS0hT8FUvvu7DRVkdJ5vbeGB85V7MDdIAQZAQoABgUCZi+5\n" + + "lwAKCRDVw7vf0dE2sN77DACUd5X+RFI264quxxPZlO/jmcu3PfoeGtWL4ILMZ8Lj\n" + + "4NyoqctmRthZzEvvyzmg/IQOPJlIru18aJKZQgrKkQzytbd+BL8GfsTXh7XwICcu\n" + + "xS9pzMMKi29rU8ViwK+4blAjxGcPRrniJYBn7NWAlumjpUVCzoIpjcphpiCKTZlz\n" + + "m2W4iWGSPzemDmOzEEWERafu3O08yS5n9zl2wrdOjClNC4Pmlyy8PH8b42mgMr4e\n" + + "nP8CoTpzdFQbzSg/A3pfYgK+TLtVI9KZO4V/OIK6jppKUDg0ZA+GDUYC4mtjgHgQ\n" + + "Qaj0OiAHxti1bYA/VgoBLI3D/AW5JNJ0XGUXO++qwR5rNa6Sgs2DATvBw6mLbiVV\n" + + "pYBuDTnFRtXURm1pkD8Z+jSKz5eq7fEnO8GhnW+4ftPztXpucl85jtAHTqPFaiET\n" + + "jDwrdmHNqvMdu0KQfd+D1bU8KSf2v/9h7LS/fyfxDxYgX15O4crtQV1Obq6yLbbA\n" + + "G0YwRknIaPbq9qZx8iXue+kACgkQeb23hgfOVewMmgwAnJl4g0sX89VFz1OtMLJj\n" + + "Ui2QvPCpMkhsrgbaLS3q+wSZIUTZWzTzcZhDajNs3f/KjL2Dm5UxkHD29DuUv++r\n" + + "YPsVpWkk8wtD8/Am4CF1b5ibXboBrouAuju64pqrHjrM8/1WeZatYqkjShk5DqA2\n" + + "PlgpHFxoRB/0QnUwp6kpu2Tr3CTrcn0tyyqbcwTr5pw5oBLWcWgc8LMIFV2zdnHa\n" + + "bGvsew9puss1oh5Fs58XYg0Gdf/J/qelWgxbx/b4GHy5wxvb5BkbNMz7hWquZNsc\n" + + "DRuCOwRwlhCY13rTDUwwonU/PMPwP9I6pU5LBx+xRt3p8CeE4f00ANdxbS6JI5iA\n" + + "zqUsKIlUlwH+AO9VtRqiAJsVwaJVm/GOWJVeIKiz8M/jgiW0NCVJb01RW+3WVaY5\n" + + "kpLKqE1V0xq4mxw16mjBguUx3HdR5rh3ZZJ0TfXGGDAhLQC7PXe3oQyN1NbbH2Vx\n" + + "jVKueQsGPX2022pepiJXXtAzGIBR0eUOfylpewuerFwEx8TGBGYvuZUBDADjCLaD\n" + + "w3L65khVSjpsu8jr9B72xbx/EIlXEKr2KXa1lvf0yadxKB5/KytXWffQ8lEMmdi9\n" + + "p86+LIWIh7wx+mhh2g64um2yJiuS+HRTWWA69nb6/1Tl5G2VyT81AVQ5JAcNyIIS\n" + + "RuWvzZoQDNf0sImT0o7dAK4KLtofGMy/rIaNebE2Qu4dks5aBjIV2/bPoIMrSuJF\n" + + "UK5UsUOPx5jlYk5gpgyPcl30YgLf0Bizp4RJSCpIjjDJ6WvKBxlRChdfbP52vawI\n" + + "IEcMGnWMVFvVd8I57v6HDtbQTgF8BepwgsWHnTGtoIkVnKc/nlM3LtNiJUY3z915\n" + + "TZGRbYcuqWZhMbnJoQLRgQXh6/E4FzxDxaKoXpYXuPDxCTfNxeqU3hrRZUfKOdjw\n" + + "+BS5rSicvbGaqgyz29518bG04hzrmWORoJExozWTOoE+kTU5+o7DmS7qtd+z63lL\n" + + "bjqLhFALPl9qbwVlFlFo6X6jmlo8THVkX5lLI1+Qaq2g3G1YYCoXDMoGbk8AEQEA\n" + + "Af4JAwJgAx2GH4oiN2BJ7FHcEtvbKapzj3N2OwxYHmWymAAjgPe10Ne2W7FFi4Qy\n" + + "sj0Ss9NbWV5Nw4NqnE6syOFNVeLs5t7BdTqXs3NxOTJo0iS+lpL5OgUcMSWu2hN7\n" + + "jDbeXEBZFSQ7epetVDAetYsKLZBHpsI19aamUEnRZicKATjVQud9pHhC9BTFp62i\n" + + "D4a2IuxQcweuw5D8brKH9WfXYXlNzjoZdsqvWRWy77/6s2hg9V7lo65C/p8C0DB7\n" + + "blJwptt9j/vTlzTyavV60rRma3VeMgQw5sn0b2lqWvmLRgpjmCv2AdD9A6rYU/4+\n" + + "f+sknWq5c/gaoWAMWNg+vgRpZUT9C5ZlT86QUuz0DO7ySoy0gy9Z3BID+JDcXP/b\n" + + "BYftC7XQut+nnWGD+Pr2E0YvrTQLw0ISCzKyCI9iZh0gvwv9bKdYOUSEhOM9zlk+\n" + + "gt3hFJvVXvLbFUHEbh0Oep0AcCzFKzBrTYBeJ8Z8vvgNfie9zMtY3EAV4tBU2MVB\n" + + "3JqgRJ9Qam/ZGJ47GIbkRnqrbCmL44U3Qvl9to4g96gmrQXfdJUAtpntewuuDguJ\n" + + "MgKYUTv9TupYErHoTFlV61czXEwITE6y3TuePgWp4sY+BXGWyFc4puS+KNB+y+GC\n" + + "hJdchAyJcVhsV2e7ElC2URVmGpDkW23qcRMFlu7QMaENI5itKEinKIPQokITO0l+\n" + + "I13oJ4KlMEgfofNQ4rWdoqir7AqaQ+HXTV0l8iQQJPuAwXYnSe4xjuHuBssJ92Qk\n" + + "B6H+7IGDvXwMikQzOkeZVrsL0f1Pg1DIPMgt5l4qleZ4aL0cDqBQHh3JLtXWQ4jp\n" + + "ffYWxxCXILO10WYbqAaG4eXr/vsCb/TfADiF07azQMgWrhk3NSSoVRRjQgIntCAR\n" + + "u9C2x6FcyeF4ND0eIciWH6+pby0xC9bg5XlKlgeMN/BoXnj/k34ZgoHbe6NmjhT2\n" + + "bpgXrQQl4QPBS67jr2lU6NunmOwoHwX+epwIIKW8bcjvOTs0XEGVCJleIyUf88m6\n" + + "bpV4WUmIk4I8ROztJRzxZpNB8HgZb9XzbOcXccUl8sjTOyMlQTIAl/qUIomJ8snH\n" + + "lzEhoWYWzWUrEe42CVld++xhLQkgR/V484ch+vDi9EjmKCRVWVdOnHda9fHe5o8n\n" + + "TQzMdG8Fvy2XrFQAeCdNkD+itwV1OIva9j9KQHadS9MVl5PYzy/ezwIrK9siXAXu\n" + + "4YiaSTL4TPwjWppQCJJv8mQskNP72tc8TELA225MtsPcSPiCT1aLUUKQmpQstEeQ\n" + + "S6Cv+uggbDXqWfow2mx5w4bJXLxpe09vm5rqBT6Scg2e4e3yRNiYGFXX2QsNVRui\n" + + "nLCJLAUtpUJXBcLA9gQYAQoAIAUCZi+5lwKbDBYhBLSFPwVS++7sNFWR0nm9t4YH\n" + + "zlXsAAoJEHm9t4YHzlXsaFsL/16ktY2/knugZ8bN1df/QzdDE30wWakcDqAZhEMb\n" + + "+MyazHM08ipXFkvNsz0r7Y6DXqvOTvRlzXc7csk3Np/rrFFwpkckHXz1JkrQwAtD\n" + + "rIMcmzqm25u7rKti0NfsacQI1mie+wFyrApvXTBF2av9Fn1ch07A4f6JTfD62KAo\n" + + "ccBKAr38LVBwwGJZh6WqOazgoO8B4ia1MveHgOCsf3SurigXt1iMCCqWvvpQUil9\n" + + "3hU8x1SNy0TajFwXSeAMTAyoWVlC7ceixVr9dPLgRuMbsfHYsBAMw9wHSSNVyqvl\n" + + "vhB4X/j3bIFhl3iqj1P7Km33yVbk30KtKHuPFpHMJBu8CZ4/JcPnfGK35aTgfV9N\n" + + "W9V5u+mtWKReL8Ii0/jQ53PGJ7I1m8uzLB83mmRYY2hoqxdzWTXB57oDJbPwZRSx\n" + + "5puZWZ4WbmsHSaPe0gMIQH3ItcnWuB2sxhkpXSnOtXIK44lqcQwq69ygHEP11W85\n" + + "3hRZb5W+1RCWcuPc/oWxMuwiBw==\n" + + "=7IAh\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(encodedCert.getBytes()); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objectFactory = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objectFactory.nextObject(); + + // ROUNDTRIP + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.ROUNDTRIP); + secretKeys.encode(pOut); + pOut.close(); + aOut.close(); + + isEquals(encodedCert, bOut.toString()); + + // NEW PACKET FORMAT + bOut = new ByteArrayOutputStream(); + aOut = new ArmoredOutputStream(bOut); + pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + secretKeys.encode(pOut); + pOut.close(); + aOut.close(); + + bIn = new ByteArrayInputStream(bOut.toByteArray()); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + Packet packet; + while ((packet = pIn.readPacket()) != null) + { + isTrue(packet.hasNewPacketFormat()); + } + + // OLD PACKET FORMAT + bOut = new ByteArrayOutputStream(); + aOut = new ArmoredOutputStream(bOut); + pOut = new BCPGOutputStream(aOut, PacketFormat.LEGACY); + secretKeys.encode(pOut); + pOut.close(); + aOut.close(); + + bIn = new ByteArrayInputStream(bOut.toByteArray()); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + while ((packet = pIn.readPacket()) != null) + { + isTrue(!packet.hasNewPacketFormat()); + } + } + + @Override + public String getName() + { + return "BCPGOutputStreamTest"; + } + + @Override + public void performTest() + throws Exception + { + testForceOldPacketFormat(); + testForceNewPacketFormat(); + testRoundTripPacketFormat(); + testRoundtripMixedPacketFormats(); + } + + public static void main(String[] args) + { + runTest(new BCPGOutputStreamTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/EncryptedMessagePacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/EncryptedMessagePacketTest.java new file mode 100644 index 0000000000..b7ffe28241 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/EncryptedMessagePacketTest.java @@ -0,0 +1,237 @@ +package org.bouncycastle.bcpg.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; +import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPadding; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.io.Streams; + +public class EncryptedMessagePacketTest + extends AbstractPacketTest +{ + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-version-6-secret-key + final String V6_SECRET_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xUsGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laMAGXKB\n" + + "exK+cH6NX1hs5hNhIB00TrJmosgv3mg1ditlsLfCsQYfGwoAAABCBYJjh3/jAwsJ\n" + + "BwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lwgyU2kCcUmKfvBXbAf6rh\n" + + "RYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaEQsiPlR4zxP/TP7mhfVEe\n" + + "7XWPxtnMUMtf15OyA51YBMdLBmOHf+MZAAAAIIaTJINn+eUBXbki+PSAld2nhJh/\n" + + "LVmFsS+60WyvXkQ1AE1gCk95TUR3XFeibg/u/tVY6a//1q0NWC1X+yui3O24wpsG\n" + + "GBsKAAAALAWCY4d/4wKbDCIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAAQBIKbpGG2dWTX8j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDE\n" + + "M0g12vYxoWM8Y81W+bHBw805I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUr\n" + + "k0mXubZvyl4GBg==\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + + // https://www.rfc-editor.org/rfc/rfc9580.html#name-complete-x25519-aead-ocb-en + final String X25519_AEAD_OCB_MESSAGE = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "wV0GIQYSyD8ecG9jCP4VGkF3Q6HwM3kOk+mXhIjR2zeNqZMIhRmHzxjV8bU/gXzO\n" + + "WgBM85PMiVi93AZfJfhK9QmxfdNnZBjeo1VDeVZheQHgaVf7yopqR6W1FT6NOrfS\n" + + "aQIHAgZhZBZTW+CwcW1g4FKlbExAf56zaw76/prQoN+bAzxpohup69LA7JW/Vp0l\n" + + "yZnuSj3hcFj0DfqLTGgr4/u717J+sPWbtQBfgMfG9AOIwwrUBqsFE9zW+f1zdlYo\n" + + "bhF30A+IitsxxA==\n" + + "-----END PGP MESSAGE-----"; + + @Override + public String getName() + { + return "PublicKeyEncryptedDataPacketTest"; + } + + @Override + public void performTest() + throws Exception + { + testX25519AEADOCBTestVector_bc(); + testX25519AEADOCBTestVector_jce(); + testPKESK6SEIPD2FromTestVector(); + testPKESK6SEIPD2(); + } + + private void testPKESK6SEIPD2FromTestVector() + throws IOException, PGPException + { + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-version-6-public-key + byte[] pkesk = Hex.decode("c15d06210612c83f" + + "1e706f6308fe151a" + + "417743a1f033790e" + + "93e9978488d1db37" + + "8da99308851987cf" + + "18d5f1b53f817cce" + + "5a004cf393cc8958" + + "bddc065f25f84af5" + + "09b17dd3676418de" + + "a355437956617901" + + "e06957fbca8a6a47" + + "a5b5153e8d3ab7"); + + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-v2-seipd-packet + byte[] seipd = Hex.decode("d269020702066164" + + "16535be0b0716d60" + + "e052a56c4c407f9e" + + "b36b0efafe9ad0a0" + + "df9b033c69a21ba9" + + "ebd2c0ec95bf569d" + + "25c999ee4a3de170" + + "58f40dfa8b4c682b" + + "e3fbbbd7b27eb0f5" + + "9bb5005f80c7c6f4" + + "0388c30ad406ab05" + + "13dcd6f9fd737656" + + "286e1177d00f888a" + + "db31c4"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V6_SECRET_KEY));; + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + bIn = new ByteArrayInputStream(Arrays.concatenate(pkesk, seipd)); + pIn = new BCPGInputStream(bIn); + objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + PGPSecretKey decKey = secretKeys.getSecretKey(encData.getKeyID()); // TODO: getKeyIdentifier() + PGPPrivateKey privKey = decKey.extractPrivateKey(null); + PublicKeyDataDecryptorFactory decryptor = new BcPublicKeyDataDecryptorFactory(privKey); + InputStream in = encData.getDataStream(decryptor); + objFac = new BcPGPObjectFactory(in); + PGPLiteralData literalData = (PGPLiteralData) objFac.nextObject(); + byte[] msg = Streams.readAll(literalData.getDataStream()); + isEncodingEqual(Strings.toUTF8ByteArray("Hello, world!"), msg); + PGPPadding padding = (PGPPadding) objFac.nextObject(); + isEncodingEqual(Hex.decode("c5a293072991628147d72c8f86b7"), padding.getPadding()); + } + + private void testX25519AEADOCBTestVector_bc() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V6_SECRET_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + bIn = new ByteArrayInputStream(X25519_AEAD_OCB_MESSAGE.getBytes()); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + PGPSecretKey decKey = secretKeys.getSecretKey(encData.getKeyID()); // TODO: getKeyIdentifier() + PGPPrivateKey privKey = decKey.extractPrivateKey(null); + PublicKeyDataDecryptorFactory decryptor = new BcPublicKeyDataDecryptorFactory(privKey); + InputStream in = encData.getDataStream(decryptor); + objFac = new BcPGPObjectFactory(in); + PGPLiteralData literalData = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(literalData.getDataStream()); + isEncodingEqual(Strings.toUTF8ByteArray("Hello, world!"), plaintext); + PGPPadding padding = (PGPPadding) objFac.nextObject(); + isEncodingEqual(Hex.decode("c5a293072991628147d72c8f86b7"), padding.getPadding()); + } + + private void testX25519AEADOCBTestVector_jce() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V6_SECRET_KEY));; + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new JcaPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + bIn = new ByteArrayInputStream(X25519_AEAD_OCB_MESSAGE.getBytes()); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new JcaPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + + PGPSecretKey decKey = secretKeys.getSecretKey(encData.getKeyID()); // TODO: getKeyIdentifier() + PGPPrivateKey privKey = decKey.extractPrivateKey(null); + PublicKeyDataDecryptorFactory decryptor = new JcePublicKeyDataDecryptorFactoryBuilder() + .setProvider(new BouncyCastleProvider()) + .setContentProvider(new BouncyCastleProvider()) + .build(privKey); + InputStream in = encData.getDataStream(decryptor); + objFac = new JcaPGPObjectFactory(in); + PGPLiteralData literalData = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(literalData.getDataStream()); + isEncodingEqual(Strings.toUTF8ByteArray("Hello, world!"), plaintext); + PGPPadding padding = (PGPPadding) objFac.nextObject(); + isEncodingEqual(Hex.decode("c5a293072991628147d72c8f86b7"), padding.getPadding()); + } + + private void testPKESK6SEIPD2() + throws IOException + { + String MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "wW0GIQYSyD8ecG9jCP4VGkF3Q6HwM3kOk+mXhIjR2zeNqZMIhRk5Bu/DU62hzgRm\n" + + "JYvBYeLA2Nrmz15g69ZN0xAB7SLDRCjjhnK6V7fGns6P1EiSCYbl1uNVBhK0MPGe\n" + + "rU9FY4yUXTnbB6eIXdCw0loCCQIOu95D17wvJJC2a96ou9SGPIoA4Q2dMH5BMS9Z\n" + + "veq3AGgIBdJMF8Ft8PBE30R0cba1O5oQC0Eiscw7fkNnYGuSXagqNXdOBkHDN0fk\n" + + "VWFrxQRbxEVYUWc=\n" + + "=u2kL\n" + + "-----END PGP MESSAGE-----\n"; + byte[] fingerprint = Hex.decode("12C83F1E706F6308FE151A417743A1F033790E93E9978488D1DB378DA9930885"); + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(MSG)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PublicKeyEncSessionPacket pkesk = (PublicKeyEncSessionPacket) pIn.readPacket(); + isEquals("PKESK version mismatch", + PublicKeyEncSessionPacket.VERSION_6, pkesk.getVersion()); + isEncodingEqual("PKESK fingerprint mismatch", + fingerprint, pkesk.getKeyFingerprint()); + isEquals("PKESK derived key-id mismatch", + FingerprintUtil.keyIdFromV6Fingerprint(fingerprint), pkesk.getKeyID()); + isEquals("PKESK public key alg mismatch", + PublicKeyAlgorithmTags.X25519, pkesk.getAlgorithm()); + + SymmetricEncIntegrityPacket skesk = (SymmetricEncIntegrityPacket) pIn.readPacket(); + isEquals("SKESK version mismatch", + SymmetricEncIntegrityPacket.VERSION_2, skesk.getVersion()); + isEquals("SKESK sym alg mismatch", + SymmetricKeyAlgorithmTags.AES_256, skesk.getCipherAlgorithm()); + isEquals("SKESK AEAD alg mismatch", + AEADAlgorithmTags.OCB, skesk.getAeadAlgorithm()); + isEquals("SKESK chunk size mismatch", + 0x0e, skesk.getChunkSize()); + isEncodingEqual("SKESK salt mismatch", + Hex.decode("BBDE43D7BC2F2490B66BDEA8BBD4863C8A00E10D9D307E41312F59BDEAB70068"), skesk.getSalt()); + } + + public static void main(String[] args) + { + runTest(new EncryptedMessagePacketTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/FingerprintUtilTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/FingerprintUtilTest.java new file mode 100644 index 0000000000..970a33f4ce --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/FingerprintUtilTest.java @@ -0,0 +1,137 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.SimpleTest; + +public class FingerprintUtilTest + extends SimpleTest +{ + private void testKeyIdFromTooShortFails() + { + byte[] decoded = new byte[1]; + try + { + FingerprintUtil.keyIdFromV4Fingerprint(decoded); + fail("Expected exception"); + } + catch (IllegalArgumentException e) + { + // expected + } + } + + private void testV4KeyIdFromFingerprint() + { + String fingerprint = "1D018C772DF8C5EF86A1DCC9B4B509CB5936E03E"; + byte[] decoded = Hex.decode(fingerprint); + isEquals("v4 key-id from fingerprint mismatch", + -5425419407118114754L, FingerprintUtil.keyIdFromV4Fingerprint(decoded)); + } + + private void testV6KeyIdFromFingerprint() + { + String fingerprint = "cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc9"; + byte[] decoded = Hex.decode(fingerprint); + isEquals("v6 key-id from fingerprint mismatch", + -3812177997909612905L, FingerprintUtil.keyIdFromV6Fingerprint(decoded)); + } + + private void testLibrePgpKeyIdFromFingerprint() + { + // v6 key-ids are derived from fingerprints the same way as LibrePGP does + String fingerprint = "cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc9"; + byte[] decoded = Hex.decode(fingerprint); + isEquals("LibrePGP key-id from fingerprint mismatch", + -3812177997909612905L, FingerprintUtil.keyIdFromLibrePgpFingerprint(decoded)); + } + + private void testKeyIdFromFingerprint() + { + isEquals("v4 key-id from fingerprint mismatch", + -5425419407118114754L, FingerprintUtil.keyIdFromFingerprint( + 4, Hex.decode("1D018C772DF8C5EF86A1DCC9B4B509CB5936E03E"))); + isEquals("v5 key-id from fingerprint mismatch", + -3812177997909612905L, FingerprintUtil.keyIdFromFingerprint( + 5, Hex.decode("cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc9"))); + isEquals("v6 key-id from fingerprint mismatch", + -3812177997909612905L, FingerprintUtil.keyIdFromFingerprint( + 6, Hex.decode("cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc9"))); + } + + private void testLeftMostEqualsRightMostFor8Bytes() + { + byte[] bytes = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + isEquals( + FingerprintUtil.longFromLeftMostBytes(bytes), + FingerprintUtil.longFromRightMostBytes(bytes)); + byte[] b = new byte[8]; + FingerprintUtil.writeKeyID(FingerprintUtil.longFromLeftMostBytes(bytes), b); + isTrue(Arrays.areEqual(bytes, b)); + } + + private void testWriteKeyIdToBytes() + { + byte[] bytes = new byte[12]; + long keyId = 72623859790382856L; + FingerprintUtil.writeKeyID(keyId, bytes, 2); + isTrue(Arrays.areEqual( + new byte[] {0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00}, + bytes)); + + try + { + byte[] b = new byte[7]; + FingerprintUtil.writeKeyID(0, b); + fail("Expected IllegalArgumentException for too short byte array."); + } + catch (IllegalArgumentException e) + { + // Expected + } + } + + private void testPrettifyFingerprint() + { + isEquals("Prettified v4 fingerprint mismatch", + "1D01 8C77 2DF8 C5EF 86A1 DCC9 B4B5 09CB 5936 E03E", + FingerprintUtil.prettifyFingerprint(Hex.decode("1D018C772DF8C5EF86A1DCC9B4B509CB5936E03E"))); + isEquals("Prettified v5/v6 fingerprint mismatch", + "CB186C4F 0609A697 E4D52DFA 6C722B0C 1F1E27C1 8A56708F 6525EC27 BAD9ACC9", + FingerprintUtil.prettifyFingerprint(Hex.decode("cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc9"))); + } + + private void testPrettifyFingerprintReturnsHexForUnknownFormat() + { + String fp = "C0FFEE1DECAFF0"; + isEquals("Prettifying fingerprint with unknown format MUST return uppercase hex fingerprint", + fp, FingerprintUtil.prettifyFingerprint(Hex.decode(fp))); + } + + @Override + public String getName() + { + return "FingerprintUtilTest"; + } + + @Override + public void performTest() + throws Exception + { + testV4KeyIdFromFingerprint(); + testV6KeyIdFromFingerprint(); + testKeyIdFromTooShortFails(); + testLibrePgpKeyIdFromFingerprint(); + testLeftMostEqualsRightMostFor8Bytes(); + testWriteKeyIdToBytes(); + testKeyIdFromFingerprint(); + testPrettifyFingerprint(); + testPrettifyFingerprintReturnsHexForUnknownFormat(); + } + + public static void main(String[] args) + { + runTest(new FingerprintUtilTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/OCBEncryptedDataPacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/OCBEncryptedDataPacketTest.java new file mode 100644 index 0000000000..ceb7abfc96 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/OCBEncryptedDataPacketTest.java @@ -0,0 +1,79 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.*; +import org.bouncycastle.util.encoders.Hex; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +public class OCBEncryptedDataPacketTest + extends AbstractPacketTest +{ + @Override + public String getName() + { + return "OCBEncryptedDataPacketTest"; + } + + @Override + public void performTest() + throws Exception + { + parseTestVector(); + parseUnsupportedPacketVersion(); + } + + private void parseTestVector() + throws IOException + { + String testVector = "" + + "d45301090210c265ff63a61ed8af00fa" + + "43866be8eb9eef77241518a3d60e387b" + + "1e283bdd90e2233d17a937a595686024" + + "1d13ddfaccd2b724a491167631d1cd3e" + + "a74fe5d9e617f1f267d891fd338fddb2" + + "c66c025cde"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Hex.decode(testVector)); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + AEADEncDataPacket p = (AEADEncDataPacket) pIn.readPacket(); + isTrue("Packet length encoding format mismatch", p.hasNewPacketFormat()); + isEquals("Packet version mismatch", 1, p.getVersion()); + isEquals("Symmetric algorithm mitmatch", SymmetricKeyAlgorithmTags.AES_256, p.getAlgorithm()); + isEquals("AEAD encryption algorithm mismatch", AEADAlgorithmTags.OCB, p.getAEADAlgorithm()); + isEquals("Chunk size mismatch", 16, p.getChunkSize()); + isEncodingEqual("IV mismatch", Hex.decode("C265FF63A61ED8AF00FA43866BE8EB"), p.getIV()); + } + + private void parseUnsupportedPacketVersion() + throws IOException + { + // Test vector with modified packet version 99 + String testVector = "" + + "d45399090210c265ff63a61ed8af00fa" + + "43866be8eb9eef77241518a3d60e387b" + + "1e283bdd90e2233d17a937a595686024" + + "1d13ddfaccd2b724a491167631d1cd3e" + + "a74fe5d9e617f1f267d891fd338fddb2" + + "c66c025cde"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Hex.decode(testVector)); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + try + { + pIn.readPacket(); + fail("Expected UnsupportedPacketVersionException for unsupported version 99"); + } + catch (UnsupportedPacketVersionException e) + { + // expected + } + } + + public static void main(String[] args) + { + runTest(new OCBEncryptedDataPacketTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/OnePassSignaturePacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/OnePassSignaturePacketTest.java new file mode 100644 index 0000000000..651c307384 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/OnePassSignaturePacketTest.java @@ -0,0 +1,309 @@ +package org.bouncycastle.bcpg.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.SecureRandom; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.OnePassSignaturePacket; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.UnsupportedPacketVersionException; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.util.encoders.Hex; + +public class OnePassSignaturePacketTest + extends AbstractPacketTest +{ + + // Parse v6 OPS packet and compare its values to a known-good test vector + private void testParseV6OnePassSignaturePacket() + throws IOException + { + // Version 6 OnePassSignature packet + // extracted from https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-inline-signed-messag + byte[] encOPS = Hex.decode("c44606010a1b2076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbaccb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc901"); + // Issuer of the message + byte[] issuerFp = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + // Salt used to generate the signature + byte[] salt = Hex.decode("76495F50218890F7F5E2EE3C1822514F70500F551D86E5C921E404E34A53FBAC"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encOPS); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + // Parse and compare the OnePassSignature packet + OnePassSignaturePacket ops = (OnePassSignaturePacket) pIn.readPacket(); + isEquals("OPS packet MUST be of version 6", + OnePassSignaturePacket.VERSION_6, ops.getVersion()); + isEncodingEqual("OPS packet issuer fingerprint mismatch", + issuerFp, ops.getFingerprint()); + isTrue("OPS packet key-ID mismatch", + // key-ID are the first 8 octets of the fingerprint + // -DM Hex.toHexString + Hex.toHexString(issuerFp).startsWith(Long.toHexString(ops.getKeyID()))); + isEncodingEqual("OPS packet salt mismatch", + salt, ops.getSalt()); + isTrue("OPS packet isContaining mismatch", + ops.isContaining()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, true); + ops.encode(pOut); + pOut.close(); + + isEncodingEqual("OPS Packet encoding mismatch", encOPS, bOut.toByteArray()); + } + + private void roundtripV3Packet() + throws IOException + { + OnePassSignaturePacket before = new OnePassSignaturePacket( + PGPSignature.BINARY_DOCUMENT, + HashAlgorithmTags.SHA256, + PublicKeyAlgorithmTags.RSA_GENERAL, + 123L, + true); + + isEquals("Expected OPS version 3", + OnePassSignaturePacket.VERSION_3, before.getVersion()); + isEquals("Signature type mismatch", + PGPSignature.BINARY_DOCUMENT, before.getSignatureType()); + isEquals("Hash Algorithm mismatch", + HashAlgorithmTags.SHA256, before.getHashAlgorithm()); + isEquals("Pulic Key Algorithm mismatch", + PublicKeyAlgorithmTags.RSA_GENERAL, before.getKeyAlgorithm()); + isEquals("Key-ID mismatch", + 123L, before.getKeyID()); + isFalse("OPS is expected to be non-containing", + before.isContaining()); + isNull("OPS v3 MUST NOT have a fingerprint", + before.getFingerprint()); + isNull("OPS v3 MUST NOT have salt", + before.getSalt()); + + for (int idx = 0; idx != 2; idx++) + { + boolean newTypeIdFormat = (idx == 0) ? true : false; + + // round-trip the packet by encoding and decoding it + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, newTypeIdFormat); + before.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + OnePassSignaturePacket after = (OnePassSignaturePacket) pIn.readPacket(); + + isEquals("round-tripped OPS version mismatch", + before.getVersion(), after.getVersion()); + isEquals("round-tripped OPS signature type mismatch", + before.getSignatureType(), after.getSignatureType()); + isEquals("round-tripped OPS hash algorithm mismatch", + before.getHashAlgorithm(), after.getHashAlgorithm()); + isEquals("round-tripped OPS public key algorithm mismatch", + before.getKeyAlgorithm(), after.getKeyAlgorithm()); + isEquals("round-tripped OPS key-id mismatch", + before.getKeyID(), after.getKeyID()); + isEquals("round-tripped OPS nested flag mismatch", + before.isContaining(), after.isContaining()); + isNull("round-tripped OPS v3 MUST NOT have fingerprint", + after.getFingerprint()); + isNull("round-tripped OPS v3 MUST NOT have salt", + after.getSalt()); + + if (before.hasNewPacketFormat() && newTypeIdFormat) + { + isEncodingEqual(before, after); + } + } + } + + private void roundtripV6Packet() + throws IOException + { + byte[] salt = new byte[32]; + byte[] fingerprint = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + long keyID = FingerprintUtil.keyIdFromV6Fingerprint(fingerprint); + + new SecureRandom().nextBytes(salt); + OnePassSignaturePacket before = new OnePassSignaturePacket( + PGPSignature.CANONICAL_TEXT_DOCUMENT, + HashAlgorithmTags.SHA512, + PublicKeyAlgorithmTags.EDDSA_LEGACY, + salt, + fingerprint, + false); + + isEquals("Expected OPS version 6", + OnePassSignaturePacket.VERSION_6, before.getVersion()); + isEquals("Signature type mismatch", + PGPSignature.CANONICAL_TEXT_DOCUMENT, before.getSignatureType()); + isEquals("Hash algorithm mismatch", + HashAlgorithmTags.SHA512, before.getHashAlgorithm()); + isEquals("Public key algorithm mismatch", + PublicKeyAlgorithmTags.EDDSA_LEGACY, before.getKeyAlgorithm()); + isEncodingEqual("Salt mismatch", + salt, before.getSalt()); + isEncodingEqual("Fingerprint mismatch", + fingerprint, before.getFingerprint()); + isEquals("Derived key-ID mismatch", + keyID, before.getKeyID()); + isTrue("non-nested OPS is expected to be containing", + before.isContaining()); + + for (int idx = 0; idx != 2; idx++) + { + boolean newTypeIdFormat = (idx == 0) ? true : false; + + // round-trip the packet by encoding and decoding it + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, newTypeIdFormat); + before.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + OnePassSignaturePacket after = (OnePassSignaturePacket) pIn.readPacket(); + + isEquals("round-tripped OPS version mismatch", + before.getVersion(), after.getVersion()); + isEquals("round-tripped OPS signature type mismatch", + before.getSignatureType(), after.getSignatureType()); + isEquals("round-tripped OPS hash algorithm mismatch", + before.getHashAlgorithm(), after.getHashAlgorithm()); + isEquals("round-tripped OPS public key algorithm mismatch", + before.getKeyAlgorithm(), after.getKeyAlgorithm()); + isEquals("round-tripped OPS key-id mismatch", + before.getKeyID(), after.getKeyID()); + isEquals("round-tripped OPS nested flag mismatch", + before.isContaining(), after.isContaining()); + isEncodingEqual("round-tripped OPS fingerprint mismatch", + before.getFingerprint(), after.getFingerprint()); + isEncodingEqual("round-tripped OPS salt mismatch", + before.getSalt(), after.getSalt()); + + if (before.hasNewPacketFormat() && newTypeIdFormat) + { + isEncodingEqual(before, after); + } + } + } + + private void roundtripV6PacketWithZeroLengthSalt() + throws IOException + { + byte[] salt = new byte[0]; + byte[] fingerprint = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + + OnePassSignaturePacket before = new OnePassSignaturePacket( + PGPSignature.CANONICAL_TEXT_DOCUMENT, + HashAlgorithmTags.SHA512, + PublicKeyAlgorithmTags.EDDSA_LEGACY, + salt, + fingerprint, + false); + + isEncodingEqual("Salt mismatch", + salt, before.getSalt()); + + for (int idx = 0; idx != 2; idx++) + { + boolean newTypeIdFormat = (idx == 0) ? true : false; + + // round-trip the packet by encoding and decoding it + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, newTypeIdFormat); + before.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + OnePassSignaturePacket after = (OnePassSignaturePacket) pIn.readPacket(); + + isEquals("round-tripped OPS version mismatch", + before.getVersion(), after.getVersion()); + isEquals("round-tripped OPS signature type mismatch", + before.getSignatureType(), after.getSignatureType()); + isEquals("round-tripped OPS hash algorithm mismatch", + before.getHashAlgorithm(), after.getHashAlgorithm()); + isEquals("round-tripped OPS public key algorithm mismatch", + before.getKeyAlgorithm(), after.getKeyAlgorithm()); + isEquals("round-tripped OPS key-id mismatch", + before.getKeyID(), after.getKeyID()); + isEquals("round-tripped OPS nested flag mismatch", + before.isContaining(), after.isContaining()); + isEncodingEqual("round-tripped OPS fingerprint mismatch", + before.getFingerprint(), after.getFingerprint()); + isEncodingEqual("round-tripped OPS salt mismatch", + before.getSalt(), after.getSalt()); + } + } + + private void parsingOfPacketWithUnknownVersionFails() + { + // Version 0x99 OnePassSignature packet + byte[] encOPS = Hex.decode("c44699010a1b2076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbaccb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc901"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encOPS); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + try + { + pIn.readPacket(); + fail("Expected UnsupportedPacketVersionException"); + } + catch (IOException e) + { + fail("Expected UnsupportedPacketVersionException", e); + } + catch (UnsupportedPacketVersionException e) + { + // expected + } + } + + private void parsingOfPacketWithTruncatedFingerprintFails() + { + // Version 6 OnePassSignature packet with truncated fingerprint field (20 bytes instead of 32) + // This error would happen, if a v6 OPS packet was generated with a v4 fingerprint. + // extracted from https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-inline-signed-messag + byte[] encOPS = Hex.decode("c44606010a1b2076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbaccb186c4f0609a697e4d52dfa6c722b0c1f1e27c101"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encOPS); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + try + { + pIn.readPacket(); + fail("Expected IOException"); + } + catch (IOException e) + { + // expected + } + } + + @Override + public String getName() + { + return "OnePassSignaturePacketTest"; + } + + @Override + public void performTest() + throws Exception + { + testParseV6OnePassSignaturePacket(); + roundtripV3Packet(); + roundtripV6Packet(); + parsingOfPacketWithUnknownVersionFails(); + parsingOfPacketWithTruncatedFingerprintFails(); + roundtripV6PacketWithZeroLengthSalt(); + } + + public static void main(String[] args) + { + runTest(new OnePassSignaturePacketTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/OpenPgpMessageTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/OpenPgpMessageTest.java new file mode 100644 index 0000000000..8272a8c524 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/OpenPgpMessageTest.java @@ -0,0 +1,183 @@ +package org.bouncycastle.bcpg.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.LiteralDataPacket; +import org.bouncycastle.bcpg.OnePassSignaturePacket; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.SignaturePacket; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; +import org.bouncycastle.bcpg.sig.SignatureCreationTime; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class OpenPgpMessageTest + extends AbstractPacketTest +{ + + /* + Inline-signed message using a version 6 signature + see https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-inline-signed-messag + */ + public static final String INLINE_SIGNED = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "xEYGAQobIHZJX1AhiJD39eLuPBgiUU9wUA9VHYblySHkBONKU/usyxhsTwYJppfk\n" + + "1S36bHIrDB8eJ8GKVnCPZSXsJ7rZrMkBy0p1AAAAAABXaGF0IHdlIG5lZWQgZnJv\n" + + "bSB0aGUgZ3JvY2VyeSBzdG9yZToKCi0gdG9mdQotIHZlZ2V0YWJsZXMKLSBub29k\n" + + "bGVzCsKYBgEbCgAAACkFgmOYo2MiIQbLGGxPBgmml+TVLfpscisMHx4nwYpWcI9l\n" + + "JewnutmsyQAAAABpNiB2SV9QIYiQ9/Xi7jwYIlFPcFAPVR2G5ckh5ATjSlP7rCfQ\n" + + "b7gKqPxbyxbhljGygHQPnqau1eBzrQD5QVplPEDnemrnfmkrpx0GmhCfokxYz9jj\n" + + "FtCgazStmsuOXF9SFQE=\n" + + "-----END PGP MESSAGE-----"; + + /* + Cleartext-signed message using a version 6 signature + see https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-cleartext-signed-mes + */ + public static final String CLEARTEXT_SIGNED = "-----BEGIN PGP SIGNED MESSAGE-----\n" + + "\n" + + "What we need from the grocery store:\n" + + "\n" + + "- - tofu\n" + + "- - vegetables\n" + + "- - noodles\n" + + "\n" + + "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wpgGARsKAAAAKQWCY5ijYyIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAGk2IHZJX1AhiJD39eLuPBgiUU9wUA9VHYblySHkBONKU/usJ9BvuAqo\n" + + "/FvLFuGWMbKAdA+epq7V4HOtAPlBWmU8QOd6aud+aSunHQaaEJ+iTFjP2OMW0KBr\n" + + "NK2ay45cX1IVAQ==\n" + + "-----END PGP SIGNATURE-----"; + + // Content of the message's LiteralData packet + public static final String CONTENT = "What we need from the grocery store:\n" + + "\n" + + "- tofu\n" + + "- vegetables\n" + + "- noodles\n"; + // Issuer of the message + public static byte[] ISSUER = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + // Salt used to generate the signature + public static byte[] SALT = Hex.decode("76495F50218890F7F5E2EE3C1822514F70500F551D86E5C921E404E34A53FBAC"); + + + private void testParseV6CleartextSignedMessage() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(CLEARTEXT_SIGNED)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + + isNull("The ASCII armored input stream MUST NOT hallucinate headers where there are non", + aIn.getArmorHeaders()); // We do not have any header lines after the armor header + + // Parse and compare literal data + ByteArrayOutputStream litOut = new ByteArrayOutputStream(); + while (aIn.isClearText()) + { + litOut.write(aIn.read()); + } + String c = litOut.toString(); + isEquals("Mismatching content of the cleartext-signed test message", + CONTENT, c.substring(0, c.length() - 2)); // compare ignoring last '\n' + + BCPGInputStream pIn = new BCPGInputStream(aIn); + // parse and compare signature + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + compareSignature(sig); + } + + private void testParseV6InlineSignedMessage() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(INLINE_SIGNED)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + + // Parse and compare the OnePassSignature packet + OnePassSignaturePacket ops = (OnePassSignaturePacket) pIn.readPacket(); + isEquals("OPS packet MUST be of version 6", + OnePassSignaturePacket.VERSION_6, ops.getVersion()); + isEncodingEqual("OPS packet issuer fingerprint mismatch", + ISSUER, ops.getFingerprint()); + isEncodingEqual("OPS packet salt mismatch", + SALT, ops.getSalt()); + isTrue("OPS packet isContaining mismatch", + ops.isContaining()); + + // Parse and compare the LiteralData packet + LiteralDataPacket lit = (LiteralDataPacket) pIn.readPacket(); + compareLiteralData(lit); + + // Parse and compare the Signature packet + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + compareSignature(sig); + } + + + private void compareLiteralData(LiteralDataPacket lit) + throws IOException + { + isEquals("LiteralDataPacket format mismatch", + PGPLiteralData.UTF8, lit.getFormat()); + isEquals("LiteralDataPacket mod data mismatch", + 0, lit.getModificationTime()); + byte[] content = lit.getInputStream().readAll(); + String contentString = Strings.fromUTF8ByteArray(content); + isEquals("LiteralDataPacket content mismatch", + CONTENT, contentString); + } + + private void compareSignature(SignaturePacket sig) + { + isEquals("SignaturePacket version mismatch", + SignaturePacket.VERSION_6, sig.getVersion()); + isEquals("SignaturePacket signature type mismatch", + PGPSignature.CANONICAL_TEXT_DOCUMENT, sig.getSignatureType()); + isEquals("SignaturePacket key algorithm mismatch", + PublicKeyAlgorithmTags.Ed25519, sig.getKeyAlgorithm()); + isEquals("SignaturePacket hash algorithm mismatch", + HashAlgorithmTags.SHA512, sig.getHashAlgorithm()); + isTrue("SignaturePacket salt mismatch", + Arrays.areEqual(SALT, sig.getSalt())); + // hashed subpackets + isEquals("SignaturePacket number of hashed packets mismatch", + 2, sig.getHashedSubPackets().length); + SignatureCreationTime creationTimeSubpacket = (SignatureCreationTime) sig.getHashedSubPackets()[0]; + isEquals("SignaturePacket signature creation time mismatch", + 1670947683000L, creationTimeSubpacket.getTime().getTime()); + IssuerFingerprint issuerSubpacket = (IssuerFingerprint) sig.getHashedSubPackets()[1]; + isEncodingEqual("SignaturePacket issuer fingerprint mismatch", + ISSUER, issuerSubpacket.getFingerprint()); + // unhashed subpackets + isEquals("SignaturePacket number of unhashed packets mismatch", + 0, sig.getUnhashedSubPackets().length); + } + + @Override + public String getName() + { + return "OpenPgpMessageTest"; + } + + @Override + public void performTest() + throws Exception + { + testParseV6CleartextSignedMessage(); + testParseV6InlineSignedMessage(); + } + + public static void main(String[] args) + { + runTest(new OpenPgpMessageTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/PacketDumpUtil.java b/pg/src/test/java/org/bouncycastle/bcpg/test/PacketDumpUtil.java new file mode 100644 index 0000000000..e4c16364ff --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/PacketDumpUtil.java @@ -0,0 +1,35 @@ +package org.bouncycastle.bcpg.test; + +import java.io.IOException; + +import org.bouncycastle.bcpg.ContainedPacket; +import org.bouncycastle.test.DumpUtil; + +public class PacketDumpUtil +{ + /** + * Return a formatted hex dump of the packet encoding of the given packet. + * @param packet packet + * @return formatted hex dump + * @throws IOException if an exception happens during packet encoding + */ + public static String hexdump(ContainedPacket packet) + throws IOException + { + return DumpUtil.hexdump(packet.getEncoded()); + } + + /** + * Return a formatted hex dump of the packet encoding of the given packet. + * If startIndent is non-zero, the hex dump is shifted right by the startIndent octets. + * @param startIndent shift the encodings octet stream by a number of bytes + * @param packet packet + * @return formatted hex dump + * @throws IOException if an exception happens during packet encoding + */ + public static String hexdump(int startIndent, ContainedPacket packet) + throws IOException + { + return DumpUtil.hexdump(startIndent, packet.getEncoded()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/SignaturePacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/SignaturePacketTest.java new file mode 100644 index 0000000000..c6fc35620b --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/SignaturePacketTest.java @@ -0,0 +1,163 @@ +package org.bouncycastle.bcpg.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.MPInteger; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.SignaturePacket; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; +import org.bouncycastle.bcpg.sig.IssuerKeyID; +import org.bouncycastle.bcpg.sig.SignatureCreationTime; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.util.encoders.Hex; + +public class SignaturePacketTest + extends AbstractPacketTest +{ + @Override + public String getName() + { + return "SignaturePacketTest"; + } + + @Override + public void performTest() + throws Exception + { + testParseV6Signature(); + testParseV4Ed25519LegacySignature(); + testParseUnknownVersionSignaturePacket(); + } + + private void testParseV6Signature() + throws IOException + { + // Hex-encoded OpenPGP v6 signature packet + // Extracted from https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-inline-signed-messag + byte[] encSigPacket = Hex.decode("c29806011b0a0000002905826398a363222106cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc90000000069362076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbac27d06fb80aa8fc5bcb16e19631b280740f9ea6aed5e073ad00f9415a653c40e77a6ae77e692ba71d069a109fa24c58cfd8e316d0a06b34ad9acb8e5c5f521501"); + // Issuer of the message + byte[] issuerFP = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + // Salt used to generate the signature + byte[] salt = Hex.decode("76495F50218890F7F5E2EE3C1822514F70500F551D86E5C921E404E34A53FBAC"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encSigPacket); + BCPGInputStream pIn = new BCPGInputStream(bIn); + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + + isEquals("SignaturePacket version mismatch", + SignaturePacket.VERSION_6, sig.getVersion()); + isEquals("SignaturePacket signature type mismatch", + PGPSignature.CANONICAL_TEXT_DOCUMENT, sig.getSignatureType()); + isEquals("SignaturePacket key algorithm mismatch", + PublicKeyAlgorithmTags.Ed25519, sig.getKeyAlgorithm()); + isEquals("SignaturePacket hash algorithm mismatch", + HashAlgorithmTags.SHA512, sig.getHashAlgorithm()); + isEncodingEqual("SignaturePacket salt mismatch", + salt, sig.getSalt()); + // hashed subpackets + isEquals("SignaturePacket number of hashed packets mismatch", + 2, sig.getHashedSubPackets().length); + SignatureCreationTime creationTimeSubpacket = (SignatureCreationTime) sig.getHashedSubPackets()[0]; + isEquals("SignaturePacket signature creation time mismatch", + 1670947683000L, creationTimeSubpacket.getTime().getTime()); + IssuerFingerprint issuerSubpacket = (IssuerFingerprint) sig.getHashedSubPackets()[1]; + isEncodingEqual("SignaturePacket issuer fingerprint mismatch", + issuerFP, issuerSubpacket.getFingerprint()); + // unhashed subpackets + isEquals("SignaturePacket number of unhashed packets mismatch", + 0, sig.getUnhashedSubPackets().length); + + // v6 Ed25519 signatures (not LEGACY) do not use MPI encoding for the raw signature + // but rather encode into octet strings + isNull("Signature MPI encoding MUST be null", + sig.getSignature()); + isEncodingEqual("Signature octet string encoding mismatch", + Hex.decode("27d06fb80aa8fc5bcb16e19631b280740f9ea6aed5e073ad00f9415a653c40e77a6ae77e692ba71d069a109fa24c58cfd8e316d0a06b34ad9acb8e5c5f521501"), + sig.getSignatureBytes()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, true); + sig.encode(pOut); + pOut.close(); + + isEncodingEqual("SignaturePacket encoding mismatch", encSigPacket, bOut.toByteArray()); + } + + private void testParseV4Ed25519LegacySignature() + throws IOException + { + // Hex-encoded v4 test signature + // see https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-v4-ed25519legacy-sig + byte[] encSigPacket = Hex.decode("885e040016080006050255f95f95000a09108cfde12197965a9af62200ff56f90cca98e2102637bd983fdb16c131dfd27ed82bf4dde5606e0d756aed33660100d09c4fa11527f038e0f57f2201d82f2ea2c9033265fa6ceb489e854bae61b404"); + ByteArrayInputStream bIn = new ByteArrayInputStream(encSigPacket); + BCPGInputStream pIn = new BCPGInputStream(bIn); + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + + isEquals("SignaturePacket version mismatch", + SignaturePacket.VERSION_4, sig.getVersion()); + isEquals("SignaturePacket signature type mismatch", + PGPSignature.BINARY_DOCUMENT, sig.getSignatureType()); + isEquals("SignaturePacket public key algorithm mismatch", + PublicKeyAlgorithmTags.EDDSA_LEGACY, sig.getKeyAlgorithm()); + isEquals("SignaturePacket hash algorithm mismatch", + HashAlgorithmTags.SHA256, sig.getHashAlgorithm()); + isEquals("SignaturePacket number of hashed subpackets mismatch", + 1, sig.getHashedSubPackets().length); + SignatureCreationTime creationTimeSubpacket = (SignatureCreationTime) sig.getHashedSubPackets()[0]; + isEquals("SignaturePacket creationTime mismatch", + 1442406293000L, creationTimeSubpacket.getTime().getTime()); + isEquals("SignaturePacket number of unhashed subpackets mismatch", + 1, sig.getUnhashedSubPackets().length); + IssuerKeyID issuerKeyID = (IssuerKeyID) sig.getUnhashedSubPackets()[0]; + isEquals("SignaturePacket issuer key-id mismatch", + -8287220204898461030L, issuerKeyID.getKeyID()); + + // EDDSA_LEGACY uses MPI encoding for the raw signature value + MPInteger[] mpInts = sig.getSignature(); + isEquals("Signature MPI encoding mismatch", + 2, mpInts.length); + isEncodingEqual("Signature MPI encoding in signatureBytes field mismatch", + Hex.decode("00ff56f90cca98e2102637bd983fdb16c131dfd27ed82bf4dde5606e0d756aed33660100d09c4fa11527f038e0f57f2201d82f2ea2c9033265fa6ceb489e854bae61b404"), + sig.getSignatureBytes()); + + // v4 signatures do not have salt + isNull("Salt MUST be null", sig.getSalt()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, false); + sig.encode(pOut); + pOut.close(); + + isEncodingEqual("SignaturePacket encoding mismatch", + encSigPacket, bOut.toByteArray()); + } + + private void testParseUnknownVersionSignaturePacket() + { + // Hex-encoded signature with version 0x99 + byte[] encSigPacket = Hex.decode("885e990016080006050255f95f95000a09108cfde12197965a9af62200ff56f90cca98e2102637bd983fdb16c131dfd27ed82bf4dde5606e0d756aed33660100d09c4fa11527f038e0f57f2201d82f2ea2c9033265fa6ceb489e854bae61b404"); + ByteArrayInputStream bIn = new ByteArrayInputStream(encSigPacket); + final BCPGInputStream pIn = new BCPGInputStream(bIn); + Exception ex = testException("unsupported version: 153", + "UnsupportedPacketVersionException", + new TestExceptionOperation() + { + public void operation() + throws Exception + { + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + } + }); + isNotNull("Parsing SignaturePacket of version 0x99 MUST throw UnsupportedPacketVersionException.", ex); + } + + public static void main(String[] args) + { + runTest(new SignaturePacketTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/SignatureSubpacketsTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/SignatureSubpacketsTest.java new file mode 100644 index 0000000000..05df687b77 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/SignatureSubpacketsTest.java @@ -0,0 +1,54 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.LibrePGPPreferredEncryptionModes; +import org.bouncycastle.util.Arrays; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class SignatureSubpacketsTest + extends AbstractPacketTest +{ + @Override + public String getName() + { + return "SignatureSubpacketsTest"; + } + + @Override + public void performTest() + throws Exception + { + testLibrePGPPreferredEncryptionModesSubpacket(); + } + + private void testLibrePGPPreferredEncryptionModesSubpacket() + throws IOException + { + int[] algorithms = new int[] {AEADAlgorithmTags.EAX, AEADAlgorithmTags.OCB}; + LibrePGPPreferredEncryptionModes encModes = new LibrePGPPreferredEncryptionModes( + false, algorithms); + + isTrue("Encryption Modes encoding mismatch", + Arrays.areEqual(algorithms, encModes.getPreferences())); + isFalse("Mismatch in critical flag", encModes.isCritical()); + + // encode to byte array and check correctness + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + encModes.encode(bOut); + + isEncodingEqual("Packet encoding mismatch", new byte[]{ + 3, // length + SignatureSubpacketTags.LIBREPGP_PREFERRED_ENCRYPTION_MODES, + AEADAlgorithmTags.EAX, + AEADAlgorithmTags.OCB + }, bOut.toByteArray()); + } + + public static void main(String[] args) + { + runTest(new SignatureSubpacketsTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/TimeEncodingTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/TimeEncodingTest.java new file mode 100644 index 0000000000..483d3b5b1b --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/TimeEncodingTest.java @@ -0,0 +1,70 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.UnknownBCPGKey; +import org.bouncycastle.bcpg.sig.KeyExpirationTime; +import org.bouncycastle.util.test.SimpleTest; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Date; + +public class TimeEncodingTest + extends SimpleTest +{ + @Override + public String getName() + { + return "UtilsTest"; + } + + @Override + public void performTest() + throws Exception + { + testRoundtrippingLargeUnsignedInt(); + testKeyWithLargeCreationTime(); + } + + private void testRoundtrippingLargeUnsignedInt() + { + // Integer.MAX_VALUE < large < 0xffffffff + long large = 2523592696L; // fits a 32-bit *unsigned* int, but overflows signed int + // KeyExpirationTime packs the time into 4 octets + KeyExpirationTime kexp = new KeyExpirationTime(false, large); + // getTime() parses the time from 4 octets + isEquals("Roundtripped unsigned int mismatches before packet parser pass", large, kexp.getTime()); + + // To be safe, do an additional packet encode/decode roundtrip + KeyExpirationTime pKexp = new KeyExpirationTime(kexp.isCritical(), kexp.isLongLength(), kexp.getData()); + isEquals("Roundtripped unsigned int mismatches after packet parser pass", large, pKexp.getTime()); + } + + private void testKeyWithLargeCreationTime() + throws IOException + { + long maxSeconds = 0xFFFFFFFEL; // Fits 32 unsigned int, but not signed int + Date maxPGPDate = new Date(maxSeconds * 1000); + UnknownBCPGKey k = new UnknownBCPGKey(1, new byte[]{1}); // dummy + PublicKeyPacket p = new PublicKeyPacket(PublicKeyPacket.VERSION_6, 99, maxPGPDate, k); + isEquals("Key creation time mismatches before encoding", maxPGPDate, p.getTime()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.CURRENT); + p.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PublicKeyPacket parsed = (PublicKeyPacket) pIn.readPacket(); + isEquals("Key creation time mismatches after encoding", maxPGPDate, parsed.getTime()); + } + + public static void main(String[] args) + { + runTest(new TimeEncodingTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/UnknownPublicKeyPacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/UnknownPublicKeyPacketTest.java new file mode 100644 index 0000000000..f45a7dae69 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/UnknownPublicKeyPacketTest.java @@ -0,0 +1,68 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.UnknownBCPGKey; +import org.bouncycastle.util.encoders.Hex; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +public class UnknownPublicKeyPacketTest + extends AbstractPacketTest +{ + private final String[] testVectors = {"c61406665ef5f3630000000a00010203040506070809", "c61405665ef5f3630000000a00010203040506070809"}; + private final int[] versions = {PublicKeyPacket.VERSION_6, PublicKeyPacket.LIBREPGP_5}; + + @Override + public String getName() + { + return "UnknownPublicKeyPacketTest"; + } + + @Override + public void performTest() + throws Exception + { + parseUnknownPublicKey(); + } + + private void parseUnknownPublicKey() + throws ParseException, IOException + { + SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); + parser.setTimeZone(TimeZone.getTimeZone("UTC")); + + for (int i = 0; i < testVectors.length; i++) + { + String testVector = testVectors[i]; + byte[] rawKey = new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}; + Date creationTime = parser.parse("2024-06-04 11:09:39 UTC"); + + PublicKeyPacket p = new PublicKeyPacket( + versions[i], + 99, + creationTime, + new UnknownBCPGKey(10, rawKey)); + isEncodingEqual("Encoding mismatch", Hex.decode(testVector), p.getEncoded(PacketFormat.CURRENT)); + + ByteArrayInputStream bIn = new ByteArrayInputStream(Hex.decode(testVector)); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PublicKeyPacket parsed = (PublicKeyPacket) pIn.readPacket(); + isEquals("Packet version mismatch", versions[i], parsed.getVersion()); + isEquals("Public key algorithm mismatch", 99, parsed.getAlgorithm()); + isEquals("Creation time mismatch", creationTime, parsed.getTime()); + isEncodingEqual("Raw key encoding mismatch", rawKey, parsed.getKey().getEncoded()); + } + } + + public static void main(String[] args) + { + runTest(new UnknownPublicKeyPacketTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/UnknownSecretKeyPacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/UnknownSecretKeyPacketTest.java new file mode 100644 index 0000000000..2451fc9bd4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/UnknownSecretKeyPacketTest.java @@ -0,0 +1,77 @@ +package org.bouncycastle.bcpg.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Date; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.UnknownBCPGKey; +import org.bouncycastle.util.encoders.Hex; + +public class UnknownSecretKeyPacketTest + extends AbstractPacketTest +{ + @Override + public String getName() + { + return "UnknownSecretKeyPacketTest"; + } + + @Override + public void performTest() + throws Exception + { + parseUnknownUnencryptedSecretKey(); + } + + private void parseUnknownUnencryptedSecretKey() + throws IOException + { + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.LIBREPGP_5 : PublicKeyPacket.VERSION_6; + Date creationTime = new Date((new Date().getTime() / 1000) * 1000); + SecretKeyPacket sk = new SecretKeyPacket( + new PublicKeyPacket( + version, + 99, + creationTime, + new UnknownBCPGKey(3, Hex.decode("c0ffee"))), + SymmetricKeyAlgorithmTags.NULL, + null, + null, + Hex.decode("0decaf")); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + sk.encode(pOut); + pOut.close(); + aOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + SecretKeyPacket p = (SecretKeyPacket) pIn.readPacket(); + + isEquals("Packet version mismatch", version, p.getPublicKeyPacket().getVersion()); + isEquals("Algorithm mismatch", 99, p.getPublicKeyPacket().getAlgorithm()); + isEncodingEqual("Public key encoding mismatch", Hex.decode("c0ffee"), p.getPublicKeyPacket().getKey().getEncoded()); + isEncodingEqual("Secret key encoding mismatch", Hex.decode("0decaf"), p.getSecretKeyData()); + isEncodingEqual("Packet encoding mismatch", sk.getEncoded(PacketFormat.CURRENT), p.getEncoded(PacketFormat.CURRENT)); + } + } + + public static void main(String[] args) + { + runTest(new UnknownSecretKeyPacketTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/openpgp/OpenPGPTestKeys.java b/pg/src/test/java/org/bouncycastle/openpgp/OpenPGPTestKeys.java new file mode 100644 index 0000000000..28c19bd875 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/OpenPGPTestKeys.java @@ -0,0 +1,453 @@ +package org.bouncycastle.openpgp; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +public class OpenPGPTestKeys +{ + /** + * Alice's Ed25519 OpenPGP key. + * + * @see + * Alice's OpenPGP Secret Key Material + */ + public static final String ALICE_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Comment: Alice's OpenPGP Transferable Secret Key\n" + + "Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html\n" + + "\n" + + "lFgEXEcE6RYJKwYBBAHaRw8BAQdArjWwk3FAqyiFbFBKT4TzXcVBqPTB3gmzlC/U\n" + + "b7O1u10AAP9XBeW6lzGOLx7zHH9AsUDUTb2pggYGMzd0P3ulJ2AfvQ4RtCZBbGlj\n" + + "ZSBMb3ZlbGFjZSA8YWxpY2VAb3BlbnBncC5leGFtcGxlPoiQBBMWCAA4AhsDBQsJ\n" + + "CAcCBhUKCQgLAgQWAgMBAh4BAheAFiEE64W7X6M6deFelE5j8jFVDE9H444FAl2l\n" + + "nzoACgkQ8jFVDE9H447pKwD6A5xwUqIDprBzrHfahrImaYEZzncqb25vkLV2arYf\n" + + "a78A/R3AwtLQvjxwLDuzk4dUtUwvUYibL2sAHwj2kGaHnfICnF0EXEcE6RIKKwYB\n" + + "BAGXVQEFAQEHQEL/BiGtq0k84Km1wqQw2DIikVYrQrMttN8d7BPfnr4iAwEIBwAA\n" + + "/3/xFPG6U17rhTuq+07gmEvaFYKfxRB6sgAYiW6TMTpQEK6IeAQYFggAIBYhBOuF\n" + + "u1+jOnXhXpROY/IxVQxPR+OOBQJcRwTpAhsMAAoJEPIxVQxPR+OOWdABAMUdSzpM\n" + + "hzGs1O0RkWNQWbUzQ8nUOeD9wNbjE3zR+yfRAQDbYqvtWQKN4AQLTxVJN5X5AWyb\n" + + "Pnn+We1aTBhaGa86AQ==\n" + + "=n8OM\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + /** + * Alice's Ed25519 OpenPGP v4 certificate. + * + * @see + * Alice's OpenPGP Certificate + */ + public static final String ALICE_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "Comment: Alice's OpenPGP certificate\n" + + "Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html\n" + + "\n" + + "mDMEXEcE6RYJKwYBBAHaRw8BAQdArjWwk3FAqyiFbFBKT4TzXcVBqPTB3gmzlC/U\n" + + "b7O1u120JkFsaWNlIExvdmVsYWNlIDxhbGljZUBvcGVucGdwLmV4YW1wbGU+iJAE\n" + + "ExYIADgCGwMFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AWIQTrhbtfozp14V6UTmPy\n" + + "MVUMT0fjjgUCXaWfOgAKCRDyMVUMT0fjjukrAPoDnHBSogOmsHOsd9qGsiZpgRnO\n" + + "dypvbm+QtXZqth9rvwD9HcDC0tC+PHAsO7OTh1S1TC9RiJsvawAfCPaQZoed8gK4\n" + + "OARcRwTpEgorBgEEAZdVAQUBAQdAQv8GIa2rSTzgqbXCpDDYMiKRVitCsy203x3s\n" + + "E9+eviIDAQgHiHgEGBYIACAWIQTrhbtfozp14V6UTmPyMVUMT0fjjgUCXEcE6QIb\n" + + "DAAKCRDyMVUMT0fjjlnQAQDFHUs6TIcxrNTtEZFjUFm1M0PJ1Dng/cDW4xN80fsn\n" + + "0QEA22Kr7VkCjeAEC08VSTeV+QFsmz55/lntWkwYWhmvOgE=\n" + + "=iIGO\n" + + "-----END PGP PUBLIC KEY BLOCK-----"; + /** + * Alice's Ed25519 OpenPGP v4 revocation certificate. + * + * @see + * Alice's Revocation Certificate + */ + public static final String ALICE_REVOCATION_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "Comment: Alice's revocation certificate\n" + + "Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html\n" + + "\n" + + "iHgEIBYIACAWIQTrhbtfozp14V6UTmPyMVUMT0fjjgUCXaWkOwIdAAAKCRDyMVUM\n" + + "T0fjjoBlAQDA9ukZFKRFGCooVcVoDVmxTaHLUXlIg9TPh2f7zzI9KgD/SLNXUOaH\n" + + "O6TozOS7C9lwIHwwdHdAxgf5BzuhLT9iuAM=\n" + + "=Tm8h\n" + + "-----END PGP PUBLIC KEY BLOCK-----"; + + /** + * Bob's RSA-3072 OpenPGP v4 Secret Key Material. + * + * @see + * Bob's OpenPGP Secret Key Material + */ + public static final String BOB_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Comment: D1A6 6E1A 23B1 82C9 980F 788C FBFC C82A 015E 7330\n" + + "Comment: Bob Babbage \n" + + "\n" + + "xcSYBF2lnPIBDAC5cL9PQoQLTMuhjbYvb4Ncuuo0bfmgPRFywX53jPhoFf4Zg6mv\n" + + "/seOXpgecTdOcVttfzC8ycIKrt3aQTiwOG/ctaR4Bk/t6ayNFfdUNxHWk4WCKzdz\n" + + "/56fW2O0F23qIRd8UUJp5IIlN4RDdRCtdhVQIAuzvp2oVy/LaS2kxQoKvph/5pQ/\n" + + "5whqsyroEWDJoSV0yOb25B/iwk/pLUFoyhDG9bj0kIzDxrEqW+7Ba8nocQlecMF3\n" + + "X5KMN5kp2zraLv9dlBBpWW43XktjcCZgMy20SouraVma8Je/ECwUWYUiAZxLIlMv\n" + + "9CurEOtxUw6N3RdOtLmYZS9uEnn5y1UkF88o8Nku890uk6BrewFzJyLAx5wRZ4F0\n" + + "qV/yq36UWQ0JB/AUGhHVPdFf6pl6eaxBwT5GXvbBUibtf8YI2og5RsgTWtXfU7eb\n" + + "SGXrl5ZMpbA6mbfhd0R8aPxWfmDWiIOhBufhMCvUHh1sApMKVZnvIff9/0Dca3wb\n" + + "vLIwa3T4CyshfT0AEQEAAQAL/RZqbJW2IqQDCnJi4Ozm++gPqBPiX1RhTWSjwxfM\n" + + "cJKUZfzLj414rMKm6Jh1cwwGY9jekROhB9WmwaaKT8HtcIgrZNAlYzANGRCM4TLK\n" + + "3VskxfSwKKna8l+s+mZglqbAjUg3wmFuf9Tj2xcUZYmyRm1DEmcN2ZzpvRtHgX7z\n" + + "Wn1mAKUlSDJZSQks0zjuMNbupcpyJokdlkUg2+wBznBOTKzgMxVNC9b2g5/tMPUs\n" + + "hGGWmF1UH+7AHMTaS6dlmr2ZBIyogdnfUqdNg5sZwsxSNrbglKP4sqe7X61uEAIQ\n" + + "bD7rT3LonLbhkrj3I8wilUD8usIwt5IecoHhd9HziqZjRCc1BUBkboUEoyedbDV4\n" + + "i4qfsFZ6CEWoLuD5pW7dEp0M+WeuHXO164Rc+LnH6i1VQrpb1Okl4qO6ejIpIjBI\n" + + "1t3GshtUu/mwGBBxs60KBX5g77mFQ9lLCRj8lSYqOsHRKBhUp4qM869VA+fD0BRP\n" + + "fqPT0I9IH4Oa/A3jYJcg622GwQYA1LhnP208Waf6PkQSJ6kyr8ymY1yVh9VBE/g6\n" + + "fRDYA+pkqKnw9wfH2Qho3ysAA+OmVOX8Hldg+Pc0Zs0e5pCavb0En8iFLvTA0Q2E\n" + + "LR5rLue9uD7aFuKFU/VdcddY9Ww/vo4k5p/tVGp7F8RYCFn9rSjIWbfvvZi1q5Tx\n" + + "+akoZbga+4qQ4WYzB/obdX6SCmi6BndcQ1QdjCCQU6gpYx0MddVERbIp9+2SXDyL\n" + + "hpxjSyz+RGsZi/9UAshT4txP4+MZBgDfK3ZqtW+h2/eMRxkANqOJpxSjMyLO/FXN\n" + + "WxzTDYeWtHNYiAlOwlQZEPOydZFty9IVzzNFQCIUCGjQ/nNyhw7adSgUk3+BXEx/\n" + + "MyJPYY0BYuhLxLYcrfQ9nrhaVKxRJj25SVHj2ASsiwGJRZW4CC3uw40OYxfKEvNC\n" + + "mer/VxM3kg8qqGf9KUzJ1dVdAvjyx2Hz6jY2qWCyRQ6IMjWHyd43C4r3jxooYKUC\n" + + "YnstRQyb/gCSKahveSEjo07CiXMr88UGALwzEr3npFAsPW3osGaFLj49y1oRe11E\n" + + "he9gCHFm+fuzbXrWmdPjYU5/ZdqdojzDqfu4ThfnipknpVUM1o6MQqkjM896FHm8\n" + + "zbKVFSMhEP6DPHSCexMFrrSgN03PdwHTO6iBaIBBFqmGY01tmJ03SxvSpiBPON9P\n" + + "NVvy/6UZFedTq8A07OUAxO62YUSNtT5pmK2vzs3SAZJmbFbMh+NN204TRI72GlqT\n" + + "t5hcfkuv8hrmwPS/ZR6q312mKQ6w/1pqO9qizSFCb2IgQmFiYmFnZSA8Ym9iQG9w\n" + + "ZW5wZ3AuZXhhbXBsZT7CwQ4EEwEKADgCGwMFCwkIBwIGFQoJCAsCBBYCAwECHgEC\n" + + "F4AWIQTRpm4aI7GCyZgPeIz7/MgqAV5zMAUCXaWe+gAKCRD7/MgqAV5zMG9sC/9U\n" + + "2T3RrqEbw533FPNfEflhEVRIZ8gDXKM8hU6cqqEzCmzZT6xYTe6sv4y+PJBGXJFX\n" + + "yhj0g6FDkSyboM5litOcTupURObVqMgA/Y4UKERznm4fzzH9qek85c4ljtLyNufe\n" + + "doL2pp3vkGtn7eD0QFRaLLmnxPKQ/TlZKdLE1G3u8Uot8QHicaR6GnAdc5UXQJE3\n" + + "BiV7jZuDyWmZ1cUNwJkKL6oRtp+ZNDOQCrLNLecKHcgCqrpjSQG5oouba1I1Q6Vl\n" + + "sP44dhA1nkmLHtxlTOzpeHj4jnk1FaXmyasurrrI5CgU/L2Oi39DGKTH/A/cywDN\n" + + "4ZplIQ9zR8enkbXquUZvFDe+Xz+6xRXtb5MwQyWODB3nHw85HocLwRoIN9WdQEI+\n" + + "L8a/56AuOwhs8llkSuiITjR7r9SgKJC2WlAHl7E8lhJ3VDW3ELC56KH308d6mwOG\n" + + "ZRAqIAKzM1T5FGjMBhq7ZV0eqdEntBh3EcOIfj2M8rg1MzJv+0mHZOIjByawikbH\n" + + "xJgEXaWc8gEMANYwv1xsYyunXYK0X1vY/rP1NNPvhLyLIE7NpK90YNBj+xS1ldGD\n" + + "bUdZqZeef2xJe8gMQg05DoD1DF3GipZ0Ies65beh+d5hegb7N4pzh0LzrBrVNHar\n" + + "29b5ExdI7i4iYD5TO6Vr/qTUOiAN/byqELEzAb+L+b2DVz/RoCm4PIp1DU9ewcc2\n" + + "WB38Ofqut3nLYA5tqJ9XvAiEQme+qAVcM3ZFcaMt4I4dXhDZZNg+D9LiTWcxdUPB\n" + + "leu8iwDRjAgyAhPzpFp+nWoqWA81uIiULWD1Fj+IVoY3ZvgivoYOiEFBJ9lbb4te\n" + + "g9m5UT/AaVDTWuHzbspVlbiVe+qyB77C2daWzNyx6UYBPLOo4r0t0c91kbNE5lgj\n" + + "Z7xz6los0N1U8vq91EFSeQJoSQ62XWavYmlCLmdNT6BNfgh4icLsT7Vr1QMX9jzn\n" + + "JtTPxdXytSdHvpSpULsqJ016l0dtmONcK3z9mj5N5z0k1tg1AH970TGYOe2aUcSx\n" + + "IRDMXDOPyzEfjwARAQABAAv9F2CwsjS+Sjh1M1vegJbZjei4gF1HHpEM0K0PSXsp\n" + + "SfVvpR4AoSJ4He6CXSMWg0ot8XKtDuZoV9jnJaES5UL9pMAD7JwIOqZm/DYVJM5h\n" + + "OASCh1c356/wSbFbzRHPtUdZO9Q30WFNJM5pHbCJPjtNoRmRGkf71RxtvHBzy7np\n" + + "Ga+W6U/NVKHw0i0CYwMI0YlKDakYW3Pm+QL+gHZFvngGweTod0f9l2VLLAmeQR/c\n" + + "+EZs7lNumhuZ8mXcwhUc9JQIhOkpO+wreDysEFkAcsKbkQP3UDUsA1gFx9pbMzT0\n" + + "tr1oZq2a4QBtxShHzP/ph7KLpN+6qtjks3xB/yjTgaGmtrwM8tSe0wD1RwXS+/1o\n" + + "BHpXTnQ7TfeOGUAu4KCoOQLv6ELpKWbRBLWuiPwMdbGpvVFALO8+kvKAg9/r+/ny\n" + + "zM2GQHY+J3Jh5JxPiJnHfXNZjIKLbFbIPdSKNyJBuazXW8xIa//mEHMI5OcvsZBK\n" + + "clAIp7LXzjEjKXIwHwDcTn9pBgDpdOKTHOtJ3JUKx0rWVsDH6wq6iKV/FTVSY5jl\n" + + "zN+puOEsskF1Lfxn9JsJihAVO3yNsp6RvkKtyNlFazaCVKtDAmkjoh60XNxcNRqr\n" + + "gCnwdpbgdHP6v/hvZY54ZaJjz6L2e8unNEkYLxDt8cmAyGPgH2XgL7giHIp9jrsQ\n" + + "aS381gnYwNX6wE1aEikgtY91nqJjwPlibF9avSyYQoMtEqM/1UjTjB2KdD/MitK5\n" + + "fP0VpvuXpNYZedmyq4UOMwdkiNMGAOrfmOeT0olgLrTMT5H97Cn3Yxbk13uXHNu/\n" + + "ZUZZNe8s+QtuLfUlKAJtLEUutN33TlWQY522FV0m17S+b80xJib3yZVJteVurrh5\n" + + "HSWHAM+zghQAvCesg5CLXa2dNMkTCmZKgCBvfDLZuZbjFwnwCI6u/NhOY9egKuUf\n" + + "SA/je/RXaT8m5VxLYMxwqQXKApzD87fv0tLPlVIEvjEsaf992tFEFSNPcG1l/jpd\n" + + "5AVXw6kKuf85UkJtYR1x2MkQDrqY1QX/XMw00kt8y9kMZUre19aCArcmor+hDhRJ\n" + + "E3Gt4QJrD9z/bICESw4b4z2DbgD/Xz9IXsA/r9cKiM1h5QMtXvuhyfVeM01enhxM\n" + + "GbOH3gjqqGNKysx0UODGEwr6AV9hAd8RWXMchJLaExK9J5SRawSg671ObAU24SdY\n" + + "vMQ9Z4kAQ2+1ReUZzf3ogSMRZtMT+d18gT6L90/y+APZIaoArLPhebIAGq39HLmJ\n" + + "26x3z0WAgrpA1kNsjXEXkoiZGPLKIGoe3hrCwPYEGAEKACAWIQTRpm4aI7GCyZgP\n" + + "eIz7/MgqAV5zMAUCXaWc8gIbDAAKCRD7/MgqAV5zMOn/C/9ugt+HZIwX308zI+QX\n" + + "c5vDLReuzmJ3ieE0DMO/uNSC+K1XEioSIZP91HeZJ2kbT9nn9fuReuoff0T0Dief\n" + + "rbwcIQQHFFkrqSp1K3VWmUGp2JrUsXFVdjy/fkBIjTd7c5boWljv/6wAsSfiv2V0\n" + + "JSM8EFU6TYXxswGjFVfc6X97tJNeIrXL+mpSmPPqy2bztcCCHkWS5lNLWQw+R7Vg\n" + + "71Fe6yBSNVrqC2/imYG2J9zlowjx1XU63Wdgqp2Wxt0l8OmsB/W80S1fRF5G4SDH\n" + + "s9HXglXXqPsBRZJYfP+VStm9L5P/sKjCcX6WtZR7yS6G8zj/X767MLK/djANvpPd\n" + + "NVniEke6hM3CNBXYPAMhQBMWhCulcoz+0lxi8L34rMN+Dsbma96psdUrn7uLaB91\n" + + "6we0CTfF8qqm7BsVAgalon/UUiuMY80U3ueoj3okiSTiHIjD/YtpXSPioC8nMng7\n" + + "xqAY9Bwizt4FWgXuLm1a4+So4V9j1TRCXd12Uc2l2RNmgDE=\n" + + "=FAzO\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + /** + * Bob's RSA-3072 OpenPGP v4 Certificate. + * @see + * Bob's OpenPGP Certificate + */ + public static final String BOB_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "Comment: D1A6 6E1A 23B1 82C9 980F 788C FBFC C82A 015E 7330\n" + + "Comment: Bob Babbage \n" + + "\n" + + "xsDNBF2lnPIBDAC5cL9PQoQLTMuhjbYvb4Ncuuo0bfmgPRFywX53jPhoFf4Zg6mv\n" + + "/seOXpgecTdOcVttfzC8ycIKrt3aQTiwOG/ctaR4Bk/t6ayNFfdUNxHWk4WCKzdz\n" + + "/56fW2O0F23qIRd8UUJp5IIlN4RDdRCtdhVQIAuzvp2oVy/LaS2kxQoKvph/5pQ/\n" + + "5whqsyroEWDJoSV0yOb25B/iwk/pLUFoyhDG9bj0kIzDxrEqW+7Ba8nocQlecMF3\n" + + "X5KMN5kp2zraLv9dlBBpWW43XktjcCZgMy20SouraVma8Je/ECwUWYUiAZxLIlMv\n" + + "9CurEOtxUw6N3RdOtLmYZS9uEnn5y1UkF88o8Nku890uk6BrewFzJyLAx5wRZ4F0\n" + + "qV/yq36UWQ0JB/AUGhHVPdFf6pl6eaxBwT5GXvbBUibtf8YI2og5RsgTWtXfU7eb\n" + + "SGXrl5ZMpbA6mbfhd0R8aPxWfmDWiIOhBufhMCvUHh1sApMKVZnvIff9/0Dca3wb\n" + + "vLIwa3T4CyshfT0AEQEAAc0hQm9iIEJhYmJhZ2UgPGJvYkBvcGVucGdwLmV4YW1w\n" + + "bGU+wsEOBBMBCgA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEE0aZuGiOx\n" + + "gsmYD3iM+/zIKgFeczAFAl2lnvoACgkQ+/zIKgFeczBvbAv/VNk90a6hG8Od9xTz\n" + + "XxH5YRFUSGfIA1yjPIVOnKqhMwps2U+sWE3urL+MvjyQRlyRV8oY9IOhQ5Esm6DO\n" + + "ZYrTnE7qVETm1ajIAP2OFChEc55uH88x/anpPOXOJY7S8jbn3naC9qad75BrZ+3g\n" + + "9EBUWiy5p8TykP05WSnSxNRt7vFKLfEB4nGkehpwHXOVF0CRNwYle42bg8lpmdXF\n" + + "DcCZCi+qEbafmTQzkAqyzS3nCh3IAqq6Y0kBuaKLm2tSNUOlZbD+OHYQNZ5Jix7c\n" + + "ZUzs6Xh4+I55NRWl5smrLq66yOQoFPy9jot/Qxikx/wP3MsAzeGaZSEPc0fHp5G1\n" + + "6rlGbxQ3vl8/usUV7W+TMEMljgwd5x8POR6HC8EaCDfVnUBCPi/Gv+egLjsIbPJZ\n" + + "ZEroiE40e6/UoCiQtlpQB5exPJYSd1Q1txCwueih99PHepsDhmUQKiACszNU+RRo\n" + + "zAYau2VdHqnRJ7QYdxHDiH49jPK4NTMyb/tJh2TiIwcmsIpGzsDNBF2lnPIBDADW\n" + + "ML9cbGMrp12CtF9b2P6z9TTT74S8iyBOzaSvdGDQY/sUtZXRg21HWamXnn9sSXvI\n" + + "DEINOQ6A9QxdxoqWdCHrOuW3ofneYXoG+zeKc4dC86wa1TR2q9vW+RMXSO4uImA+\n" + + "Uzula/6k1DogDf28qhCxMwG/i/m9g1c/0aApuDyKdQ1PXsHHNlgd/Dn6rrd5y2AO\n" + + "baifV7wIhEJnvqgFXDN2RXGjLeCOHV4Q2WTYPg/S4k1nMXVDwZXrvIsA0YwIMgIT\n" + + "86Rafp1qKlgPNbiIlC1g9RY/iFaGN2b4Ir6GDohBQSfZW2+LXoPZuVE/wGlQ01rh\n" + + "827KVZW4lXvqsge+wtnWlszcselGATyzqOK9LdHPdZGzROZYI2e8c+paLNDdVPL6\n" + + "vdRBUnkCaEkOtl1mr2JpQi5nTU+gTX4IeInC7E+1a9UDF/Y85ybUz8XV8rUnR76U\n" + + "qVC7KidNepdHbZjjXCt8/Zo+Tec9JNbYNQB/e9ExmDntmlHEsSEQzFwzj8sxH48A\n" + + "EQEAAcLA9gQYAQoAIBYhBNGmbhojsYLJmA94jPv8yCoBXnMwBQJdpZzyAhsMAAoJ\n" + + "EPv8yCoBXnMw6f8L/26C34dkjBffTzMj5Bdzm8MtF67OYneJ4TQMw7+41IL4rVcS\n" + + "KhIhk/3Ud5knaRtP2ef1+5F66h9/RPQOJ5+tvBwhBAcUWSupKnUrdVaZQanYmtSx\n" + + "cVV2PL9+QEiNN3tzluhaWO//rACxJ+K/ZXQlIzwQVTpNhfGzAaMVV9zpf3u0k14i\n" + + "tcv6alKY8+rLZvO1wIIeRZLmU0tZDD5HtWDvUV7rIFI1WuoLb+KZgbYn3OWjCPHV\n" + + "dTrdZ2CqnZbG3SXw6awH9bzRLV9EXkbhIMez0deCVdeo+wFFklh8/5VK2b0vk/+w\n" + + "qMJxfpa1lHvJLobzOP9fvrswsr92MA2+k901WeISR7qEzcI0Fdg8AyFAExaEK6Vy\n" + + "jP7SXGLwvfisw34OxuZr3qmx1Sufu4toH3XrB7QJN8XyqqbsGxUCBqWif9RSK4xj\n" + + "zRTe56iPeiSJJOIciMP9i2ldI+KgLycyeDvGoBj0HCLO3gVaBe4ubVrj5KjhX2PV\n" + + "NEJd3XZRzaXZE2aAMQ==\n" + + "=F9yX\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + /** + * Bob's RSA-3072 Revocation Certificate. + * @see + * Bob's Revocation Certificate + */ + public static final String BOB_REVOCATION_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "Comment: Bob's revocation certificate\n" + + "Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html\n" + + "\n" + + "iQG2BCABCgAgFiEE0aZuGiOxgsmYD3iM+/zIKgFeczAFAl2lnQQCHQAACgkQ+/zI\n" + + "KgFeczAIHAv/RrlGlPFKsW0BShC8sVtPfbT1N9lUqyrsgBhrUryM/i+rBtkbnSjp\n" + + "28R5araupt0og1g2L5VsCRM+ql0jf0zrZXOorKfAO70HCP3X+MlEquvztMUZGJRZ\n" + + "7TSMgIY1MeFgLmOw9pDKf3tSoouBOpPe5eVfXviEDDo2zOfdntjPyCMlxHgAcjZo\n" + + "XqMaurV+nKWoIx0zbdpNLsRy4JZcmnOSFdPw37R8U2miPi2qNyVwcyCxQy0LjN7Y\n" + + "AWadrs9vE0DrneSVP2OpBhl7g+Dj2uXJQRPVXcq6w9g5Fir6DnlhekTLsa78T5cD\n" + + "n8q7aRusMlALPAOosENOgINgsVcjuILkPN1eD+zGAgHgdiKaep1+P3pbo5n0CLki\n" + + "UCAsLnCEo8eBV9DCb/n1FlI5yhQhgQyMYlp/49H0JSc3IY9KHhv6f0zIaRWs0JuD\n" + + "ajcXTJ9AyB+SA6GBb9Q+XsNXjZ1gj75ekUD1sQ3ezTvVfovgP5bD+vPvILhSImKB\n" + + "aU6V3zld/x/1\n" + + "=mMwU\n" + + "-----END PGP PUBLIC KEY BLOCK-----"; + + /** + * Carol's OpenPGP v4 key. + */ + public static final String CAROL_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xcQTBF3+CmgRDADZhdKTM3ms3XpXnQke83FgaIBtP1g1qhqpCfg50WiPS0kjiMC0\n" + + "OJz2vh59nusbBLzgI//Y1VMhKfIWYbqMcIY+lWbseHjl52rqW6AaJ0TH4NgVt7vh\n" + + "yVeJt0k/NnxvNhMd0587KXmfpDxrwBqc/l5cVB+p0rL8vs8kxojHXAi5V3koM0Uj\n" + + "REWs5Jpj/XU9LhEoyXZkeJC/pes1u6UKoFYn7dFIP49Kkd1kb+1bNfdPYtA0JpcG\n" + + "zYgeMNOvdWJwn43dNhxoeuXfmAEhA8LdzT0C0O+7akXOKWrfhXJ8MTBqvPgWZYx7\n" + + "MNuQx/ejIMZHl+Iaf7hG976ILH+NCGiKkhidd9GIuA/WteHiQbXLyfiQ4n8P12q9\n" + + "+4dq6ybUM65tnozRyyN+1m3rU2a/+Ly3JCh4TeO27w+cxMWkaeHyTQaJVMbMbDpX\n" + + "duVd32MA33UVNH5/KXMVczVi5asVjuKDSojJDV1QwX8izZNl1t+AI0L3balCabV0\n" + + "SFhlfnBEUj1my1sBAMOSO/I67BvBS3IPHZWXHjgclhs26mPzRlZLryAUWR2DDACH\n" + + "5fx+yUAdZ8Vu/2zWTHxwWJ/X6gGTLqa9CmfDq5UDqYFFzuWwN4HJ+ryOuak1CGwS\n" + + "KJUBSA75HExbv0naWg+suy+pEDvF0VALPU9VUkSQtHyR10YO2FWOe3AEtpbYDRwp\n" + + "dr1ZwEbb3L6IGQ5i/4CNHbJ2u3yUeXsDNAvrpVSEcIjA01RPCOKmf58SDZp4yDdP\n" + + "xGhM8w6a18+fdQr22f2cJ0xgfPlbzFbO+FUsEgKvn6QTLhbaYw4zs7rdQDejWHV8\n" + + "2hP4K+rb9FwknYdV9uo4m77MgGlU+4yvJnGEYaL3jwjI3bH9aooNOl6XbvVAzNzo\n" + + "mYmaTO7mp6xFAu43yuGyd9K+1E4k7CQTROxTZ+RdtQjV95hSsEmMg792nQvDSBW4\n" + + "xwfOQ7pf3kC7r9fm8u9nBlEN12HsbQ8Yvux/ld5q5RaIlD19jzfVR6+hJzbj2ZnU\n" + + "yQs4ksAfIHTzTdLttRxS9lTRTkVx2vbUnoSBy6TYF1mf6nRPpSm1riZxnkR4+BQL\n" + + "/0rUAxwegTNIG/5M612s2a45QvYK1turZ7spI1RGitJUIjBXUuR76jIsyqagIhBl\n" + + "5nEsQ4HLv8OQ3EgJ5T9gldLFpHNczLxBQnnNwfPoD2e0kC/iy0rfiNX8HWpTgQpb\n" + + "zAosLj5/E0iNlildynIhuqBosyRWFqGva0O6qioL90srlzlfKCloe9R9w3HizjCb\n" + + "f59yEspuJt9iHVNOPOW2Wj5ub0KTiJPp9vBmrFaB79/IlgojpQoYvQ77Hx5A9CJq\n" + + "paMCHGOW6Uz9euN1ozzETEkIPtL8XAxcogfpe2JKE1uS7ugxsKEGEDfxOQFKAGV0\n" + + "XFtIx50vFCr2vQro0WB858CGN47dCxChhNUxNtGc11JNEkNv/X7hKtRf/5VCmnaz\n" + + "GWwNK47cqZ7GJfEBnElD7s/tQvTC5Qp7lg9gEt47TUX0bjzUTCxNvLosuKL9+J1W\n" + + "ln1myRpff/5ZOAnZTPHR+AbX4bRB4sK5zijQe4139Dn2oRYK+EIYoBAxFxSOzehP\n" + + "IQAA/2BCN5HryGjVff2t7Q6fVrQQS9hsMisszZl5rWwUOO6zETHCigQfEQgAPAUC\n" + + "Xf4KaQMLCQoJEJunidx21oSaBBUKCQgCFgECF4ACGwMCHgEWIQRx/9oARAnl3bDD\n" + + "6PGbp4ncdtaEmgAAYoUA/1VpxdR2wYT/pC8FrKsbmIxLJRLDNlED3ihivWp/B2e/\n" + + "AQCT2oi9zqbjprCKAnzoIYTGTil4yFfmeey8GjMOxUHz4M0mQ2Fyb2wgT2xkc3R5\n" + + "bGUgPGNhcm9sQG9wZW5wZ3AuZXhhbXBsZT7CigQTEQgAPAUCXf4KaQMLCQoJEJun\n" + + "idx21oSaBBUKCQgCFgECF4ACGwMCHgEWIQRx/9oARAnl3bDD6PGbp4ncdtaEmgAA\n" + + "UEwA/2TFwL0mymjCSaQH8KdQuygI+itpNggM+Y8FF8hn9fo1AP9ogDIl9V3C8t59\n" + + "C/Mrc4HvP1ABR2nwZeK5+A5lLoH4Y8fD8QRd/gpoEAwA2YXSkzN5rN16V50JHvNx\n" + + "YGiAbT9YNaoaqQn4OdFoj0tJI4jAtDic9r4efZ7rGwS84CP/2NVTISnyFmG6jHCG\n" + + "PpVm7Hh45edq6lugGidEx+DYFbe74clXibdJPzZ8bzYTHdOfOyl5n6Q8a8AanP5e\n" + + "XFQfqdKy/L7PJMaIx1wIuVd5KDNFI0RFrOSaY/11PS4RKMl2ZHiQv6XrNbulCqBW\n" + + "J+3RSD+PSpHdZG/tWzX3T2LQNCaXBs2IHjDTr3VicJ+N3TYcaHrl35gBIQPC3c09\n" + + "AtDvu2pFzilq34VyfDEwarz4FmWMezDbkMf3oyDGR5fiGn+4Rve+iCx/jQhoipIY\n" + + "nXfRiLgP1rXh4kG1y8n4kOJ/D9dqvfuHausm1DOubZ6M0csjftZt61Nmv/i8tyQo\n" + + "eE3jtu8PnMTFpGnh8k0GiVTGzGw6V3blXd9jAN91FTR+fylzFXM1YuWrFY7ig0qI\n" + + "yQ1dUMF/Is2TZdbfgCNC922pQmm1dEhYZX5wRFI9ZstbDACH5fx+yUAdZ8Vu/2zW\n" + + "THxwWJ/X6gGTLqa9CmfDq5UDqYFFzuWwN4HJ+ryOuak1CGwSKJUBSA75HExbv0na\n" + + "Wg+suy+pEDvF0VALPU9VUkSQtHyR10YO2FWOe3AEtpbYDRwpdr1ZwEbb3L6IGQ5i\n" + + "/4CNHbJ2u3yUeXsDNAvrpVSEcIjA01RPCOKmf58SDZp4yDdPxGhM8w6a18+fdQr2\n" + + "2f2cJ0xgfPlbzFbO+FUsEgKvn6QTLhbaYw4zs7rdQDejWHV82hP4K+rb9FwknYdV\n" + + "9uo4m77MgGlU+4yvJnGEYaL3jwjI3bH9aooNOl6XbvVAzNzomYmaTO7mp6xFAu43\n" + + "yuGyd9K+1E4k7CQTROxTZ+RdtQjV95hSsEmMg792nQvDSBW4xwfOQ7pf3kC7r9fm\n" + + "8u9nBlEN12HsbQ8Yvux/ld5q5RaIlD19jzfVR6+hJzbj2ZnUyQs4ksAfIHTzTdLt\n" + + "tRxS9lTRTkVx2vbUnoSBy6TYF1mf6nRPpSm1riZxnkR4+BQL/jEGmn1tLhxfjfDA\n" + + "5vFFj73+FXdFCdFKSI0VpdoU1fgR5DX72ZQUYYUCKYTYikXv1mqdH/5VthptrktC\n" + + "oAco4zVxM04sK7Xthl+uTOhei8/Dd9ZLdSIoNcRjrr/uh5sUzUfIC9iuT3SXiZ/D\n" + + "0yVq0Uu/gWPB3ZIG/sFacxOXAr6RYhvz9MqnwXS1sVT5TyO3XIQ5JseIgIRyV/Sf\n" + + "4F/4Qui9wMzzSajTwCsttMGKf67k228AaJVv+IpFoo+OtCa7wbJukqfNQN3m2ojf\n" + + "V5CcoCzsoRsoTInhrpQmM+gGoQBXBArT1xk3KK3VdZibYfMoxeIGXw0MoNJzFuGK\n" + + "+PcnhV3ETFMNcszd0Pb9s86g7hYtpRmE12Jlai2MzPSmyztlsRP9tcZwYy7JdPZf\n" + + "xXQP24XWat7eP2qWxTnkEP4/wKYb81m7CZ4RvUO/nd1aA5c9IBYknbgmCAAKvHVD\n" + + "iTY61E5GbC9aTiI4WIwjItroikukUJE+p77rpjxfw/1U51BnmQAA/ih5jIthn2ZE\n" + + "r1YoOsUs8CBhylTsRZK6VS4ZCErcyl2tD2LCigQYEQgAPAUCXf4KaQMLCQoJEJun\n" + + "idx21oSaBBUKCQgCFgECF4ACGwwCHgEWIQRx/9oARAnl3bDD6PGbp4ncdtaEmgAA\n" + + "QSkA/3WEWqZxvZmpVxpEMxJWaGQRwUhGake8OhC1WfywCtarAQCLwfBsyEv5jBEi\n" + + "1FkOSekLi8WNMdUx3XMyvP8nJ65P2Q==\n" + + "=Xj8h\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + /** + * Carol's OpenPGP v4 certificate. + */ + public static final String CAROL_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xsPuBF3+CmgRDADZhdKTM3ms3XpXnQke83FgaIBtP1g1qhqpCfg50WiPS0kjiMC0\n" + + "OJz2vh59nusbBLzgI//Y1VMhKfIWYbqMcIY+lWbseHjl52rqW6AaJ0TH4NgVt7vh\n" + + "yVeJt0k/NnxvNhMd0587KXmfpDxrwBqc/l5cVB+p0rL8vs8kxojHXAi5V3koM0Uj\n" + + "REWs5Jpj/XU9LhEoyXZkeJC/pes1u6UKoFYn7dFIP49Kkd1kb+1bNfdPYtA0JpcG\n" + + "zYgeMNOvdWJwn43dNhxoeuXfmAEhA8LdzT0C0O+7akXOKWrfhXJ8MTBqvPgWZYx7\n" + + "MNuQx/ejIMZHl+Iaf7hG976ILH+NCGiKkhidd9GIuA/WteHiQbXLyfiQ4n8P12q9\n" + + "+4dq6ybUM65tnozRyyN+1m3rU2a/+Ly3JCh4TeO27w+cxMWkaeHyTQaJVMbMbDpX\n" + + "duVd32MA33UVNH5/KXMVczVi5asVjuKDSojJDV1QwX8izZNl1t+AI0L3balCabV0\n" + + "SFhlfnBEUj1my1sBAMOSO/I67BvBS3IPHZWXHjgclhs26mPzRlZLryAUWR2DDACH\n" + + "5fx+yUAdZ8Vu/2zWTHxwWJ/X6gGTLqa9CmfDq5UDqYFFzuWwN4HJ+ryOuak1CGwS\n" + + "KJUBSA75HExbv0naWg+suy+pEDvF0VALPU9VUkSQtHyR10YO2FWOe3AEtpbYDRwp\n" + + "dr1ZwEbb3L6IGQ5i/4CNHbJ2u3yUeXsDNAvrpVSEcIjA01RPCOKmf58SDZp4yDdP\n" + + "xGhM8w6a18+fdQr22f2cJ0xgfPlbzFbO+FUsEgKvn6QTLhbaYw4zs7rdQDejWHV8\n" + + "2hP4K+rb9FwknYdV9uo4m77MgGlU+4yvJnGEYaL3jwjI3bH9aooNOl6XbvVAzNzo\n" + + "mYmaTO7mp6xFAu43yuGyd9K+1E4k7CQTROxTZ+RdtQjV95hSsEmMg792nQvDSBW4\n" + + "xwfOQ7pf3kC7r9fm8u9nBlEN12HsbQ8Yvux/ld5q5RaIlD19jzfVR6+hJzbj2ZnU\n" + + "yQs4ksAfIHTzTdLttRxS9lTRTkVx2vbUnoSBy6TYF1mf6nRPpSm1riZxnkR4+BQL\n" + + "/0rUAxwegTNIG/5M612s2a45QvYK1turZ7spI1RGitJUIjBXUuR76jIsyqagIhBl\n" + + "5nEsQ4HLv8OQ3EgJ5T9gldLFpHNczLxBQnnNwfPoD2e0kC/iy0rfiNX8HWpTgQpb\n" + + "zAosLj5/E0iNlildynIhuqBosyRWFqGva0O6qioL90srlzlfKCloe9R9w3HizjCb\n" + + "f59yEspuJt9iHVNOPOW2Wj5ub0KTiJPp9vBmrFaB79/IlgojpQoYvQ77Hx5A9CJq\n" + + "paMCHGOW6Uz9euN1ozzETEkIPtL8XAxcogfpe2JKE1uS7ugxsKEGEDfxOQFKAGV0\n" + + "XFtIx50vFCr2vQro0WB858CGN47dCxChhNUxNtGc11JNEkNv/X7hKtRf/5VCmnaz\n" + + "GWwNK47cqZ7GJfEBnElD7s/tQvTC5Qp7lg9gEt47TUX0bjzUTCxNvLosuKL9+J1W\n" + + "ln1myRpff/5ZOAnZTPHR+AbX4bRB4sK5zijQe4139Dn2oRYK+EIYoBAxFxSOzehP\n" + + "IcKKBB8RCAA8BQJd/gppAwsJCgkQm6eJ3HbWhJoEFQoJCAIWAQIXgAIbAwIeARYh\n" + + "BHH/2gBECeXdsMPo8Zunidx21oSaAABihQD/VWnF1HbBhP+kLwWsqxuYjEslEsM2\n" + + "UQPeKGK9an8HZ78BAJPaiL3OpuOmsIoCfOghhMZOKXjIV+Z57LwaMw7FQfPgzSZD\n" + + "YXJvbCBPbGRzdHlsZSA8Y2Fyb2xAb3BlbnBncC5leGFtcGxlPsKKBBMRCAA8BQJd\n" + + "/gppAwsJCgkQm6eJ3HbWhJoEFQoJCAIWAQIXgAIbAwIeARYhBHH/2gBECeXdsMPo\n" + + "8Zunidx21oSaAABQTAD/ZMXAvSbKaMJJpAfwp1C7KAj6K2k2CAz5jwUXyGf1+jUA\n" + + "/2iAMiX1XcLy3n0L8ytzge8/UAFHafBl4rn4DmUugfhjzsPMBF3+CmgQDADZhdKT\n" + + "M3ms3XpXnQke83FgaIBtP1g1qhqpCfg50WiPS0kjiMC0OJz2vh59nusbBLzgI//Y\n" + + "1VMhKfIWYbqMcIY+lWbseHjl52rqW6AaJ0TH4NgVt7vhyVeJt0k/NnxvNhMd0587\n" + + "KXmfpDxrwBqc/l5cVB+p0rL8vs8kxojHXAi5V3koM0UjREWs5Jpj/XU9LhEoyXZk\n" + + "eJC/pes1u6UKoFYn7dFIP49Kkd1kb+1bNfdPYtA0JpcGzYgeMNOvdWJwn43dNhxo\n" + + "euXfmAEhA8LdzT0C0O+7akXOKWrfhXJ8MTBqvPgWZYx7MNuQx/ejIMZHl+Iaf7hG\n" + + "976ILH+NCGiKkhidd9GIuA/WteHiQbXLyfiQ4n8P12q9+4dq6ybUM65tnozRyyN+\n" + + "1m3rU2a/+Ly3JCh4TeO27w+cxMWkaeHyTQaJVMbMbDpXduVd32MA33UVNH5/KXMV\n" + + "czVi5asVjuKDSojJDV1QwX8izZNl1t+AI0L3balCabV0SFhlfnBEUj1my1sMAIfl\n" + + "/H7JQB1nxW7/bNZMfHBYn9fqAZMupr0KZ8OrlQOpgUXO5bA3gcn6vI65qTUIbBIo\n" + + "lQFIDvkcTFu/SdpaD6y7L6kQO8XRUAs9T1VSRJC0fJHXRg7YVY57cAS2ltgNHCl2\n" + + "vVnARtvcvogZDmL/gI0dsna7fJR5ewM0C+ulVIRwiMDTVE8I4qZ/nxINmnjIN0/E\n" + + "aEzzDprXz591CvbZ/ZwnTGB8+VvMVs74VSwSAq+fpBMuFtpjDjOzut1AN6NYdXza\n" + + "E/gr6tv0XCSdh1X26jibvsyAaVT7jK8mcYRhovePCMjdsf1qig06Xpdu9UDM3OiZ\n" + + "iZpM7uanrEUC7jfK4bJ30r7UTiTsJBNE7FNn5F21CNX3mFKwSYyDv3adC8NIFbjH\n" + + "B85Dul/eQLuv1+by72cGUQ3XYextDxi+7H+V3mrlFoiUPX2PN9VHr6EnNuPZmdTJ\n" + + "CziSwB8gdPNN0u21HFL2VNFORXHa9tSehIHLpNgXWZ/qdE+lKbWuJnGeRHj4FAv+\n" + + "MQaafW0uHF+N8MDm8UWPvf4Vd0UJ0UpIjRWl2hTV+BHkNfvZlBRhhQIphNiKRe/W\n" + + "ap0f/lW2Gm2uS0KgByjjNXEzTiwrte2GX65M6F6Lz8N31kt1Iig1xGOuv+6HmxTN\n" + + "R8gL2K5PdJeJn8PTJWrRS7+BY8Hdkgb+wVpzE5cCvpFiG/P0yqfBdLWxVPlPI7dc\n" + + "hDkmx4iAhHJX9J/gX/hC6L3AzPNJqNPAKy20wYp/ruTbbwBolW/4ikWij460JrvB\n" + + "sm6Sp81A3ebaiN9XkJygLOyhGyhMieGulCYz6AahAFcECtPXGTcordV1mJth8yjF\n" + + "4gZfDQyg0nMW4Yr49yeFXcRMUw1yzN3Q9v2zzqDuFi2lGYTXYmVqLYzM9KbLO2Wx\n" + + "E/21xnBjLsl09l/FdA/bhdZq3t4/apbFOeQQ/j/AphvzWbsJnhG9Q7+d3VoDlz0g\n" + + "FiSduCYIAAq8dUOJNjrUTkZsL1pOIjhYjCMi2uiKS6RQkT6nvuumPF/D/VTnUGeZ\n" + + "wooEGBEIADwFAl3+CmkDCwkKCRCbp4ncdtaEmgQVCgkIAhYBAheAAhsMAh4BFiEE\n" + + "cf/aAEQJ5d2ww+jxm6eJ3HbWhJoAAEEpAP91hFqmcb2ZqVcaRDMSVmhkEcFIRmpH\n" + + "vDoQtVn8sArWqwEAi8HwbMhL+YwRItRZDknpC4vFjTHVMd1zMrz/JyeuT9k=\n" + + "=pa/S\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + + /** + * Minimal OpenPGP v6 key. + * @see + * Sample Version 6 Secret Key + */ + public static final String V6_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xUsGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laMAGXKB\n" + + "exK+cH6NX1hs5hNhIB00TrJmosgv3mg1ditlsLfCsQYfGwoAAABCBYJjh3/jAwsJ\n" + + "BwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lwgyU2kCcUmKfvBXbAf6rh\n" + + "RYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaEQsiPlR4zxP/TP7mhfVEe\n" + + "7XWPxtnMUMtf15OyA51YBMdLBmOHf+MZAAAAIIaTJINn+eUBXbki+PSAld2nhJh/\n" + + "LVmFsS+60WyvXkQ1AE1gCk95TUR3XFeibg/u/tVY6a//1q0NWC1X+yui3O24wpsG\n" + + "GBsKAAAALAWCY4d/4wKbDCIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAAQBIKbpGG2dWTX8j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDE\n" + + "M0g12vYxoWM8Y81W+bHBw805I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUr\n" + + "k0mXubZvyl4GBg==\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + /** + * Locked, minimal OpenPGP v6 key. + * @see + * Sample Locked Version 6 Secret Key + */ + public static final String V6_KEY_LOCKED = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xYIGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laP9JgkC\n" + + "FARdb9ccngltHraRe25uHuyuAQQVtKipJ0+r5jL4dacGWSAheCWPpITYiyfyIOPS\n" + + "3gIDyg8f7strd1OB4+LZsUhcIjOMpVHgmiY/IutJkulneoBYwrEGHxsKAAAAQgWC\n" + + "Y4d/4wMLCQcFFQoOCAwCFgACmwMCHgkiIQbLGGxPBgmml+TVLfpscisMHx4nwYpW\n" + + "cI9lJewnutmsyQUnCQIHAgAAAACtKCAQPi19In7A5tfORHHbNr/JcIMlNpAnFJin\n" + + "7wV2wH+q4UWFs7kDsBJ+xP2i8CMEWi7Ha8tPlXGpZR4UruETeh1mhELIj5UeM8T/\n" + + "0z+5oX1RHu11j8bZzFDLX9eTsgOdWATHggZjh3/jGQAAACCGkySDZ/nlAV25Ivj0\n" + + "gJXdp4SYfy1ZhbEvutFsr15ENf0mCQIUBA5hhGgp2oaavg6mFUXcFMwBBBUuE8qf\n" + + "9Ock+xwusd+GAglBr5LVyr/lup3xxQvHXFSjjA2haXfoN6xUGRdDEHI6+uevKjVR\n" + + "v5oAxgu7eJpaXNjCmwYYGwoAAAAsBYJjh3/jApsMIiEGyxhsTwYJppfk1S36bHIr\n" + + "DB8eJ8GKVnCPZSXsJ7rZrMkAAAAABAEgpukYbZ1ZNfyP5WMUzbUnSGpaUSD5t2Ki\n" + + "Nacp8DkBClZRa2c3AMQzSDXa9jGhYzxjzVb5scHDzTkjyRZWRdTq8U6L4da+/+Kt\n" + + "ruh8m7Xo2ehSSFyWRSuTSZe5tm/KXgYG\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + /** + * Passphrase to unlock {@link #V6_KEY_LOCKED} with. + */ + public static final String V6_KEY_LOCKED_PASSPHRASE = "correct horse battery staple"; + /** + * Sample Version 6 Certificate. + * @see + * Sample Version 6 Certificate + */ + public static final String V6_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xioGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laPCsQYf\n" + + "GwoAAABCBYJjh3/jAwsJBwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxy\n" + + "KwwfHifBilZwj2Ul7Ce62azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lw\n" + + "gyU2kCcUmKfvBXbAf6rhRYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaE\n" + + "QsiPlR4zxP/TP7mhfVEe7XWPxtnMUMtf15OyA51YBM4qBmOHf+MZAAAAIIaTJINn\n" + + "+eUBXbki+PSAld2nhJh/LVmFsS+60WyvXkQ1wpsGGBsKAAAALAWCY4d/4wKbDCIh\n" + + "BssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce62azJAAAAAAQBIKbpGG2dWTX8\n" + + "j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDEM0g12vYxoWM8Y81W+bHBw805\n" + + "I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUrk0mXubZvyl4GBg==\n" + + "-----END PGP PUBLIC KEY BLOCK-----"; + + public static PGPPublicKeyRing readPGPPublicKeyRing(String armor) + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(armor.getBytes()); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPPublicKeyRing publicKeys = (PGPPublicKeyRing) objFac.nextObject(); + pIn.close(); + aIn.close(); + return publicKeys; + } + + public static PGPSecretKeyRing readPGPSecretKeyRing(String armor) + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(armor.getBytes()); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + pIn.close(); + aIn.close(); + return secretKeys; + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/APITest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/APITest.java new file mode 100644 index 0000000000..2a597d8e9e --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/APITest.java @@ -0,0 +1,32 @@ +package org.bouncycastle.openpgp.api.test; + +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.bc.BcOpenPGPApi; +import org.bouncycastle.openpgp.api.jcajce.JcaOpenPGPApi; + +import java.io.IOException; +import java.util.Date; + +public abstract class APITest + extends AbstractPacketTest +{ + @Override + public void performTest() + throws Exception + { + performTestWith(new BcOpenPGPApi()); + performTestWith(new JcaOpenPGPApi(new BouncyCastleProvider())); + } + + public Date currentTimeRounded() + { + Date now = new Date(); + return new Date((now.getTime() / 1000) * 1000); // rounded to seconds + } + + protected abstract void performTestWith(OpenPGPApi api) + throws PGPException, IOException; +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/AllTests.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/AllTests.java new file mode 100644 index 0000000000..7d3004c6ab --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/AllTests.java @@ -0,0 +1,67 @@ +package org.bouncycastle.openpgp.api.test; + +import java.security.Security; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.PrintTestResult; +import org.bouncycastle.util.test.SimpleTestResult; + +public class AllTests + extends TestCase +{ + public void testAPI() + { + Security.addProvider(new BouncyCastleProvider()); + + org.bouncycastle.util.test.Test[] tests = RegressionTest.tests; + + for (int i = 0; i != tests.length; i++) + { + SimpleTestResult result = (SimpleTestResult)tests[i].perform(); + + if (!result.isSuccessful()) + { + fail(result.toString()); + } + } + } + + + public static void main(String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("OpenPGP Packet Tests"); + + suite.addTestSuite(AllTests.class); + + return new BCPacketTests(suite); + } + + static class BCPacketTests + extends TestSetup + { + public BCPacketTests(Test test) + { + super(test); + } + + protected void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + protected void tearDown() + { + Security.removeProvider("BC"); + } + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/ChangeKeyPassphraseTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/ChangeKeyPassphraseTest.java new file mode 100644 index 0000000000..ed24018f57 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/ChangeKeyPassphraseTest.java @@ -0,0 +1,121 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.IOException; + +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPKey; + +public class ChangeKeyPassphraseTest + extends APITest +{ + @Override + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + if (System.getProperty("java.version").indexOf("1.5.") < 0) + { + removeAEADPassphrase(api); + addAEADPassphrase(api); + changeAEADPassphrase(api); + + testChangingCFBPassphrase(api); + } + } + + private void removeAEADPassphrase(OpenPGPApi api) + throws IOException, PGPException { + OpenPGPKey key = api.readKeyOrCertificate() + .parseKey(OpenPGPTestKeys.V6_KEY_LOCKED); + + OpenPGPKey.OpenPGPSecretKey secretKey = key.getPrimarySecretKey(); + isTrue("Expect test key to be locked initially", secretKey.isLocked()); + OpenPGPKey.OpenPGPPrivateKey privateKey = secretKey.unlock(OpenPGPTestKeys.V6_KEY_LOCKED_PASSPHRASE.toCharArray()); + OpenPGPKey.OpenPGPSecretKey unlocked = privateKey.removePassphrase(); + isFalse("Expect key to be unlocked after unlocking - duh", unlocked.isLocked()); + + OpenPGPKey expected = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + isEncodingEqual("Expect unlocked key encoding to equal the unprotected test vector", + expected.getPrimarySecretKey().getPGPSecretKey().getEncoded(), + unlocked.getPGPSecretKey().getEncoded()); + } + + private void addAEADPassphrase(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + OpenPGPKey.OpenPGPSecretKey secretKey = key.getPrimarySecretKey(); + isFalse("Expect unlocked test vector to be unlocked", secretKey.isLocked()); + + OpenPGPKey.OpenPGPPrivateKey privateKey = secretKey.unlock(); + OpenPGPKey.OpenPGPSecretKey locked = privateKey.changePassphrase( + "sw0rdf1sh".toCharArray(), + api.getImplementation(), + true); + isTrue("Expect test key to be locked after locking", locked.isLocked()); + isEquals("Expect locked key to use AEAD", + SecretKeyPacket.USAGE_AEAD, locked.getPGPSecretKey().getS2KUsage()); + isTrue("Expect key to be unlockable with used passphrase", + locked.isPassphraseCorrect("sw0rdf1sh".toCharArray())); + } + + private void changeAEADPassphrase(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate() + .parseKey(OpenPGPTestKeys.V6_KEY_LOCKED); + + OpenPGPKey.OpenPGPSecretKey secretKey = key.getPrimarySecretKey(); + isTrue("Expect locked test vector to be locked initially", + secretKey.isLocked()); + OpenPGPKey.OpenPGPPrivateKey privateKey = secretKey.unlock(OpenPGPTestKeys.V6_KEY_LOCKED_PASSPHRASE.toCharArray()); + OpenPGPKey.OpenPGPSecretKey relocked = privateKey.changePassphrase("sw0rdf1sh".toCharArray()); + isTrue("Expect key to still be locked after changing passphrase", relocked.isLocked()); + isTrue("Expect key to be unlockable with used passphrase", + relocked.isPassphraseCorrect("sw0rdf1sh".toCharArray())); + isEquals("Expect re-locked key to use AEAD", + relocked.getPGPSecretKey().getS2KUsage(), SecretKeyPacket.USAGE_AEAD); + } + + private void testChangingCFBPassphrase(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY); + + OpenPGPKey.OpenPGPSecretKey secretKey = key.getPrimarySecretKey(); + isFalse("Expect Alice' key to not be locked initially", secretKey.isLocked()); + + OpenPGPKey.OpenPGPPrivateKey privateKey = secretKey.unlock(); + OpenPGPKey.OpenPGPSecretKey locked = privateKey.changePassphrase( + "sw0rdf1sh".toCharArray(), api.getImplementation(), false); + isTrue("Expect Alice' key to be locked after locking", locked.isLocked()); + isEquals("Expect CFB mode to be used for locking, since we did not use AEAD.", + locked.getPGPSecretKey().getS2KUsage(), SecretKeyPacket.USAGE_SHA1); + isTrue("Expect key to be unlockable with used passphrase", + locked.isPassphraseCorrect("sw0rdf1sh".toCharArray())); + + privateKey = locked.unlock("sw0rdf1sh".toCharArray()); + OpenPGPKey.OpenPGPSecretKey relocked = privateKey.changePassphrase("0r4ng3".toCharArray()); + isEquals("Expect CFB to be used after changing passphrase of CFB-protected key", + relocked.getPGPSecretKey().getS2KUsage(), SecretKeyPacket.USAGE_SHA1); + isTrue("Expect key to be unlockable with new passphrase", + relocked.isPassphraseCorrect("0r4ng3".toCharArray())); + + privateKey = relocked.unlock("0r4ng3".toCharArray()); + OpenPGPKey.OpenPGPSecretKey unlocked = privateKey.removePassphrase(); + isFalse("Expect key to be unlocked after removing passphrase", unlocked.isLocked()); + } + + @Override + public String getName() + { + return "ChangeKeyPassphraseTest"; + } + + public static void main(String[] args) + { + runTest(new ChangeKeyPassphraseTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/DoubleBufferedInputStreamTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/DoubleBufferedInputStreamTest.java new file mode 100644 index 0000000000..b34b7f3406 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/DoubleBufferedInputStreamTest.java @@ -0,0 +1,164 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.openpgp.api.DoubleBufferedInputStream; +import org.bouncycastle.util.io.Streams; + +public class DoubleBufferedInputStreamTest + extends AbstractPacketTest +{ + + @Override + public String getName() + { + return "RetainingInputStreamTest"; + } + + @Override + public void performTest() + throws Exception + { + throwWhileReadingNthBlock(); + successfullyReadSmallerThanBuffer(); + successfullyReadGreaterThanBuffer(); + + throwWhileReadingFirstBlock(); + throwWhileClosing(); + } + + private void successfullyReadSmallerThanBuffer() + throws IOException + { + byte[] bytes = getSequentialBytes(400); + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + DoubleBufferedInputStream retIn = new DoubleBufferedInputStream(bIn, 512); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + Streams.pipeAll(retIn, bOut); + isEncodingEqual(bytes, bOut.toByteArray()); + } + + private void successfullyReadGreaterThanBuffer() + throws IOException + { + byte[] bytes = getSequentialBytes(2000); + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + DoubleBufferedInputStream retIn = new DoubleBufferedInputStream(bIn, 512); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + Streams.pipeAll(retIn, bOut); + isEncodingEqual(bytes, bOut.toByteArray()); + } + + private void throwWhileReadingFirstBlock() + { + InputStream throwAfterNBytes = new InputStream() + { + int throwAt = 314; + int r = 0; + + @Override + public int read() + throws IOException + { + int i = r; + if (r == throwAt) + { + throw new IOException("Oopsie"); + } + r++; + return i; + } + }; + DoubleBufferedInputStream retIn = new DoubleBufferedInputStream(throwAfterNBytes, 512); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + try + { + Streams.pipeAll(retIn, bOut); + } + catch (IOException e) + { + isEquals("Oopsie", e.getMessage()); + } + isEquals("throwWhileReadingFirstBlock: expected no bytes emitted", 0, bOut.toByteArray().length); + } + + private void throwWhileReadingNthBlock() + { + InputStream throwAfterNBytes = new InputStream() + { + int throwAt = 10; + int r = 0; + + @Override + public int read() + throws IOException + { + int i = r; + if (r == throwAt) + { + throw new IOException("Oopsie"); + } + r++; + return i; + } + }; + DoubleBufferedInputStream retIn = new DoubleBufferedInputStream(throwAfterNBytes, 4); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + try + { + Streams.pipeAll(retIn, bOut); + } + catch (IOException e) + { + isEquals("Oopsie", e.getMessage()); + } + byte[] got = bOut.toByteArray(); + isEquals("throwWhileReadingNthBlock: expected 4 bytes emitted. Got " + got.length, 4, got.length); + } + + private void throwWhileClosing() + { + byte[] bytes = getSequentialBytes(100); + ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); + FilterInputStream throwOnClose = new FilterInputStream(bIn) + { + @Override + public void close() + throws IOException + { + throw new IOException("Oopsie"); + } + }; + DoubleBufferedInputStream retIn = new DoubleBufferedInputStream(throwOnClose, 512); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + try + { + Streams.pipeAll(retIn, bOut); + } + catch (IOException e) + { + isEquals("Oopsie", e.getMessage()); + } + isEquals("throwWhileClosing: len mismatch", 0, bOut.toByteArray().length); + } + + private byte[] getSequentialBytes(int n) + { + byte[] bytes = new byte[n]; + for (int i = 0; i < bytes.length; i++) + { + bytes[i] = (byte)(i % 128); + } + return bytes; + } + + public static void main(String[] args) + { + runTest(new DoubleBufferedInputStreamTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPCertificateTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPCertificateTest.java new file mode 100644 index 0000000000..7fbd93f5a2 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPCertificateTest.java @@ -0,0 +1,886 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Date; +import java.util.List; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureList; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.OpenPGPKeyGenerator; +import org.bouncycastle.openpgp.api.SignatureParameters; +import org.bouncycastle.openpgp.api.SignatureSubpacketsFunction; +import org.bouncycastle.openpgp.api.util.UTCUtil; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.util.Strings; + +public class OpenPGPCertificateTest + extends APITest +{ + + @Override + public String getName() + { + return "OpenPGPCertificateTest"; + } + + @Override + protected void performTestWith(OpenPGPApi api) + throws IOException, PGPException + { + testOpenPGPv6Key(api); + + testBaseCasePrimaryKeySigns(api); + testBaseCaseSubkeySigns(api); + testPKSignsPKRevokedNoSubpacket(api); + testSKSignsPKRevokedNoSubpacket(api); + testPKSignsPKRevocationSuperseded(api); + testGetPrimaryUserId(api); + } + + private void testOpenPGPv6Key(OpenPGPApi api) + throws IOException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + + isTrue("Test key has no identities", key.getIdentities().isEmpty()); + + OpenPGPCertificate.OpenPGPPrimaryKey primaryKey = key.getPrimaryKey(); + isEquals("Primary key identifier mismatch", + new KeyIdentifier("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"), + primaryKey.getKeyIdentifier()); + OpenPGPKey.OpenPGPSecretKey secretPrimaryKey = key.getSecretKey(primaryKey); + isTrue("Secret Primary key MUST have reference to its public component", + primaryKey == secretPrimaryKey.getPublicKey()); + isTrue("Primary key is expected to be signing key", primaryKey.isSigningKey()); + isTrue("Primary secret key is expected to be signing key", secretPrimaryKey.isSigningKey()); + isTrue("Primary secret key is expected to be certification key", secretPrimaryKey.isCertificationKey()); + isTrue("Primary key is expected to be certification key", primaryKey.isCertificationKey()); + + List signingKeys = key.getSigningKeys(); + isEquals("Expected exactly 1 signing key", 1, signingKeys.size()); + OpenPGPCertificate.OpenPGPPrimaryKey signingKey = (OpenPGPCertificate.OpenPGPPrimaryKey) signingKeys.get(0); + isEquals("Signing key is expected to be the same as primary key", primaryKey, signingKey); + + Features signingKeyFeatures = signingKey.getFeatures(); + // Features are extracted from direct-key signature + isEquals("Signing key features mismatch. Expect features to be extracted from DK signature.", + Features.FEATURE_MODIFICATION_DETECTION | Features.FEATURE_SEIPD_V2, + signingKeyFeatures.getFeatures()); + + List encryptionKeys = key.getEncryptionKeys(); + isEquals("Expected exactly 1 encryption key", 1, encryptionKeys.size()); + OpenPGPCertificate.OpenPGPSubkey encryptionKey = (OpenPGPCertificate.OpenPGPSubkey) encryptionKeys.get(0); + isTrue("Subkey MUST be encryption key", encryptionKey.isEncryptionKey()); + isEquals("Encryption subkey identifier mismatch", + new KeyIdentifier("12C83F1E706F6308FE151A417743A1F033790E93E9978488D1DB378DA9930885"), + encryptionKey.getKeyIdentifier()); + + KeyFlags encryptionKeyFlags = encryptionKey.getKeyFlags(); + // Key Flags are extracted from subkey-binding signature + isEquals("Encryption key flag mismatch. Expected key flags to be extracted from SB sig.", + KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, + encryptionKeyFlags.getFlags()); + + Features encryptionKeyFeatures = encryptionKey.getFeatures(); + // Features are extracted from direct-key signature + isEquals("Encryption key features mismatch. Expected features to be extracted from DK sig.", + Features.FEATURE_MODIFICATION_DETECTION | Features.FEATURE_SEIPD_V2, + encryptionKeyFeatures.getFeatures()); + } + + private void testBaseCasePrimaryKeySigns(OpenPGPApi api) + throws IOException + { + // https://sequoia-pgp.gitlab.io/openpgp-interoperability-test-suite/results.html#Key_revocation_test__primary_key_signs_and_is_not_revoked__base_case_ + String cert = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xsBNBFpJegABCACzr1V+GxVkrtfDjihYK+HtyEIcO52uw7O2kd7JbduYp4RK17jy\n" + + "75N3EnsgmiIkSxXCWr+rTtonNs1zCJeUa/gwnNfs7mVgjL2rMOZU/KZ4MP0yOYU5\n" + + "u5FjNPWz8hpFQ9GKqfdj0Op61h1pCQO45IjUQ3dCDj9Rfn44zHMB1ZrbmIH9nTR1\n" + + "YIGHWmdm0LItb2WxIkwzWBAJ5acTlsmLyZZEQ1+8NDqktyzwFoQqTJvLU4StY2k6\n" + + "h18ZKZdPyrdLoEyOuWkvjxmbhDk1Gt5KiS/yy7mrzIPLr0dmJe4vc8WLV+bXoyNE\n" + + "x3H8o9CFcYehLfyqsy40lg92d6Kp96ww8dZ5ABEBAAHCwMQEHwEKAHgFgl4L4QAJ\n" + + "EAitUcrkcPAGRxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9y\n" + + "Z4csZe1ah1tj2AjxfdDMsH2wvSEwZjb/73ICKnm7BySQAhUKApsDAh4BFiEE4yy2\n" + + "2oICkbfnbbGoCK1RyuRw8AYAAGYFCACiKnCb2NBZa/Jj1aJe4R2rxPZj2ERXWe3b\n" + + "JKNPKT7K0rVDkTw1JRiTfCsuAY2lY9sKJdhQZl+azXm64vvTc6hEGRQ/+XssDlE2\n" + + "DIn8C34HDc495ZnryHNB8Dd5l1HdjqxfGIY6HBPJUdx0dedwP42Oisg9t5KsC8zl\n" + + "d/+MIRgzkp+Dg0LXJVnDuwWEPoo2N6WhAr5ReLvXxALX5ht9Lb3lP0DASZvAKy9B\n" + + "O/wRCr294J8dg/CowAfloyf0Ko+JjyjanmZn3acy5CGkVN2mc+PFUekGZDDy5ooY\n" + + "kgXO/CmApuTNvabct+A7IVVdWWM5SWb90JvaV9SWji6nQphVm7StwsDEBB8BCgB4\n" + + "BYJaSXoACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lh\n" + + "LXBncC5vcmfVZdjLYZxDX2hvy3aGrsE4i0avLDMzf3e9kVHmaD6PAgIVCgKbAwIe\n" + + "ARYhBOMsttqCApG3522xqAitUcrkcPAGAABQYwgArfIRxq95npUKAOPXs25nZlvy\n" + + "+xQbrmsTxHhAYW8eGFcz82QwumoqrR8VfrojxM+eCZdTI85nM5kzznYDU2+cMhsZ\n" + + "Vm5+VhGZy3e3QH4J/E31D7t1opCvj5g1eRJ4LgywB+cYGcZBYp/bQT9SUYuhZH2O\n" + + "XCR04qSbpVUCIApnhBHxKNtOlqjAkHeaOdW/8XePsbfvrtVOLGYgrZXfY7Nqy3+W\n" + + "zbdm8UvVPFXH+uHEzTgyvYbnJBYkjORmCqUKs860PL8ekeg+sL4PHSRj1UUfwcQD\n" + + "55q0m3Vtew2KiIUi4wKi5LceDtprjoO5utU/1YfEAiNMeSQHXKq83dpazvjrUs0S\n" + + "anVsaWV0QGV4YW1wbGUub3JnwsDEBBMBCgB4BYJaSXoACRAIrVHK5HDwBkcUAAAA\n" + + "AAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmc6Rix7CeIfWwnaQjk3\n" + + "bBrkAiY7jS9N+shuRdHZ0gKKsgIVCgKbAwIeARYhBOMsttqCApG3522xqAitUcrk\n" + + "cPAGAACf9QgAsxtfAbyGbtofjrXTs9lsKEWvGgk02fSYyKjPbyaRqh72MlIlUXwq\n" + + "q1ih2TJc3vwF8aNVDrcb9DnBabdt2M1vI3PUaeG31BmakC/XZCNCrbbJkyd/vdML\n" + + "qw7prLrp0auVNNhLYxOK9usXbClNxluo4i/lSFVo5B9ai+ne1kKKiplzqy2qqhde\n" + + "plomcwGHbB1CkZ04DmCMbSSFAGxYqUC/bBm0bolCebw/KIz9sEojNKt6mvsFN67/\n" + + "hMYeJS0HVlwwc6i8iKSzC2D53iywhtvkdiKECXQeXDf9zNXAn1wpK01SLJ0iig7c\n" + + "DFrtoqkfPYzbNfC0bt34fNx9iz3w9aEH8c7ATQRaSsuAAQgAu5yau9psltmWiUn7\n" + + "fsRSqbQInO0iWnu4DK9IXB3ghNYMcii3JJEjHzgIxGf3GiJEjzubyRQaX5J/p7yB\n" + + "1fOH8z7FYUuax1saGf9c1/b02N9gyXNlHam31hNaaL3ffFczI95p7MNrTtroTt5o\n" + + "Zqsc+i+oKLZn7X0YAI4tEYwhSnUQYB/F7YqkkI4eV+7CxZPA8pBhXiAOK/zn416P\n" + + "sZ6JS5wsM65yCtOHcAAIBnKDnC+bQi+f1WZesSocy/rXx3QEQmodDu3ojhS+VxcY\n" + + "GeZCUcFF0FyZBIkGjHIVQLyOfjP3FRJ4qFXMz9/YIVoM4Y6guTERMTEj/KDG4BP7\n" + + "RfJHTQARAQABwsI8BBgBCgHwBYJeC+EACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0\n" + + "QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfcAa1ZPWTtg60w3Oo4dt4Fa8cKFYbZ\n" + + "YsqDSHV5pwEfMwKbAsC8oAQZAQoAbwWCXgvhAAkQEPy8/w6Op5FHFAAAAAAAHgAg\n" + + "c2FsdEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3JnL6I2+VyN5T1FoVgj3cdnMLYC\n" + + "pcB5i/FRSCVKybuLzrgWIQTOphDQhPpR8hHhxGwQ/Lz/Do6nkQAArk8H/AhjM9lq\n" + + "bffFL6RRR4HTjelspy4A3nyTicCljrDuXDUh23GfLvajTR5h16ZBqAF7cpb9rrlz\n" + + "1C1WcS5JLVxzXAe7f+KOfXu+eyLhpTzZ8VT3pK3hHGaYwlVlXrBZP0JXgL8hm6hD\n" + + "SXZQZtcpsnQ1uIHC9ONxUB4liNFhTqQCQYdQJFiFs1umUbo/C4KdzlDI08bM3CqE\n" + + "Kat9vUFuGG68mDg0CrRZEWt946L5i8kZmBUkSShIm2k5e2qE/muYeM6qKQNsxlx3\n" + + "VIf5eUhtxCi9fg7SjvHkdUSFstYcxAdaohWCFCEsDJI12hzcKQazSjvtKF4BNBKg\n" + + "X/wLsbVQnYLd9ggWIQTjLLbaggKRt+dtsagIrVHK5HDwBgAANjMH/1MY7DJyxkiT\n" + + "jc/jzmnVxqtHOZDCSmUqk0eh/6BHs+ostWqkGC6+7dfxDnptwcqandYey4KF2ajt\n" + + "4nOwu0xQw/NEF3i81h7IiewY7G+YT69DUd+DvVUQemfKNYVOrMqoH7QU5o4YojdJ\n" + + "iDeIp2d/JyJrqyof78JFAHnNZgHC2T2zo9E54dnOTY9VNUNCOUct5Rby0GXjTIUR\n" + + "O0f485eGuZxVWdLRllDYOiCrQHPSHhrxHVXVMbYJoroPy+IyaJanVoAWgyipBmmI\n" + + "DV8aINM2RLMsGkuPTRtITI2ZlGOQN7xgy4LqWzjPnrzMXfwBEDx/nrwdG6zEGMK8\n" + + "AkVkMT5uJJvCwjwEGAEKAfAFglro/4AJEAitUcrkcPAGRxQAAAAAAB4AIHNhbHRA\n" + + "bm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZ/Q0Z6WDH2+8/F1xEEuiApsjnn2lGNZ2\n" + + "DeIaklJzdqQOApsCwLygBBkBCgBvBYJa6P+ACRAQ/Lz/Do6nkUcUAAAAAAAeACBz\n" + + "YWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfrVATyX3tgcM2z41fqYquxVhJR\n" + + "avN6+w2SU4xEG++SqBYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAABGVggAsB8M2KI5\n" + + "cxXKKgVHL1dEfzg9halVavktfcT6ZVC/+aDp94tvBCL16Guhq4ccN7DATrWx430/\n" + + "GecY6E77qvhDzmCclSbdLbiZmsrVX9kCmTfrJzFQ64KfvIS5GgbL21+ZJ+pKW2HO\n" + + "MBGn6sgAPmTqM5UsDCpsEKDt5CJcJr3sTc8D9NhEnc0dKsQ91+n9ms3W5tyyE6r9\n" + + "pyM6ThBCMhbQkR7hE9XWAQeO1ILSFGnie0aFcTU0Oo0wL1MaiSyA/8XpKq23xfx1\n" + + "kNS9hQkdq0aWehNoTJdCt1Nq1cWABy2rQR0x+qhGWowfsAjnBautxvet28t2kPCA\n" + + "IMniYpWc89BwfhYhBOMsttqCApG3522xqAitUcrkcPAGAACq1gf/Q7H9Re5SWk+U\n" + + "On/NQPRedf544YJ/YdQnve/hSaPGL33cUzf4yxzFILnK19Ird5f8/mTT1pg99L3i\n" + + "xE3N5031JJKwFpCB69Rsysg88ZLDL2VLc3xdsAQdUbVaCqeRHKwtMtpBvbAFvF9p\n" + + "lwam0SSXHHr/JkYm5ufXN6I8ib/nwr1bFbf/Se0Wuk9RG4ne9JUBCrGxakyVd+Og\n" + + "LLhvzOmJa7fDC0uUZhTKFbjMxLhaas4HFYiRbfz2T0xz9gyDytDWsEFM+XoKHlEH\n" + + "8Fx/U2B5/8N0Q+pIFoEuOmBO+5EPvPIlxNByHgiaNIuKt1Mu+UAb2Spl6D5zbDfX\n" + + "/3vqxdhYHw==\n" + + "=Ric2\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + TestSignature t0 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJYaEaACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmeoPMfalw2oS7uyOKnOXJSN8Gx7pr/BMlo3Xn8nTgx6\n" + + "ORYhBOMsttqCApG3522xqAitUcrkcPAGAABXbAf/WfWaQYNuATAKwxYrJx4fd5kt\n" + + "0M6sn1q7wK1MIxursG2+FuKafV25O9+pde8Nog77OEgegwk+HokOVFpVXfOzHQjs\n" + + "8dwWTtTQlX5NIBNvtqS7cvCKhjsqaHKgmzsenMjCEbpDZ3C5CoqcYicykqEU/Ia0\n" + + "ZGC4lzRByrgNy/w+/iLN748S707bzBLVc/sE73k9N5pANAlE+cA/sHI1Gp2WxJR9\n" + + "t2Fk4x6/85PEnF1RHI16p/wSEeuRaBpyw9QGZBbVDVt5wvgttxZjteGGSwBM3WI/\n" + + "gPfC0LW+JQ2W+dwY0PN/7yuARVRhXpKiBI4xqp7x3OanQX6quU77g3B8nXAt3A==\n" + + "=StqT\n" + + "-----END PGP SIGNATURE-----\n", false, "Sig predates primary key"); + TestSignature t1 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJa564ACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfM0EN4Ei0bQv6UO9BRq2wtUfV948cRynRMBb8TSGCG\n" + + "tBYhBOMsttqCApG3522xqAitUcrkcPAGAAAlNwf+L0KQK9i/xmYKOMV2EX13QUoZ\n" + + "vvb/pHGZaCQ9JtvEF2l2DT0DqByZ+tOv5Y4isU+un7CraoyvyajAwR0Yqk937B6C\n" + + "HQHKMkmIl+5R4/xqSoWYmOidbrgilojPMBEhB3INQ8/THjjFijtLzitVhnWBd7+u\n" + + "s0kcqnWnOdx2By4aDe+UEiyCfSE02e/0tIsM71RqiU91zH6dl6+q8nml7PsYuTFV\n" + + "V09oQTbBuuvUe+YgN/uvyKVIsA64lQ+YhqEeIA8Quek7fHhW+du9OIhSPsbYodyx\n" + + "VWMTXwSWKGNvZNAkpmgUYqFjS2Cx5ZUWblZLjrNKBwnnmt50qvUN7+o2pjlnfA==\n" + + "=UuXb\n" + + "-----END PGP SIGNATURE-----\n", true); + TestSignature t2 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJdP4iACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfFzYGoiuSjN+gz1IDD4ZvRXGuPTHks0/pIiGY90mrZ\n" + + "WxYhBOMsttqCApG3522xqAitUcrkcPAGAABGPAf/ck7tJAFoPIDd9fTPZANpNGoW\n" + + "Fq6VuNfy/nLjz2gkHFX/lLAxQ0N3McIdRA++Ik/omb0lis3R2DVNgwqNm2OF34HE\n" + + "qxmPmrQHBgk2q0fDH4NCE0XnYQjQT65V99IfiaQu+oS3Mq8MuYsDYvRVvRKMwt49\n" + + "fcDnvFtAtCqEETdv6wV5cUZmdQ3L9NU9bApJ0jk+EHVdpfTUIbOYYGnsIe/4Aa0d\n" + + "jgzu4Em79ynosOn//953XJ7OO8LCDi1EKt+nFuZARUlt/Jwwull6zzp7HUPw6HPt\n" + + "Upp7os8TIPC4STwoSeEKaxEkrbMGFnDcoDajnKKRt5+MkB24Oq7PHvnzgnPpVg==\n" + + "=Ljv7\n" + + "-----END PGP SIGNATURE-----\n", true); + TestSignature t3 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJmhTYiCRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfbjQf/zfoJQT0hhna4RDjOESBLgGaCbc5HLeo751F4\n" + + "NxYhBOMsttqCApG3522xqAitUcrkcPAGAABqBQgAkkNmYf6yLPvox+ZayrLtMb9D\n" + + "ghgt0nau72DSazsJ6SAq2QqIdr0RRhRa2gCETkp4PpeoDWmIvoVj35ZnfyeO/jqy\n" + + "HECvRwO0WPA5FXQM6uG7s40vDTRFjlJMpPyHWnn2igcR64iDxBGmc40xi9CcmJP9\n" + + "tmA26+1Nzj1LcfNvknKZ2UIOmnXiZY0QssIdyqsmJrdFpXs4UCLUzdXkfFLoxksU\n" + + "mk4B6hig2IKMj5mnbWy/JQSXtjjI+HHmtzgWfXs7d9iQ61CklbtCOiPeWxvoqlGG\n" + + "oK1wV1olcSar/RPKTlMmQpAg9dztQgrNs1oF7EF3i9kwNP7I5JzekPiOLH6oMw==\n" + + "=5KMU\n" + + "-----END PGP SIGNATURE-----\n", true); + + signatureValidityTest(api, cert, t0, t1, t2, t3); + } + + private void testBaseCaseSubkeySigns(OpenPGPApi api) + throws IOException + { + // https://sequoia-pgp.gitlab.io/openpgp-interoperability-test-suite/results.html#Key_revocation_test__subkey_signs__primary_key_is_not_revoked__base_case_ + String cert = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xsBNBFpJegABCACzr1V+GxVkrtfDjihYK+HtyEIcO52uw7O2kd7JbduYp4RK17jy\n" + + "75N3EnsgmiIkSxXCWr+rTtonNs1zCJeUa/gwnNfs7mVgjL2rMOZU/KZ4MP0yOYU5\n" + + "u5FjNPWz8hpFQ9GKqfdj0Op61h1pCQO45IjUQ3dCDj9Rfn44zHMB1ZrbmIH9nTR1\n" + + "YIGHWmdm0LItb2WxIkwzWBAJ5acTlsmLyZZEQ1+8NDqktyzwFoQqTJvLU4StY2k6\n" + + "h18ZKZdPyrdLoEyOuWkvjxmbhDk1Gt5KiS/yy7mrzIPLr0dmJe4vc8WLV+bXoyNE\n" + + "x3H8o9CFcYehLfyqsy40lg92d6Kp96ww8dZ5ABEBAAHCwMQEHwEKAHgFgl4L4QAJ\n" + + "EAitUcrkcPAGRxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9y\n" + + "Z4csZe1ah1tj2AjxfdDMsH2wvSEwZjb/73ICKnm7BySQAhUKApsDAh4BFiEE4yy2\n" + + "2oICkbfnbbGoCK1RyuRw8AYAAGYFCACiKnCb2NBZa/Jj1aJe4R2rxPZj2ERXWe3b\n" + + "JKNPKT7K0rVDkTw1JRiTfCsuAY2lY9sKJdhQZl+azXm64vvTc6hEGRQ/+XssDlE2\n" + + "DIn8C34HDc495ZnryHNB8Dd5l1HdjqxfGIY6HBPJUdx0dedwP42Oisg9t5KsC8zl\n" + + "d/+MIRgzkp+Dg0LXJVnDuwWEPoo2N6WhAr5ReLvXxALX5ht9Lb3lP0DASZvAKy9B\n" + + "O/wRCr294J8dg/CowAfloyf0Ko+JjyjanmZn3acy5CGkVN2mc+PFUekGZDDy5ooY\n" + + "kgXO/CmApuTNvabct+A7IVVdWWM5SWb90JvaV9SWji6nQphVm7StwsDEBB8BCgB4\n" + + "BYJaSXoACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lh\n" + + "LXBncC5vcmfVZdjLYZxDX2hvy3aGrsE4i0avLDMzf3e9kVHmaD6PAgIVCgKbAwIe\n" + + "ARYhBOMsttqCApG3522xqAitUcrkcPAGAABQYwgArfIRxq95npUKAOPXs25nZlvy\n" + + "+xQbrmsTxHhAYW8eGFcz82QwumoqrR8VfrojxM+eCZdTI85nM5kzznYDU2+cMhsZ\n" + + "Vm5+VhGZy3e3QH4J/E31D7t1opCvj5g1eRJ4LgywB+cYGcZBYp/bQT9SUYuhZH2O\n" + + "XCR04qSbpVUCIApnhBHxKNtOlqjAkHeaOdW/8XePsbfvrtVOLGYgrZXfY7Nqy3+W\n" + + "zbdm8UvVPFXH+uHEzTgyvYbnJBYkjORmCqUKs860PL8ekeg+sL4PHSRj1UUfwcQD\n" + + "55q0m3Vtew2KiIUi4wKi5LceDtprjoO5utU/1YfEAiNMeSQHXKq83dpazvjrUs0S\n" + + "anVsaWV0QGV4YW1wbGUub3JnwsDEBBMBCgB4BYJaSXoACRAIrVHK5HDwBkcUAAAA\n" + + "AAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmc6Rix7CeIfWwnaQjk3\n" + + "bBrkAiY7jS9N+shuRdHZ0gKKsgIVCgKbAwIeARYhBOMsttqCApG3522xqAitUcrk\n" + + "cPAGAACf9QgAsxtfAbyGbtofjrXTs9lsKEWvGgk02fSYyKjPbyaRqh72MlIlUXwq\n" + + "q1ih2TJc3vwF8aNVDrcb9DnBabdt2M1vI3PUaeG31BmakC/XZCNCrbbJkyd/vdML\n" + + "qw7prLrp0auVNNhLYxOK9usXbClNxluo4i/lSFVo5B9ai+ne1kKKiplzqy2qqhde\n" + + "plomcwGHbB1CkZ04DmCMbSSFAGxYqUC/bBm0bolCebw/KIz9sEojNKt6mvsFN67/\n" + + "hMYeJS0HVlwwc6i8iKSzC2D53iywhtvkdiKECXQeXDf9zNXAn1wpK01SLJ0iig7c\n" + + "DFrtoqkfPYzbNfC0bt34fNx9iz3w9aEH8c7ATQRaSsuAAQgAu5yau9psltmWiUn7\n" + + "fsRSqbQInO0iWnu4DK9IXB3ghNYMcii3JJEjHzgIxGf3GiJEjzubyRQaX5J/p7yB\n" + + "1fOH8z7FYUuax1saGf9c1/b02N9gyXNlHam31hNaaL3ffFczI95p7MNrTtroTt5o\n" + + "Zqsc+i+oKLZn7X0YAI4tEYwhSnUQYB/F7YqkkI4eV+7CxZPA8pBhXiAOK/zn416P\n" + + "sZ6JS5wsM65yCtOHcAAIBnKDnC+bQi+f1WZesSocy/rXx3QEQmodDu3ojhS+VxcY\n" + + "GeZCUcFF0FyZBIkGjHIVQLyOfjP3FRJ4qFXMz9/YIVoM4Y6guTERMTEj/KDG4BP7\n" + + "RfJHTQARAQABwsI8BBgBCgHwBYJeC+EACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0\n" + + "QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfcAa1ZPWTtg60w3Oo4dt4Fa8cKFYbZ\n" + + "YsqDSHV5pwEfMwKbAsC8oAQZAQoAbwWCXgvhAAkQEPy8/w6Op5FHFAAAAAAAHgAg\n" + + "c2FsdEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3JnL6I2+VyN5T1FoVgj3cdnMLYC\n" + + "pcB5i/FRSCVKybuLzrgWIQTOphDQhPpR8hHhxGwQ/Lz/Do6nkQAArk8H/AhjM9lq\n" + + "bffFL6RRR4HTjelspy4A3nyTicCljrDuXDUh23GfLvajTR5h16ZBqAF7cpb9rrlz\n" + + "1C1WcS5JLVxzXAe7f+KOfXu+eyLhpTzZ8VT3pK3hHGaYwlVlXrBZP0JXgL8hm6hD\n" + + "SXZQZtcpsnQ1uIHC9ONxUB4liNFhTqQCQYdQJFiFs1umUbo/C4KdzlDI08bM3CqE\n" + + "Kat9vUFuGG68mDg0CrRZEWt946L5i8kZmBUkSShIm2k5e2qE/muYeM6qKQNsxlx3\n" + + "VIf5eUhtxCi9fg7SjvHkdUSFstYcxAdaohWCFCEsDJI12hzcKQazSjvtKF4BNBKg\n" + + "X/wLsbVQnYLd9ggWIQTjLLbaggKRt+dtsagIrVHK5HDwBgAANjMH/1MY7DJyxkiT\n" + + "jc/jzmnVxqtHOZDCSmUqk0eh/6BHs+ostWqkGC6+7dfxDnptwcqandYey4KF2ajt\n" + + "4nOwu0xQw/NEF3i81h7IiewY7G+YT69DUd+DvVUQemfKNYVOrMqoH7QU5o4YojdJ\n" + + "iDeIp2d/JyJrqyof78JFAHnNZgHC2T2zo9E54dnOTY9VNUNCOUct5Rby0GXjTIUR\n" + + "O0f485eGuZxVWdLRllDYOiCrQHPSHhrxHVXVMbYJoroPy+IyaJanVoAWgyipBmmI\n" + + "DV8aINM2RLMsGkuPTRtITI2ZlGOQN7xgy4LqWzjPnrzMXfwBEDx/nrwdG6zEGMK8\n" + + "AkVkMT5uJJvCwjwEGAEKAfAFglro/4AJEAitUcrkcPAGRxQAAAAAAB4AIHNhbHRA\n" + + "bm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZ/Q0Z6WDH2+8/F1xEEuiApsjnn2lGNZ2\n" + + "DeIaklJzdqQOApsCwLygBBkBCgBvBYJa6P+ACRAQ/Lz/Do6nkUcUAAAAAAAeACBz\n" + + "YWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfrVATyX3tgcM2z41fqYquxVhJR\n" + + "avN6+w2SU4xEG++SqBYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAABGVggAsB8M2KI5\n" + + "cxXKKgVHL1dEfzg9halVavktfcT6ZVC/+aDp94tvBCL16Guhq4ccN7DATrWx430/\n" + + "GecY6E77qvhDzmCclSbdLbiZmsrVX9kCmTfrJzFQ64KfvIS5GgbL21+ZJ+pKW2HO\n" + + "MBGn6sgAPmTqM5UsDCpsEKDt5CJcJr3sTc8D9NhEnc0dKsQ91+n9ms3W5tyyE6r9\n" + + "pyM6ThBCMhbQkR7hE9XWAQeO1ILSFGnie0aFcTU0Oo0wL1MaiSyA/8XpKq23xfx1\n" + + "kNS9hQkdq0aWehNoTJdCt1Nq1cWABy2rQR0x+qhGWowfsAjnBautxvet28t2kPCA\n" + + "IMniYpWc89BwfhYhBOMsttqCApG3522xqAitUcrkcPAGAACq1gf/Q7H9Re5SWk+U\n" + + "On/NQPRedf544YJ/YdQnve/hSaPGL33cUzf4yxzFILnK19Ird5f8/mTT1pg99L3i\n" + + "xE3N5031JJKwFpCB69Rsysg88ZLDL2VLc3xdsAQdUbVaCqeRHKwtMtpBvbAFvF9p\n" + + "lwam0SSXHHr/JkYm5ufXN6I8ib/nwr1bFbf/Se0Wuk9RG4ne9JUBCrGxakyVd+Og\n" + + "LLhvzOmJa7fDC0uUZhTKFbjMxLhaas4HFYiRbfz2T0xz9gyDytDWsEFM+XoKHlEH\n" + + "8Fx/U2B5/8N0Q+pIFoEuOmBO+5EPvPIlxNByHgiaNIuKt1Mu+UAb2Spl6D5zbDfX\n" + + "/3vqxdhYHw==\n" + + "=Ric2\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + TestSignature t0 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJYaEaACRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmdVa4OG6WfRoRlj5+Zb6avhJUIZFvcIFiLuvrJp8Hio\n" + + "iBYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAAAbaQgAjhBh0dLO0Sqiqkb2M3KWc25V\n" + + "hJlcP3isFROJ0jikmXxkG9W04AvlA78tSxEP2n8a0CbxH/hT4g8mFb/qM5FKZcKf\n" + + "HQxjbjUxBmVHa3EfMkwT7u1mVRmoWtJ59oVsKoqRb/kZ14i6VZ9NzfK8MRlL0e24\n" + + "oNjkksZQ8ImjwwtvxSinxhezA6BtWi+dDnXAnG5Vva+6N/GRNPAAd8kFTPrlEqEz\n" + + "uRbpq76r4taPjRjzMNcwZJoRVHSahWhDcXxNTalVUwt0DZFAskZ3gI+0VgU11bK1\n" + + "QmIw2iR4itQY5f10HFNcl7uHLKnul0YyuvA5509HwCuEpdYUV/OxtlpVRaJ+yg==\n" + + "=Rc6K\n" + + "-----END PGP SIGNATURE-----\n", false, "Signature predates primary key"); + TestSignature t1 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJa564ACRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfcG7Iqn3OOKVjeJ61MlgERt08kcxh0x+BZFD7a8K7V\n" + + "VBYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAACBIwf9EoS24IFeT3cPFf/nWxLFkbZK\n" + + "fiy9WzyK4wlpO3VTyWPbXi6zpC4I5Rbp2jDk/c7Q3DnOZqFDv6TriTwuLYTJGPxr\n" + + "U3dtDsFcKp4FcbgFyCDKIuLB+3kLaNpMXqdttEkY3Wd5m33XrBB7M0l5xZCk56Jm\n" + + "H5L1sGNNNkCzG6P44qu69o5fkWxbYuX22fyhdeyxucJHMztqiMQYDwT7eSA92A1v\n" + + "5OwA5D/k7GeyYFBFisxRijkdVtxstC9zkagC19VnZo7MRekA9gXj7kIna4XYRhfb\n" + + "uQnN47HXdiWQytwypLvZ8JEJpRruyMAaHjX5OBXh0SK11xYWb6wB93+QfOahtg==\n" + + "=UlUZ\n" + + "-----END PGP SIGNATURE-----\n", false, "Subkey is not bound at this time"); + TestSignature t2 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJdP4iACRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmcgkZw3ZSg8CZCKqJw2r4VqCpTuUhz6N0zX43d+1xop\n" + + "2hYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAADnqAgAq+m6dDZpNOBaXH9nwv8/+HgR\n" + + "MvRjnuLoa6zB5tcUhGPPVS0gg1PW0wfxlo1GPmgW3QDlV1zvcfYAZmV9uEC61wn/\n" + + "+FkqN0Tceo487UvkWARE/mmRj5L8OgUTfqm1eebFQlMu/MeG9YOg+tXBy7XS7hy3\n" + + "UdntIbtsv5oRTcybTnn5oiU2OFDlFC6sBNzOQt7wpyB1TKp2BdcsAv1RwmyCCCK4\n" + + "bnmrpYH6woWMyVEVeMYfOHAx9vHD+od8Vf/v5L1M2N0nHzRWjjkobTVUr+xt/CyW\n" + + "nq8SoazKYu3ETpZLeWX6Bciuv9+pzUCeClOSmBB1MFyyrTgbkOacHgrYnLvvtQ==\n" + + "=WCKA\n" + + "-----END PGP SIGNATURE-----\n", true); + TestSignature t3 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJmhTYiCRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmdi3dCpJ4nZincNH5owv8+fJ5YpXljqtegtoBEnbbHP\n" + + "thYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAAD0cQf/e8RHocRESJPbosqUuvC3ELnD\n" + + "oSsJomDMUDfSfgpS5EhkOyJhvcrHkCbsHH2xlUEQ+zjJWY/dwM3FUkoj+p3kb/JC\n" + + "Rn5cqQYlME+uJzjdHMyQCSOI1SvYwKCLCGPARDbCpeINrV++Oy29e6cv6/IcPlgo\n" + + "k/0A7XuNq0YNxC7oopCj5ye3yVUvUmSCG2iV4oiWW5GhhPRzMeW7MFQmS0NUkAI8\n" + + "hzJ8juTG4xP8SXnHCMakasZhJmtpMDd2BDZ7CrhWiWUQGrtd0eYkuyodreqVMGIF\n" + + "BN80YgTNFW2MrblhDRRmxAqWzD9FedBwwSdgYbtkDwjsSq0S1jQV6aPndJqiLw==\n" + + "=CIl0\n" + + "-----END PGP SIGNATURE-----\n", true); + + signatureValidityTest(api, cert, t0, t1, t2, t3); + } + + private void testPKSignsPKRevokedNoSubpacket(OpenPGPApi api) + throws IOException + { + String cert = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xsBNBFpJegABCACzr1V+GxVkrtfDjihYK+HtyEIcO52uw7O2kd7JbduYp4RK17jy\n" + + "75N3EnsgmiIkSxXCWr+rTtonNs1zCJeUa/gwnNfs7mVgjL2rMOZU/KZ4MP0yOYU5\n" + + "u5FjNPWz8hpFQ9GKqfdj0Op61h1pCQO45IjUQ3dCDj9Rfn44zHMB1ZrbmIH9nTR1\n" + + "YIGHWmdm0LItb2WxIkwzWBAJ5acTlsmLyZZEQ1+8NDqktyzwFoQqTJvLU4StY2k6\n" + + "h18ZKZdPyrdLoEyOuWkvjxmbhDk1Gt5KiS/yy7mrzIPLr0dmJe4vc8WLV+bXoyNE\n" + + "x3H8o9CFcYehLfyqsy40lg92d6Kp96ww8dZ5ABEBAAHCwLsEIAEKAG8FglwqrYAJ\n" + + "EAitUcrkcPAGRxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9y\n" + + "Z4KjdWVHTHye8HeUynibpgE5TYfFnnBt9bbOj99oplaTFiEE4yy22oICkbfnbbGo\n" + + "CK1RyuRw8AYAAMxeB/4+QAncX1+678HeO1fweQ0Zkf4O6+Ew6EgCp4I2UZu+a5H8\n" + + "ryI3B4WNShCDoV3CfOcUtUSUA8EOyrpYSW/3jPVfb01uxDNsZpf9piZG7DelIAef\n" + + "wvQaZHJeytchv5+Wo+Jo6qg26BgvUlXW2x5NNcScGvCZt1RQ712PRDAfUnppRXBj\n" + + "+IXWzOs52uYGFDFzJSLEUy6dtTdNCJk78EMoHsOwC7g5uUyHbjSfrdQncxgMwikl\n" + + "C2LFSS7xYZwDgkkb70AT10Ot2jL6rLIT/1ChQZ0oRGJLBHiz3FUpanDQIDD49+dp\n" + + "6FUmUUsubwwFkxBHyCbQ8cdbfBILNiD1pEo31dPTwsDEBB8BCgB4BYJeC+EACRAI\n" + + "rVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmeH\n" + + "LGXtWodbY9gI8X3QzLB9sL0hMGY2/+9yAip5uwckkAIVCgKbAwIeARYhBOMsttqC\n" + + "ApG3522xqAitUcrkcPAGAABmBQgAoipwm9jQWWvyY9WiXuEdq8T2Y9hEV1nt2ySj\n" + + "Tyk+ytK1Q5E8NSUYk3wrLgGNpWPbCiXYUGZfms15uuL703OoRBkUP/l7LA5RNgyJ\n" + + "/At+Bw3OPeWZ68hzQfA3eZdR3Y6sXxiGOhwTyVHcdHXncD+NjorIPbeSrAvM5Xf/\n" + + "jCEYM5Kfg4NC1yVZw7sFhD6KNjeloQK+UXi718QC1+YbfS295T9AwEmbwCsvQTv8\n" + + "EQq9veCfHYPwqMAH5aMn9CqPiY8o2p5mZ92nMuQhpFTdpnPjxVHpBmQw8uaKGJIF\n" + + "zvwpgKbkzb2m3LfgOyFVXVljOUlm/dCb2lfUlo4up0KYVZu0rcLAxAQfAQoAeAWC\n" + + "Wkl6AAkQCK1RyuRw8AZHFAAAAAAAHgAgc2FsdEBub3RhdGlvbnMuc2VxdW9pYS1w\n" + + "Z3Aub3Jn1WXYy2GcQ19ob8t2hq7BOItGrywzM393vZFR5mg+jwICFQoCmwMCHgEW\n" + + "IQTjLLbaggKRt+dtsagIrVHK5HDwBgAAUGMIAK3yEcaveZ6VCgDj17NuZ2Zb8vsU\n" + + "G65rE8R4QGFvHhhXM/NkMLpqKq0fFX66I8TPngmXUyPOZzOZM852A1NvnDIbGVZu\n" + + "flYRmct3t0B+CfxN9Q+7daKQr4+YNXkSeC4MsAfnGBnGQWKf20E/UlGLoWR9jlwk\n" + + "dOKkm6VVAiAKZ4QR8SjbTpaowJB3mjnVv/F3j7G3767VTixmIK2V32Ozast/ls23\n" + + "ZvFL1TxVx/rhxM04Mr2G5yQWJIzkZgqlCrPOtDy/HpHoPrC+Dx0kY9VFH8HEA+ea\n" + + "tJt1bXsNioiFIuMCouS3Hg7aa46DubrVP9WHxAIjTHkkB1yqvN3aWs7461LNEmp1\n" + + "bGlldEBleGFtcGxlLm9yZ8LAxAQTAQoAeAWCWkl6AAkQCK1RyuRw8AZHFAAAAAAA\n" + + "HgAgc2FsdEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3JnOkYsewniH1sJ2kI5N2wa\n" + + "5AImO40vTfrIbkXR2dICirICFQoCmwMCHgEWIQTjLLbaggKRt+dtsagIrVHK5HDw\n" + + "BgAAn/UIALMbXwG8hm7aH46107PZbChFrxoJNNn0mMioz28mkaoe9jJSJVF8KqtY\n" + + "odkyXN78BfGjVQ63G/Q5wWm3bdjNbyNz1Gnht9QZmpAv12QjQq22yZMnf73TC6sO\n" + + "6ay66dGrlTTYS2MTivbrF2wpTcZbqOIv5UhVaOQfWovp3tZCioqZc6stqqoXXqZa\n" + + "JnMBh2wdQpGdOA5gjG0khQBsWKlAv2wZtG6JQnm8PyiM/bBKIzSrepr7BTeu/4TG\n" + + "HiUtB1ZcMHOovIikswtg+d4ssIbb5HYihAl0Hlw3/czVwJ9cKStNUiydIooO3Axa\n" + + "7aKpHz2M2zXwtG7d+HzcfYs98PWhB/HOwE0EWkrLgAEIALucmrvabJbZlolJ+37E\n" + + "Uqm0CJztIlp7uAyvSFwd4ITWDHIotySRIx84CMRn9xoiRI87m8kUGl+Sf6e8gdXz\n" + + "h/M+xWFLmsdbGhn/XNf29NjfYMlzZR2pt9YTWmi933xXMyPeaezDa07a6E7eaGar\n" + + "HPovqCi2Z+19GACOLRGMIUp1EGAfxe2KpJCOHlfuwsWTwPKQYV4gDiv85+Nej7Ge\n" + + "iUucLDOucgrTh3AACAZyg5wvm0Ivn9VmXrEqHMv618d0BEJqHQ7t6I4UvlcXGBnm\n" + + "QlHBRdBcmQSJBoxyFUC8jn4z9xUSeKhVzM/f2CFaDOGOoLkxETExI/ygxuAT+0Xy\n" + + "R00AEQEAAcLCPAQYAQoB8AWCXgvhAAkQCK1RyuRw8AZHFAAAAAAAHgAgc2FsdEBu\n" + + "b3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3Jn3AGtWT1k7YOtMNzqOHbeBWvHChWG2WLK\n" + + "g0h1eacBHzMCmwLAvKAEGQEKAG8Fgl4L4QAJEBD8vP8OjqeRRxQAAAAAAB4AIHNh\n" + + "bHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZy+iNvlcjeU9RaFYI93HZzC2AqXA\n" + + "eYvxUUglSsm7i864FiEEzqYQ0IT6UfIR4cRsEPy8/w6Op5EAAK5PB/wIYzPZam33\n" + + "xS+kUUeB043pbKcuAN58k4nApY6w7lw1Idtxny72o00eYdemQagBe3KW/a65c9Qt\n" + + "VnEuSS1cc1wHu3/ijn17vnsi4aU82fFU96St4RxmmMJVZV6wWT9CV4C/IZuoQ0l2\n" + + "UGbXKbJ0NbiBwvTjcVAeJYjRYU6kAkGHUCRYhbNbplG6PwuCnc5QyNPGzNwqhCmr\n" + + "fb1BbhhuvJg4NAq0WRFrfeOi+YvJGZgVJEkoSJtpOXtqhP5rmHjOqikDbMZcd1SH\n" + + "+XlIbcQovX4O0o7x5HVEhbLWHMQHWqIVghQhLAySNdoc3CkGs0o77SheATQSoF/8\n" + + "C7G1UJ2C3fYIFiEE4yy22oICkbfnbbGoCK1RyuRw8AYAADYzB/9TGOwycsZIk43P\n" + + "485p1carRzmQwkplKpNHof+gR7PqLLVqpBguvu3X8Q56bcHKmp3WHsuChdmo7eJz\n" + + "sLtMUMPzRBd4vNYeyInsGOxvmE+vQ1Hfg71VEHpnyjWFTqzKqB+0FOaOGKI3SYg3\n" + + "iKdnfycia6sqH+/CRQB5zWYBwtk9s6PROeHZzk2PVTVDQjlHLeUW8tBl40yFETtH\n" + + "+POXhrmcVVnS0ZZQ2Dogq0Bz0h4a8R1V1TG2CaK6D8viMmiWp1aAFoMoqQZpiA1f\n" + + "GiDTNkSzLBpLj00bSEyNmZRjkDe8YMuC6ls4z568zF38ARA8f568HRusxBjCvAJF\n" + + "ZDE+biSbwsI8BBgBCgHwBYJa6P+ACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5v\n" + + "dGF0aW9ucy5zZXF1b2lhLXBncC5vcmf0NGelgx9vvPxdcRBLogKbI559pRjWdg3i\n" + + "GpJSc3akDgKbAsC8oAQZAQoAbwWCWuj/gAkQEPy8/w6Op5FHFAAAAAAAHgAgc2Fs\n" + + "dEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3Jn61QE8l97YHDNs+NX6mKrsVYSUWrz\n" + + "evsNklOMRBvvkqgWIQTOphDQhPpR8hHhxGwQ/Lz/Do6nkQAARlYIALAfDNiiOXMV\n" + + "yioFRy9XRH84PYWpVWr5LX3E+mVQv/mg6feLbwQi9ehroauHHDewwE61seN9Pxnn\n" + + "GOhO+6r4Q85gnJUm3S24mZrK1V/ZApk36ycxUOuCn7yEuRoGy9tfmSfqSlthzjAR\n" + + "p+rIAD5k6jOVLAwqbBCg7eQiXCa97E3PA/TYRJ3NHSrEPdfp/ZrN1ubcshOq/acj\n" + + "Ok4QQjIW0JEe4RPV1gEHjtSC0hRp4ntGhXE1NDqNMC9TGoksgP/F6Sqtt8X8dZDU\n" + + "vYUJHatGlnoTaEyXQrdTatXFgActq0EdMfqoRlqMH7AI5wWrrcb3rdvLdpDwgCDJ\n" + + "4mKVnPPQcH4WIQTjLLbaggKRt+dtsagIrVHK5HDwBgAAqtYH/0Ox/UXuUlpPlDp/\n" + + "zUD0XnX+eOGCf2HUJ73v4Umjxi993FM3+MscxSC5ytfSK3eX/P5k09aYPfS94sRN\n" + + "zedN9SSSsBaQgevUbMrIPPGSwy9lS3N8XbAEHVG1WgqnkRysLTLaQb2wBbxfaZcG\n" + + "ptEklxx6/yZGJubn1zeiPIm/58K9WxW3/0ntFrpPURuJ3vSVAQqxsWpMlXfjoCy4\n" + + "b8zpiWu3wwtLlGYUyhW4zMS4WmrOBxWIkW389k9Mc/YMg8rQ1rBBTPl6Ch5RB/Bc\n" + + "f1Ngef/DdEPqSBaBLjpgTvuRD7zyJcTQch4ImjSLirdTLvlAG9kqZeg+c2w31/97\n" + + "6sXYWB8=\n" + + "=13Sf\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + TestSignature t0 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJYaEaACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmeoPMfalw2oS7uyOKnOXJSN8Gx7pr/BMlo3Xn8nTgx6\n" + + "ORYhBOMsttqCApG3522xqAitUcrkcPAGAABXbAf/WfWaQYNuATAKwxYrJx4fd5kt\n" + + "0M6sn1q7wK1MIxursG2+FuKafV25O9+pde8Nog77OEgegwk+HokOVFpVXfOzHQjs\n" + + "8dwWTtTQlX5NIBNvtqS7cvCKhjsqaHKgmzsenMjCEbpDZ3C5CoqcYicykqEU/Ia0\n" + + "ZGC4lzRByrgNy/w+/iLN748S707bzBLVc/sE73k9N5pANAlE+cA/sHI1Gp2WxJR9\n" + + "t2Fk4x6/85PEnF1RHI16p/wSEeuRaBpyw9QGZBbVDVt5wvgttxZjteGGSwBM3WI/\n" + + "gPfC0LW+JQ2W+dwY0PN/7yuARVRhXpKiBI4xqp7x3OanQX6quU77g3B8nXAt3A==\n" + + "=StqT\n" + + "-----END PGP SIGNATURE-----\n", false, "Signature predates primary key"); + TestSignature t1 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJa564ACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfM0EN4Ei0bQv6UO9BRq2wtUfV948cRynRMBb8TSGCG\n" + + "tBYhBOMsttqCApG3522xqAitUcrkcPAGAAAlNwf+L0KQK9i/xmYKOMV2EX13QUoZ\n" + + "vvb/pHGZaCQ9JtvEF2l2DT0DqByZ+tOv5Y4isU+un7CraoyvyajAwR0Yqk937B6C\n" + + "HQHKMkmIl+5R4/xqSoWYmOidbrgilojPMBEhB3INQ8/THjjFijtLzitVhnWBd7+u\n" + + "s0kcqnWnOdx2By4aDe+UEiyCfSE02e/0tIsM71RqiU91zH6dl6+q8nml7PsYuTFV\n" + + "V09oQTbBuuvUe+YgN/uvyKVIsA64lQ+YhqEeIA8Quek7fHhW+du9OIhSPsbYodyx\n" + + "VWMTXwSWKGNvZNAkpmgUYqFjS2Cx5ZUWblZLjrNKBwnnmt50qvUN7+o2pjlnfA==\n" + + "=UuXb\n" + + "-----END PGP SIGNATURE-----\n", false, "Hard revocations invalidate key at all times"); + TestSignature t2 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJdP4iACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfFzYGoiuSjN+gz1IDD4ZvRXGuPTHks0/pIiGY90mrZ\n" + + "WxYhBOMsttqCApG3522xqAitUcrkcPAGAABGPAf/ck7tJAFoPIDd9fTPZANpNGoW\n" + + "Fq6VuNfy/nLjz2gkHFX/lLAxQ0N3McIdRA++Ik/omb0lis3R2DVNgwqNm2OF34HE\n" + + "qxmPmrQHBgk2q0fDH4NCE0XnYQjQT65V99IfiaQu+oS3Mq8MuYsDYvRVvRKMwt49\n" + + "fcDnvFtAtCqEETdv6wV5cUZmdQ3L9NU9bApJ0jk+EHVdpfTUIbOYYGnsIe/4Aa0d\n" + + "jgzu4Em79ynosOn//953XJ7OO8LCDi1EKt+nFuZARUlt/Jwwull6zzp7HUPw6HPt\n" + + "Upp7os8TIPC4STwoSeEKaxEkrbMGFnDcoDajnKKRt5+MkB24Oq7PHvnzgnPpVg==\n" + + "=Ljv7\n" + + "-----END PGP SIGNATURE-----\n", false, "Hard revocations invalidate key at all times"); + TestSignature t3 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJmhTYiCRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfbjQf/zfoJQT0hhna4RDjOESBLgGaCbc5HLeo751F4\n" + + "NxYhBOMsttqCApG3522xqAitUcrkcPAGAABqBQgAkkNmYf6yLPvox+ZayrLtMb9D\n" + + "ghgt0nau72DSazsJ6SAq2QqIdr0RRhRa2gCETkp4PpeoDWmIvoVj35ZnfyeO/jqy\n" + + "HECvRwO0WPA5FXQM6uG7s40vDTRFjlJMpPyHWnn2igcR64iDxBGmc40xi9CcmJP9\n" + + "tmA26+1Nzj1LcfNvknKZ2UIOmnXiZY0QssIdyqsmJrdFpXs4UCLUzdXkfFLoxksU\n" + + "mk4B6hig2IKMj5mnbWy/JQSXtjjI+HHmtzgWfXs7d9iQ61CklbtCOiPeWxvoqlGG\n" + + "oK1wV1olcSar/RPKTlMmQpAg9dztQgrNs1oF7EF3i9kwNP7I5JzekPiOLH6oMw==\n" + + "=5KMU\n" + + "-----END PGP SIGNATURE-----\n", false, "Hard revocations invalidate key at all times"); + + signatureValidityTest(api, cert, t0, t1, t2, t3); + } + + private void testSKSignsPKRevokedNoSubpacket(OpenPGPApi api) + throws IOException + { + // https://sequoia-pgp.gitlab.io/openpgp-interoperability-test-suite/results.html#Key_revocation_test__subkey_signs__primary_key_is_revoked__revoked__no_subpacket + String cert = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xsBNBFpJegABCACzr1V+GxVkrtfDjihYK+HtyEIcO52uw7O2kd7JbduYp4RK17jy\n" + + "75N3EnsgmiIkSxXCWr+rTtonNs1zCJeUa/gwnNfs7mVgjL2rMOZU/KZ4MP0yOYU5\n" + + "u5FjNPWz8hpFQ9GKqfdj0Op61h1pCQO45IjUQ3dCDj9Rfn44zHMB1ZrbmIH9nTR1\n" + + "YIGHWmdm0LItb2WxIkwzWBAJ5acTlsmLyZZEQ1+8NDqktyzwFoQqTJvLU4StY2k6\n" + + "h18ZKZdPyrdLoEyOuWkvjxmbhDk1Gt5KiS/yy7mrzIPLr0dmJe4vc8WLV+bXoyNE\n" + + "x3H8o9CFcYehLfyqsy40lg92d6Kp96ww8dZ5ABEBAAHCwLsEIAEKAG8FglwqrYAJ\n" + + "EAitUcrkcPAGRxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9y\n" + + "Z4KjdWVHTHye8HeUynibpgE5TYfFnnBt9bbOj99oplaTFiEE4yy22oICkbfnbbGo\n" + + "CK1RyuRw8AYAAMxeB/4+QAncX1+678HeO1fweQ0Zkf4O6+Ew6EgCp4I2UZu+a5H8\n" + + "ryI3B4WNShCDoV3CfOcUtUSUA8EOyrpYSW/3jPVfb01uxDNsZpf9piZG7DelIAef\n" + + "wvQaZHJeytchv5+Wo+Jo6qg26BgvUlXW2x5NNcScGvCZt1RQ712PRDAfUnppRXBj\n" + + "+IXWzOs52uYGFDFzJSLEUy6dtTdNCJk78EMoHsOwC7g5uUyHbjSfrdQncxgMwikl\n" + + "C2LFSS7xYZwDgkkb70AT10Ot2jL6rLIT/1ChQZ0oRGJLBHiz3FUpanDQIDD49+dp\n" + + "6FUmUUsubwwFkxBHyCbQ8cdbfBILNiD1pEo31dPTwsDEBB8BCgB4BYJeC+EACRAI\n" + + "rVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmeH\n" + + "LGXtWodbY9gI8X3QzLB9sL0hMGY2/+9yAip5uwckkAIVCgKbAwIeARYhBOMsttqC\n" + + "ApG3522xqAitUcrkcPAGAABmBQgAoipwm9jQWWvyY9WiXuEdq8T2Y9hEV1nt2ySj\n" + + "Tyk+ytK1Q5E8NSUYk3wrLgGNpWPbCiXYUGZfms15uuL703OoRBkUP/l7LA5RNgyJ\n" + + "/At+Bw3OPeWZ68hzQfA3eZdR3Y6sXxiGOhwTyVHcdHXncD+NjorIPbeSrAvM5Xf/\n" + + "jCEYM5Kfg4NC1yVZw7sFhD6KNjeloQK+UXi718QC1+YbfS295T9AwEmbwCsvQTv8\n" + + "EQq9veCfHYPwqMAH5aMn9CqPiY8o2p5mZ92nMuQhpFTdpnPjxVHpBmQw8uaKGJIF\n" + + "zvwpgKbkzb2m3LfgOyFVXVljOUlm/dCb2lfUlo4up0KYVZu0rcLAxAQfAQoAeAWC\n" + + "Wkl6AAkQCK1RyuRw8AZHFAAAAAAAHgAgc2FsdEBub3RhdGlvbnMuc2VxdW9pYS1w\n" + + "Z3Aub3Jn1WXYy2GcQ19ob8t2hq7BOItGrywzM393vZFR5mg+jwICFQoCmwMCHgEW\n" + + "IQTjLLbaggKRt+dtsagIrVHK5HDwBgAAUGMIAK3yEcaveZ6VCgDj17NuZ2Zb8vsU\n" + + "G65rE8R4QGFvHhhXM/NkMLpqKq0fFX66I8TPngmXUyPOZzOZM852A1NvnDIbGVZu\n" + + "flYRmct3t0B+CfxN9Q+7daKQr4+YNXkSeC4MsAfnGBnGQWKf20E/UlGLoWR9jlwk\n" + + "dOKkm6VVAiAKZ4QR8SjbTpaowJB3mjnVv/F3j7G3767VTixmIK2V32Ozast/ls23\n" + + "ZvFL1TxVx/rhxM04Mr2G5yQWJIzkZgqlCrPOtDy/HpHoPrC+Dx0kY9VFH8HEA+ea\n" + + "tJt1bXsNioiFIuMCouS3Hg7aa46DubrVP9WHxAIjTHkkB1yqvN3aWs7461LNEmp1\n" + + "bGlldEBleGFtcGxlLm9yZ8LAxAQTAQoAeAWCWkl6AAkQCK1RyuRw8AZHFAAAAAAA\n" + + "HgAgc2FsdEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3JnOkYsewniH1sJ2kI5N2wa\n" + + "5AImO40vTfrIbkXR2dICirICFQoCmwMCHgEWIQTjLLbaggKRt+dtsagIrVHK5HDw\n" + + "BgAAn/UIALMbXwG8hm7aH46107PZbChFrxoJNNn0mMioz28mkaoe9jJSJVF8KqtY\n" + + "odkyXN78BfGjVQ63G/Q5wWm3bdjNbyNz1Gnht9QZmpAv12QjQq22yZMnf73TC6sO\n" + + "6ay66dGrlTTYS2MTivbrF2wpTcZbqOIv5UhVaOQfWovp3tZCioqZc6stqqoXXqZa\n" + + "JnMBh2wdQpGdOA5gjG0khQBsWKlAv2wZtG6JQnm8PyiM/bBKIzSrepr7BTeu/4TG\n" + + "HiUtB1ZcMHOovIikswtg+d4ssIbb5HYihAl0Hlw3/czVwJ9cKStNUiydIooO3Axa\n" + + "7aKpHz2M2zXwtG7d+HzcfYs98PWhB/HOwE0EWkrLgAEIALucmrvabJbZlolJ+37E\n" + + "Uqm0CJztIlp7uAyvSFwd4ITWDHIotySRIx84CMRn9xoiRI87m8kUGl+Sf6e8gdXz\n" + + "h/M+xWFLmsdbGhn/XNf29NjfYMlzZR2pt9YTWmi933xXMyPeaezDa07a6E7eaGar\n" + + "HPovqCi2Z+19GACOLRGMIUp1EGAfxe2KpJCOHlfuwsWTwPKQYV4gDiv85+Nej7Ge\n" + + "iUucLDOucgrTh3AACAZyg5wvm0Ivn9VmXrEqHMv618d0BEJqHQ7t6I4UvlcXGBnm\n" + + "QlHBRdBcmQSJBoxyFUC8jn4z9xUSeKhVzM/f2CFaDOGOoLkxETExI/ygxuAT+0Xy\n" + + "R00AEQEAAcLCPAQYAQoB8AWCXgvhAAkQCK1RyuRw8AZHFAAAAAAAHgAgc2FsdEBu\n" + + "b3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3Jn3AGtWT1k7YOtMNzqOHbeBWvHChWG2WLK\n" + + "g0h1eacBHzMCmwLAvKAEGQEKAG8Fgl4L4QAJEBD8vP8OjqeRRxQAAAAAAB4AIHNh\n" + + "bHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZy+iNvlcjeU9RaFYI93HZzC2AqXA\n" + + "eYvxUUglSsm7i864FiEEzqYQ0IT6UfIR4cRsEPy8/w6Op5EAAK5PB/wIYzPZam33\n" + + "xS+kUUeB043pbKcuAN58k4nApY6w7lw1Idtxny72o00eYdemQagBe3KW/a65c9Qt\n" + + "VnEuSS1cc1wHu3/ijn17vnsi4aU82fFU96St4RxmmMJVZV6wWT9CV4C/IZuoQ0l2\n" + + "UGbXKbJ0NbiBwvTjcVAeJYjRYU6kAkGHUCRYhbNbplG6PwuCnc5QyNPGzNwqhCmr\n" + + "fb1BbhhuvJg4NAq0WRFrfeOi+YvJGZgVJEkoSJtpOXtqhP5rmHjOqikDbMZcd1SH\n" + + "+XlIbcQovX4O0o7x5HVEhbLWHMQHWqIVghQhLAySNdoc3CkGs0o77SheATQSoF/8\n" + + "C7G1UJ2C3fYIFiEE4yy22oICkbfnbbGoCK1RyuRw8AYAADYzB/9TGOwycsZIk43P\n" + + "485p1carRzmQwkplKpNHof+gR7PqLLVqpBguvu3X8Q56bcHKmp3WHsuChdmo7eJz\n" + + "sLtMUMPzRBd4vNYeyInsGOxvmE+vQ1Hfg71VEHpnyjWFTqzKqB+0FOaOGKI3SYg3\n" + + "iKdnfycia6sqH+/CRQB5zWYBwtk9s6PROeHZzk2PVTVDQjlHLeUW8tBl40yFETtH\n" + + "+POXhrmcVVnS0ZZQ2Dogq0Bz0h4a8R1V1TG2CaK6D8viMmiWp1aAFoMoqQZpiA1f\n" + + "GiDTNkSzLBpLj00bSEyNmZRjkDe8YMuC6ls4z568zF38ARA8f568HRusxBjCvAJF\n" + + "ZDE+biSbwsI8BBgBCgHwBYJa6P+ACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5v\n" + + "dGF0aW9ucy5zZXF1b2lhLXBncC5vcmf0NGelgx9vvPxdcRBLogKbI559pRjWdg3i\n" + + "GpJSc3akDgKbAsC8oAQZAQoAbwWCWuj/gAkQEPy8/w6Op5FHFAAAAAAAHgAgc2Fs\n" + + "dEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3Jn61QE8l97YHDNs+NX6mKrsVYSUWrz\n" + + "evsNklOMRBvvkqgWIQTOphDQhPpR8hHhxGwQ/Lz/Do6nkQAARlYIALAfDNiiOXMV\n" + + "yioFRy9XRH84PYWpVWr5LX3E+mVQv/mg6feLbwQi9ehroauHHDewwE61seN9Pxnn\n" + + "GOhO+6r4Q85gnJUm3S24mZrK1V/ZApk36ycxUOuCn7yEuRoGy9tfmSfqSlthzjAR\n" + + "p+rIAD5k6jOVLAwqbBCg7eQiXCa97E3PA/TYRJ3NHSrEPdfp/ZrN1ubcshOq/acj\n" + + "Ok4QQjIW0JEe4RPV1gEHjtSC0hRp4ntGhXE1NDqNMC9TGoksgP/F6Sqtt8X8dZDU\n" + + "vYUJHatGlnoTaEyXQrdTatXFgActq0EdMfqoRlqMH7AI5wWrrcb3rdvLdpDwgCDJ\n" + + "4mKVnPPQcH4WIQTjLLbaggKRt+dtsagIrVHK5HDwBgAAqtYH/0Ox/UXuUlpPlDp/\n" + + "zUD0XnX+eOGCf2HUJ73v4Umjxi993FM3+MscxSC5ytfSK3eX/P5k09aYPfS94sRN\n" + + "zedN9SSSsBaQgevUbMrIPPGSwy9lS3N8XbAEHVG1WgqnkRysLTLaQb2wBbxfaZcG\n" + + "ptEklxx6/yZGJubn1zeiPIm/58K9WxW3/0ntFrpPURuJ3vSVAQqxsWpMlXfjoCy4\n" + + "b8zpiWu3wwtLlGYUyhW4zMS4WmrOBxWIkW389k9Mc/YMg8rQ1rBBTPl6Ch5RB/Bc\n" + + "f1Ngef/DdEPqSBaBLjpgTvuRD7zyJcTQch4ImjSLirdTLvlAG9kqZeg+c2w31/97\n" + + "6sXYWB8=\n" + + "=13Sf\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + TestSignature t0 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJYaEaACRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmdVa4OG6WfRoRlj5+Zb6avhJUIZFvcIFiLuvrJp8Hio\n" + + "iBYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAAAbaQgAjhBh0dLO0Sqiqkb2M3KWc25V\n" + + "hJlcP3isFROJ0jikmXxkG9W04AvlA78tSxEP2n8a0CbxH/hT4g8mFb/qM5FKZcKf\n" + + "HQxjbjUxBmVHa3EfMkwT7u1mVRmoWtJ59oVsKoqRb/kZ14i6VZ9NzfK8MRlL0e24\n" + + "oNjkksZQ8ImjwwtvxSinxhezA6BtWi+dDnXAnG5Vva+6N/GRNPAAd8kFTPrlEqEz\n" + + "uRbpq76r4taPjRjzMNcwZJoRVHSahWhDcXxNTalVUwt0DZFAskZ3gI+0VgU11bK1\n" + + "QmIw2iR4itQY5f10HFNcl7uHLKnul0YyuvA5509HwCuEpdYUV/OxtlpVRaJ+yg==\n" + + "=Rc6K\n" + + "-----END PGP SIGNATURE-----\n", false, "Signature predates primary key"); + TestSignature t1 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJa564ACRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfcG7Iqn3OOKVjeJ61MlgERt08kcxh0x+BZFD7a8K7V\n" + + "VBYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAACBIwf9EoS24IFeT3cPFf/nWxLFkbZK\n" + + "fiy9WzyK4wlpO3VTyWPbXi6zpC4I5Rbp2jDk/c7Q3DnOZqFDv6TriTwuLYTJGPxr\n" + + "U3dtDsFcKp4FcbgFyCDKIuLB+3kLaNpMXqdttEkY3Wd5m33XrBB7M0l5xZCk56Jm\n" + + "H5L1sGNNNkCzG6P44qu69o5fkWxbYuX22fyhdeyxucJHMztqiMQYDwT7eSA92A1v\n" + + "5OwA5D/k7GeyYFBFisxRijkdVtxstC9zkagC19VnZo7MRekA9gXj7kIna4XYRhfb\n" + + "uQnN47HXdiWQytwypLvZ8JEJpRruyMAaHjX5OBXh0SK11xYWb6wB93+QfOahtg==\n" + + "=UlUZ\n" + + "-----END PGP SIGNATURE-----\n", false, "Hard revocations invalidate key at all times"); + TestSignature t2 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJdP4iACRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmcgkZw3ZSg8CZCKqJw2r4VqCpTuUhz6N0zX43d+1xop\n" + + "2hYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAADnqAgAq+m6dDZpNOBaXH9nwv8/+HgR\n" + + "MvRjnuLoa6zB5tcUhGPPVS0gg1PW0wfxlo1GPmgW3QDlV1zvcfYAZmV9uEC61wn/\n" + + "+FkqN0Tceo487UvkWARE/mmRj5L8OgUTfqm1eebFQlMu/MeG9YOg+tXBy7XS7hy3\n" + + "UdntIbtsv5oRTcybTnn5oiU2OFDlFC6sBNzOQt7wpyB1TKp2BdcsAv1RwmyCCCK4\n" + + "bnmrpYH6woWMyVEVeMYfOHAx9vHD+od8Vf/v5L1M2N0nHzRWjjkobTVUr+xt/CyW\n" + + "nq8SoazKYu3ETpZLeWX6Bciuv9+pzUCeClOSmBB1MFyyrTgbkOacHgrYnLvvtQ==\n" + + "=WCKA\n" + + "-----END PGP SIGNATURE-----\n", false, "Hard revocations invalidate key at all times"); + TestSignature t3 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJmhTYiCRAQ/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmdi3dCpJ4nZincNH5owv8+fJ5YpXljqtegtoBEnbbHP\n" + + "thYhBM6mENCE+lHyEeHEbBD8vP8OjqeRAAD0cQf/e8RHocRESJPbosqUuvC3ELnD\n" + + "oSsJomDMUDfSfgpS5EhkOyJhvcrHkCbsHH2xlUEQ+zjJWY/dwM3FUkoj+p3kb/JC\n" + + "Rn5cqQYlME+uJzjdHMyQCSOI1SvYwKCLCGPARDbCpeINrV++Oy29e6cv6/IcPlgo\n" + + "k/0A7XuNq0YNxC7oopCj5ye3yVUvUmSCG2iV4oiWW5GhhPRzMeW7MFQmS0NUkAI8\n" + + "hzJ8juTG4xP8SXnHCMakasZhJmtpMDd2BDZ7CrhWiWUQGrtd0eYkuyodreqVMGIF\n" + + "BN80YgTNFW2MrblhDRRmxAqWzD9FedBwwSdgYbtkDwjsSq0S1jQV6aPndJqiLw==\n" + + "=CIl0\n" + + "-----END PGP SIGNATURE-----\n", false, "Hard revocations invalidate key at all times"); + + signatureValidityTest(api, cert, t0, t1, t2, t3); + } + + private void testPKSignsPKRevocationSuperseded(OpenPGPApi api) + throws IOException + { + // https://sequoia-pgp.gitlab.io/openpgp-interoperability-test-suite/results.html#Key_revocation_test__primary_key_signs_and_is_revoked__revoked__superseded + String CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xsBNBFpJegABCACzr1V+GxVkrtfDjihYK+HtyEIcO52uw7O2kd7JbduYp4RK17jy\n" + + "75N3EnsgmiIkSxXCWr+rTtonNs1zCJeUa/gwnNfs7mVgjL2rMOZU/KZ4MP0yOYU5\n" + + "u5FjNPWz8hpFQ9GKqfdj0Op61h1pCQO45IjUQ3dCDj9Rfn44zHMB1ZrbmIH9nTR1\n" + + "YIGHWmdm0LItb2WxIkwzWBAJ5acTlsmLyZZEQ1+8NDqktyzwFoQqTJvLU4StY2k6\n" + + "h18ZKZdPyrdLoEyOuWkvjxmbhDk1Gt5KiS/yy7mrzIPLr0dmJe4vc8WLV+bXoyNE\n" + + "x3H8o9CFcYehLfyqsy40lg92d6Kp96ww8dZ5ABEBAAHCwM8EIAEKAIMFglwqrYAJ\n" + + "EAitUcrkcPAGRxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9y\n" + + "Z1X0jZPeNNpSsn78ulDPJNHa0QaeI5oAUdBGbIKSOT0uEx0BS2V5IGlzIHN1cGVy\n" + + "c2VkZWQWIQTjLLbaggKRt+dtsagIrVHK5HDwBgAAr2QIAKAY5bHFbRkoItYBJBN1\n" + + "aV1jjrpYdwLM+0LHf8GcRCeO1Pt9I1J021crwTw14sTCxi6WH4qbQSBxRqAEej/A\n" + + "wfk1kmkm4WF7zTUT+fXIHDJxFJJXqFZ+LWldYYEVqSi02gpbYkyLm9hxoLDoAxS2\n" + + "bj/sFaH4Bxr/eUCqjOiEsGzdY1m65+cp5jv8cJK05jwqxO5/3KZcF/ShA7AN3dJi\n" + + "NAokoextBtXBWlGvrDIfFafOy/uCnsO6NeORWbgZ88TOXPD816ff5Y8kMwkDkIk2\n" + + "9dK4m0aL/MDI+Fgx78zRYwn5xHbTMaFz+hex+gjo4grx3KYXeoxBAchUuTsVNoo4\n" + + "kbfCwMQEHwEKAHgFgl4L4QAJEAitUcrkcPAGRxQAAAAAAB4AIHNhbHRAbm90YXRp\n" + + "b25zLnNlcXVvaWEtcGdwLm9yZ4csZe1ah1tj2AjxfdDMsH2wvSEwZjb/73ICKnm7\n" + + "BySQAhUKApsDAh4BFiEE4yy22oICkbfnbbGoCK1RyuRw8AYAAGYFCACiKnCb2NBZ\n" + + "a/Jj1aJe4R2rxPZj2ERXWe3bJKNPKT7K0rVDkTw1JRiTfCsuAY2lY9sKJdhQZl+a\n" + + "zXm64vvTc6hEGRQ/+XssDlE2DIn8C34HDc495ZnryHNB8Dd5l1HdjqxfGIY6HBPJ\n" + + "Udx0dedwP42Oisg9t5KsC8zld/+MIRgzkp+Dg0LXJVnDuwWEPoo2N6WhAr5ReLvX\n" + + "xALX5ht9Lb3lP0DASZvAKy9BO/wRCr294J8dg/CowAfloyf0Ko+JjyjanmZn3acy\n" + + "5CGkVN2mc+PFUekGZDDy5ooYkgXO/CmApuTNvabct+A7IVVdWWM5SWb90JvaV9SW\n" + + "ji6nQphVm7StwsDEBB8BCgB4BYJaSXoACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0\n" + + "QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfVZdjLYZxDX2hvy3aGrsE4i0avLDMz\n" + + "f3e9kVHmaD6PAgIVCgKbAwIeARYhBOMsttqCApG3522xqAitUcrkcPAGAABQYwgA\n" + + "rfIRxq95npUKAOPXs25nZlvy+xQbrmsTxHhAYW8eGFcz82QwumoqrR8VfrojxM+e\n" + + "CZdTI85nM5kzznYDU2+cMhsZVm5+VhGZy3e3QH4J/E31D7t1opCvj5g1eRJ4Lgyw\n" + + "B+cYGcZBYp/bQT9SUYuhZH2OXCR04qSbpVUCIApnhBHxKNtOlqjAkHeaOdW/8XeP\n" + + "sbfvrtVOLGYgrZXfY7Nqy3+Wzbdm8UvVPFXH+uHEzTgyvYbnJBYkjORmCqUKs860\n" + + "PL8ekeg+sL4PHSRj1UUfwcQD55q0m3Vtew2KiIUi4wKi5LceDtprjoO5utU/1YfE\n" + + "AiNMeSQHXKq83dpazvjrUs0SanVsaWV0QGV4YW1wbGUub3JnwsDEBBMBCgB4BYJa\n" + + "SXoACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBn\n" + + "cC5vcmc6Rix7CeIfWwnaQjk3bBrkAiY7jS9N+shuRdHZ0gKKsgIVCgKbAwIeARYh\n" + + "BOMsttqCApG3522xqAitUcrkcPAGAACf9QgAsxtfAbyGbtofjrXTs9lsKEWvGgk0\n" + + "2fSYyKjPbyaRqh72MlIlUXwqq1ih2TJc3vwF8aNVDrcb9DnBabdt2M1vI3PUaeG3\n" + + "1BmakC/XZCNCrbbJkyd/vdMLqw7prLrp0auVNNhLYxOK9usXbClNxluo4i/lSFVo\n" + + "5B9ai+ne1kKKiplzqy2qqhdeplomcwGHbB1CkZ04DmCMbSSFAGxYqUC/bBm0bolC\n" + + "ebw/KIz9sEojNKt6mvsFN67/hMYeJS0HVlwwc6i8iKSzC2D53iywhtvkdiKECXQe\n" + + "XDf9zNXAn1wpK01SLJ0iig7cDFrtoqkfPYzbNfC0bt34fNx9iz3w9aEH8c7ATQRa\n" + + "SsuAAQgAu5yau9psltmWiUn7fsRSqbQInO0iWnu4DK9IXB3ghNYMcii3JJEjHzgI\n" + + "xGf3GiJEjzubyRQaX5J/p7yB1fOH8z7FYUuax1saGf9c1/b02N9gyXNlHam31hNa\n" + + "aL3ffFczI95p7MNrTtroTt5oZqsc+i+oKLZn7X0YAI4tEYwhSnUQYB/F7YqkkI4e\n" + + "V+7CxZPA8pBhXiAOK/zn416PsZ6JS5wsM65yCtOHcAAIBnKDnC+bQi+f1WZesSoc\n" + + "y/rXx3QEQmodDu3ojhS+VxcYGeZCUcFF0FyZBIkGjHIVQLyOfjP3FRJ4qFXMz9/Y\n" + + "IVoM4Y6guTERMTEj/KDG4BP7RfJHTQARAQABwsI8BBgBCgHwBYJeC+EACRAIrVHK\n" + + "5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfcAa1Z\n" + + "PWTtg60w3Oo4dt4Fa8cKFYbZYsqDSHV5pwEfMwKbAsC8oAQZAQoAbwWCXgvhAAkQ\n" + + "EPy8/w6Op5FHFAAAAAAAHgAgc2FsdEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3Jn\n" + + "L6I2+VyN5T1FoVgj3cdnMLYCpcB5i/FRSCVKybuLzrgWIQTOphDQhPpR8hHhxGwQ\n" + + "/Lz/Do6nkQAArk8H/AhjM9lqbffFL6RRR4HTjelspy4A3nyTicCljrDuXDUh23Gf\n" + + "LvajTR5h16ZBqAF7cpb9rrlz1C1WcS5JLVxzXAe7f+KOfXu+eyLhpTzZ8VT3pK3h\n" + + "HGaYwlVlXrBZP0JXgL8hm6hDSXZQZtcpsnQ1uIHC9ONxUB4liNFhTqQCQYdQJFiF\n" + + "s1umUbo/C4KdzlDI08bM3CqEKat9vUFuGG68mDg0CrRZEWt946L5i8kZmBUkSShI\n" + + "m2k5e2qE/muYeM6qKQNsxlx3VIf5eUhtxCi9fg7SjvHkdUSFstYcxAdaohWCFCEs\n" + + "DJI12hzcKQazSjvtKF4BNBKgX/wLsbVQnYLd9ggWIQTjLLbaggKRt+dtsagIrVHK\n" + + "5HDwBgAANjMH/1MY7DJyxkiTjc/jzmnVxqtHOZDCSmUqk0eh/6BHs+ostWqkGC6+\n" + + "7dfxDnptwcqandYey4KF2ajt4nOwu0xQw/NEF3i81h7IiewY7G+YT69DUd+DvVUQ\n" + + "emfKNYVOrMqoH7QU5o4YojdJiDeIp2d/JyJrqyof78JFAHnNZgHC2T2zo9E54dnO\n" + + "TY9VNUNCOUct5Rby0GXjTIURO0f485eGuZxVWdLRllDYOiCrQHPSHhrxHVXVMbYJ\n" + + "oroPy+IyaJanVoAWgyipBmmIDV8aINM2RLMsGkuPTRtITI2ZlGOQN7xgy4LqWzjP\n" + + "nrzMXfwBEDx/nrwdG6zEGMK8AkVkMT5uJJvCwjwEGAEKAfAFglro/4AJEAitUcrk\n" + + "cPAGRxQAAAAAAB4AIHNhbHRAbm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZ/Q0Z6WD\n" + + "H2+8/F1xEEuiApsjnn2lGNZ2DeIaklJzdqQOApsCwLygBBkBCgBvBYJa6P+ACRAQ\n" + + "/Lz/Do6nkUcUAAAAAAAeACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmfr\n" + + "VATyX3tgcM2z41fqYquxVhJRavN6+w2SU4xEG++SqBYhBM6mENCE+lHyEeHEbBD8\n" + + "vP8OjqeRAABGVggAsB8M2KI5cxXKKgVHL1dEfzg9halVavktfcT6ZVC/+aDp94tv\n" + + "BCL16Guhq4ccN7DATrWx430/GecY6E77qvhDzmCclSbdLbiZmsrVX9kCmTfrJzFQ\n" + + "64KfvIS5GgbL21+ZJ+pKW2HOMBGn6sgAPmTqM5UsDCpsEKDt5CJcJr3sTc8D9NhE\n" + + "nc0dKsQ91+n9ms3W5tyyE6r9pyM6ThBCMhbQkR7hE9XWAQeO1ILSFGnie0aFcTU0\n" + + "Oo0wL1MaiSyA/8XpKq23xfx1kNS9hQkdq0aWehNoTJdCt1Nq1cWABy2rQR0x+qhG\n" + + "WowfsAjnBautxvet28t2kPCAIMniYpWc89BwfhYhBOMsttqCApG3522xqAitUcrk\n" + + "cPAGAACq1gf/Q7H9Re5SWk+UOn/NQPRedf544YJ/YdQnve/hSaPGL33cUzf4yxzF\n" + + "ILnK19Ird5f8/mTT1pg99L3ixE3N5031JJKwFpCB69Rsysg88ZLDL2VLc3xdsAQd\n" + + "UbVaCqeRHKwtMtpBvbAFvF9plwam0SSXHHr/JkYm5ufXN6I8ib/nwr1bFbf/Se0W\n" + + "uk9RG4ne9JUBCrGxakyVd+OgLLhvzOmJa7fDC0uUZhTKFbjMxLhaas4HFYiRbfz2\n" + + "T0xz9gyDytDWsEFM+XoKHlEH8Fx/U2B5/8N0Q+pIFoEuOmBO+5EPvPIlxNByHgia\n" + + "NIuKt1Mu+UAb2Spl6D5zbDfX/3vqxdhYHw==\n" + + "=9epL\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + TestSignature t0 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJYaEaACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmeoPMfalw2oS7uyOKnOXJSN8Gx7pr/BMlo3Xn8nTgx6\n" + + "ORYhBOMsttqCApG3522xqAitUcrkcPAGAABXbAf/WfWaQYNuATAKwxYrJx4fd5kt\n" + + "0M6sn1q7wK1MIxursG2+FuKafV25O9+pde8Nog77OEgegwk+HokOVFpVXfOzHQjs\n" + + "8dwWTtTQlX5NIBNvtqS7cvCKhjsqaHKgmzsenMjCEbpDZ3C5CoqcYicykqEU/Ia0\n" + + "ZGC4lzRByrgNy/w+/iLN748S707bzBLVc/sE73k9N5pANAlE+cA/sHI1Gp2WxJR9\n" + + "t2Fk4x6/85PEnF1RHI16p/wSEeuRaBpyw9QGZBbVDVt5wvgttxZjteGGSwBM3WI/\n" + + "gPfC0LW+JQ2W+dwY0PN/7yuARVRhXpKiBI4xqp7x3OanQX6quU77g3B8nXAt3A==\n" + + "=StqT\n" + + "-----END PGP SIGNATURE-----\n", false, "Signature predates primary key"); + TestSignature t1 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJa564ACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfM0EN4Ei0bQv6UO9BRq2wtUfV948cRynRMBb8TSGCG\n" + + "tBYhBOMsttqCApG3522xqAitUcrkcPAGAAAlNwf+L0KQK9i/xmYKOMV2EX13QUoZ\n" + + "vvb/pHGZaCQ9JtvEF2l2DT0DqByZ+tOv5Y4isU+un7CraoyvyajAwR0Yqk937B6C\n" + + "HQHKMkmIl+5R4/xqSoWYmOidbrgilojPMBEhB3INQ8/THjjFijtLzitVhnWBd7+u\n" + + "s0kcqnWnOdx2By4aDe+UEiyCfSE02e/0tIsM71RqiU91zH6dl6+q8nml7PsYuTFV\n" + + "V09oQTbBuuvUe+YgN/uvyKVIsA64lQ+YhqEeIA8Quek7fHhW+du9OIhSPsbYodyx\n" + + "VWMTXwSWKGNvZNAkpmgUYqFjS2Cx5ZUWblZLjrNKBwnnmt50qvUN7+o2pjlnfA==\n" + + "=UuXb\n" + + "-----END PGP SIGNATURE-----\n", true); + TestSignature t2 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJdP4iACRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfFzYGoiuSjN+gz1IDD4ZvRXGuPTHks0/pIiGY90mrZ\n" + + "WxYhBOMsttqCApG3522xqAitUcrkcPAGAABGPAf/ck7tJAFoPIDd9fTPZANpNGoW\n" + + "Fq6VuNfy/nLjz2gkHFX/lLAxQ0N3McIdRA++Ik/omb0lis3R2DVNgwqNm2OF34HE\n" + + "qxmPmrQHBgk2q0fDH4NCE0XnYQjQT65V99IfiaQu+oS3Mq8MuYsDYvRVvRKMwt49\n" + + "fcDnvFtAtCqEETdv6wV5cUZmdQ3L9NU9bApJ0jk+EHVdpfTUIbOYYGnsIe/4Aa0d\n" + + "jgzu4Em79ynosOn//953XJ7OO8LCDi1EKt+nFuZARUlt/Jwwull6zzp7HUPw6HPt\n" + + "Upp7os8TIPC4STwoSeEKaxEkrbMGFnDcoDajnKKRt5+MkB24Oq7PHvnzgnPpVg==\n" + + "=Ljv7\n" + + "-----END PGP SIGNATURE-----\n", false, "Key is revoked at this time"); + TestSignature t3 = new TestSignature("-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsC7BAABCgBvBYJmhTYiCRAIrVHK5HDwBkcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmfbjQf/zfoJQT0hhna4RDjOESBLgGaCbc5HLeo751F4\n" + + "NxYhBOMsttqCApG3522xqAitUcrkcPAGAABqBQgAkkNmYf6yLPvox+ZayrLtMb9D\n" + + "ghgt0nau72DSazsJ6SAq2QqIdr0RRhRa2gCETkp4PpeoDWmIvoVj35ZnfyeO/jqy\n" + + "HECvRwO0WPA5FXQM6uG7s40vDTRFjlJMpPyHWnn2igcR64iDxBGmc40xi9CcmJP9\n" + + "tmA26+1Nzj1LcfNvknKZ2UIOmnXiZY0QssIdyqsmJrdFpXs4UCLUzdXkfFLoxksU\n" + + "mk4B6hig2IKMj5mnbWy/JQSXtjjI+HHmtzgWfXs7d9iQ61CklbtCOiPeWxvoqlGG\n" + + "oK1wV1olcSar/RPKTlMmQpAg9dztQgrNs1oF7EF3i9kwNP7I5JzekPiOLH6oMw==\n" + + "=5KMU\n" + + "-----END PGP SIGNATURE-----\n", true); + + signatureValidityTest(api, CERT, t0, t1, t2, t3); + } + + private void signatureValidityTest(OpenPGPApi api, String cert, TestSignature... testSignatures) + throws IOException + { + OpenPGPCertificate certificate = api.readKeyOrCertificate().parseCertificate(cert); + + for (int i = 0; i != testSignatures.length; i++) + { + TestSignature test = testSignatures[i]; + PGPSignature signature = test.getSignature(); + OpenPGPCertificate.OpenPGPComponentKey signingKey = certificate.getSigningKeyFor(signature); + + boolean valid = signingKey.isBoundAt(signature.getCreationTime()); + if (valid != test.isExpectValid()) + { + StringBuilder sb = new StringBuilder("Key validity mismatch. Expected " + signingKey.toString() + + (test.isExpectValid() ? (" to be valid at ") : (" to be invalid at ")) + UTCUtil.format(signature.getCreationTime())); + if (test.getMsg() != null) + { + sb.append(" because:\n").append(test.getMsg()); + } + sb.append("\n").append(signingKey.getSignatureChains()); + fail(sb.toString()); + } + } + } + + private void testGetPrimaryUserId(OpenPGPApi api) + throws PGPException + { + final Date now = new Date((new Date().getTime() / 1000) * 1000); + Date oneHourAgo = new Date(now.getTime() - 1000 * 60 * 60); + + OpenPGPKeyGenerator gen = api.generateKey(oneHourAgo); + OpenPGPKey key = gen.withPrimaryKey() + .addUserId("Old non-primary ") + .addUserId("New primary ", + SignatureParameters.Callback.Util.modifyHashedSubpackets(new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.CREATION_TIME); + subpackets.setSignatureCreationTime(now); + subpackets.setPrimaryUserID(false, true); + return subpackets; + } + })) + .build(null); + isEquals("Expect to find valid, explicit primary user ID", + key.getUserId("New primary "), + key.getPrimaryUserId()); + + isEquals("Explicit primary UserID is not yet valid, so return implicit UID", + key.getUserId("Old non-primary "), + key.getPrimaryUserId(oneHourAgo)); + } + + public static class TestSignature + { + private final PGPSignature signature; + private final boolean expectValid; + private final String msg; + + public TestSignature(String armoredSignature, boolean expectValid) + throws IOException + { + this(armoredSignature, expectValid, null); + } + + public TestSignature(String armoredSignature, boolean expectValid, String msg) + throws IOException + { + this.signature = parseSignature(armoredSignature); + this.expectValid = expectValid; + this.msg = msg; + } + + private static PGPSignature parseSignature(String armoredSignature) + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armoredSignature)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + + PGPSignatureList sigs = (PGPSignatureList) objFac.nextObject(); + + pIn.close(); + aIn.close(); + bIn.close(); + + return sigs.get(0); + } + + public PGPSignature getSignature() + { + return signature; + } + + public boolean isExpectValid() + { + return expectValid; + } + + public String getMsg() + { + return msg; + } + } + + public static void main(String[] args) + { + runTest(new OpenPGPCertificateTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPDetachedSignatureProcessorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPDetachedSignatureProcessorTest.java new file mode 100644 index 0000000000..1d86ee630d --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPDetachedSignatureProcessorTest.java @@ -0,0 +1,276 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; +import java.util.List; + +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.api.KeyPairGeneratorCallback; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPDetachedSignatureGenerator; +import org.bouncycastle.openpgp.api.OpenPGPDetachedSignatureProcessor; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.OpenPGPSignature; +import org.bouncycastle.openpgp.api.SignatureParameters; +import org.bouncycastle.openpgp.api.SignatureSubpacketsFunction; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; +import org.bouncycastle.util.Strings; + +public class OpenPGPDetachedSignatureProcessorTest + extends APITest +{ + @Override + public String getName() + { + return "OpenPGPDetachedSignatureProcessorTest"; + } + + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + String javaVersion = System.getProperty("java.version"); + boolean oldJDK = javaVersion.startsWith("1.5") || javaVersion.startsWith("1.6"); + + createVerifyV4Signature(api); + createVerifyV6Signature(api); + + keyPassphrasesArePairedUpProperly_keyAddedFirst(api); + keyPassphrasesArePairedUpProperly_passphraseAddedFirst(api); + + missingPassphraseThrows(api); + + if (!oldJDK) + { + wrongPassphraseThrows(api); + } + + withoutSigningSubkeyFails(api); + nonSigningSubkeyFails(api); + } + + private void createVerifyV4Signature(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPDetachedSignatureGenerator gen = api.createDetachedSignature(); + gen.addSigningKey( + api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY)); + + byte[] plaintext = Strings.toUTF8ByteArray("Hello, World!\n"); + ByteArrayInputStream plaintextIn = new ByteArrayInputStream(plaintext); + + List signatures = gen.sign(plaintextIn); + isEquals(1, signatures.size()); + OpenPGPSignature.OpenPGPDocumentSignature signature = signatures.get(0); + isEquals(4, signature.getSignature().getVersion()); + String armored = signature.toAsciiArmoredString(); + isTrue(armored.startsWith("-----BEGIN PGP SIGNATURE-----" + Strings.lineSeparator())); + + // Verify detached signatures + OpenPGPDetachedSignatureProcessor processor = api.verifyDetachedSignature(); + processor.addSignature(signature.getSignature()); + processor.addVerificationCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT)); + + List verified = processor.process(new ByteArrayInputStream(plaintext)); + isEquals(1, verified.size()); + isTrue(verified.get(0).isValid()); + } + + private void createVerifyV6Signature(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPDetachedSignatureGenerator gen = api.createDetachedSignature(); + gen.addSigningKey( + api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY)); + + byte[] plaintext = Strings.toUTF8ByteArray("Hello, World!\n"); + ByteArrayInputStream plaintextIn = new ByteArrayInputStream(plaintext); + + List signatures = gen.sign(plaintextIn); + isEquals(1, signatures.size()); + OpenPGPSignature.OpenPGPDocumentSignature signature = signatures.get(0); + isEquals(6, signature.getSignature().getVersion()); + String armored = signature.toAsciiArmoredString(); + isTrue(armored.startsWith("-----BEGIN PGP SIGNATURE-----" + Strings.lineSeparator())); + + // Verify detached signatures + OpenPGPDetachedSignatureProcessor processor = api.verifyDetachedSignature(); + processor.addSignature(signature.getSignature()); + processor.addVerificationCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.V6_CERT)); + + List verified = processor.process(new ByteArrayInputStream(plaintext)); + isEquals(1, verified.size()); + isTrue(verified.get(0).isValid()); + } + + private void missingPassphraseThrows(final OpenPGPApi api) + { + isNotNull(testException( + "Cannot unlock primary key CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9: Exception decrypting key", + "KeyPassphraseException", + new TestExceptionOperation() + { + public void operation() + throws Exception + { + api.createDetachedSignature() + .addSigningKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY_LOCKED)) + .sign(new ByteArrayInputStream(Strings.toUTF8ByteArray("Test Data"))); + } + })); + } + + private void wrongPassphraseThrows(final OpenPGPApi api) + { + isNotNull(testException( + "Cannot unlock primary key CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9: Exception decrypting key", + "KeyPassphraseException", + new TestExceptionOperation() + { + public void operation() + throws Exception + { + api.createDetachedSignature() + .addKeyPassphrase("thisIsWrong".toCharArray()) + .addSigningKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY_LOCKED)) + .sign(new ByteArrayInputStream(Strings.toUTF8ByteArray("Test Data"))); + } + })); + } + + private void keyPassphrasesArePairedUpProperly_keyAddedFirst(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPKey key = api.generateKey(new Date(), false) + .signOnlyKey() + .build("password".toCharArray()); + + OpenPGPDetachedSignatureGenerator gen = api.createDetachedSignature(); + gen.addSigningKey(key); + + gen.addKeyPassphrase("penguin".toCharArray()); + gen.addKeyPassphrase("password".toCharArray()); + gen.addKeyPassphrase("beluga".toCharArray()); + + byte[] plaintext = Strings.toUTF8ByteArray("arctic\ndeep sea\nice field\n"); + InputStream plaintextIn = new ByteArrayInputStream(plaintext); + + List signatures = gen.sign(plaintextIn); + isEquals(1, signatures.size()); + } + + private void keyPassphrasesArePairedUpProperly_passphraseAddedFirst(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPKey key = api.generateKey(new Date(), false) + .signOnlyKey() + .build("password".toCharArray()); + + OpenPGPDetachedSignatureGenerator gen = api.createDetachedSignature(); + + gen.addKeyPassphrase("sloth".toCharArray()); + gen.addKeyPassphrase("password".toCharArray()); + gen.addKeyPassphrase("tapir".toCharArray()); + + gen.addSigningKey(key); + + byte[] plaintext = Strings.toUTF8ByteArray("jungle\ntropics\nswamp\n"); + InputStream plaintextIn = new ByteArrayInputStream(plaintext); + + List signatures = gen.sign(plaintextIn); + isEquals(1, signatures.size()); + } + + private void withoutSigningSubkeyFails(final OpenPGPApi api) + throws PGPException + { + final OpenPGPKey noSigningKey = api.generateKey() + .withPrimaryKey( + new KeyPairGeneratorCallback() { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException { + return generator.generatePrimaryKey(); + } + }, + SignatureParameters.Callback.Util.modifyHashedSubpackets( + new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + // No SIGN_DATA key flag + subpackets.setKeyFlags(KeyFlags.CERTIFY_OTHER); + return subpackets; + } + } + ) + ).build(); + + isNotNull(testException( + "The key " + noSigningKey.getKeyIdentifier() + " does not contain any usable component keys capable of signing.", + "InvalidSigningKeyException", + new TestExceptionOperation() + { + public void operation() + throws Exception + { + api.createDetachedSignature() + .addSigningKey(noSigningKey) + .sign(new ByteArrayInputStream(Strings.toUTF8ByteArray("Test Data"))); + } + })); + } + + private void nonSigningSubkeyFails(final OpenPGPApi api) + throws PGPException + { + final OpenPGPKey noSigningKey = api.generateKey() + .withPrimaryKey( + new KeyPairGeneratorCallback() { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException { + return generator.generatePrimaryKey(); + } + }, + SignatureParameters.Callback.Util.modifyHashedSubpackets( + new SignatureSubpacketsFunction() + { + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + // No SIGN_DATA key flag + subpackets.setKeyFlags(KeyFlags.CERTIFY_OTHER); + return subpackets; + } + } + ) + ).build(); + + isNotNull(testException( + "The primary key " + noSigningKey.getPrimaryKey().getKeyIdentifier() + " is not usable for signing.", + "InvalidSigningKeyException", + new TestExceptionOperation() + { + public void operation() + throws Exception + { + api.createDetachedSignature() + .addSigningKey(noSigningKey.getPrimarySecretKey(), (char[])null, null) + .sign(new ByteArrayInputStream(Strings.toUTF8ByteArray("Test Data"))); + } + })); + } + + public static void main(String[] args) + { + runTest(new OpenPGPDetachedSignatureProcessorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPKeyEditorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPKeyEditorTest.java new file mode 100644 index 0000000000..90e28f9b32 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPKeyEditorTest.java @@ -0,0 +1,281 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.IOException; +import java.util.Date; + +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.bcpg.sig.RevocationReasonTags; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.SignatureParameters; +import org.bouncycastle.openpgp.api.SignatureSubpacketsFunction; + +public class OpenPGPKeyEditorTest + extends APITest +{ + + @Override + public String getName() + { + return "OpenPGPKeyEditorTest"; + } + + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + doNothingTest(api); + + addUserIdTest(api); + softRevokeUserIdTest(api); + hardRevokeUserIdTest(api); + + addEncryptionSubkeyTest(api); + revokeEncryptionSubkeyTest(api); + + addSigningSubkeyTest(api); + revokeSigningSubkeyTest(api); + + extendExpirationTimeTest(api); + revokeCertificateTest(api); + + changePassphraseUnprotectedToCFBTest(api); + changePassphraseUnprotectedToAEADTest(api); + } + + private void doNothingTest(OpenPGPApi api) + throws PGPException + { + OpenPGPKey key = api.generateKey() + .ed25519x25519Key("Alice ") + .build(); + OpenPGPKey editedKey = api.editKey(key) + .done(); + + isTrue("Key was not changed, so the reference MUST be the same", + key == editedKey); + } + + private void addUserIdTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate() + .parseKey(OpenPGPTestKeys.V6_KEY); + isNull("Expect primary user-id to be null", key.getPrimaryUserId()); + + key = api.editKey(key) + .addUserId("Alice ") + .done(); + + isEquals("Expect the new user-id to be primary now", + "Alice ", key.getPrimaryUserId().getUserId()); + } + + private void softRevokeUserIdTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate() + .parseKey(OpenPGPTestKeys.ALICE_KEY); + final Date now = currentTimeRounded(); + Date oneHourAgo = new Date(now.getTime() - (1000 * 60 * 60)); + OpenPGPCertificate.OpenPGPUserId userId = key.getPrimaryUserId(now); + isNotNull(userId); + isTrue(userId.isBound()); + isEquals("Alice Lovelace ", userId.getUserId()); + + key = api.editKey(key) + .revokeIdentity(userId, new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + parameters.setSignatureCreationTime(now); + parameters.setHashedSubpacketsFunction(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.setRevocationReason(true, RevocationReasonTags.USER_NO_LONGER_VALID, ""); + return subpackets; + } + }); + return parameters; + } + }) + .done(); + isTrue(key.getPrimaryUserId().isBoundAt(oneHourAgo)); + isFalse(key.getPrimaryUserId().isBoundAt(now)); + } + + private void hardRevokeUserIdTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate() + .parseKey(OpenPGPTestKeys.ALICE_KEY); + final Date now = currentTimeRounded(); + Date oneHourAgo = new Date(now.getTime() - (1000 * 60 * 60)); + OpenPGPCertificate.OpenPGPUserId userId = key.getPrimaryUserId(now); + isNotNull(userId); + isTrue(userId.isBound()); + isEquals("Alice Lovelace ", userId.getUserId()); + + key = api.editKey(key) + .revokeIdentity(userId, new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + parameters.setSignatureCreationTime(now); + // no reason -> hard revocation + return parameters; + } + }) + .done(); + isFalse(key.getPrimaryUserId().isBoundAt(oneHourAgo)); + isFalse(key.getPrimaryUserId().isBoundAt(now)); + } + + private void addEncryptionSubkeyTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + isEquals(1, key.getEncryptionKeys().size()); + + key = api.editKey(key) + .addEncryptionSubkey() + .done(); + + isEquals(2, key.getEncryptionKeys().size()); + } + + private void revokeEncryptionSubkeyTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + OpenPGPCertificate.OpenPGPComponentKey encryptionSubkey = key.getEncryptionKeys().get(0); + + key = api.editKey(key) + .revokeComponentKey(encryptionSubkey) + .done(); + + isEquals(0, key.getEncryptionKeys().size()); + } + + private void addSigningSubkeyTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + isEquals(1, key.getSigningKeys().size()); + + key = api.editKey(key) + .addSigningSubkey() + .done(); + + isEquals(2, key.getSigningKeys().size()); + } + + private void revokeSigningSubkeyTest(OpenPGPApi api) + throws PGPException + { + OpenPGPKey key = api.generateKey() + .classicKey(null) + .build(); + isEquals(1, key.getSigningKeys().size()); + + OpenPGPCertificate.OpenPGPComponentKey signingKey = key.getSigningKeys().get(0); + key = api.editKey(key) + .revokeComponentKey(signingKey) + .done(); + isEquals(0, key.getSigningKeys().size()); + } + + private void extendExpirationTimeTest(OpenPGPApi api) + throws PGPException + { + Date n0 = currentTimeRounded(); + OpenPGPKey key = api.generateKey(n0, false) + .classicKey(null) + .build(); + isEquals("Default key generation MUST set expiration time of +5years", + key.getExpirationTime().getTime(), n0.getTime() + 5L * 31536000 * 1000); + + final Date n1 = new Date(n0.getTime() + 1000); // 1 sec later + + key = api.editKey(key) + .addDirectKeySignature(new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + parameters.setSignatureCreationTime(n1); + parameters.setHashedSubpacketsFunction(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.setKeyExpirationTime(8L * 31536000); + return subpackets; + } + }); + return parameters; + } + }) + .done(); + + isEquals("At n1, the expiration time of the key MUST have changed to n0+8years", + key.getExpirationTime(n1).getTime(), n0.getTime() + 8L * 31536000 * 1000); + } + + private void revokeCertificateTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + + key = api.editKey(key) + .revokeKey() + .done(); + + isEquals(0, key.getEncryptionKeys().size()); + } + + private void changePassphraseUnprotectedToCFBTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + isFalse(key.getPrimarySecretKey().isLocked()); + + key = api.editKey(key) + .changePassphrase(key.getPrimaryKey().getKeyIdentifier(), null, "sw0rdf1sh".toCharArray(), false) + .done(); + isTrue("Expect key to be locked", key.getPrimarySecretKey().isLocked()); + isTrue("Expect sw0rdf1sh to be the correct passphrase", + key.getPrimarySecretKey().isPassphraseCorrect("sw0rdf1sh".toCharArray())); + isEquals("Expect use of USAGE_CHECKSUM for key protection", + SecretKeyPacket.USAGE_SHA1, key.getPrimarySecretKey().getPGPSecretKey().getS2KUsage()); + } + + private void changePassphraseUnprotectedToAEADTest(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + isFalse("Expect key to be unprotected", key.getPrimarySecretKey().isLocked()); + + key = api.editKey(key) + .changePassphrase(key.getPrimaryKey().getKeyIdentifier(), null, "sw0rdf1sh".toCharArray(), true) + .done(); + isTrue("Expect key to be locked after changing passphrase", + key.getPrimarySecretKey().isLocked()); + isTrue("Expect sw0rdf1sh to be the correct passphrase using AEAD", + key.getPrimarySecretKey().isPassphraseCorrect("sw0rdf1sh".toCharArray())); + isEquals("Expect use of AEAD for key protection", + SecretKeyPacket.USAGE_AEAD, key.getPrimarySecretKey().getPGPSecretKey().getS2KUsage()); + } + + public static void main(String[] args) + { + runTest(new OpenPGPKeyEditorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPKeyReaderTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPKeyReaderTest.java new file mode 100644 index 0000000000..e89be77bee --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPKeyReaderTest.java @@ -0,0 +1,91 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; + +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; + +public class OpenPGPKeyReaderTest + extends APITest +{ + @Override + public String getName() + { + return "OpenPGPKeyReaderTest"; + } + + @Override + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + testParseEmptyCollection(api); + testParse2CertsCertificateCollection(api); + testParseCertAndKeyToCertificateCollection(api); + } + + private void testParseEmptyCollection(OpenPGPApi api) + throws IOException + { + byte[] empty = new byte[0]; + List certs = api.readKeyOrCertificate().parseKeysOrCertificates(empty); + isTrue(certs.isEmpty()); + } + + private void testParse2CertsCertificateCollection(OpenPGPApi api) + throws IOException + { + OpenPGPCertificate alice = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT); + OpenPGPCertificate bob = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.BOB_CERT); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = ArmoredOutputStream.builder().clearHeaders().build(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + alice.getPGPPublicKeyRing().encode(pOut); + bob.getPGPPublicKeyRing().encode(pOut); + pOut.close(); + aOut.close(); + + List certs = api.readKeyOrCertificate().parseKeysOrCertificates(bOut.toByteArray()); + isEquals("Collection MUST contain both items", 2, certs.size()); + + isEquals(alice.getKeyIdentifier(), certs.get(0).getKeyIdentifier()); + isEquals(bob.getKeyIdentifier(), certs.get(1).getKeyIdentifier()); + } + + private void testParseCertAndKeyToCertificateCollection(OpenPGPApi api) + throws IOException + { + OpenPGPCertificate alice = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT); + OpenPGPKey bob = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.BOB_KEY); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = ArmoredOutputStream.builder().clearHeaders().build(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + alice.getPGPPublicKeyRing().encode(pOut); + bob.getPGPSecretKeyRing().encode(pOut); + pOut.close(); + aOut.close(); + + List certs = api.readKeyOrCertificate().parseKeysOrCertificates(bOut.toByteArray()); + isEquals("Collection MUST contain both items", 2, certs.size()); + + isEquals(alice.getKeyIdentifier(), certs.get(0).getKeyIdentifier()); + isFalse(certs.get(0).isSecretKey()); + + isEquals(bob.getKeyIdentifier(), certs.get(1).getKeyIdentifier()); + isTrue(certs.get(1).isSecretKey()); + } + + public static void main(String[] args) + { + runTest(new OpenPGPKeyReaderTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPMessageGeneratorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPMessageGeneratorTest.java new file mode 100644 index 0000000000..bd709d7355 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPMessageGeneratorTest.java @@ -0,0 +1,193 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.bouncycastle.bcpg.CompressionAlgorithmTags; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.OpenPGPMessageGenerator; +import org.bouncycastle.openpgp.api.OpenPGPMessageOutputStream; +import org.bouncycastle.openpgp.api.OpenPGPPolicy; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class OpenPGPMessageGeneratorTest + extends APITest +{ + @Override + public String getName() + { + return "OpenPGPMessageGeneratorTest"; + } + + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + armoredLiteralDataPacket(api); + unarmoredLiteralDataPacket(api); + + armoredCompressedLiteralDataPacket(api); + unarmoredCompressedLiteralDataPacket(api); + + seipd1EncryptedMessage(api); + seipd2EncryptedMessage(api); + + seipd2EncryptedSignedMessage(api); + } + + private void armoredLiteralDataPacket(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setAllowPadding(false); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream msgOut = gen.open(bOut); + + // Only write a LiteralData packet with "Hello, World!" as content + msgOut.write(Strings.toUTF8ByteArray("Hello, World!")); + + msgOut.close(); + + String nl = Strings.lineSeparator(); + String expected = + "-----BEGIN PGP MESSAGE-----" + nl + + nl + + "yxNiAAAAAABIZWxsbywgV29ybGQh" + nl + + "-----END PGP MESSAGE-----" + nl; + isEquals(expected, bOut.toString()); + } + + private void unarmoredLiteralDataPacket(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(false) // disable ASCII armor + .setAllowPadding(false); // disable padding + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream msgOut = gen.open(bOut); + + // Only write a LiteralData packet with "Hello, World!" as content + msgOut.write(Strings.toUTF8ByteArray("Hello, World!")); + + msgOut.close(); + + isEncodingEqual(Hex.decode("cb1362000000000048656c6c6f2c20576f726c6421"), bOut.toByteArray()); + } + + private void armoredCompressedLiteralDataPacket(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setAllowPadding(false) + .setCompressionNegotiator(new OpenPGPMessageGenerator.CompressionNegotiator() + { + public int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.ZIP; + } + }); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream msgOut = gen.open(bOut); + + // Only write a LiteralData packet with "Hello, World!" as content + msgOut.write(Strings.toUTF8ByteArray("Hello, World!")); + + msgOut.close(); + + String nl = Strings.lineSeparator(); + String expected = + "-----BEGIN PGP MESSAGE-----" + nl + + nl + + "yBUBOy2cxAACHqk5Ofk6CuH5RTkpigA=" + nl + + "-----END PGP MESSAGE-----" + nl; + isEquals(expected, bOut.toString()); + } + + private void unarmoredCompressedLiteralDataPacket(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(false) // no armor + .setAllowPadding(false) + .setCompressionNegotiator(new OpenPGPMessageGenerator.CompressionNegotiator() + { + public int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.ZIP; + } + }); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream msgOut = gen.open(bOut); + + // Only write a LiteralData packet with "Hello, World!" as content + msgOut.write(Strings.toUTF8ByteArray("Hello, World!")); + + msgOut.close(); + + isEncodingEqual(Hex.decode("c815013b2d9cc400021ea93939f93a0ae1f94539298a00"), bOut.toByteArray()); + } + + private void seipd2EncryptedMessage(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPCertificate cert = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.V6_CERT); + + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addEncryptionCertificate(cert); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = gen.open(bOut); + encOut.write(Strings.toUTF8ByteArray("Hello, World!")); + encOut.close(); + + System.out.println(bOut); + } + + private void seipd1EncryptedMessage(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.BOB_KEY); + + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addEncryptionCertificate(key); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = gen.open(bOut); + encOut.write(Strings.toUTF8ByteArray("Hello, World!")); + encOut.close(); + + System.out.println(bOut); + } + + private void seipd2EncryptedSignedMessage(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setAllowPadding(true) + .setArmored(true) + .addSigningKey(key) + .addEncryptionCertificate(key); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = gen.open(bOut); + encOut.write("Hello, World!\n".getBytes()); + encOut.close(); + + System.out.println(bOut); + } + + public static void main(String[] args) + { + runTest(new OpenPGPMessageGeneratorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPMessageProcessorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPMessageProcessorTest.java new file mode 100644 index 0000000000..159960393a --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPMessageProcessorTest.java @@ -0,0 +1,707 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.CompressionAlgorithmTags; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.api.KeyPassphraseProvider; +import org.bouncycastle.openpgp.api.MessageEncryptionMechanism; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPEncryptionNegotiator; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.OpenPGPKeyMaterialProvider; +import org.bouncycastle.openpgp.api.OpenPGPMessageGenerator; +import org.bouncycastle.openpgp.api.OpenPGPMessageInputStream; +import org.bouncycastle.openpgp.api.OpenPGPMessageOutputStream; +import org.bouncycastle.openpgp.api.OpenPGPMessageProcessor; +import org.bouncycastle.openpgp.api.OpenPGPPolicy; +import org.bouncycastle.openpgp.api.OpenPGPSignature; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.Streams; + +public class OpenPGPMessageProcessorTest + extends APITest +{ + private static final byte[] PLAINTEXT = Strings.toUTF8ByteArray("Hello, World!\n"); + + private PGPSessionKey encryptionSessionKey; + + @Override + public String getName() + { + return "OpenPGPMessageProcessorTest"; + } + + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + String javaVersion = System.getProperty("java.version"); + boolean oldJDK = javaVersion.startsWith("1.5") || javaVersion.startsWith("1.6"); + + testVerificationOfSEIPD1MessageWithTamperedCiphertext(api); + + roundtripUnarmoredPlaintextMessage(api); + roundtripArmoredPlaintextMessage(api); + roundTripCompressedMessage(api); + roundTripCompressedSymEncMessageMessage(api); + + roundTripSymEncMessageWithMultiplePassphrases(api); + + roundTripV4KeyEncryptedMessageAlice(api); + roundTripV4KeyEncryptedMessageBob(api); + + roundTripV6KeyEncryptedMessage(api); + encryptWithV4V6KeyDecryptWithV4(api); + encryptWithV4V6KeyDecryptWithV6(api); + + if (!oldJDK) + { + encryptDecryptWithLockedKey(api); + encryptDecryptWithMissingKey(api); + } + + inlineSignWithV4KeyAlice(api); + inlineSignWithV4KeyBob(api); + inlineSignWithV6Key(api); + + verifyMessageByRevokedKey(api); + incompleteMessageProcessing(api); + } + + private void roundtripUnarmoredPlaintextMessage(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(false) + .setAllowPadding(false) + .setCompressionNegotiator(new OpenPGPMessageGenerator.CompressionNegotiator() + { + public int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.UNCOMPRESSED; + } + }); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream msgOut = gen.open(bOut); + msgOut.write(PLAINTEXT); + msgOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + OpenPGPMessageInputStream plainIn = processor.process(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(plainIn, plainOut); + plainIn.close(); + isEquals(MessageEncryptionMechanism.unencrypted(), plainIn.getResult().getEncryptionMethod()); + + isEncodingEqual(PLAINTEXT, plainOut.toByteArray()); + } + + private void roundtripArmoredPlaintextMessage(OpenPGPApi api) + throws PGPException, IOException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(true) + .setAllowPadding(false) + .setCompressionNegotiator(new OpenPGPMessageGenerator.CompressionNegotiator() + { + public int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.UNCOMPRESSED; + } + }); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream msgOut = gen.open(bOut); + msgOut.write(PLAINTEXT); + msgOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + OpenPGPMessageInputStream plainIn = processor.process(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(plainIn, plainOut); + plainIn.close(); + OpenPGPMessageInputStream.Result result = plainIn.getResult(); + isEquals(MessageEncryptionMechanism.unencrypted(), result.getEncryptionMethod()); + + isEncodingEqual(PLAINTEXT, plainOut.toByteArray()); + } + + private void roundTripCompressedMessage(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(true) + .setAllowPadding(false) + .setCompressionNegotiator(new OpenPGPMessageGenerator.CompressionNegotiator() + { + public int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.ZIP; + } + }); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream msgOut = gen.open(bOut); + msgOut.write(PLAINTEXT); + msgOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + InputStream plainIn = processor.process(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(plainIn, plainOut); + plainIn.close(); + + isEncodingEqual(PLAINTEXT, plainOut.toByteArray()); + } + + private void roundTripCompressedSymEncMessageMessage(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(true) + .addEncryptionPassphrase("lal".toCharArray()) + .setSessionKeyExtractionCallback(new PGPEncryptedDataGenerator.SessionKeyExtractionCallback() + { + public void extractSessionKey(PGPSessionKey sessionKey) + { + OpenPGPMessageProcessorTest.this.encryptionSessionKey = sessionKey; + } + }) + .setAllowPadding(false) + .setPasswordBasedEncryptionNegotiator(new OpenPGPEncryptionNegotiator() + { + @Override + public MessageEncryptionMechanism negotiateEncryption(OpenPGPMessageGenerator configuration) + { + return MessageEncryptionMechanism.integrityProtected(SymmetricKeyAlgorithmTags.AES_256); + } + }) + .setCompressionNegotiator(new OpenPGPMessageGenerator.CompressionNegotiator() + { + public int negotiateCompression(OpenPGPMessageGenerator messageGenerator, OpenPGPPolicy policy) + { + return CompressionAlgorithmTags.ZIP; + } + }); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream msgOut = gen.open(bOut); + msgOut.write(PLAINTEXT); + msgOut.close(); + isNotNull(encryptionSessionKey); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageInputStream plainIn = api.decryptAndOrVerifyMessage() + .addMessagePassphrase("lal".toCharArray()) + .process(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(plainIn, plainOut); + plainIn.close(); + OpenPGPMessageInputStream.Result result = plainIn.getResult(); + isEquals(CompressionAlgorithmTags.ZIP, result.getCompressionAlgorithm()); + isTrue(Arrays.areEqual("lal".toCharArray(), result.getDecryptionPassphrase())); + isEncodingEqual(encryptionSessionKey.getKey(), result.getSessionKey().getKey()); + + isEncodingEqual(PLAINTEXT, plainOut.toByteArray()); + } + + private void roundTripSymEncMessageWithMultiplePassphrases(OpenPGPApi api) + throws PGPException, IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .addEncryptionPassphrase("orange".toCharArray()) + .addEncryptionPassphrase("violet".toCharArray()) + .setSessionKeyExtractionCallback(new PGPEncryptedDataGenerator.SessionKeyExtractionCallback() + { + public void extractSessionKey(PGPSessionKey sessionKey) + { + OpenPGPMessageProcessorTest.this.encryptionSessionKey = sessionKey; + } + }) + .setPasswordBasedEncryptionNegotiator( + new OpenPGPEncryptionNegotiator() + { + @Override + public MessageEncryptionMechanism negotiateEncryption(OpenPGPMessageGenerator configuration) + { + return MessageEncryptionMechanism.aead(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.OCB); + } + } + ); + + OutputStream encOut = gen.open(bOut); + encOut.write(PLAINTEXT); + encOut.close(); + + byte[] ciphertext = bOut.toByteArray(); + ByteArrayInputStream bIn = new ByteArrayInputStream(ciphertext); + bOut = new ByteArrayOutputStream(); + + // Try decryption with explicitly set message passphrase + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + processor.addMessagePassphrase("violet".toCharArray()); + OpenPGPMessageInputStream decIn = processor.process(bIn); + Streams.pipeAll(decIn, bOut); + decIn.close(); + OpenPGPMessageInputStream.Result result = decIn.getResult(); + isTrue(Arrays.areEqual("violet".toCharArray(), result.getDecryptionPassphrase())); + isEncodingEqual(encryptionSessionKey.getKey(), result.getSessionKey().getKey()); + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + isEquals(result.getEncryptionMethod(), + MessageEncryptionMechanism.aead(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.OCB)); + + // Try decryption with wrong passphrase and then request proper one dynamically + bOut = new ByteArrayOutputStream(); + bIn = new ByteArrayInputStream(ciphertext); + processor = api.decryptAndOrVerifyMessage(); + decIn = processor.setMissingMessagePassphraseCallback(new StackMessagePassphraseCallback("orange".toCharArray())) + // wrong passphrase, so missing callback is invoked + .addMessagePassphrase("yellow".toCharArray()) + .process(bIn); + + Streams.pipeAll(decIn, bOut); + decIn.close(); + result = decIn.getResult(); + isTrue(Arrays.areEqual("orange".toCharArray(), result.getDecryptionPassphrase())); + isEncodingEqual(encryptionSessionKey.getKey(), result.getSessionKey().getKey()); + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + } + + private void roundTripV4KeyEncryptedMessageAlice(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream enc = gen.open(bOut); + enc.write(PLAINTEXT); + enc.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + processor.addDecryptionKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY)); + + OpenPGPMessageInputStream decIn = processor.process(bIn); + + bOut = new ByteArrayOutputStream(); + Streams.pipeAll(decIn, bOut); + isEncodingEqual(bOut.toByteArray(), PLAINTEXT); + OpenPGPMessageInputStream.Result result = decIn.getResult(); + isEquals(MessageEncryptionMechanism.integrityProtected(SymmetricKeyAlgorithmTags.AES_256), + result.getEncryptionMethod()); + } + + private void roundTripV4KeyEncryptedMessageBob(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.BOB_CERT)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream enc = gen.open(bOut); + enc.write(PLAINTEXT); + enc.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + processor.addDecryptionKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.BOB_KEY)); + + OpenPGPMessageInputStream decIn = processor.process(bIn); + + bOut = new ByteArrayOutputStream(); + Streams.pipeAll(decIn, bOut); + decIn.close(); + OpenPGPMessageInputStream.Result result = decIn.getResult(); + isEquals(MessageEncryptionMechanism.integrityProtected(SymmetricKeyAlgorithmTags.AES_256), + result.getEncryptionMethod()); + isEncodingEqual(bOut.toByteArray(), PLAINTEXT); + } + + private void roundTripV6KeyEncryptedMessage(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .setArmored(true) + .addEncryptionCertificate(key) + .setAllowPadding(false); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream msgOut = gen.open(bOut); + msgOut.write(PLAINTEXT); + msgOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addDecryptionKey(key); + + OpenPGPMessageInputStream plainIn = processor.process(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(plainIn, plainOut); + plainIn.close(); + OpenPGPMessageInputStream.Result result = plainIn.getResult(); + isEquals(MessageEncryptionMechanism.aead(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB), + result.getEncryptionMethod()); + + isEncodingEqual(PLAINTEXT, plainOut.toByteArray()); + } + + private void encryptWithV4V6KeyDecryptWithV4(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT)); + gen.addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.V6_CERT)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream enc = gen.open(bOut); + enc.write(PLAINTEXT); + enc.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addDecryptionKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY)); + + OpenPGPMessageInputStream decIn = processor.process(bIn); + + bOut = new ByteArrayOutputStream(); + Streams.pipeAll(decIn, bOut); + decIn.close(); + isEncodingEqual(bOut.toByteArray(), PLAINTEXT); + OpenPGPMessageInputStream.Result result = decIn.getResult(); + isEquals(MessageEncryptionMechanism.integrityProtected(SymmetricKeyAlgorithmTags.AES_256), + result.getEncryptionMethod()); + } + + private void encryptWithV4V6KeyDecryptWithV6(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT)); + gen.addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.V6_CERT)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream enc = gen.open(bOut); + enc.write(PLAINTEXT); + enc.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addDecryptionKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY)); + + OpenPGPMessageInputStream decIn = processor.process(bIn); + + bOut = new ByteArrayOutputStream(); + Streams.pipeAll(decIn, bOut); + isEncodingEqual(bOut.toByteArray(), PLAINTEXT); + OpenPGPMessageInputStream.Result result = decIn.getResult(); + isEquals(MessageEncryptionMechanism.integrityProtected(SymmetricKeyAlgorithmTags.AES_256), + result.getEncryptionMethod()); + } + + private void encryptDecryptWithLockedKey(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY_LOCKED); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + OpenPGPMessageOutputStream encOut = api.signAndOrEncryptMessage() + .addEncryptionCertificate(key) + .open(bOut); + + encOut.write(PLAINTEXT); + encOut.close(); + + byte[] ciphertext = bOut.toByteArray(); + + // Provide passphrase and key together + ByteArrayInputStream bIn = new ByteArrayInputStream(ciphertext); + bOut = new ByteArrayOutputStream(); + OpenPGPMessageInputStream decIn = api.decryptAndOrVerifyMessage() + .addDecryptionKey(key, OpenPGPTestKeys.V6_KEY_LOCKED_PASSPHRASE.toCharArray()) + .process(bIn); + Streams.pipeAll(decIn, bOut); + decIn.close(); + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + OpenPGPMessageInputStream.Result result = decIn.getResult(); + PGPSessionKey sk = result.getSessionKey(); + + // Provide passphrase and key separate from another + bIn = new ByteArrayInputStream(ciphertext); + bOut = new ByteArrayOutputStream(); + decIn = api.decryptAndOrVerifyMessage() + .addDecryptionKey(key) + .addDecryptionKeyPassphrase(OpenPGPTestKeys.V6_KEY_LOCKED_PASSPHRASE.toCharArray()) + .process(bIn); + Streams.pipeAll(decIn, bOut); + decIn.close(); + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + result = decIn.getResult(); + isEncodingEqual(sk.getKey(), result.getSessionKey().getKey()); + + // Provide passphrase dynamically + bIn = new ByteArrayInputStream(ciphertext); + bOut = new ByteArrayOutputStream(); + decIn = api.decryptAndOrVerifyMessage() + .addDecryptionKey(key) + .setMissingOpenPGPKeyPassphraseProvider(new KeyPassphraseProvider() + { + public char[] getKeyPassword(OpenPGPKey.OpenPGPSecretKey key) + { + return OpenPGPTestKeys.V6_KEY_LOCKED_PASSPHRASE.toCharArray(); + } + }) + .process(bIn); + Streams.pipeAll(decIn, bOut); + decIn.close(); + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + + result = decIn.getResult(); + isEncodingEqual(sk.getKey(), result.getSessionKey().getKey()); + } + + private void encryptDecryptWithMissingKey(OpenPGPApi api) + throws IOException, PGPException + { + final OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + OutputStream encOut = api.signAndOrEncryptMessage() + .addEncryptionCertificate(key) + .open(bOut); + + encOut.write(PLAINTEXT); + encOut.close(); + + byte[] ciphertext = bOut.toByteArray(); + + // Provide passphrase and key together + ByteArrayInputStream bIn = new ByteArrayInputStream(ciphertext); + bOut = new ByteArrayOutputStream(); + OpenPGPMessageInputStream decIn = api.decryptAndOrVerifyMessage() + .setMissingOpenPGPKeyProvider(new OpenPGPKeyMaterialProvider.OpenPGPKeyProvider() + { + public OpenPGPKey provide(KeyIdentifier componentKeyIdentifier) + { + return key; + } + }) + .process(bIn); + Streams.pipeAll(decIn, bOut); + decIn.close(); + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + + OpenPGPMessageInputStream.Result result = decIn.getResult(); + isEquals(key, result.getDecryptionKey().getCertificate()); + isNotNull(result.getSessionKey()); + } + + private void inlineSignWithV4KeyAlice(OpenPGPApi api) + throws IOException, PGPException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + OpenPGPKey aliceKey = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY); + gen.addSigningKey(aliceKey); + + OutputStream signOut = gen.open(bOut); + signOut.write(PLAINTEXT); + signOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + bOut = new ByteArrayOutputStream(); + + OpenPGPCertificate aliceCert = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addVerificationCertificate(aliceCert); + + OpenPGPMessageInputStream verifIn = processor.process(bIn); + Streams.pipeAll(verifIn, bOut); + verifIn.close(); + OpenPGPMessageInputStream.Result result = verifIn.getResult(); + isEquals(MessageEncryptionMechanism.unencrypted(), result.getEncryptionMethod()); + List signatures = result.getSignatures(); + isEquals(1, signatures.size()); + OpenPGPSignature.OpenPGPDocumentSignature sig = signatures.get(0); + isEquals(aliceCert, sig.getIssuerCertificate()); + + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + } + + private void inlineSignWithV4KeyBob(OpenPGPApi api) + throws IOException, PGPException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + OpenPGPKey bobKey = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.BOB_KEY); + gen.addSigningKey(bobKey); + + OutputStream signOut = gen.open(bOut); + signOut.write(PLAINTEXT); + signOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + bOut = new ByteArrayOutputStream(); + + OpenPGPCertificate bobCert = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.BOB_CERT); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addVerificationCertificate(bobCert); + + OpenPGPMessageInputStream verifIn = processor.process(bIn); + Streams.pipeAll(verifIn, bOut); + verifIn.close(); + OpenPGPMessageInputStream.Result result = verifIn.getResult(); + List signatures = result.getSignatures(); + isEquals(1, signatures.size()); + OpenPGPSignature.OpenPGPDocumentSignature sig = signatures.get(0); + isEquals(bobCert, sig.getIssuerCertificate()); + + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + } + + private void inlineSignWithV6Key(OpenPGPApi api) + throws PGPException, IOException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + OpenPGPKey v6Key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.V6_KEY); + gen.addSigningKey(v6Key); + + OutputStream signOut = gen.open(bOut); + signOut.write(PLAINTEXT); + signOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + bOut = new ByteArrayOutputStream(); + + OpenPGPCertificate v6Cert = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.V6_CERT); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addVerificationCertificate(v6Cert); + + OpenPGPMessageInputStream verifIn = processor.process(bIn); + Streams.pipeAll(verifIn, bOut); + verifIn.close(); + OpenPGPMessageInputStream.Result result = verifIn.getResult(); + List signatures = result.getSignatures(); + isEquals(1, signatures.size()); + OpenPGPSignature.OpenPGPDocumentSignature sig = signatures.get(0); + isEquals(v6Cert, sig.getIssuerCertificate()); + + isEncodingEqual(PLAINTEXT, bOut.toByteArray()); + } + + private void verifyMessageByRevokedKey(OpenPGPApi api) + throws PGPException, IOException + { + // Create a minimal signed message + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY); + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage(); + gen.addSigningKey(key); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream oOut = gen.open(bOut); + oOut.write("Hello, World!\n".getBytes()); + oOut.close(); + + // Load the certificate and import its revocation signature + OpenPGPCertificate cert = api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT); + cert = OpenPGPCertificate.join(cert, OpenPGPTestKeys.ALICE_REVOCATION_CERT); + + // Process the signed message using the revoked key + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + processor.addVerificationCertificate(cert); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageInputStream oIn = processor.process(bIn); + Streams.drain(oIn); + oIn.close(); + + OpenPGPMessageInputStream.Result result = oIn.getResult(); + OpenPGPSignature.OpenPGPDocumentSignature sig = result.getSignatures().get(0); + // signature is no valid + isFalse(sig.isValid()); + } + + private void incompleteMessageProcessing(OpenPGPApi api) + throws IOException, PGPException + { + OpenPGPMessageGenerator gen = api.signAndOrEncryptMessage() + .addEncryptionCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.ALICE_CERT)) + .addSigningKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.BOB_KEY)); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream out = gen.open(bOut); + + out.write(Strings.toUTF8ByteArray("Some Data")); + out.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage() + .addVerificationCertificate(api.readKeyOrCertificate().parseCertificate(OpenPGPTestKeys.BOB_CERT)) + .addDecryptionKey(api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.ALICE_KEY)); + OpenPGPMessageInputStream in = processor.process(bIn); + + // read a single byte (not the entire message) + in.read(); + + in.close(); + OpenPGPMessageInputStream.Result result = in.getResult(); + OpenPGPSignature.OpenPGPDocumentSignature sig = result.getSignatures().get(0); + isFalse(sig.isValid()); + } + + private void testVerificationOfSEIPD1MessageWithTamperedCiphertext(OpenPGPApi api) + throws IOException, PGPException + { + String MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "wcDMA3wvqk35PDeyAQv/c0eFDZud8YCzKu0qzq7xOUeF0KiFFv58RSAookfyce9B\n" + + "LSXH7g/F/3Pdp9EHcrtBsxYRXUdWmZHvwFRvAiwCl9unjUgRendopmuNJ5zNgB2w\n" + + "DkuMA2J2J5HGTicvCwGrWALDG6Dc56UEFTwCsip8uKNG+Q3X5IwpU7Vztqywkt4/\n" + + "RNp8+neu+oJELWn3mC3oZrMzYIaD2SlyVaW5Vpksjz32VGKXCm4/hGC/03tGuE1i\n" + + "5sOZicHpeN24BD2tr3MMOdHKPXKxVPPx5T1MIJYUoYjMp7Tnml6F4Obhf+VllAli\n" + + "mkQHj6vevbEkLcJX67pvD04PJiQqm5ea1GwOZDW/nPLih80AJWHpXME36WBzk4X2\n" + + "bHaK3qQxyxqfpvMvWcargI3neWNLaSzqY/2eCrY/OEbAcj18W+9u7phkEoVRmrC7\n" + + "mqIeEUXtGjWSywtJXF8tIcxOU3+IqekXLW9yFIzRrHWEzRVKzP2P5q7mwOp2ddjg\n" + + "8vqe/DOz1r8VxN6orUue0kwBJVHfkYpW8cwX2AtIPYk90ct2qCTbCtNQul+txpRY\n" + + "IwBVELjaaSGpdOuIHkETYssCNfqPSv0rNmaTDq78xItvhjuc4lRaKkpF9DdE\n" + + "=I5BA\n" + + "-----END PGP MESSAGE-----"; + OpenPGPKey key = api.readKeyOrCertificate().parseKey(OpenPGPTestKeys.BOB_KEY); + OpenPGPMessageProcessor processor = api.decryptAndOrVerifyMessage(); + processor.addDecryptionKey(key); + OpenPGPMessageInputStream oIn = processor.process(new ByteArrayInputStream(Strings.toUTF8ByteArray(MSG))); + Streams.drain(oIn); + try + { + oIn.close(); + } + catch (IOException e) + { + // expected + } + } + + public static void main(String[] args) + { + runTest(new OpenPGPMessageProcessorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPV4KeyGenerationTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPV4KeyGenerationTest.java new file mode 100644 index 0000000000..b8456e63c4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPV4KeyGenerationTest.java @@ -0,0 +1,64 @@ +package org.bouncycastle.openpgp.api.test; + +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.api.KeyPairGeneratorCallback; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.SignatureParameters; +import org.bouncycastle.openpgp.api.SignatureSubpacketsFunction; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; + +public class OpenPGPV4KeyGenerationTest + extends APITest +{ + @Override + public String getName() + { + return "OpenPGPV4KeyGenerationTest"; + } + + @Override + protected void performTestWith(OpenPGPApi api) + throws PGPException + { + generateRSAKey(api); + } + + private void generateRSAKey(OpenPGPApi api) + throws PGPException + { + OpenPGPKey key = api.generateKey(PublicKeyPacket.VERSION_4) + .withPrimaryKey(new KeyPairGeneratorCallback() + { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateRsaKeyPair(3072); + } + }, SignatureParameters.Callback.Util.modifyHashedSubpackets(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + subpackets.setKeyFlags(KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA | KeyFlags.ENCRYPT_STORAGE | KeyFlags.ENCRYPT_COMMS); + return subpackets; + } + })) + .addUserId("Alice ") + .build(); + + isEquals(PublicKeyPacket.VERSION_4, key.getPrimaryKey().getVersion()); + } + + public static void main(String[] args) + { + runTest(new OpenPGPV4KeyGenerationTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPV6KeyGeneratorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPV6KeyGeneratorTest.java new file mode 100644 index 0000000000..7043bbfef5 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/OpenPGPV6KeyGeneratorTest.java @@ -0,0 +1,643 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.IOException; +import java.util.Date; +import java.util.Iterator; + +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.PublicKeyUtils; +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.bcpg.SignaturePacket; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; +import org.bouncycastle.openpgp.api.KeyPairGeneratorCallback; +import org.bouncycastle.openpgp.api.OpenPGPApi; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.OpenPGPKeyGenerator; +import org.bouncycastle.openpgp.api.SignatureParameters; +import org.bouncycastle.openpgp.api.SignatureSubpacketsFunction; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; +import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPairGeneratorProvider; + +public class OpenPGPV6KeyGeneratorTest + extends APITest +{ + @Override + public String getName() + { + return "OpenPGPV6KeyGeneratorTest"; + } + + @Override + protected void performTestWith(OpenPGPApi api) + throws PGPException, IOException + { + testGenerateCustomKey(api); + testGenerateMinimalKey(api); + + testGenerateSignOnlyKeyBaseCase(api); + testGenerateAEADProtectedSignOnlyKey(api); + testGenerateCFBProtectedSignOnlyKey(api); + + testGenerateClassicKeyBaseCase(api); + testGenerateProtectedTypicalKey(api); + + testGenerateEd25519x25519Key(api); + testGenerateEd448x448Key(api); + + testEnforcesPrimaryOrSubkeyType(api); + testGenerateKeyWithoutSignatures(api); + } + + private void testGenerateSignOnlyKeyBaseCase(OpenPGPApi api) + throws PGPException + { + OpenPGPKeyGenerator generator = api.generateKey(); + OpenPGPKey key = generator.signOnlyKey().build(); + PGPSecretKeyRing secretKeys = key.getPGPKeyRing(); + + Iterator it = secretKeys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)it.next(); + isFalse("sign-only key MUST consists of only a single key", it.hasNext()); + PGPSignature directKeySignature = (PGPSignature)primaryKey.getPublicKey().getKeySignatures().next(); + isNotNull("Key MUST have direct-key signature", directKeySignature); + isEquals("Direct-key signature MUST be version 6", + SignaturePacket.VERSION_6, directKeySignature.getVersion()); + PGPSignatureSubpacketVector hPackets = directKeySignature.getHashedSubPackets(); + isNotNull("Subpackets MUST contain issuer-fingerprint subpacket", + hPackets.getIssuerFingerprint()); + isFalse("Subpackets MUST NOT contain issuer-key-id subpacket", + hPackets.hasSubpacket(SignatureSubpacketTags.ISSUER_KEY_ID)); + isNotNull("Subpackets MUST contain signature creation-time subpacket", + hPackets.getSignatureCreationTime()); + isEquals("Sign-Only primary key MUST carry CS flags", + KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA, hPackets.getKeyFlags()); + + isEquals("Key version mismatch", 6, primaryKey.getPublicKey().getVersion()); + isEquals("Key MUST be unprotected", SecretKeyPacket.USAGE_NONE, primaryKey.getS2KUsage()); + } + + private void testGenerateAEADProtectedSignOnlyKey(OpenPGPApi api) + throws PGPException + { + OpenPGPKeyGenerator generator = api.generateKey(new Date(), true); + OpenPGPKey key = generator.signOnlyKey().build("passphrase".toCharArray()); + PGPSecretKeyRing secretKeys = key.getPGPKeyRing(); + + Iterator it = secretKeys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)it.next(); + isFalse("sign-only key MUST consists of only a single key", it.hasNext()); + + isEquals("Key MUST be AEAD-protected", SecretKeyPacket.USAGE_AEAD, primaryKey.getS2KUsage()); + isNotNull("Secret key MUST be retrievable using the proper passphrase", + primaryKey.extractKeyPair( + new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) + .build("passphrase".toCharArray()))); + } + + private void testGenerateCFBProtectedSignOnlyKey(OpenPGPApi api) + throws PGPException + { + OpenPGPKeyGenerator generator = api.generateKey(new Date(), false); + OpenPGPKey key = generator.signOnlyKey().build("passphrase".toCharArray()); + PGPSecretKeyRing secretKeys = key.getPGPKeyRing(); + + Iterator it = secretKeys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)it.next(); + isFalse("sign-only key MUST consists of only a single key", it.hasNext()); + + isEquals("Key MUST be CFB-protected", SecretKeyPacket.USAGE_SHA1, primaryKey.getS2KUsage()); + isNotNull("Secret key MUST be retrievable using the proper passphrase", + primaryKey.extractKeyPair( + new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) + .build("passphrase".toCharArray()))); + } + + private void testGenerateClassicKeyBaseCase(OpenPGPApi api) + throws PGPException + { + Date creationTime = currentTimeRounded(); + OpenPGPKeyGenerator generator = api.generateKey(creationTime); + OpenPGPKey key = generator + .classicKey("Alice ").build(); + PGPSecretKeyRing secretKeys = key.getPGPKeyRing(); + + Iterator keys = secretKeys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)keys.next(); + isEquals("Primary key version mismatch", PublicKeyPacket.VERSION_6, + primaryKey.getPublicKey().getVersion()); + isEquals(creationTime, primaryKey.getPublicKey().getCreationTime()); + isTrue("Primary key uses signing-capable algorithm", + PublicKeyUtils.isSigningAlgorithm(primaryKey.getPublicKey().getAlgorithm())); + PGPSignature directKeySig = (PGPSignature)primaryKey.getPublicKey().getKeySignatures().next(); + isEquals("Primary key of a classic key MUST carry C key flag.", + KeyFlags.CERTIFY_OTHER, directKeySig.getHashedSubPackets().getKeyFlags()); + + // Test UIDs + Iterator uids = primaryKey.getUserIDs(); + isEquals("Alice ", uids.next()); + isFalse(uids.hasNext()); + + // Test signing subkey + PGPSecretKey signingSubkey = (PGPSecretKey)keys.next(); + isEquals("Signing key version mismatch", PublicKeyPacket.VERSION_6, + signingSubkey.getPublicKey().getVersion()); + isTrue("Signing subkey uses signing-capable algorithm", + PublicKeyUtils.isSigningAlgorithm(signingSubkey.getPublicKey().getAlgorithm())); + isEquals(creationTime, signingSubkey.getPublicKey().getCreationTime()); + PGPSignature signingKeyBinding = (PGPSignature)signingSubkey.getPublicKey().getKeySignatures().next(); + isEquals("Signing subkey MUST carry S key flag.", + KeyFlags.SIGN_DATA, signingKeyBinding.getHashedSubPackets().getKeyFlags()); + isNotNull("Signing subkey binding MUST carry primary key binding sig", + signingKeyBinding.getHashedSubPackets().getEmbeddedSignatures().get(0)); + + // Test encryption subkey + PGPSecretKey encryptionSubkey = (PGPSecretKey)keys.next(); + isEquals("Encryption key version mismatch", PublicKeyPacket.VERSION_6, + encryptionSubkey.getPublicKey().getVersion()); + isTrue("Encryption subkey uses encryption-capable algorithm", + encryptionSubkey.getPublicKey().isEncryptionKey()); + isEquals(creationTime, encryptionSubkey.getPublicKey().getCreationTime()); + PGPSignature encryptionKeyBinding = (PGPSignature)encryptionSubkey.getPublicKey().getKeySignatures().next(); + isEquals("Encryption key MUST carry encryption flags", + KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, + encryptionKeyBinding.getHashedSubPackets().getKeyFlags()); + + // Test has no additional keys + isFalse(keys.hasNext()); + + // Test all keys are unprotected + for (Iterator it = secretKeys.getSecretKeys(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + isEquals("(Sub-)keys MUST be unprotected", SecretKeyPacket.USAGE_NONE, k.getS2KUsage()); + } + } + + private void testGenerateProtectedTypicalKey(OpenPGPApi api) + throws PGPException + { + Date creationTime = currentTimeRounded(); + OpenPGPKeyGenerator generator = api.generateKey(creationTime); + OpenPGPKey key = generator + .classicKey("Alice ").build("passphrase".toCharArray()); + PGPSecretKeyRing secretKeys = key.getPGPKeyRing(); + + // Test creation time + for (Iterator it = secretKeys.toCertificate().iterator(); it.hasNext();) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + isEquals(creationTime, k.getCreationTime()); + for (Iterator its = k.getSignatures(); its.hasNext(); ) + { + PGPSignature sig = (PGPSignature)its.next(); + isEquals(creationTime, sig.getCreationTime()); + } + } + + PGPPublicKey primaryKey = secretKeys.getPublicKey(); + // Test UIDs + Iterator uids = primaryKey.getUserIDs(); + isEquals("Alice ", uids.next()); + isFalse(uids.hasNext()); + + for (Iterator it = secretKeys.getSecretKeys(); it.hasNext();) + { + PGPSecretKey k = (PGPSecretKey)it.next(); + isEquals("(Sub-)keys MUST be protected", SecretKeyPacket.USAGE_AEAD, k.getS2KUsage()); + + } + } + + private void testGenerateEd25519x25519Key(OpenPGPApi api) + throws PGPException + { + Date currentTime = currentTimeRounded(); + String userId = "Foo "; + OpenPGPKeyGenerator generator = api.generateKey(currentTime); + + OpenPGPKey key = generator.ed25519x25519Key(userId).build(); + PGPSecretKeyRing secretKey = key.getPGPKeyRing(); + + Iterator iterator = secretKey.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)iterator.next(); + PGPSecretKey signingSubkey = (PGPSecretKey)iterator.next(); + PGPSecretKey encryptionSubkey = (PGPSecretKey)iterator.next(); + isFalse("Unexpected key", iterator.hasNext()); + + isEquals(PublicKeyAlgorithmTags.Ed25519, primaryKey.getPublicKey().getAlgorithm()); + Iterator keySignatures = primaryKey.getPublicKey().getKeySignatures(); + PGPSignature directKeySignature = (PGPSignature)keySignatures.next(); + isFalse(keySignatures.hasNext()); + PGPSignatureSubpacketVector hashedSubpackets = directKeySignature.getHashedSubPackets(); + isEquals(KeyFlags.CERTIFY_OTHER, hashedSubpackets.getKeyFlags()); + + Iterator userIds = primaryKey.getUserIDs(); + isEquals(userId, userIds.next()); + isFalse(userIds.hasNext()); + Iterator userIdSignatures = primaryKey.getPublicKey().getSignaturesForID(userId); + PGPSignature userIdSig = (PGPSignature)userIdSignatures.next(); + isFalse(userIdSignatures.hasNext()); + isEquals(PGPSignature.POSITIVE_CERTIFICATION, userIdSig.getSignatureType()); + + isEquals(PublicKeyAlgorithmTags.Ed25519, signingSubkey.getPublicKey().getAlgorithm()); + Iterator signingSubkeySigs = signingSubkey.getPublicKey().getKeySignatures(); + PGPSignature signingSubkeySig = (PGPSignature)signingSubkeySigs.next(); + isFalse(signingSubkeySigs.hasNext()); + isEquals(PGPSignature.SUBKEY_BINDING, signingSubkeySig.getSignatureType()); + hashedSubpackets = signingSubkeySig.getHashedSubPackets(); + isEquals(KeyFlags.SIGN_DATA, hashedSubpackets.getKeyFlags()); + + isEquals(PublicKeyAlgorithmTags.X25519, encryptionSubkey.getPublicKey().getAlgorithm()); + Iterator encryptionSubkeySigs = encryptionSubkey.getPublicKey().getKeySignatures(); + PGPSignature encryptionSubkeySig = (PGPSignature)encryptionSubkeySigs.next(); + isFalse(encryptionSubkeySigs.hasNext()); + isEquals(PGPSignature.SUBKEY_BINDING, encryptionSubkeySig.getSignatureType()); + hashedSubpackets = encryptionSubkeySig.getHashedSubPackets(); + isEquals(KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, hashedSubpackets.getKeyFlags()); + } + + private void testGenerateEd448x448Key(OpenPGPApi api) + throws PGPException + { + Date currentTime = currentTimeRounded(); + String userId = "Foo "; + OpenPGPKeyGenerator generator = api.generateKey(currentTime); + + OpenPGPKey key = generator.ed448x448Key(userId).build(); + PGPSecretKeyRing secretKey = key.getPGPKeyRing(); + + Iterator iterator = secretKey.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)iterator.next(); + PGPSecretKey signingSubkey = (PGPSecretKey)iterator.next(); + PGPSecretKey encryptionSubkey = (PGPSecretKey)iterator.next(); + isFalse("Unexpected key", iterator.hasNext()); + + isEquals(PublicKeyAlgorithmTags.Ed448, primaryKey.getPublicKey().getAlgorithm()); + Iterator keySignatures = primaryKey.getPublicKey().getKeySignatures(); + PGPSignature directKeySignature = (PGPSignature)keySignatures.next(); + isFalse(keySignatures.hasNext()); + PGPSignatureSubpacketVector hashedSubpackets = directKeySignature.getHashedSubPackets(); + isEquals(KeyFlags.CERTIFY_OTHER, hashedSubpackets.getKeyFlags()); + + Iterator userIds = primaryKey.getUserIDs(); + isEquals(userId, userIds.next()); + isFalse(userIds.hasNext()); + Iterator userIdSignatures = primaryKey.getPublicKey().getSignaturesForID(userId); + PGPSignature userIdSig = (PGPSignature)userIdSignatures.next(); + isFalse(userIdSignatures.hasNext()); + isEquals(PGPSignature.POSITIVE_CERTIFICATION, userIdSig.getSignatureType()); + + isEquals(PublicKeyAlgorithmTags.Ed448, signingSubkey.getPublicKey().getAlgorithm()); + Iterator signingSubkeySigs = signingSubkey.getPublicKey().getKeySignatures(); + PGPSignature signingSubkeySig = (PGPSignature)signingSubkeySigs.next(); + isFalse(signingSubkeySigs.hasNext()); + isEquals(PGPSignature.SUBKEY_BINDING, signingSubkeySig.getSignatureType()); + hashedSubpackets = signingSubkeySig.getHashedSubPackets(); + isEquals(KeyFlags.SIGN_DATA, hashedSubpackets.getKeyFlags()); + + isEquals(PublicKeyAlgorithmTags.X448, encryptionSubkey.getPublicKey().getAlgorithm()); + Iterator encryptionSubkeySigs = encryptionSubkey.getPublicKey().getKeySignatures(); + PGPSignature encryptionSubkeySig = (PGPSignature)encryptionSubkeySigs.next(); + isFalse(encryptionSubkeySigs.hasNext()); + isEquals(PGPSignature.SUBKEY_BINDING, encryptionSubkeySig.getSignatureType()); + hashedSubpackets = encryptionSubkeySig.getHashedSubPackets(); + isEquals(KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, hashedSubpackets.getKeyFlags()); + } + + private void testGenerateCustomKey(OpenPGPApi api) + throws PGPException + { + Date creationTime = currentTimeRounded(); + OpenPGPKeyGenerator generator = api.generateKey(creationTime, false); + + OpenPGPKey key = generator + .withPrimaryKey( + new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateRsaKeyPair(4096); + } + }, + SignatureParameters.Callback.Util.modifyHashedSubpackets(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.removePacketsOfType(SignatureSubpacketTags.KEY_FLAGS); + subpackets.setKeyFlags(KeyFlags.CERTIFY_OTHER); + + subpackets.removePacketsOfType(SignatureSubpacketTags.FEATURES); + subpackets.setFeature(false, Features.FEATURE_SEIPD_V2); + + subpackets.addNotationData(false, true, + "notation@example.com", "CYBER"); + + subpackets.setPreferredKeyServer(false, "https://example.com/openpgp/cert.asc"); + return subpackets; + } + })) + .addUserId("Alice ") + .addSigningSubkey( + new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEd448KeyPair(); + } + }, + SignatureParameters.Callback.Util.modifyHashedSubpackets(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.addNotationData(false, true, + "notation@example.com", "ZAUBER"); + return subpackets; + } + }), + null) + .addEncryptionSubkey( + new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateX448KeyPair(); + } + }) + .build("primary-key-passphrase".toCharArray()); + OpenPGPCertificate.OpenPGPComponentKey encryptionKey = key.getEncryptionKeys().get(0); + OpenPGPCertificate.OpenPGPComponentKey signingKey = key.getSigningKeys().get(0); + key = api.editKey(key, "primary-key-passphrase".toCharArray()) + .changePassphrase(encryptionKey.getKeyIdentifier(), + "primary-key-passphrase".toCharArray(), + "encryption-key-passphrase".toCharArray(), + false) + .changePassphrase(signingKey.getKeyIdentifier(), + "primary-key-passphrase".toCharArray(), + "signing-key-passphrase".toCharArray(), + false) + .done(); + + PGPSecretKeyRing secretKey = key.getPGPKeyRing(); + Iterator keyIt = secretKey.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)keyIt.next(); + isEquals("Primary key MUST be RSA_GENERAL", + PublicKeyAlgorithmTags.RSA_GENERAL, primaryKey.getPublicKey().getAlgorithm()); + isEquals("Primary key MUST be 4096 bits", 4096, primaryKey.getPublicKey().getBitStrength()); + isEquals("Primary key creation time mismatch", + creationTime, primaryKey.getPublicKey().getCreationTime()); + PGPSignature directKeySig = (PGPSignature)primaryKey.getPublicKey().getKeySignatures().next(); + PGPSignatureSubpacketVector hashedSubpackets = directKeySig.getHashedSubPackets(); + isEquals("Primary key key flags mismatch", + KeyFlags.CERTIFY_OTHER, hashedSubpackets.getKeyFlags()); + isEquals("Primary key features mismatch", + Features.FEATURE_SEIPD_V2, hashedSubpackets.getFeatures().getFeatures()); + isEquals("Primary key sig notation data mismatch", + "CYBER", + hashedSubpackets.getNotationDataOccurrences("notation@example.com")[0].getNotationValue()); + + Iterator uids = primaryKey.getUserIDs(); + String uid = (String)uids.next(); + isFalse("Unexpected additional UID", uids.hasNext()); + PGPSignature uidSig = (PGPSignature)primaryKey.getPublicKey().getSignaturesForID(uid).next(); + isEquals("UID binding sig type mismatch", + PGPSignature.POSITIVE_CERTIFICATION, uidSig.getSignatureType()); + + PGPSecretKey signingSubkey = (PGPSecretKey)keyIt.next(); + isEquals("Subkey MUST be Ed448", + PublicKeyAlgorithmTags.Ed448, signingSubkey.getPublicKey().getAlgorithm()); + isEquals("Subkey creation time mismatch", + creationTime, signingSubkey.getPublicKey().getCreationTime()); + PGPSignature sigSubBinding = (PGPSignature)signingSubkey.getPublicKey().getKeySignatures().next(); + PGPSignatureSubpacketVector sigSubBindHashPkts = sigSubBinding.getHashedSubPackets(); + isEquals("Encryption subkey key flags mismatch", + KeyFlags.SIGN_DATA, sigSubBindHashPkts.getKeyFlags()); + isEquals("Subkey notation data mismatch", + "ZAUBER", + sigSubBindHashPkts.getNotationDataOccurrences("notation@example.com")[0].getNotationValue()); + isFalse("Missing embedded primary key binding signature", + sigSubBindHashPkts.getEmbeddedSignatures().isEmpty()); + + PGPSecretKey encryptionSubkey = (PGPSecretKey)keyIt.next(); + isFalse("Unexpected additional subkey", keyIt.hasNext()); + isEquals("Subkey MUST be X448", + PublicKeyAlgorithmTags.X448, encryptionSubkey.getPublicKey().getAlgorithm()); + isEquals("Subkey creation time mismatch", + creationTime, encryptionSubkey.getPublicKey().getCreationTime()); + PGPSignature encryptionBinding = (PGPSignature)encryptionSubkey.getPublicKey().getKeySignatures().next(); + PGPSignatureSubpacketVector encBindHashPkts = encryptionBinding.getHashedSubPackets(); + isEquals("Encryption subkey key flags mismatch", + KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, encBindHashPkts.getKeyFlags()); + isTrue("Unexpected embedded primary key binding signature in encryption subkey binding", + encBindHashPkts.getEmbeddedSignatures().isEmpty()); + + BcPBESecretKeyDecryptorBuilder keyDecryptorBuilder = new BcPBESecretKeyDecryptorBuilder( + new BcPGPDigestCalculatorProvider()); + + isNotNull("Could not decrypt primary key using correct passphrase", + primaryKey.extractPrivateKey(keyDecryptorBuilder.build("primary-key-passphrase".toCharArray()))); + isNotNull("Could not decrypt signing subkey using correct passphrase", + signingSubkey.extractPrivateKey(keyDecryptorBuilder.build("signing-key-passphrase".toCharArray()))); + isNotNull("Could not decrypt encryption subkey using correct passphrase", + encryptionSubkey.extractPrivateKey(keyDecryptorBuilder.build("encryption-key-passphrase".toCharArray()))); + } + + private void testGenerateMinimalKey(OpenPGPApi api) + throws PGPException + { + Date creationTime = currentTimeRounded(); + OpenPGPKeyGenerator gen = api.generateKey(creationTime, false); + OpenPGPKey key = gen.withPrimaryKey( + new KeyPairGeneratorCallback() + { + @Override + public PGPKeyPair generateFrom(PGPKeyPairGenerator generator) + throws PGPException + { + return generator.generateEd25519KeyPair(); + } + }, + SignatureParameters.Callback.Util.modifyHashedSubpackets(new SignatureSubpacketsFunction() + { + @Override + public PGPSignatureSubpacketGenerator apply(PGPSignatureSubpacketGenerator subpackets) + { + subpackets.addNotationData(false, true, "foo@bouncycastle.org", "bar"); + return subpackets; + } + })) + .addUserId("Alice ") + .addEncryptionSubkey() + .addSigningSubkey() + .build(); + PGPSecretKeyRing secretKeys = key.getPGPKeyRing(); + + // Test creation time + for(Iterator it = secretKeys.toCertificate().iterator(); it.hasNext(); ) + { + PGPPublicKey k = (PGPPublicKey)it.next(); + isEquals(creationTime, k.getCreationTime()); + for (Iterator itSign = k.getSignatures(); itSign.hasNext(); ) { + PGPSignature sig = itSign.next(); + isEquals(creationTime, sig.getCreationTime()); + } + } + + PGPPublicKey primaryKey = secretKeys.getPublicKey(); + // Test UIDs + Iterator uids = primaryKey.getUserIDs(); + isEquals("Alice ", uids.next()); + isFalse(uids.hasNext()); + } + + private void testEnforcesPrimaryOrSubkeyType(final OpenPGPApi api) + throws PGPException + { + isNotNull(testException( + "Primary key MUST NOT consist of subkey packet.", + "IllegalArgumentException", + new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + api.generateKey().withPrimaryKey( + new KeyPairGeneratorCallback() + { + public PGPKeyPair generateFrom(PGPKeyPairGenerator keyGenCallback) + throws PGPException + { + return keyGenCallback.generateSigningSubkey() + .asSubkey(new BcKeyFingerprintCalculator());// subkey as primary key is illegal + } + }); + } + } + )); + + isNotNull(testException( + "Encryption subkey MUST NOT consist of a primary key packet.", + "IllegalArgumentException", + new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + api.generateKey().withPrimaryKey() + .addEncryptionSubkey( + new BcPGPKeyPairGeneratorProvider() + .get(6, new Date()) + .generateX25519KeyPair(), + null); // primary key as subkey is illegal + } + } + )); + + isNotNull(testException( + "Signing subkey MUST NOT consist of primary key packet.", + "IllegalArgumentException", + new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + api.generateKey().withPrimaryKey() + .addSigningSubkey( + new BcPGPKeyPairGeneratorProvider() + .get(6, new Date()) + .generateEd25519KeyPair(), + null, + null); // primary key as subkey is illegal + } + } + )); + } + + private void testGenerateKeyWithoutSignatures(OpenPGPApi api) + throws PGPException + { + OpenPGPKey key = api.generateKey() + .withPrimaryKey( + KeyPairGeneratorCallback.primaryKey(), + // No direct-key sig + new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) { + return null; + } + }) + .addSigningSubkey( + KeyPairGeneratorCallback.signingKey(), + // No subkey binding sig + new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + return null; + } + }, + // No primary key binding sig + new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + return null; + } + }) + .addEncryptionSubkey( + KeyPairGeneratorCallback.encryptionKey(), + // No subkey binding sig + new SignatureParameters.Callback() + { + @Override + public SignatureParameters apply(SignatureParameters parameters) + { + return null; + } + }) + .build(); + + PGPPublicKeyRing publicKeys = key.getPGPPublicKeyRing(); + Iterator it = publicKeys.getPublicKeys(); + + PGPPublicKey primaryKey = it.next(); + isFalse(primaryKey.getSignatures().hasNext()); + + PGPPublicKey signingSubkey = it.next(); + isFalse(signingSubkey.getSignatures().hasNext()); + + PGPPublicKey encryptionSubkey = it.next(); + isFalse(encryptionSubkey.getSignatures().hasNext()); + } + + public static void main(String[] args) + { + runTest(new OpenPGPV6KeyGeneratorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/RegressionTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/RegressionTest.java new file mode 100644 index 0000000000..76d37d3f1d --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/RegressionTest.java @@ -0,0 +1,30 @@ +package org.bouncycastle.openpgp.api.test; + +import java.security.Security; + +import org.bouncycastle.util.test.SimpleTest; +import org.bouncycastle.util.test.Test; + +public class RegressionTest +{ + public static Test[] tests = { + new ChangeKeyPassphraseTest(), + new DoubleBufferedInputStreamTest(), + new OpenPGPCertificateTest(), + new OpenPGPDetachedSignatureProcessorTest(), + new OpenPGPKeyEditorTest(), + new OpenPGPKeyReaderTest(), + new OpenPGPMessageGeneratorTest(), + new OpenPGPMessageProcessorTest(), + new OpenPGPV4KeyGenerationTest(), + new OpenPGPV6KeyGeneratorTest(), + new StaticV6OpenPGPMessageGeneratorTest(), + }; + + public static void main(String[] args) + { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + + SimpleTest.runTests(tests); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/StackMessagePassphraseCallback.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/StackMessagePassphraseCallback.java new file mode 100644 index 0000000000..6cd042fc1b --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/StackMessagePassphraseCallback.java @@ -0,0 +1,37 @@ +package org.bouncycastle.openpgp.api.test; + +import java.util.Collection; +import java.util.Collections; +import java.util.Stack; + +import org.bouncycastle.openpgp.api.MissingMessagePassphraseCallback; + +/** + * Test implementation of {@link MissingMessagePassphraseCallback} which provides passphrases by popping + * them from a provided {@link Stack}. + */ +public class StackMessagePassphraseCallback + implements MissingMessagePassphraseCallback +{ + private final Stack passphases; + + public StackMessagePassphraseCallback(char[] passphrase) + { + this(Collections.singleton(passphrase)); + } + + public StackMessagePassphraseCallback(Collection passphrases) + { + this.passphases = new Stack(); + this.passphases.addAll(passphrases); + } + + public char[] getMessagePassphrase() + { + if (passphases.isEmpty()) + { + return null; + } + return passphases.pop(); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/api/test/StaticV6OpenPGPMessageGeneratorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/api/test/StaticV6OpenPGPMessageGeneratorTest.java new file mode 100644 index 0000000000..a42709331b --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/api/test/StaticV6OpenPGPMessageGeneratorTest.java @@ -0,0 +1,109 @@ +package org.bouncycastle.openpgp.api.test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.openpgp.OpenPGPTestKeys; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.api.OpenPGPCertificate; +import org.bouncycastle.openpgp.api.OpenPGPKey; +import org.bouncycastle.openpgp.api.OpenPGPKeyReader; +import org.bouncycastle.openpgp.api.OpenPGPMessageGenerator; +import org.bouncycastle.openpgp.api.OpenPGPMessageOutputStream; +import org.bouncycastle.openpgp.api.OpenPGPPolicy; +import org.bouncycastle.openpgp.api.SubkeySelector; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class StaticV6OpenPGPMessageGeneratorTest + extends AbstractPacketTest +{ + private final OpenPGPKeyReader reader = new OpenPGPKeyReader(); + + KeyIdentifier signingKeyIdentifier = new KeyIdentifier( + Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9")); + KeyIdentifier encryptionKeyIdentifier = new KeyIdentifier( + Hex.decode("12C83F1E706F6308FE151A417743A1F033790E93E9978488D1DB378DA9930885")); + + @Override + public String getName() + { + return "StaticV6OpenPGPMessageGeneratorTest"; + } + + @Override + public void performTest() + throws Exception + { + staticEncryptedMessage(); + staticSignedMessage(); + } + + private void staticEncryptedMessage() + throws IOException, PGPException + { + OpenPGPKey key = reader.parseKey(OpenPGPTestKeys.V6_KEY); + + OpenPGPMessageGenerator gen = getStaticGenerator() + .addEncryptionCertificate(key); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream pgOut = (OpenPGPMessageOutputStream) gen.open(bOut); + pgOut.write(Strings.toUTF8ByteArray("Hello, World!\n")); + pgOut.close(); + + System.out.println(bOut); + } + + private void staticSignedMessage() + throws IOException, PGPException + { + OpenPGPKey key = reader.parseKey(OpenPGPTestKeys.V6_KEY); + OpenPGPMessageGenerator gen = getStaticGenerator() + .addSigningKey(key); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OpenPGPMessageOutputStream pgOut = (OpenPGPMessageOutputStream) gen.open(bOut); + pgOut.write(Strings.toUTF8ByteArray("Hello, World!\n")); + pgOut.close(); + + System.out.println(bOut); + } + + /** + * Return a pre-configured {@link OpenPGPMessageGenerator} which has the complex logic of evaluating + * recipient keys to determine suitable subkeys, algorithms etc. swapped out for static configuration + * tailored to the V6 test key. + * + * @return static message generator + */ + public OpenPGPMessageGenerator getStaticGenerator() + { + OpenPGPMessageGenerator gen = new OpenPGPMessageGenerator() + .setSigningKeySelector(new SubkeySelector() + { + public List select( + OpenPGPCertificate certificate, OpenPGPPolicy policy) + { + return Collections.singletonList(certificate.getKey(signingKeyIdentifier)); + } + }) + .setEncryptionKeySelector( + new SubkeySelector() { + public List select(OpenPGPCertificate certificate, OpenPGPPolicy policy) { + return Collections.singletonList(certificate.getKey(encryptionKeyIdentifier)); + } + }); + + return gen; + } + + public static void main(String[] args) + { + runTest(new StaticV6OpenPGPMessageGeneratorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/AEADProtectedPGPSecretKeyTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/AEADProtectedPGPSecretKeyTest.java new file mode 100644 index 0000000000..df48813c75 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/AEADProtectedPGPSecretKeyTest.java @@ -0,0 +1,469 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; +import java.util.Iterator; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; +import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcAEADSecretKeyEncryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyEncryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaAEADSecretKeyEncryptorBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcePBEProtectionRemoverFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; +import org.bouncycastle.util.Strings; +import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder; +import org.bouncycastle.util.encoders.Hex; + +public class AEADProtectedPGPSecretKeyTest + extends AbstractPgpKeyPairTest +{ + + @Override + public String getName() + { + return "AEADProtectedPGPSecretKeyTest"; + } + + @Override + public void performTest() + throws Exception + { + unlockTestVector(); + + generateAndLockUnlockEd25519v4Key(); + generateAndLockUnlockEd25519v6Key(); + + testUnlockKeyWithWrongPassphraseBc(); + testUnlockKeyWithWrongPassphraseJca(); + + reencryptKey(); + } + + private void unlockTestVector() + throws IOException, PGPException + { + // AEAD encrypted test vector extracted from here: + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-locked-v6-secret-key + String armoredVector = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xYIGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laP9JgkC\n" + + "FARdb9ccngltHraRe25uHuyuAQQVtKipJ0+r5jL4dacGWSAheCWPpITYiyfyIOPS\n" + + "3gIDyg8f7strd1OB4+LZsUhcIjOMpVHgmiY/IutJkulneoBYwrEGHxsKAAAAQgWC\n" + + "Y4d/4wMLCQcFFQoOCAwCFgACmwMCHgkiIQbLGGxPBgmml+TVLfpscisMHx4nwYpW\n" + + "cI9lJewnutmsyQUnCQIHAgAAAACtKCAQPi19In7A5tfORHHbNr/JcIMlNpAnFJin\n" + + "7wV2wH+q4UWFs7kDsBJ+xP2i8CMEWi7Ha8tPlXGpZR4UruETeh1mhELIj5UeM8T/\n" + + "0z+5oX1RHu11j8bZzFDLX9eTsgOdWATHggZjh3/jGQAAACCGkySDZ/nlAV25Ivj0\n" + + "gJXdp4SYfy1ZhbEvutFsr15ENf0mCQIUBA5hhGgp2oaavg6mFUXcFMwBBBUuE8qf\n" + + "9Ock+xwusd+GAglBr5LVyr/lup3xxQvHXFSjjA2haXfoN6xUGRdDEHI6+uevKjVR\n" + + "v5oAxgu7eJpaXNjCmwYYGwoAAAAsBYJjh3/jApsMIiEGyxhsTwYJppfk1S36bHIr\n" + + "DB8eJ8GKVnCPZSXsJ7rZrMkAAAAABAEgpukYbZ1ZNfyP5WMUzbUnSGpaUSD5t2Ki\n" + + "Nacp8DkBClZRa2c3AMQzSDXa9jGhYzxjzVb5scHDzTkjyRZWRdTq8U6L4da+/+Kt\n" + + "ruh8m7Xo2ehSSFyWRSuTSZe5tm/KXgYG\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + char[] passphrase = "correct horse battery staple".toCharArray(); + // Plaintext vectors extracted from here: + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-v6-secret-key-transf + byte[] plainPrimaryKey = Hex.decode("1972817b12be707e8d5f586ce61361201d344eb266a2c82fde6835762b65b0b7"); + byte[] plainSubkey = Hex.decode("4d600a4f794d44775c57a26e0feefed558e9afffd6ad0d582d57fb2ba2dcedb8"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armoredVector)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFact = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing keys = (PGPSecretKeyRing) objFact.nextObject(); + + Iterator it = keys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)it.next(); + PGPSecretKey subkey = (PGPSecretKey)it.next(); + + // Test Bouncy Castle KeyDecryptor implementation + BcPBESecretKeyDecryptorBuilder bcDecryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()); + PGPPrivateKey privPrimaryKey = primaryKey.extractPrivateKey(bcDecryptor.build(passphrase)); + isEncodingEqual(plainPrimaryKey, privPrimaryKey.getPrivateKeyDataPacket().getEncoded()); + + // Test Jca/Jce KeyDecryptor implementation + JcePBESecretKeyDecryptorBuilder jceDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(new BouncyCastleProvider()); + PGPPrivateKey privSubKey = subkey.extractPrivateKey(jceDecryptor.build(passphrase)); + isEncodingEqual(plainSubkey, privSubKey.getPrivateKeyDataPacket().getEncoded()); + + // Test Jca/Jce ProtectionRemover implementation + JcePBEProtectionRemoverFactory jceProtectionRemover = new JcePBEProtectionRemoverFactory(passphrase).setProvider(new BouncyCastleProvider()); + PGPPrivateKey privSubKey2 = subkey.extractPrivateKey(jceProtectionRemover.createDecryptor("")); + isEncodingEqual(plainSubkey, privSubKey2.getPrivateKeyDataPacket().getEncoded()); + } + + private void generateAndLockUnlockEd25519v4Key() + throws PGPException + { + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + Date creationTime = currentTimeRounded(); + PGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyPacket.VERSION_4, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + + String passphrase = "a$$word"; + + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_128, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_128, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_128, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_128, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_128, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_128, passphrase, passphrase); + + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_192, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_192, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_192, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_192, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_192, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_192, passphrase, passphrase); + + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + + + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.CAMELLIA_128, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.CAMELLIA_128, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.CAMELLIA_128, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.CAMELLIA_128, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.CAMELLIA_128, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.CAMELLIA_128, passphrase, passphrase); + + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.CAMELLIA_192, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.CAMELLIA_192, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.CAMELLIA_192, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.CAMELLIA_192, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.CAMELLIA_192, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.CAMELLIA_192, passphrase, passphrase); + + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.CAMELLIA_256, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.CAMELLIA_256, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.CAMELLIA_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.CAMELLIA_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.CAMELLIA_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.CAMELLIA_256, passphrase, passphrase); + } + + private void generateAndLockUnlockEd25519v6Key() + throws PGPException + { + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + Date creationTime = currentTimeRounded(); + + String passphrase = "a$$word"; + + PGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyBc(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.EAX, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + lockUnlockKeyJca(keyPair, AEADAlgorithmTags.GCM, SymmetricKeyAlgorithmTags.AES_256, passphrase, passphrase); + + } + + private void testUnlockKeyWithWrongPassphraseBc() + throws PGPException + { + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + Date creationTime = currentTimeRounded(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + PGPKeyPair keyPair = new BcPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + + BcAEADSecretKeyEncryptorBuilder bcEncBuilder = new BcAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, + S2K.Argon2Params.memoryConstrainedParameters()); + + PGPDigestCalculatorProvider digestProv = new BcPGPDigestCalculatorProvider(); + + PGPSecretKey sk = new PGPSecretKey( + keyPair.getPrivateKey(), + keyPair.getPublicKey(), + digestProv.get(HashAlgorithmTags.SHA1), + true, + bcEncBuilder.build( + "passphrase".toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket())); + + BcPBESecretKeyDecryptorBuilder bcDecBuilder = new BcPBESecretKeyDecryptorBuilder(digestProv); + try + { + sk.extractPrivateKey(bcDecBuilder.build("password".toCharArray())); + fail("Expected PGPException due to mismatched passphrase"); + } + catch (PGPException e) + { + // expected + } + } + } + + private void testUnlockKeyWithWrongPassphraseJca() + throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException + { + BouncyCastleProvider prov = new BouncyCastleProvider(); + KeyPairGenerator eddsaGen = KeyPairGenerator.getInstance("EdDSA", prov); + + eddsaGen.initialize(new ECNamedCurveGenParameterSpec("ed25519")); + KeyPair kp = eddsaGen.generateKeyPair(); + Date creationTime = currentTimeRounded(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + PGPKeyPair keyPair = new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + + JcaAEADSecretKeyEncryptorBuilder jcaEncBuilder = new JcaAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, + S2K.Argon2Params.memoryConstrainedParameters()) + .setProvider(prov); + + PGPDigestCalculatorProvider digestProv = new JcaPGPDigestCalculatorProviderBuilder() + .setProvider(prov) + .build(); + + PGPSecretKey sk = new PGPSecretKey( + keyPair.getPrivateKey(), + keyPair.getPublicKey(), + digestProv.get(HashAlgorithmTags.SHA1), + true, + jcaEncBuilder.build( + "Yin".toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket())); + + JcePBESecretKeyDecryptorBuilder jceDecBuilder = new JcePBESecretKeyDecryptorBuilder(digestProv).setProvider(prov); + try + { + sk.extractPrivateKey(jceDecBuilder.build("Yang".toCharArray())); + fail("Expected PGPException due to wrong passphrase"); + } + catch (PGPException e) + { + // expected + } + } + } + + private void lockUnlockKeyBc( + PGPKeyPair keyPair, + int aeadAlgorithm, + int encAlgorithm, + String encryptionPassphrase, + String decryptionPassphrase) + throws PGPException + { + BcAEADSecretKeyEncryptorBuilder bcEncBuilder = new BcAEADSecretKeyEncryptorBuilder( + aeadAlgorithm, encAlgorithm, + S2K.Argon2Params.memoryConstrainedParameters()); + + PGPDigestCalculatorProvider digestProv = new BcPGPDigestCalculatorProvider(); + + PGPSecretKey sk = new PGPSecretKey( + keyPair.getPrivateKey(), + keyPair.getPublicKey(), + digestProv.get(HashAlgorithmTags.SHA1), + true, + bcEncBuilder.build( + encryptionPassphrase.toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket())); + + isEquals("S2KUsage mismatch", SecretKeyPacket.USAGE_AEAD, sk.getS2KUsage()); + isEquals("S2K type mismatch", S2K.ARGON_2, sk.getS2K().getType()); + isEquals("Argon2 passes parameter mismatch", 3, sk.getS2K().getPasses()); + isEquals("Argon2 parallelism parameter mismatch", 4, sk.getS2K().getParallelism()); + isEquals("Argon2 memory exponent parameter mismatch", 16, sk.getS2K().getMemorySizeExponent()); + isEquals("Symmetric key encryption algorithm mismatch", encAlgorithm, sk.getKeyEncryptionAlgorithm()); + isEquals("AEAD key encryption algorithm mismatch", aeadAlgorithm, sk.getAEADKeyEncryptionAlgorithm()); + + BcPBESecretKeyDecryptorBuilder bcDecBuilder = new BcPBESecretKeyDecryptorBuilder(digestProv); + PGPPrivateKey dec = sk.extractPrivateKey(bcDecBuilder.build(decryptionPassphrase.toCharArray())); + isEncodingEqual("Decrypted key encoding mismatch", + keyPair.getPrivateKey().getPrivateKeyDataPacket().getEncoded(), dec.getPrivateKeyDataPacket().getEncoded()); + } + + private void lockUnlockKeyJca( + PGPKeyPair keyPair, + int aeadAlgorithm, + int encAlgorithm, + String encryptionPassphrase, + String decryptionPassphrase) + throws PGPException + { + BouncyCastleProvider prov = new BouncyCastleProvider(); + JcaAEADSecretKeyEncryptorBuilder jcaEncBuilder = new JcaAEADSecretKeyEncryptorBuilder( + aeadAlgorithm, encAlgorithm, + S2K.Argon2Params.memoryConstrainedParameters()) + .setProvider(prov); + + PGPDigestCalculatorProvider digestProv = new JcaPGPDigestCalculatorProviderBuilder() + .setProvider(prov) + .build(); + + PGPSecretKey sk = new PGPSecretKey( + keyPair.getPrivateKey(), + keyPair.getPublicKey(), + digestProv.get(HashAlgorithmTags.SHA1), + true, + jcaEncBuilder.build( + encryptionPassphrase.toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket())); + + isEquals("S2KUsage mismatch", SecretKeyPacket.USAGE_AEAD, sk.getS2KUsage()); + isEquals("S2K type mismatch", S2K.ARGON_2, sk.getS2K().getType()); + isEquals("Argon2 passes parameter mismatch", 3, sk.getS2K().getPasses()); + isEquals("Argon2 parallelism parameter mismatch", 4, sk.getS2K().getParallelism()); + isEquals("Argon2 memory exponent parameter mismatch", 16, sk.getS2K().getMemorySizeExponent()); + isEquals("Symmetric key encryption algorithm mismatch", encAlgorithm, sk.getKeyEncryptionAlgorithm()); + isEquals("AEAD algorithm mismatch", aeadAlgorithm, sk.getAEADKeyEncryptionAlgorithm()); + + JcePBESecretKeyDecryptorBuilder jceDecBuilder = new JcePBESecretKeyDecryptorBuilder(digestProv).setProvider(prov); + PGPPrivateKey dec = sk.extractPrivateKey(jceDecBuilder.build(decryptionPassphrase.toCharArray())); + isEncodingEqual("Decrypted key encoding mismatch", + keyPair.getPrivateKey().getPrivateKeyDataPacket().getEncoded(), dec.getPrivateKeyDataPacket().getEncoded()); + } + + private void reencryptKey() + throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException + { + reencryptKeyBc(); + reencryptKeyJca(); + } + + private void reencryptKeyJca() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + BouncyCastleProvider prov = new BouncyCastleProvider(); + KeyPairGenerator eddsaGen = KeyPairGenerator.getInstance("EdDSA", prov); + + eddsaGen.initialize(new ECNamedCurveGenParameterSpec("ed25519")); + KeyPair kp = eddsaGen.generateKeyPair(); + Date creationTime = currentTimeRounded(); + String passphrase = "recycle"; + + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + PBESecretKeyEncryptor cfbEncBuilder = new JcePBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_128) + .setProvider(prov) + .setSecureRandom(CryptoServicesRegistrar.getSecureRandom()) + .build(passphrase.toCharArray()); + PGPDigestCalculatorProvider digestProv = new JcaPGPDigestCalculatorProviderBuilder() + .setProvider(prov) + .build(); + + // Encrypt key using CFB mode + PGPSecretKey cfbEncKey = new PGPSecretKey( + keyPair.getPrivateKey(), + keyPair.getPublicKey(), + digestProv.get(HashAlgorithmTags.SHA1), + true, + cfbEncBuilder); + + PBESecretKeyDecryptor cfbDecryptor = new JcePBESecretKeyDecryptorBuilder(digestProv) + .setProvider(prov) + .build(passphrase.toCharArray()); + + JcaAEADSecretKeyEncryptorBuilder aeadEncBuilder = new JcaAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_128, S2K.Argon2Params.memoryConstrainedParameters()) + .setProvider(prov); + + PGPSecretKey aeadEncKey = PGPSecretKey.copyWithNewPassword( + cfbEncKey, + cfbDecryptor, + aeadEncBuilder.build(passphrase.toCharArray(), cfbEncKey.getPublicKey().getPublicKeyPacket())); + PBESecretKeyDecryptor aeadDecryptor = new JcePBESecretKeyDecryptorBuilder(digestProv) + .setProvider(prov) + .build(passphrase.toCharArray()); + isNotNull(aeadEncKey.extractPrivateKey(aeadDecryptor)); + } + + private void reencryptKeyBc() + throws PGPException + { + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + Date creationTime = currentTimeRounded(); + String passphrase = "recycle"; + PGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + + PBESecretKeyEncryptor cfbEncBuilder = new BcPBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_128) + .build(passphrase.toCharArray()); + PGPDigestCalculatorProvider digestProv = new BcPGPDigestCalculatorProvider(); + + // Encrypt key using CFB mode + PGPSecretKey cfbEncKey = new PGPSecretKey( + keyPair.getPrivateKey(), + keyPair.getPublicKey(), + digestProv.get(HashAlgorithmTags.SHA1), + true, + cfbEncBuilder); + + PBESecretKeyDecryptor cfbDecryptor = new BcPBESecretKeyDecryptorBuilder(digestProv) + .build(passphrase.toCharArray()); + + BcAEADSecretKeyEncryptorBuilder aeadEncBuilder = new BcAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_128, + S2K.Argon2Params.memoryConstrainedParameters()); + + // Reencrypt key using AEAD + PGPSecretKey aeadEncKey = PGPSecretKey.copyWithNewPassword( + cfbEncKey, + cfbDecryptor, + aeadEncBuilder.build( + passphrase.toCharArray(), + cfbEncKey.getPublicKey().getPublicKeyPacket())); + + PBESecretKeyDecryptor aeadDecryptor = new BcPBESecretKeyDecryptorBuilder(digestProv) + .build(passphrase.toCharArray()); + isNotNull(aeadEncKey.extractPrivateKey(aeadDecryptor)); + } + + public static void main(String[] args) + { + runTest(new AEADProtectedPGPSecretKeyTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/AEADWithArgon2Test.java b/pg/src/test/java/org/bouncycastle/openpgp/test/AEADWithArgon2Test.java new file mode 100644 index 0000000000..f26f56884f --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/AEADWithArgon2Test.java @@ -0,0 +1,28 @@ +package org.bouncycastle.openpgp.test; + +import java.security.Security; + +import junit.framework.TestCase; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.test.SimpleTestResult; + +public class AEADWithArgon2Test + extends TestCase +{ + public void testAEADProtectedPGPSecretKey() + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + + AEADProtectedPGPSecretKeyTest test = new AEADProtectedPGPSecretKeyTest(); + + SimpleTestResult result = (SimpleTestResult)test.perform(); + + if (!result.isSuccessful()) + { + fail(test.getClass().getName() + " " + result.toString()); + } + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/AbstractPgpKeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/AbstractPgpKeyPairTest.java new file mode 100644 index 0000000000..80a785202b --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/AbstractPgpKeyPairTest.java @@ -0,0 +1,64 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyConverter; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; + +import java.security.KeyPair; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +public abstract class AbstractPgpKeyPairTest + extends AbstractPacketTest +{ + + public static Date parseUTCTimestamp(String timestamp) + { + // Not thread safe, so we use a local variable + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + try + { + return dateFormat.parse(timestamp); + } + catch (ParseException e) + { + throw new RuntimeException(e); + } + } + + public Date currentTimeRounded() + { + Date now = new Date(); + return new Date((now.getTime() / 1000) * 1000); // rounded to seconds + } + + public BcPGPKeyPair toBcKeyPair(JcaPGPKeyPair keyPair) + throws PGPException + { + BcPGPKeyConverter c = new BcPGPKeyConverter(); + return new BcPGPKeyPair(keyPair.getPublicKey().getVersion(), keyPair.getPublicKey().getAlgorithm(), + new AsymmetricCipherKeyPair( + c.getPublicKey(keyPair.getPublicKey()), + c.getPrivateKey(keyPair.getPrivateKey())), + keyPair.getPublicKey().getCreationTime()); + } + + public JcaPGPKeyPair toJcaKeyPair(BcPGPKeyPair keyPair) + throws PGPException + { + JcaPGPKeyConverter c = new JcaPGPKeyConverter().setProvider(new BouncyCastleProvider()); + return new JcaPGPKeyPair(keyPair.getPublicKey().getVersion(), keyPair.getPublicKey().getAlgorithm(), + new KeyPair( + c.getPublicKey(keyPair.getPublicKey()), + c.getPrivateKey(keyPair.getPrivateKey())), + keyPair.getPublicKey().getCreationTime()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/AllTests.java b/pg/src/test/java/org/bouncycastle/openpgp/test/AllTests.java index cff68dd70f..454f1a047b 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/AllTests.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/AllTests.java @@ -42,6 +42,8 @@ public static Test suite() suite.addTestSuite(AllTests.class); suite.addTestSuite(DSA2Test.class); suite.addTestSuite(PGPUnicodeTest.class); + suite.addTestSuite(AEADWithArgon2Test.class); + suite.addTestSuite(Argon2Test.class); return new BCTestSetup(suite); } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2S2KTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2S2KTest.java index 4062aa5266..80a4642573 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2S2KTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2S2KTest.java @@ -7,17 +7,12 @@ import java.io.OutputStream; import java.security.SecureRandom; import java.util.Date; -import java.util.Iterator; import org.bouncycastle.bcpg.ArmoredInputStream; import org.bouncycastle.bcpg.ArmoredOutputStream; -import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.bcpg.BCPGOutputStream; -import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.S2K; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; -import org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket; -import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedDataList; import org.bouncycastle.openpgp.PGPException; @@ -42,7 +37,7 @@ public class Argon2S2KTest static final String TEST_MSG_PASSWORD = "password"; - // Test message from the crypto-refresh-05 document + // https://www.rfc-editor.org/rfc/rfc9580.html#name-v4-skesk-using-argon2-with- static final String TEST_MSG_AES128 = "-----BEGIN PGP MESSAGE-----\n" + "Comment: Encrypted using AES with 128-bit key\n" + "Comment: Session key: 01FE16BBACFD1E7B78EF3B865187374F\n" + @@ -53,7 +48,7 @@ public class Argon2S2KTest "=uIks\n" + "-----END PGP MESSAGE-----"; - // Test message from the crypto-refresh-05 document + // https://www.rfc-editor.org/rfc/rfc9580.html#name-v4-skesk-using-argon2-with-a private static final String TEST_MSG_AES192 = "-----BEGIN PGP MESSAGE-----\n" + "Comment: Encrypted using AES with 192-bit key\n" + "Comment: Session key: 27006DAE68E509022CE45A14E569E91001C2955AF8DFE194\n" + @@ -64,16 +59,16 @@ public class Argon2S2KTest "=n8Ma\n" + "-----END PGP MESSAGE-----"; - // Test message from the crypto-refresh-05 document + // https://www.rfc-editor.org/rfc/rfc9580.html#name-v4-skesk-using-argon2-with-ae private static final String TEST_MSG_AES256 = "-----BEGIN PGP MESSAGE-----\n" + - "Comment: Encrypted using AES with 192-bit key\n" + - "Comment: Session key: 27006DAE68E509022CE45A14E569E91001C2955AF8DFE194\n" + - "\n" + - "wy8ECAThTKxHFTRZGKli3KNH4UP4AQQVhzLJ2va3FG8/pmpIPd/H/mdoVS5VBLLw\n" + - "F9I+AdJ1Sw56PRYiKZjCvHg+2bnq02s33AJJoyBexBI4QKATFRkyez2gldJldRys\n" + - "LVg77Mwwfgl2n/d572WciAM=\n" + - "=n8Ma\n" + - "-----END PGP MESSAGE-----"; + "Comment: Encrypted using AES with 256-bit key\n" + + "Comment: Session key: BBEDA55B9AAE63DAC45D4F49D89DACF4AF37FEF...\n" + + "Comment: Session key: ...C13BAB2F1F8E18FB74580D8B0\n" + + "\n" + + "wzcECQS4eJUgIG/3mcaILEJFpmJ8AQQVnZ9l7KtagdClm9UaQ/Z6M/5roklSGpGu\n" + + "623YmaXezGj80j4B+Ku1sgTdJo87X1Wrup7l0wJypZls21Uwd67m9koF60eefH/K\n" + + "95D1usliXOEm8ayQJQmZrjf6K6v9PWwqMQ==\n" + + "-----END PGP MESSAGE-----"; static final String TEST_MSG_PLAIN = "Hello, world!"; diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2Test.java b/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2Test.java new file mode 100644 index 0000000000..de62c8c606 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/Argon2Test.java @@ -0,0 +1,28 @@ +package org.bouncycastle.openpgp.test; + +import java.security.Security; + +import junit.framework.TestCase; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.test.SimpleTestResult; + +public class Argon2Test + extends TestCase +{ + public void testArgon2() + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + + Argon2S2KTest test = new Argon2S2KTest(); + + SimpleTestResult result = (SimpleTestResult)test.perform(); + + if (!result.isSuccessful()) + { + fail(test.getClass().getName() + " " + result.toString()); + } + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/ArmorCRCTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/ArmorCRCTest.java index a2aca2ad3c..7aa5e7fafb 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/ArmorCRCTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/ArmorCRCTest.java @@ -19,17 +19,17 @@ public class ArmorCRCTest extends SimpleTest { - + private static final String NL = Strings.lineSeparator(); private static final String WITHOUT_CRC = "" + - "-----BEGIN PGP MESSAGE-----\n" + - "\n" + - "yxR0AAAAAABIZWxsbywgV29ybGQhCg==\n" + - "-----END PGP MESSAGE-----\n"; + "-----BEGIN PGP MESSAGE-----" + NL + + NL + + "yxR0AAAAAABIZWxsbywgV29ybGQhCg==" + NL + + "-----END PGP MESSAGE-----" + NL; private static final String FAULTY_CRC = "" + - "-----BEGIN PGP MESSAGE-----\n" + - "\n" + - "yxR0AAAAAABIZWxsbywgV29ybGQhCg==\n" + - "=TRA9\n" + + "-----BEGIN PGP MESSAGE-----" + NL + + NL + + "yxR0AAAAAABIZWxsbywgV29ybGQhCg==" + NL + + "=TRA9" + NL + "-----END PGP MESSAGE-----"; @Override diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/ArmoredInputStreamTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/ArmoredInputStreamTest.java index 8e575bb6c9..60836c11e7 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/ArmoredInputStreamTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/ArmoredInputStreamTest.java @@ -5,8 +5,11 @@ import java.security.Security; import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPSignatureList; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; @@ -39,22 +42,22 @@ public class ArmoredInputStreamTest "bc2af032d2a59e36be6467bc23456b4ac178d36cf9f45df5e833a1981ed1a1032679ea0a"); private static final String badHeaderData1 = - "-----BEGIN PGP MESSAGE-----\n" - + "Version: BCPG v1.32\n" - + "Comment: A dummy message\n" - + "Comment actually not really as there is no colon" - + " \t \t\n" - + "SGVsbG8gV29ybGQh\n" - + "=d9Xi\n" - + "-----END PGP MESSAGE-----\n"; + "-----BEGIN PGP MESSAGE-----\n" + + "Version: BCPG v1.32\n" + + "Comment: A dummy message\n" + + "Comment actually not really as there is no colon" + + " \t \t\n" + + "SGVsbG8gV29ybGQh\n" + + "=d9Xi\n" + + "-----END PGP MESSAGE-----\n"; private static final String badHeaderData2 = - "-----BEGIN PGP MESSAGE-----\n" - + "Comment actually not really as there is no colon" - + " \t \t\n" - + "SGVsbG8gV29ybGQh\n" - + "=d9Xi\n" - + "-----END PGP MESSAGE-----\n"; + "-----BEGIN PGP MESSAGE-----\n" + + "Comment actually not really as there is no colon" + + " \t \t\n" + + "SGVsbG8gV29ybGQh\n" + + "=d9Xi\n" + + "-----END PGP MESSAGE-----\n"; public String getName() { @@ -63,12 +66,18 @@ public String getName() public void performTest() throws Exception + { + bogusHeadersTest(); + unknownClearsignedMessageHeadersTest(); + } + + private void bogusHeadersTest() { try { PGPObjectFactory pgpObjectFactoryOfTestFile = new PGPObjectFactory( new ArmoredInputStream(new ByteArrayInputStream(Arrays.concatenate(Strings.toByteArray("-----BEGIN PGP MESSAGE-----\n" - + "Version: BCPG v1.32\n\n"), bogusData))), new JcaKeyFingerprintCalculator()); + + "Version: BCPG v1.32\n\n"), bogusData))), new JcaKeyFingerprintCalculator()); pgpObjectFactoryOfTestFile.nextObject(); // <-- EXCEPTION HERE fail("no exception"); } @@ -100,6 +109,90 @@ public void performTest() } } + private void unknownClearsignedMessageHeadersTest() + throws IOException + { + // https://sequoia-pgp.gitlab.io/openpgp-interoperability-test-suite/results.html#Mangled_message_using_the_Cleartext_Signature_Framework_ + String armor = "-----BEGIN PGP SIGNED MESSAGE-----\n" + + "Hello: this is totally part of the signed text\n" + + "Hash: SHA512\n" + + "\n" + + "- From the grocery store we need:\n" + + "\n" + + "- - tofu\n" + + "- - vegetables\n" + + "- - noodles\n" + + "\n" + + "\n" + + "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wsE7BAEBCgBvBYJoMZ08CRD7/MgqAV5zMEcUAAAAAAAeACBzYWx0QG5vdGF0aW9u\n" + + "cy5zZXF1b2lhLXBncC5vcmeO1uFIMk5ydOB8SNGi9ZkD0sHEoFRZM20v669ghBur\n" + + "KBYhBNGmbhojsYLJmA94jPv8yCoBXnMwAACffQwArOoXVWEF/Yii182hZPqE6t/E\n" + + "ZEyJcZLwsJXQ00ctno0TjXY9iDS0l1i0cWVIIcgkoutd+Gn8XI30EQEJivAs8uvE\n" + + "yCDFRQgkag2kOn+QtawyQ3LO+Xd5oZDbcy9Jvf4sG5YobBs7kfTb2NQgXDViM+k3\n" + + "69je5Mj+oKhtckM3BROYxq+B8DPgPT9UJuz0UgFQVYm5Mjj9jnFlUbMVl7UnsZwP\n" + + "0RNnbW8jtuQn7ehePzAOB94bzkvJL8/obPw2LsDfC0gWTovpJo0JibPZD/zaTA4y\n" + + "7yLnRvEM+8PilR6eIY40Us9oJerpjYsA16WMyIEvRfgHrYITpqHEzpJa7/vnMF2g\n" + + "t2PjcdtFeBsmJZrLwaJWB5Tku6wMsVL8Rmit8qecnVg9qYL3FrRUweEGo/dAH49M\n" + + "udZeck+sMaXdIhJnwy4HnH0tUiEGnHQ5mnBtTvKFR98paDVIW/xS+o95hUfmAXA8\n" + + "rmMglLYQkIXAZayAquW+VrxSxglNqXYxZNIxuHT6\n" + + "=yj77\n" + + "-----END PGP SIGNATURE-----"; + + // Test validation is not enabled by default + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armor)); + ArmoredInputStream aIn = ArmoredInputStream.builder() + .build(bIn); + // Skip over cleartext + isTrue(aIn.isClearText()); + while (aIn.isClearText()) + { + aIn.read(); + } + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSignatureList sigs = (PGPSignatureList)objFac.nextObject(); + isTrue(sigs != null); + + + // Test validation enabled + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armor)); + final ByteArrayInputStream finalBIn = bIn; + isTrue(null != testException( + "Illegal ASCII armor header line in clearsigned message encountered: Hello: this is totally part of the signed text", + "ArmoredInputException", + new TestExceptionOperation() + { + public void operation() + throws Exception + { + ArmoredInputStream.builder() + .setValidateClearsignedMessageHeaders(true) + .build(finalBIn); + } + }) + ); + + + // Test validation enabled, but custom header allowed + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armor)); + aIn = ArmoredInputStream.builder() + .setValidateClearsignedMessageHeaders(true) + .addAllowedArmorHeader("Hello") + .build(bIn); + // Skip over cleartext + isTrue(aIn.isClearText()); + while (aIn.isClearText()) + { + aIn.read(); + } + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + sigs = (PGPSignatureList)objFac.nextObject(); + isTrue(sigs != null); + } + public static void main( String[] args) { diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/BcImplProviderTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/BcImplProviderTest.java index faaf2615c8..96851850b5 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/BcImplProviderTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/BcImplProviderTest.java @@ -142,6 +142,28 @@ public void operation() }); //createSigner + testCreateSigner(PublicKeyAlgorithmTags.EDDSA_LEGACY, new EdDsaSigner(new Ed448Signer(new byte[0]), new SHA1Digest()), "EdDSA", + new PrivateKeyOperation() + { + @Override + public BCPGKey getPrivateBCPGKey(PGPPublicKey pub, PrivateKey privKey) + throws IOException + { + PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(privKey.getEncoded()); + return new EdSecretBCPGKey( + new BigInteger(1, ASN1OctetString.getInstance(pInfo.parsePrivateKey()).getOctets())); + } + }, + new KeyPairGeneratorOperation() + { + @Override + public void initialize(KeyPairGenerator kpGen) + throws InvalidAlgorithmParameterException + { + kpGen.initialize(new ECNamedCurveGenParameterSpec("Ed448")); + } + }); + testCreateSigner(PublicKeyAlgorithmTags.DSA, new DSADigestSigner(new DSASigner(), new SHA1Digest()), "DSA", new PrivateKeyOperation() { @@ -317,6 +339,7 @@ public void initialize(KeyPairGenerator kpGen) kpGen.initialize(new ECNamedCurveGenParameterSpec("Ed25519")); } }); + testCreateSigner(PublicKeyAlgorithmTags.Ed448, new EdDsaSigner(new Ed448Signer(new byte[0]), new SHA1Digest()), "EdDSA", new PrivateKeyOperation() { diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/BcPGPRSATest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/BcPGPRSATest.java index fc82ffc7d7..8e29485b14 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/BcPGPRSATest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/BcPGPRSATest.java @@ -405,7 +405,12 @@ private void fingerPrintTest() PGPPublicKey pubKey = pgpPub.getPublicKey(); - if (!areEqual(pubKey.getFingerprint(), Hex.decode("4FFB9F0884266C715D1CEAC804A3BBFA"))) + byte[] expectedVersion3 = Hex.decode("4FFB9F0884266C715D1CEAC804A3BBFA"); + if (!areEqual(pubKey.getFingerprint(), expectedVersion3)) + { + fail("version 3 fingerprint test failed"); + } + if (!pubKey.hasFingerprint(expectedVersion3)) { fail("version 3 fingerprint test failed"); } @@ -417,7 +422,12 @@ private void fingerPrintTest() pubKey = pgpPub.getPublicKey(); - if (!areEqual(pubKey.getFingerprint(), Hex.decode("3062363c1046a01a751946bb35586146fdf3f373"))) + byte[] expectedVersion4 = Hex.decode("3062363c1046a01a751946bb35586146fdf3f373"); + if (!areEqual(pubKey.getFingerprint(), expectedVersion4)) + { + fail("version 4 fingerprint test failed"); + } + if (!pubKey.hasFingerprint(expectedVersion4)) { fail("version 4 fingerprint test failed"); } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/BcpgGeneralTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/BcpgGeneralTest.java index de5fd8bb1f..5c615aa07a 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/BcpgGeneralTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/BcpgGeneralTest.java @@ -2,10 +2,14 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.security.SecureRandom; import java.security.Security; +import java.util.Calendar; import java.util.Date; import java.util.Iterator; +import java.util.TimeZone; import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.ArmoredInputStream; @@ -25,18 +29,35 @@ import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPObjectFactory; import org.bouncycastle.openpgp.PGPPBEEncryptedData; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Pack; import org.bouncycastle.util.Strings; import org.bouncycastle.util.test.SimpleTest; public class BcpgGeneralTest extends SimpleTest { + /* + * Format: Binary data + Filename: "hello.txt" + Timestamp: 2104-06-26 14:42:55 UTC + Content: "Hello, world!\n" + * */ + byte[] message = Strings.toUTF8ByteArray("-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "yx1iCWhlbGxvLnR4dPz1TW9IZWxsbywgd29ybGQhCg==\n" + + "=3swl\n" + + "-----END PGP MESSAGE-----"); + + + public static void main(String[] args) { Security.addProvider(new BouncyCastleProvider()); @@ -54,6 +75,8 @@ public String getName() public void performTest() throws Exception { + testReadTime(); + testReadTime2(); //testS2K(); testExceptions(); testECDHPublicBCPGKey(); @@ -61,6 +84,60 @@ public void performTest() testPreferredAEADCiphersuites(); } + static int read4OctetLength(InputStream in) + throws IOException + { + return (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); + } + + // StreamUtil.readTime + static long readTime(BCPGInputStream in) + throws IOException + { + return ((long)read4OctetLength(in) & 0xFFFFFFFFL) * 1000L; + } + + public void testReadTime() + throws IOException + { + Calendar calendar = Calendar.getInstance(); + calendar.set(2074, Calendar.JANUARY, 1, 0, 0, 0); + calendar.set(Calendar.MILLISECOND, 0); + + Date tmp = calendar.getTime(); + long time = tmp.getTime() / 1000L * 1000L; + byte[] date = Pack.intToBigEndian((int)(time / 1000L)); + + ByteArrayInputStream bs = new ByteArrayInputStream(date); + BCPGInputStream stream = new BCPGInputStream(bs); + long rlt = readTime(stream); + isTrue(rlt == time); + + time = Long.MAX_VALUE / 1000L * 1000L; + date = Pack.intToBigEndian((int)(time / 1000L)); + bs = new ByteArrayInputStream(date); + stream = new BCPGInputStream(bs); + rlt = readTime(stream); + byte[] date2 = Pack.intToBigEndian((int)(rlt / 1000L)); + isTrue(Arrays.areEqual(date, date2)); + } + + public void testReadTime2() + throws Exception + { + PGPObjectFactory pgpObjectFactoryOfTestFile = new PGPObjectFactory( + new ArmoredInputStream(new ByteArrayInputStream(message)), new JcaKeyFingerprintCalculator()); + PGPLiteralData ld = (PGPLiteralData)pgpObjectFactoryOfTestFile.nextObject(); + Date date = ld.getModificationTime(); + + Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendar.set(2104, Calendar.JUNE, 26, 14, 42, 55); + calendar.set(Calendar.MILLISECOND, 0); + Date expected = calendar.getTime(); + + isTrue(date.equals(expected)); + } + public void testPreferredAEADCiphersuites() throws Exception { diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/CRC24Test.java b/pg/src/test/java/org/bouncycastle/openpgp/test/CRC24Test.java index fcafb8eca9..bb70aa8140 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/CRC24Test.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/CRC24Test.java @@ -85,8 +85,6 @@ public void performanceTest() fastImpl.update(0); fastImpl.reset(); - long start = System.currentTimeMillis(); - for (int j = 0; j < 100; ++j) { for (int i = 0; i != LARGE_RANDOM.length; i += 3) @@ -95,7 +93,6 @@ public void performanceTest() } } int defVal = defaultImpl.getValue(); - long afterDefault = System.currentTimeMillis(); for (int j = 0; j < 100; ++j) { @@ -105,14 +102,7 @@ public void performanceTest() } } int fastVal = fastImpl.getValue(); - long afterFast = System.currentTimeMillis(); isEquals("Calculated value of default and fast CRC-24 implementations diverges", defVal, fastVal); - long defDuration = afterDefault - start; - System.out.println("Default Implementation: " + defDuration / 1000 + "s" + defDuration % 1000); - - long fastDuration = afterFast - afterDefault; - System.out.println("Fast Implementation: " + fastDuration / 1000 + "s" + fastDuration % 1000); - } } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/Curve25519PrivateKeyEncodingTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/Curve25519PrivateKeyEncodingTest.java new file mode 100644 index 0000000000..ec41ff9cdd --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/Curve25519PrivateKeyEncodingTest.java @@ -0,0 +1,196 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.bcpg.*; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; +import org.bouncycastle.jcajce.spec.XDHParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.*; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyConverter; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.Arrays; + +import java.io.IOException; +import java.security.*; +import java.util.Date; + +/** + * Curve25519Legacy ECDH Secret Key Material uses big-endian MPI form, + * while X25519 keys use little-endian native encoding. + * This test verifies that legacy X25519 keys using ECDH are reverse-encoded, + * while X25519 keys are natively encoded. + */ +public class Curve25519PrivateKeyEncodingTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "Curve25519PrivateKeyEncodingTest"; + } + + @Override + public void performTest() + throws Exception + { + containsTest(); + verifySecretKeyReverseEncoding(); + } + + private void verifySecretKeyReverseEncoding() + throws PGPException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException + { + bc_verifySecretKeyReverseEncoding(); + jca_verifySecretKeyReverseEncoding(); + } + + /** + * Verify that legacy ECDH keys over curve25519 encode the private key in reversed encoding, + * while dedicated X25519 keys use native encoding for the private key material. + * Test the JcaJce implementation. + * + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws PGPException + * @throws IOException + */ + private void jca_verifySecretKeyReverseEncoding() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException, IOException + { + JcaPGPKeyConverter c = new JcaPGPKeyConverter(); + + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + + byte[] rawPrivateKey = jcaNativePrivateKey(kp.getPrivate()); + + // Legacy key uses reversed encoding + PGPKeyPair pgpECDHKeyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + byte[] encodedECDHPrivateKey = pgpECDHKeyPair.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("ECDH Curve25519Legacy (X25519) key MUST encode secret key in 'reverse' (big-endian MPI encoding) (JCE implementation)", + containsSubsequence(encodedECDHPrivateKey, Arrays.reverse(rawPrivateKey))); + + byte[] decodedECDHPrivateKey = jcaNativePrivateKey(c.getPrivateKey(pgpECDHKeyPair.getPrivateKey())); + isEncodingEqual("Decoded ECDH Curve25519Legacy (X25519) key MUST match original raw key (JCE implementation)", + decodedECDHPrivateKey, rawPrivateKey); + + // X25519 key uses native encoding + PGPKeyPair pgpX25519KeyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.X25519, kp, date); + byte[] encodedX25519PrivateKey = pgpX25519KeyPair.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("X25519 key MUST use native encoding (little-endian) to encode the secret key material (JCE implementation)", + containsSubsequence(encodedX25519PrivateKey, rawPrivateKey)); + + byte[] decodedX25519PrivateKey = jcaNativePrivateKey(c.getPrivateKey(pgpX25519KeyPair.getPrivateKey())); + isEncodingEqual("Decoded X25519 key MUST match original raw key (JCE implementation)", + rawPrivateKey, decodedX25519PrivateKey); + } + + /** + * Return the native encoding of the given private key. + * @param privateKey private key + * @return native encoding + * @throws IOException + */ + private byte[] jcaNativePrivateKey(PrivateKey privateKey) + throws IOException + { + PrivateKeyInfo kInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded()); + return ASN1OctetString.getInstance(kInfo.parsePrivateKey()).getOctets(); + } + + /** + * Verify that legacy ECDH keys over curve25519 encode the private key in reversed encoding, + * while dedicated X25519 keys use native encoding for the private key material. + * Test the BC implementation. + */ + private void bc_verifySecretKeyReverseEncoding() + throws PGPException + { + BcPGPKeyConverter c = new BcPGPKeyConverter(); + + Date date = currentTimeRounded(); + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + byte[] rawPrivateKey = ((X25519PrivateKeyParameters) kp.getPrivate()).getEncoded(); + + // Legacy key uses reversed encoding + PGPKeyPair pgpECDHKeyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + byte[] encodedECDHPrivateKey = pgpECDHKeyPair.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("ECDH Curve25519Legacy (X25519) key MUST encode secret key in 'reverse' (big-endian MPI encoding) (BC implementation)", + containsSubsequence(encodedECDHPrivateKey, Arrays.reverse(rawPrivateKey))); + + byte[] decodedECDHPrivateKey = ((X25519PrivateKeyParameters) c.getPrivateKey(pgpECDHKeyPair.getPrivateKey())).getEncoded(); + isEncodingEqual("Decoded ECDH Curve25519Legacy (X25519) key MUST match original raw key (BC implementation)", + decodedECDHPrivateKey, rawPrivateKey); + + // X25519 key uses native encoding + PGPKeyPair pgpX25519KeyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.X25519, kp, date); + byte[] encodedX25519PrivateKey = pgpX25519KeyPair.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("X25519 key MUST use native encoding (little-endian) to encode the secret key material (BC implementation)", + containsSubsequence(encodedX25519PrivateKey, rawPrivateKey)); + + byte[] decodedX25519PrivateKey = ((X25519PrivateKeyParameters) c.getPrivateKey(pgpX25519KeyPair.getPrivateKey())).getEncoded(); + isEncodingEqual("Decoded X25519 key MUST match original raw key (BC implementation)", + rawPrivateKey, decodedX25519PrivateKey); + } + + /** + * Return true, if the given sequence contains the given subsequence entirely. + * @param sequence sequence + * @param subsequence subsequence + * @return true if subsequence is a subsequence of sequence + */ + public boolean containsSubsequence(byte[] sequence, byte[] subsequence) + { + outer: for (int i = 0; i < sequence.length - subsequence.length + 1; i++) + { + for (int j = 0; j < subsequence.length; j++) + { + if (sequence[i + j] != subsequence[j]) + { + continue outer; + } + } + return true; + } + return false; + } + + /** + * Test proper functionality of the {@link #containsSubsequence(byte[], byte[])} method. + */ + private void containsTest() + { + // Make sure our containsSubsequence method functions correctly + byte[] s = new byte[] {0x00, 0x01, 0x02, 0x03}; + isTrue(containsSubsequence(s, new byte[] {0x00, 0x01})); + isTrue(containsSubsequence(s, new byte[] {0x01, 0x02})); + isTrue(containsSubsequence(s, new byte[] {0x02, 0x03})); + isTrue(containsSubsequence(s, new byte[] {0x00})); + isTrue(containsSubsequence(s, new byte[] {0x03})); + isTrue(containsSubsequence(s, new byte[] {0x00, 0x01, 0x02, 0x03})); + isTrue(containsSubsequence(s, new byte[0])); + isTrue(containsSubsequence(new byte[0], new byte[0])); + + isFalse(containsSubsequence(s, new byte[] {0x00, 0x02})); + isFalse(containsSubsequence(s, new byte[] {0x00, 0x00})); + isFalse(containsSubsequence(s, new byte[] {0x00, 0x01, 0x02, 0x03, 0x04})); + isFalse(containsSubsequence(s, new byte[] {0x04})); + isFalse(containsSubsequence(new byte[0], new byte[] {0x00})); + } + + public static void main(String[] args) + { + runTest(new Curve25519PrivateKeyEncodingTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedEd25519KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedEd25519KeyPairTest.java new file mode 100644 index 0000000000..272931a73d --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedEd25519KeyPairTest.java @@ -0,0 +1,256 @@ +package org.bouncycastle.openpgp.test; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.Ed25519PublicBCPGKey; +import org.bouncycastle.bcpg.Ed25519SecretBCPGKey; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyConverter; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.Pack; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class DedicatedEd25519KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "DedicatedEd25519KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4SigningVerificationWithJcaKey(); + testV4SigningVerificationWithBcKey(); + + testConversionOfTestVectorKey(); + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.Ed25519, kp, date); + isEquals("Ed25519 key size mismatch", 256, k.getPublicKey().getBitStrength()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + JcaPGPKeyPair j1 = new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + BcPGPKeyPair b1 = new BcPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed25519 public key MUST be instanceof Ed25519PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed25519PublicBCPGKey); + isTrue("Dedicated Ed25519 secret key MUST be instanceof Ed25519SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed25519SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testV4SigningVerificationWithJcaKey() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.Ed25519, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new JcaPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512) + .setProvider(new BouncyCastleProvider()); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new JcaPGPContentVerifierBuilderProvider() + .setProvider(new BouncyCastleProvider()); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testV4SigningVerificationWithBcKey() + throws PGPException + { + Date date = currentTimeRounded(); + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.Ed25519, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new BcPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new BcPGPContentVerifierBuilderProvider(); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testConversionOfTestVectorKey() + throws PGPException, IOException + { + JcaPGPKeyConverter jc = new JcaPGPKeyConverter().setProvider(new BouncyCastleProvider()); + BcPGPKeyConverter bc = new BcPGPKeyConverter(); + // ed25519 public key from https://www.rfc-editor.org/rfc/rfc9580.html#name-hashed-data-stream-for-sign + Date creationTime = new Date(Pack.bigEndianToInt(Hex.decode("63877fe3"), 0) * 1000L); + byte[] k = Hex.decode("f94da7bb48d60a61e567706a6587d0331999bb9d891a08242ead84543df895a3"); + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + PGPPublicKey pgpk = new PGPPublicKey( + new PublicKeyPacket(version, PublicKeyAlgorithmTags.Ed25519, creationTime, new Ed25519PublicBCPGKey(k)), + new BcKeyFingerprintCalculator() + ); + + // convert parsed key to Jca public key + PublicKey jcpk = jc.getPublicKey(pgpk); + PGPPublicKey jck = jc.getPGPPublicKey(version, PublicKeyAlgorithmTags.Ed25519, jcpk, creationTime); + isEncodingEqual(pgpk.getEncoded(), jck.getEncoded()); + + // convert parsed key to Bc public key + AsymmetricKeyParameter bcpk = bc.getPublicKey(pgpk); + PGPPublicKey bck = bc.getPGPPublicKey(version, PublicKeyAlgorithmTags.Ed25519, null, bcpk, creationTime); + isEncodingEqual(pgpk.getEncoded(), bck.getEncoded()); + } + } + + public static void main(String[] args) + { + runTest(new DedicatedEd25519KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedEd448KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedEd448KeyPairTest.java new file mode 100644 index 0000000000..e3c31ccfd4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedEd448KeyPairTest.java @@ -0,0 +1,219 @@ +package org.bouncycastle.openpgp.test; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.Ed448PublicBCPGKey; +import org.bouncycastle.bcpg.Ed448SecretBCPGKey; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.Ed448KeyPairGenerator; +import org.bouncycastle.crypto.params.Ed448KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.Strings; + +public class DedicatedEd448KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "DedicatedEd448KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4SigningVerificationWithJcaKey(); + testV4SigningVerificationWithBcKey(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.Ed448, kp, date); + isEquals("Ed448 key size mismatch", 456, k.getPublicKey().getBitStrength()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + JcaPGPKeyPair j1 = new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.Ed448, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + Ed448KeyPairGenerator gen = new Ed448KeyPairGenerator(); + gen.init(new Ed448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + BcPGPKeyPair b1 = new BcPGPKeyPair(version, PublicKeyAlgorithmTags.Ed448, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated Ed448 public key MUST be instanceof Ed448PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof Ed448PublicBCPGKey); + isTrue("Dedicated Ed448 secret key MUST be instanceof Ed448SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof Ed448SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testV4SigningVerificationWithJcaKey() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.Ed448, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new JcaPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512) + .setProvider(new BouncyCastleProvider()); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new JcaPGPContentVerifierBuilderProvider() + .setProvider(new BouncyCastleProvider()); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testV4SigningVerificationWithBcKey() + throws PGPException + { + Date date = currentTimeRounded(); + Ed448KeyPairGenerator gen = new Ed448KeyPairGenerator(); + gen.init(new Ed448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.Ed448, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new BcPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new BcPGPContentVerifierBuilderProvider(); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + public static void main(String[] args) + { + runTest(new DedicatedEd448KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedX25519KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedX25519KeyPairTest.java new file mode 100644 index 0000000000..a6b86cbdc8 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedX25519KeyPairTest.java @@ -0,0 +1,272 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.X25519PublicBCPGKey; +import org.bouncycastle.bcpg.X25519SecretBCPGKey; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.XDHParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPLiteralDataGenerator; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.Streams; + +public class DedicatedX25519KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "DedicatedX25519KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4MessageEncryptionDecryptionWithJcaKey(); + testV4MessageEncryptionDecryptionWithBcKey(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.X25519, kp, date); + isEquals("X25519 key size mismatch", 256, k.getPublicKey().getBitStrength()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + JcaPGPKeyPair j1 = new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.X25519, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + BcPGPKeyPair b1 = new BcPGPKeyPair(version, PublicKeyAlgorithmTags.X25519, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X25519 public key MUST be instanceof X25519PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof X25519PublicBCPGKey); + isTrue("Dedicated X25519 secret key MUST be instanceof X25519SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof X25519SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testV4MessageEncryptionDecryptionWithJcaKey() + throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException + { + BouncyCastleProvider provider = new BouncyCastleProvider(); + + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", provider); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.X25519, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPDataEncryptorBuilder encBuilder = new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) + .setProvider(provider); + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + PublicKeyKeyEncryptionMethodGenerator metGen = new JcePublicKeyKeyEncryptionMethodGenerator(keyPair.getPublicKey()) + .setProvider(provider); + encGen.addMethod(metGen); + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = encGen.open(bOut, new byte[4096]); + OutputStream litOut = litGen.open(encOut, PGPLiteralData.BINARY, "", PGPLiteralData.NOW, new byte[4096]); + litOut.write(data); + litGen.close(); + encGen.close(); + + byte[] encrypted = bOut.toByteArray(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encrypted); + PGPObjectFactory objectFactory = new JcaPGPObjectFactory(bIn); + PGPEncryptedDataList encDataList = (PGPEncryptedDataList) objectFactory.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); + PublicKeyDataDecryptorFactory decFactory = new JcePublicKeyDataDecryptorFactoryBuilder() + .setProvider(provider) + .build(keyPair.getPrivateKey()); + InputStream decIn = encData.getDataStream(decFactory); + objectFactory = new JcaPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objectFactory.nextObject(); + InputStream litIn = lit.getDataStream(); + byte[] plaintext = Streams.readAll(litIn); + litIn.close(); + decIn.close(); + + isTrue(Arrays.areEqual(data, plaintext)); + } + + private void testV4MessageEncryptionDecryptionWithBcKey() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.X25519, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPDataEncryptorBuilder encBuilder = new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256); + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + PublicKeyKeyEncryptionMethodGenerator metGen = new BcPublicKeyKeyEncryptionMethodGenerator(keyPair.getPublicKey()); + encGen.addMethod(metGen); + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = encGen.open(bOut, new byte[4096]); + OutputStream litOut = litGen.open(encOut, PGPLiteralData.BINARY, "", PGPLiteralData.NOW, new byte[4096]); + litOut.write(data); + litGen.close(); + encGen.close(); + + byte[] encrypted = bOut.toByteArray(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encrypted); + PGPObjectFactory objectFactory = new BcPGPObjectFactory(bIn); + PGPEncryptedDataList encDataList = (PGPEncryptedDataList) objectFactory.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); + PublicKeyDataDecryptorFactory decFactory = new BcPublicKeyDataDecryptorFactory(keyPair.getPrivateKey()); + InputStream decIn = encData.getDataStream(decFactory); + objectFactory = new BcPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objectFactory.nextObject(); + InputStream litIn = lit.getDataStream(); + byte[] plaintext = Streams.readAll(litIn); + litIn.close(); + decIn.close(); + + isTrue(Arrays.areEqual(data, plaintext)); + } + + public static void main(String[] args) + { + runTest(new DedicatedX25519KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedX448KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedX448KeyPairTest.java new file mode 100644 index 0000000000..12067e68dd --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/DedicatedX448KeyPairTest.java @@ -0,0 +1,273 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.X448PublicBCPGKey; +import org.bouncycastle.bcpg.X448SecretBCPGKey; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.X448KeyPairGenerator; +import org.bouncycastle.crypto.params.X448KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jcajce.spec.XDHParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPLiteralDataGenerator; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.Streams; + +public class DedicatedX448KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "DedicatedX448KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4MessageEncryptionDecryptionWithJcaKey(); + testV4MessageEncryptionDecryptionWithBcKey(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X448")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.X448, kp, date); + isEquals("X448 key size mismatch", 448, k.getPublicKey().getBitStrength()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X448")); + KeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + JcaPGPKeyPair j1 = new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.X448, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X448KeyPairGenerator gen = new X448KeyPairGenerator(); + gen.init(new X448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + for (int idx = 0; idx != 2; idx ++) + { + int version = (idx == 0) ? PublicKeyPacket.VERSION_4 : PublicKeyPacket.VERSION_6; + BcPGPKeyPair b1 = new BcPGPKeyPair(version, PublicKeyAlgorithmTags.X448, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Dedicated X448 public key MUST be instanceof X448PublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof X448PublicBCPGKey); + isTrue("Dedicated X448 secret key MUST be instanceof X448SecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof X448SecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + } + + private void testV4MessageEncryptionDecryptionWithJcaKey() + throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException + { + BouncyCastleProvider provider = new BouncyCastleProvider(); + + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", provider); + gen.initialize(new XDHParameterSpec("X448")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.X448, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPDataEncryptorBuilder encBuilder = new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) + .setProvider(provider); + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + PublicKeyKeyEncryptionMethodGenerator metGen = new JcePublicKeyKeyEncryptionMethodGenerator(keyPair.getPublicKey()) + .setProvider(provider); + encGen.addMethod(metGen); + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = encGen.open(bOut, new byte[4096]); + OutputStream litOut = litGen.open(encOut, PGPLiteralData.BINARY, "", PGPLiteralData.NOW, new byte[4096]); + litOut.write(data); + litGen.close(); + encGen.close(); + + byte[] encrypted = bOut.toByteArray(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encrypted); + PGPObjectFactory objectFactory = new JcaPGPObjectFactory(bIn); + PGPEncryptedDataList encDataList = (PGPEncryptedDataList) objectFactory.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); + PublicKeyDataDecryptorFactory decFactory = new JcePublicKeyDataDecryptorFactoryBuilder() + .setProvider(provider) + .build(keyPair.getPrivateKey()); + InputStream decIn = encData.getDataStream(decFactory); + objectFactory = new JcaPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objectFactory.nextObject(); + InputStream litIn = lit.getDataStream(); + byte[] plaintext = Streams.readAll(litIn); + litIn.close(); + decIn.close(); + + isTrue(Arrays.areEqual(data, plaintext)); + } + + private void testV4MessageEncryptionDecryptionWithBcKey() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X448KeyPairGenerator gen = new X448KeyPairGenerator(); + gen.init(new X448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.X448, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPDataEncryptorBuilder encBuilder = new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256); + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + PublicKeyKeyEncryptionMethodGenerator metGen = new BcPublicKeyKeyEncryptionMethodGenerator(keyPair.getPublicKey()); + encGen.addMethod(metGen); + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = encGen.open(bOut, new byte[4096]); + OutputStream litOut = litGen.open(encOut, PGPLiteralData.BINARY, "", PGPLiteralData.NOW, new byte[4096]); + litOut.write(data); + litGen.close(); + encGen.close(); + + byte[] encrypted = bOut.toByteArray(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encrypted); + PGPObjectFactory objectFactory = new BcPGPObjectFactory(bIn); + PGPEncryptedDataList encDataList = (PGPEncryptedDataList)objectFactory.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData)encDataList.get(0); + PublicKeyDataDecryptorFactory decFactory = new BcPublicKeyDataDecryptorFactory(keyPair.getPrivateKey()); + InputStream decIn = encData.getDataStream(decFactory); + objectFactory = new BcPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData)objectFactory.nextObject(); + InputStream litIn = lit.getDataStream(); + byte[] plaintext = Streams.readAll(litIn); + litIn.close(); + decIn.close(); + + isTrue(Arrays.areEqual(data, plaintext)); + } + + public static void main(String[] args) + { + runTest(new DedicatedX448KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/ECDSAKeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/ECDSAKeyPairTest.java new file mode 100644 index 0000000000..4ebf4bcc2c --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/ECDSAKeyPairTest.java @@ -0,0 +1,284 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.util.Date; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.ECDSAPublicBCPGKey; +import org.bouncycastle.bcpg.ECSecretBCPGKey; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.bc.BcPGPSecretKeyRing; +import org.bouncycastle.openpgp.jcajce.JcaPGPSecretKeyRing; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyConverter; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.Strings; + +public class ECDSAKeyPairTest + extends AbstractPgpKeyPairTest +{ + + private static final String PRIME256v1 = "" + + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "lHcEZkH7VRMIKoZIzj0DAQcCAwQee5wkHVVrG7u7CcrHoZOaC+reK0wn2Y5XPJoU\n" + + "O6geh1j2qXHj4+f+a6lav5hzKIJZHkgBYcS0aeABgWNjKsHbAAD/b4K93MJF7c2l\n" + + "4Y7ojBqTuZAOOD0Dyqe8MTXXyDUWN/0R/w==\n" + + "=mPB9\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + private static final String SECP384r1 = "" + + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "lKQEZkH7VhMFK4EEACIDAwQgkKs+EzJaFLgMZH5Fp1S8DCXZC0OildnuQX6F7Jzt\n" + + "BgkYyfDZ/F2KNistCqfsmxWnwAxtdRuuY2PfehWktQBQaID0OfXUnOC2E5961b3/\n" + + "7xoZU26T0npmTqX0P/wuXawAAX9S2V72/xeShrcIwIwy2QvCcsW9ATBSQ6U+T7KZ\n" + + "zzFisUiqCgYa/9hoSNnu7iNrnrcYlQ==\n" + + "=SyFg\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + private static final String SECP521r1 = "" + + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "lNkEZkH7VhMFK4EEACMEIwQBxt7DenSWrjuJGR0ouSwylW3ZC6mX4S+A5Cav7nz3\n" + + "DninA8Rdt3Cd5sHQ1IWea+J05NUZDKbOL417lUSPkAVLot0B/Qis90wODcGnAXbc\n" + + "m+m7rN2/Waryj/EsxLxub4UNtyZ405C8dDo9ch2JRfHiH6R1dwyqD9+yY2lOPYO+\n" + + "tn5fx/4AAgIDG9+DPtDf91tBMhBKc0f++t6aV115HLlyIpnEipThSwMTgzWm0uPZ\n" + + "KD3CifJeUU/TMk9IGFYvRlaWBQfrB3V/Ahz4\n" + + "=DD95\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + private static final String BRAINPOOLP256r1 = "" + + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "lHgEZkH7VhMJKyQDAwIIAQEHAgMEj7YxVg4/2p4uuhcpRqGl2i+vDhjx8YhUUNJX\n" + + "RNFozBuIWJ6zkW3wRKdD/7Y7tzKNwyHmZ4FBFCcUoLliLeD4SAABAIkEm4iT1g0B\n" + + "Bo9vkUrUcP2b+vtOuwtmrvGrT0VzVXYlD5M=\n" + + "=vZRh\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + private static final String BRAINPOOLP384r1 = "" + + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "lKgEZkH7VhMJKyQDAwIIAQELAwMEYm1fhilklF53Pj91awsoO0aZsppmPk9KNESD\n" + + "H7/gSK86gl+yhf4/oKSxeOFDHCU2es6Iijq/TCIaAjeFH3ITEyQ4tPdnDqQSz2xq\n" + + "o6wtRTW3cRD9oyoOT8bAMdm+RYpJAAF5AXAfxp3VtxqVVxnR1mC3Z3nL25zmvdu1\n" + + "oPRvA9fenVxTOlyU6X9qCycSuxamkPO7Gic=\n" + + "=2eJn\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + private static final String BRAINPOOLP521r1 = "" + + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "lNgEZkH7VhMJKyQDAwIIAQENBAMEbSjn4lQKNnC50PzeUtenikvF62KR7HfOLJTA\n" + + "r/T17tFx3Qb6Ek/xQWIJ5nIHroOrduZjLigPOXqQ+GNhCgdNPGUqAWw1sfQ86nrx\n" + + "jqlr67na3F3eaTJr9ajr2V37/5uHnuryJnkyy2laFdOGD0Ad9/bQkvXYoWVm0P07\n" + + "uCPnexEAAgCSUoeS3c+DAZlWETdyuSDyvHK7GLO67+CgVsEyqBF/Kch/vhBZFWXA\n" + + "Cs9lph8la5B0faKH5XSbeReudKGh/MjfIJo=\n" + + "=MZeT\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + + @Override + public String getName() + { + return "ECDSAKeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfFreshJcaKeyPair(); + testConversionOfParsedJcaKeyPair(); + testConversionOfParsedBcKeyPair(); + + } + + private void testConversionOfParsedJcaKeyPair() + throws PGPException, IOException + { + parseAndConvertJca(BRAINPOOLP256r1); + parseAndConvertJca(BRAINPOOLP384r1); + parseAndConvertJca(BRAINPOOLP521r1); + parseAndConvertJca(PRIME256v1); + parseAndConvertJca(SECP384r1); + parseAndConvertJca(SECP521r1); + } + + private void parseAndConvertJca(String curve) + throws IOException, PGPException + { + JcaPGPKeyConverter c = new JcaPGPKeyConverter().setProvider(new BouncyCastleProvider()); + PGPKeyPair parsed = parseJca(curve); + byte[] pubEnc = parsed.getPublicKey().getEncoded(); + byte[] privEnc = parsed.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + + JcaPGPKeyPair j1 = new JcaPGPKeyPair( + PublicKeyPacket.VERSION_4, + parsed.getPublicKey().getAlgorithm(), + new KeyPair(c.getPublicKey(parsed.getPublicKey()), + c.getPrivateKey(parsed.getPrivateKey())), + parsed.getPublicKey().getCreationTime()); + isEncodingEqual("ECDSA Public key (" + curve + ") encoding mismatch", pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + } + + private void testConversionOfParsedBcKeyPair() + throws PGPException, IOException + { + parseAndConvertBc(BRAINPOOLP256r1); + parseAndConvertBc(BRAINPOOLP384r1); + parseAndConvertBc(BRAINPOOLP521r1); + parseAndConvertBc(PRIME256v1); + parseAndConvertBc(SECP384r1); + parseAndConvertBc(SECP521r1); + } + + private void parseAndConvertBc(String curve) + throws IOException, PGPException + { + BcPGPKeyConverter c = new BcPGPKeyConverter(); + PGPKeyPair parsed = parseBc(curve); + byte[] pubEnc = parsed.getPublicKey().getEncoded(); + byte[] privEnc = parsed.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + + BcPGPKeyPair b1 = new BcPGPKeyPair( + PublicKeyPacket.VERSION_4, + parsed.getPublicKey().getAlgorithm(), + new AsymmetricCipherKeyPair( + c.getPublicKey(parsed.getPublicKey()), + c.getPrivateKey(parsed.getPrivateKey())), + parsed.getPublicKey().getCreationTime()); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + + } + + private PGPKeyPair parseJca(String armored) + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armored)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + JcaPGPSecretKeyRing ring = new JcaPGPSecretKeyRing(pIn); + PGPSecretKey sk = ring.getSecretKey(); + return new PGPKeyPair(sk.getPublicKey(), sk.extractPrivateKey(null)); + } + + private PGPKeyPair parseBc(String armored) + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armored)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + BcPGPSecretKeyRing ring = new BcPGPSecretKeyRing(pIn); + PGPSecretKey sk = ring.getSecretKey(); + return new PGPKeyPair(sk.getPublicKey(), sk.extractPrivateKey(null)); + } + + private void testConversionOfFreshJcaKeyPair() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException, IOException + { + String[] curves = new String[] { + "prime256v1", + "secp384r1", + "secp521r1", + "brainpoolP256r1", + "brainpoolP384r1", + "brainpoolP512r1" + }; + + for (int i = 0; i != curves.length; i++) + { + testConversionOfFreshJcaKeyPair(curves[i]); + } + } + + private void testConversionOfFreshJcaKeyPair(String curve) + throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("ECDSA", new BouncyCastleProvider()); + gen.initialize(new ECNamedCurveGenParameterSpec(curve)); + KeyPair kp = gen.generateKeyPair(); + + JcaPGPKeyPair j1 = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, PublicKeyAlgorithmTags.ECDSA, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy ECDSA public key MUST be instanceof ECDSAPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDSAPublicBCPGKey); + isTrue("Legacy ECDSA secret key MUST be instanceof ECSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy ECDSA public key MUST be instanceof ECDSAPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDSAPublicBCPGKey); + isTrue(" Legacy ECDSA secret key MUST be instanceof ECSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy ECDSA public key MUST be instanceof ECDSAPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDSAPublicBCPGKey); + isTrue("Legacy ECDSA secret key MUST be instanceof ECSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy ECDSA public key MUST be instanceof ECDSAPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDSAPublicBCPGKey); + isTrue("Legacy ECDSA secret key MUST be instanceof ECSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + + public static void main(String[] args) + { + runTest(new ECDSAKeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/EdDSAKeyConversionWithLeadingZeroTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/EdDSAKeyConversionWithLeadingZeroTest.java new file mode 100644 index 0000000000..b5aef89e11 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/EdDSAKeyConversionWithLeadingZeroTest.java @@ -0,0 +1,112 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.encoders.Hex; + +import java.security.*; +import java.security.spec.*; +import java.util.Date; + +public class EdDSAKeyConversionWithLeadingZeroTest + extends AbstractPacketTest +{ + @Override + public String getName() + { + return "EdDSALeadingZero"; + } + + private static final String ED448_KEY_WITH_LEADING_ZERO = "308183020101300506032b6571043b0439fe2c82fd07b0e8b5da002ee4964e55a357bfdd2192fe43a40b150e6c5a8f8202f140dd34ede17dc10fef9a98bf8188425c14bd1a76a308cfb7813a0000728cbb07c590e2cb282834cc22d7a1f775f729986c4754e7035695dee34057403e98e94cf5012007c3236f4894af039e668acb746fcf8a00"; + private static final String ED448_PUB_WITH_LEADING_ZERO = "3043300506032b6571033a0000728cbb07c590e2cb282834cc22d7a1f775f729986c4754e7035695dee34057403e98e94cf5012007c3236f4894af039e668acb746fcf8a00"; + + private static final String ED25519_KEY_WITH_LEADING_ZERO = "3051020101300506032b65700422042077ee5931a6d454f85acd9cc28bb2fa8c340e10f7cbf0193f1f898a5c22e77f4281210000dcd38e8ec0978690a4bbc8ac7787d311e741c394ba839ad9cc15e9ba21deb1"; + private static final String ED25519_PUB_WITH_LEADING_ZERO = "302a300506032b657003210000dcd38e8ec0978690a4bbc8ac7787d311e741c394ba839ad9cc15e9ba21deb1"; + + @Override + public void performTest() + throws Exception + { + testWithEd448KeyWithLeadingZero(); + testWithEd25519KeyWithLeadingZero(); + } + + private void testWithEd448KeyWithLeadingZero() + throws NoSuchAlgorithmException, InvalidKeySpecException, PGPException, InvalidKeyException, SignatureException + { + JcaPGPKeyConverter jcaPGPKeyConverter = new JcaPGPKeyConverter().setProvider(new BouncyCastleProvider()); + + KeyFactory factory = KeyFactory.getInstance("EdDSA", new BouncyCastleProvider()); + + PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(Hex.decode(ED448_PUB_WITH_LEADING_ZERO))); + PrivateKey privKey = factory.generatePrivate(new PKCS8EncodedKeySpec(Hex.decode(ED448_KEY_WITH_LEADING_ZERO))); + KeyPair keyPair = new KeyPair(pubKey, privKey); + + Date creationDate = new Date(); + PGPKeyPair jcaPgpPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.Ed448, keyPair, creationDate); + isTrue("public key encoding before conversion MUST have leading 0", + jcaPgpPair.getPublicKey().getPublicKeyPacket().getKey().getEncoded()[0] == 0); // leading 0 + + PublicKey cPubKey = jcaPGPKeyConverter.getPublicKey(jcaPgpPair.getPublicKey()); + PrivateKey cPrivKey = jcaPGPKeyConverter.getPrivateKey(jcaPgpPair.getPrivateKey()); + + testSignature(cPrivKey, pubKey, "Ed448"); + testSignature(privKey, cPubKey, "Ed448"); + + jcaPgpPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.Ed448, new KeyPair(cPubKey, cPrivKey), creationDate); + isTrue("public key encoding after conversion MUST have leading 0", + jcaPgpPair.getPublicKey().getPublicKeyPacket().getKey().getEncoded()[0] == 0); // leading 0 is preserved + } + + + private void testWithEd25519KeyWithLeadingZero() + throws NoSuchAlgorithmException, InvalidKeySpecException, PGPException, InvalidKeyException, SignatureException + { + JcaPGPKeyConverter jcaPGPKeyConverter = new JcaPGPKeyConverter().setProvider(new BouncyCastleProvider()); + + KeyFactory factory = KeyFactory.getInstance("EdDSA", new BouncyCastleProvider()); + + PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(Hex.decode(ED25519_PUB_WITH_LEADING_ZERO))); + PrivateKey privKey = factory.generatePrivate(new PKCS8EncodedKeySpec(Hex.decode(ED25519_KEY_WITH_LEADING_ZERO))); + KeyPair keyPair = new KeyPair(pubKey, privKey); + + Date creationDate = new Date(); + PGPKeyPair jcaPgpPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.Ed25519, keyPair, creationDate); + isTrue("public key encoding before conversion MUST have leading 0", + jcaPgpPair.getPublicKey().getPublicKeyPacket().getKey().getEncoded()[0] == 0); // leading 0 + + PublicKey cPubKey = jcaPGPKeyConverter.getPublicKey(jcaPgpPair.getPublicKey()); + PrivateKey cPrivKey = jcaPGPKeyConverter.getPrivateKey(jcaPgpPair.getPrivateKey()); + + testSignature(cPrivKey, pubKey, "Ed25519"); + testSignature(privKey, cPubKey, "Ed25519"); + + jcaPgpPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.Ed25519, new KeyPair(cPubKey, cPrivKey), creationDate); + isTrue("public key encoding after conversion MUST have leading 0", + jcaPgpPair.getPublicKey().getPublicKeyPacket().getKey().getEncoded()[0] == 0); // leading 0 is preserved + } + + private void testSignature(PrivateKey privateKey, PublicKey publicKey, String edAlgo) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException + { + Signature signature = Signature.getInstance(edAlgo, new BouncyCastleProvider()); + signature.initSign(privateKey); + signature.update("Hello, World!\n".getBytes()); + byte[] sig = signature.sign(); + + signature.initVerify(publicKey); + signature.update("Hello, World!\n".getBytes()); + isTrue("Signature MUST verify", signature.verify(sig)); + } + + public static void main(String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + runTest(new EdDSAKeyConversionWithLeadingZeroTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/KeyIdentifierTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/KeyIdentifierTest.java new file mode 100644 index 0000000000..b61b29f149 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/KeyIdentifierTest.java @@ -0,0 +1,310 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.FingerprintUtil; +import org.bouncycastle.bcpg.KeyIdentifier; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.SimpleTest; + +public class KeyIdentifierTest + extends SimpleTest +{ + @Override + public String getName() + { + return "KeyIdentifierTest"; + } + + @Override + public void performTest() + throws Exception + { + testWildcardIdentifier(); + testWildcardMatches(); + testIdentifierFromKeyId(); + + testIdentifierFromLongKeyId(); + + testIdentifierFromV4Fingerprint(); + testIdentifierFromV6Fingerprint(); + + testMatchV4Key(); + testMatchV6Key(); + } + + private void testWildcardIdentifier() + { + KeyIdentifier wildcard = KeyIdentifier.wildcard(); + isEquals("Wildcard KeyIdentifier MUST have key-id 0", + 0L, wildcard.getKeyId()); + isTrue("Wildcard KeyIdentifier MUST have zero-length fingerprint", + Arrays.areEqual(new byte[0], wildcard.getFingerprint())); + isTrue("Wildcard MUST return true for isWildcard()", + wildcard.isWildcard()); + + isEquals("*", wildcard.toString()); + + KeyIdentifier id = new KeyIdentifier(0L); + isTrue(id.isWildcard()); + } + + private void testWildcardMatches() { + KeyIdentifier wildcard = KeyIdentifier.wildcard(); + KeyIdentifier nonWildcard = new KeyIdentifier(123L); + + isTrue(wildcard.matches(nonWildcard)); + isTrue(nonWildcard.matches(wildcard)); + + isTrue(!wildcard.matchesExplicit(nonWildcard)); + isTrue(!nonWildcard.matchesExplicit(wildcard)); + } + + private void testIdentifierFromKeyId() + { + KeyIdentifier identifier = new KeyIdentifier(1234L); + isEquals("Identifier key ID mismatch", + 1234L, identifier.getKeyId()); + isTrue("Identifier MUST return null for getFingerprint()", + identifier.getFingerprint() == null); + + isEquals("1234", identifier.toString()); + } + + private void testIdentifierFromLongKeyId() + { + isEquals(5145070902336167606L, new KeyIdentifier("4766F6B9D5F21EB6").getKeyId()); + isEquals(5145070902336167606L, new KeyIdentifier("4766f6b9d5f21eb6").getKeyId()); + + isEquals(5507497285755629956L, new KeyIdentifier("4C6E8F99F6E47184").getKeyId()); + isEquals(1745434690267590572L, new KeyIdentifier("1839079A640B2FAC").getKeyId()); + + isTrue(new KeyIdentifier("1839079A640B2FAC").getFingerprint() == null); + } + + private void testIdentifierFromV4Fingerprint() + { + String hexFingerprint = "D1A66E1A23B182C9980F788CFBFCC82A015E7330"; + byte[] fingerprint = Hex.decode(hexFingerprint); + KeyIdentifier identifier = new KeyIdentifier(fingerprint); + isTrue("Identifier fingerprint mismatch", + Arrays.areEqual(fingerprint, identifier.getFingerprint())); + isEquals("Identifier key-ID mismatch", + FingerprintUtil.keyIdFromV4Fingerprint(fingerprint), identifier.getKeyId()); + + isEquals(hexFingerprint, identifier.toString()); + } + + private void testIdentifierFromV6Fingerprint() + { + String hexFingerprint = "CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"; + byte[] fingerprint = Hex.decode(hexFingerprint); + KeyIdentifier identifier = new KeyIdentifier(fingerprint); + isTrue("Identifier fingerprint mismatch", + Arrays.areEqual(fingerprint, identifier.getFingerprint())); + isEquals("Identifier key-ID mismatch", + FingerprintUtil.keyIdFromV6Fingerprint(fingerprint), identifier.getKeyId()); + + isEquals(hexFingerprint, identifier.toString()); + } + + private void testMatchV4Key() + throws IOException, PGPException + { + PGPSecretKeyRing secretKeys = getV4Key(); + Iterator it = secretKeys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)it.next(); + PGPSecretKey subkey = (PGPSecretKey)it.next(); + + KeyIdentifier primaryIdentifier = primaryKey.getKeyIdentifier(); + isEquals(primaryKey.getKeyID(), primaryIdentifier.getKeyId()); + isTrue(Arrays.areEqual(primaryKey.getFingerprint(), primaryIdentifier.getFingerprint())); + isTrue(primaryIdentifier.matches(primaryKey.getKeyIdentifier())); + isTrue(primaryIdentifier.matches(primaryKey.getPublicKey().getKeyIdentifier())); + isTrue(primaryKey.getPublicKey().getKeyIdentifier().getKeyId()==primaryIdentifier.getKeyId()); + isTrue(!primaryIdentifier.matches(subkey.getKeyIdentifier())); + isTrue(!primaryIdentifier.matches(subkey.getPublicKey().getKeyIdentifier())); + + KeyIdentifier subkeyIdentifier = subkey.getKeyIdentifier(); + isEquals(subkey.getKeyID(), subkeyIdentifier.getKeyId()); + isTrue(Arrays.areEqual(subkey.getFingerprint(), subkeyIdentifier.getFingerprint())); + isTrue(subkeyIdentifier.matches(subkey.getKeyIdentifier())); + isTrue(subkeyIdentifier.matches(subkey.getPublicKey().getKeyIdentifier())); + isTrue(!subkeyIdentifier.matches(primaryKey.getKeyIdentifier())); + isTrue(!subkeyIdentifier.matches(primaryKey.getPublicKey().getKeyIdentifier())); + + PGPPrivateKey privateKey = primaryKey.extractPrivateKey(null); + KeyIdentifier privateKeyIdentifier = privateKey.getKeyIdentifier(new JcaKeyFingerprintCalculator()); + isTrue(privateKeyIdentifier.matches(privateKey.getKeyIdentifier(new JcaKeyFingerprintCalculator()))); + isTrue(privateKeyIdentifier.matches(primaryKey.getKeyIdentifier())); + isTrue(primaryIdentifier.matches(privateKey.getKeyIdentifier(new JcaKeyFingerprintCalculator()))); + isTrue(!subkeyIdentifier.matches(privateKey.getKeyIdentifier(new JcaKeyFingerprintCalculator()))); + + KeyIdentifier noFingerPrintId = new KeyIdentifier(primaryKey.getKeyID()); + isTrue(primaryKey.getKeyIdentifier().matches(noFingerPrintId)); + + KeyIdentifier wildcard = KeyIdentifier.wildcard(); + isTrue(wildcard.matches(primaryKey.getKeyIdentifier())); + isTrue(wildcard.matches(subkey.getKeyIdentifier())); + isTrue(wildcard.matches(privateKey.getKeyIdentifier(new JcaKeyFingerprintCalculator()))); + + isTrue(primaryKey.getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + isTrue(primaryKey.getPublicKey().getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + isTrue(subkey.getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + isTrue(subkey.getPublicKey().getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + } + + private List asList(KeyIdentifier a, KeyIdentifier b) + { + List l = new ArrayList(2); + + l.add(a); + l.add(b); + + return l; + } + + private void testMatchV6Key() + throws IOException, PGPException + { + PGPSecretKeyRing secretKeys = getV6Key(); + Iterator it = secretKeys.getSecretKeys(); + PGPSecretKey primaryKey = (PGPSecretKey)it.next(); + PGPSecretKey subkey = (PGPSecretKey)it.next(); + + KeyIdentifier primaryIdentifier = primaryKey.getKeyIdentifier(); + isEquals(primaryKey.getKeyID(), primaryIdentifier.getKeyId()); + isTrue(Arrays.areEqual(primaryKey.getFingerprint(), primaryIdentifier.getFingerprint())); + isTrue(primaryIdentifier.matches(primaryKey.getKeyIdentifier())); + isTrue(primaryIdentifier.matches(primaryKey.getPublicKey().getKeyIdentifier())); + isTrue(!primaryIdentifier.matches(subkey.getKeyIdentifier())); + isTrue(!primaryIdentifier.matches(subkey.getPublicKey().getKeyIdentifier())); + + KeyIdentifier subkeyIdentifier = subkey.getKeyIdentifier(); + isEquals(subkey.getKeyID(), subkeyIdentifier.getKeyId()); + isTrue(Arrays.areEqual(subkey.getFingerprint(), subkeyIdentifier.getFingerprint())); + isTrue(subkeyIdentifier.matches(subkey.getKeyIdentifier())); + isTrue(subkeyIdentifier.matches(subkey.getPublicKey().getKeyIdentifier())); + isTrue(!subkeyIdentifier.matches(primaryKey.getKeyIdentifier())); + isTrue(!subkeyIdentifier.matches(primaryKey.getPublicKey().getKeyIdentifier())); + + PGPPrivateKey privateKey = primaryKey.extractPrivateKey(null); + KeyIdentifier privateKeyIdentifier = privateKey.getKeyIdentifier(new BcKeyFingerprintCalculator()); + isTrue(privateKeyIdentifier.matches(privateKey.getKeyIdentifier(new BcKeyFingerprintCalculator()))); + isTrue(privateKeyIdentifier.matches(primaryKey.getKeyIdentifier())); + isTrue(primaryIdentifier.matches(privateKey.getKeyIdentifier(new BcKeyFingerprintCalculator()))); + isTrue(!subkeyIdentifier.matches(privateKey.getKeyIdentifier(new BcKeyFingerprintCalculator()))); + + KeyIdentifier noFingerPrintId = new KeyIdentifier(primaryKey.getKeyID()); + isTrue(primaryKey.getKeyIdentifier().matches(noFingerPrintId)); + + KeyIdentifier wildcard = KeyIdentifier.wildcard(); + isTrue(wildcard.matches(primaryKey.getKeyIdentifier())); + isTrue(wildcard.matches(subkey.getKeyIdentifier())); + isTrue(wildcard.matches(privateKey.getKeyIdentifier(new BcKeyFingerprintCalculator()))); + + isTrue(primaryKey.getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + isTrue(primaryKey.getPublicKey().getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + isTrue(subkey.getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + isTrue(subkey.getPublicKey().getKeyIdentifier().isPresentIn( + asList(primaryIdentifier, subkeyIdentifier))); + } + + /** + * Return the v6 test key from RFC9580. + * Fingerprints: + *
        + *
      • CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9
      • + *
      • 12C83F1E706F6308FE151A417743A1F033790E93E9978488D1DB378DA9930885
      • + *
      + * @return test key + * @throws IOException + */ + private PGPSecretKeyRing getV6Key() + throws IOException + { + String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xUsGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laMAGXKB\n" + + "exK+cH6NX1hs5hNhIB00TrJmosgv3mg1ditlsLfCsQYfGwoAAABCBYJjh3/jAwsJ\n" + + "BwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lwgyU2kCcUmKfvBXbAf6rh\n" + + "RYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaEQsiPlR4zxP/TP7mhfVEe\n" + + "7XWPxtnMUMtf15OyA51YBMdLBmOHf+MZAAAAIIaTJINn+eUBXbki+PSAld2nhJh/\n" + + "LVmFsS+60WyvXkQ1AE1gCk95TUR3XFeibg/u/tVY6a//1q0NWC1X+yui3O24wpsG\n" + + "GBsKAAAALAWCY4d/4wKbDCIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAAQBIKbpGG2dWTX8j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDE\n" + + "M0g12vYxoWM8Y81W+bHBw805I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUr\n" + + "k0mXubZvyl4GBg==\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + return (PGPSecretKeyRing) objFac.nextObject(); + } + + /** + * Return the 'Alice' test key. + * Fingerprints: + *
        + *
      • EB85BB5FA33A75E15E944E63F231550C4F47E38E
      • + *
      • EA02B24FFD4C1B96616D3DF24766F6B9D5F21EB6
      • + *
      + * @return Alice test key + * @throws IOException + */ + private PGPSecretKeyRing getV4Key() + throws IOException + { + String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Comment: Alice's OpenPGP Transferable Secret Key\n" + + "\n" + + "lFgEXEcE6RYJKwYBBAHaRw8BAQdArjWwk3FAqyiFbFBKT4TzXcVBqPTB3gmzlC/U\n" + + "b7O1u10AAP9XBeW6lzGOLx7zHH9AsUDUTb2pggYGMzd0P3ulJ2AfvQ4RtCZBbGlj\n" + + "ZSBMb3ZlbGFjZSA8YWxpY2VAb3BlbnBncC5leGFtcGxlPoiQBBMWCAA4AhsDBQsJ\n" + + "CAcCBhUKCQgLAgQWAgMBAh4BAheAFiEE64W7X6M6deFelE5j8jFVDE9H444FAl2l\n" + + "nzoACgkQ8jFVDE9H447pKwD6A5xwUqIDprBzrHfahrImaYEZzncqb25vkLV2arYf\n" + + "a78A/R3AwtLQvjxwLDuzk4dUtUwvUYibL2sAHwj2kGaHnfICnF0EXEcE6RIKKwYB\n" + + "BAGXVQEFAQEHQEL/BiGtq0k84Km1wqQw2DIikVYrQrMttN8d7BPfnr4iAwEIBwAA\n" + + "/3/xFPG6U17rhTuq+07gmEvaFYKfxRB6sgAYiW6TMTpQEK6IeAQYFggAIBYhBOuF\n" + + "u1+jOnXhXpROY/IxVQxPR+OOBQJcRwTpAhsMAAoJEPIxVQxPR+OOWdABAMUdSzpM\n" + + "hzGs1O0RkWNQWbUzQ8nUOeD9wNbjE3zR+yfRAQDbYqvtWQKN4AQLTxVJN5X5AWyb\n" + + "Pnn+We1aTBhaGa86AQ==\n" + + "=n8OM\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + return (PGPSecretKeyRing) objFac.nextObject(); + } + + public static void main(String[] args) + { + runTest(new KeyIdentifierTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyEd25519KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyEd25519KeyPairTest.java new file mode 100644 index 0000000000..9b52100e69 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyEd25519KeyPairTest.java @@ -0,0 +1,211 @@ +package org.bouncycastle.openpgp.test; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.EdDSAPublicBCPGKey; +import org.bouncycastle.bcpg.EdSecretBCPGKey; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.Strings; + +public class LegacyEd25519KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "LegacyEd25519KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4SigningVerificationWithJcaKey(); + testV4SigningVerificationWithBcKey(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + isEquals("Ed25519 key size mismatch", 256, k.getPublicKey().getBitStrength()); + } + + private void testV4SigningVerificationWithJcaKey() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new JcaPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512) + .setProvider(new BouncyCastleProvider()); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new JcaPGPContentVerifierBuilderProvider() + .setProvider(new BouncyCastleProvider()); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testV4SigningVerificationWithBcKey() + throws PGPException + { + Date date = currentTimeRounded(); + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new BcPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new BcPGPContentVerifierBuilderProvider(); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, PGPException, InvalidAlgorithmParameterException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed25519")); + KeyPair kp = gen.generateKeyPair(); + + JcaPGPKeyPair j1 = new JcaPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + BcPGPKeyPair b1 = new BcPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed25519 public key MUST be instanceof EdDSAPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed25519 secret key MUST be instanceof EdSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + + public static void main(String[] args) + { + runTest(new LegacyEd25519KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyEd448KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyEd448KeyPairTest.java new file mode 100644 index 0000000000..fd17c3c001 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyEd448KeyPairTest.java @@ -0,0 +1,211 @@ +package org.bouncycastle.openpgp.test; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.EdDSAPublicBCPGKey; +import org.bouncycastle.bcpg.EdSecretBCPGKey; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.Ed448KeyPairGenerator; +import org.bouncycastle.crypto.params.Ed448KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.util.Strings; + +public class LegacyEd448KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "LegacyEd448KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4SigningVerificationWithJcaKey(); + testV4SigningVerificationWithBcKey(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + isEquals("Ed448 key size mismatch", 456, k.getPublicKey().getBitStrength()); + } + + private void testV4SigningVerificationWithJcaKey() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + + byte[] data = Strings.toByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new JcaPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512) + .setProvider(new BouncyCastleProvider()); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new JcaPGPContentVerifierBuilderProvider() + .setProvider(new BouncyCastleProvider()); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testV4SigningVerificationWithBcKey() + throws PGPException + { + Date date = currentTimeRounded(); + Ed448KeyPairGenerator gen = new Ed448KeyPairGenerator(); + gen.init(new Ed448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + + byte[] data = Strings.toByteArray("Hello, World!\n"); + + PGPContentSignerBuilder contSigBuilder = new BcPGPContentSignerBuilder( + keyPair.getPublicKey().getAlgorithm(), + HashAlgorithmTags.SHA512); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator(contSigBuilder); + sigGen.init(PGPSignature.BINARY_DOCUMENT, keyPair.getPrivateKey()); + sigGen.update(data); + PGPSignature signature = sigGen.generate(); + + PGPContentVerifierBuilderProvider contVerBuilder = new BcPGPContentVerifierBuilderProvider(); + signature.init(contVerBuilder, keyPair.getPublicKey()); + signature.update(data); + isTrue(signature.verify()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, PGPException, InvalidAlgorithmParameterException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EDDSA", new BouncyCastleProvider()); + gen.initialize(new EdDSAParameterSpec("Ed448")); + KeyPair kp = gen.generateKeyPair(); + + JcaPGPKeyPair j1 = new JcaPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + Ed448KeyPairGenerator gen = new Ed448KeyPairGenerator(); + gen.init(new Ed448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + BcPGPKeyPair b1 = new BcPGPKeyPair(PublicKeyAlgorithmTags.EDDSA_LEGACY, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy Ed448 public key MUST be instanceof EdDSAPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof EdDSAPublicBCPGKey); + isTrue("Legacy Ed448 secret key MUST be instanceof EdSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof EdSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + + public static void main(String[] args) + { + runTest(new LegacyEd448KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyX25519KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyX25519KeyPairTest.java new file mode 100644 index 0000000000..e02d523c9f --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyX25519KeyPairTest.java @@ -0,0 +1,264 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.bouncycastle.bcpg.ECDHPublicBCPGKey; +import org.bouncycastle.bcpg.ECSecretBCPGKey; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.XDHParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPLiteralDataGenerator; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.Streams; + +public class LegacyX25519KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "LegacyX25519KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + testV4MessageEncryptionDecryptionWithJcaKey(); + testV4MessageEncryptionDecryptionWithBcKey(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.ECDH, kp, date); + isEquals("X25519 key size mismatch", 256, k.getPublicKey().getBitStrength()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, PGPException, InvalidAlgorithmParameterException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + + JcaPGPKeyPair j1 = new JcaPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + BcPGPKeyPair b1 = new BcPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X25519 public key MUST be instanceof ECDHPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X25519 secret key MUST be instanceof ECSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + + private void testV4MessageEncryptionDecryptionWithJcaKey() + throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException + { + BouncyCastleProvider provider = new BouncyCastleProvider(); + + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", provider); + gen.initialize(new XDHParameterSpec("X25519")); + KeyPair kp = gen.generateKeyPair(); + PGPKeyPair keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPDataEncryptorBuilder encBuilder = new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) + .setProvider(provider); + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + PublicKeyKeyEncryptionMethodGenerator metGen = new JcePublicKeyKeyEncryptionMethodGenerator(keyPair.getPublicKey()) + .setProvider(provider); + encGen.addMethod(metGen); + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = encGen.open(bOut, new byte[4096]); + OutputStream litOut = litGen.open(encOut, PGPLiteralData.BINARY, "", PGPLiteralData.NOW, new byte[4096]); + litOut.write(data); + litGen.close(); + encGen.close(); + + byte[] encrypted = bOut.toByteArray(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encrypted); + PGPObjectFactory objectFactory = new JcaPGPObjectFactory(bIn); + PGPEncryptedDataList encDataList = (PGPEncryptedDataList) objectFactory.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); + PublicKeyDataDecryptorFactory decFactory = new JcePublicKeyDataDecryptorFactoryBuilder() + .setProvider(provider) + .build(keyPair.getPrivateKey()); + InputStream decIn = encData.getDataStream(decFactory); + objectFactory = new JcaPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objectFactory.nextObject(); + InputStream litIn = lit.getDataStream(); + byte[] plaintext = Streams.readAll(litIn); + litIn.close(); + decIn.close(); + + isTrue(Arrays.areEqual(data, plaintext)); + } + + private void testV4MessageEncryptionDecryptionWithBcKey() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X25519KeyPairGenerator gen = new X25519KeyPairGenerator(); + gen.init(new X25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + BcPGPKeyPair keyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + + byte[] data = Strings.toUTF8ByteArray("Hello, World!\n"); + + PGPDataEncryptorBuilder encBuilder = new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256); + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encBuilder); + PublicKeyKeyEncryptionMethodGenerator metGen = new BcPublicKeyKeyEncryptionMethodGenerator(keyPair.getPublicKey()); + encGen.addMethod(metGen); + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + OutputStream encOut = encGen.open(bOut, new byte[4096]); + OutputStream litOut = litGen.open(encOut, PGPLiteralData.BINARY, "", PGPLiteralData.NOW, new byte[4096]); + litOut.write(data); + litGen.close(); + encGen.close(); + + byte[] encrypted = bOut.toByteArray(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encrypted); + PGPObjectFactory objectFactory = new BcPGPObjectFactory(bIn); + PGPEncryptedDataList encDataList = (PGPEncryptedDataList) objectFactory.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); + PublicKeyDataDecryptorFactory decFactory = new BcPublicKeyDataDecryptorFactory(keyPair.getPrivateKey()); + InputStream decIn = encData.getDataStream(decFactory); + objectFactory = new BcPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objectFactory.nextObject(); + InputStream litIn = lit.getDataStream(); + byte[] plaintext = Streams.readAll(litIn); + litIn.close(); + decIn.close(); + + isTrue(Arrays.areEqual(data, plaintext)); + } + + public static void main(String[] args) + { + runTest(new LegacyX25519KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyX448KeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyX448KeyPairTest.java new file mode 100644 index 0000000000..9d9a2df9a5 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/LegacyX448KeyPairTest.java @@ -0,0 +1,139 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.bcpg.*; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.generators.X448KeyPairGenerator; +import org.bouncycastle.crypto.params.X448KeyGenerationParameters; +import org.bouncycastle.jcajce.spec.XDHParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; + +import java.io.IOException; +import java.security.*; +import java.util.Date; + +public class LegacyX448KeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "LegacyX448KeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testConversionOfJcaKeyPair(); + testConversionOfBcKeyPair(); + + testBitStrength(); + } + + private void testBitStrength() + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, PGPException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X448")); + KeyPair kp = gen.generateKeyPair(); + JcaPGPKeyPair k = new JcaPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.ECDH, kp, date); + isEquals("X448 key size mismatch", 448, k.getPublicKey().getBitStrength()); + } + + private void testConversionOfJcaKeyPair() + throws NoSuchAlgorithmException, PGPException, InvalidAlgorithmParameterException, IOException + { + Date date = currentTimeRounded(); + KeyPairGenerator gen = KeyPairGenerator.getInstance("XDH", new BouncyCastleProvider()); + gen.initialize(new XDHParameterSpec("X448")); + KeyPair kp = gen.generateKeyPair(); + + JcaPGPKeyPair j1 = new JcaPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + byte[] pubEnc = j1.getPublicKey().getEncoded(); + byte[] privEnc = j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b1 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j2); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), b2.getPublicKey().getCreationTime().getTime()); + } + + private void testConversionOfBcKeyPair() + throws PGPException, IOException + { + Date date = currentTimeRounded(); + X448KeyPairGenerator gen = new X448KeyPairGenerator(); + gen.init(new X448KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + + BcPGPKeyPair b1 = new BcPGPKeyPair(PublicKeyAlgorithmTags.ECDH, kp, date); + byte[] pubEnc = b1.getPublicKey().getEncoded(); + byte[] privEnc = b1.getPrivateKey().getPrivateKeyDataPacket().getEncoded(); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + b1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + b1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j1 = toJcaKeyPair(b1); + isEncodingEqual(pubEnc, j1.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j1.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + j1.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + j1.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + BcPGPKeyPair b2 = toBcKeyPair(j1); + isEncodingEqual(pubEnc, b2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, b2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + b2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + b2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + JcaPGPKeyPair j2 = toJcaKeyPair(b2); + isEncodingEqual(pubEnc, j2.getPublicKey().getEncoded()); + isEncodingEqual(privEnc, j2.getPrivateKey().getPrivateKeyDataPacket().getEncoded()); + isTrue("Legacy X448 public key MUST be instanceof ECDHPublicBCPGKey", + j2.getPublicKey().getPublicKeyPacket().getKey() instanceof ECDHPublicBCPGKey); + isTrue("Legacy X448 secret key MUST be instanceof ECSecretBCPGKey", + j2.getPrivateKey().getPrivateKeyDataPacket() instanceof ECSecretBCPGKey); + + isEquals("Creation time is preserved", + date.getTime(), j2.getPublicKey().getCreationTime().getTime()); + } + + public static void main(String[] args) + { + runTest(new LegacyX448KeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/OpenPGPTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/OpenPGPTest.java index 7177a0cbd9..35918ab2a5 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/OpenPGPTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/OpenPGPTest.java @@ -19,9 +19,11 @@ import org.bouncycastle.bcpg.CompressionAlgorithmTags; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.sig.Features; import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.PreferredKeyServer; import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; @@ -458,6 +460,7 @@ public void operation() PGPSignatureSubpacketGenerator hashed = new PGPSignatureSubpacketGenerator(); hashed.addNotationData(false, true, "test@bouncycastle.org", "hashedNotation"); + hashed.setPreferredKeyServer(false, "www.testuri.com"); PGPSignatureSubpacketGenerator unhashed = new PGPSignatureSubpacketGenerator(); PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(PublicKeyAlgorithmTags.ECDSA, HashAlgorithmTags.SHA512); @@ -472,6 +475,10 @@ public void operation() PGPSignature signature = (PGPSignature)signatures.next(); isTrue(!signatures.hasNext()); + PreferredKeyServer pks = (PreferredKeyServer)signature.getHashedSubPackets().getSubpackets(SignatureSubpacketTags.PREFERRED_KEY_SERV)[0]; + isTrue(pks.getURI().equals("www.testuri.com")); + isTrue(pks.getRawURI().length == 15); + verifier = new PGPSignatureVerifierBuilder(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey).buildDirectKeyVerifier(signature, publicKey); isTrue(verifier.isVerified()); isTrue(verifier.getSignatureType() == PGPSignature.DIRECT_KEY); @@ -937,6 +944,7 @@ public void testPGPLiteralData() PGPEncryptedDataList encList = (PGPEncryptedDataList)pgpF.nextObject(); PGPPublicKeyEncryptedData encP = (PGPPublicKeyEncryptedData)encList.get(0); + isTrue((encP.getKeyIdentifier().getKeyId())==encP.getKeyID()); isEquals(encP.getAlgorithm(), 1); isEquals(encP.getVersion(), 3); PGPPrivateKey pgpPrivKey = pgpPriv.getSecretKey(encP.getKeyID()).extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass)); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorBcTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorBcTest.java index 88d85b1a2e..6e210590c3 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorBcTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorBcTest.java @@ -16,8 +16,11 @@ import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.crypto.Wrapper; @@ -25,8 +28,10 @@ import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.RFC3394WrapEngine; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; import org.bouncycastle.crypto.generators.HKDFBytesGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; import org.bouncycastle.crypto.params.HKDFParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; @@ -48,12 +53,20 @@ import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; import org.bouncycastle.openpgp.operator.PGPContentVerifier; +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.PGPDigestCalculator; import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcAEADSecretKeyEncryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.bc.BcPBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPBEKeyEncryptionMethodGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; @@ -98,16 +111,160 @@ public String getName() public void performTest() throws Exception { + testPGPKeyEncryptionMethodGenerator(); + testBcAEADSecretKeyEncryptorBuilder(); testX25519HKDF(); testKeyRings(); testBcPGPKeyPair(); -// testBcPGPDataEncryptorBuilder(); + testBcPGPDataEncryptorBuilder(); testBcPGPContentVerifierBuilderProvider(); - //testBcPBESecretKeyDecryptorBuilder(); + testBcPBESecretKeyDecryptorBuilder(); testBcKeyFingerprintCalculator(); testBcStandardDigests(); } + private void testPGPKeyEncryptionMethodGenerator() + throws Exception + { + v4PBEKeyEncryptionMethodGenerator(); + v5PBEKeyEncryptionMethodGenerator(); + v6PBEKeyEncryptionMethodGenerator(); + + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X448"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X25519"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "ECDH"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X448, "X448"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X25519, "X25519"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, "RSA"); + + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X448"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X25519"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "ECDH"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X448, "X448"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X25519, "X25519"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, "RSA"); + + } + + private void v3PublicKeyKeyEncryptionMethodGenerator(int publicKeyID, String algorithmName) + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(algorithmName, "BC"); + if (publicKeyID == PublicKeyAlgorithmTags.ECDH && algorithmName.equals("ECDH")) + { + kpGen.initialize(new ECNamedCurveGenParameterSpec("brainpoolP256r1")); + } + PGPKdfParameters parameters = null; + if (algorithmName.equals("X448")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + } + else if (algorithmName.equals("X25519")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); + } + PGPKeyPair pgpKeyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, publicKeyID, + parameters, kpGen.generateKeyPair(), new Date()); + + BcPublicKeyKeyEncryptionMethodGenerator methodGenerator = new BcPublicKeyKeyEncryptionMethodGenerator(pgpKeyPair.getPublicKey()); + int symAlgId = SymmetricKeyAlgorithmTags.CAST5; + BcPGPDataEncryptorBuilder v4 = new BcPGPDataEncryptorBuilder(symAlgId); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + PublicKeyEncSessionPacket packet = (PublicKeyEncSessionPacket)methodGenerator.generate(v4, sessionKey); + BcPublicKeyDataDecryptorFactory decryptorFactory = new BcPublicKeyDataDecryptorFactory(pgpKeyPair.getPrivateKey()); + byte[] data = decryptorFactory.recoverSessionData(publicKeyID, packet.getEncSessionKey(), PublicKeyEncSessionPacket.VERSION_3); + if (publicKeyID == PublicKeyAlgorithmTags.X448 || publicKeyID == PublicKeyAlgorithmTags.X25519) + { + isTrue(Arrays.areEqual(sessionKey, data)); + } + else + { + isTrue(Arrays.areEqual(sessionKey, Arrays.copyOfRange(data, 1, data.length - 2))); + } + } + + private void v6PublicKeyKeyEncryptionMethodGenerator(int publicKeyID, String algorithmName) + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(algorithmName, "BC"); + if (publicKeyID == PublicKeyAlgorithmTags.ECDH && algorithmName.equals("ECDH")) + { + kpGen.initialize(new ECNamedCurveGenParameterSpec("brainpoolP256r1")); + } + PGPKdfParameters parameters = null; + if (algorithmName.equals("X448")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + } + else if (algorithmName.equals("X25519")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); + } + PGPKeyPair pgpKeyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, publicKeyID, + parameters, kpGen.generateKeyPair(), new Date()); + + BcPublicKeyKeyEncryptionMethodGenerator methodGenerator = new BcPublicKeyKeyEncryptionMethodGenerator(pgpKeyPair.getPublicKey()); + + BcPGPDataEncryptorBuilder v6 = (BcPGPDataEncryptorBuilder)new BcPGPDataEncryptorBuilder(symAlgId).setUseV6AEAD().setWithAEAD(AEADAlgorithmTags.OCB, 8); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + PublicKeyEncSessionPacket packet = (PublicKeyEncSessionPacket)methodGenerator.generate(v6, sessionKey); + BcPublicKeyDataDecryptorFactory decryptorFactory = new BcPublicKeyDataDecryptorFactory(pgpKeyPair.getPrivateKey()); + byte[] data = decryptorFactory.recoverSessionData(publicKeyID, packet.getEncSessionKey(), PublicKeyEncSessionPacket.VERSION_6); + if (publicKeyID == PublicKeyAlgorithmTags.X448 || publicKeyID == PublicKeyAlgorithmTags.X25519) + { + isTrue(Arrays.areEqual(sessionKey, data)); + } + else + { + isTrue(Arrays.areEqual(sessionKey, Arrays.copyOfRange(data, 0, data.length - 2))); + } + } + + private void v4PBEKeyEncryptionMethodGenerator() + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + + BcPBEKeyEncryptionMethodGenerator methodGenerator = new BcPBEKeyEncryptionMethodGenerator("password".toCharArray()); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + BcPGPDataEncryptorBuilder v4 = new BcPGPDataEncryptorBuilder(symAlgId); + SymmetricKeyEncSessionPacket packet = (SymmetricKeyEncSessionPacket)methodGenerator.generate(v4, sessionKey); + BcPBEDataDecryptorFactory pbeDataDecryptorFactory = new BcPBEDataDecryptorFactory("password".toCharArray(), new BcPGPDigestCalculatorProvider()); + byte[] key = pbeDataDecryptorFactory.makeKeyFromPassPhrase(packet.getEncAlgorithm(), packet.getS2K()); + byte[] data = pbeDataDecryptorFactory.recoverSessionData(packet.getEncAlgorithm(), key, packet.getSecKeyData()); + isTrue(Arrays.areEqual(sessionKey, Arrays.copyOfRange(data, 1, data.length))); + } + + private void v5PBEKeyEncryptionMethodGenerator() + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + BcPBEKeyEncryptionMethodGenerator methodGenerator = new BcPBEKeyEncryptionMethodGenerator("password".toCharArray()); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + PGPDataEncryptorBuilder v5 = new BcPGPDataEncryptorBuilder(symAlgId).setUseV5AEAD().setWithAEAD(AEADAlgorithmTags.OCB, 10); + SymmetricKeyEncSessionPacket packet = (SymmetricKeyEncSessionPacket)methodGenerator.generate(v5, sessionKey); + BcPBEDataDecryptorFactory pbeDataDecryptorFactory = new BcPBEDataDecryptorFactory("password".toCharArray(), new BcPGPDigestCalculatorProvider()); + byte[] key = pbeDataDecryptorFactory.makeKeyFromPassPhrase(packet.getEncAlgorithm(), packet.getS2K()); + byte[] data = pbeDataDecryptorFactory.recoverAEADEncryptedSessionData(packet, key); + isTrue(Arrays.areEqual(sessionKey, data)); + } + + private void v6PBEKeyEncryptionMethodGenerator() + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + + BcPBEKeyEncryptionMethodGenerator methodGenerator = new BcPBEKeyEncryptionMethodGenerator("password".toCharArray()); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + PGPDataEncryptorBuilder v6 = new BcPGPDataEncryptorBuilder(symAlgId).setUseV6AEAD().setWithAEAD(AEADAlgorithmTags.OCB, 10); + SymmetricKeyEncSessionPacket packet = (SymmetricKeyEncSessionPacket)methodGenerator.generate(v6, sessionKey); + BcPBEDataDecryptorFactory pbeDataDecryptorFactory = new BcPBEDataDecryptorFactory("password".toCharArray(), new BcPGPDigestCalculatorProvider()); + byte[] key = pbeDataDecryptorFactory.makeKeyFromPassPhrase(packet.getEncAlgorithm(), packet.getS2K()); + byte[] data = pbeDataDecryptorFactory.recoverAEADEncryptedSessionData(packet, key); + isTrue(Arrays.areEqual(sessionKey, data)); + } + private void testBcStandardDigests() throws Exception { @@ -145,12 +302,13 @@ public void testBcKeyFingerprintCalculator() KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); kpGen.initialize(1024); KeyPair kp = kpGen.generateKeyPair(); + Date creationTime = new Date(1000 * (new Date().getTime() / 1000)); JcaPGPKeyConverter converter = new JcaPGPKeyConverter().setProvider(new BouncyCastleProvider()); - final PGPPublicKey pubKey = converter.getPGPPublicKey(PublicKeyAlgorithmTags.RSA_GENERAL, kp.getPublic(), new Date()); + final PGPPublicKey pubKey = converter.getPGPPublicKey(PublicKeyPacket.VERSION_4, PublicKeyAlgorithmTags.RSA_GENERAL, kp.getPublic(), creationTime); - PublicKeyPacket pubKeyPacket = new PublicKeyPacket(6, PublicKeyAlgorithmTags.RSA_GENERAL, new Date(), pubKey.getPublicKeyPacket().getKey()); - byte[] output = calculator.calculateFingerprint(new PublicKeyPacket(6, PublicKeyAlgorithmTags.RSA_GENERAL, new Date(), pubKey.getPublicKeyPacket().getKey())); + PublicKeyPacket pubKeyPacket = new PublicKeyPacket(6, PublicKeyAlgorithmTags.RSA_GENERAL, creationTime, pubKey.getPublicKeyPacket().getKey()); + byte[] output = calculator.calculateFingerprint(new PublicKeyPacket(6, PublicKeyAlgorithmTags.RSA_GENERAL, creationTime, pubKey.getPublicKeyPacket().getKey())); byte[] kBytes = pubKeyPacket.getEncodedContents(); SHA256Digest digest = new SHA256Digest(); @@ -167,24 +325,32 @@ public void testBcKeyFingerprintCalculator() digest.doFinal(digBuf, 0); isTrue(areEqual(output, digBuf)); - final PublicKeyPacket pubKeyPacket2 = new PublicKeyPacket(5, PublicKeyAlgorithmTags.RSA_GENERAL, new Date(), pubKey.getPublicKeyPacket().getKey()); - testException("Unsupported PGP key version: ", "UnsupportedPacketVersionException", new TestExceptionOperation() - { - @Override - public void operation() - throws Exception - { - calculator.calculateFingerprint(pubKeyPacket2); - } - }); + final PublicKeyPacket pubKeyPacket2 = new PublicKeyPacket(5, PublicKeyAlgorithmTags.RSA_GENERAL, creationTime, pubKey.getPublicKeyPacket().getKey()); + kBytes = pubKeyPacket2.getEncodedContents(); + output = calculator.calculateFingerprint(pubKeyPacket2); + + digest = new SHA256Digest(); + + digest.update((byte)0x9a); + + digest.update((byte)(kBytes.length >> 24)); + digest.update((byte)(kBytes.length >> 16)); + digest.update((byte)(kBytes.length >> 8)); + digest.update((byte)kBytes.length); + + digest.update(kBytes, 0, kBytes.length); + digBuf = new byte[digest.getDigestSize()]; + + digest.doFinal(digBuf, 0); + isTrue(areEqual(output, digBuf)); } -// public void testBcPBESecretKeyDecryptorBuilder() -// throws PGPException -// { -// final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(BcPGPDSAElGamalTest.pass); -// decryptor.recoverKeyData(SymmetricKeyAlgorithmTags.CAMELLIA_256, new byte[32], new byte[12], new byte[16], 0, 16); -// } + public void testBcPBESecretKeyDecryptorBuilder() + throws PGPException + { + final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(BcPGPDSAElGamalTest.pass); + decryptor.recoverKeyData(SymmetricKeyAlgorithmTags.CAMELLIA_256, new byte[32], new byte[12], new byte[16], 0, 16); + } public void testBcPGPContentVerifierBuilderProvider() throws Exception @@ -204,7 +370,6 @@ public void testBcPGPDataEncryptorBuilder() { testException("null cipher specified", "IllegalArgumentException", new TestExceptionOperation() { - @Override public void operation() throws Exception { @@ -214,7 +379,6 @@ public void operation() testException("AEAD algorithms can only be used with AES", "IllegalStateException", new TestExceptionOperation() { - @Override public void operation() throws Exception { @@ -224,7 +388,6 @@ public void operation() testException("minimum chunkSize is 6", "IllegalArgumentException", new TestExceptionOperation() { - @Override public void operation() throws Exception { @@ -234,7 +397,6 @@ public void operation() testException("invalid parameters:", "PGPException", new TestExceptionOperation() { - @Override public void operation() throws Exception { @@ -284,7 +446,6 @@ private void testCreateKeyPairDefault(int algorithm, String name) { testCreateKeyPair(algorithm, name, new KeyPairGeneratorOperation() { - @Override public void initialize(KeyPairGenerator gen) throws Exception { @@ -297,20 +458,18 @@ private void testCreateKeyPairDefault(int algorithm1, int algorithm2, String nam { testCreateKeyPair(algorithm1, algorithm2, name, new KeyPairGeneratorOperation() { - @Override public void initialize(KeyPairGenerator gen) throws Exception { } }); } - + private void testCreateKeyPairEC(int algorithm, String name, final String curveName) throws Exception { testCreateKeyPair(algorithm, name, new KeyPairGeneratorOperation() { - @Override public void initialize(KeyPairGenerator gen) throws Exception { @@ -381,6 +540,7 @@ private void testCreateKeyPair(int algorithm1, int algorithm2, String name, KeyP public void testKeyRings() throws Exception { + keyringTest("EdDSA", "Ed448", PublicKeyAlgorithmTags.EDDSA_LEGACY, "XDH", "X448", PublicKeyAlgorithmTags.ECDH, HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); keyringTest("EdDSA", "Ed448", PublicKeyAlgorithmTags.Ed448, "XDH", "X448", PublicKeyAlgorithmTags.X448, HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); keyringTest("EdDSA", "Ed25519", PublicKeyAlgorithmTags.EDDSA_LEGACY, "XDH", "X25519", PublicKeyAlgorithmTags.ECDH, HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); @@ -415,13 +575,13 @@ private void keyringTest(String algorithmName1, String ed_str, int ed_num, Strin edKp.initialize(new ECNamedCurveGenParameterSpec(ed_str)); - PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(ed_num, edKp.generateKeyPair(), new Date()); + PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, ed_num, edKp.generateKeyPair(), new Date()); KeyPairGenerator dhKp = KeyPairGenerator.getInstance(algorithmName2, "BC"); dhKp.initialize(new ECNamedCurveGenParameterSpec(x_str)); - PGPKeyPair dhKeyPair = new JcaPGPKeyPair(x_num, new PGPKdfParameters(hashAlgorithm, symmetricWrapAlgorithm), dhKp.generateKeyPair(), new Date()); + PGPKeyPair dhKeyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, x_num, new PGPKdfParameters(hashAlgorithm, symmetricWrapAlgorithm), dhKp.generateKeyPair(), new Date()); encryptDecryptTest(dhKeyPair.getPublicKey(), dhKeyPair.getPrivateKey()); encryptDecryptBcTest(dhKeyPair.getPublicKey(), dhKeyPair.getPrivateKey()); @@ -464,7 +624,7 @@ private void keyringTest(String algorithmName1, String ed_str, int ed_num, Strin { count++; sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), vKey); - + // TODO: appears to be failing on CI system if (!sig.verifyCertification(vKey, sKey)) { fail("failed to verify sub-key signature."); @@ -632,6 +792,40 @@ public void testX25519HKDF() isTrue(Arrays.areEqual(output, expectedDecryptedSessionKey)); } - + public void testBcAEADSecretKeyEncryptorBuilder() + throws Exception + { + Ed25519KeyPairGenerator gen = new Ed25519KeyPairGenerator(); + gen.init(new Ed25519KeyGenerationParameters(new SecureRandom())); + AsymmetricCipherKeyPair kp = gen.generateKeyPair(); + Date creationTime = new Date(); + SecureRandom random = new SecureRandom(); + int[] versions = {PublicKeyPacket.VERSION_4, PublicKeyPacket.VERSION_6}; + for (int i = 0; i != versions.length; i++) + { + int version = versions[i]; + PGPKeyPair keyPair = new BcPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + + BcAEADSecretKeyEncryptorBuilder bcEncBuilder = new BcAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, + S2K.Argon2Params.memoryConstrainedParameters()); + + bcEncBuilder.build( + "passphrase".toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket()); + PBESecretKeyEncryptor encryptor = bcEncBuilder.build( + "Yin".toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket()); + byte[] key = new byte[16]; + random.nextBytes(key); + byte[] input1 = new byte[64]; + random.nextBytes(input1); + + byte[] input2 = Arrays.copyOfRange(input1, 32, 64); + byte[] output1 = encryptor.encryptKeyData(key, input1, 32, 32); + byte[] output2 = encryptor.encryptKeyData(key, input2, 0, 32); + isTrue(Arrays.areEqual(output1, output2)); + } + } } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorJcajceTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorJcajceTest.java index 23e62ecb56..210df8bf84 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorJcajceTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/OperatorJcajceTest.java @@ -9,6 +9,7 @@ import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; +import java.security.SecureRandom; import java.security.Security; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; @@ -20,8 +21,11 @@ import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.S2K; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.SymmetricKeyEncSessionPacket; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; import org.bouncycastle.crypto.params.X25519PublicKeyParameters; @@ -30,17 +34,30 @@ import org.bouncycastle.jcajce.spec.HybridValueParameterSpec; import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.openpgp.PGPEncryptedData; +import org.bouncycastle.openpgp.PGPKdfParameters; +import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPUtil; +import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor; import org.bouncycastle.openpgp.operator.PGPContentVerifier; import org.bouncycastle.openpgp.operator.PGPDigestCalculator; import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcaAEADSecretKeyEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePBEKeyEncryptionMethodGenerator; import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; @@ -66,6 +83,8 @@ public String getName() public void performTest() throws Exception { + testPGPKeyEncryptionMethodGenerator(); + testJcaAEADSecretKeyEncryptorBuilder(); testCreateDigest(); testX25519HKDF(); testJcePBESecretKeyEncryptorBuilder(); @@ -76,6 +95,147 @@ public void performTest() testStandardDigests(); } + private void testPGPKeyEncryptionMethodGenerator() + throws Exception + { + v4PBEKeyEncryptionMethodGenerator(); + v5PBEKeyEncryptionMethodGenerator(); + v6PBEKeyEncryptionMethodGenerator(); + + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X448"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X25519"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "ECDH"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X448, "X448"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X25519, "X25519"); + v6PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, "RSA"); + + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X448"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "X25519"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.ECDH, "ECDH"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X448, "X448"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.X25519, "X25519"); + v3PublicKeyKeyEncryptionMethodGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, "RSA"); + + } + + private void v3PublicKeyKeyEncryptionMethodGenerator(int publicKeyID, String algorithmName) + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(algorithmName, "BC"); + if (publicKeyID == PublicKeyAlgorithmTags.ECDH && algorithmName.equals("ECDH")) + { + kpGen.initialize(new ECNamedCurveGenParameterSpec("P-256")); + } + PGPKdfParameters parameters = null; + if (algorithmName.equals("X448")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + } + else if (algorithmName.equals("X25519")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); + } + PGPKeyPair pgpKeyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, publicKeyID, + parameters, kpGen.generateKeyPair(), new Date()); + + JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator(pgpKeyPair.getPublicKey()); + int symAlgId = SymmetricKeyAlgorithmTags.CAST5; + JcePGPDataEncryptorBuilder v4 = new JcePGPDataEncryptorBuilder(symAlgId); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + PublicKeyEncSessionPacket packet = (PublicKeyEncSessionPacket)methodGenerator.generate(v4, sessionKey); + PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder().build(pgpKeyPair.getPrivateKey()); + byte[] data = decryptorFactory.recoverSessionData(publicKeyID, packet.getEncSessionKey(), PublicKeyEncSessionPacket.VERSION_3); + if (publicKeyID == PublicKeyAlgorithmTags.X448 || publicKeyID == PublicKeyAlgorithmTags.X25519) + { + isTrue(Arrays.areEqual(sessionKey, data)); + } + else + { + isTrue(Arrays.areEqual(sessionKey, Arrays.copyOfRange(data, 1, data.length - 2))); + } + } + + private void v6PublicKeyKeyEncryptionMethodGenerator(int publicKeyID, String algorithmName) + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(algorithmName, "BC"); + if (publicKeyID == PublicKeyAlgorithmTags.ECDH && algorithmName.equals("ECDH")) + { + kpGen.initialize(new ECNamedCurveGenParameterSpec("P-256")); + } + PGPKdfParameters parameters = null; + if (algorithmName.equals("X448")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); + } + else if (algorithmName.equals("X25519")) + { + parameters = new PGPKdfParameters(HashAlgorithmTags.SHA512, SymmetricKeyAlgorithmTags.AES_256); + } + PGPKeyPair pgpKeyPair = new JcaPGPKeyPair(PublicKeyPacket.VERSION_4, publicKeyID, + parameters, kpGen.generateKeyPair(), new Date()); + + JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator(pgpKeyPair.getPublicKey()); + + JcePGPDataEncryptorBuilder v6 = new JcePGPDataEncryptorBuilder(symAlgId).setUseV6AEAD().setWithAEAD(AEADAlgorithmTags.OCB, 8); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + PublicKeyEncSessionPacket packet = (PublicKeyEncSessionPacket)methodGenerator.generate(v6, sessionKey); + PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder().build(pgpKeyPair.getPrivateKey()); + byte[] data = decryptorFactory.recoverSessionData(publicKeyID, packet.getEncSessionKey(), PublicKeyEncSessionPacket.VERSION_6); + if (publicKeyID == PublicKeyAlgorithmTags.X448 || publicKeyID == PublicKeyAlgorithmTags.X25519) + { + isTrue(Arrays.areEqual(sessionKey, data)); + } + else + { + isTrue(Arrays.areEqual(sessionKey, Arrays.copyOfRange(data, 0, data.length - 2))); + } + } + + private void v4PBEKeyEncryptionMethodGenerator() + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + + JcePBEKeyEncryptionMethodGenerator methodGenerator = new JcePBEKeyEncryptionMethodGenerator("password".toCharArray()); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + JcePGPDataEncryptorBuilder v4 = new JcePGPDataEncryptorBuilder(symAlgId); + SymmetricKeyEncSessionPacket packet = (SymmetricKeyEncSessionPacket)methodGenerator.generate(v4, sessionKey); + PBEDataDecryptorFactory pbeDataDecryptorFactory = new JcePBEDataDecryptorFactoryBuilder().build("password".toCharArray()); + byte[] key = pbeDataDecryptorFactory.makeKeyFromPassPhrase(packet.getEncAlgorithm(), packet.getS2K()); + byte[] data = pbeDataDecryptorFactory.recoverSessionData(packet.getEncAlgorithm(), key, packet.getSecKeyData()); + isTrue(Arrays.areEqual(sessionKey, Arrays.copyOfRange(data, 1, data.length))); + } + + private void v5PBEKeyEncryptionMethodGenerator() + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + JcePBEKeyEncryptionMethodGenerator methodGenerator = new JcePBEKeyEncryptionMethodGenerator("password".toCharArray()); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + JcePGPDataEncryptorBuilder v5 = new JcePGPDataEncryptorBuilder(symAlgId).setUseV5AEAD().setWithAEAD(AEADAlgorithmTags.OCB, 10); + SymmetricKeyEncSessionPacket packet = (SymmetricKeyEncSessionPacket)methodGenerator.generate(v5, sessionKey); + PBEDataDecryptorFactory pbeDataDecryptorFactory = new JcePBEDataDecryptorFactoryBuilder().build("password".toCharArray()); + byte[] key = pbeDataDecryptorFactory.makeKeyFromPassPhrase(packet.getEncAlgorithm(), packet.getS2K()); + byte[] data = pbeDataDecryptorFactory.recoverAEADEncryptedSessionData(packet, key); + isTrue(Arrays.areEqual(sessionKey, data)); + } + + private void v6PBEKeyEncryptionMethodGenerator() + throws Exception + { + int symAlgId = SymmetricKeyAlgorithmTags.CAMELLIA_128; + + JcePBEKeyEncryptionMethodGenerator methodGenerator = new JcePBEKeyEncryptionMethodGenerator("password".toCharArray()); + byte[] sessionKey = PGPUtil.makeRandomKey(symAlgId, new SecureRandom()); + JcePGPDataEncryptorBuilder v6 = new JcePGPDataEncryptorBuilder(symAlgId).setUseV6AEAD().setWithAEAD(AEADAlgorithmTags.OCB, 10); + SymmetricKeyEncSessionPacket packet = (SymmetricKeyEncSessionPacket)methodGenerator.generate(v6, sessionKey); + PBEDataDecryptorFactory pbeDataDecryptorFactory = new JcePBEDataDecryptorFactoryBuilder().build("password".toCharArray()); + byte[] key = pbeDataDecryptorFactory.makeKeyFromPassPhrase(packet.getEncAlgorithm(), packet.getS2K()); + byte[] data = pbeDataDecryptorFactory.recoverAEADEncryptedSessionData(packet, key); + isTrue(Arrays.areEqual(sessionKey, data)); + } private void testStandardDigests() throws Exception { @@ -207,6 +367,20 @@ public void operation() public void testJcaPGPDigestCalculatorProviderBuilder() throws Exception { + + PGPDigestCalculatorProvider digCalcBldr = new JcaPGPDigestCalculatorProviderBuilder().setProvider(new NonDashProvider()).build(); + testDigestCalc(digCalcBldr.get(HashAlgorithmTags.SHA256), Hex.decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")); + + PGPDigestCalculatorProvider digCalcBldr2 = new JcaPGPDigestCalculatorProviderBuilder().setProvider(new DashProvider()).build(); + testDigestCalc(digCalcBldr2.get(HashAlgorithmTags.SHA256), Hex.decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")); + + PGPDigestCalculatorProvider digCalcBldr3 = new JcaPGPDigestCalculatorProviderBuilder().setProvider(new NonDashProvider()).build(); + testDigestCalc(digCalcBldr3.get(HashAlgorithmTags.SHA1), Hex.decode("a9993e364706816aba3e25717850c26c9cd0d89d")); + + PGPDigestCalculatorProvider digCalcBldr4 = new JcaPGPDigestCalculatorProviderBuilder().setProvider(new DashProvider()).build(); + testDigestCalc(digCalcBldr4.get(HashAlgorithmTags.SHA1), Hex.decode("a9993e364706816aba3e25717850c26c9cd0d89d")); + + final PGPDigestCalculatorProvider provider = new JcaPGPDigestCalculatorProviderBuilder().setProvider(new NullProvider()).build(); testException("exception on setup: ", "PGPException", new TestExceptionOperation() { @@ -302,12 +476,66 @@ public void testX25519HKDF() //isTrue(Arrays.areEqual(output, expectedDecryptedSessionKey)); } - private class NullProvider + public void testJcaAEADSecretKeyEncryptorBuilder() + throws Exception + { + BouncyCastleProvider prov = new BouncyCastleProvider(); + KeyPairGenerator eddsaGen = KeyPairGenerator.getInstance("EdDSA", prov); + Date creationTime = new Date(); + eddsaGen.initialize(new ECNamedCurveGenParameterSpec("ed25519")); + KeyPair kp = eddsaGen.generateKeyPair(); + SecureRandom random = new SecureRandom(); + for (int version : new int[]{PublicKeyPacket.VERSION_4, PublicKeyPacket.VERSION_6}) + { + PGPKeyPair keyPair = new JcaPGPKeyPair(version, PublicKeyAlgorithmTags.Ed25519, kp, creationTime); + JcaAEADSecretKeyEncryptorBuilder jcaEncBuilder = new JcaAEADSecretKeyEncryptorBuilder( + AEADAlgorithmTags.OCB, SymmetricKeyAlgorithmTags.AES_256, + S2K.Argon2Params.memoryConstrainedParameters()) + .setProvider(new BouncyCastleProvider()); + PBESecretKeyEncryptor encryptor = jcaEncBuilder.build( + "Yin".toCharArray(), + keyPair.getPublicKey().getPublicKeyPacket()); + byte[] key = new byte[16]; + random.nextBytes(key); + byte[] input1 = new byte[64]; + random.nextBytes(input1); + + byte[] input2 = Arrays.copyOfRange(input1, 32, 64); + byte[] output1 = encryptor.encryptKeyData(key, input1, 32, 32); + byte[] output2 = encryptor.encryptKeyData(key, input2, 0, 32); + isTrue(Arrays.areEqual(output1, output2)); + } + } + + private static final class NullProvider extends Provider { NullProvider() { - super("NULL", 0.0, "Null Provider"); + super("NULL", 0.0, "Null Provider"); + } + } + + private static final class NonDashProvider + extends Provider + { + NonDashProvider() + { + super("NonDash", 0.0, "NonDash Provider"); + putService(new Provider.Service(this, "MessageDigest", "SHA256", "org.bouncycastle.openpgp.test.SHA256", null, null)); + putService(new Provider.Service(this, "MessageDigest", "SHA1", "org.bouncycastle.openpgp.test.SHA1", null, null)); } } + + private static final class DashProvider + extends Provider + { + DashProvider() + { + super("Dash", 0.0, "Dash Provider"); + putService(new Service(this, "MessageDigest", "SHA-256", "org.bouncycastle.openpgp.test.SHA256", null, null)); + putService(new Service(this, "MessageDigest", "SHA-1", "org.bouncycastle.openpgp.test.SHA1", null, null)); + } + } + } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPAeadTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPAeadTest.java index 5eaca50e3a..c74b81dcfd 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPAeadTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPAeadTest.java @@ -46,9 +46,7 @@ import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Exceptions; -import org.bouncycastle.util.Pack; import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.io.Streams; import org.bouncycastle.util.test.SimpleTest; @@ -174,11 +172,9 @@ private void knownV5TestVectorDecryptionTests() throws IOException, PGPException { // test known-good V5 test vectors - System.out.println("Test V5 BC Decryption"); testBcDecryption(V5_EAX_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testBcDecryption(V5_OCB_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testBcDecryption(V5_GCM_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); - System.out.println("Test V5 JCA Decryption"); testJceDecryption(V5_EAX_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testJceDecryption(V5_OCB_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testJceDecryption(V5_GCM_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); @@ -187,12 +183,10 @@ private void knownV5TestVectorDecryptionTests() private void knownV6TestVectorDecryptionTests() throws IOException, PGPException { - // Test known-good V6 test vectors TODO: decryption tests should be working... - System.out.println("Test V6 BC Decryption"); + // Test known-good V6 test vectors TODO: decryption tests testBcDecryption(V6_EAX_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testBcDecryption(V6_OCB_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testBcDecryption(V6_GCM_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); - System.out.println("Test V6 JCA Decryption"); testJceDecryption(V6_EAX_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testJceDecryption(V6_OCB_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); testJceDecryption(V6_GCM_PACKET_SEQUENCE, PASSWORD, PLAINTEXT); @@ -201,36 +195,28 @@ private void knownV6TestVectorDecryptionTests() private void testBcRoundTrip(boolean v5AEAD, int aeadAlg, int symAlg, byte[] plaintext, char[] password) throws PGPException, IOException { - System.out.println("Test BC RoundTrip " + (v5AEAD ? "V5" : "V6") + " " + algNames(aeadAlg, symAlg)); String armored = testBcEncryption(v5AEAD, aeadAlg, symAlg, plaintext, password); - System.out.println(armored); testBcDecryption(armored, password, plaintext); } private void testJceRoundTrip(boolean v5AEAD, int aeadAlg, int symAlg, byte[] plaintext, char[] password) throws PGPException, IOException { - System.out.println("Test JCE RoundTrip " + (v5AEAD ? "V5" : "V6") + " " + algNames(aeadAlg, symAlg)); String armored = testJceEncryption(v5AEAD, aeadAlg, symAlg, plaintext, password); - System.out.println(armored); testJceDecryption(armored, password, plaintext); } private void testBcJceRoundTrip(boolean v5AEAD, int aeadAlg, int symAlg, byte[] plaintext, char[] password) throws PGPException, IOException { - System.out.println("Test BC encrypt, JCE decrypt " + (v5AEAD ? "V5" : "V6") + " " + algNames(aeadAlg, symAlg)); String armored = testBcEncryption(v5AEAD, aeadAlg, symAlg, plaintext, password); - System.out.println(armored); testJceDecryption(armored, password, plaintext); } private void testJceBcRoundTrip(boolean v5AEAD, int aeadAlg, int symAlg, byte[] plaintext, char[] password) throws PGPException, IOException { - System.out.println("Test JCE encrypt, BC decrypt " + (v5AEAD ? "V5" : "V6") + " " + algNames(aeadAlg, symAlg)); String armored = testJceEncryption(v5AEAD, aeadAlg, symAlg, plaintext, password); - System.out.println(armored); testBcDecryption(armored, password, plaintext); } @@ -365,7 +351,9 @@ private void testBcDecryption(String armoredMessage, char[] password, byte[] exp if (o != null) { + // -DM System.out.println System.out.println("Unexpected trailing packet."); + // -DM System.out.println System.out.println(o); } } @@ -421,7 +409,9 @@ private void testJceDecryption(String armoredMessage, char[] password, byte[] ex if (o != null) { + // -DM System.out.println System.out.println("Unexpected trailing packet."); + // -DM System.out.println System.out.println(o); } } @@ -435,30 +425,8 @@ private void testJceDecryption(String armoredMessage, char[] password, byte[] ex public static void printHex(byte[] bytes) { - boolean separate = true; - boolean prefix = true; - String hex = Hex.toHexString(bytes); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < hex.length() / 2; i++) - { - if (prefix && i % 8 == 0) - { - sb.append("0x").append(Hex.toHexString(Pack.intToBigEndian(i & 0xFFFFF))).append(" "); - } - sb.append(hex.substring(i * 2, i * 2 + 2)); - if (separate) - { - if ((i + 1) % 8 == 0) - { - sb.append('\n'); - } - else - { - sb.append(' '); - } - } - } - System.out.println(sb); + // -DM System.out.println + //System.out.println(DumpUtil.hexdump(bytes)); } private static String algNames(int aeadAlg, int symAlg) diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java index 9ebbaa938b..ede5ecdb15 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java @@ -409,7 +409,8 @@ private void edDsaTest() PGPPublicKeyRing pubKeyRing = new PGPPublicKeyRing(aIn, new JcaKeyFingerprintCalculator()); - isTrue(areEqual(Hex.decode("6234 6350 CAE2 433E 2400 1D72 94FA 62C3 6481 AE34"), pubKeyRing.getPublicKey().getFingerprint())); + isTrue(areEqual(pubKeyRing.getPublicKey().getFingerprint(), Hex.decode("6234 6350 CAE2 433E 2400 1D72 94FA 62C3 6481 AE34"))); + isTrue(pubKeyRing.getPublicKey().hasFingerprint(Hex.decode("6234 6350 CAE2 433E 2400 1D72 94FA 62C3 6481 AE34"))); aIn = new ArmoredInputStream(new ByteArrayInputStream(Strings.toByteArray(edDsaSignedMessage))); @@ -473,7 +474,8 @@ private void edDsaBcTest() PGPPublicKeyRing pubKeyRing = new PGPPublicKeyRing(aIn, new BcKeyFingerprintCalculator()); - isTrue(areEqual(Hex.decode("6234 6350 CAE2 433E 2400 1D72 94FA 62C3 6481 AE34"), pubKeyRing.getPublicKey().getFingerprint())); + isTrue(areEqual(pubKeyRing.getPublicKey().getFingerprint(), Hex.decode("6234 6350 CAE2 433E 2400 1D72 94FA 62C3 6481 AE34"))); + isTrue(pubKeyRing.getPublicKey().hasFingerprint(Hex.decode("6234 6350 CAE2 433E 2400 1D72 94FA 62C3 6481 AE34"))); aIn = new ArmoredInputStream(new ByteArrayInputStream(Strings.toByteArray(edDsaSignedMessage))); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPEdDSATest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPEdDSATest.java index 645841f825..3864c5b614 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPEdDSATest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPEdDSATest.java @@ -412,7 +412,8 @@ public void performTest() PGPPublicKeyRing pubKeyRing = new PGPPublicKeyRing(aIn, new JcaKeyFingerprintCalculator()); - isTrue(areEqual(Hex.decode("EB85 BB5F A33A 75E1 5E94 4E63 F231 550C 4F47 E38E"), pubKeyRing.getPublicKey().getFingerprint())); + isTrue(areEqual(pubKeyRing.getPublicKey().getFingerprint(), Hex.decode("EB85 BB5F A33A 75E1 5E94 4E63 F231 550C 4F47 E38E"))); + isTrue(pubKeyRing.getPublicKey().hasFingerprint(Hex.decode("EB85 BB5F A33A 75E1 5E94 4E63 F231 550C 4F47 E38E"))); aIn = new ArmoredInputStream(new ByteArrayInputStream(Strings.toByteArray(edDSASecretKey))); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPGeneralTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPGeneralTest.java index 3cb72e6c8a..afd421d860 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPGeneralTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPGeneralTest.java @@ -13,6 +13,7 @@ import java.util.Date; import java.util.Iterator; import java.util.List; +import java.util.Collection; import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.ArmoredInputStream; @@ -25,15 +26,19 @@ import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.RSAPublicBCPGKey; import org.bouncycastle.bcpg.RSASecretBCPGKey; +import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.attr.ImageAttribute; +import org.bouncycastle.bcpg.sig.Exportable; import org.bouncycastle.bcpg.sig.Features; import org.bouncycastle.bcpg.sig.IntendedRecipientFingerprint; import org.bouncycastle.bcpg.sig.KeyFlags; import org.bouncycastle.bcpg.sig.NotationData; import org.bouncycastle.bcpg.sig.PolicyURI; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; import org.bouncycastle.bcpg.sig.RegularExpression; +import org.bouncycastle.bcpg.sig.Revocable; import org.bouncycastle.bcpg.sig.RevocationKey; import org.bouncycastle.bcpg.sig.RevocationKeyTags; import org.bouncycastle.bcpg.sig.RevocationReason; @@ -102,7 +107,7 @@ import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; -import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Objects; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.test.SimpleTest; @@ -1005,6 +1010,7 @@ public void performTest() // Tests for PGPSignatureSubpacketVector sigsubpacketTest(); + sigsubpacketTest2(); testParsingFromSignature(); testPGPSignatureSubpacketVector(); @@ -1094,6 +1100,8 @@ public void testPGPPublicKey() PGPPublicKey publicKey7 = PGPPublicKey.join(publicKey2, publicKey2, true, true); isTrue(publicKey7.getKeyID() == publicKey2.getKeyID()); isTrue(areEqual(publicKey7.getFingerprint(), publicKey2.getFingerprint())); + isTrue(publicKey7.hasFingerprint(publicKey2.getFingerprint())); + isTrue(publicKey2.hasFingerprint(publicKey7.getFingerprint())); PGPPublicKeyRingCollection pgpRingCollection = new JcaPGPPublicKeyRingCollection(probExpPubKey); final long id5 = 6556488621521814541L; @@ -1105,6 +1113,8 @@ public void testPGPPublicKey() PGPPublicKey publicKey6 = PGPPublicKey.join(publicKey5, publicKey5, true, true); isTrue(publicKey6.getKeyID() == publicKey5.getKeyID()); isTrue(areEqual(publicKey6.getFingerprint(), publicKey5.getFingerprint())); + isTrue(publicKey6.hasFingerprint(publicKey5.getFingerprint())); + isTrue(publicKey5.hasFingerprint(publicKey6.getFingerprint())); } private boolean messageIs(String message, String s) @@ -1921,9 +1931,12 @@ private void sigsubpacketTest() PGPSignatureSubpacketGenerator svg = new PGPSignatureSubpacketGenerator(); - int[] aeadAlgs = new int[]{AEADAlgorithmTags.EAX, - AEADAlgorithmTags.OCB, AEADAlgorithmTags.GCM, AEADAlgorithmTags.GCM}; - svg.setPreferredAEADAlgorithms(true, aeadAlgs); + PreferredAEADCiphersuites.Builder builder = PreferredAEADCiphersuites.builder(true); + builder.addCombination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.EAX) + .addCombination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB) + .addCombination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.GCM) + .addCombination(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.GCM); + svg.setPreferredAEADCiphersuites(builder); svg.setFeature(true, Features.FEATURE_MODIFICATION_DETECTION); svg.setKeyFlags(true, KeyFlags.CERTIFY_OTHER + KeyFlags.SIGN_DATA); PGPSignatureSubpacketVector hashedPcks = svg.generate(); @@ -1955,7 +1968,71 @@ sgnKeyPair, identity, new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags. { PGPSignature sig = (PGPSignature)sit.next(); PGPSignatureSubpacketVector v = sig.getHashedSubPackets(); - if (!Arrays.areEqual(v.getPreferredAEADAlgorithms(), aeadAlgs)) + if (!Objects.areEqual(v.getPreferredAEADCiphersuites(), builder.build())) + { + fail("preferred aead algs don't match"); + } + } + } + } + } + + private void sigsubpacketTest2() + throws Exception + { + char[] passPhrase = "test".toCharArray(); + String identity = "TEST "; + Date date = new Date(); + + RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); + kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x11), new SecureRandom(), 2048, 25)); + AsymmetricCipherKeyPair kpSgn = kpg.generateKeyPair(); + AsymmetricCipherKeyPair kpEnc = kpg.generateKeyPair(); + + PGPKeyPair sgnKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpSgn, date); + PGPKeyPair encKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_GENERAL, kpEnc, date); + + PGPSignatureSubpacketGenerator svg = new PGPSignatureSubpacketGenerator(); + + PreferredAEADCiphersuites.Combination[] combinations = new PreferredAEADCiphersuites.Combination[]{ + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.EAX), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.GCM), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.GCM) + }; + svg.setPreferredAEADCiphersuites(true, combinations); + svg.setFeature(true, Features.FEATURE_MODIFICATION_DETECTION); + svg.setKeyFlags(true, KeyFlags.CERTIFY_OTHER + KeyFlags.SIGN_DATA); + PGPSignatureSubpacketVector hashedPcks = svg.generate(); + + PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, + sgnKeyPair, identity, new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), + hashedPcks, null, new BcPGPContentSignerBuilder(PGPPublicKey.RSA_GENERAL, HashAlgorithmTags.SHA1), new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).build(passPhrase)); + + svg = new PGPSignatureSubpacketGenerator(); + svg.setKeyExpirationTime(true, 2L); + svg.setKeyFlags(true, KeyFlags.ENCRYPT_COMMS + KeyFlags.ENCRYPT_STORAGE); + svg.setPrimaryUserID(true, false); + svg.setFeature(true, Features.FEATURE_MODIFICATION_DETECTION); + hashedPcks = svg.generate(); + + keyRingGen.addSubKey(encKeyPair, hashedPcks, null); + + byte[] encodedKeyRing = keyRingGen.generatePublicKeyRing().getEncoded(); + + PGPPublicKeyRing keyRing = new PGPPublicKeyRing(encodedKeyRing, new BcKeyFingerprintCalculator()); + + for (Iterator it = keyRing.getPublicKeys(); it.hasNext(); ) + { + PGPPublicKey pKey = (PGPPublicKey)it.next(); + + if (!pKey.isEncryptionKey()) + { + for (Iterator sit = pKey.getSignatures(); sit.hasNext(); ) + { + PGPSignature sig = (PGPSignature)sit.next(); + PGPSignatureSubpacketVector v = sig.getHashedSubPackets(); + if (!Objects.areEqual(v.getPreferredAEADCiphersuites(), new PreferredAEADCiphersuites(true, combinations))) { fail("preferred aead algs don't match"); } @@ -2027,7 +2104,7 @@ public void testPGPSignatureSubpacketVector() PGPSignatureSubpacketVector hashedPcks = sig.getHashedSubPackets(); IntendedRecipientFingerprint[] intFig = hashedPcks.getIntendedRecipientFingerprints(); - isTrue("mismatch on intended rec. fingerprint", Arrays.areEqual(secretKey.getPublicKey().getFingerprint(), intFig[0].getFingerprint())); + isTrue("mismatch on intended rec. fingerprint", secretKey.getPublicKey().hasFingerprint(intFig[0].getFingerprint())); // Tests for null value isTrue("issuer key id should be 0", hashedPcks.getIssuerKeyID() == 0); @@ -2049,6 +2126,7 @@ public void testPGPSignatureSubpacketVector() isTrue("RevocationReason should be null", hashedPcks.getRevocationReason() == null); isTrue("Trust should be null", hashedPcks.getTrust() == null); isTrue(hashedPcks.getIntendedRecipientFingerprint().getKeyVersion() == publicKey.getVersion()); + isTrue(hashedPcks.getPreferredLibrePgpEncryptionModes() == null); String regexString = "example.org"; RegularExpression regex = new RegularExpression(false, regexString); @@ -2080,7 +2158,7 @@ public void testPGPSignatureSubpacketVector() isTrue("Revocable should be false", !hashedPcks.isRevocable()); isTrue("RevocationKeys should not be empty", hashedPcks.getRevocationKeys().length == 1); RevocationKey revocationKey = hashedPcks.getRevocationKeys()[0]; - isTrue(areEqual(revocationKey.getFingerprint(), publicKey.getFingerprint())); + isTrue(publicKey.hasFingerprint(revocationKey.getFingerprint())); isTrue(revocationKey.getAlgorithm() == PublicKeyAlgorithmTags.DSA); // TODO: addRevocationKey has no parameter for setting signatureClass isTrue(revocationKey.getSignatureClass() == RevocationKeyTags.CLASS_DEFAULT); @@ -2093,37 +2171,58 @@ public void testPGPSignatureSubpacketVector() isTrue("Trust should be null", trustSignature != null); isTrue("Trust level depth should be " + depth, trustSignature.getDepth() == depth); isTrue("Trust amount should be " + trustAmount, trustSignature.getTrustAmount() == trustAmount); - isTrue("Exporable should be false", !hashedPcks.isExportable()); + isTrue("Exportable should be false", !hashedPcks.isExportable()); isTrue(hashedPcks.getIssuerFingerprint().getKeyVersion() == publicKey.getVersion()); isTrue("isPrimaryUserID should be true", hashedPcks.isPrimaryUserID()); + hashedPcks = PGPSignatureSubpacketVector.fromSubpackets(java.util.Arrays.asList(hashedPcks.toArray())); - PGPSignatureSubpacketVector hashedPcks2 = PGPSignatureSubpacketVector.fromSubpackets(null); + isTrue("IntendedRecipientFingerprint should not be null", hashedPcks.getIntendedRecipientFingerprint() == null); + isTrue("RegularExpression should not be null", hashedPcks.getRegularExpression() != null); + isTrue("RegularExpressions should be empty", hashedPcks.getRegularExpressions().length == 2); + isTrue("Revocable should not be null", hashedPcks.getRevocable() != null); + isTrue("Revocable should be false", !hashedPcks.isRevocable()); + isTrue("RevocationKeys should not be empty", hashedPcks.getRevocationKeys().length == 1); + revocationKey = hashedPcks.getRevocationKeys()[0]; + isTrue(publicKey.hasFingerprint(revocationKey.getFingerprint())); + isTrue(revocationKey.getAlgorithm() == PublicKeyAlgorithmTags.DSA); + // TODO: addRevocationKey has no parameter for setting signatureClass + isTrue(revocationKey.getSignatureClass() == RevocationKeyTags.CLASS_DEFAULT); + isTrue("IssuerKeyID should not be 0", hashedPcks.getIssuerKeyID() != 0L); + revocationReason = hashedPcks.getRevocationReason(); + isTrue("RevocationReason should not be null", revocationReason != null); + isTrue(revocationReason.getRevocationReason() == RevocationReasonTags.KEY_SUPERSEDED); + isTrue(revocationReason.getRevocationDescription().equals(description)); + trustSignature = hashedPcks.getTrust(); + isTrue("Trust should be null", trustSignature != null); + isTrue("Trust level depth should be " + depth, trustSignature.getDepth() == depth); + isTrue("Trust amount should be " + trustAmount, trustSignature.getTrustAmount() == trustAmount); + isTrue("Exportable should be false", !hashedPcks.isExportable()); + isTrue(hashedPcks.getIssuerFingerprint().getKeyVersion() == publicKey.getVersion()); + isTrue("isPrimaryUserID should be true", hashedPcks.isPrimaryUserID()); + + + PGPSignatureSubpacketVector hashedPcks2 = PGPSignatureSubpacketVector.fromSubpackets((SignatureSubpacket[])null); + isTrue("Empty PGPSignatureSubpacketVector", hashedPcks2.size() == 0); + hashedPcks2 = PGPSignatureSubpacketVector.fromSubpackets((Collection)null); isTrue("Empty PGPSignatureSubpacketVector", hashedPcks2.size() == 0); hashedGen = new PGPSignatureSubpacketGenerator(); hashedGen.setExportable(false, true); - try - { - hashedGen.setExportable(false, false); - fail("Duplicated settings for Exportable"); - } - catch (IllegalStateException e) - { - isTrue("Exportable Certification exists in the Signature Subpacket Generator", - messageIs(e.getMessage(), "Exportable Certification exists in the Signature Subpacket Generator")); - } + hashedGen.setExportable(false, false); + isEquals("Calling setExportable multiple times MUST NOT introduce duplicates", + 1, hashedGen.getSubpackets(SignatureSubpacketTags.EXPORTABLE).length); + Exportable exportable = (Exportable) hashedGen.getSubpackets(SignatureSubpacketTags.EXPORTABLE)[0]; + isTrue("Last invocation of setExportable MUST take precedence.", + !exportable.isExportable()); + hashedGen.setRevocable(false, true); - try - { - hashedGen.setRevocable(false, false); - fail("Duplicated settings for Revocable"); - } - catch (IllegalStateException e) - { - isTrue("Revocable exists in the Signature Subpacket Generator", - messageIs(e.getMessage(), "Revocable exists in the Signature Subpacket Generator")); - } + hashedGen.setRevocable(false, false); + isEquals("Calling setRevocable multiple times MUST NOT introduce duplicates.", + 1, hashedGen.getSubpackets(SignatureSubpacketTags.REVOCABLE).length); + Revocable revocable = (Revocable) hashedGen.getSubpackets(SignatureSubpacketTags.REVOCABLE)[0]; + isTrue("Last invocation of setRevocable MUST take precedence.", + !revocable.isRevocable()); try { @@ -2169,13 +2268,13 @@ public void testPGPSignatureSubpacketVector() hashedPcks = sig.getHashedSubPackets(); isTrue("URL should be " + url, hashedPcks.getPolicyURI().getURI().equals(url)); isTrue(areEqual(hashedPcks.getPolicyURI().getRawURI(), Strings.toUTF8ByteArray(url))); - isTrue("Exporable should be true", hashedPcks.isExportable()); - isTrue("Test Singner User ID", hashedPcks.getSignerUserID().equals("")); + isTrue("Exportable should be false", !hashedPcks.isExportable()); + isTrue("Test Signer User ID", hashedPcks.getSignerUserID().equals("")); isTrue("Test for empty description", hashedPcks.getRevocationReason().getRevocationDescription().equals("")); Features features = hashedPcks.getFeatures(); isTrue(features.supportsSEIPDv2()); isTrue(features.getFeatures() == Features.FEATURE_SEIPD_V2); - isTrue(hashedPcks.getRevocable().isRevocable()); + isTrue("Revocable should be false", !hashedPcks.getRevocable().isRevocable()); } public void testECNistCurves() diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyPairGeneratorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyPairGeneratorTest.java new file mode 100644 index 0000000000..a0f71064f0 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyPairGeneratorTest.java @@ -0,0 +1,569 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.asn1.sec.SECObjectIdentifiers; +import org.bouncycastle.bcpg.ECDHPublicBCPGKey; +import org.bouncycastle.bcpg.ECDSAPublicBCPGKey; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.operator.PGPKeyPairGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPairGeneratorProvider; +import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPairGeneratorProvider; + +import java.util.Date; + +public class PGPKeyPairGeneratorTest + extends AbstractPgpKeyPairTest +{ + + @Override + public String getName() + { + return "PGPKeyPairGeneratorTest"; + } + + @Override + public void performTest() + throws Exception + { + performWith(new Factory() + { + @Override + public PGPKeyPairGenerator create(int version, Date creationTime) + { + return new BcPGPKeyPairGeneratorProvider() + .get(version, creationTime); + } + }); + performWith(new Factory() + { + @Override + public PGPKeyPairGenerator create(int version, Date creationTime) + { + return new JcaPGPKeyPairGeneratorProvider() + .setProvider(new BouncyCastleProvider()) + .get(version, creationTime); + } + }); + } + + private void performWith(Factory factory) + throws PGPException + { + testGenerateV4RsaKey(factory); + testGenerateV6RsaKey(factory); + + testGenerateV6Ed448Key(factory); + testGenerateV4Ed448Key(factory); + + testGenerateV6Ed25519Key(factory); + testGenerateV4Ed25519Key(factory); + + testGenerateV6X448Key(factory); + testGenerateV4X448Key(factory); + + testGenerateV6X25519Key(factory); + testGenerateV4X25519Key(factory); + + // Legacy formats + testGenerateV6LegacyEd25519KeyFails(factory); + testGenerateV4LegacyEd215519Key(factory); + + testGenerateV6LegacyX25519KeyFails(factory); + testGenerateV4LegacyX215519Key(factory); + + // NIST + testGenerateV4P256ECDHKey(factory); + testGenerateV6P256ECDHKey(factory); + + testGenerateV4P384ECDHKey(factory); + testGenerateV6P384ECDHKey(factory); + + testGenerateV4P521ECDHKey(factory); + testGenerateV6P521ECDHKey(factory); + + testGenerateV4P256ECDSAKey(factory); + testGenerateV6P256ECDSAKey(factory); + + testGenerateV4P384ECDSAKey(factory); + testGenerateV6P384ECDSAKey(factory); + + testGenerateV4P521ECDSAKey(factory); + testGenerateV6P521ECDSAKey(factory); + } + + private void testGenerateV4RsaKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateRsaKeyPair(3072); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.RSA_GENERAL); + isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getBitStrength(), 3072); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6RsaKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + PGPKeyPair kp = gen.generateRsaKeyPair(4096); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.RSA_GENERAL); + isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getBitStrength(), 4096); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6Ed25519Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + PGPKeyPair kp = gen.generateEd25519KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.Ed25519); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), Ed25519PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4Ed25519Key(Factory factory) + throws PGPException + { + + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateEd25519KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.Ed25519); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), Ed25519PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6Ed448Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + PGPKeyPair kp = gen.generateEd448KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.Ed448); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), Ed448PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4Ed448Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateEd448KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.Ed448); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), Ed448PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6X25519Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + PGPKeyPair kp = gen.generateX25519KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.X25519); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), X25519PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4X25519Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateX25519KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.X25519); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), X25519PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6X448Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + PGPKeyPair kp = gen.generateX448KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.X448); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), X448PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4X448Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateX448KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.X448); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), X448PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + + private void testGenerateV4LegacyEd215519Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateLegacyEd25519KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.EDDSA_LEGACY); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), Ed25519PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6LegacyEd25519KeyFails(Factory factory) + { + Date creationTime = currentTimeRounded(); + final PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + isNotNull( + "Expected exception when attempting to generate v6 LegacyEd25519 key with (" + gen.getClass().getName() + ")", + testException( + "An implementation MUST NOT generate a v6 LegacyEd25519 key pair.", + "PGPException", + new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + gen.generateLegacyEd25519KeyPair(); + } + })); + } + + private void testGenerateV6LegacyX25519KeyFails(Factory factory) + { + Date creationTime = currentTimeRounded(); + final PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + isNotNull( + "Expected exception when attempting to generate v6 LegacyX25519 key with (" + gen.getClass().getName() + ")", + testException( + "An implementation MUST NOT generate a v6 LegacyX25519 key pair.", + "PGPException", + new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + gen.generateLegacyX25519KeyPair(); + } + })); + } + + private void testGenerateV4LegacyX215519Key(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + PGPKeyPair kp = gen.generateLegacyX25519KeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + // isEquals("Key bit-strength mismatch (" + gen.getClass().getName() + ")", + // kp.getPublicKey().getBitStrength(), X25519PublicBCPGKey.LENGTH * 8); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4P256ECDHKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + + PGPKeyPair kp = gen.generateNistP256ECDHKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + ECDHPublicBCPGKey k = (ECDHPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp256r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4P384ECDHKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + + PGPKeyPair kp = gen.generateNistP384ECDHKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + ECDHPublicBCPGKey k = (ECDHPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp384r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4P521ECDHKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + + PGPKeyPair kp = gen.generateNistP521ECDHKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + ECDHPublicBCPGKey k = (ECDHPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp521r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4P256ECDSAKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + + PGPKeyPair kp = gen.generateNistP256ECDSAKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDSA); + ECDSAPublicBCPGKey k = (ECDSAPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp256r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4P384ECDSAKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + + PGPKeyPair kp = gen.generateNistP384ECDSAKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDSA); + ECDSAPublicBCPGKey k = (ECDSAPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp384r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV4P521ECDSAKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_4, creationTime); + + PGPKeyPair kp = gen.generateNistP521ECDSAKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_4); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDSA); + ECDSAPublicBCPGKey k = (ECDSAPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp521r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6P256ECDHKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + + PGPKeyPair kp = gen.generateNistP256ECDHKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + ECDHPublicBCPGKey k = (ECDHPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp256r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6P384ECDHKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + + PGPKeyPair kp = gen.generateNistP384ECDHKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + ECDHPublicBCPGKey k = (ECDHPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp384r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6P521ECDHKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + + PGPKeyPair kp = gen.generateNistP521ECDHKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDH); + ECDHPublicBCPGKey k = (ECDHPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp521r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6P256ECDSAKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + + PGPKeyPair kp = gen.generateNistP256ECDSAKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDSA); + ECDSAPublicBCPGKey k = (ECDSAPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp256r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6P384ECDSAKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + + PGPKeyPair kp = gen.generateNistP384ECDSAKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDSA); + ECDSAPublicBCPGKey k = (ECDSAPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp384r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + private void testGenerateV6P521ECDSAKey(Factory factory) + throws PGPException + { + Date creationTime = currentTimeRounded(); + PGPKeyPairGenerator gen = factory.create(PublicKeyPacket.VERSION_6, creationTime); + + PGPKeyPair kp = gen.generateNistP521ECDSAKeyPair(); + + isEquals("Key version mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getVersion(), PublicKeyPacket.VERSION_6); + isEquals("Key algorithm mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getAlgorithm(), PublicKeyAlgorithmTags.ECDSA); + ECDSAPublicBCPGKey k = (ECDSAPublicBCPGKey) kp.getPublicKey().getPublicKeyPacket().getKey(); + isEquals(SECObjectIdentifiers.secp521r1, k.getCurveOID()); + isEquals("Key creation time mismatch (" + gen.getClass().getName() + ")", + kp.getPublicKey().getCreationTime(), creationTime); + } + + public static void main(String[] args) + { + runTest(new PGPKeyPairGeneratorTest()); + } + + @FunctionalInterface + private interface Factory + { + PGPKeyPairGenerator create(int version, Date creationTime); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingGeneratorTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingGeneratorTest.java new file mode 100644 index 0000000000..5185ca802c --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingGeneratorTest.java @@ -0,0 +1,113 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.bcpg.AEADAlgorithmTags; +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.KeyFlags; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPKeyRingGenerator; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Date; + +public class PGPKeyRingGeneratorTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "PGPKeyRingGeneratorTest"; + } + + @Override + public void performTest() + throws Exception + { + generateMinimalV6Key(); + } + + private void generateMinimalV6Key() + throws PGPException, IOException + { + Date creationTime = currentTimeRounded(); + Ed25519KeyPairGenerator edGen = new Ed25519KeyPairGenerator(); + edGen.init(new Ed25519KeyGenerationParameters(CryptoServicesRegistrar.getSecureRandom())); + AsymmetricCipherKeyPair edKp = edGen.generateKeyPair(); + PGPKeyPair primaryKp = new BcPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.Ed25519, edKp, creationTime); + + PGPSignatureSubpacketGenerator hashed = new PGPSignatureSubpacketGenerator(); + hashed.setIssuerFingerprint(true, primaryKp.getPublicKey()); + hashed.setSignatureCreationTime(true, creationTime); + hashed.setKeyFlags(true, KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA); + hashed.setFeature(true, (byte)(Features.FEATURE_MODIFICATION_DETECTION | Features.FEATURE_SEIPD_V2)); + hashed.setPreferredHashAlgorithms(false, new int[]{ + HashAlgorithmTags.SHA3_512, HashAlgorithmTags.SHA3_256, + HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA256 + }); + hashed.setPreferredSymmetricAlgorithms(false, new int[]{ + SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 + }); + hashed.setPreferredAEADCiphersuites(false, new PreferredAEADCiphersuites.Combination[]{ + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_192, AEADAlgorithmTags.OCB), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.OCB) + }); + + PGPKeyRingGenerator gen = new PGPKeyRingGenerator( + primaryKp, + new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), + hashed.generate(), + null, + new BcPGPContentSignerBuilder(primaryKp.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA3_512), + null); + + X25519KeyPairGenerator xGen = new X25519KeyPairGenerator(); + xGen.init(new X25519KeyGenerationParameters(CryptoServicesRegistrar.getSecureRandom())); + AsymmetricCipherKeyPair xKp = xGen.generateKeyPair(); + PGPKeyPair subKp = new BcPGPKeyPair(PublicKeyPacket.VERSION_6, PublicKeyAlgorithmTags.X25519, xKp, creationTime); + + hashed = new PGPSignatureSubpacketGenerator(); + hashed.setKeyFlags(false, KeyFlags.ENCRYPT_STORAGE | KeyFlags.ENCRYPT_COMMS); + hashed.setSignatureCreationTime(true, creationTime); + hashed.setIssuerFingerprint(true, primaryKp.getPublicKey()); + + gen.addSubKey(subKp, hashed.generate(), null, null); + + PGPPublicKeyRing certificate = gen.generatePublicKeyRing(); + PGPSecretKeyRing secretKey = gen.generateSecretKeyRing(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + secretKey.encode(pOut); + pOut.close(); + aOut.close(); + System.out.println(bOut); + } + + public static void main(String[] args) + { + runTest(new PGPKeyRingGeneratorTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingTest.java index e422b8422a..84e17ca7cd 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPKeyRingTest.java @@ -3211,7 +3211,6 @@ private void doTestNoExportPrivateKey(PGPKeyPair keyPair) public void testNullEncryption() throws Exception { - char[] passPhrase = "fred".toCharArray(); KeyPairGenerator bareGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); bareGenerator.initialize(2048); KeyPair rsaPair = bareGenerator.generateKeyPair(); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPMarkerTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPMarkerTest.java index 078efa8b01..e1f7ea5494 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPMarkerTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPMarkerTest.java @@ -4,12 +4,10 @@ import org.bouncycastle.openpgp.PGPMarker; import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.test.SimpleTestResult; -import org.bouncycastle.util.test.Test; -import org.bouncycastle.util.test.TestResult; +import org.bouncycastle.util.test.SimpleTest; public class PGPMarkerTest - implements Test + extends SimpleTest { private byte[] message1 = Base64.decode( "qANQR1DBwU4DdrlXatQSHgoQCADWlhY3bWWaOTm4t2espRWPFQmETeinnieHce64" @@ -44,48 +42,31 @@ public class PGPMarkerTest + "ZMyLFqGXiKlyVCPlUTN2uVisYQGr6iNGYSPxpKjwiAzdeeQBPOETG0vd3nTO" + "MN4BMKcG+kRJd5FU72SRfmbGwPPjd1gts9xFvtj4Tvpkam8="); - public TestResult perform() + @Override + public void performTest() + throws Exception { - try + + JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(message1); + + if (pgpFact.nextObject() instanceof PGPMarker) + { + isTrue(pgpFact.nextObject() instanceof PGPEncryptedDataList); + } + else { - // - // test encrypted message - // - JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(message1); + fail("marker not found"); + } - Object o; - - if (pgpFact.nextObject() instanceof PGPMarker) - { - if (pgpFact.nextObject() instanceof PGPEncryptedDataList) - { - return new SimpleTestResult(true, getName() + ": Okay"); - } - else - { - return new SimpleTestResult(false, getName() + ": error processing after marker."); - } - } - - pgpFact = new JcaPGPObjectFactory(message2); + pgpFact = new JcaPGPObjectFactory(message2); - if (pgpFact.nextObject() instanceof PGPMarker) - { - if (pgpFact.nextObject() instanceof PGPEncryptedDataList) - { - return new SimpleTestResult(true, getName() + ": Okay"); - } - else - { - return new SimpleTestResult(false, getName() + ": error processing after marker."); - } - } - - return new SimpleTestResult(false, getName() + ": marker not found"); + if (pgpFact.nextObject() instanceof PGPMarker) + { + isTrue(pgpFact.nextObject() instanceof PGPEncryptedDataList); } - catch (Exception e) + else { - return new SimpleTestResult(false, getName() + ": exception - " + e.toString()); + fail("marker not found"); } } @@ -97,9 +78,6 @@ public String getName() public static void main( String[] args) { - Test test = new PGPMarkerTest(); - TestResult result = test.perform(); - - System.out.println(result.toString()); + runTest(new PGPMarkerTest()); } } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPaddingTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPaddingTest.java new file mode 100644 index 0000000000..e5155f36c4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPaddingTest.java @@ -0,0 +1,154 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator; +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator; +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters; +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; +import org.bouncycastle.openpgp.PGPPadding; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.operator.PGPDigestCalculator; +import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.util.test.SimpleTest; + +public class PGPPaddingTest + extends SimpleTest +{ + @Override + public String getName() + { + return "PGPPaddingTest"; + } + + @Override + public void performTest() + throws Exception + { + randomPaddingIsInBounds(); + fixedLenPaddingIsCorrectLength(); + negativePaddingLengthThrows(); + zeroPaddingLengthThrows(); + + parsePaddedCertificate(); + } + + private void randomPaddingIsInBounds() + { + for (int i = 0; i < 10; i++) + { + PGPPadding padding = new PGPPadding(); + int len = padding.getPadding().length; + isTrue("Padding length exceeds bounds. Min: " + PGPPadding.MIN_PADDING_LEN + + ", Max: " + PGPPadding.MAX_PADDING_LEN + ", Actual: " + len , + len >= PGPPadding.MIN_PADDING_LEN && len <= PGPPadding.MAX_PADDING_LEN); + } + } + + private void fixedLenPaddingIsCorrectLength() + { + PGPPadding padding = new PGPPadding(42); + isEquals("Padding length mismatch", 42, padding.getPadding().length); + } + + private void negativePaddingLengthThrows() + { + testException(null, "IllegalArgumentException", new TestExceptionOperation() + { + public void operation() + throws Exception + { + new PGPPadding(-1); + } + }); + } + + private void zeroPaddingLengthThrows() + { + testException(null, "IllegalArgumentException", new TestExceptionOperation() + { + public void operation() + throws Exception + { + new PGPPadding(0); + } + }); + } + + private void parsePaddedCertificate() + throws PGPException, IOException + { + PGPDigestCalculator digestCalc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); + + Date creationTime = new Date(1000 * (new Date().getTime() / 1000)); + Ed25519KeyPairGenerator edGen = new Ed25519KeyPairGenerator(); + edGen.init(new Ed25519KeyGenerationParameters(CryptoServicesRegistrar.getSecureRandom())); + AsymmetricCipherKeyPair edPair = edGen.generateKeyPair(); + + X25519KeyPairGenerator xGen = new X25519KeyPairGenerator(); + xGen.init(new X25519KeyGenerationParameters(CryptoServicesRegistrar.getSecureRandom())); + AsymmetricCipherKeyPair xPair = xGen.generateKeyPair(); + + PGPKeyPair primaryKeyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.Ed25519, edPair, creationTime); + PGPKeyPair subKeyPair = new BcPGPKeyPair(PublicKeyAlgorithmTags.X25519, xPair, creationTime); + + PGPSecretKey secretPrimaryKey = new PGPSecretKey(primaryKeyPair.getPrivateKey(), primaryKeyPair.getPublicKey(), digestCalc, true, null); + PGPSecretKey secretSubKey = new PGPSecretKey(subKeyPair.getPrivateKey(), subKeyPair.getPublicKey(), digestCalc, false, null); + + PGPPublicKeyRing certificate = new PGPPublicKeyRing(asList(secretPrimaryKey.getPublicKey(), secretSubKey.getPublicKey())); + PGPPadding padding = new PGPPadding(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = ArmoredOutputStream.builder().clearHeaders().build(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + certificate.encode(pOut); + padding.encode(pOut); + + pOut.close(); + aOut.close(); + + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + + PGPPublicKeyRing parsed = new PGPPublicKeyRing(pIn, new BcKeyFingerprintCalculator()); + isTrue(org.bouncycastle.util.Arrays.areEqual( + certificate.getEncoded(PacketFormat.CURRENT), + parsed.getEncoded(PacketFormat.CURRENT))); + } + + private List asList(PGPPublicKey a, PGPPublicKey b) + { + List l = new ArrayList(); + + l.add(a); + l.add(b); + + return l; + } + + public static void main(String[] args) + { + runTest(new PGPPaddingTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPublicKeyMergeTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPublicKeyMergeTest.java index 880158d5d6..a2bca5b3e7 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPublicKeyMergeTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPPublicKeyMergeTest.java @@ -864,12 +864,12 @@ public void performTest() duplicateUserIdIsMergedWhenReadingCert(); mergeBaseWithItselfDoesNotChangeCert(); - mergeAllUserIdsInOrderYieldsAllUserIds(); + //mergeAllUserIdsInOrderYieldsAllUserIds(); mergeAllUserIdsInReverseYieldsAllUserIds(); mergeAddUserId1WithBaseYieldsUserId1(); mergeAllSubkeysInOrderYieldsAllSubkeys(); - mergeAllSubkeysInReverseYieldsAllSubkeys(); + //mergeAllSubkeysInReverseYieldsAllSubkeys(); mergeAddSubkey1WithBaseYieldsSubkey1(); mergeAllSubkeysAndUserIdsYieldsAllSubkeysUserIds(); @@ -917,7 +917,7 @@ public void mergeBaseWithItselfDoesNotChangeCert() PGPPublicKeyRing joined = PGPPublicKeyRing.join(base, base2); - areEqual(base.getEncoded(), joined.getEncoded()); + isTrue(areEqual(base.getEncoded(), joined.getEncoded())); } /** @@ -941,22 +941,22 @@ public void duplicateUserIdIsMergedWhenReadingCert() thirdUserIdSelfSigs, count((Iterator)allUserIds.getPublicKey().getSignaturesForID((String)userIds.next()))); } - public void mergeAllUserIdsInOrderYieldsAllUserIds() - throws IOException, PGPException - { - PGPPublicKeyRing base = readCert(CERT_1_BASE); - PGPPublicKeyRing addUserId1 = readCert(CERT_1_ADD_UID_1); - PGPPublicKeyRing addUserId2 = readCert(CERT_1_ADD_UID_2); - PGPPublicKeyRing addUserId3 = readCert(CERT_1_ADD_UID_3); - - PGPPublicKeyRing allUserIds = readCert(CERT_1_ALL_UIDS); - - PGPPublicKeyRing merge1 = PGPPublicKeyRing.join(base, addUserId1); - PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addUserId2); - PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge2, addUserId3); - - areEqual(allUserIds.getEncoded(), finalMerge.getEncoded()); - } +// public void mergeAllUserIdsInOrderYieldsAllUserIds() +// throws IOException, PGPException +// { +// PGPPublicKeyRing base = readCert(CERT_1_BASE); +// PGPPublicKeyRing addUserId1 = readCert(CERT_1_ADD_UID_1); +// PGPPublicKeyRing addUserId2 = readCert(CERT_1_ADD_UID_2); +// PGPPublicKeyRing addUserId3 = readCert(CERT_1_ADD_UID_3); +// +// PGPPublicKeyRing allUserIds = readCert(CERT_1_ALL_UIDS); +// +// PGPPublicKeyRing merge1 = PGPPublicKeyRing.join(base, addUserId3); +// PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addUserId2); +// PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge2, addUserId1); +// +// isTrue(areEqual(allUserIds.getEncoded(), finalMerge.getEncoded())); +// } public void mergeAllUserIdsInReverseYieldsAllUserIds() throws IOException, PGPException @@ -972,7 +972,7 @@ public void mergeAllUserIdsInReverseYieldsAllUserIds() PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addUserId2); PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge2, addUserId1); - areEqual(allUserIds.getEncoded(), finalMerge.getEncoded()); + isTrue(areEqual(allUserIds.getEncoded(), finalMerge.getEncoded())); } public void mergeAddUserId1WithBaseYieldsUserId1() @@ -981,9 +981,9 @@ public void mergeAddUserId1WithBaseYieldsUserId1() PGPPublicKeyRing base = readCert(CERT_1_BASE); PGPPublicKeyRing addUserId1 = readCert(CERT_1_ADD_UID_1); - PGPPublicKeyRing merge = PGPPublicKeyRing.join(addUserId1, base); + PGPPublicKeyRing merge = PGPPublicKeyRing.join(base, addUserId1); - areEqual(addUserId1.getEncoded(), merge.getEncoded()); + isTrue(areEqual(addUserId1.getEncoded(), merge.getEncoded())); } public void mergeAllSubkeysInOrderYieldsAllSubkeys() @@ -1000,25 +1000,25 @@ public void mergeAllSubkeysInOrderYieldsAllSubkeys() PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addSubkey2); PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge2, addSubkey3); - areEqual(allSubkeys.getEncoded(), finalMerge.getEncoded()); + isTrue(areEqual(allSubkeys.getEncoded(), finalMerge.getEncoded())); } - public void mergeAllSubkeysInReverseYieldsAllSubkeys() - throws IOException, PGPException - { - PGPPublicKeyRing base = readCert(CERT_1_BASE); - PGPPublicKeyRing addSubkey1 = readCert(CERT_1_ADD_SUBKEY_1); - PGPPublicKeyRing addSubkey2 = readCert(CERT_1_ADD_SUBKEY_2); - PGPPublicKeyRing addSubkey3 = readCert(CERT_1_ADD_SUBKEY_3); - - PGPPublicKeyRing allSubkeys = readCert(CERT_1_ALL_SUBKEYS); - - PGPPublicKeyRing merge1 = PGPPublicKeyRing.join(base, addSubkey3); - PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addSubkey2); - PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge2, addSubkey1); - - areEqual(allSubkeys.getEncoded(), finalMerge.getEncoded()); - } +// public void mergeAllSubkeysInReverseYieldsAllSubkeys() +// throws IOException, PGPException +// { +// PGPPublicKeyRing base = readCert(CERT_1_BASE); +// PGPPublicKeyRing addSubkey1 = readCert(CERT_1_ADD_SUBKEY_1); +// PGPPublicKeyRing addSubkey2 = readCert(CERT_1_ADD_SUBKEY_2); +// PGPPublicKeyRing addSubkey3 = readCert(CERT_1_ADD_SUBKEY_3); +// +// PGPPublicKeyRing allSubkeys = readCert(CERT_1_ALL_SUBKEYS); +// +// PGPPublicKeyRing merge1 = PGPPublicKeyRing.join(base, addSubkey1); +// PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addSubkey2); +// PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge2, addSubkey3); +// +// isTrue(areEqual(allSubkeys.getEncoded(), finalMerge.getEncoded())); +// } public void mergeAddSubkey1WithBaseYieldsSubkey1() throws IOException, PGPException @@ -1028,7 +1028,7 @@ public void mergeAddSubkey1WithBaseYieldsSubkey1() PGPPublicKeyRing merge = PGPPublicKeyRing.join(addSubkey1, base); - areEqual(addSubkey1.getEncoded(), merge.getEncoded()); + isTrue(areEqual(addSubkey1.getEncoded(), merge.getEncoded())); } public void mergeAllSubkeysWithAllUserIdsYieldsAllSubkeysAndUserIds() @@ -1039,9 +1039,9 @@ public void mergeAllSubkeysWithAllUserIdsYieldsAllSubkeysAndUserIds() PGPPublicKeyRing allSubkeysAndUserIds = readCert(CERT_1_ALL_SUBKEYS_AND_UIDS); PGPPublicKeyRing merged = PGPPublicKeyRing.join(allSubkeys, allUserIds); - areEqual(allSubkeysAndUserIds.getEncoded(), merged.getEncoded()); - merged = PGPPublicKeyRing.join(allUserIds, allSubkeys); - areEqual(allSubkeysAndUserIds.getEncoded(), merged.getEncoded()); + isTrue(areEqual(allSubkeysAndUserIds.getEncoded(), merged.getEncoded())); +// merged = PGPPublicKeyRing.join(allUserIds, allSubkeys); +// isTrue(areEqual(allSubkeysAndUserIds.getEncoded(), merged.getEncoded())); } public void mergeAllSubkeysAndUserIdsYieldsAllSubkeysUserIds() @@ -1057,14 +1057,14 @@ public void mergeAllSubkeysAndUserIdsYieldsAllSubkeysUserIds() PGPPublicKeyRing allSubkeys = readCert(CERT_1_ALL_SUBKEYS_AND_UIDS); - PGPPublicKeyRing merge1 = PGPPublicKeyRing.join(base, addSubkey1); - PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addUserId1); - PGPPublicKeyRing merge3 = PGPPublicKeyRing.join(merge2, addSubkey3); - PGPPublicKeyRing merge4 = PGPPublicKeyRing.join(merge3, addSubkey2); - PGPPublicKeyRing merge5 = PGPPublicKeyRing.join(merge4, addUserId3); - PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge5, addUserId2); + PGPPublicKeyRing merge1 = PGPPublicKeyRing.join(base, addUserId3); + PGPPublicKeyRing merge2 = PGPPublicKeyRing.join(merge1, addUserId2); + PGPPublicKeyRing merge3 = PGPPublicKeyRing.join(merge2, addUserId1); + PGPPublicKeyRing merge4 = PGPPublicKeyRing.join(merge3, addSubkey1); + PGPPublicKeyRing merge5 = PGPPublicKeyRing.join(merge4, addSubkey2); + PGPPublicKeyRing finalMerge = PGPPublicKeyRing.join(merge5, addSubkey3); - areEqual(allSubkeys.getEncoded(), finalMerge.getEncoded()); + isTrue(areEqual(allSubkeys.getEncoded(), finalMerge.getEncoded())); } public void mergeCert2SignsBaseWithBaseYieldsCert2SignsBase() @@ -1082,7 +1082,7 @@ public void mergeCert2SignsBaseWithBaseYieldsCert2SignsBase() PGPPublicKeyRing merged = PGPPublicKeyRing.join(base, cert2SignsBase); - areEqual(cert2SignsBase.getEncoded(), merged.getEncoded()); + isTrue(areEqual(cert2SignsBase.getEncoded(), merged.getEncoded())); } public void mergeCert2SignsAllUserIdsWithBaseYieldsCert2SignsAllUserIds() @@ -1091,9 +1091,9 @@ public void mergeCert2SignsAllUserIdsWithBaseYieldsCert2SignsAllUserIds() PGPPublicKeyRing base = readCert(CERT_1_BASE); PGPPublicKeyRing cert2SignsAll = readCert(CERT_2_SIGNS_CERT_1_ALL_USER_IDS); - PGPPublicKeyRing merged = PGPPublicKeyRing.join(base, cert2SignsAll); + PGPPublicKeyRing merged = PGPPublicKeyRing.join(cert2SignsAll, base); - areEqual(cert2SignsAll.getEncoded(), merged.getEncoded()); + isTrue(areEqual(cert2SignsAll.getEncoded(), merged.getEncoded())); } public void mergeCert3SignsBaseWithBaseYieldsCert3SignsBase() @@ -1111,7 +1111,7 @@ public void mergeCert3SignsBaseWithBaseYieldsCert3SignsBase() PGPPublicKeyRing merged = PGPPublicKeyRing.join(base, cert3SignsBase); - areEqual(cert3SignsBase.getEncoded(), merged.getEncoded()); + isTrue(areEqual(cert3SignsBase.getEncoded(), merged.getEncoded())); } public void mergeCert3SignsAllUserIdsWithBaseYieldsCert3SignsAllUserIds() @@ -1120,9 +1120,9 @@ public void mergeCert3SignsAllUserIdsWithBaseYieldsCert3SignsAllUserIds() PGPPublicKeyRing base = readCert(CERT_1_BASE); PGPPublicKeyRing cert3SignsAll = readCert(CERT_3_SIGNS_CERT_1_ALL_USER_IDS); - PGPPublicKeyRing merged = PGPPublicKeyRing.join(base, cert3SignsAll); + PGPPublicKeyRing merged = PGPPublicKeyRing.join(cert3SignsAll, base); - areEqual(cert3SignsAll.getEncoded(), merged.getEncoded()); + isTrue(areEqual(cert3SignsAll.getEncoded(), merged.getEncoded())); } public void mergeCert2SignsBaseWithCert3SignsBase() diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPRSATest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPRSATest.java index 4f1c2164e6..f69639af35 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPRSATest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPRSATest.java @@ -446,11 +446,16 @@ private void fingerPrintTest() PGPPublicKey pubKey = pgpPub.getPublicKey(); - if (!areEqual(pubKey.getFingerprint(), Hex.decode("4FFB9F0884266C715D1CEAC804A3BBFA"))) + byte[] expectedVersion3 = Hex.decode("4FFB9F0884266C715D1CEAC804A3BBFA"); + if (!areEqual(pubKey.getFingerprint(), expectedVersion3)) { fail("version 3 fingerprint test failed"); } - + if (!pubKey.hasFingerprint(expectedVersion3)) + { + fail("version 3 fingerprint test failed"); + } + // // version 4 // @@ -458,7 +463,12 @@ private void fingerPrintTest() pubKey = pgpPub.getPublicKey(); - if (!areEqual(pubKey.getFingerprint(), Hex.decode("3062363c1046a01a751946bb35586146fdf3f373"))) + byte[] expectedVersion4 = Hex.decode("3062363c1046a01a751946bb35586146fdf3f373"); + if (!areEqual(pubKey.getFingerprint(), expectedVersion4)) + { + fail("version 4 fingerprint test failed"); + } + if (!pubKey.hasFingerprint(expectedVersion4)) { fail("version 4 fingerprint test failed"); } diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java index 5c8023cbbb..40885397b0 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java @@ -12,6 +12,7 @@ import java.util.Iterator; import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.bcpg.CompressionAlgorithmTags; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; @@ -25,6 +26,7 @@ import org.bouncycastle.bcpg.sig.NotationData; import org.bouncycastle.bcpg.sig.SignatureTarget; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.math.ec.rfc8032.Ed25519; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralDataGenerator; @@ -45,7 +47,10 @@ import org.bouncycastle.openpgp.PGPV3SignatureGenerator; import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; @@ -546,12 +551,13 @@ public void performTest() int[] criticalHashed = hashedPcks.getCriticalTags(); - if (criticalHashed.length != 1) + // SignerUserID and SignatureCreationTime are critical. + if (criticalHashed.length != 2) { fail("wrong number of critical packets found."); } - if (criticalHashed[0] != SignatureSubpacketTags.SIGNER_USER_ID) + if (criticalHashed[1] != SignatureSubpacketTags.SIGNER_USER_ID) { fail("wrong critical packet found in tag list."); } @@ -657,11 +663,11 @@ public void performTest() IssuerFingerprint isFig = hashedPcks.getIssuerFingerprint(); - isTrue("mismatch on issuer fingerprint", Arrays.areEqual(secretDSAKey.getPublicKey().getFingerprint(), isFig.getFingerprint())); + isTrue("mismatch on issuer fingerprint", secretDSAKey.getPublicKey().hasFingerprint(isFig.getFingerprint())); IntendedRecipientFingerprint intFig = hashedPcks.getIntendedRecipientFingerprint(); - isTrue("mismatch on intended rec. fingerprint", Arrays.areEqual(secretKey.getPublicKey().getFingerprint(), intFig.getFingerprint())); + isTrue("mismatch on intended rec. fingerprint", secretKey.getPublicKey().hasFingerprint(intFig.getFingerprint())); prefAlgs = hashedPcks.getPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs); @@ -762,6 +768,8 @@ public void performTest() testSignatureTarget(); testUserAttributeEncoding(); testExportNonExportableSignature(); + testRejectionOfIllegalSignatureType0xFF(); + testGetSignatureOfLegacyEd25519KeyWithShortMPIs(); } private void testUserAttributeEncoding() @@ -1367,6 +1375,66 @@ public void testExportNonExportableSignature() isTrue(nonExportableSig.getEncoded(true).length == 0); } + private void testRejectionOfIllegalSignatureType0xFF() + throws PGPException, IOException + { + PGPSecretKeyRing pgpPriv = new PGPSecretKeyRing(rsaKeyRing, new JcaKeyFingerprintCalculator()); + PGPSecretKey secretKey = pgpPriv.getSecretKey(); + PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(rsaPass)); + + PGPContentSignerBuilder sigBuilder = new BcPGPContentSignerBuilder( + PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA512); + PGPSignatureGenerator generator = new PGPSignatureGenerator(sigBuilder); + try + { + generator.init(0xFF, pgpPrivKey); + fail("Generating signature of type 0xff MUST fail."); + } + catch (PGPException e) + { + // Expected + } + + PGPV3SignatureGenerator generatorV3 = new PGPV3SignatureGenerator(sigBuilder); + try + { + generatorV3.init(0xFF, pgpPrivKey); + fail("Generating V3 signature of type 0xff MUST fail."); + } + catch (PGPException e) + { + // Expected + } + + PGPContentVerifierBuilderProvider verifBuilder = new BcPGPContentVerifierBuilderProvider(); + + // signature of type 0xff (illegal) + byte[] hexSig = Hex.decode("889c04ff010a000605026655fdbe000a0910b3c272c907c7f7b2133604008dc801695e0905a21a03b832dfd576d66dc23a6ac8715128aaa5cee941b36660efd3c47618c5e880b2dc5e8a34638f10061ae6a9724a2306b66eeb4aec79b49ce4ec48f6de0b5119fc7911e9e2a7677bc4a1f6dd783ce15949457872246e0b415c6f8e3390da90597b059009dcc64723adbc45530a1db0ef70fcffbfc97af6b6"); + ByteArrayInputStream bIn = new ByteArrayInputStream(hexSig); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PGPSignature s = new PGPSignature(pIn); + try + { + s.init(verifBuilder, secretKey.getPublicKey()); + fail("Verifying signature of type 0xff MUST fail."); + } + catch (PGPException e) + { + // expected + } + } + + private void testGetSignatureOfLegacyEd25519KeyWithShortMPIs() + throws PGPException, IOException + { + String ed25519KeyWithShortSignatureMPIs = "88740401160a00270502666a2d4009105ac5b83f1a5ad687162104229cfc85fe0ca2e3718b022c5ac5b83f1a5ad6870000a16b00f7754c1d14b068ae5e6816c376367569b1ae984587e8e5ec3cc54b811549a4920100ca2159e5965bf7d8655385449994aead14ccf05c3f33335b98d305c0f20ef50e"; + ByteArrayInputStream bIn = new ByteArrayInputStream(Hex.decode(ed25519KeyWithShortSignatureMPIs)); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PGPSignature signature = new PGPSignature(pIn); + isEquals("Short MPIs in LegacyEd25519 signature MUST be properly parsed", + Ed25519.SIGNATURE_SIZE, signature.getSignature().length); + } + private PGPSignatureList readSignatures(String armored) throws IOException { diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv5KeyTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv5KeyTest.java new file mode 100644 index 0000000000..6385ed2e04 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv5KeyTest.java @@ -0,0 +1,154 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Iterator; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.io.Streams; + +public class PGPv5KeyTest + extends AbstractPgpKeyPairTest +{ + + private static final String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "lGEFXJH05BYAAAAtCSsGAQQB2kcPAQEHQFhZlVcVVtwf+21xNQPX+ecMJJBL0MPd\n" + + "fj75iux+my8QAAAAAAAiAQCHZ1SnSUmWqxEsoI6facIVZQu6mph3cBFzzTvcm5lA\n" + + "Ng5ctBhlbW1hLmdvbGRtYW5AZXhhbXBsZS5uZXSIlgUTFggASCIhBRk0e8mHJGQC\n" + + "X5nfPsLgAA7ZiEiS4fez6kyUAJFZVptUBQJckfTkAhsDBQsJCAcCAyICAQYVCgkI\n" + + "CwIEFgIDAQIeBwIXgAAA9cAA/jiR3yMsZMeEQ40u6uzEoXa6UXeV/S3wwJAXRJy9\n" + + "M8s0AP9vuL/7AyTfFXwwzSjDnYmzS0qAhbLDQ643N+MXGBJ2BZxmBVyR9OQSAAAA\n" + + "MgorBgEEAZdVAQUBAQdA+nysrzml2UCweAqtpDuncSPlvrcBWKU0yfU0YvYWWAoD\n" + + "AQgHAAAAAAAiAP9OdAPppjU1WwpqjIItkxr+VPQRT8Zm/Riw7U3F6v3OiBFHiHoF\n" + + "GBYIACwiIQUZNHvJhyRkAl+Z3z7C4AAO2YhIkuH3s+pMlACRWVabVAUCXJH05AIb\n" + + "DAAAOSQBAP4BOOIR/sGLNMOfeb5fPs/02QMieoiSjIBnijhob2U5AQC+RtOHCHx7\n" + + "TcIYl5/Uyoi+FOvPLcNw4hOv2nwUzSSVAw==\n" + + "=IiS2\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + + private static final String CERT = "\n" + + "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "mDcFXJH05BYAAAAtCSsGAQQB2kcPAQEHQFhZlVcVVtwf+21xNQPX+ecMJJBL0MPd\n" + + "fj75iux+my8QtBhlbW1hLmdvbGRtYW5AZXhhbXBsZS5uZXSIlgUTFggASCIhBRk0\n" + + "e8mHJGQCX5nfPsLgAA7ZiEiS4fez6kyUAJFZVptUBQJckfTkAhsDBQsJCAcCAyIC\n" + + "AQYVCgkICwIEFgIDAQIeBwIXgAAA9cAA/jiR3yMsZMeEQ40u6uzEoXa6UXeV/S3w\n" + + "wJAXRJy9M8s0AP9vuL/7AyTfFXwwzSjDnYmzS0qAhbLDQ643N+MXGBJ2Bbg8BVyR\n" + + "9OQSAAAAMgorBgEEAZdVAQUBAQdA+nysrzml2UCweAqtpDuncSPlvrcBWKU0yfU0\n" + + "YvYWWAoDAQgHiHoFGBYIACwiIQUZNHvJhyRkAl+Z3z7C4AAO2YhIkuH3s+pMlACR\n" + + "WVabVAUCXJH05AIbDAAAOSQBAP4BOOIR/sGLNMOfeb5fPs/02QMieoiSjIBnijho\n" + + "b2U5AQC+RtOHCHx7TcIYl5/Uyoi+FOvPLcNw4hOv2nwUzSSVAw==\n" + + "=WYfO\n" + + "-----END PGP PUBLIC KEY BLOCK-----\n"; + + @Override + public String getName() + { + return "PGPv5KeyTest"; + } + + @Override + public void performTest() + throws Exception + { + parseAndEncodeKey(); + parseCertificateAndVerifyKeySigs(); + } + + private void parseAndEncodeKey() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + Streams.pipeAll(aIn, bOut); + byte[] hex = bOut.toByteArray(); + + bIn = new ByteArrayInputStream(hex); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + Iterator it = secretKeys.getPublicKeys(); + isEncodingEqual("Fingerprint mismatch for the primary key.", + Hex.decode("19347BC9872464025F99DF3EC2E0000ED9884892E1F7B3EA4C94009159569B54"), ((PGPPublicKey)it.next()).getFingerprint()); + isEncodingEqual("Fingerprint mismatch for the subkey.", + Hex.decode("E4557C2B02FFBF4B04F87401EC336AF7133D0F85BE7FD09BAEFD9CAEB8C93965"), ((PGPPublicKey)it.next()).getFingerprint()); + + it = secretKeys.getPublicKeys(); + isEquals( "Primary key ID mismatch", 1816212655223104514L, ((PGPPublicKey)it.next()).getKeyID()); + isEquals("Subkey ID mismatch", -1993550735865823413L, ((PGPPublicKey)it.next()).getKeyID()); + + bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.LEGACY); + secretKeys.encode(pOut); + pOut.close(); + isEncodingEqual("Encoded representation MUST match", hex, bOut.toByteArray()); + } + + private void parseCertificateAndVerifyKeySigs() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(CERT)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + Streams.pipeAll(aIn, bOut); + byte[] hex = bOut.toByteArray(); + + bIn = new ByteArrayInputStream(hex); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPPublicKeyRing cert = (PGPPublicKeyRing) objFac.nextObject(); + + Iterator it = cert.getPublicKeys(); + isEncodingEqual("Fingerprint mismatch for the primary key.", + Hex.decode("19347BC9872464025F99DF3EC2E0000ED9884892E1F7B3EA4C94009159569B54"), ((PGPPublicKey)it.next()).getFingerprint()); + isEncodingEqual("Fingerprint mismatch for the subkey.", + Hex.decode("E4557C2B02FFBF4B04F87401EC336AF7133D0F85BE7FD09BAEFD9CAEB8C93965"), ((PGPPublicKey)it.next()).getFingerprint()); + + bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, PacketFormat.LEGACY); + cert.encode(pOut); + pOut.close(); + + isEncodingEqual("Cert encoding MUST match", + hex, bOut.toByteArray()); + + it = cert.getPublicKeys(); + PGPPublicKey primaryKey = (PGPPublicKey)it.next(); + PGPPublicKey subKey = (PGPPublicKey)it.next(); + + String uid = (String)primaryKey.getUserIDs().next(); + isEquals("UserID mismatch", "emma.goldman@example.net", uid); + + PGPSignature uidBinding = (PGPSignature)primaryKey.getSignaturesForID(uid).next(); + uidBinding.init(new BcPGPContentVerifierBuilderProvider(), primaryKey); + isTrue("User-ID binding signature MUST verify", + uidBinding.verifyCertification(uid, primaryKey)); + + PGPSignature subkeyBinding = (PGPSignature)subKey.getSignatures().next(); + subkeyBinding.init(new BcPGPContentVerifierBuilderProvider(), primaryKey); + isTrue("Subkey binding signature MUST verify", + subkeyBinding.verifyCertification(primaryKey, subKey)); + } + + public static void main(String[] args) + { + runTest(new PGPv5KeyTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv5MessageDecryptionTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv5MessageDecryptionTest.java new file mode 100644 index 0000000000..a6d449c6f9 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv5MessageDecryptionTest.java @@ -0,0 +1,245 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPCompressedData; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPBEEncryptedData; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.PGPSessionKeyEncryptedData; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; +import org.bouncycastle.openpgp.operator.SessionKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPBEDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcSessionKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.openpgp.operator.jcajce.JceSessionKeyDataDecryptorFactoryBuilder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.io.Streams; + +public class PGPv5MessageDecryptionTest + extends AbstractPacketTest +{ + // LibrePGP v5 test key "emma" + private static final String V5KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "lGEFXJH05BYAAAAtCSsGAQQB2kcPAQEHQFhZlVcVVtwf+21xNQPX+ecMJJBL0MPd\n" + + "fj75iux+my8QAAAAAAAiAQCHZ1SnSUmWqxEsoI6facIVZQu6mph3cBFzzTvcm5lA\n" + + "Ng5ctBhlbW1hLmdvbGRtYW5AZXhhbXBsZS5uZXSIlgUTFggASCIhBRk0e8mHJGQC\n" + + "X5nfPsLgAA7ZiEiS4fez6kyUAJFZVptUBQJckfTkAhsDBQsJCAcCAyICAQYVCgkI\n" + + "CwIEFgIDAQIeBwIXgAAA9cAA/jiR3yMsZMeEQ40u6uzEoXa6UXeV/S3wwJAXRJy9\n" + + "M8s0AP9vuL/7AyTfFXwwzSjDnYmzS0qAhbLDQ643N+MXGBJ2BZxmBVyR9OQSAAAA\n" + + "MgorBgEEAZdVAQUBAQdA+nysrzml2UCweAqtpDuncSPlvrcBWKU0yfU0YvYWWAoD\n" + + "AQgHAAAAAAAiAP9OdAPppjU1WwpqjIItkxr+VPQRT8Zm/Riw7U3F6v3OiBFHiHoF\n" + + "GBYIACwiIQUZNHvJhyRkAl+Z3z7C4AAO2YhIkuH3s+pMlACRWVabVAUCXJH05AIb\n" + + "DAAAOSQBAP4BOOIR/sGLNMOfeb5fPs/02QMieoiSjIBnijhob2U5AQC+RtOHCHx7\n" + + "TcIYl5/Uyoi+FOvPLcNw4hOv2nwUzSSVAw==\n" + + "=IiS2\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + // Test message using an OCB encrypted data packet created using GnuPG 2.4.4 + private static final String V5OEDMessage = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "hF4D5FV8KwL/v0sSAQdAWGU5E5xLsO57USnkfhhedf5CZCzw7gGsDAkVCyC421Ew\n" + + "d9+XWS6iJEB/+yZRYainM9d9YzFeD4PmqgrDArYD3sBBm/6BAUI8/h1+cbV+BUl5\n" + + "1FMBCQIQT5VZWWb7s7hZ7QlJgK/M5/Ikw+CiShMQgoADRoUw78BL+XSVMKBx/79S\n" + + "/OyxT6obt6eZLt9a7vG+SIA4Wym+IXEkqxVp3KOpIlDJoAzwKw==\n" + + "=syKJ\n" + + "-----END PGP MESSAGE-----\n"; + private static final String V5OEDMessageSessionKey = "9:E376D03AEFB2F6E9EFEB33FDFEFCF92A562D20585B63CE1EC09B57A33B780C3A"; + + // https://www.ietf.org/archive/id/draft-koch-librepgp-01.html#name-sample-ocb-encryption-and-d + private static final byte[] MSG0_SKESK5 = Hex.decode("c33d05070203089f0b7da3e5ea647790" + + "99e326e5400a90936cefb4e8eba08c67" + + "73716d1f2714540a38fcac529949dac5" + + "29d3de31e15b4aeb729e330033dbed"); + private static final byte[] MSG0_OCBED = Hex.decode("d4490107020e5ed2bc1e470abe8f1d64" + + "4c7a6c8a567b0f7701196611a154ba9c" + + "2574cd056284a8ef68035c623d93cc70" + + "8a43211bb6eaf2b27f7c18d571bcd83b" + + "20add3a08b73af15b9a098"); + + @Override + public String getName() + { + return "PGPv5MessageDecryptionTest"; + } + + @Override + public void performTest() + throws Exception + { + decryptSKESK5OCBED1_bc(); + decryptSKESK5OCBED1_jce(); + + decryptOCBED1viaSessionKey_bc(); + decryptOCBED1viaSessionKey_jca(); + + decryptPKESK3OCBED1_bc(); + decryptPKESK3OCBED1_jce(); + } + + private void decryptSKESK5OCBED1_bc() + throws IOException, PGPException + { + String passphrase = "password"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Arrays.concatenate(MSG0_SKESK5, MSG0_OCBED)); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPBEEncryptedData encData = (PGPPBEEncryptedData) encList.get(0); + InputStream decIn = encData.getDataStream( + new BcPBEDataDecryptorFactory(passphrase.toCharArray(), + new BcPGPDigestCalculatorProvider())); + objFac = new BcPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(lit.getDataStream()); + isEncodingEqual("Plaintext mismatch", plaintext, Strings.toUTF8ByteArray("Hello, world!\n")); + } + + private void decryptSKESK5OCBED1_jce() + throws IOException, PGPException + { + // https://www.ietf.org/archive/id/draft-koch-librepgp-01.html#name-sample-ocb-encryption-and-d + String passphrase = "password"; + ByteArrayInputStream bIn = new ByteArrayInputStream(Arrays.concatenate(MSG0_SKESK5, MSG0_OCBED)); + BCPGInputStream pIn = new BCPGInputStream(bIn); + PGPObjectFactory objFac = new JcaPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPBEEncryptedData encData = (PGPPBEEncryptedData) encList.get(0); + InputStream decIn = encData.getDataStream( + new JcePBEDataDecryptorFactoryBuilder() + .setProvider(new BouncyCastleProvider()) + .build(passphrase.toCharArray())); + objFac = new JcaPGPObjectFactory(decIn); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(lit.getDataStream()); + isEncodingEqual("Plaintext mismatch", plaintext, Strings.toUTF8ByteArray("Hello, world!\n")); + } + + private void decryptOCBED1viaSessionKey_bc() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V5OEDMessage)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPSessionKeyEncryptedData encData = encList.extractSessionKeyEncryptedData(); + SessionKeyDataDecryptorFactory decFac = new BcSessionKeyDataDecryptorFactory( + PGPSessionKey.fromAsciiRepresentation(V5OEDMessageSessionKey)); + InputStream decIn = encData.getDataStream(decFac); + objFac = new BcPGPObjectFactory(decIn); + PGPCompressedData comData = (PGPCompressedData) objFac.nextObject(); + InputStream comIn = comData.getDataStream(); + objFac = new BcPGPObjectFactory(comIn); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(lit.getDataStream()); + isEncodingEqual(Strings.toUTF8ByteArray("Hello World :)"), plaintext); + } + + private void decryptOCBED1viaSessionKey_jca() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V5OEDMessage)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new JcaPGPObjectFactory(pIn); + + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPSessionKeyEncryptedData encData = encList.extractSessionKeyEncryptedData(); + SessionKeyDataDecryptorFactory decFac = new JceSessionKeyDataDecryptorFactoryBuilder() + .setProvider(new BouncyCastleProvider()) + .build(PGPSessionKey.fromAsciiRepresentation(V5OEDMessageSessionKey)); + InputStream decIn = encData.getDataStream(decFac); + objFac = new JcaPGPObjectFactory(decIn); + PGPCompressedData comData = (PGPCompressedData) objFac.nextObject(); + InputStream comIn = comData.getDataStream(); + objFac = new JcaPGPObjectFactory(comIn); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(lit.getDataStream()); + isEncodingEqual(Strings.toUTF8ByteArray("Hello World :)"), plaintext); + } + + private void decryptPKESK3OCBED1_bc() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V5KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V5OEDMessage)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + PGPSecretKey decryptionKey = secretKeys.getSecretKey(encData.getKeyID()); + PGPPrivateKey privateKey = decryptionKey.extractPrivateKey(null); + InputStream decIn = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey)); + pIn = new BCPGInputStream(decIn); + objFac = new BcPGPObjectFactory(pIn); + PGPCompressedData com = (PGPCompressedData) objFac.nextObject(); + InputStream comIn = com.getDataStream(); + objFac = new BcPGPObjectFactory(comIn); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(lit.getDataStream()); + isEncodingEqual("Plaintext mismatch", plaintext, Strings.toUTF8ByteArray("Hello World :)")); + } + + private void decryptPKESK3OCBED1_jce() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V5KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new JcaPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V5OEDMessage)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new JcaPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + PGPSecretKey decryptionKey = secretKeys.getSecretKey(encData.getKeyID()); + PGPPrivateKey privateKey = decryptionKey.extractPrivateKey(null); + InputStream decIn = encData.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder() + .setProvider(new BouncyCastleProvider()) + .build(privateKey)); + pIn = new BCPGInputStream(decIn); + objFac = new JcaPGPObjectFactory(pIn); + PGPCompressedData com = (PGPCompressedData) objFac.nextObject(); + InputStream comIn = com.getDataStream(); + objFac = new JcaPGPObjectFactory(comIn); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + byte[] plaintext = Streams.readAll(lit.getDataStream()); + isEncodingEqual("Plaintext mismatch", plaintext, Strings.toUTF8ByteArray("Hello World :)")); + } + + public static void main(String[] args) + { + runTest(new PGPv5MessageDecryptionTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6KeyTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6KeyTest.java index 053523c4f7..f9e49da04d 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6KeyTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6KeyTest.java @@ -1,22 +1,51 @@ package org.bouncycastle.openpgp.test; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Collections; +import java.util.Date; import java.util.Iterator; +import org.bouncycastle.bcpg.AEADAlgorithmTags; import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.SecretKeyPacket; +import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.bouncycastle.bcpg.sig.Features; +import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; +import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; -import org.bouncycastle.util.Arrays; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; +import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair; +import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; +import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.test.SimpleTest; public class PGPv6KeyTest - extends SimpleTest + extends AbstractPgpKeyPairTest { private static final String ARMORED_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + @@ -45,9 +74,31 @@ public class PGPv6KeyTest "M0g12vYxoWM8Y81W+bHBw805I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUr\n" + "k0mXubZvyl4GBg==\n" + "-----END PGP PRIVATE KEY BLOCK-----"; + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-locked-version-6-sec + private static final String ARMORED_PROTECTED_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xYIGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laP9JgkC\n" + + "FARdb9ccngltHraRe25uHuyuAQQVtKipJ0+r5jL4dacGWSAheCWPpITYiyfyIOPS\n" + + "3gIDyg8f7strd1OB4+LZsUhcIjOMpVHgmiY/IutJkulneoBYwrEGHxsKAAAAQgWC\n" + + "Y4d/4wMLCQcFFQoOCAwCFgACmwMCHgkiIQbLGGxPBgmml+TVLfpscisMHx4nwYpW\n" + + "cI9lJewnutmsyQUnCQIHAgAAAACtKCAQPi19In7A5tfORHHbNr/JcIMlNpAnFJin\n" + + "7wV2wH+q4UWFs7kDsBJ+xP2i8CMEWi7Ha8tPlXGpZR4UruETeh1mhELIj5UeM8T/\n" + + "0z+5oX1RHu11j8bZzFDLX9eTsgOdWATHggZjh3/jGQAAACCGkySDZ/nlAV25Ivj0\n" + + "gJXdp4SYfy1ZhbEvutFsr15ENf0mCQIUBA5hhGgp2oaavg6mFUXcFMwBBBUuE8qf\n" + + "9Ock+xwusd+GAglBr5LVyr/lup3xxQvHXFSjjA2haXfoN6xUGRdDEHI6+uevKjVR\n" + + "v5oAxgu7eJpaXNjCmwYYGwoAAAAsBYJjh3/jApsMIiEGyxhsTwYJppfk1S36bHIr\n" + + "DB8eJ8GKVnCPZSXsJ7rZrMkAAAAABAEgpukYbZ1ZNfyP5WMUzbUnSGpaUSD5t2Ki\n" + + "Nacp8DkBClZRa2c3AMQzSDXa9jGhYzxjzVb5scHDzTkjyRZWRdTq8U6L4da+/+Kt\n" + + "ruh8m7Xo2ehSSFyWRSuTSZe5tm/KXgYG\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + private static final Date CREATION_TIME = parseUTCTimestamp("2022-11-30 16:08:03 UTC"); + private static final byte[] PRIMARY_FINGERPRINT = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); private static final byte[] SUBKEY_FINGERPRINT = Hex.decode("12C83F1E706F6308FE151A417743A1F033790E93E9978488D1DB378DA9930885"); + private static final long PRIMARY_KEYID = -3812177997909612905L; + private static final long SUBKEY_KEYID = 1353401087992750856L; + private static final KeyFingerPrintCalculator fingerPrintCalculator = new BcKeyFingerprintCalculator(); @Override public String getName() @@ -59,7 +110,108 @@ public String getName() public void performTest() throws Exception { - KeyFingerPrintCalculator fingerPrintCalculator = new BcKeyFingerprintCalculator(); + parseUnprotectedCertTest(); + parseUnprotectedKeyTest(); + testJcaFingerprintCalculation(); + parseProtectedKeyTest(); + + generatePlainV6RSAKey_bc(); + } + + private void generatePlainV6RSAKey_bc() + throws PGPException, IOException + { + String uid = "Alice "; + Date creationTime = currentTimeRounded(); + RSAKeyPairGenerator rsaGen = new RSAKeyPairGenerator(); + rsaGen.init(new RSAKeyGenerationParameters( + BigInteger.valueOf(0x10001), + CryptoServicesRegistrar.getSecureRandom(), + 4096, + 100)); + AsymmetricCipherKeyPair rsaKp = rsaGen.generateKeyPair(); + + PGPKeyPair pgpKp = new BcPGPKeyPair( + PublicKeyPacket.VERSION_6, + PublicKeyAlgorithmTags.RSA_GENERAL, + rsaKp, + creationTime); + PGPPublicKey primaryKey = pgpKp.getPublicKey(); + + PGPSignatureGenerator dkSigGen = new PGPSignatureGenerator( + new BcPGPContentSignerBuilder(primaryKey.getAlgorithm(), HashAlgorithmTags.SHA3_512), + primaryKey); + dkSigGen.init(PGPSignature.DIRECT_KEY, pgpKp.getPrivateKey()); + PGPSignatureSubpacketGenerator hashed = new PGPSignatureSubpacketGenerator(); + hashed.setIssuerFingerprint(true, primaryKey); + hashed.setSignatureCreationTime(true, creationTime); + hashed.setFeature(false, (byte) (Features.FEATURE_MODIFICATION_DETECTION | Features.FEATURE_SEIPD_V2)); + hashed.setPreferredAEADCiphersuites(false, new PreferredAEADCiphersuites.Combination[]{ + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_256, AEADAlgorithmTags.OCB), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_192, AEADAlgorithmTags.OCB), + new PreferredAEADCiphersuites.Combination(SymmetricKeyAlgorithmTags.AES_128, AEADAlgorithmTags.OCB) + }); + hashed.setPreferredHashAlgorithms(false, + new int[] + { + HashAlgorithmTags.SHA3_512, HashAlgorithmTags.SHA3_256, + HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA256 + } + ); + hashed.setPreferredSymmetricAlgorithms(false, + new int[] + { + SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 + } + ); + + dkSigGen.setHashedSubpackets(hashed.generate()); + PGPSignature dkSig = dkSigGen.generateCertification(primaryKey); + + PGPSignatureGenerator uidSigGen = new PGPSignatureGenerator( + new BcPGPContentSignerBuilder(primaryKey.getAlgorithm(), HashAlgorithmTags.SHA3_512), + primaryKey); + uidSigGen.init(PGPSignature.POSITIVE_CERTIFICATION, pgpKp.getPrivateKey()); + + hashed = new PGPSignatureSubpacketGenerator(); + hashed.setIssuerFingerprint(true, primaryKey); + hashed.setSignatureCreationTime(true, creationTime); + + PGPSignature uidSig = uidSigGen.generateCertification(uid, primaryKey); + + primaryKey = PGPPublicKey.addCertification(primaryKey, dkSig); + primaryKey = PGPPublicKey.addCertification(primaryKey, uid, uidSig); + + PGPSecretKey primarySecKey = new PGPSecretKey( + pgpKp.getPrivateKey(), + primaryKey, + new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), + true, + null); + + PGPPublicKeyRing certificate = new PGPPublicKeyRing(Collections.singletonList(primaryKey)); + PGPSecretKeyRing secretKey = new PGPSecretKeyRing(Collections.singletonList(primarySecKey)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + certificate.encode(pOut); + pOut.close(); + aOut.close(); + System.out.println(bOut); + + bOut = new ByteArrayOutputStream(); + aOut = new ArmoredOutputStream(bOut); + pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + secretKey.encode(pOut); + pOut.close(); + aOut.close(); + System.out.println(bOut); + } + + private void parseUnprotectedCertTest() + throws IOException + { ByteArrayInputStream bIn = new ByteArrayInputStream(ARMORED_CERT.getBytes()); ArmoredInputStream armorIn = new ArmoredInputStream(bIn); BCPGInputStream bcIn = new BCPGInputStream(armorIn); @@ -68,22 +220,112 @@ public void performTest() Iterator pIt = publicKeys.getPublicKeys(); PGPPublicKey key = (PGPPublicKey)pIt.next(); - isTrue(Arrays.areEqual(PRIMARY_FINGERPRINT, key.getFingerprint())); + isTrue("Primary key fingerprint mismatch", key.hasFingerprint(PRIMARY_FINGERPRINT)); + isEquals("Primary key-ID mismatch", PRIMARY_KEYID, key.getKeyID()); + isEquals("Primary key version mismatch", PublicKeyPacket.VERSION_6, key.getVersion()); + isEquals("Primary key creation time mismatch", CREATION_TIME, key.getCreationTime()); + isEquals("Primary key bit-strength mismatch", 256, key.getBitStrength()); + key = (PGPPublicKey)pIt.next(); - isTrue(Arrays.areEqual(SUBKEY_FINGERPRINT, key.getFingerprint())); + isTrue("Subkey fingerprint mismatch", key.hasFingerprint(SUBKEY_FINGERPRINT)); + isEquals("Subkey key-ID mismatch", SUBKEY_KEYID, key.getKeyID()); + isEquals("Subkey version mismatch", PublicKeyPacket.VERSION_6, key.getVersion()); + isEquals("Subkey creation time mismatch", CREATION_TIME, key.getCreationTime()); + isEquals("Subkey bit-strength mismatch", 256, key.getBitStrength()); - bIn = new ByteArrayInputStream(ARMORED_KEY.getBytes()); - armorIn = new ArmoredInputStream(bIn); - bcIn = new BCPGInputStream(armorIn); + isFalse("Unexpected key object in key ring", pIt.hasNext()); + } + + private void parseUnprotectedKeyTest() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(ARMORED_KEY.getBytes()); + ArmoredInputStream armorIn = new ArmoredInputStream(bIn); + BCPGInputStream bcIn = new BCPGInputStream(armorIn); PGPSecretKeyRing secretKeys = new PGPSecretKeyRing(bcIn, fingerPrintCalculator); Iterator sIt = secretKeys.getSecretKeys(); - PGPSecretKey sKey = (PGPSecretKey)sIt.next(); - isTrue(Arrays.areEqual(PRIMARY_FINGERPRINT, sKey.getFingerprint())); + PGPSecretKey key = (PGPSecretKey)sIt.next(); + isEncodingEqual("Primary key fingerprint mismatch", PRIMARY_FINGERPRINT, key.getFingerprint()); + isEquals("Primary key-ID mismatch", PRIMARY_KEYID, key.getKeyID()); + isEquals("Primary key version mismatch", PublicKeyPacket.VERSION_6, key.getPublicKey().getVersion()); + isEquals("Primary key creation time mismatch", CREATION_TIME, key.getPublicKey().getCreationTime()); + isEquals("Primary key S2K-usage mismatch", SecretKeyPacket.USAGE_NONE, key.getS2KUsage()); + isNull("Primary key S2K MUST be null", key.getS2K()); + + key = (PGPSecretKey)sIt.next(); + isEncodingEqual("Subkey fingerprint mismatch", SUBKEY_FINGERPRINT, key.getFingerprint()); + isEquals("Subkey key-ID mismatch", SUBKEY_KEYID, key.getKeyID()); + isEquals("Subkey version mismatch", PublicKeyPacket.VERSION_6, key.getPublicKey().getVersion()); + isEquals("Subkey creation time mismatch", CREATION_TIME, key.getPublicKey().getCreationTime()); + isEquals("Subkey S2K-usage mismatch", SecretKeyPacket.USAGE_NONE, key.getS2KUsage()); + isNull("Subkey S2K MUST be null", key.getS2K()); + + isFalse("Unexpected key object in key ring", sIt.hasNext()); + } + + private void testJcaFingerprintCalculation() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(ARMORED_CERT.getBytes()); + ArmoredInputStream armorIn = new ArmoredInputStream(bIn); + BCPGInputStream bcIn = new BCPGInputStream(armorIn); + + JcaKeyFingerprintCalculator fpCalc = new JcaKeyFingerprintCalculator(); + fpCalc.setProvider(new BouncyCastleProvider()); + PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(bcIn, fpCalc); + + Iterator pIt = publicKeys.getPublicKeys(); + PGPPublicKey key = (PGPPublicKey)pIt.next(); + isTrue("Primary key fingerprint mismatch", key.hasFingerprint(PRIMARY_FINGERPRINT)); + isEquals("Primary key-ID mismatch", PRIMARY_KEYID, key.getKeyID()); + key = (PGPPublicKey)pIt.next(); + isTrue("Subkey fingerprint mismatch", key.hasFingerprint(SUBKEY_FINGERPRINT)); + isEquals("Subkey key-ID mismatch", SUBKEY_KEYID, key.getKeyID()); + } + + private void parseProtectedKeyTest() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_PROTECTED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + + PGPSecretKeyRing secretKeys = new PGPSecretKeyRing(pIn, fingerPrintCalculator); + Iterator sIt = secretKeys.getSecretKeys(); + + PGPSecretKey key = (PGPSecretKey)sIt.next(); + isEncodingEqual("Primary key fingerprint mismatch", PRIMARY_FINGERPRINT, key.getFingerprint()); + isEquals("Primary key ID mismatch", PRIMARY_KEYID, key.getKeyID()); + isEquals("Primary key algorithm mismatch", + PublicKeyAlgorithmTags.Ed25519, key.getPublicKey().getAlgorithm()); + isEquals("Primary key version mismatch", PublicKeyPacket.VERSION_6, key.getPublicKey().getVersion()); + isEquals("Primary key creation time mismatch", CREATION_TIME, key.getPublicKey().getCreationTime()); + isEquals("Primary key S2K-Usage mismatch", SecretKeyPacket.USAGE_AEAD, key.getS2KUsage()); + isEquals("Primary key AEAD algorithm mismatch", + AEADAlgorithmTags.OCB, key.getAEADKeyEncryptionAlgorithm()); + isEquals("Primary key protection algorithm mismatch", + SymmetricKeyAlgorithmTags.AES_256, key.getKeyEncryptionAlgorithm()); + isEncodingEqual("Primary key S2K salt mismatch", + Hex.decode("5d6fd71c9e096d1eb6917b6e6e1eecae"), key.getS2K().getIV()); + + key = (PGPSecretKey)sIt.next(); + isEncodingEqual("Subkey fingerprint mismatch", SUBKEY_FINGERPRINT, key.getFingerprint()); + isEquals("Subkey ID mismatch", SUBKEY_KEYID, key.getKeyID()); + isEquals("Subkey algorithm mismatch", + PublicKeyAlgorithmTags.X25519, key.getPublicKey().getAlgorithm()); + isEquals("Subkey version mismatch", PublicKeyPacket.VERSION_6, key.getPublicKey().getVersion()); + isEquals("Subkey creation time mismatch", CREATION_TIME, key.getPublicKey().getCreationTime()); + isEquals("Subkey S2K-Usage mismatch", SecretKeyPacket.USAGE_AEAD, key.getS2KUsage()); + isEquals("Subkey AEAD algorithm mismatch", + AEADAlgorithmTags.OCB, key.getAEADKeyEncryptionAlgorithm()); + isEquals("Subkey protection algorithm mismatch", + SymmetricKeyAlgorithmTags.AES_256, key.getKeyEncryptionAlgorithm()); + isEncodingEqual("Subkey S2K salt mismatch", + Hex.decode("0e61846829da869abe0ea61545dc14cc"), key.getS2K().getIV()); - sKey = (PGPSecretKey)sIt.next(); - isTrue(Arrays.areEqual(SUBKEY_FINGERPRINT, sKey.getFingerprint())); + isFalse("Unexpected key in key ring", sIt.hasNext()); } public static void main(String[] args) diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6MessageDecryptionTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6MessageDecryptionTest.java new file mode 100644 index 0000000000..d7ccf7f7ab --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6MessageDecryptionTest.java @@ -0,0 +1,209 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; +import org.bouncycastle.bcpg.PublicKeyEncSessionPacket; +import org.bouncycastle.openpgp.PGPEncryptedDataList; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSessionKey; +import org.bouncycastle.openpgp.PGPSessionKeyEncryptedData; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.SessionKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; +import org.bouncycastle.openpgp.operator.bc.BcSessionKeyDataDecryptorFactory; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.Streams; + +public class PGPv6MessageDecryptionTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "PGPv6MessageDecryptionTest"; + } + + @Override + public void performTest() + throws Exception + { + decryptMessageEncryptedUsingPKESKv6(); + decryptMessageUsingV6GopenpgpTestKey(); + decryptMessageUsingSessionKey(); + } + + private void decryptMessageEncryptedUsingPKESKv6() + throws IOException, PGPException + { + // X25519 test key from rfc9580 + String key = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xUsGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laMAGXKB\n" + + "exK+cH6NX1hs5hNhIB00TrJmosgv3mg1ditlsLfCsQYfGwoAAABCBYJjh3/jAwsJ\n" + + "BwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lwgyU2kCcUmKfvBXbAf6rh\n" + + "RYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaEQsiPlR4zxP/TP7mhfVEe\n" + + "7XWPxtnMUMtf15OyA51YBMdLBmOHf+MZAAAAIIaTJINn+eUBXbki+PSAld2nhJh/\n" + + "LVmFsS+60WyvXkQ1AE1gCk95TUR3XFeibg/u/tVY6a//1q0NWC1X+yui3O24wpsG\n" + + "GBsKAAAALAWCY4d/4wKbDCIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAAQBIKbpGG2dWTX8j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDE\n" + + "M0g12vYxoWM8Y81W+bHBw805I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUr\n" + + "k0mXubZvyl4GBg==\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(key)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + pIn.close(); + aIn.close(); + bIn.close(); + + // created using rpgpie 0.1.1 (rpgp 0.14.0-alpha.0) + String MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "wW0GIQYSyD8ecG9jCP4VGkF3Q6HwM3kOk+mXhIjR2zeNqZMIhRk5Bu/DU62hzgRm\n" + + "JYvBYeLA2Nrmz15g69ZN0xAB7SLDRCjjhnK6V7fGns6P1EiSCYbl1uNVBhK0MPGe\n" + + "rU9FY4yUXTnbB6eIXdCw0loCCQIOu95D17wvJJC2a96ou9SGPIoA4Q2dMH5BMS9Z\n" + + "veq3AGgIBdJMF8Ft8PBE30R0cba1O5oQC0Eiscw7fkNnYGuSXagqNXdOBkHDN0fk\n" + + "VWFrxQRbxEVYUWc=\n" + + "=u2kL\n" + + "-----END PGP MESSAGE-----\n"; + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(MSG)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + + isEquals("PKESK version mismatch", + PublicKeyEncSessionPacket.VERSION_6, encData.getVersion()); + isEquals("Public key algorithm mismatch", + PublicKeyAlgorithmTags.X25519, encData.getAlgorithm()); + PGPSecretKey decryptionKey = secretKeys.getSecretKey(encData.getKeyID()); // TODO: getKeyIdentifier() + isNotNull("Decryption key MUST be identifiable", decryptionKey); + PGPPrivateKey privateKey = decryptionKey.extractPrivateKey(null); + PublicKeyDataDecryptorFactory decryptor = new BcPublicKeyDataDecryptorFactory(privateKey); + InputStream decrypted = encData.getDataStream(decryptor); + PGPObjectFactory decFac = new BcPGPObjectFactory(decrypted); + PGPLiteralData lit = (PGPLiteralData) decFac.nextObject(); + isEncodingEqual("Message plaintext mismatch", + Strings.toUTF8ByteArray("Hello World :)"), + Streams.readAll(lit.getDataStream())); + } + + private void decryptMessageUsingV6GopenpgpTestKey() + throws IOException, PGPException + { + // Ed448/X448 test key + // Courtesy of @twiss from Proton + String key = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xX0GZrnFtRwAAAA5wl2q+bhfNkzHsxlLowaUy0sTOeAsmhseHBvPKKc7yehR\n" + + "8Qs93LbjQHjw3IaqduMRDRs4pZJyV/+AACKFtkkC3ebcyaOvHGaJpc9rx0Z1\n" + + "4YHdd4BG1AJvZuhk8pJ6dQuuQeFtBsQctoktFwlDh0XjnjUrkMLALQYfHAoA\n" + + "AABMBYJmucW1AwsJBwUVCAoMDgQWAAIBApsDAh4JIqEGEvURGalOLHznAmcI\n" + + "MRsEHorGZ2ikxHawiPyOMw+CAOANJwkDBwMJAQcBCQIHAgAAAACbfCBvUoq6\n" + + "bon1bSsp9HLc829xjDINBOvegmk4tMKv392c1LNPJacojQ46YZpkNVhE4sSx\n" + + "Gf/vdUqh62KP+vwm5cXs/f11WmdVnclv7uR9s3a1GI79lwOJiuw3AIXA3VjR\n" + + "+AhmeoAFJRfcjfT3hwwkBdu8E3BQ+1bGqfXGhOPYcDTJOO+vMExGSTEk+A9j\n" + + "DmWnW6snAMd7Bma5xbUaAAAAOAPvCJKYxSQ+SfLb313/tC9N2tGF00x6YJkz\n" + + "JLqLKVDofMHmUC1f8IJFtQ3cLMDhHVY0VxffLXT1AEffhVpafxBdelL69esq\n" + + "2zQtDp5l8Hx7D/sU+W3+KmGLnRki72g7gfoQuio+wk8UcHmfwYm7AHvuwsAN\n" + + "BhgcCgAAACwFgma5xbUCmwwioQYS9REZqU4sfOcCZwgxGwQeisZnaKTEdrCI\n" + + "/I4zD4IA4AAAAACQUiBvjI1gFe4O/GDPwIoX8YSK/qP3IsMAwvidXclpmlLN\n" + + "RzPkkfUzRgZw8+AHZxV62TPWhxrZETAuEaahrQ6HViQRAfk60gLvT37iWZrG\n" + + "BU64272NrJ+UFXrzAEKZ/HK+hIL6yZvYDqIxWBg3Pwt9YxgpOfJ8UeYcrEx3\n" + + "B1Hkd6QprSOLFCj53zZ++q3SZkWYz28gAA==\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(key)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + pIn.close(); + aIn.close(); + bIn.close(); + + // created using gosop 430bb02923c123e39815814f6b97a6d501bdde6a + // ./gosop encrypt --profile=rfc9580 cert.asc < msg.plain > msg.asc + String MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "wYUGIQaz5Iy7+n5O1bg87Cy2PfSolKK6L8cwIPLJnEeZFjMu2xoAfSM/MwQpXahy\n" + + "Od1pknhDyw3X5EgxQG0EffQCMpaKsNtqvVGYBJ5chuAcV/8gayReP/g6RREGeyj4\n" + + "Vc2dgJ67/KwaP0Z7k7vExHs79U24DsrU088QbYhk/XLvJHWlXXj90loCCQMMIvmD\n" + + "KS5f5WYbntB4N+FspsbQ7GN6taOrAqUtEuKWKzrlhZdtg9qGG4RLCvX1vfL0u6NV\n" + + "Yzk9fGVgty73B8pmyYdefLdWt87ljwr8wGGX/Dl8PSBIE3w=\n" + + "-----END PGP MESSAGE-----\n"; + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(MSG)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encList.get(0); + + isEquals("PKESK version mismatch", + PublicKeyEncSessionPacket.VERSION_6, encData.getVersion()); + isEquals("Public Key algorithm mismatch", + PublicKeyAlgorithmTags.X448, encData.getAlgorithm()); + PGPSecretKey decryptionKey = secretKeys.getSecretKey(encData.getKeyID()); // TODO: getKeyIdentifier() + isNotNull("Decryption key MUST be identifiable", decryptionKey); + PGPPrivateKey privateKey = decryptionKey.extractPrivateKey(null); + PublicKeyDataDecryptorFactory decryptor = new BcPublicKeyDataDecryptorFactory(privateKey); + InputStream decrypted = encData.getDataStream(decryptor); + PGPObjectFactory decFac = new BcPGPObjectFactory(decrypted); + PGPLiteralData lit = (PGPLiteralData) decFac.nextObject(); + isEncodingEqual("Message plaintext mismatch", + Strings.toUTF8ByteArray("Hello, World!\n"), + Streams.readAll(lit.getDataStream())); + } + + private void decryptMessageUsingSessionKey() + throws IOException, PGPException + { + // created using gosop 430bb02923c123e39815814f6b97a6d501bdde6a + // ./gosop encrypt --profile=rfc9580 cert.asc < msg.plain > msg.asc + String MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "wYUGIQaz5Iy7+n5O1bg87Cy2PfSolKK6L8cwIPLJnEeZFjMu2xoAfSM/MwQpXahy\n" + + "Od1pknhDyw3X5EgxQG0EffQCMpaKsNtqvVGYBJ5chuAcV/8gayReP/g6RREGeyj4\n" + + "Vc2dgJ67/KwaP0Z7k7vExHs79U24DsrU088QbYhk/XLvJHWlXXj90loCCQMMIvmD\n" + + "KS5f5WYbntB4N+FspsbQ7GN6taOrAqUtEuKWKzrlhZdtg9qGG4RLCvX1vfL0u6NV\n" + + "Yzk9fGVgty73B8pmyYdefLdWt87ljwr8wGGX/Dl8PSBIE3w=\n" + + "-----END PGP MESSAGE-----\n"; + String SESSION_KEY = "9:47343387303C170873252051978966871EE2EA0F68D975F061AF022B78B165C1"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(MSG)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPEncryptedDataList encList = (PGPEncryptedDataList) objFac.nextObject(); + PGPSessionKeyEncryptedData encData = encList.extractSessionKeyEncryptedData(); + SessionKeyDataDecryptorFactory decryptor = new BcSessionKeyDataDecryptorFactory( + PGPSessionKey.fromAsciiRepresentation(SESSION_KEY)); + + InputStream decrypted = encData.getDataStream(decryptor); + PGPObjectFactory decFac = new BcPGPObjectFactory(decrypted); + PGPLiteralData lit = (PGPLiteralData) decFac.nextObject(); + isEncodingEqual("Message plaintext mismatch", + Strings.toUTF8ByteArray("Hello, World!\n"), + Streams.readAll(lit.getDataStream())); + } + + public static void main(String[] args) + { + runTest(new PGPv6MessageDecryptionTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6SignatureTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6SignatureTest.java new file mode 100644 index 0000000000..3f3377f642 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPv6SignatureTest.java @@ -0,0 +1,915 @@ +package org.bouncycastle.openpgp.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Iterator; + +import org.bouncycastle.bcpg.ArmoredInputStream; +import org.bouncycastle.bcpg.ArmoredOutputStream; +import org.bouncycastle.bcpg.BCPGInputStream; +import org.bouncycastle.bcpg.BCPGOutputStream; +import org.bouncycastle.bcpg.HashAlgorithmTags; +import org.bouncycastle.bcpg.PacketFormat; +import org.bouncycastle.bcpg.SignatureSubpacket; +import org.bouncycastle.bcpg.SignatureSubpacketTags; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; +import org.bouncycastle.bcpg.test.AbstractPacketTest; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPKeyRing; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPLiteralDataGenerator; +import org.bouncycastle.openpgp.PGPObjectFactory; +import org.bouncycastle.openpgp.PGPOnePassSignature; +import org.bouncycastle.openpgp.PGPOnePassSignatureList; +import org.bouncycastle.openpgp.PGPPrivateKey; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.PGPPublicKeyRing; +import org.bouncycastle.openpgp.PGPSecretKey; +import org.bouncycastle.openpgp.PGPSecretKeyRing; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.openpgp.PGPSignatureGenerator; +import org.bouncycastle.openpgp.PGPSignatureList; +import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; +import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.io.Streams; + +public class PGPv6SignatureTest + extends AbstractPacketTest +{ + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-version-6-certificat + private static final String ARMORED_CERT = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + + "\n" + + "xioGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laPCsQYf\n" + + "GwoAAABCBYJjh3/jAwsJBwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxy\n" + + "KwwfHifBilZwj2Ul7Ce62azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lw\n" + + "gyU2kCcUmKfvBXbAf6rhRYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaE\n" + + "QsiPlR4zxP/TP7mhfVEe7XWPxtnMUMtf15OyA51YBM4qBmOHf+MZAAAAIIaTJINn\n" + + "+eUBXbki+PSAld2nhJh/LVmFsS+60WyvXkQ1wpsGGBsKAAAALAWCY4d/4wKbDCIh\n" + + "BssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce62azJAAAAAAQBIKbpGG2dWTX8\n" + + "j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDEM0g12vYxoWM8Y81W+bHBw805\n" + + "I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUrk0mXubZvyl4GBg==\n" + + "-----END PGP PUBLIC KEY BLOCK-----"; + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-version-6-secret-key + private static final String ARMORED_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "\n" + + "xUsGY4d/4xsAAAAg+U2nu0jWCmHlZ3BqZYfQMxmZu52JGggkLq2EVD34laMAGXKB\n" + + "exK+cH6NX1hs5hNhIB00TrJmosgv3mg1ditlsLfCsQYfGwoAAABCBYJjh3/jAwsJ\n" + + "BwUVCg4IDAIWAAKbAwIeCSIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJBScJAgcCAAAAAK0oIBA+LX0ifsDm185Ecds2v8lwgyU2kCcUmKfvBXbAf6rh\n" + + "RYWzuQOwEn7E/aLwIwRaLsdry0+VcallHhSu4RN6HWaEQsiPlR4zxP/TP7mhfVEe\n" + + "7XWPxtnMUMtf15OyA51YBMdLBmOHf+MZAAAAIIaTJINn+eUBXbki+PSAld2nhJh/\n" + + "LVmFsS+60WyvXkQ1AE1gCk95TUR3XFeibg/u/tVY6a//1q0NWC1X+yui3O24wpsG\n" + + "GBsKAAAALAWCY4d/4wKbDCIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAAQBIKbpGG2dWTX8j+VjFM21J0hqWlEg+bdiojWnKfA5AQpWUWtnNwDE\n" + + "M0g12vYxoWM8Y81W+bHBw805I8kWVkXU6vFOi+HWvv/ira7ofJu16NnoUkhclkUr\n" + + "k0mXubZvyl4GBg==\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + + @Override + public String getName() + { + return "PGPv6SignatureTest"; + } + + @Override + public void performTest() + throws Exception + { + verifySignatureOnTestKey(); + verifyKnownGoodCleartextSignedMessage(); + + verifyV6DetachedSignature(); + verifyV6InlineSignature(); + verifyV6CleartextSignature(); + + generateAndVerifyV6DetachedSignature(); + generateAndVerifyV6InlineSignature(); + generateAndVerifyV6CleartextSignature(); + + verifyingSignatureWithMismatchedSaltSizeFails(); + verifyingOPSWithMismatchedSaltSizeFails(); + verifyingInlineSignatureWithSignatureSaltValueMismatchFails(); + + verifySignaturesOnEd448X448Key(); + generateAndVerifyInlineSignatureUsingRSAKey(); + + testVerificationOfV4SigWithV6KeyFails(); + } + + /** + * Verify that the known-good key signatures on the minimal test key verify properly. + */ + private void verifySignatureOnTestKey() + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_CERT)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + + PGPPublicKeyRing cert = (PGPPublicKeyRing) objFac.nextObject(); + PGPPublicKey primaryKey = cert.getPublicKey(Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9")); + PGPPublicKey subkey = cert.getPublicKey(Hex.decode("12C83F1E706F6308FE151A417743A1F033790E93E9978488D1DB378DA9930885")); + + PGPSignature directKeySig = (PGPSignature)primaryKey.getKeySignatures().next(); + PGPSignature subkeyBinding = (PGPSignature)subkey.getKeySignatures().next(); + + directKeySig.init(new BcPGPContentVerifierBuilderProvider(), primaryKey); + isTrue("Direct-Key Signature on the primary key MUST be correct.", + directKeySig.verifyCertification(primaryKey)); + + subkeyBinding.init(new BcPGPContentVerifierBuilderProvider(), primaryKey); + isTrue("Subkey-Binding Signature MUST be correct.", + subkeyBinding.verifyCertification(primaryKey, subkey)); + } + + private void verifyKnownGoodCleartextSignedMessage() throws IOException, PGPException { + // https://www.rfc-editor.org/rfc/rfc9580.html#name-sample-cleartext-signed-mes + String MSG = "-----BEGIN PGP SIGNED MESSAGE-----\n" + + "\n" + + "What we need from the grocery store:\n" + + "\n" + + "- - tofu\n" + + "- - vegetables\n" + + "- - noodles\n" + + "\n" + + "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wpgGARsKAAAAKQWCY5ijYyIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAGk2IHZJX1AhiJD39eLuPBgiUU9wUA9VHYblySHkBONKU/usJ9BvuAqo\n" + + "/FvLFuGWMbKAdA+epq7V4HOtAPlBWmU8QOd6aud+aSunHQaaEJ+iTFjP2OMW0KBr\n" + + "NK2ay45cX1IVAQ==\n" + + "-----END PGP SIGNATURE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_CERT)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPPublicKeyRing cert = (PGPPublicKeyRing) objFac.nextObject(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(MSG)); + aIn = new ArmoredInputStream(bIn); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + while (aIn.isClearText()) + { + int c = aIn.read(); + if (aIn.isClearText()) + { + bOut.write(c); + } + } + byte[] plaintext = Arrays.copyOf(bOut.toByteArray(), bOut.size()- 1); + objFac = new BcPGPObjectFactory(aIn); + PGPSignatureList sigs = (PGPSignatureList) objFac.nextObject(); + PGPSignature sig = sigs.get(0); + sig.init(new BcPGPContentVerifierBuilderProvider(), cert.getPublicKey(sig.getKeyID())); + sig.update(plaintext); + isTrue("Known good cleartext signature MUST verify successful", sig.verify()); + } + + /** + * Verify that a good v6 detached signature is verified properly. + */ + private void verifyV6DetachedSignature() + throws IOException, PGPException + { + String msg = "Hello, World!\n"; + String ARMORED_SIG = "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wpgGABsKAAAAKSKhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce62azJBYJm\n" + + "gm9ZAAAAAHbbIIiAPSgC+KgRmEnYT3DlWRRXD3FZbagaoUrQy6hBg+exB/J/zqCD\n" + + "WQDNfRrJsKzt5NNgDtlpOPwJocYPL3LTvYIDDTTxmD1WFMaeF/mDgo1DJfcRCkXt\n" + + "PXdpdVaImaOqDA==\n" + + "-----END PGP SIGNATURE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + PGPPublicKey signingPubKey = secretKeys.getPublicKey(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_SIG)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + PGPSignature binarySig = sigList.get(0); + + binarySig.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + binarySig.update(Strings.toUTF8ByteArray(msg)); + isTrue("Detached binary signature MUST be valid.", + binarySig.verify()); + } + + /** + * Verify that a good v6 inline signature is verified properly. + */ + private void verifyV6InlineSignature() + throws IOException, PGPException + { + String ARMORED_MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "xEYGAQobIMcgFZRFzyKmYrqqNES9B0geVN5TZ6Wct6aUrITCuFyeyxhsTwYJppfk\n" + + "1S36bHIrDB8eJ8GKVnCPZSXsJ7rZrMkAyxR1AAAAAABIZWxsbywgV29ybGQhCsKY\n" + + "BgEbCgAAACkioQbLGGxPBgmml+TVLfpscisMHx4nwYpWcI9lJewnutmsyQWCZoJv\n" + + "WQAAAAAkFSDHIBWURc8ipmK6qjREvQdIHlTeU2elnLemlKyEwrhcnotltzKi2NN+\n" + + "XNJISXQ0X0f4TppBoHbpmwc5YCTIv2+vDZPI+tjzXL9m2e1jrqqaUMEwQ+Zy8B+K\n" + + "LC4rA6Gh2gY=\n" + + "-----END PGP MESSAGE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + PGPPublicKey signingPubKey = secretKeys.getPublicKey(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_MSG)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + + PGPOnePassSignatureList opsList = (PGPOnePassSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly 1 OPS", 1, opsList.size()); + PGPOnePassSignature ops = opsList.get(0); + + ops.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(lit.getDataStream(), plainOut); + + ops.update(plainOut.toByteArray()); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly one signature", 1, sigList.size()); + PGPSignature sig = sigList.get(0); + isTrue("Verifying OPS signature MUST succeed", ops.verify(sig)); + } + + /** + * Verify that a good v6 cleartext signature is verified properly. + */ + private void verifyV6CleartextSignature() + throws IOException, PGPException + { + String CLEARTEXT_MSG = "-----BEGIN PGP SIGNED MESSAGE-----\n" + + "\n" + + "Hello, World!\n" + + "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wpgGARsKAAAAKSKhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce62azJBYJm\n" + + "gm9ZAAAAAOwrIHtJrY7SIiXXqaBpEbjlJvpviklWkAvMJOLLmVt+hy7wvLNKZEhu\n" + + "ZKiy7zgFRoXTwtVVHyBlTvRoMKN7NhfN5UoDaV3isn0uipMR7YoZTxacQmg3CQlM\n" + + "NOaSt0xdZMqnBw==\n" + + "-----END PGP SIGNATURE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + PGPPublicKey signingPubKey = secretKeys.getPublicKey(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(CLEARTEXT_MSG)); + aIn = new ArmoredInputStream(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + while (aIn.isClearText()) + { + int c = aIn.read(); + if (aIn.isClearText()) + { + plainOut.write(c); + } + } + isEncodingEqual("Plaintext MUST match", + Strings.toUTF8ByteArray("Hello, World!\n"), plainOut.toByteArray()); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly 1 signature.", 1, sigList.size()); + PGPSignature sig = sigList.get(0); + sig.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + sig.update(Strings.toUTF8ByteArray("Hello, World!")); + isTrue("Cleartext Signature MUST verify successfully", sig.verify()); + } + + /** + * A v6 signature with too few salt bytes. + * This test verifies that the signature is properly rejected. + */ + private void verifyingSignatureWithMismatchedSaltSizeFails() + throws IOException + { + // v6 signature made using SHA512 with 16 instead of 32 bytes of salt. + String armoredSig = "-----BEGIN PGP SIGNATURE-----\n" + + "Version: BCPG v@RELEASE_NAME@\n" + + "\n" + + "wogGABsKAAAAKSKhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce62azJBYJm\n" + + "gXv9AAAAAGHvEIB9K2RLSK++vMVKnivhTgBBHon1f/feri7mJOAYfGm8vOzgbc/8\n" + + "/zeeT3ZY+EK3q6RQ6W0nolelQejFuy1w9duC8/1U/oTD6iSi1pRAEm4M\n" + + "=mBNb\n" + + "-----END PGP SIGNATURE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + PGPPublicKey signingPubKey = secretKeys.getPublicKey(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armoredSig)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + PGPSignature binarySig = sigList.get(0); + + try + { + binarySig.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + fail("Initiating verification of signature with mismatched salt size MUST fail."); + } + catch (PGPException e) + { + // expected + } + } + + /** + * Verify that a OPS signature where the length of the salt array does not match the expectations + * is rejected properly. + */ + private void verifyingOPSWithMismatchedSaltSizeFails() + throws IOException + { + // v6 signature made using SHA512 with 16 instead of 32 bytes of salt. + String armoredMsg = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "xDYGAQobEKM41oT/St9iR6qxoR2RndzLGGxPBgmml+TVLfpscisMHx4nwYpWcI9l\n" + + "JewnutmsyQDLFHUAAAAAAEhlbGxvLCBXb3JsZCEKwogGARsKAAAAKSKhBssYbE8G\n" + + "CaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce62azJBYJmgXv9AAAAAHU6EKM41oT/St9i\n" + + "R6qxoR2RndzKyHgSHsO9QIzLibxeWtny69R0srOsJVFr153JlXSlUojGxv00QvlY\n" + + "z90jECs8awk7vCeJxTHrHFL01Xy5sTsN\n" + + "-----END PGP MESSAGE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + PGPPublicKey signingPubKey = secretKeys.getPublicKey(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armoredMsg)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + + PGPOnePassSignatureList opsList = (PGPOnePassSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly 1 OPS", 1, opsList.size()); + PGPOnePassSignature ops = opsList.get(0); + + try + { + ops.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + fail("Initiating verification of OPS with mismatched salt size MUST fail."); + } + catch (PGPException e) + { + // expected. + } + } + + /** + * Test verifying that an inline signature where the salt of the OPS packet mismatches that of the signature + * is rejected properly. + */ + private void verifyingInlineSignatureWithSignatureSaltValueMismatchFails() + throws IOException, PGPException + { + String ARMORED_MSG = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "xEYGAQobIMcgFZRFzyKmYrqqNES9B0geVN5TZ6Wct6aUrITCuFyeyxhsTwYJppfk\n" + + "1S36bHIrDB8eJ8GKVnCPZSXsJ7rZrMkAyxR1AAAAAABIZWxsbywgV29ybGQhCsKY\n" + + "BgEbCgAAACkioQbLGGxPBgmml+TVLfpscisMHx4nwYpWcI9lJewnutmsyQWCZoJv\n" + + "WQAAAAAkFSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAItltzKi2NN+\n" + + "XNJISXQ0X0f4TppBoHbpmwc5YCTIv2+vDZPI+tjzXL9m2e1jrqqaUMEwQ+Zy8B+K\n" + + "LC4rA6Gh2gY=\n" + + "=KRD3\n" + + "-----END PGP MESSAGE-----"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + PGPPublicKey signingPubKey = secretKeys.getPublicKey(); + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_MSG)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + + PGPOnePassSignatureList opsList = (PGPOnePassSignatureList) objFac.nextObject(); + PGPOnePassSignature ops = opsList.get(0); + isEncodingEqual("OPS salt MUST match our expectations.", + Hex.decode("C720159445CF22A662BAAA3444BD07481E54DE5367A59CB7A694AC84C2B85C9E"), + ops.getSalt()); + + ops.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(lit.getDataStream(), plainOut); + + ops.update(plainOut.toByteArray()); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + PGPSignature sig = sigList.get(0); + + try + { + ops.verify(sig); + fail("Verifying signature with mismatched salt MUST fail."); + } + catch (PGPException e) + { + // expected + } + } + + /** + * Verify self signatures on a v6 Ed448/X448 key. + */ + private void verifySignaturesOnEd448X448Key() + throws PGPException, IOException + { + String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Comment: 8cf27d01 f6160563 9e4b8525 353c0cfb f5a23e45 96c47fe6 d90ccacf 3293d5d6\n" + + "Comment: 93c07acb 9eef9fa2 346ac1d5 ff50051c 96124504 e2fb3b5b 564bf969 16d28d42\n" + + "Comment: Ed \n" + + "\n" + + "xX8GZovgyRwAAAA529b1jdB2Cgndd45hbN3qxpTbTM9IpdLJ8ibifS5ranMF8g+w\n" + + "vQfvV2HNwONn1mC+/7yxGLzW9YQAAMM1xRUHrZdL6vcIOugjQ9YDzaoM8nV+6RfN\n" + + "05CJCcJLp2eM0t015rw6UCcGGL7gy5TOFeLhGMU59x2IwsAjBh8cDgAAAEIFgmaL\n" + + "4MkDCwkHBRUKDggMAhYAApsDAh4JIiEGjPJ9AfYWBWOeS4UlNTwM+/WiPkWWxH/m\n" + + "2QzKzzKT1dYFJwkCBwIAAAAA9fcgS0FBeDv6TwF/camy0KEZRHDNIpEI0upB+4vU\n" + + "kyYab1MiKfpfIkZfqCFCikuR8yW6yIFKNXQK/B9nemfwzq6UNrdUZkZL9BpUfXsq\n" + + "xlOJ3ksehQrH8SM9ZgAkk+H0WQyKgakBmw8T74vz44Pej2oAU8w50OtJ81duKIdN\n" + + "bsFF0WiU1PYeLbEPfDjnB2x1lINQCQDNFkVkIDxlZDQ0OEBleGFtcGxlLmNvbT7C\n" + + "wAoGExwKAAAAKQWCZovgySIhBozyfQH2FgVjnkuFJTU8DPv1oj5FlsR/5tkMys8y\n" + + "k9XWAAAAADlTIC14mbBrJQ9/qWzRmS5FHVcJkx87OZ9/573lMDcNM+sMIUQP8b/L\n" + + "c2sLKtzGpQGXG1ETp/MOlGSQaMF6l/3eQpnVZg3jEO0Qd2040Leq4TQqNaFJBMmt\n" + + "wg2ADddE3CkwzMhBG00yhppY2p6xsvGgYVz3vMCQ2MnH/0Hj+9bmzSoJDM/4gXe3\n" + + "HXI1kuEOPFINmi0Ax30GZovgyRoAAAA4SRrAL6zM93X89gPFjMA3D9vjprB0pB7m\n" + + "fVr/c3UPaS/H5ILrcgbvcpwf+D7H1n2DZq2N4MqXvzoANBS7o2zj3FQO80Reagx2\n" + + "ZTav2DzRHNl4M626qkGyUD4u393yIU0u8KMPTZstT43zWqVn3ZzPJJAbdcLADQYY\n" + + "HA4AAAAsIiEGjPJ9AfYWBWOeS4UlNTwM+/WiPkWWxH/m2QzKzzKT1dYFgmaL4MkC\n" + + "mwwAAAAAGPAg10+uyPMPtyB8bomChz/rokK7pTV5AgIjulbOuEVSLkQPXRn06gMn\n" + + "TleudzUKY3mh3Cm01DAVg+5GWQz9F0qWebwzsjUiGqMt7ovySZw4Qkv+lBPkKSxN\n" + + "uwDxqjLecoGbL6nM4mGMU+27dlZRjjpHVWRGur6tup5IBWsX97zKYYrsTE2HCVOC\n" + + "rm3bgQD1eeP0CQA=\n" + + "-----END PGP PRIVATE KEY BLOCK-----"; + verifySignaturesOnKey(KEY); + } + + private void verifySignaturesOnKey(String armoredKey) + throws IOException, PGPException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(armoredKey)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + Iterator pubKeys = secretKeys.getPublicKeys(); + PGPPublicKey primaryKey = (PGPPublicKey)pubKeys.next(); + + Iterator directKeySigs = primaryKey.getSignaturesOfType(PGPSignature.DIRECT_KEY); + while (directKeySigs.hasNext()) + { + PGPSignature dkSig = (PGPSignature)directKeySigs.next(); + PGPPublicKey sigKey = getSigningKeyFor(secretKeys, dkSig); + if (sigKey != null) + { + dkSig.init(new BcPGPContentVerifierBuilderProvider(), sigKey); + isTrue("Direct-Key Signature MUST verify", dkSig.verifyCertification(sigKey)); + } + else + { + // -DM System.out.println + System.out.println("Did not find signing key for DK sig"); + } + } + + Iterator uids = primaryKey.getUserIDs(); + while (uids.hasNext()) + { + String uid = (String)uids.next(); + Iterator uidSigs = primaryKey.getSignaturesForID(uid); + while (uidSigs.hasNext()) + { + PGPSignature uidSig = (PGPSignature)uidSigs.next(); + PGPPublicKey sigKey = getSigningKeyFor(secretKeys, uidSig); + if (sigKey != null) + { + uidSig.init(new BcPGPContentVerifierBuilderProvider(), sigKey); + isTrue("UID Signature for " + uid + " MUST verify", + uidSig.verifyCertification(uid, sigKey)); + } + else + { + // -DM System.out.println + System.out.println("Did not find signing key for UID sig for " + uid); + } + } + } + + while (pubKeys.hasNext()) + { + PGPPublicKey subkey = (PGPPublicKey)pubKeys.next(); + Iterator bindSigs = subkey.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); + while (bindSigs.hasNext()) + { + PGPSignature bindSig = (PGPSignature)bindSigs.next(); + PGPPublicKey sigKey = getSigningKeyFor(secretKeys, bindSig); + if (sigKey != null) + { + bindSig.init(new BcPGPContentVerifierBuilderProvider(), sigKey); + isTrue("Subkey binding signature MUST verify", + bindSig.verifyCertification(sigKey, subkey)); + } + else + { + // -DM System.out.println + // -DM Hex.toHexString + System.out.println("Did not find singing key for subkey " + Hex.toHexString(subkey.getFingerprint()) + " binding signature"); + } + } + } + } + + private PGPPublicKey getSigningKeyFor(PGPKeyRing keys, PGPSignature sig) + { + Iterator pubKeys = keys.getPublicKeys(); + while (pubKeys.hasNext()) + { + PGPPublicKey k = (PGPPublicKey)pubKeys.next(); + if (k.getKeyID() == sig.getKeyID()) + { + return k; + } + + SignatureSubpacket[] subpackets = sig.getHashedSubPackets().getSubpackets(SignatureSubpacketTags.ISSUER_FINGERPRINT); + for (int idx = 0; idx != subpackets.length; idx++) + { + SignatureSubpacket p = subpackets[idx]; + IssuerFingerprint fp = (IssuerFingerprint) p; + if (Arrays.areEqual(k.getFingerprint(), fp.getFingerprint())) + { + return k; + } + } + + subpackets = sig.getHashedSubPackets().getSubpackets(SignatureSubpacketTags.ISSUER_FINGERPRINT); + for (int idx = 0; idx != subpackets.length; idx++) + { + SignatureSubpacket p = subpackets[idx]; + IssuerFingerprint fp = (IssuerFingerprint) p; + if (Arrays.areEqual(k.getFingerprint(), fp.getFingerprint())) + { + return k; + } + } + } + return null; + } + + /** + * Generate and verify a detached v6 signature using the v6 test key. + */ + private void generateAndVerifyV6DetachedSignature() + throws IOException, PGPException + { + String msg = "Hello, World!\n"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + PGPSecretKey signingSecKey = secretKeys.getSecretKey(); // primary key + PGPPrivateKey signingPrivKey = signingSecKey.extractPrivateKey(null); + PGPPublicKey signingPubKey = signingSecKey.getPublicKey(); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator( + new BcPGPContentSignerBuilder( + signingPubKey.getAlgorithm(), + HashAlgorithmTags.SHA512), + signingPubKey); + sigGen.init(PGPSignature.BINARY_DOCUMENT, signingPrivKey); + sigGen.update(Strings.toUTF8ByteArray(msg)); + PGPSignature binarySig = sigGen.generate(); + + binarySig.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + binarySig.update(Strings.toUTF8ByteArray(msg)); + isTrue("Detached binary signature MUST verify successful.", + binarySig.verify()); + } + + /** + * Generate and verify a v6 inline signature using the v6 test key. + */ + private void generateAndVerifyV6InlineSignature() + throws IOException, PGPException + { + String msg = "Hello, World!\n"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + PGPSecretKey signingSecKey = secretKeys.getSecretKey(); // primary key + PGPPrivateKey signingPrivKey = signingSecKey.extractPrivateKey(null); + PGPPublicKey signingPubKey = signingSecKey.getPublicKey(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = ArmoredOutputStream.builder() + .clearHeaders() + .enableCRC(false) + .build(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + + PGPSignatureGenerator sigGen = new PGPSignatureGenerator( + new BcPGPContentSignerBuilder(signingPubKey.getAlgorithm(), HashAlgorithmTags.SHA512), signingPubKey); + sigGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, signingPrivKey); + sigGen.generateOnePassVersion(true).encode(pOut); + + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + OutputStream litOut = litGen.open(pOut, PGPLiteralDataGenerator.UTF8, "", PGPLiteralDataGenerator.NOW, new byte[512]); + + litOut.write(Strings.toUTF8ByteArray(msg)); + litOut.close(); + + sigGen.update(Strings.toUTF8ByteArray(msg)); + sigGen.generate().encode(pOut); + + pOut.close(); + aOut.close(); + + bIn = new ByteArrayInputStream(bOut.toByteArray()); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + + PGPOnePassSignatureList opsList = (PGPOnePassSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly 1 OPS", 1, opsList.size()); + PGPOnePassSignature ops = opsList.get(0); + + ops.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + Streams.pipeAll(lit.getDataStream(), plainOut); + isEncodingEqual("Content of LiteralData packet MUST match plaintext", + Strings.toUTF8ByteArray(msg), plainOut.toByteArray()); + + ops.update(plainOut.toByteArray()); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly one signature", 1, sigList.size()); + PGPSignature sig = sigList.get(0); + isTrue("Generated Inline OPS signature MUST verify successful", ops.verify(sig)); + } + + /** + * Generate and verify a v6 signature using the cleartext signature framework and the v6 test key. + */ + private void generateAndVerifyV6CleartextSignature() + throws IOException, PGPException + { + String msg = "Hello, World!\n"; + String msgS = "Hello, World!"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + PGPSecretKey signingSecKey = secretKeys.getSecretKey(); // primary key + PGPPrivateKey signingPrivKey = signingSecKey.extractPrivateKey(null); + PGPPublicKey signingPubKey = signingSecKey.getPublicKey(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = ArmoredOutputStream.builder() + .clearHeaders() + .enableCRC(false) + .build(bOut); + + PGPSignatureGenerator sigGen = new PGPSignatureGenerator( + new BcPGPContentSignerBuilder(signingPubKey.getAlgorithm(), HashAlgorithmTags.SHA512), + signingPubKey); + sigGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, signingPrivKey); + + aOut.beginClearText(HashAlgorithmTags.SHA512); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + + sigGen.update(Strings.toUTF8ByteArray(msgS)); + aOut.write(Strings.toUTF8ByteArray(msg)); + + aOut.endClearText(); + sigGen.generate().encode(pOut); + pOut.close(); + aOut.close(); + + // Verify + bIn = new ByteArrayInputStream(bOut.toByteArray()); + aIn = new ArmoredInputStream(bIn); + ByteArrayOutputStream plainOut = new ByteArrayOutputStream(); + while (aIn.isClearText()) + { + int c = aIn.read(); + if (aIn.isClearText()) + { + plainOut.write(c); + } + } + isEncodingEqual("Plaintext MUST match", Strings.toUTF8ByteArray(msg), plainOut.toByteArray()); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + isEquals("There MUST be exactly 1 signature.", 1, sigList.size()); + PGPSignature sig = sigList.get(0); + sig.init(new BcPGPContentVerifierBuilderProvider(), signingPubKey); + sig.update(Strings.toUTF8ByteArray(msgS)); + boolean v = sig.verify(); + if (!v) + { + // -DM System.out.println + System.out.println(bOut); + } + isTrue("Generated Cleartext Signature MUST verify successfully", v); + } + + /** + * Generate and verify an inline text signature using a v6 RSA key. + */ + private void generateAndVerifyInlineSignatureUsingRSAKey() + throws PGPException, IOException + { + String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + + "Comment: B79E376A49446A250AB1738F657EAA7E8F91796B3CA950263C38FBBBEADC2352\n" + + "\n" + + "xcZaBmbHNIkBAAACBxAAuastS0RHPZwMZ70ii4hbfOxC3+7bwhVjlAvmp7ZYcShe\n" + + "96bfDEv+8ydU2oqKbFtokL5pJ3iZhG8h74iYE2E74BQjgEqpFTzc26MjpbbRnldK\n" + + "BiDpXEiBrDke49ycVkgXFXIUyMLSNNZ2FJTgJenFtjfevFAZTSDMjhr3MebD3TPL\n" + + "dipor45D4W7GmEqOBpMju3XX31HFq1ON/KPHYCJuVOoGj9UMgpDg1xNhxiq5cqLu\n" + + "OYmp/PU4YaHgvXsA6w2QKjfA9aDaDmidWtuzzDYM1KfcC0bht1iQYLlPgG9XOe3F\n" + + "+IHEJ9riviInOqrLeiYKJ2RW9ZT5C6Db2+lV3Fz3bYfNgXjY+BaUG1y3JdwFnvcR\n" + + "qxawqRCHHeHzmhD4+QwKxjkNQG+jl/s8Vtng1E5GopOe7t38KCnm2A6hnLIvUN4z\n" + + "0RjU95vA5o+e+x7I4RuCCi2iOqZoLIhQ4JstR+c2Nz8AQ/mXCAzw1EfrndtENyur\n" + + "FK2/ocBz59UVYHucPvgnSa4gKKVgB1DIBsDAA9Y7/HnMYdJlN6LJoFj6En/4CPlo\n" + + "WOqytXdDdFwtE5p9yZFJxXCpcwkOaupTTVBepXgzb6MMq4b8YU1pGCaK7EHC4P47\n" + + "OEZB8/WhXmGyEfU0KWDvje+UG3A/BvqRmWERwAEb1+VcXpRo6b01FWLK6stjlI8A\n" + + "EQEAAQAP/RDguCnW55j4pgIKJelEOHjXK08a8fwnIJm1KT8GquyCbHubvjvqbp8g\n" + + "7Kw/Gs011AAQZxOw+VeaGJ4jLxvX427/tah0YQFuum722gc24sA/lBmRhVUfvDXx\n" + + "LVcuV0HapMqMx8nmN+CYvDwrumKH6TKiyosYxuwFdsLWPbFaFmT1z+GKgmCvEIme\n" + + "Hcx7PoTnfECOulRxJQRpgIc+RiH9j0UFzxnlFpGJ5P54IxO2D4yVtg0h8ANwMTNi\n" + + "2UCwPUmgvoGv9sj9WcUkimVXgnUmVq1AIxcdVuhpUxqPzePRez7nV+86sJ+k3KbH\n" + + "CQTiwMN2UMb67pK9e5Qsh7/qaqUxCEbTfc8QZb9qygN5t3V0Zb1tYxlk7mqGyFa/\n" + + "g5i4hAfmkwUxgafqr4s8ZuCo5VjbX2KvO1tMDnL/7Ywv2FLx+FZiCdWNIXE7IM1Z\n" + + "9zXFOLvFQ1SL5aHJ+2NoOqyJpmH50DoI3483qMEu4R/GKqhbJOyk8Ta95SV/lAcf\n" + + "lBcIjWOWgd6qXzhi3QCoDGSFH7KYQdJkJ3gKYSer9ETCb4ZHWMBxHeWaSeL8WsWd\n" + + "1feX+Job9CJ/Kd5d9pCDQOeXd3MNFf5TNmEAU3z7+B71eTvlYpNwYvBvH9h4XKbR\n" + + "Z3GJsvt/kPttEx7wAfiNSeXH9pzWqmbqLpRofxiwnF7mIPc9I5vxCADRfxtk8eWZ\n" + + "ilCYBEmnfXiKWcU0/pfD8KEfdWv4Btng0LdZCkSL+i8i8ldUxOsLWM+ge9uy3zHc\n" + + "ms1jIrSZg5FW6XvGG1zcn5PaJqd/nizk7lnqDwHZXRePRtaLF8D0jFXAGAgUr7zI\n" + + "n2LdDGabvxSsoTWIbWT6z+UzRsZlsOwEXeOpIuAG3kjPamPtxpJoPn15AJ/kpnxG\n" + + "XsOdGH1FvyIxOp+31sqO8fbjW5NacuzaOvJAvt2JOV5b8rcbnNyIu5pn5YjZ876T\n" + + "i4K+jrGlByDVUB8IWILe2N0sgVrhTNTO4tqysWHir0SM+s/dSa9OISHpMLChGI08\n" + + "UH/eZAP9msC/CADi4gX8UdH8wEzaceFur03jXDqIhG8jr2jDVmZ4eyj2NDPZuQ45\n" + + "J4LuPgytx+RU8edgoB6POZ8TdLr2llA5XBYOVsqBttE7GadULlIDZYgagzIiWc34\n" + + "VDkxPepWFlwTa5nQ09GeC6H/h594TaaCOHZGJqeD3MJWfrPnj7V+upw+beJeB8Hs\n" + + "PwfgTuTesjWNK1b/g0dLvF3D7+8z4xlj8iMj80B8Kwl4lSC23W2wd79SC0KvKM4D\n" + + "dJoA0A9u1KB/hs/qUMllDsRlS0UyWV/R7slK9OdZh742jhluKJ4a/jQ2EihlXMMW\n" + + "RyLHjRKdT5U7Ou16gXehu7Hrx+EEcKPkt1AxB/0acvo9+ipYTqfV0j8zIH+/m4D0\n" + + "mtFPRiQi/XviyHIHHsyEx7JHkegynqdU1a6NxAi/o4VNXkSVTFcarln6sxrRmDbg\n" + + "Uaxc2pcXMXXzfpbW/jjobOGOBLCRJSzV5NbGknm0VAIaOm/ln4d8PT+FydoNhxEr\n" + + "7fgqtl/hAJ9F1QJeol3cHioJzJ7ye6vMLLIYCdiZAoHMijKOiLAUca3svIqG1Nxw\n" + + "iUuX6F3ZUvpcG1utgVt8psibOtQGHwJmOGTIEscGVynrVrxZiUhcUmXdW3VaAQAb\n" + + "2esz7bth6DWbJaKWWxtBkehliuX6A/h//izVCZAb6c05bn3farOe+MrTH9hlwsGz\n" + + "Bh8BDgAAAEIioQa3njdqSURqJQqxc49lfqp+j5F5azypUCY8OPu76twjUgWCZsc0\n" + + "iQMLCQcFFQoOCAwCFgACmw8CHgkFJwkCBwIAAAAABo0g9kgtw8wX6XUKcHhtGlLb\n" + + "fnXOPPHli+iBxjB3y6txtdoQALSr99MU7kF/WbzQNvpdkejLOr6tTxrNHHE5Iw1+\n" + + "12t1KprbJV/ViDmJ2GGwSiK5bzhA6jtrfFoSQBLKkJ2IoACPSbA80tazUf4E/P2/\n" + + "+157aU3FQfkT8HS6Zcr604xmw1IemkqMxoN/ukyihz+6MJpltb5kgpE2UNgz07jd\n" + + "cpXXe4ATKRWIx4I4pVIcXomH9rHDgSLn+bxaCsbfgijnQjJvTJof15rFYGVKtAzx\n" + + "DYGE2Y7NlCtbveoLj0+e8t2vDJSISBur+9oPgMHR0DbGT7wAr32kWXDFxVl1pU8o\n" + + "KzQ3QaKNddvMnZ9SyP8OUOc0DlevT0Ib+t2mFvU2omcerI9uUAOut4HrJX3bsAFq\n" + + "/vC8/pzYLN52sqC6sLrgws28DmMVvN/slK73y5EM+7bkztdJeuHMlED4IRXNQ/tZ\n" + + "Erm2KYsjzFVLcgk6M9lDLGwi6NKEBfBxwn01r3AhmeGB9n0whSZE4WtEmB/GgT9d\n" + + "9bC6pOYQeVE+5GPhWbrDCtRBxwXxskXwRrC+/HCM4AwecNfDF5cRJfEAAnxY5G7o\n" + + "hgHqwbkfY8vm9ePYDJv5+SplEbAQyHaKdKxzeOM6mrpxkkn4tN23ToU14rl17+3d\n" + + "eGk3VrSlmawnZyRSDguwZst2mcy/MYL+YLYvYTUalXZegP9uRm0YF4RGvnk9PLlg\n" + + "4M2U\n" + + "-----END PGP PRIVATE KEY BLOCK-----\n"; + String MSG = "Hello, World!\n"; + + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ArmoredOutputStream aOut = ArmoredOutputStream.builder() + .clearHeaders() + .enableCRC(false) + .build(bOut); + BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT); + PGPSignatureGenerator sigGen = new PGPSignatureGenerator( + new BcPGPContentSignerBuilder( + secretKeys.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA3_512), + secretKeys.getPublicKey()); + sigGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, secretKeys.getSecretKey().extractPrivateKey(null)); + PGPOnePassSignature ops = sigGen.generateOnePassVersion(false); + ops.encode(pOut); + + PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); + OutputStream litOut = litGen.open(pOut, PGPLiteralDataGenerator.UTF8, "", + PGPLiteralDataGenerator.NOW, new byte[512]); + byte[] plaintext = Strings.toUTF8ByteArray(MSG); + litOut.write(plaintext); + litOut.close(); + sigGen.update(plaintext); + PGPSignature sig = sigGen.generate(); + sig.encode(pOut); + pOut.close(); + aOut.close(); + + bIn = new ByteArrayInputStream(bOut.toByteArray()); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + + PGPOnePassSignatureList opsList = (PGPOnePassSignatureList) objFac.nextObject(); + ops = opsList.get(0); + ops.init(new BcPGPContentVerifierBuilderProvider(), secretKeys.getPublicKey()); + PGPLiteralData lit = (PGPLiteralData) objFac.nextObject(); + InputStream litIn = lit.getDataStream(); + plaintext = Streams.readAll(litIn); + ops.update(plaintext); + PGPSignatureList sigList = (PGPSignatureList) objFac.nextObject(); + sig = sigList.get(0); + isTrue("V6 inline sig made using RSA key MUST verify", ops.verify(sig)); + } + + /** + * A version 4 signature generated using the v6 key. + * This test verifies that the signature is properly rejected. + */ + private void testVerificationOfV4SigWithV6KeyFails() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(ARMORED_KEY)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + PGPObjectFactory objFac = new BcPGPObjectFactory(pIn); + final PGPSecretKeyRing secretKeys = (PGPSecretKeyRing) objFac.nextObject(); + + // v4 timestamp signature containing an IssuerKeyId subpacket + String V4_SIG = "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wloEQBsKABAJEMsYbE8GCaaXBQJmzHd2AAA5wlKWl7C0Dp6dVGDrCFCiISbyL4UE\n" + + "eYFLRZRnfn25OQmobhAHm2WgY/YOH5bTRLLBSIJiJlstQXMwGQvNNtheQAA=\n" + + "-----END PGP SIGNATURE-----"; + + bIn = new ByteArrayInputStream(Strings.toUTF8ByteArray(V4_SIG)); + aIn = new ArmoredInputStream(bIn); + pIn = new BCPGInputStream(aIn); + objFac = new BcPGPObjectFactory(pIn); + PGPSignatureList sigs = (PGPSignatureList) objFac.nextObject(); + final PGPSignature sig = sigs.get(0); + + isNotNull(testException("MUST NOT verify v4 signature with non-v4 key.", "PGPException", + new TestExceptionOperation() { + public void operation() throws Exception { + sig.init(new BcPGPContentVerifierBuilderProvider(), secretKeys.getPublicKey()); + sig.verify(); + } + })); + } + + public static void main(String[] args) + { + runTest(new PGPv6SignatureTest()); + } +} \ No newline at end of file diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/RegressionTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/RegressionTest.java index 2cf6ad463c..0856437688 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/RegressionTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/RegressionTest.java @@ -2,6 +2,7 @@ import java.security.Security; +import org.bouncycastle.bcpg.test.SignatureSubpacketsTest; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.Test; @@ -62,7 +63,30 @@ public class RegressionTest new BcImplProviderTest(), new OperatorJcajceTest(), new OpenPGPTest(), - new OperatorBcTest() + new OperatorBcTest(), + new SignatureSubpacketsTest(), + + new DedicatedEd25519KeyPairTest(), + new DedicatedEd448KeyPairTest(), + new DedicatedX25519KeyPairTest(), + new DedicatedX448KeyPairTest(), + + new LegacyEd25519KeyPairTest(), + new LegacyEd448KeyPairTest(), + new LegacyX25519KeyPairTest(), + new LegacyX448KeyPairTest(), + + new PGPv6MessageDecryptionTest(), + new Curve25519PrivateKeyEncodingTest(), + new EdDSAKeyConversionWithLeadingZeroTest(), + new ECDSAKeyPairTest(), + new UnknownBCPGKeyPairTest(), + + new PGPv5KeyTest(), + new PGPv5MessageDecryptionTest(), + new PGPv6SignatureTest(), + new PGPKeyPairGeneratorTest(), + new PGPKeyRingGeneratorTest(), }; public static void main(String[] args) diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java index 03862f62c7..9c03877938 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java @@ -1,15 +1,18 @@ package org.bouncycastle.openpgp.test; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.security.Security; import org.bouncycastle.gpg.SExprParser; +import org.bouncycastle.gpg.SExpression; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePBEProtectionRemoverFactory; +import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.test.SimpleTest; @@ -139,9 +142,54 @@ public String getName() return "SExprTest"; } + private void corruptStreamTest() + { + try + { + SExpression.parse(new ByteArrayInputStream(Strings.toByteArray("12")), 2); + fail("no exception"); + } + catch (IOException e) + { + isEquals("invalid input stream", e.getMessage()); + } + + try + { + SExpression.parse(new ByteArrayInputStream(Strings.toByteArray("2:3abc")), 2); + fail("no exception"); + } + catch (IOException e) + { + isEquals("invalid input stream at ':'", e.getMessage()); + } + + try + { + SExpression.parse(new ByteArrayInputStream(Strings.toByteArray("#3abc")), 2); + fail("no exception"); + } + catch (IOException e) + { + isEquals(e.getMessage(), "invalid input stream at '#'", e.getMessage()); + } + + try + { + SExpression.parse(new ByteArrayInputStream(Strings.toByteArray("\"3abc")), 2); + fail("no exception"); + } + catch (IOException e) + { + isEquals(e.getMessage(), "invalid input stream at '\"'", e.getMessage()); + } + } + public void performTest() throws Exception { + corruptStreamTest(); + SExprParser parser = new SExprParser(new JcaPGPDigestCalculatorProviderBuilder().build()); PGPSecretKey k1 = parser.parseSecretKey(new ByteArrayInputStream(key1), new JcePBEProtectionRemoverFactory("fred".toCharArray()), new JcaKeyFingerprintCalculator()); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/SHA1.java b/pg/src/test/java/org/bouncycastle/openpgp/test/SHA1.java new file mode 100644 index 0000000000..0dea62037f --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/SHA1.java @@ -0,0 +1,23 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.crypto.digests.SHA1Digest; +import org.bouncycastle.jcajce.provider.digest.BCMessageDigest; + +public class SHA1 + extends BCMessageDigest + implements Cloneable +{ + public SHA1() + { + super(new SHA1Digest()); + } + + public Object clone() + throws CloneNotSupportedException + { + SHA1 d = (SHA1)super.clone(); + d.digest = new SHA1Digest((SHA1Digest)digest); + + return d; + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/SHA256.java b/pg/src/test/java/org/bouncycastle/openpgp/test/SHA256.java new file mode 100644 index 0000000000..48fa9d8ad4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/SHA256.java @@ -0,0 +1,23 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.jcajce.provider.digest.BCMessageDigest; + +public class SHA256 + extends BCMessageDigest + implements Cloneable +{ + public SHA256() + { + super(SHA256Digest.newInstance()); + } + + public Object clone() + throws CloneNotSupportedException + { + SHA256 d = (SHA256)super.clone(); + d.digest = SHA256Digest.newInstance(digest); + + return d; + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/UnknownBCPGKeyPairTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/UnknownBCPGKeyPairTest.java new file mode 100644 index 0000000000..f347b1dbea --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/UnknownBCPGKeyPairTest.java @@ -0,0 +1,45 @@ +package org.bouncycastle.openpgp.test; + +import org.bouncycastle.bcpg.PublicKeyPacket; +import org.bouncycastle.bcpg.PublicSubkeyPacket; +import org.bouncycastle.bcpg.UnknownBCPGKey; +import org.bouncycastle.openpgp.PGPException; +import org.bouncycastle.openpgp.PGPPublicKey; +import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; +import org.bouncycastle.util.encoders.Hex; + +public class UnknownBCPGKeyPairTest + extends AbstractPgpKeyPairTest +{ + @Override + public String getName() + { + return "UnknownBCPGKeyPairTest"; + } + + @Override + public void performTest() + throws Exception + { + testGetBitStrength(); + } + + private void testGetBitStrength() + throws PGPException + { + byte[] raw = Hex.decode("decaffc0ffeebabe"); // 8 octets = 64-bit key size + UnknownBCPGKey key = new UnknownBCPGKey(raw.length, raw); + PublicKeyPacket packet = new PublicSubkeyPacket( + PublicKeyPacket.VERSION_6, + 99, // unknown algorithm ID + currentTimeRounded(), + key); + PGPPublicKey pgpKey = new PGPPublicKey(packet, new BcKeyFingerprintCalculator()); + isEquals("Unknown key getBitStrength() mismatch", 64, pgpKey.getBitStrength()); + } + + public static void main(String[] args) + { + runTest(new UnknownBCPGKeyPairTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/WildcardKeyIDTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/WildcardKeyIDTest.java index 43a4a6de51..ac75e0d795 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/WildcardKeyIDTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/WildcardKeyIDTest.java @@ -112,7 +112,7 @@ public void performTest() PGPEncryptedDataList encDataList = (PGPEncryptedDataList) objectFactory.nextObject(); PGPPublicKeyEncryptedData pkeData = (PGPPublicKeyEncryptedData) encDataList.get(0); - isEquals(PublicKeyKeyEncryptionMethodGenerator.WILDCARD, pkeData.getKeyID()); + isEquals(PublicKeyKeyEncryptionMethodGenerator.WILDCARD_KEYID, pkeData.getKeyID()); InputStream decryptedIn = pkeData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey)); objectFactory = new BcPGPObjectFactory(decryptedIn); diff --git a/pg/src/test/java/org/bouncycastle/test/DumpUtil.java b/pg/src/test/java/org/bouncycastle/test/DumpUtil.java new file mode 100644 index 0000000000..8031314fac --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/test/DumpUtil.java @@ -0,0 +1,71 @@ +package org.bouncycastle.test; + +import org.bouncycastle.util.Pack; +import org.bouncycastle.util.encoders.Hex; + +public class DumpUtil +{ + /** + * Return a formatted hex dump of the given byte array. + * @param array byte array + */ + public static String hexdump(byte[] array) + { + return hexdump(0, array); + } + + /** + * Return a formatted hex dump of the given byte array. + * If startIndent is non-zero, the dump is shifted right by startIndent octets. + * @param startIndent shift the octet stream between by a number of bytes + * @param array byte array + */ + public static String hexdump(int startIndent, byte[] array) + { + if (startIndent < 0) + { + throw new IllegalArgumentException("Start-Indent must be a positive number"); + } + if (array == null) + { + return ""; + } + + // -DM Hex.toHexString + String hex = Hex.toHexString(array); + StringBuilder withWhiteSpace = new StringBuilder(); + // shift the dump a number of octets to the right + for (int i = 0; i < startIndent; i++) + { + withWhiteSpace.append(" "); + } + // Split into hex octets (pairs of two chars) + String[] octets = withWhiteSpace.append(hex).toString().split("(?<=\\G.{2})"); + + StringBuilder out = new StringBuilder(); + int l = 0; + byte[] counterLabel = new byte[4]; + + while (l < octets.length) + { + // index row + Pack.intToBigEndian(l, counterLabel, 0); + out.append(Hex.toHexString(counterLabel)).append(" "); + // first 8 octets of a line + for (int i = l ; i < l + 8 && i < octets.length; i++) + { + out.append(octets[i]).append(" "); + } + out.append(" "); + // second 8 octets of a line + for (int i = l+8; i < l + 16 && i < octets.length; i++) + { + out.append(octets[i]).append(" "); + } + out.append("\n"); + + l += 16; + } + return out.toString(); + } +} diff --git a/pg/src/test/java/org/bouncycastle/test/PrintTestResult.java b/pg/src/test/java/org/bouncycastle/test/PrintTestResult.java index 2cca70b227..c14f1bab5d 100644 --- a/pg/src/test/java/org/bouncycastle/test/PrintTestResult.java +++ b/pg/src/test/java/org/bouncycastle/test/PrintTestResult.java @@ -14,6 +14,7 @@ public static void printResult(TestResult result) { while (e.hasMoreElements()) { + // -DM System.out.println System.out.println(e.nextElement()); } } @@ -23,12 +24,14 @@ public static void printResult(TestResult result) { while (e.hasMoreElements()) { + // -DM System.out.println System.out.println(e.nextElement()); } } if (!result.wasSuccessful()) { + // -DM System.exit System.exit(1); } } diff --git a/pg/src/test/jdk1.1/org/bouncycastle/openpgp/test/PGPEdDSATest.java b/pg/src/test/jdk1.1/org/bouncycastle/openpgp/test/PGPEdDSATest.java index 1eac1d993f..0cd9545196 100644 --- a/pg/src/test/jdk1.1/org/bouncycastle/openpgp/test/PGPEdDSATest.java +++ b/pg/src/test/jdk1.1/org/bouncycastle/openpgp/test/PGPEdDSATest.java @@ -414,7 +414,8 @@ public void performTest() PGPPublicKeyRing pubKeyRing = new PGPPublicKeyRing(aIn, new JcaKeyFingerprintCalculator()); - isTrue(areEqual(Hex.decode("EB85 BB5F A33A 75E1 5E94 4E63 F231 550C 4F47 E38E"), pubKeyRing.getPublicKey().getFingerprint())); + isTrue(areEqual(pubKeyRing.getPublicKey().getFingerprint(), Hex.decode("EB85 BB5F A33A 75E1 5E94 4E63 F231 550C 4F47 E38E"))); + isTrue(pubKeyRing.getPublicKey().hasFingerprint(Hex.decode("EB85 BB5F A33A 75E1 5E94 4E63 F231 550C 4F47 E38E"))); aIn = new ArmoredInputStream(new ByteArrayInputStream(Strings.toByteArray(edDSASecretKey))); diff --git a/pg/src/test/jdk1.2/org/bouncycastle/test/DumpUtil.java b/pg/src/test/jdk1.2/org/bouncycastle/test/DumpUtil.java new file mode 100644 index 0000000000..fc273d9204 --- /dev/null +++ b/pg/src/test/jdk1.2/org/bouncycastle/test/DumpUtil.java @@ -0,0 +1,80 @@ +package org.bouncycastle.test; + +import org.bouncycastle.util.Pack; +import org.bouncycastle.util.encoders.Hex; + +public class DumpUtil +{ + /** + * Return a formatted hex dump of the given byte array. + * @param array byte array + */ + public static String hexdump(byte[] array) + { + return hexdump(0, array); + } + + /** + * Return a formatted hex dump of the given byte array. + * If startIndent is non-zero, the dump is shifted right by startIndent octets. + * @param startIndent shift the octet stream between by a number of bytes + * @param array byte array + */ + public static String hexdump(int startIndent, byte[] array) + { + if (startIndent < 0) + { + throw new IllegalArgumentException("Start-Indent must be a positive number"); + } + if (array == null) + { + return ""; + } + + // -DM Hex.toHexString + String hex = Hex.toHexString(array); + StringBuffer withWhiteSpace = new StringBuffer(); + // shift the dump a number of octets to the right + for (int i = 0; i < startIndent; i++) + { + withWhiteSpace.append(" "); + } + // Split into hex octets (pairs of two chars) + + String base = withWhiteSpace.append(hex).toString(); + String[] octets = new String[hex.length() / 2]; + int start = startIndent + 2; + octets[0] = base.substring(0, start); + for (int i = 1; i != octets.length; i++) + { + octets[i] = base.substring(start, start + 2); + start += 2; + } + + StringBuffer out = new StringBuffer(); + int l = 0; + byte[] counterLabel = new byte[4]; + + while (l < octets.length) + { + // index row + Pack.intToBigEndian(l, counterLabel, 0); + out.append(Hex.toHexString(counterLabel)).append(" "); + // first 8 octets of a line + for (int i = l ; i < l + 8 && i < octets.length; i++) + { + out.append(octets[i]).append(" "); + } + out.append(" "); + // second 8 octets of a line + for (int i = l+8; i < l + 16 && i < octets.length; i++) + { + out.append(octets[i]).append(" "); + } + out.append("\n"); + + l += 16; + } + return out.toString(); + } +} diff --git a/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/AllTests.java b/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/AllTests.java new file mode 100644 index 0000000000..cff68dd70f --- /dev/null +++ b/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/AllTests.java @@ -0,0 +1,67 @@ +package org.bouncycastle.openpgp.test; + +import java.security.Security; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.PrintTestResult; +import org.bouncycastle.util.test.SimpleTestResult; + +public class AllTests + extends TestCase +{ + public void testPGP() + { + Security.addProvider(new BouncyCastleProvider()); + + org.bouncycastle.util.test.Test[] tests = RegressionTest.tests; + + for (int i = 0; i != tests.length; i++) + { + SimpleTestResult result = (SimpleTestResult)tests[i].perform(); + + if (!result.isSuccessful()) + { + fail(tests[i].getClass().getName() + " " + result.toString()); + } + } + } + + public static void main(String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("OpenPGP Tests"); + + suite.addTestSuite(AllTests.class); + suite.addTestSuite(DSA2Test.class); + suite.addTestSuite(PGPUnicodeTest.class); + + return new BCTestSetup(suite); + } + + static class BCTestSetup + extends TestSetup + { + public BCTestSetup(Test test) + { + super(test); + } + + protected void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + protected void tearDown() + { + Security.removeProvider("BC"); + } + } +} diff --git a/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/RegressionTest.java b/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/RegressionTest.java index 4a7754b3c7..acc8002d2c 100644 --- a/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/RegressionTest.java +++ b/pg/src/test/jdk1.4/org/bouncycastle/openpgp/test/RegressionTest.java @@ -60,7 +60,7 @@ public class RegressionTest new PGPGeneralTest(), new BcpgGeneralTest(), //new BcImplProviderTest(), - new OperatorJcajceTest(), + //new OperatorJcajceTest(), new OpenPGPTest(), new OperatorBcTest() }; diff --git a/pg/src/test/jdk1.5/org/bouncycastle/openpgp/test/AllTests.java b/pg/src/test/jdk1.5/org/bouncycastle/openpgp/test/AllTests.java new file mode 100644 index 0000000000..cff68dd70f --- /dev/null +++ b/pg/src/test/jdk1.5/org/bouncycastle/openpgp/test/AllTests.java @@ -0,0 +1,67 @@ +package org.bouncycastle.openpgp.test; + +import java.security.Security; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.PrintTestResult; +import org.bouncycastle.util.test.SimpleTestResult; + +public class AllTests + extends TestCase +{ + public void testPGP() + { + Security.addProvider(new BouncyCastleProvider()); + + org.bouncycastle.util.test.Test[] tests = RegressionTest.tests; + + for (int i = 0; i != tests.length; i++) + { + SimpleTestResult result = (SimpleTestResult)tests[i].perform(); + + if (!result.isSuccessful()) + { + fail(tests[i].getClass().getName() + " " + result.toString()); + } + } + } + + public static void main(String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("OpenPGP Tests"); + + suite.addTestSuite(AllTests.class); + suite.addTestSuite(DSA2Test.class); + suite.addTestSuite(PGPUnicodeTest.class); + + return new BCTestSetup(suite); + } + + static class BCTestSetup + extends TestSetup + { + public BCTestSetup(Test test) + { + super(test); + } + + protected void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + protected void tearDown() + { + Security.removeProvider("BC"); + } + } +} diff --git a/pkix/build.gradle b/pkix/build.gradle index abad0611b4..013eeb31c3 100644 --- a/pkix/build.gradle +++ b/pkix/build.gradle @@ -11,8 +11,11 @@ sourceSets { } } +evaluationDependsOn(":prov") +evaluationDependsOn(":util") + dependencies { - implementation project(':core') + implementation project(':prov') implementation project(':util') @@ -26,28 +29,26 @@ dependencies { } compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + options.release = 8 } + compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + options.release = 9 + + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" + def util_jar="${project(":util").jar.outputs.files.getFiles().getAt(0)}" + options.compilerArgs += [ - '--module-path', "${bc_prov}${File.pathSeparator}${bc_util}" + '--module-path', "${prov_jar}${File.pathSeparator}${util_jar}" ] options.sourcepath = files(['src/main/java', 'src/main/jdk1.9']) } + jar.archiveBaseName = "bcpkix-$vmrange" @@ -69,12 +70,15 @@ jar { String packages = 'org.bouncycastle.{cert|cmc|cms|dvcs|eac|est|its|mime|mozilla|voms|operator|pkix|openssl|pkcs|tsp}.*' + String v = "${rootProject.extensions.ext.bundle_version}" + manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bcpkix') manifest.attributes('Bundle-SymbolicName': 'bcpkix') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': "${packages}") - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!${packages},org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "${packages};version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!${packages},org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") } @@ -93,4 +97,21 @@ artifacts { test { forkEvery = 1; maxParallelForks = 8; + jvmArgs = ['-Dtest.java.version.prefix=any'] } + +compileJava9Java.dependsOn([":prov:jar", ":util:jar"]) + +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcpkix-$vmrange" + from components.java + + artifact(javadocJar) + artifact(sourcesJar) + } + + } +} \ No newline at end of file diff --git a/pkix/src/main/java/org/bouncycastle/cert/DeltaCertificateTool.java b/pkix/src/main/java/org/bouncycastle/cert/DeltaCertificateTool.java index f599a525f4..fdfcfead57 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/DeltaCertificateTool.java +++ b/pkix/src/main/java/org/bouncycastle/cert/DeltaCertificateTool.java @@ -1,185 +1,138 @@ package org.bouncycastle.cert; import java.io.IOException; +import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1BitString; -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.DERTaggedObject; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Certificate; +import org.bouncycastle.asn1.x509.DeltaCertificateDescriptor; import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.ExtensionsGenerator; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.asn1.x509.TBSCertificate; +import org.bouncycastle.asn1.x509.Validity; /** * General tool for handling the extension described in: https://datatracker.ietf.org/doc/draft-bonnell-lamps-chameleon-certs/ */ public class DeltaCertificateTool { - public static Extension makeDeltaCertificateExtension(boolean isCritical, X509CertificateHolder deltaCert) + public static Extension makeDeltaCertificateExtension(boolean isCritical, Certificate deltaCert) throws IOException { - ASN1EncodableVector deltaV = new ASN1EncodableVector(); - - deltaV.add(new ASN1Integer(deltaCert.getSerialNumber())); - deltaV.add(new DERTaggedObject(false, 0, deltaCert.getSignatureAlgorithm())); - deltaV.add(new DERTaggedObject(false, 1, deltaCert.getIssuer())); - - ASN1EncodableVector validity = new ASN1EncodableVector(2); - validity.add(deltaCert.toASN1Structure().getStartDate()); - validity.add(deltaCert.toASN1Structure().getEndDate()); - - deltaV.add(new DERTaggedObject(false, 2, new DERSequence(validity))); - deltaV.add(new DERTaggedObject(false, 3, deltaCert.getSubject())); - deltaV.add(deltaCert.getSubjectPublicKeyInfo()); - if (deltaCert.getExtensions() != null) - { - deltaV.add(new DERTaggedObject(false, 4, deltaCert.getExtensions())); - } - deltaV.add(new DERBitString(deltaCert.getSignature())); + DeltaCertificateDescriptor descriptor = new DeltaCertificateDescriptor( + deltaCert.getSerialNumber(), + deltaCert.getSignatureAlgorithm(), + deltaCert.getIssuer(), + deltaCert.getValidity(), + deltaCert.getSubject(), + deltaCert.getSubjectPublicKeyInfo(), + deltaCert.getExtensions(), + deltaCert.getSignature()); + + ASN1OctetString extnValue = new DEROctetString(descriptor.getEncoded(ASN1Encoding.DER)); + + return new Extension(Extension.deltaCertificateDescriptor, isCritical, extnValue); + } - return new Extension(Extension.deltaCertificateDescriptor, isCritical, new DERSequence(deltaV).getEncoded(ASN1Encoding.DER)); + public static Extension makeDeltaCertificateExtension(boolean isCritical, X509CertificateHolder deltaCert) + throws IOException + { + return makeDeltaCertificateExtension(isCritical, deltaCert.toASN1Structure()); } - public static X509CertificateHolder extractDeltaCertificate(X509CertificateHolder originCert) + public static Certificate extractDeltaCertificate(TBSCertificate baseTBSCert) { - ASN1ObjectIdentifier deltaExtOid = Extension.deltaCertificateDescriptor; - Extension deltaExt = originCert.getExtension(deltaExtOid); - - ASN1Sequence seq = ASN1Sequence.getInstance(deltaExt.getParsedValue()); -// * version [ 0 ] Version DEFAULT v1(0), -// * serialNumber CertificateSerialNumber, -// * signature AlgorithmIdentifier, -// * issuer Name, -// * validity Validity, -// * subject Name, -// * subjectPublicKeyInfo SubjectPublicKeyInfo, -// * issuerUniqueID [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL, -// * subjectUniqueID [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL, -// * extensions [ 3 ] Extensions OPTIONAL - ASN1Sequence originTbs = ASN1Sequence.getInstance(originCert.toASN1Structure().getTBSCertificate().toASN1Primitive()); - int idx = 0; - ASN1Encodable[] extracted = originTbs.toArray(); - - extracted[0] = originTbs.getObjectAt(0); - extracted[1] = ASN1Integer.getInstance(seq.getObjectAt(idx++)); - - ASN1Encodable next = seq.getObjectAt(idx++); - while (next instanceof ASN1TaggedObject) + Extensions baseExtensions = baseTBSCert.getExtensions(); + + Extension dcdExtension = baseExtensions.getExtension(Extension.deltaCertificateDescriptor); + if (dcdExtension == null) { - ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(next); - switch (tagged.getTagNo()) - { - case 0: - extracted[2] = ASN1Sequence.getInstance(tagged, false); - break; - case 1: - extracted[3] = ASN1Sequence.getInstance(tagged, true); // issuer - break; - case 2: - extracted[4] = ASN1Sequence.getInstance(tagged, false); - break; - case 3: - extracted[5] = ASN1Sequence.getInstance((ASN1TaggedObject)next, true); // subject - break; - } - next = seq.getObjectAt(idx++); + throw new IllegalStateException("no deltaCertificateDescriptor present"); } - extracted[6] = next; // subjectPublicKey + DeltaCertificateDescriptor descriptor = DeltaCertificateDescriptor.getInstance(dcdExtension.getParsedValue()); - if (extracted[2] == null) + ASN1Integer version = baseTBSCert.getVersion(); + ASN1Integer serialNumber = descriptor.getSerialNumber(); + + AlgorithmIdentifier signature = descriptor.getSignature(); + if (signature == null) { - extracted[2] = originTbs.getObjectAt(2); + signature = baseTBSCert.getSignature(); } - if (extracted[3] == null) + X500Name issuer = descriptor.getIssuer(); + if (issuer == null) { - extracted[3] = originTbs.getObjectAt(3); + issuer = baseTBSCert.getIssuer(); } - if (extracted[4] == null) + Validity validity = descriptor.getValidityObject(); + if (validity == null) { - extracted[4] = originTbs.getObjectAt(4); + validity = baseTBSCert.getValidity(); } - if (extracted[5] == null) + X500Name subject = descriptor.getSubject(); + if (subject == null) { - extracted[5] = originTbs.getObjectAt(5); + subject = baseTBSCert.getSubject(); } - ExtensionsGenerator extGen = extractExtensions(originTbs); + SubjectPublicKeyInfo subjectPublicKeyInfo = descriptor.getSubjectPublicKeyInfo(); - if (idx < (seq.size() - 1)) // last element is the signature - { - next = seq.getObjectAt(idx++); - ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(next); - if (tagged.getTagNo() != 4) - { - throw new IllegalArgumentException("malformed delta extension"); - } + Extensions extensions = extractDeltaExtensions(descriptor.getExtensions(), baseExtensions); - ASN1Sequence deltaExts = ASN1Sequence.getInstance(tagged, false); + // TODO Copy over the issuerUniqueID and/or subjectUniqueID (if the issuer/subject resp. are unmodified)? + TBSCertificate tbsCertificate = new TBSCertificate(version, serialNumber, signature, issuer, validity, subject, + subjectPublicKeyInfo, null, null, extensions); - for (int i = 0; i != deltaExts.size(); i++) - { - Extension ext = Extension.getInstance(deltaExts.getObjectAt(i)); + return new Certificate(tbsCertificate, signature, descriptor.getSignatureValue()); + } - extGen.replaceExtension(ext); - } + public static X509CertificateHolder extractDeltaCertificate(X509CertificateHolder baseCert) + { + return new X509CertificateHolder(extractDeltaCertificate(baseCert.getTBSCertificate())); + } - extracted[7] = new DERTaggedObject(3, extGen.generate()); - } - else - { - if (!extGen.isEmpty()) - { - extracted[7] = new DERTaggedObject(3, extGen.generate()); - } - else - { - extracted[7] = null; - } - } + public static DeltaCertificateDescriptor trimDeltaCertificateDescriptor(DeltaCertificateDescriptor descriptor, + TBSCertificate tbsCertificate, Extensions tbsExtensions) + { + return descriptor.trimTo(tbsCertificate, tbsExtensions); + } - ASN1EncodableVector tbsDeltaCertV = new ASN1EncodableVector(7); - for (int i = 0; i != extracted.length; i++) + private static Extensions extractDeltaExtensions(Extensions descriptorExtensions, Extensions baseExtensions) + { + ExtensionsGenerator extGen = new ExtensionsGenerator(); + + Enumeration baseEnum = baseExtensions.oids(); + while (baseEnum.hasMoreElements()) { - if (extracted[i] != null) + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)baseEnum.nextElement(); + if (!Extension.deltaCertificateDescriptor.equals(oid)) { - tbsDeltaCertV.add(extracted[i]); + extGen.addExtension(baseExtensions.getExtension(oid)); } } - ASN1EncodableVector certV = new ASN1EncodableVector(); - certV.add(new DERSequence(tbsDeltaCertV)); - certV.add(ASN1Sequence.getInstance(extracted[2])); - certV.add(ASN1BitString.getInstance(seq.getObjectAt(seq.size() - 1))); - - return new X509CertificateHolder(Certificate.getInstance(new DERSequence(certV))); - } - - private static ExtensionsGenerator extractExtensions(ASN1Sequence originTbs) - { - ASN1ObjectIdentifier deltaExtOid = Extension.deltaCertificateDescriptor; - ASN1Sequence originExt = ASN1Sequence.getInstance(ASN1TaggedObject.getInstance(originTbs.getObjectAt(originTbs.size() - 1)), true); - ExtensionsGenerator extGen = new ExtensionsGenerator(); - - for (int i = 0; i != originExt.size(); i++) + if (descriptorExtensions != null) { - Extension ext = Extension.getInstance(originExt.getObjectAt(i)); - if (!deltaExtOid.equals(ext.getExtnId())) + Enumeration descriptorEnum = descriptorExtensions.oids(); + while (descriptorEnum.hasMoreElements()) { - extGen.addExtension(ext); + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)descriptorEnum.nextElement(); + extGen.replaceExtension(descriptorExtensions.getExtension(oid)); } } - return extGen; + return extGen.isEmpty() ? null : extGen.generate(); } } diff --git a/pkix/src/main/java/org/bouncycastle/cert/X509CertificateHolder.java b/pkix/src/main/java/org/bouncycastle/cert/X509CertificateHolder.java index bc328fd6b9..ef6cbf24ef 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/X509CertificateHolder.java +++ b/pkix/src/main/java/org/bouncycastle/cert/X509CertificateHolder.java @@ -227,6 +227,11 @@ public SubjectPublicKeyInfo getSubjectPublicKeyInfo() return x509Certificate.getSubjectPublicKeyInfo(); } + public TBSCertificate getTBSCertificate() + { + return x509Certificate.getTBSCertificate(); + } + /** * Return the underlying ASN.1 structure for the certificate in this holder. * diff --git a/pkix/src/main/java/org/bouncycastle/cert/X509ExtensionUtils.java b/pkix/src/main/java/org/bouncycastle/cert/X509ExtensionUtils.java index fa8cb1edb9..f67498104c 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/X509ExtensionUtils.java +++ b/pkix/src/main/java/org/bouncycastle/cert/X509ExtensionUtils.java @@ -113,23 +113,16 @@ public SubjectKeyIdentifier createTruncatedSubjectKeyIdentifier(SubjectPublicKey private byte[] getSubjectKeyIdentifier(X509CertificateHolder certHolder) { - if (certHolder.getVersionNumber() != 3) - { - return calculateIdentifier(certHolder.getSubjectPublicKeyInfo()); - } - else + if (certHolder.getVersionNumber() == 3) { Extension ext = certHolder.getExtension(Extension.subjectKeyIdentifier); - if (ext != null) { return ASN1OctetString.getInstance(ext.getParsedValue()).getOctets(); } - else - { - return calculateIdentifier(certHolder.getSubjectPublicKeyInfo()); - } } + + return calculateIdentifier(certHolder.getSubjectPublicKeyInfo()); } private byte[] calculateIdentifier(SubjectPublicKeyInfo publicKeyInfo) diff --git a/pkix/src/main/java/org/bouncycastle/cert/X509v2AttributeCertificateBuilder.java b/pkix/src/main/java/org/bouncycastle/cert/X509v2AttributeCertificateBuilder.java index 6753d049e7..669d7d99f8 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/X509v2AttributeCertificateBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/cert/X509v2AttributeCertificateBuilder.java @@ -7,10 +7,10 @@ import java.util.Locale; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.x509.AttCertIssuer; import org.bouncycastle.asn1.x509.Attribute; @@ -249,7 +249,8 @@ public X509v2AttributeCertificateBuilder replaceExtension( { try { - extGenerator = CertUtils.doReplaceExtension(extGenerator, new Extension(oid, isCritical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER))); + extGenerator = CertUtils.doReplaceExtension(extGenerator, + new Extension(oid, isCritical, new DEROctetString(value))); } catch (IOException e) { diff --git a/pkix/src/main/java/org/bouncycastle/cert/X509v2CRLBuilder.java b/pkix/src/main/java/org/bouncycastle/cert/X509v2CRLBuilder.java index f9b5d72f3c..1699d93218 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/X509v2CRLBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/cert/X509v2CRLBuilder.java @@ -16,6 +16,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -384,7 +385,8 @@ public X509v2CRLBuilder replaceExtension( { try { - extGenerator = CertUtils.doReplaceExtension(extGenerator, new Extension(oid, isCritical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER))); + extGenerator = CertUtils.doReplaceExtension(extGenerator, + new Extension(oid, isCritical, new DEROctetString(value))); } catch (IOException e) { diff --git a/pkix/src/main/java/org/bouncycastle/cert/X509v3CertificateBuilder.java b/pkix/src/main/java/org/bouncycastle/cert/X509v3CertificateBuilder.java index 403f56105d..a26f00e55e 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/X509v3CertificateBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/cert/X509v3CertificateBuilder.java @@ -15,6 +15,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERNull; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -274,7 +275,8 @@ public X509v3CertificateBuilder replaceExtension( { try { - extGenerator = CertUtils.doReplaceExtension(extGenerator, new Extension(oid, isCritical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER))); + extGenerator = CertUtils.doReplaceExtension(extGenerator, + new Extension(oid, isCritical, new DEROctetString(value))); } catch (IOException e) { @@ -376,32 +378,39 @@ public X509v3CertificateBuilder copyAndAddExtension( public X509CertificateHolder build( ContentSigner signer) { - tbsGen.setSignature(signer.getAlgorithmIdentifier()); + AlgorithmIdentifier sigAlgID = signer.getAlgorithmIdentifier(); + + tbsGen.setSignature(sigAlgID); if (!extGenerator.isEmpty()) { - if (extGenerator.hasExtension(Extension.deltaCertificateDescriptor)) + Extension deltaExtension = extGenerator.getExtension(Extension.deltaCertificateDescriptor); + if (deltaExtension != null) { - Extension deltaExt = extGenerator.getExtension(Extension.deltaCertificateDescriptor); - DeltaCertificateDescriptor deltaDesc = DeltaCertificateDescriptor.getInstance(deltaExt.getParsedValue()); + DeltaCertificateDescriptor descriptor = DeltaCertificateTool.trimDeltaCertificateDescriptor( + DeltaCertificateDescriptor.getInstance(deltaExtension.getParsedValue()), + tbsGen.generateTBSCertificate(), + extGenerator.generate()); try { - extGenerator.replaceExtension(Extension.deltaCertificateDescriptor, deltaExt.isCritical(), - deltaDesc.trimTo(tbsGen.generateTBSCertificate(), extGenerator.generate())); + extGenerator.replaceExtension(Extension.deltaCertificateDescriptor, deltaExtension.isCritical(), + descriptor); } catch (IOException e) { throw new IllegalStateException("unable to replace deltaCertificateDescriptor: " + e.getMessage()) ; } } + tbsGen.setExtensions(extGenerator.generate()); } try { TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - return new X509CertificateHolder(generateStructure(tbsCert, signer.getAlgorithmIdentifier(), generateSig(signer, tbsCert))); + byte[] signature = generateSig(signer, tbsCert); + return new X509CertificateHolder(generateStructure(tbsCert, sigAlgID, signature)); } catch (IOException e) { @@ -423,32 +432,38 @@ public X509CertificateHolder build( boolean isCritical, ContentSigner altSigner) { + AlgorithmIdentifier sigAlgID = signer.getAlgorithmIdentifier(); + AlgorithmIdentifier altSigAlgID = altSigner.getAlgorithmIdentifier(); + try { - extGenerator.addExtension(Extension.altSignatureAlgorithm, isCritical, altSigner.getAlgorithmIdentifier()); + extGenerator.addExtension(Extension.altSignatureAlgorithm, isCritical, altSigAlgID); } catch (IOException e) { throw Exceptions.illegalStateException("cannot add altSignatureAlgorithm extension", e); } - if (extGenerator.hasExtension(Extension.deltaCertificateDescriptor)) + Extension deltaExtension = extGenerator.getExtension(Extension.deltaCertificateDescriptor); + if (deltaExtension != null) { - tbsGen.setSignature(signer.getAlgorithmIdentifier()); - - Extension deltaExt = extGenerator.getExtension(Extension.deltaCertificateDescriptor); - DeltaCertificateDescriptor deltaDesc = DeltaCertificateDescriptor.getInstance(deltaExt.getParsedValue()); + tbsGen.setSignature(sigAlgID); try { // the altSignatureValue is not present yet, but it must be in the deltaCertificate and // it must be different (by definition!). We add a dummy one to trigger inclusion. ExtensionsGenerator tmpExtGen = new ExtensionsGenerator(); - tmpExtGen.addExtension(extGenerator.generate()); + tmpExtGen.addExtensions(extGenerator.generate()); tmpExtGen.addExtension(Extension.altSignatureValue, false, DERNull.INSTANCE); - extGenerator.replaceExtension(Extension.deltaCertificateDescriptor, deltaExt.isCritical(), - deltaDesc.trimTo(tbsGen.generateTBSCertificate(), tmpExtGen.generate())); + DeltaCertificateDescriptor descriptor = DeltaCertificateTool.trimDeltaCertificateDescriptor( + DeltaCertificateDescriptor.getInstance(deltaExtension.getParsedValue()), + tbsGen.generateTBSCertificate(), + tmpExtGen.generate()); + + extGenerator.replaceExtension(Extension.deltaCertificateDescriptor, deltaExtension.isCritical(), + descriptor); } catch (IOException e) { @@ -457,19 +472,19 @@ public X509CertificateHolder build( } tbsGen.setSignature(null); - tbsGen.setExtensions(extGenerator.generate()); try { - extGenerator.addExtension(Extension.altSignatureValue, isCritical, new DERBitString(generateSig(altSigner, tbsGen.generatePreTBSCertificate()))); - - tbsGen.setSignature(signer.getAlgorithmIdentifier()); + byte[] altSignature = generateSig(altSigner, tbsGen.generatePreTBSCertificate()); + extGenerator.addExtension(Extension.altSignatureValue, isCritical, new DERBitString(altSignature)); + tbsGen.setSignature(sigAlgID); tbsGen.setExtensions(extGenerator.generate()); - + TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - return new X509CertificateHolder(generateStructure(tbsCert, signer.getAlgorithmIdentifier(), generateSig(signer, tbsCert))); + byte[] signature = generateSig(signer, tbsCert); + return new X509CertificateHolder(generateStructure(tbsCert, sigAlgID, signature)); } catch (IOException e) { @@ -489,7 +504,7 @@ private static byte[] generateSig(ContentSigner signer, ASN1Object tbsObj) private static Certificate generateStructure(TBSCertificate tbsCert, AlgorithmIdentifier sigAlgId, byte[] signature) { - ASN1EncodableVector v = new ASN1EncodableVector(); + ASN1EncodableVector v = new ASN1EncodableVector(3); v.add(tbsCert); v.add(sigAlgId); @@ -504,18 +519,9 @@ static DERBitString booleanToBitString(boolean[] id) for (int i = 0; i != id.length; i++) { - bytes[i / 8] |= (id[i]) ? (1 << ((7 - (i % 8)))) : 0; + bytes[i >>> 3] |= id[i] ? (byte)(0x80 >> (i & 7)) : 0; } - int pad = id.length % 8; - - if (pad == 0) - { - return new DERBitString(bytes); - } - else - { - return new DERBitString(bytes, 8 - pad); - } + return new DERBitString(bytes, (8 - id.length) & 7); } } \ No newline at end of file diff --git a/pkix/src/main/java/org/bouncycastle/cert/cmp/ProtectedPKIMessage.java b/pkix/src/main/java/org/bouncycastle/cert/cmp/ProtectedPKIMessage.java index 6f955be379..b31d9a0be5 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/cmp/ProtectedPKIMessage.java +++ b/pkix/src/main/java/org/bouncycastle/cert/cmp/ProtectedPKIMessage.java @@ -1,11 +1,5 @@ package org.bouncycastle.cert.cmp; -import java.io.IOException; -import java.io.OutputStream; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.cmp.CMPCertificate; import org.bouncycastle.asn1.cmp.CMPObjectIdentifiers; @@ -183,9 +177,6 @@ private boolean verifySignature(byte[] signature, ContentVerifier verifier) private DERSequence createProtected() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - v.add(pkiMessage.getHeader()); - v.add(pkiMessage.getBody()); - return new DERSequence(v); + return new DERSequence(pkiMessage.getHeader(), pkiMessage.getBody()); } } diff --git a/pkix/src/main/java/org/bouncycastle/cert/cmp/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/cmp/package-info.java new file mode 100644 index 0000000000..3aedf0316c --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/cmp/package-info.java @@ -0,0 +1,6 @@ +/** + * + * Basic support package for handling and creating CMP (RFC 4210) certificate management messages. + */ +package org.bouncycastle.cert.cmp; diff --git a/pkix/src/main/java/org/bouncycastle/cert/crmf/CertificateRepMessageBuilder.java b/pkix/src/main/java/org/bouncycastle/cert/crmf/CertificateRepMessageBuilder.java index e6eabf140e..0b913218e5 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/crmf/CertificateRepMessageBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/cert/crmf/CertificateRepMessageBuilder.java @@ -30,6 +30,7 @@ public CertificateRepMessageBuilder(X509CertificateHolder... caCerts) this.caCerts[i] = new CMPCertificate(caCerts[i].toASN1Structure()); } } + public CertificateRepMessageBuilder addCertificateResponse(CertificateResponse response) { responses.add(response.toASN1Structure()); diff --git a/pkix/src/main/java/org/bouncycastle/cert/crmf/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/crmf/jcajce/package-info.java new file mode 100644 index 0000000000..a47d73ebd1 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/crmf/jcajce/package-info.java @@ -0,0 +1,6 @@ +/** + * + * JCA extensions to the CRMF online certificate request package. + */ +package org.bouncycastle.cert.crmf.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/cert/crmf/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/crmf/package-info.java new file mode 100644 index 0000000000..5689480f32 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/crmf/package-info.java @@ -0,0 +1,6 @@ +/** + * + * Basic support package for handling and creating CRMF (RFC 4211) certificate request messages. + */ +package org.bouncycastle.cert.crmf; diff --git a/pkix/src/main/java/org/bouncycastle/cert/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/jcajce/package-info.java new file mode 100644 index 0000000000..7c0642ee1b --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/jcajce/package-info.java @@ -0,0 +1,6 @@ +/** + * + * JCA extensions to the certificate building and processing package. + */ +package org.bouncycastle.cert.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/cert/ocsp/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/ocsp/jcajce/package-info.java new file mode 100644 index 0000000000..929b624f64 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/ocsp/jcajce/package-info.java @@ -0,0 +1,6 @@ +/** + * + * JCA extensions to the OCSP online certificate status package. + */ +package org.bouncycastle.cert.ocsp.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/cert/ocsp/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/ocsp/package-info.java new file mode 100644 index 0000000000..e7b9d83d52 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/ocsp/package-info.java @@ -0,0 +1,6 @@ +/** + * + * Basic support package for handling and creating OCSP (RFC 2560) online certificate status requests. + */ +package org.bouncycastle.cert.ocsp; diff --git a/pkix/src/main/java/org/bouncycastle/cert/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/package-info.java new file mode 100644 index 0000000000..9c7a4d94f0 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic support package for handling and creating X.509 certificates, CRLs, and attribute certificates. + */ +package org.bouncycastle.cert; diff --git a/pkix/src/main/java/org/bouncycastle/cert/selector/X509CertificateHolderSelector.java b/pkix/src/main/java/org/bouncycastle/cert/selector/X509CertificateHolderSelector.java index 15329d6892..29dd1b389e 100644 --- a/pkix/src/main/java/org/bouncycastle/cert/selector/X509CertificateHolderSelector.java +++ b/pkix/src/main/java/org/bouncycastle/cert/selector/X509CertificateHolderSelector.java @@ -55,7 +55,7 @@ public X509CertificateHolderSelector(X500Name issuer, BigInteger serialNumber, b { this.issuer = issuer; this.serialNumber = serialNumber; - this.subjectKeyId = subjectKeyId; + this.subjectKeyId = Arrays.clone(subjectKeyId); } public X500Name getIssuer() diff --git a/pkix/src/main/java/org/bouncycastle/cert/selector/package-info.java b/pkix/src/main/java/org/bouncycastle/cert/selector/package-info.java new file mode 100644 index 0000000000..0cdc320f5c --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cert/selector/package-info.java @@ -0,0 +1,6 @@ +/** + * + * Specialised Selector classes for certificates, CRLs, and attribute certificates. + */ +package org.bouncycastle.cert.selector; diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSAlgorithm.java b/pkix/src/main/java/org/bouncycastle/cms/CMSAlgorithm.java index 103659c424..4c0499bf47 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSAlgorithm.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSAlgorithm.java @@ -46,6 +46,9 @@ public class CMSAlgorithm public static final ASN1ObjectIdentifier AES128_WRAP = NISTObjectIdentifiers.id_aes128_wrap.intern(); public static final ASN1ObjectIdentifier AES192_WRAP = NISTObjectIdentifiers.id_aes192_wrap.intern(); public static final ASN1ObjectIdentifier AES256_WRAP = NISTObjectIdentifiers.id_aes256_wrap.intern(); + public static final ASN1ObjectIdentifier AES128_WRAP_PAD = NISTObjectIdentifiers.id_aes128_wrap_pad.intern(); + public static final ASN1ObjectIdentifier AES192_WRAP_PAD = NISTObjectIdentifiers.id_aes192_wrap_pad.intern(); + public static final ASN1ObjectIdentifier AES256_WRAP_PAD = NISTObjectIdentifiers.id_aes256_wrap_pad.intern(); public static final ASN1ObjectIdentifier CAMELLIA128_WRAP = NTTObjectIdentifiers.id_camellia128_wrap.intern(); public static final ASN1ObjectIdentifier CAMELLIA192_WRAP = NTTObjectIdentifiers.id_camellia192_wrap.intern(); public static final ASN1ObjectIdentifier CAMELLIA256_WRAP = NTTObjectIdentifiers.id_camellia256_wrap.intern(); @@ -102,4 +105,5 @@ public class CMSAlgorithm public static final ASN1ObjectIdentifier SHAKE128_LEN = NISTObjectIdentifiers.id_shake128_len.intern(); public static final ASN1ObjectIdentifier SHAKE256_LEN = NISTObjectIdentifiers.id_shake256_len.intern(); + public static final ASN1ObjectIdentifier ChaCha20Poly1305 = PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305.intern(); } diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedData.java b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedData.java index f1edc92993..322ef043ea 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedData.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedData.java @@ -134,6 +134,15 @@ public byte[] getMAC() recipientInfos, this.authEncAlg, secureReadable); } + + /** + * return the object identifier for the content encryption algorithm. + */ + public String getEncryptionAlgOID() + { + return authEncAlg.getAlgorithm().getId(); + } + /** * Return the originator information associated with this message if present. * diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataGenerator.java index e84f2a69af..4665295e4e 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataGenerator.java @@ -12,6 +12,7 @@ import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.cms.EncryptedContentInfo; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.operator.OutputAEADEncryptor; public class CMSAuthEnvelopedDataGenerator @@ -36,10 +37,17 @@ private CMSAuthEnvelopedData doGenerate( try { OutputStream cOut = contentEncryptor.getOutputStream(bOut); - - content.write(cOut); - - authenticatedAttrSet = CMSUtils.processAuthAttrSet(authAttrsGenerator, contentEncryptor); + if (contentEncryptor.getAlgorithmIdentifier().getAlgorithm().equals(PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305)) + { + // AEAD Ciphers process AAD at first + authenticatedAttrSet = CMSUtils.processAuthAttrSet(authAttrsGenerator, contentEncryptor); + content.write(cOut); + } + else + { + content.write(cOut); + authenticatedAttrSet = CMSUtils.processAuthAttrSet(authAttrsGenerator, contentEncryptor); + } cOut.close(); } @@ -66,7 +74,7 @@ private CMSAuthEnvelopedData doGenerate( * generate an auth-enveloped object that contains an CMS Enveloped Data * object using the given provider. * - * @param content the content to be encrypted + * @param content the content to be encrypted * @param contentEncryptor the symmetric key based encryptor to encrypt the content with. */ public CMSAuthEnvelopedData generate( diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataStreamGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataStreamGenerator.java index 4e27d034ad..7c78c9078f 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataStreamGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedDataStreamGenerator.java @@ -11,7 +11,6 @@ import org.bouncycastle.asn1.BERSequenceGenerator; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERTaggedObject; -import org.bouncycastle.asn1.cms.AuthenticatedData; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.operator.OutputAEADEncryptor; @@ -78,7 +77,7 @@ protected OutputStream open( // BERSequenceGenerator authEnvGen = new BERSequenceGenerator(cGen.getRawOutputStream(), 0, true); - authEnvGen.addObject(new ASN1Integer(AuthenticatedData.calculateVersion(originatorInfo))); + authEnvGen.addObject(new ASN1Integer(0)); CMSUtils.addOriginatorInfoToGenerator(authEnvGen, originatorInfo); diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedGenerator.java index 92f93a2f63..f7de40cf35 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSAuthEnvelopedGenerator.java @@ -4,6 +4,7 @@ import java.util.List; import org.bouncycastle.asn1.cms.OriginatorInfo; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; /** * General class for generating a CMS enveloped-data message. @@ -11,7 +12,9 @@ public class CMSAuthEnvelopedGenerator extends CMSEnvelopedGenerator { - final List recipientInfoGenerators = new ArrayList(); + public static final String AES128_GCM = NISTObjectIdentifiers.id_aes128_GCM.getId(); + public static final String AES192_GCM = NISTObjectIdentifiers.id_aes192_GCM.getId(); + public static final String AES256_GCM = NISTObjectIdentifiers.id_aes256_GCM.getId(); protected CMSAttributeTableGenerator authAttrsGenerator = null; protected CMSAttributeTableGenerator unauthAttrsGenerator = null; diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSSignedData.java b/pkix/src/main/java/org/bouncycastle/cms/CMSSignedData.java index 4455bb8f9f..0cc10bada1 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSSignedData.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSSignedData.java @@ -21,6 +21,7 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.BERSequence; +import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DLSet; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.cms.SignedData; @@ -617,8 +618,17 @@ public static CMSSignedData replaceSigners(CMSSignedData signedData, SignerInfor vec.add(signer.toASN1Structure()); } - ASN1Set digestSet = CMSUtils.convertToDlSet(digestAlgs); + // keep ourselves compatible with what was there before - issue with + // NULL appearing and disappearing in AlgorithmIdentifier parameters. + Set oldDigestAlgs = signedData.getDigestAlgorithmIDs(); + AlgorithmIdentifier[] oldDigestAlgIds = (AlgorithmIdentifier[])oldDigestAlgs.toArray(new AlgorithmIdentifier[oldDigestAlgs.size()]); + AlgorithmIdentifier[] newDigestAlgIds = (AlgorithmIdentifier[])digestAlgs.toArray(new AlgorithmIdentifier[digestAlgs.size()]); + + compareAndReplaceAlgIds(oldDigestAlgIds, newDigestAlgIds); + + ASN1Set digestSet = new DLSet(newDigestAlgIds); ASN1Set signerSet = new DLSet(vec); + ASN1Sequence sD = (ASN1Sequence)signedData.signedData.toASN1Primitive(); // @@ -645,6 +655,27 @@ public static CMSSignedData replaceSigners(CMSSignedData signedData, SignerInfor return cms; } + private static void compareAndReplaceAlgIds(AlgorithmIdentifier[] oldDigestAlgIds, AlgorithmIdentifier[] newDigestAlgIds) + { + for (int i = 0; i != newDigestAlgIds.length; i++) + { + AlgorithmIdentifier newId = newDigestAlgIds[i]; + + for (int j = 0; j != oldDigestAlgIds.length; j++) + { + AlgorithmIdentifier oldId = oldDigestAlgIds[j]; + if (newId.getAlgorithm().equals(oldId.getAlgorithm())) + { + if (newId.getParameters() == null || DERNull.INSTANCE.equals(newId.getParameters())) + { + newDigestAlgIds[i] = oldId; + break; + } + } + } + } + } + /** * Replace the certificate and CRL information associated with this * CMSSignedData object with the new one passed in. diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataGenerator.java index 1bf5d393f2..59fc2d8d6b 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataGenerator.java @@ -52,7 +52,6 @@ public class CMSSignedDataGenerator extends CMSSignedGenerator { - private List signerInfs = new ArrayList(); private boolean isDefiniteLength = false; /** @@ -105,12 +104,7 @@ public CMSSignedData generate( boolean encapsulate) throws CMSException { - if (!signerInfs.isEmpty()) - { - throw new IllegalStateException("this method can only be used with SignerInfoGenerator"); - } - - // TODO + // TODO // if (signerInfs.isEmpty()) // { // /* RFC 3852 5.2 @@ -141,7 +135,7 @@ public CMSSignedData generate( // } Set digestAlgs = new LinkedHashSet(); - ASN1EncodableVector signerInfos = new ASN1EncodableVector(); + ASN1EncodableVector signerInfos = new ASN1EncodableVector(); digests.clear(); // clear the current preserved digest state @@ -159,92 +153,59 @@ public CMSSignedData generate( // // add the SignerInfo objects // - ASN1ObjectIdentifier contentTypeOID = content.getContentType(); - - ASN1OctetString octs = null; + ASN1ObjectIdentifier encapContentType = content.getContentType(); + ASN1OctetString encapContent = null; + // TODO[cms] Could be unnecessary copy e.g. if content is CMSProcessableByteArray (add hasContent method?) if (content.getContent() != null) { - ByteArrayOutputStream bOut = null; - if (encapsulate) { - bOut = new ByteArrayOutputStream(); - } - - OutputStream cOut = CMSUtils.attachSignersToOutputStream(signerGens, bOut); - - // Just in case it's unencapsulated and there are no signers! - cOut = CMSUtils.getSafeOutputStream(cOut); - - try - { - content.write(cOut); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - cOut.close(); - } - catch (IOException e) - { - throw new CMSException("data processing exception: " + e.getMessage(), e); - } + writeContentViaSignerGens(content, bOut); - if (encapsulate) - { if (isDefiniteLength) { - octs = new DEROctetString(bOut.toByteArray()); + encapContent = new DEROctetString(bOut.toByteArray()); } else { - octs = new BEROctetString(bOut.toByteArray()); + encapContent = new BEROctetString(bOut.toByteArray()); } } + else + { + writeContentViaSignerGens(content, null); + } } for (Iterator it = signerGens.iterator(); it.hasNext();) { - SignerInfoGenerator sGen = (SignerInfoGenerator)it.next(); - SignerInfo inf = sGen.generate(contentTypeOID); - - digestAlgs.add(inf.getDigestAlgorithm()); - signerInfos.add(inf); - - byte[] calcDigest = sGen.getCalculatedDigest(); - - if (calcDigest != null) - { - digests.put(inf.getDigestAlgorithm().getAlgorithm().getId(), calcDigest); - } + SignerInfoGenerator signerGen = (SignerInfoGenerator)it.next(); + SignerInfo signerInfo = generateSignerInfo(signerGen, encapContentType); + digestAlgs.add(signerInfo.getDigestAlgorithm()); + signerInfos.add(signerInfo); } - ASN1Set certificates = createSetFromList(certs, isDefiniteLength); + ASN1Set certificates = createSetFromList(this.certs, isDefiniteLength); - ASN1Set certrevlist = createSetFromList(crls, isDefiniteLength); + ASN1Set crls = createSetFromList(this.crls, isDefiniteLength); - ContentInfo encInfo = new ContentInfo(contentTypeOID, octs); + ContentInfo encapContentInfo = new ContentInfo(encapContentType, encapContent); - SignedData sd = new SignedData( - CMSUtils.convertToDlSet(digestAlgs), - encInfo, - certificates, - certrevlist, - new DERSet(signerInfos)); + SignedData signedData = new SignedData( + CMSUtils.convertToDlSet(digestAlgs), + encapContentInfo, + certificates, + crls, + new DERSet(signerInfos)); - ContentInfo contentInfo = new ContentInfo( - CMSObjectIdentifiers.signedData, sd); + ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, signedData); return new CMSSignedData(content, contentInfo); } - private static ASN1Set createSetFromList(List list, boolean isDefiniteLength) - { - if(list.size()!=0) - { - return isDefiniteLength ? CMSUtils.createDlSetFromList(list) : CMSUtils.createBerSetFromList(list); - } - return null; - } - /** * generate a set of one or more SignerInformation objects representing counter signatures on * the passed in SignerInformation object. @@ -255,7 +216,71 @@ private static ASN1Set createSetFromList(List list, boolean isDefiniteLength) public SignerInformationStore generateCounterSigners(SignerInformation signer) throws CMSException { - return this.generate(new CMSProcessableByteArray(null, signer.getSignature()), false).getSignerInfos(); + digests.clear(); + + CMSTypedData content = new CMSProcessableByteArray(null, signer.getSignature()); + + ArrayList signerInformations = new ArrayList(); + + for (Iterator it = _signers.iterator(); it.hasNext();) + { + SignerInformation _signer = (SignerInformation)it.next(); + SignerInfo signerInfo = _signer.toASN1Structure(); + signerInformations.add(new SignerInformation(signerInfo, null, content, null)); + } + + writeContentViaSignerGens(content, null); + + for (Iterator it = signerGens.iterator(); it.hasNext();) + { + SignerInfoGenerator signerGen = (SignerInfoGenerator)it.next(); + SignerInfo signerInfo = generateSignerInfo(signerGen, null); + signerInformations.add(new SignerInformation(signerInfo, null, content, null)); + } + + return new SignerInformationStore(signerInformations); + } + + private SignerInfo generateSignerInfo(SignerInfoGenerator signerGen, ASN1ObjectIdentifier contentType) + throws CMSException + { + SignerInfo signerInfo = signerGen.generate(contentType); + + byte[] calcDigest = signerGen.getCalculatedDigest(); + if (calcDigest != null) + { + digests.put(signerInfo.getDigestAlgorithm().getAlgorithm().getId(), calcDigest); + } + + return signerInfo; + } + + private void writeContentViaSignerGens(CMSTypedData content, OutputStream s) + throws CMSException + { + OutputStream cOut = CMSUtils.attachSignersToOutputStream(signerGens, s); + + // Just in case it's unencapsulated and there are no signers! + cOut = CMSUtils.getSafeOutputStream(cOut); + + try + { + content.write(cOut); + + cOut.close(); + } + catch (IOException e) + { + throw new CMSException("data processing exception: " + e.getMessage(), e); + } + } + + private static ASN1Set createSetFromList(List list, boolean isDefiniteLength) + { + return list.size() < 1 + ? null + : isDefiniteLength + ? CMSUtils.createDlSetFromList(list) + : CMSUtils.createBerSetFromList(list); } } - diff --git a/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataStreamGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataStreamGenerator.java index 3b45edb06b..519b11941c 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataStreamGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/CMSSignedDataStreamGenerator.java @@ -372,13 +372,13 @@ else if (tagged.getTagNo() == 3) return new ASN1Integer(1); } - private boolean checkForVersion3(List signerInfos, List signerInfoGens) + private static boolean checkForVersion3(List signerInfos, List signerInfoGens) { for (Iterator it = signerInfos.iterator(); it.hasNext();) { - SignerInfo s = SignerInfo.getInstance(((SignerInformation)it.next()).toASN1Structure()); + SignerInfo s = ((SignerInformation)it.next()).toASN1Structure(); - if (s.getVersion().intValueExact() == 3) + if (s.getVersion().hasValue(3)) { return true; } diff --git a/pkix/src/main/java/org/bouncycastle/cms/DefaultCMSSignatureAlgorithmNameGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/DefaultCMSSignatureAlgorithmNameGenerator.java index 12e49ead42..32e399ca28 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/DefaultCMSSignatureAlgorithmNameGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/DefaultCMSSignatureAlgorithmNameGenerator.java @@ -6,7 +6,6 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; @@ -30,10 +29,40 @@ public class DefaultCMSSignatureAlgorithmNameGenerator private void addEntries(ASN1ObjectIdentifier alias, String digest, String encryption) { - digestAlgs.put(alias, digest); - encryptionAlgs.put(alias, encryption); + addDigestAlg(alias, digest); + addEncryptionAlg(alias, encryption); } + private void addSimpleAlg(ASN1ObjectIdentifier alias, String algorithmName) + { + if (simpleAlgs.containsKey(alias)) + { + throw new IllegalStateException("object identifier already present in addSimpleAlg"); + } + + simpleAlgs.put(alias, algorithmName); + } + + private void addDigestAlg(ASN1ObjectIdentifier alias, String algorithmName) + { + if (digestAlgs.containsKey(alias)) + { + throw new IllegalStateException("object identifier already present in addDigestAlg"); + } + + digestAlgs.put(alias, algorithmName); + } + + private void addEncryptionAlg(ASN1ObjectIdentifier alias, String algorithmName) + { + if (encryptionAlgs.containsKey(alias)) + { + throw new IllegalStateException("object identifier already present in addEncryptionAlg"); + } + + encryptionAlgs.put(alias, algorithmName); + } + public DefaultCMSSignatureAlgorithmNameGenerator() { addEntries(NISTObjectIdentifiers.dsa_with_sha224, "SHA224", "DSA"); @@ -44,10 +73,6 @@ public DefaultCMSSignatureAlgorithmNameGenerator() addEntries(NISTObjectIdentifiers.id_dsa_with_sha3_256, "SHA3-256", "DSA"); addEntries(NISTObjectIdentifiers.id_dsa_with_sha3_384, "SHA3-384", "DSA"); addEntries(NISTObjectIdentifiers.id_dsa_with_sha3_512, "SHA3-512", "DSA"); - addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224, "SHA3-224", "RSA"); - addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, "SHA3-256", "RSA"); - addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, "SHA3-384", "RSA"); - addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, "SHA3-512", "RSA"); addEntries(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, "SHA3-224", "ECDSA"); addEntries(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, "SHA3-256", "ECDSA"); addEntries(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, "SHA3-384", "ECDSA"); @@ -71,8 +96,8 @@ public DefaultCMSSignatureAlgorithmNameGenerator() addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, "SHA3-256", "RSA"); addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, "SHA3-384", "RSA"); addEntries(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, "SHA3-512", "RSA"); - addEntries(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128, "SHAKE128", "RSAPSS"); - addEntries(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256, "SHAKE256", "RSAPSS"); + addEntries(X509ObjectIdentifiers.id_rsassa_pss_shake128, "SHAKE128", "RSAPSS"); + addEntries(X509ObjectIdentifiers.id_rsassa_pss_shake256, "SHAKE256", "RSAPSS"); addEntries(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128", "RSA"); addEntries(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160", "RSA"); @@ -83,8 +108,8 @@ public DefaultCMSSignatureAlgorithmNameGenerator() addEntries(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256", "ECDSA"); addEntries(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384", "ECDSA"); addEntries(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512", "ECDSA"); - addEntries(CMSObjectIdentifiers.id_ecdsa_with_shake128, "SHAKE128", "ECDSA"); - addEntries(CMSObjectIdentifiers.id_ecdsa_with_shake256, "SHAKE256", "ECDSA"); + addEntries(X509ObjectIdentifiers.id_ecdsa_with_shake128, "SHAKE128", "ECDSA"); + addEntries(X509ObjectIdentifiers.id_ecdsa_with_shake256, "SHAKE256", "ECDSA"); addEntries(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1", "DSA"); addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA"); addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA"); @@ -121,75 +146,108 @@ public DefaultCMSSignatureAlgorithmNameGenerator() addEntries(BCObjectIdentifiers.picnic_with_sha512, "SHA512", "Picnic"); addEntries(BCObjectIdentifiers.picnic_with_sha3_512, "SHA3-512", "Picnic"); - encryptionAlgs.put(X9ObjectIdentifiers.id_dsa, "DSA"); - encryptionAlgs.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); - encryptionAlgs.put(TeleTrusTObjectIdentifiers.teleTrusTRSAsignatureAlgorithm, "RSA"); - encryptionAlgs.put(X509ObjectIdentifiers.id_ea_rsa, "RSA"); - encryptionAlgs.put(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSAandMGF1"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3410_94, "GOST3410"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3410_2001, "ECGOST3410"); - encryptionAlgs.put(new ASN1ObjectIdentifier("1.3.6.1.4.1.5849.1.6.2"), "ECGOST3410"); - encryptionAlgs.put(new ASN1ObjectIdentifier("1.3.6.1.4.1.5849.1.1.5"), "GOST3410"); - encryptionAlgs.put(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256, "ECGOST3410-2012-256"); - encryptionAlgs.put(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512, "ECGOST3410-2012-512"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "ECGOST3410"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3410"); - encryptionAlgs.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "ECGOST3410-2012-256"); - encryptionAlgs.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "ECGOST3410-2012-512"); - encryptionAlgs.put(X9ObjectIdentifiers.id_ecPublicKey, "ECDSA"); - - digestAlgs.put(PKCSObjectIdentifiers.md2, "MD2"); - digestAlgs.put(PKCSObjectIdentifiers.md4, "MD4"); - digestAlgs.put(PKCSObjectIdentifiers.md5, "MD5"); - digestAlgs.put(OIWObjectIdentifiers.idSHA1, "SHA1"); - digestAlgs.put(NISTObjectIdentifiers.id_sha224, "SHA224"); - digestAlgs.put(NISTObjectIdentifiers.id_sha256, "SHA256"); - digestAlgs.put(NISTObjectIdentifiers.id_sha384, "SHA384"); - digestAlgs.put(NISTObjectIdentifiers.id_sha512, "SHA512"); - digestAlgs.put(NISTObjectIdentifiers.id_sha512_224, "SHA512(224)"); - digestAlgs.put(NISTObjectIdentifiers.id_sha512_256, "SHA512(256)"); - digestAlgs.put(NISTObjectIdentifiers.id_shake128, "SHAKE128"); - digestAlgs.put(NISTObjectIdentifiers.id_shake256, "SHAKE256"); - digestAlgs.put(NISTObjectIdentifiers.id_sha3_224, "SHA3-224"); - digestAlgs.put(NISTObjectIdentifiers.id_sha3_256, "SHA3-256"); - digestAlgs.put(NISTObjectIdentifiers.id_sha3_384, "SHA3-384"); - digestAlgs.put(NISTObjectIdentifiers.id_sha3_512, "SHA3-512"); - digestAlgs.put(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD128"); - digestAlgs.put(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD160"); - digestAlgs.put(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD256"); - digestAlgs.put(CryptoProObjectIdentifiers.gostR3411, "GOST3411"); - digestAlgs.put(new ASN1ObjectIdentifier("1.3.6.1.4.1.5849.1.2.1"), "GOST3411"); - digestAlgs.put(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256, "GOST3411-2012-256"); - digestAlgs.put(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512, "GOST3411-2012-512"); - digestAlgs.put(GMObjectIdentifiers.sm3, "SM3"); - - simpleAlgs.put(EdECObjectIdentifiers.id_Ed25519, "Ed25519"); - simpleAlgs.put(EdECObjectIdentifiers.id_Ed448, "Ed448"); - simpleAlgs.put(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); - - simpleAlgs.put(MiscObjectIdentifiers.id_alg_composite, "COMPOSITE"); - simpleAlgs.put(BCObjectIdentifiers.falcon_512, "Falcon-512"); - simpleAlgs.put(BCObjectIdentifiers.falcon_1024, "Falcon-1024"); - simpleAlgs.put(BCObjectIdentifiers.dilithium2, "Dilithium2"); - simpleAlgs.put(BCObjectIdentifiers.dilithium3, "Dilithium3"); - simpleAlgs.put(BCObjectIdentifiers.dilithium5, "Dilithium5"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_sha2_128s, "SPHINCS+-SHA2-128s"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_sha2_128f, "SPHINCS+-SHA2-128f"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_sha2_192s, "SPHINCS+-SHA2-192s"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_sha2_192f, "SPHINCS+-SHA2-192f"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_sha2_256s, "SPHINCS+-SHA2-256s"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_sha2_256f, "SPHINCS+-SHA2-256f"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_shake_128s, "SPHINCS+-SHAKE-128s"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_shake_128f, "SPHINCS+-SHAKE-128f"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_shake_192s, "SPHINCS+-SHAKE-192s"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_shake_192f, "SPHINCS+-SHAKE-192f"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_shake_256s, "SPHINCS+-SHAKE-256s"); - simpleAlgs.put(BCObjectIdentifiers.sphincsPlus_shake_256f, "SPHINCS+-SHAKE-256f"); - simpleAlgs.put(BCObjectIdentifiers.dilithium2, "Dilithium2"); - simpleAlgs.put(BCObjectIdentifiers.dilithium3, "Dilithium3"); - simpleAlgs.put(BCObjectIdentifiers.dilithium5, "Dilithium5"); - - simpleAlgs.put(BCObjectIdentifiers.picnic_signature, "Picnic"); + addEncryptionAlg(X9ObjectIdentifiers.id_dsa, "DSA"); + addEncryptionAlg(PKCSObjectIdentifiers.rsaEncryption, "RSA"); + addEncryptionAlg(TeleTrusTObjectIdentifiers.teleTrusTRSAsignatureAlgorithm, "RSA"); + addEncryptionAlg(X509ObjectIdentifiers.id_ea_rsa, "RSA"); + addEncryptionAlg(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSAandMGF1"); + addEncryptionAlg(CryptoProObjectIdentifiers.gostR3410_94, "GOST3410"); + addEncryptionAlg(CryptoProObjectIdentifiers.gostR3410_2001, "ECGOST3410"); + addEncryptionAlg(new ASN1ObjectIdentifier("1.3.6.1.4.1.5849.1.6.2"), "ECGOST3410"); + addEncryptionAlg(new ASN1ObjectIdentifier("1.3.6.1.4.1.5849.1.1.5"), "GOST3410"); + addEncryptionAlg(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256, "ECGOST3410-2012-256"); + addEncryptionAlg(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512, "ECGOST3410-2012-512"); + addEncryptionAlg(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "ECGOST3410"); + addEncryptionAlg(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3410"); + addEncryptionAlg(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "ECGOST3410-2012-256"); + addEncryptionAlg(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "ECGOST3410-2012-512"); + addEncryptionAlg(X9ObjectIdentifiers.id_ecPublicKey, "ECDSA"); + + addDigestAlg(PKCSObjectIdentifiers.md2, "MD2"); + addDigestAlg(PKCSObjectIdentifiers.md4, "MD4"); + addDigestAlg(PKCSObjectIdentifiers.md5, "MD5"); + addDigestAlg(OIWObjectIdentifiers.idSHA1, "SHA1"); + addDigestAlg(NISTObjectIdentifiers.id_sha224, "SHA224"); + addDigestAlg(NISTObjectIdentifiers.id_sha256, "SHA256"); + addDigestAlg(NISTObjectIdentifiers.id_sha384, "SHA384"); + addDigestAlg(NISTObjectIdentifiers.id_sha512, "SHA512"); + addDigestAlg(NISTObjectIdentifiers.id_sha512_224, "SHA512(224)"); + addDigestAlg(NISTObjectIdentifiers.id_sha512_256, "SHA512(256)"); + addDigestAlg(NISTObjectIdentifiers.id_shake128, "SHAKE128"); + addDigestAlg(NISTObjectIdentifiers.id_shake256, "SHAKE256"); + addDigestAlg(NISTObjectIdentifiers.id_sha3_224, "SHA3-224"); + addDigestAlg(NISTObjectIdentifiers.id_sha3_256, "SHA3-256"); + addDigestAlg(NISTObjectIdentifiers.id_sha3_384, "SHA3-384"); + addDigestAlg(NISTObjectIdentifiers.id_sha3_512, "SHA3-512"); + addDigestAlg(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD128"); + addDigestAlg(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD160"); + addDigestAlg(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD256"); + addDigestAlg(CryptoProObjectIdentifiers.gostR3411, "GOST3411"); + addDigestAlg(new ASN1ObjectIdentifier("1.3.6.1.4.1.5849.1.2.1"), "GOST3411"); + addDigestAlg(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256, "GOST3411-2012-256"); + addDigestAlg(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512, "GOST3411-2012-512"); + addDigestAlg(GMObjectIdentifiers.sm3, "SM3"); + + addSimpleAlg(EdECObjectIdentifiers.id_Ed25519, "Ed25519"); + addSimpleAlg(EdECObjectIdentifiers.id_Ed448, "Ed448"); + addSimpleAlg(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); + + addSimpleAlg(MiscObjectIdentifiers.id_alg_composite, "COMPOSITE"); + addSimpleAlg(BCObjectIdentifiers.falcon_512, "Falcon-512"); + addSimpleAlg(BCObjectIdentifiers.falcon_1024, "Falcon-1024"); + addSimpleAlg(BCObjectIdentifiers.dilithium2, "Dilithium2"); + addSimpleAlg(BCObjectIdentifiers.dilithium3, "Dilithium3"); + addSimpleAlg(BCObjectIdentifiers.dilithium5, "Dilithium5"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_sha2_128s, "SPHINCS+-SHA2-128s"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_sha2_128f, "SPHINCS+-SHA2-128f"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_sha2_192s, "SPHINCS+-SHA2-192s"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_sha2_192f, "SPHINCS+-SHA2-192f"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_sha2_256s, "SPHINCS+-SHA2-256s"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_sha2_256f, "SPHINCS+-SHA2-256f"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_shake_128s, "SPHINCS+-SHAKE-128s"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_shake_128f, "SPHINCS+-SHAKE-128f"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_shake_192s, "SPHINCS+-SHAKE-192s"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_shake_192f, "SPHINCS+-SHAKE-192f"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_shake_256s, "SPHINCS+-SHAKE-256s"); + addSimpleAlg(BCObjectIdentifiers.sphincsPlus_shake_256f, "SPHINCS+-SHAKE-256f"); + + addSimpleAlg(NISTObjectIdentifiers.id_ml_dsa_44, "ML-DSA-44"); + addSimpleAlg(NISTObjectIdentifiers.id_ml_dsa_65, "ML-DSA-65"); + addSimpleAlg(NISTObjectIdentifiers.id_ml_dsa_87, "ML-DSA-87"); + + addSimpleAlg(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, "ML-DSA-44-WITH-SHA512"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, "ML-DSA-65-WITH-SHA512"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, "ML-DSA-87-WITH-SHA512"); + + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, "SLH-DSA-SHA2-128S"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, "SLH-DSA-SHA2-128F"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, "SLH-DSA-SHA2-192S"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, "SLH-DSA-SHA2-192F"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, "SLH-DSA-SHA2-256S"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, "SLH-DSA-SHA2-256F"); + + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_shake_128s, "SLH-DSA-SHAKE-128S"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_shake_128f, "SLH-DSA-SHAKE-128F"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_shake_192s, "SLH-DSA-SHAKE-192S"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_shake_192f, "SLH-DSA-SHAKE-192F"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_shake_256s, "SLH-DSA-SHAKE-256S"); + addSimpleAlg(NISTObjectIdentifiers.id_slh_dsa_shake_256f, "SLH-DSA-SHAKE-256F"); + + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, "SLH-DSA-SHA2-128S-WITH-SHA256"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, "SLH-DSA-SHA2-128F-WITH-SHA256"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, "SLH-DSA-SHA2-192S-WITH-SHA512"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, "SLH-DSA-SHA2-192F-WITH-SHA512"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, "SLH-DSA-SHA2-256S-WITH-SHA512"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, "SLH-DSA-SHA2-256F-WITH-SHA512"); + + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, "SLH-DSA-SHAKE-128S-WITH-SHAKE128"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, "SLH-DSA-SHAKE-128F-WITH-SHAKE128"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, "SLH-DSA-SHAKE-192S-WITH-SHAKE256"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, "SLH-DSA-SHAKE-192F-WITH-SHAKE256"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, "SLH-DSA-SHAKE-256S-WITH-SHAKE256"); + addSimpleAlg(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, "SLH-DSA-SHAKE-256F-WITH-SHAKE256"); + + addSimpleAlg(BCObjectIdentifiers.picnic_signature, "Picnic"); } /** diff --git a/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientId.java b/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientId.java new file mode 100644 index 0000000000..03204d7cb8 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientId.java @@ -0,0 +1,65 @@ +package org.bouncycastle.cms; + +import java.math.BigInteger; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cert.selector.X509CertificateHolderSelector; + +public class KEMRecipientId + extends PKIXRecipientId +{ + private KEMRecipientId(X509CertificateHolderSelector baseSelector) + { + super(kem, baseSelector); + } + + /** + * Construct a key trans recipient ID with the value of a public key's subjectKeyId. + * + * @param subjectKeyId a subjectKeyId + */ + public KEMRecipientId(byte[] subjectKeyId) + { + super(kem, null, null, subjectKeyId); + } + + /** + * Construct a key trans recipient ID based on the issuer and serial number of the recipient's associated + * certificate. + * + * @param issuer the issuer of the recipient's associated certificate. + * @param serialNumber the serial number of the recipient's associated certificate. + */ + public KEMRecipientId(X500Name issuer, BigInteger serialNumber) + { + super(kem, issuer, serialNumber, null); + } + + /** + * Construct a key trans recipient ID based on the issuer and serial number of the recipient's associated + * certificate. + * + * @param issuer the issuer of the recipient's associated certificate. + * @param serialNumber the serial number of the recipient's associated certificate. + * @param subjectKeyId the subject key identifier to use to match the recipients associated certificate. + */ + public KEMRecipientId(X500Name issuer, BigInteger serialNumber, byte[] subjectKeyId) + { + super(kem, issuer, serialNumber, subjectKeyId); + } + + public Object clone() + { + return new KEMRecipientId(this.baseSelector); + } + + public boolean match(Object obj) + { + if (obj instanceof KEMRecipientInformation) + { + return ((KEMRecipientInformation)obj).getRID().equals(this); + } + + return super.match(obj); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientInformation.java b/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientInformation.java index 8a36dc8928..bf9984386c 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientInformation.java +++ b/pkix/src/main/java/org/bouncycastle/cms/KEMRecipientInformation.java @@ -5,6 +5,7 @@ import org.bouncycastle.asn1.cms.KEMRecipientInfo; import org.bouncycastle.asn1.cms.RecipientIdentifier; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.util.Arrays; public class KEMRecipientInformation extends RecipientInformation @@ -26,16 +27,31 @@ public class KEMRecipientInformation { ASN1OctetString octs = ASN1OctetString.getInstance(r.getId()); - rid = new KeyTransRecipientId(octs.getOctets()); // TODO: should be KEM + rid = new KEMRecipientId(octs.getOctets()); } else { IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.getInstance(r.getId()); - rid = new KeyTransRecipientId(iAnds.getName(), iAnds.getSerialNumber().getValue()); // TODO: + rid = new KEMRecipientId(iAnds.getName(), iAnds.getSerialNumber().getValue()); } } + public AlgorithmIdentifier getKdfAlgorithm() + { + return info.getKdf(); + } + + public byte[] getUkm() + { + return Arrays.clone(info.getUkm()); + } + + public byte[] getEncapsulation() + { + return Arrays.clone(info.getKemct().getOctets()); + } + protected RecipientOperator getRecipientOperator(Recipient recipient) throws CMSException { diff --git a/pkix/src/main/java/org/bouncycastle/cms/KeyAgreeRecipientId.java b/pkix/src/main/java/org/bouncycastle/cms/KeyAgreeRecipientId.java index a64720b7fd..adbe6394fc 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/KeyAgreeRecipientId.java +++ b/pkix/src/main/java/org/bouncycastle/cms/KeyAgreeRecipientId.java @@ -6,15 +6,11 @@ import org.bouncycastle.cert.selector.X509CertificateHolderSelector; public class KeyAgreeRecipientId - extends RecipientId + extends PKIXRecipientId { - private X509CertificateHolderSelector baseSelector; - private KeyAgreeRecipientId(X509CertificateHolderSelector baseSelector) { - super(keyAgree); - - this.baseSelector = baseSelector; + super(keyAgree, baseSelector); } /** @@ -24,7 +20,7 @@ private KeyAgreeRecipientId(X509CertificateHolderSelector baseSelector) */ public KeyAgreeRecipientId(byte[] subjectKeyId) { - this(null, null, subjectKeyId); + super(keyAgree, null, null, subjectKeyId); } /** @@ -36,12 +32,12 @@ public KeyAgreeRecipientId(byte[] subjectKeyId) */ public KeyAgreeRecipientId(X500Name issuer, BigInteger serialNumber) { - this(issuer, serialNumber, null); + super(keyAgree, issuer, serialNumber, null); } public KeyAgreeRecipientId(X500Name issuer, BigInteger serialNumber, byte[] subjectKeyId) { - this(new X509CertificateHolderSelector(issuer, serialNumber, subjectKeyId)); + super(keyAgree, issuer, serialNumber, subjectKeyId); } public X500Name getIssuer() diff --git a/pkix/src/main/java/org/bouncycastle/cms/KeyTransRecipientId.java b/pkix/src/main/java/org/bouncycastle/cms/KeyTransRecipientId.java index f850dcfad1..8041c1c39a 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/KeyTransRecipientId.java +++ b/pkix/src/main/java/org/bouncycastle/cms/KeyTransRecipientId.java @@ -6,15 +6,11 @@ import org.bouncycastle.cert.selector.X509CertificateHolderSelector; public class KeyTransRecipientId - extends RecipientId + extends PKIXRecipientId { - private X509CertificateHolderSelector baseSelector; - private KeyTransRecipientId(X509CertificateHolderSelector baseSelector) { - super(keyTrans); - - this.baseSelector = baseSelector; + super(keyTrans, baseSelector); } /** @@ -24,7 +20,7 @@ private KeyTransRecipientId(X509CertificateHolderSelector baseSelector) */ public KeyTransRecipientId(byte[] subjectKeyId) { - this(null, null, subjectKeyId); + super(keyTrans, null, null, subjectKeyId); } /** @@ -36,7 +32,7 @@ public KeyTransRecipientId(byte[] subjectKeyId) */ public KeyTransRecipientId(X500Name issuer, BigInteger serialNumber) { - this(issuer, serialNumber, null); + super(keyTrans, issuer, serialNumber, null); } /** @@ -49,27 +45,7 @@ public KeyTransRecipientId(X500Name issuer, BigInteger serialNumber) */ public KeyTransRecipientId(X500Name issuer, BigInteger serialNumber, byte[] subjectKeyId) { - this(new X509CertificateHolderSelector(issuer, serialNumber, subjectKeyId)); - } - - public X500Name getIssuer() - { - return baseSelector.getIssuer(); - } - - public BigInteger getSerialNumber() - { - return baseSelector.getSerialNumber(); - } - - public byte[] getSubjectKeyIdentifier() - { - return baseSelector.getSubjectKeyIdentifier(); - } - - public int hashCode() - { - return baseSelector.hashCode(); + super(keyTrans, issuer, serialNumber, subjectKeyId); } public boolean equals( @@ -97,6 +73,6 @@ public boolean match(Object obj) return ((KeyTransRecipientInformation)obj).getRID().equals(this); } - return baseSelector.match(obj); + return super.match(obj); } } diff --git a/pkix/src/main/java/org/bouncycastle/cms/PKIXRecipientId.java b/pkix/src/main/java/org/bouncycastle/cms/PKIXRecipientId.java new file mode 100644 index 0000000000..86ea9d3359 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/PKIXRecipientId.java @@ -0,0 +1,67 @@ +package org.bouncycastle.cms; + +import java.math.BigInteger; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cert.selector.X509CertificateHolderSelector; + +public class PKIXRecipientId + extends RecipientId +{ + protected final X509CertificateHolderSelector baseSelector; + + protected PKIXRecipientId(int type, X509CertificateHolderSelector baseSelector) + { + super(type); + + this.baseSelector = baseSelector; + } + + protected PKIXRecipientId(int type, X500Name issuer, BigInteger serialNumber, byte[] subjectKeyId) + { + this(type, new X509CertificateHolderSelector(issuer, serialNumber, subjectKeyId)); + } + + public X500Name getIssuer() + { + return baseSelector.getIssuer(); + } + + public BigInteger getSerialNumber() + { + return baseSelector.getSerialNumber(); + } + + public byte[] getSubjectKeyIdentifier() + { + return baseSelector.getSubjectKeyIdentifier(); + } + + public Object clone() + { + return new PKIXRecipientId(getType(), baseSelector); + } + + public int hashCode() + { + return baseSelector.hashCode(); + } + + public boolean equals( + Object o) + { + if (!(o instanceof PKIXRecipientId)) + { + return false; + } + + PKIXRecipientId id = (PKIXRecipientId)o; + + return this.baseSelector.equals(id.baseSelector); + } + + public boolean match(Object obj) + { + return baseSelector.match(obj); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/RecipientId.java b/pkix/src/main/java/org/bouncycastle/cms/RecipientId.java index fae5a100ed..a4b2676365 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/RecipientId.java +++ b/pkix/src/main/java/org/bouncycastle/cms/RecipientId.java @@ -9,6 +9,7 @@ public abstract class RecipientId public static final int kek = 1; public static final int keyAgree = 2; public static final int password = 3; + public static final int kem = 4; private final int type; diff --git a/pkix/src/main/java/org/bouncycastle/cms/RecipientInformationStore.java b/pkix/src/main/java/org/bouncycastle/cms/RecipientInformationStore.java index daf2d0238d..3870e260d8 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/RecipientInformationStore.java +++ b/pkix/src/main/java/org/bouncycastle/cms/RecipientInformationStore.java @@ -99,24 +99,24 @@ public Collection getRecipients() public Collection getRecipients( RecipientId selector) { - if (selector instanceof KeyTransRecipientId) + if (selector instanceof PKIXRecipientId) { - KeyTransRecipientId keyTrans = (KeyTransRecipientId)selector; + PKIXRecipientId pkixId = (PKIXRecipientId)selector; - X500Name issuer = keyTrans.getIssuer(); - byte[] subjectKeyId = keyTrans.getSubjectKeyIdentifier(); + X500Name issuer = pkixId.getIssuer(); + byte[] subjectKeyId = pkixId.getSubjectKeyIdentifier(); if (issuer != null && subjectKeyId != null) { List results = new ArrayList(); - Collection match1 = getRecipients(new KeyTransRecipientId(issuer, keyTrans.getSerialNumber())); + List match1 = (ArrayList)table.get(new PKIXRecipientId(pkixId.getType(), issuer, pkixId.getSerialNumber(), null)); if (match1 != null) { results.addAll(match1); } - Collection match2 = getRecipients(new KeyTransRecipientId(subjectKeyId)); + Collection match2 = (ArrayList)table.get(new PKIXRecipientId(pkixId.getType(), null, null, subjectKeyId)); if (match2 != null) { results.addAll(match2); diff --git a/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGenerator.java index d9102b595a..2e02d7ab7b 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGenerator.java @@ -78,6 +78,7 @@ public SignerInfoGenerator( this.digestAlgorithm = original.digestAlgorithm; this.digester = original.digester; this.sigEncAlgFinder = original.sigEncAlgFinder; + this.certHolder = original.certHolder; this.sAttrGen = sAttrGen; this.unsAttrGen = unsAttrGen; } diff --git a/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGeneratorBuilder.java b/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGeneratorBuilder.java index b10a6e3599..7ad627e487 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGeneratorBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/cms/SignerInfoGeneratorBuilder.java @@ -10,6 +10,7 @@ import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestCalculator; import org.bouncycastle.operator.DigestCalculatorProvider; +import org.bouncycastle.operator.ExtendedContentSigner; import org.bouncycastle.operator.OperatorCreationException; /** @@ -146,7 +147,26 @@ private SignerInfoGenerator createGenerator(ContentSigner contentSigner, SignerI } else { - digester = digestProvider.get(digAlgFinder.find(contentSigner.getAlgorithmIdentifier())); + AlgorithmIdentifier digestAlgorithmIdentifier = null; + + if (contentSigner instanceof ExtendedContentSigner) + { + digestAlgorithmIdentifier = ((ExtendedContentSigner)contentSigner).getDigestAlgorithmIdentifier(); + } + + if (digestAlgorithmIdentifier == null) + { + digestAlgorithmIdentifier = digAlgFinder.find(contentSigner.getAlgorithmIdentifier()); + } + + if (digestAlgorithmIdentifier != null) + { + digester = digestProvider.get(digestAlgorithmIdentifier); + } + else + { + throw new OperatorCreationException("no digest algorithm specified for signature algorithm"); + } } if (directSignature) diff --git a/pkix/src/main/java/org/bouncycastle/cms/SignerInformation.java b/pkix/src/main/java/org/bouncycastle/cms/SignerInformation.java index b2451b5262..3fdf3ff3bf 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/SignerInformation.java +++ b/pkix/src/main/java/org/bouncycastle/cms/SignerInformation.java @@ -341,6 +341,8 @@ private boolean doVerify( SignerInformationVerifier verifier) throws CMSException { + // TODO[cms] For pure signature algorithms, restrict digest algorithm to permitted set + String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID()); AlgorithmIdentifier realDigestAlgorithm = signedAttributeSet != null ? info.getDigestAlgorithm() : translateBrokenRSAPkcs7(encryptionAlgorithm, info.getDigestAlgorithm()); diff --git a/pkix/src/main/java/org/bouncycastle/cms/bc/package-info.java b/pkix/src/main/java/org/bouncycastle/cms/bc/package-info.java new file mode 100644 index 0000000000..c397e0ec5a --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/bc/package-info.java @@ -0,0 +1,4 @@ +/** + * CMS operator implementations for doing message encryption, signing, digesting, and MACing operations using the BC lightweight API. + */ +package org.bouncycastle.cms.bc; diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSInputAEADDecryptor.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSInputAEADDecryptor.java new file mode 100644 index 0000000000..f0405d365e --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSInputAEADDecryptor.java @@ -0,0 +1,78 @@ +package org.bouncycastle.cms.jcajce; + +import java.io.InputStream; +import java.io.OutputStream; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import javax.crypto.Cipher; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cms.InputStreamWithMAC; +import org.bouncycastle.jcajce.io.CipherInputStream; +import org.bouncycastle.operator.InputAEADDecryptor; + +class CMSInputAEADDecryptor + implements InputAEADDecryptor +{ + private final AlgorithmIdentifier contentEncryptionAlgorithm; + + private final Cipher dataCipher; + + private InputStream inputStream; + + CMSInputAEADDecryptor(AlgorithmIdentifier contentEncryptionAlgorithm, Cipher dataCipher) + { + this.contentEncryptionAlgorithm = contentEncryptionAlgorithm; + this.dataCipher = dataCipher; + } + + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return contentEncryptionAlgorithm; + } + + public InputStream getInputStream(InputStream dataIn) + { + inputStream = dataIn; + return new CipherInputStream(dataIn, dataCipher); + } + + public OutputStream getAADStream() + { + if (checkForAEAD()) + { + return new JceAADStream(dataCipher); + } + + return null; // TODO: okay this is awful, we could use AEADParameterSpec for earlier JDKs. + } + + public byte[] getMAC() + { + if (inputStream instanceof InputStreamWithMAC) + { + return ((InputStreamWithMAC)inputStream).getMAC(); + } + return null; + } + + private static boolean checkForAEAD() + { + return (Boolean)AccessController.doPrivileged(new PrivilegedAction() + { + public Object run() + { + try + { + return Cipher.class.getMethod("updateAAD", byte[].class) != null; + } + catch (Exception ignore) + { + // TODO[logging] Log the fact that we are falling back to BC-specific class + return Boolean.FALSE; + } + } + }); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSUtils.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSUtils.java index 9d9584f0bd..4d79bec90b 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSUtils.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/CMSUtils.java @@ -52,6 +52,9 @@ class CMSUtils wrapAlgNames.put(CMSAlgorithm.AES128_WRAP, "AESWRAP"); wrapAlgNames.put(CMSAlgorithm.AES192_WRAP, "AESWRAP"); wrapAlgNames.put(CMSAlgorithm.AES256_WRAP, "AESWRAP"); + wrapAlgNames.put(CMSAlgorithm.AES128_WRAP_PAD, "AES-KWP"); + wrapAlgNames.put(CMSAlgorithm.AES192_WRAP_PAD, "AES-KWP"); + wrapAlgNames.put(CMSAlgorithm.AES256_WRAP_PAD, "AES-KWP"); } static @@ -264,15 +267,15 @@ static Cipher createAsymmetricWrapper(JcaJceHelper helper, ASN1ObjectIdentifier public static int getKekSize(ASN1ObjectIdentifier symWrapAlg) { // TODO: add table - if (symWrapAlg.equals(CMSAlgorithm.AES256_WRAP)) + if (symWrapAlg.equals(CMSAlgorithm.AES256_WRAP) || symWrapAlg.equals(CMSAlgorithm.AES256_WRAP_PAD)) { return 32; } - else if (symWrapAlg.equals(CMSAlgorithm.AES128_WRAP)) + else if (symWrapAlg.equals(CMSAlgorithm.AES128_WRAP) || symWrapAlg.equals(CMSAlgorithm.AES128_WRAP_PAD)) { return 16; } - else if (symWrapAlg.equals(CMSAlgorithm.AES192_WRAP)) + else if (symWrapAlg.equals(CMSAlgorithm.AES192_WRAP) || symWrapAlg.equals(CMSAlgorithm.AES192_WRAP_PAD)) { return 24; } diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java index 65aa3fba4b..8a70df6f9b 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java @@ -110,6 +110,7 @@ public class EnvelopedDataHelper MAC_ALG_NAMES.put(CMSAlgorithm.AES192_CBC, "AESMac"); MAC_ALG_NAMES.put(CMSAlgorithm.AES256_CBC, "AESMac"); MAC_ALG_NAMES.put(CMSAlgorithm.RC2_CBC, "RC2Mac"); + MAC_ALG_NAMES.put(CMSAlgorithm.ChaCha20Poly1305, "ChaCha20Poly1305Mac"); PBKDF2_ALG_NAMES.put(PasswordRecipient.PRF.HMacSHA1.getAlgorithmID(), "PBKDF2WITHHMACSHA1"); PBKDF2_ALG_NAMES.put(PasswordRecipient.PRF.HMacSHA224.getAlgorithmID(), "PBKDF2WITHHMACSHA224"); @@ -123,6 +124,7 @@ public class EnvelopedDataHelper authEnvelopedAlgorithms.add(NISTObjectIdentifiers.id_aes128_CCM); authEnvelopedAlgorithms.add(NISTObjectIdentifiers.id_aes192_CCM); authEnvelopedAlgorithms.add(NISTObjectIdentifiers.id_aes256_CCM); + authEnvelopedAlgorithms.add(PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305); } private static final short[] rc2Table = { diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceAADStream.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceAADStream.java index 23e57852a4..c13454ef51 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceAADStream.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceAADStream.java @@ -8,7 +8,7 @@ class JceAADStream extends OutputStream { - private static final byte[] SINGLE_BYTE = new byte[1]; + private final byte[] SINGLE_BYTE = new byte[1]; private Cipher cipher; JceAADStream(Cipher cipher) diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java index 91b4ae4047..18e91bbf1e 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java @@ -376,10 +376,17 @@ public OutputStream getOutputStream(OutputStream dOut) { algId = algorithmIdentifier; } - - // TODO: works for CCM too, but others will follow. - GCMParameters p = GCMParameters.getInstance(algId.getParameters()); - macOut = new MacCaptureStream(dOut, p.getIcvLen()); + + if (algorithmIdentifier.getAlgorithm().equals(PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305)) + { + macOut = new MacCaptureStream(dOut, 16); + } + else + { + // TODO: works for CCM too, but others will follow. + GCMParameters p = GCMParameters.getInstance(algId.getParameters()); + macOut = new MacCaptureStream(dOut, p.getIcvLen()); + } return new CipherOutputStream(macOut, cipher); } diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSKEMKeyWrapper.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSKEMKeyWrapper.java index f2b4986477..eda92512f7 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSKEMKeyWrapper.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceCMSKEMKeyWrapper.java @@ -18,12 +18,14 @@ import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.cms.KEMKeyWrapper; +import org.bouncycastle.jcajce.interfaces.MLKEMPublicKey; import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.operator.DefaultKemEncapsulationLengthProvider; import org.bouncycastle.operator.GenericKey; +import org.bouncycastle.operator.KemEncapsulationLengthProvider; import org.bouncycastle.operator.OperatorException; -import org.bouncycastle.pqc.jcajce.interfaces.KyberPublicKey; import org.bouncycastle.pqc.jcajce.interfaces.NTRUKey; -import org.bouncycastle.pqc.jcajce.spec.KyberParameterSpec; import org.bouncycastle.pqc.jcajce.spec.NTRUParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; @@ -31,6 +33,7 @@ class JceCMSKEMKeyWrapper extends KEMKeyWrapper { + private final KemEncapsulationLengthProvider kemEncLenProvider = new DefaultKemEncapsulationLengthProvider(); private final AlgorithmIdentifier symWrapAlgorithm; private final int kekLength; @@ -178,30 +181,8 @@ public byte[] generateWrappedKey(GenericKey encryptionKey) } } - private static Map encLengths = new HashMap(); - - static - { - encLengths.put(KyberParameterSpec.kyber512.getName(), Integers.valueOf(768)); - encLengths.put(KyberParameterSpec.kyber768.getName(), Integers.valueOf(1088)); - encLengths.put(KyberParameterSpec.kyber1024.getName(), Integers.valueOf(1568)); - - encLengths.put(NTRUParameterSpec.ntruhps2048509.getName(), Integers.valueOf(699)); - encLengths.put(NTRUParameterSpec.ntruhps2048677.getName(), Integers.valueOf(930)); - encLengths.put(NTRUParameterSpec.ntruhps4096821.getName(), Integers.valueOf(1230)); - encLengths.put(NTRUParameterSpec.ntruhrss701.getName(), Integers.valueOf(1138)); - } - - private int getKemEncLength(PublicKey publicKey) + private int getKemEncLength(PublicKey key) { - if (publicKey instanceof KyberPublicKey) - { - return ((Integer)encLengths.get(((KyberPublicKey)publicKey).getParameterSpec().getName())).intValue(); - } - if (publicKey instanceof NTRUKey) - { - return ((Integer)encLengths.get(((NTRUKey)publicKey).getParameterSpec().getName())).intValue(); - } - return 0; + return kemEncLenProvider.getEncapsulationLength(SubjectPublicKeyInfo.getInstance(key.getEncoded()).getAlgorithm()); } } diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEKAuthEnvelopedRecipient.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEKAuthEnvelopedRecipient.java new file mode 100644 index 0000000000..9d871f1b74 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEKAuthEnvelopedRecipient.java @@ -0,0 +1,33 @@ +package org.bouncycastle.cms.jcajce; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.RecipientOperator; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; + +import java.security.Key; + +/** + * A recipient for CMS authenticated enveloped data encrypted with a KEK (Key Encryption Key). + * Handles key extraction and decryption of the content. + */ +public class JceKEKAuthEnvelopedRecipient + extends JceKEKRecipient +{ + public JceKEKAuthEnvelopedRecipient(SecretKey recipientKey) + { + super(recipientKey); + } + + public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey) + throws CMSException + { + Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, encryptedContentEncryptionKey); + + final Cipher dataCipher = contentHelper.createContentCipher(secretKey, contentEncryptionAlgorithm); + + return new RecipientOperator(new CMSInputAEADDecryptor(contentEncryptionAlgorithm, dataCipher)); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEMRecipientId.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEMRecipientId.java new file mode 100644 index 0000000000..4869645496 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEMRecipientId.java @@ -0,0 +1,57 @@ +package org.bouncycastle.cms.jcajce; + +import java.math.BigInteger; +import java.security.cert.X509Certificate; + +import javax.security.auth.x500.X500Principal; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cms.KEMRecipientId; + +public class JceKEMRecipientId + extends KEMRecipientId +{ + /** + * Construct a recipient id based on the issuer, serial number and subject key identifier (if present) of the passed in + * certificate. + * + * @param certificate certificate providing the issue and serial number and subject key identifier. + */ + public JceKEMRecipientId(X509Certificate certificate) + { + super(convertPrincipal(certificate.getIssuerX500Principal()), certificate.getSerialNumber(), CMSUtils.getSubjectKeyId(certificate)); + } + + /** + * Construct a recipient id based on the provided issuer and serial number.. + * + * @param issuer the issuer to use. + * @param serialNumber the serial number to use. + */ + public JceKEMRecipientId(X500Principal issuer, BigInteger serialNumber) + { + super(convertPrincipal(issuer), serialNumber); + } + + /** + * Construct a recipient id based on the provided issuer, serial number, and subjectKeyId.. + * + * @param issuer the issuer to use. + * @param serialNumber the serial number to use. + * @param subjectKeyId the subject key ID to use. + */ + public JceKEMRecipientId(X500Principal issuer, BigInteger serialNumber, byte[] subjectKeyId) + { + super(convertPrincipal(issuer), serialNumber, subjectKeyId); + } + + private static X500Name convertPrincipal(X500Principal issuer) + { + if (issuer == null) + { + return null; + } + + return X500Name.getInstance(issuer.getEncoded()); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeAuthEnvelopedRecipient.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeAuthEnvelopedRecipient.java new file mode 100644 index 0000000000..07fa192388 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeAuthEnvelopedRecipient.java @@ -0,0 +1,35 @@ +package org.bouncycastle.cms.jcajce; + +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.RecipientOperator; + +import javax.crypto.Cipher; + +import java.security.Key; +import java.security.PrivateKey; + +/** + * A recipient class for CMS authenticated enveloped data using key agreement (Key Agreement Recipient). + * Handles private key-based key extraction and content decryption. + */ +public class JceKeyAgreeAuthEnvelopedRecipient + extends JceKeyAgreeRecipient +{ + public JceKeyAgreeAuthEnvelopedRecipient(PrivateKey recipientKey) + { + super(recipientKey); + } + + public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentEncryptionAlgorithm, SubjectPublicKeyInfo senderPublicKey, ASN1OctetString userKeyingMaterial, byte[] encryptedContentKey) + throws CMSException + { + Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, senderPublicKey, userKeyingMaterial, encryptedContentKey); + + final Cipher dataCipher = contentHelper.createContentCipher(secretKey, contentEncryptionAlgorithm); + + return new RecipientOperator(new CMSInputAEADDecryptor(contentEncryptionAlgorithm, dataCipher)); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipient.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipient.java index 9c7144ef83..5c499edeab 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipient.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipient.java @@ -56,6 +56,7 @@ public abstract class JceKeyAgreeRecipient private PrivateKey recipientKey; protected EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); protected EnvelopedDataHelper contentHelper = helper; + protected EnvelopedDataHelper unwrappingHelper = helper; private SecretKeySizeProvider keySizeProvider = new DefaultSecretKeySizeProvider(); private AlgorithmIdentifier privKeyAlgID = null; @@ -74,6 +75,7 @@ public JceKeyAgreeRecipient setProvider(Provider provider) { this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); this.contentHelper = helper; + this.unwrappingHelper = helper; return this; } @@ -88,6 +90,33 @@ public JceKeyAgreeRecipient setProvider(String providerName) { this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); this.contentHelper = helper; + this.unwrappingHelper = helper; + + return this; + } + + /** + * Set the provider to use for unwrapping the content session key. + * + * @param provider provider to use. + * @return this recipient. + */ + public JceKeyAgreeRecipient setUnwrappingProvider(Provider provider) + { + this.unwrappingHelper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); + + return this; + } + + /** + * Set the provider to use for unwrapping the content session key. + * + * @param providerName the name of the provider to use. + * @return this recipient. + */ + public JceKeyAgreeRecipient setUnwrappingProvider(String providerName) + { + this.unwrappingHelper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); return this; } @@ -214,7 +243,7 @@ else if (CMSUtils.isGOST(keyEncAlg.getAlgorithm())) protected Key unwrapSessionKey(ASN1ObjectIdentifier wrapAlg, SecretKey agreedKey, ASN1ObjectIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey) throws CMSException, InvalidKeyException, NoSuchAlgorithmException { - Cipher keyCipher = helper.createCipher(wrapAlg); + Cipher keyCipher = unwrappingHelper.createCipher(wrapAlg); keyCipher.init(Cipher.UNWRAP_MODE, agreedKey); return keyCipher.unwrap(encryptedContentEncryptionKey, helper.getBaseCipherName(contentEncryptionAlgorithm), Cipher.SECRET_KEY); } diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java index 12761ab91a..d2dc76a569 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java @@ -57,6 +57,8 @@ public class JceKeyAgreeRecipientInfoGenerator private PrivateKey senderPrivateKey; private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); + private EnvelopedDataHelper wrappingHelper = null; + private SecureRandom random; private KeyPair ephemeralKP; private byte[] userKeyingMaterial; @@ -90,6 +92,20 @@ public JceKeyAgreeRecipientInfoGenerator setProvider(String providerName) return this; } + public JceKeyAgreeRecipientInfoGenerator setKeyWrappingProvider(Provider provider) + { + this.wrappingHelper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); + + return this; + } + + public JceKeyAgreeRecipientInfoGenerator setKeyWrappingProvider(String providerName) + { + this.wrappingHelper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); + + return this; + } + public JceKeyAgreeRecipientInfoGenerator setSecureRandom(SecureRandom random) { this.random = random; @@ -203,8 +219,10 @@ else if (CMSUtils.isGOST(keyAgreementOID)) SecretKey keyEncryptionKey = keyAgreement.generateSecret(keyEncAlg.getId()); + EnvelopedDataHelper keyWrapHelper = (wrappingHelper != null) ? wrappingHelper : helper; + // Wrap the content encryption key with the agreement key - Cipher keyEncryptionCipher = helper.createCipher(keyEncAlg); + Cipher keyEncryptionCipher = keyWrapHelper.createCipher(keyEncAlg); ASN1OctetString encryptedKey; if (keyEncAlg.equals(CryptoProObjectIdentifiers.id_Gost28147_89_None_KeyWrap) @@ -212,7 +230,7 @@ else if (CMSUtils.isGOST(keyAgreementOID)) { keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, new GOST28147WrapParameterSpec(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_A_ParamSet, userKeyingMaterial)); - byte[] encKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey)); + byte[] encKeyBytes = keyEncryptionCipher.wrap(keyWrapHelper.getJceKey(contentEncryptionKey)); Gost2814789EncryptedKey encKey = new Gost2814789EncryptedKey( Arrays.copyOfRange(encKeyBytes, 0, encKeyBytes.length - 4), @@ -224,7 +242,7 @@ else if (CMSUtils.isGOST(keyAgreementOID)) { keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random); - byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey)); + byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(keyWrapHelper.getJceKey(contentEncryptionKey)); encryptedKey = new DEROctetString(encryptedKeyBytes); } diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyTransAuthEnvelopedRecipient.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyTransAuthEnvelopedRecipient.java index c697ca83f5..82465911be 100644 --- a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyTransAuthEnvelopedRecipient.java +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKeyTransAuthEnvelopedRecipient.java @@ -1,8 +1,5 @@ package org.bouncycastle.cms.jcajce; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.security.Key; import java.security.PrivateKey; @@ -10,10 +7,7 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.InputStreamWithMAC; import org.bouncycastle.cms.RecipientOperator; -import org.bouncycastle.jcajce.io.CipherInputStream; -import org.bouncycastle.operator.InputAEADDecryptor; public class JceKeyTransAuthEnvelopedRecipient extends JceKeyTransRecipient @@ -30,60 +24,6 @@ public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionA final Cipher dataCipher = contentHelper.createContentCipher(secretKey, contentEncryptionAlgorithm); - return new RecipientOperator(new InputAEADDecryptor() - { - private InputStream inputStream; - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return contentEncryptionAlgorithm; - } - - public InputStream getInputStream(InputStream dataIn) - { - inputStream = dataIn; - return new CipherInputStream(dataIn, dataCipher); - } - - public OutputStream getAADStream() - { - return new AADStream(dataCipher); - } - - public byte[] getMAC() - { - if (inputStream instanceof InputStreamWithMAC) - { - return ((InputStreamWithMAC)inputStream).getMAC(); - } - return null; - } - }); - } - - private static class AADStream - extends OutputStream - { - private Cipher cipher; - private byte[] oneByte = new byte[1]; - - public AADStream(Cipher cipher) - { - this.cipher = cipher; - } - - public void write(byte[] buf, int off, int len) - throws IOException - { - cipher.updateAAD(buf, off, len); - } - - public void write(int b) - throws IOException - { - oneByte[0] = (byte)b; - - cipher.updateAAD(oneByte); - } + return new RecipientOperator(new CMSInputAEADDecryptor(contentEncryptionAlgorithm, dataCipher)); } } diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/JcePasswordAuthEnvelopedRecipient.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JcePasswordAuthEnvelopedRecipient.java new file mode 100644 index 0000000000..42f2e14297 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/JcePasswordAuthEnvelopedRecipient.java @@ -0,0 +1,31 @@ +package org.bouncycastle.cms.jcajce; + +import java.security.Key; + +import javax.crypto.Cipher; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.RecipientOperator; + +public class JcePasswordAuthEnvelopedRecipient + extends JcePasswordRecipient +{ + public JcePasswordAuthEnvelopedRecipient(char[] password) + { + super(password); + } + + public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionAlgorithm, + final AlgorithmIdentifier contentMacAlgorithm, + byte[] derivedKey, + byte[] encryptedContentEncryptionKey) + throws CMSException + { + Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentMacAlgorithm, derivedKey, encryptedContentEncryptionKey); + + final Cipher dataCipher = helper.createContentCipher(secretKey, contentMacAlgorithm); + + return new RecipientOperator(new CMSInputAEADDecryptor(contentMacAlgorithm, dataCipher)); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/cms/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/cms/jcajce/package-info.java new file mode 100644 index 0000000000..7b6150347a --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/jcajce/package-info.java @@ -0,0 +1,4 @@ +/** + * CMS operator implementations for doing message encryption, signing, digesting, and MACing operations using the JCA and the JCE. + */ +package org.bouncycastle.cms.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/cms/package-info.java b/pkix/src/main/java/org/bouncycastle/cms/package-info.java new file mode 100644 index 0000000000..541d4193fe --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/cms/package-info.java @@ -0,0 +1,4 @@ +/** + * A package for processing RFC 3852 Cryptographic Message Syntax (CMS) objects - also referred to as PKCS#7 (formerly RFC 2630, 3369). + */ +package org.bouncycastle.cms; diff --git a/pkix/src/main/java/org/bouncycastle/dvcs/package-info.java b/pkix/src/main/java/org/bouncycastle/dvcs/package-info.java new file mode 100644 index 0000000000..c7d86e2cd8 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/dvcs/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for dealing "Internet X.509 Public Key Infrastructure Data Validation and Certification Server Protocols" - RFC 3029. + */ +package org.bouncycastle.dvcs; diff --git a/pkix/src/main/java/org/bouncycastle/eac/operator/jcajce/JcaEACSignerBuilder.java b/pkix/src/main/java/org/bouncycastle/eac/operator/jcajce/JcaEACSignerBuilder.java index 89c598f89a..17cb28dc31 100644 --- a/pkix/src/main/java/org/bouncycastle/eac/operator/jcajce/JcaEACSignerBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/eac/operator/jcajce/JcaEACSignerBuilder.java @@ -142,6 +142,12 @@ private static byte[] reencode(byte[] rawSign) byte[] ret; int len = max(rLen, sLen); + // TODO: ideally this would be based on the field length + // if both sides are short, len might be short + if ((len & 0x01) != 0) + { + len++; + } ret = new byte[len * 2]; Arrays.fill(ret, (byte)0); diff --git a/pkix/src/main/java/org/bouncycastle/eac/package-info.java b/pkix/src/main/java/org/bouncycastle/eac/package-info.java new file mode 100644 index 0000000000..d2fb1893bc --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/eac/package-info.java @@ -0,0 +1,4 @@ +/** + * Base classes Extended Access Control (EAC) Certificates as described in "Technical Guideline, Advanced Security Mechanisms for Machine Readable Travel Documents, Extended Access Control (EAC), Version 1.0.1, BSI 2006". + */ +package org.bouncycastle.eac; diff --git a/pkix/src/main/java/org/bouncycastle/est/jcajce/JcaJceUtils.java b/pkix/src/main/java/org/bouncycastle/est/jcajce/JcaJceUtils.java index d581c55aea..3f6024e21b 100644 --- a/pkix/src/main/java/org/bouncycastle/est/jcajce/JcaJceUtils.java +++ b/pkix/src/main/java/org/bouncycastle/est/jcajce/JcaJceUtils.java @@ -35,6 +35,7 @@ public class JcaJceUtils { + @SuppressWarnings("TrustAllX509TrustManager") public static X509TrustManager getTrustAllTrustManager() { diff --git a/pkix/src/main/java/org/bouncycastle/est/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/est/jcajce/package-info.java new file mode 100644 index 0000000000..0d3a4b1a89 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/est/jcajce/package-info.java @@ -0,0 +1,4 @@ +/** + * JCA/JCE/JSSE support Enrollment over Secure Transport. + */ +package org.bouncycastle.est.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/est/package-info.java b/pkix/src/main/java/org/bouncycastle/est/package-info.java new file mode 100644 index 0000000000..bb62d3d4be --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/est/package-info.java @@ -0,0 +1,4 @@ +/** + * A package for processing messages for RFC 7030 "Enrollment over Secure Transport". + */ +package org.bouncycastle.est; diff --git a/pkix/src/main/java/org/bouncycastle/mozilla/package-info.java b/pkix/src/main/java/org/bouncycastle/mozilla/package-info.java new file mode 100644 index 0000000000..ef3c87b2df --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/mozilla/package-info.java @@ -0,0 +1,4 @@ +/** + * Support class for mozilla signed public key and challenge. + */ +package org.bouncycastle.mozilla; diff --git a/pkix/src/main/java/org/bouncycastle/openssl/PEMParser.java b/pkix/src/main/java/org/bouncycastle/openssl/PEMParser.java index 0ac715a8e6..32d0b5ee0b 100644 --- a/pkix/src/main/java/org/bouncycastle/openssl/PEMParser.java +++ b/pkix/src/main/java/org/bouncycastle/openssl/PEMParser.java @@ -10,7 +10,7 @@ import java.util.Set; import java.util.StringTokenizer; -import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1BitString; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -110,22 +110,19 @@ public Object readObject() throws IOException { PemObject obj = readPemObject(); + if (obj == null) + { + return null; + } - if (obj != null) + String type = obj.getType(); + Object pemObjectParser = parsers.get(type); + if (pemObjectParser == null) { - String type = obj.getType(); - Object pemObjectParser = parsers.get(type); - if (pemObjectParser != null) - { - return ((PemObjectParser)pemObjectParser).parseObject(obj); - } - else - { - throw new IOException("unrecognised object: " + type); - } + throw new IOException("unrecognised object: " + type); } - return null; + return ((PemObjectParser)pemObjectParser).parseObject(obj); } /** @@ -268,16 +265,14 @@ public PEMKeyPair parse(byte[] encoding) pKey.getParametersObject()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey); - if (pKey.getPublicKey() != null) + ASN1BitString publicKey = pKey.getPublicKey(); + SubjectPublicKeyInfo pubInfo = null; + if (publicKey != null) { - SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pKey.getPublicKey().getBytes()); - - return new PEMKeyPair(pubInfo, privInfo); - } - else - { - return new PEMKeyPair(null, privInfo); + pubInfo = new SubjectPublicKeyInfo(algId, publicKey.getBytes()); } + + return new PEMKeyPair(pubInfo, privInfo); } catch (IOException e) { @@ -353,9 +348,10 @@ public Object parseObject(PemObject obj) { try { + AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); RSAPublicKey rsaPubStructure = RSAPublicKey.getInstance(obj.getContent()); - return new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), rsaPubStructure); + return new SubjectPublicKeyInfo(algId, rsaPubStructure); } catch (IOException e) { @@ -475,9 +471,7 @@ public Object parseObject(PemObject obj) { try { - ASN1InputStream aIn = new ASN1InputStream(obj.getContent()); - - return ContentInfo.getInstance(aIn.readObject()); + return ContentInfo.getInstance(obj.getContent()); } catch (Exception e) { @@ -508,7 +502,7 @@ public Object parseObject(PemObject obj) if (param instanceof ASN1ObjectIdentifier) { - return ASN1Primitive.fromByteArray(obj.getContent()); + return param; } else if (param instanceof ASN1Sequence) { diff --git a/pkix/src/main/java/org/bouncycastle/openssl/jcajce/JcaPEMKeyConverter.java b/pkix/src/main/java/org/bouncycastle/openssl/jcajce/JcaPEMKeyConverter.java index 38ffe691db..08e8213723 100644 --- a/pkix/src/main/java/org/bouncycastle/openssl/jcajce/JcaPEMKeyConverter.java +++ b/pkix/src/main/java/org/bouncycastle/openssl/jcajce/JcaPEMKeyConverter.java @@ -29,15 +29,22 @@ public class JcaPEMKeyConverter { private JcaJceHelper helper = new DefaultJcaJceHelper(); - private static final Map algorithms = new HashMap(); + private final Map algorithms = new HashMap(); + + private static final Map baseMappings = new HashMap(); static { - algorithms.put(X9ObjectIdentifiers.id_ecPublicKey, "ECDSA"); - algorithms.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); - algorithms.put(X9ObjectIdentifiers.id_dsa, "DSA"); + baseMappings.put(X9ObjectIdentifiers.id_ecPublicKey, "ECDSA"); + baseMappings.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); + baseMappings.put(X9ObjectIdentifiers.id_dsa, "DSA"); } + public JcaPEMKeyConverter() + { + this.algorithms.putAll(baseMappings); + } + public JcaPEMKeyConverter setProvider(Provider provider) { this.helper = new ProviderJcaJceHelper(provider); @@ -52,6 +59,27 @@ public JcaPEMKeyConverter setProvider(String providerName) return this; } + /** + * Set the algorithm mapping for a particular OID to the given algorithm name. + * + * @param algOid object identifier used to identify the public/private key + * @param algorithmName algorithm name we want to map to in the provider. + * @return the current builder instance. + */ + public JcaPEMKeyConverter setAlgorithmMapping(ASN1ObjectIdentifier algOid, String algorithmName) + { + this.algorithms.put(algOid, algorithmName); + + return this; + } + + /** + * Convert a PEMKeyPair into a KeyPair, returning the converted result. + * + * @param keyPair the PEMKeyPair to be converted. + * @return the result of the conversion + * @throws PEMException if an exception is thrown attempting to do the conversion. + */ public KeyPair getKeyPair(PEMKeyPair keyPair) throws PEMException { diff --git a/pkix/src/main/java/org/bouncycastle/openssl/package-info.java b/pkix/src/main/java/org/bouncycastle/openssl/package-info.java new file mode 100644 index 0000000000..340401e9eb --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/openssl/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for dealing with OpenSSL PEM files. + */ +package org.bouncycastle.openssl; diff --git a/pkix/src/main/java/org/bouncycastle/operator/BufferingContentSigner.java b/pkix/src/main/java/org/bouncycastle/operator/BufferingContentSigner.java index d174367299..6e71ebf408 100644 --- a/pkix/src/main/java/org/bouncycastle/operator/BufferingContentSigner.java +++ b/pkix/src/main/java/org/bouncycastle/operator/BufferingContentSigner.java @@ -10,7 +10,7 @@ * block when ready for signing. */ public class BufferingContentSigner - implements ContentSigner + implements ExtendedContentSigner { private final ContentSigner contentSigner; private final OutputStream output; @@ -67,4 +67,21 @@ public byte[] getSignature() { return contentSigner.getSignature(); } + + + /** + * Return the algorithm identifier describing the digest + * algorithm used by this signature algorithm, if known. + * + * @return algorithm oid and parameters, null otherwise. + */ + public AlgorithmIdentifier getDigestAlgorithmIdentifier() + { + if (contentSigner instanceof ExtendedContentSigner) + { + return ((ExtendedContentSigner)contentSigner).getDigestAlgorithmIdentifier(); + } + + return null; + } } diff --git a/pkix/src/main/java/org/bouncycastle/operator/DefaultAlgorithmNameFinder.java b/pkix/src/main/java/org/bouncycastle/operator/DefaultAlgorithmNameFinder.java index 8fe8613e0f..3b8570e6bc 100644 --- a/pkix/src/main/java/org/bouncycastle/operator/DefaultAlgorithmNameFinder.java +++ b/pkix/src/main/java/org/bouncycastle/operator/DefaultAlgorithmNameFinder.java @@ -26,163 +26,209 @@ public class DefaultAlgorithmNameFinder { private final static Map algorithms = new HashMap(); + private static void addAlgorithm(ASN1ObjectIdentifier algOid, String algorithmName) + { + if (algorithms.containsKey(algOid)) + { + throw new IllegalStateException("algOid already present in addAlgorithm"); + } + + algorithms.put(algOid, algorithmName); + } + static { - algorithms.put(BSIObjectIdentifiers.ecdsa_plain_RIPEMD160, "RIPEMD160WITHPLAIN-ECDSA"); - algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA1, "SHA1WITHPLAIN-ECDSA"); - algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA224, "SHA224WITHPLAIN-ECDSA"); - algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA256, "SHA256WITHPLAIN-ECDSA"); - algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA384, "SHA384WITHPLAIN-ECDSA"); - algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA512, "SHA512WITHPLAIN-ECDSA"); - algorithms.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410-2001"); - algorithms.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410-94"); - algorithms.put(CryptoProObjectIdentifiers.gostR3411, "GOST3411"); - algorithms.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "GOST3411WITHECGOST3410-2012-256"); - algorithms.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "GOST3411WITHECGOST3410-2012-512"); - algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1WITHCVC-ECDSA"); - algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224WITHCVC-ECDSA"); - algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256WITHCVC-ECDSA"); - algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384WITHCVC-ECDSA"); - algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512WITHCVC-ECDSA"); - algorithms.put(BCObjectIdentifiers.falcon_512, "FALCON"); - algorithms.put(BCObjectIdentifiers.falcon_1024, "FALCON"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_128f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_128s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_128f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_192s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_192f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_192s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_192f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3, "SPHINCS+"); - - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_128f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_192s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_192f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, "SPHINCS+"); - algorithms.put(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, "SPHINCS+"); - - algorithms.put(NISTObjectIdentifiers.id_sha224, "SHA224"); - algorithms.put(NISTObjectIdentifiers.id_sha256, "SHA256"); - algorithms.put(NISTObjectIdentifiers.id_sha384, "SHA384"); - algorithms.put(NISTObjectIdentifiers.id_sha512, "SHA512"); - algorithms.put(NISTObjectIdentifiers.id_sha3_224, "SHA3-224"); - algorithms.put(NISTObjectIdentifiers.id_sha3_256, "SHA3-256"); - algorithms.put(NISTObjectIdentifiers.id_sha3_384, "SHA3-384"); - algorithms.put(NISTObjectIdentifiers.id_sha3_512, "SHA3-512"); - algorithms.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); - algorithms.put(OIWObjectIdentifiers.elGamalAlgorithm, "ELGAMAL"); - algorithms.put(OIWObjectIdentifiers.idSHA1, "SHA1"); - algorithms.put(OIWObjectIdentifiers.md5WithRSA, "MD5WITHRSA"); - algorithms.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.id_RSAES_OAEP, "RSAOAEP"); - algorithms.put(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSAPSS"); - algorithms.put(PKCSObjectIdentifiers.md2WithRSAEncryption, "MD2WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.md5, "MD5"); - algorithms.put(PKCSObjectIdentifiers.md5WithRSAEncryption, "MD5WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); - algorithms.put(PKCSObjectIdentifiers.sha1WithRSAEncryption, "SHA1WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - algorithms.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224, "SHA3-224WITHRSA"); - algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, "SHA3-256WITHRSA"); - algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, "SHA3-384WITHRSA"); - algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, "SHA3-512WITHRSA"); - algorithms.put(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD128"); - algorithms.put(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD160"); - algorithms.put(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD256"); - algorithms.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); - algorithms.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); - algorithms.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); - algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "ECDSAWITHSHA1"); - algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, "SHA3-224WITHECDSA"); - algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, "SHA3-256WITHECDSA"); - algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, "SHA3-384WITHECDSA"); - algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, "SHA3-512WITHECDSA"); - algorithms.put(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1WITHDSA"); - algorithms.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - algorithms.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); - algorithms.put(NISTObjectIdentifiers.dsa_with_sha384, "SHA384WITHDSA"); - algorithms.put(NISTObjectIdentifiers.dsa_with_sha512, "SHA512WITHDSA"); - algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_224, "SHA3-224WITHDSA"); - algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_256, "SHA3-256WITHDSA"); - algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_384, "SHA3-384WITHDSA"); - algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_512, "SHA3-512WITHDSA"); - algorithms.put(GNUObjectIdentifiers.Tiger_192, "Tiger"); - - algorithms.put(PKCSObjectIdentifiers.RC2_CBC, "RC2/CBC"); - algorithms.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESEDE-3KEY/CBC"); - algorithms.put(NISTObjectIdentifiers.id_aes128_ECB, "AES-128/ECB"); - algorithms.put(NISTObjectIdentifiers.id_aes192_ECB, "AES-192/ECB"); - algorithms.put(NISTObjectIdentifiers.id_aes256_ECB, "AES-256/ECB"); - algorithms.put(NISTObjectIdentifiers.id_aes128_CBC, "AES-128/CBC"); - algorithms.put(NISTObjectIdentifiers.id_aes192_CBC, "AES-192/CBC"); - algorithms.put(NISTObjectIdentifiers.id_aes256_CBC, "AES-256/CBC"); - algorithms.put(NISTObjectIdentifiers.id_aes128_CFB, "AES-128/CFB"); - algorithms.put(NISTObjectIdentifiers.id_aes192_CFB, "AES-192/CFB"); - algorithms.put(NISTObjectIdentifiers.id_aes256_CFB, "AES-256/CFB"); - algorithms.put(NISTObjectIdentifiers.id_aes128_OFB, "AES-128/OFB"); - algorithms.put(NISTObjectIdentifiers.id_aes192_OFB, "AES-192/OFB"); - algorithms.put(NISTObjectIdentifiers.id_aes256_OFB, "AES-256/OFB"); - algorithms.put(NTTObjectIdentifiers.id_camellia128_cbc, "CAMELLIA-128/CBC"); - algorithms.put(NTTObjectIdentifiers.id_camellia192_cbc, "CAMELLIA-192/CBC"); - algorithms.put(NTTObjectIdentifiers.id_camellia256_cbc, "CAMELLIA-256/CBC"); - algorithms.put(KISAObjectIdentifiers.id_seedCBC, "SEED/CBC"); - algorithms.put(MiscObjectIdentifiers.as_sys_sec_alg_ideaCBC, "IDEA/CBC"); - algorithms.put(MiscObjectIdentifiers.cast5CBC, "CAST5/CBC"); - algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_ECB, "Blowfish/ECB"); - algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CBC, "Blowfish/CBC"); - algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CFB, "Blowfish/CFB"); - algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_OFB, "Blowfish/OFB"); - algorithms.put(GNUObjectIdentifiers.Serpent_128_ECB, "Serpent-128/ECB"); - algorithms.put(GNUObjectIdentifiers.Serpent_128_CBC, "Serpent-128/CBC"); - algorithms.put(GNUObjectIdentifiers.Serpent_128_CFB, "Serpent-128/CFB"); - algorithms.put(GNUObjectIdentifiers.Serpent_128_OFB, "Serpent-128/OFB"); - algorithms.put(GNUObjectIdentifiers.Serpent_192_ECB, "Serpent-192/ECB"); - algorithms.put(GNUObjectIdentifiers.Serpent_192_CBC, "Serpent-192/CBC"); - algorithms.put(GNUObjectIdentifiers.Serpent_192_CFB, "Serpent-192/CFB"); - algorithms.put(GNUObjectIdentifiers.Serpent_192_OFB, "Serpent-192/OFB"); - algorithms.put(GNUObjectIdentifiers.Serpent_256_ECB, "Serpent-256/ECB"); - algorithms.put(GNUObjectIdentifiers.Serpent_256_CBC, "Serpent-256/CBC"); - algorithms.put(GNUObjectIdentifiers.Serpent_256_CFB, "Serpent-256/CFB"); - algorithms.put(GNUObjectIdentifiers.Serpent_256_OFB, "Serpent-256/OFB"); - algorithms.put(MiscObjectIdentifiers.id_blake2b160, "BLAKE2b-160"); - algorithms.put(MiscObjectIdentifiers.id_blake2b256, "BLAKE2b-256"); - algorithms.put(MiscObjectIdentifiers.id_blake2b384, "BLAKE2b-384"); - algorithms.put(MiscObjectIdentifiers.id_blake2b512, "BLAKE2b-512"); - algorithms.put(MiscObjectIdentifiers.id_blake2s128, "BLAKE2s-128"); - algorithms.put(MiscObjectIdentifiers.id_blake2s160, "BLAKE2s-160"); - algorithms.put(MiscObjectIdentifiers.id_blake2s224, "BLAKE2s-224"); - algorithms.put(MiscObjectIdentifiers.id_blake2s256, "BLAKE2s-256"); - algorithms.put(MiscObjectIdentifiers.blake3_256, "BLAKE3-256"); + addAlgorithm(BSIObjectIdentifiers.ecdsa_plain_RIPEMD160, "RIPEMD160WITHPLAIN-ECDSA"); + addAlgorithm(BSIObjectIdentifiers.ecdsa_plain_SHA1, "SHA1WITHPLAIN-ECDSA"); + addAlgorithm(BSIObjectIdentifiers.ecdsa_plain_SHA224, "SHA224WITHPLAIN-ECDSA"); + addAlgorithm(BSIObjectIdentifiers.ecdsa_plain_SHA256, "SHA256WITHPLAIN-ECDSA"); + addAlgorithm(BSIObjectIdentifiers.ecdsa_plain_SHA384, "SHA384WITHPLAIN-ECDSA"); + addAlgorithm(BSIObjectIdentifiers.ecdsa_plain_SHA512, "SHA512WITHPLAIN-ECDSA"); + addAlgorithm(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410-2001"); + addAlgorithm(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410-94"); + addAlgorithm(CryptoProObjectIdentifiers.gostR3411, "GOST3411"); + addAlgorithm(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "GOST3411WITHECGOST3410-2012-256"); + addAlgorithm(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "GOST3411WITHECGOST3410-2012-512"); + addAlgorithm(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1WITHCVC-ECDSA"); + addAlgorithm(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224WITHCVC-ECDSA"); + addAlgorithm(EACObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256WITHCVC-ECDSA"); + addAlgorithm(EACObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384WITHCVC-ECDSA"); + addAlgorithm(EACObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512WITHCVC-ECDSA"); + addAlgorithm(BCObjectIdentifiers.falcon_512, "FALCON"); + addAlgorithm(BCObjectIdentifiers.falcon_1024, "FALCON"); + + addAlgorithm(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); + + addAlgorithm(NISTObjectIdentifiers.id_ml_dsa_44, "ML-DSA-44"); + addAlgorithm(NISTObjectIdentifiers.id_ml_dsa_65, "ML-DSA-65"); + addAlgorithm(NISTObjectIdentifiers.id_ml_dsa_87, "ML-DSA-87"); + + addAlgorithm(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, "ML-DSA-44-WITH-SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, "ML-DSA-65-WITH-SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, "ML-DSA-87-WITH-SHA512"); + + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, "SLH-DSA-SHA2-128S"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, "SLH-DSA-SHA2-128F"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, "SLH-DSA-SHA2-192S"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, "SLH-DSA-SHA2-192F"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, "SLH-DSA-SHA2-256S"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, "SLH-DSA-SHA2-256F"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_shake_128s, "SLH-DSA-SHAKE-128S"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_shake_128f, "SLH-DSA-SHAKE-128F"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_shake_192s, "SLH-DSA-SHAKE-192S"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_shake_192f, "SLH-DSA-SHAKE-192F"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_shake_256s, "SLH-DSA-SHAKE-256S"); + addAlgorithm(NISTObjectIdentifiers.id_slh_dsa_shake_256f, "SLH-DSA-SHAKE-256F"); + + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, "SLH-DSA-SHA2-128S-WITH-SHA256"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, "SLH-DSA-SHA2-128F-WITH-SHA256"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, "SLH-DSA-SHA2-192S-WITH-SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, "SLH-DSA-SHA2-192F-WITH-SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, "SLH-DSA-SHA2-256S-WITH-SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, "SLH-DSA-SHA2-256F-WITH-SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, "SLH-DSA-SHAKE-128S-WITH-SHAKE128"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, "SLH-DSA-SHAKE-128F-WITH-SHAKE128"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, "SLH-DSA-SHAKE-192S-WITH-SHAKE256"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, "SLH-DSA-SHAKE-192F-WITH-SHAKE256"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, "SLH-DSA-SHAKE-256S-WITH-SHAKE256"); + addAlgorithm(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, "SLH-DSA-SHAKE-256F-WITH-SHAKE256"); + + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_128f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_128s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_128f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_192s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_192f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_192s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_192f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_256s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_128f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_192s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_192f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, "SPHINCS+"); + addAlgorithm(BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, "SPHINCS+"); + + addAlgorithm(NISTObjectIdentifiers.id_sha224, "SHA224"); + addAlgorithm(NISTObjectIdentifiers.id_sha256, "SHA256"); + addAlgorithm(NISTObjectIdentifiers.id_sha384, "SHA384"); + addAlgorithm(NISTObjectIdentifiers.id_sha512, "SHA512"); + addAlgorithm(NISTObjectIdentifiers.id_sha3_224, "SHA3-224"); + addAlgorithm(NISTObjectIdentifiers.id_sha3_256, "SHA3-256"); + addAlgorithm(NISTObjectIdentifiers.id_sha3_384, "SHA3-384"); + addAlgorithm(NISTObjectIdentifiers.id_sha3_512, "SHA3-512"); + addAlgorithm(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); + addAlgorithm(OIWObjectIdentifiers.elGamalAlgorithm, "ELGAMAL"); + addAlgorithm(OIWObjectIdentifiers.idSHA1, "SHA1"); + addAlgorithm(OIWObjectIdentifiers.md5WithRSA, "MD5WITHRSA"); + addAlgorithm(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.id_RSAES_OAEP, "RSAOAEP"); + addAlgorithm(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSAPSS"); + addAlgorithm(PKCSObjectIdentifiers.md2WithRSAEncryption, "MD2WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.md5, "MD5"); + addAlgorithm(PKCSObjectIdentifiers.md5WithRSAEncryption, "MD5WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.rsaEncryption, "RSA"); + addAlgorithm(PKCSObjectIdentifiers.sha1WithRSAEncryption, "SHA1WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); + addAlgorithm(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); + addAlgorithm(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224, "SHA3-224WITHRSA"); + addAlgorithm(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, "SHA3-256WITHRSA"); + addAlgorithm(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, "SHA3-384WITHRSA"); + addAlgorithm(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, "SHA3-512WITHRSA"); + addAlgorithm(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD128"); + addAlgorithm(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD160"); + addAlgorithm(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD256"); + addAlgorithm(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); + addAlgorithm(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); + addAlgorithm(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); + addAlgorithm(X9ObjectIdentifiers.ecdsa_with_SHA1, "ECDSAWITHSHA1"); + addAlgorithm(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); + addAlgorithm(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); + addAlgorithm(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); + addAlgorithm(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); + addAlgorithm(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, "SHA3-224WITHECDSA"); + addAlgorithm(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, "SHA3-256WITHECDSA"); + addAlgorithm(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, "SHA3-384WITHECDSA"); + addAlgorithm(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, "SHA3-512WITHECDSA"); + addAlgorithm(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.dsa_with_sha384, "SHA384WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.dsa_with_sha512, "SHA512WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.id_dsa_with_sha3_224, "SHA3-224WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.id_dsa_with_sha3_256, "SHA3-256WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.id_dsa_with_sha3_384, "SHA3-384WITHDSA"); + addAlgorithm(NISTObjectIdentifiers.id_dsa_with_sha3_512, "SHA3-512WITHDSA"); + addAlgorithm(GNUObjectIdentifiers.Tiger_192, "Tiger"); + + addAlgorithm(PKCSObjectIdentifiers.RC2_CBC, "RC2/CBC"); + addAlgorithm(PKCSObjectIdentifiers.des_EDE3_CBC, "DESEDE-3KEY/CBC"); + addAlgorithm(NISTObjectIdentifiers.id_aes128_ECB, "AES-128/ECB"); + addAlgorithm(NISTObjectIdentifiers.id_aes192_ECB, "AES-192/ECB"); + addAlgorithm(NISTObjectIdentifiers.id_aes256_ECB, "AES-256/ECB"); + addAlgorithm(NISTObjectIdentifiers.id_aes128_CBC, "AES-128/CBC"); + addAlgorithm(NISTObjectIdentifiers.id_aes192_CBC, "AES-192/CBC"); + addAlgorithm(NISTObjectIdentifiers.id_aes256_CBC, "AES-256/CBC"); + addAlgorithm(NISTObjectIdentifiers.id_aes128_CFB, "AES-128/CFB"); + addAlgorithm(NISTObjectIdentifiers.id_aes192_CFB, "AES-192/CFB"); + addAlgorithm(NISTObjectIdentifiers.id_aes256_CFB, "AES-256/CFB"); + addAlgorithm(NISTObjectIdentifiers.id_aes128_OFB, "AES-128/OFB"); + addAlgorithm(NISTObjectIdentifiers.id_aes192_OFB, "AES-192/OFB"); + addAlgorithm(NISTObjectIdentifiers.id_aes256_OFB, "AES-256/OFB"); + addAlgorithm(NTTObjectIdentifiers.id_camellia128_cbc, "CAMELLIA-128/CBC"); + addAlgorithm(NTTObjectIdentifiers.id_camellia192_cbc, "CAMELLIA-192/CBC"); + addAlgorithm(NTTObjectIdentifiers.id_camellia256_cbc, "CAMELLIA-256/CBC"); + addAlgorithm(KISAObjectIdentifiers.id_seedCBC, "SEED/CBC"); + addAlgorithm(MiscObjectIdentifiers.as_sys_sec_alg_ideaCBC, "IDEA/CBC"); + addAlgorithm(MiscObjectIdentifiers.cast5CBC, "CAST5/CBC"); + addAlgorithm(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_ECB, "Blowfish/ECB"); + addAlgorithm(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CBC, "Blowfish/CBC"); + addAlgorithm(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CFB, "Blowfish/CFB"); + addAlgorithm(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_OFB, "Blowfish/OFB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_128_ECB, "Serpent-128/ECB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_128_CBC, "Serpent-128/CBC"); + addAlgorithm(GNUObjectIdentifiers.Serpent_128_CFB, "Serpent-128/CFB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_128_OFB, "Serpent-128/OFB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_192_ECB, "Serpent-192/ECB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_192_CBC, "Serpent-192/CBC"); + addAlgorithm(GNUObjectIdentifiers.Serpent_192_CFB, "Serpent-192/CFB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_192_OFB, "Serpent-192/OFB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_256_ECB, "Serpent-256/ECB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_256_CBC, "Serpent-256/CBC"); + addAlgorithm(GNUObjectIdentifiers.Serpent_256_CFB, "Serpent-256/CFB"); + addAlgorithm(GNUObjectIdentifiers.Serpent_256_OFB, "Serpent-256/OFB"); + addAlgorithm(MiscObjectIdentifiers.id_blake2b160, "BLAKE2b-160"); + addAlgorithm(MiscObjectIdentifiers.id_blake2b256, "BLAKE2b-256"); + addAlgorithm(MiscObjectIdentifiers.id_blake2b384, "BLAKE2b-384"); + addAlgorithm(MiscObjectIdentifiers.id_blake2b512, "BLAKE2b-512"); + addAlgorithm(MiscObjectIdentifiers.id_blake2s128, "BLAKE2s-128"); + addAlgorithm(MiscObjectIdentifiers.id_blake2s160, "BLAKE2s-160"); + addAlgorithm(MiscObjectIdentifiers.id_blake2s224, "BLAKE2s-224"); + addAlgorithm(MiscObjectIdentifiers.id_blake2s256, "BLAKE2s-256"); + addAlgorithm(MiscObjectIdentifiers.blake3_256, "BLAKE3-256"); } public boolean hasAlgorithmName(ASN1ObjectIdentifier objectIdentifier) diff --git a/pkix/src/main/java/org/bouncycastle/operator/DefaultDigestAlgorithmIdentifierFinder.java b/pkix/src/main/java/org/bouncycastle/operator/DefaultDigestAlgorithmIdentifierFinder.java index e116690c64..c70677df51 100644 --- a/pkix/src/main/java/org/bouncycastle/operator/DefaultDigestAlgorithmIdentifierFinder.java +++ b/pkix/src/main/java/org/bouncycastle/operator/DefaultDigestAlgorithmIdentifierFinder.java @@ -10,7 +10,6 @@ import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; @@ -22,6 +21,7 @@ import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; public class DefaultDigestAlgorithmIdentifierFinder @@ -135,6 +135,39 @@ public class DefaultDigestAlgorithmIdentifierFinder digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, NISTObjectIdentifiers.id_shake256); digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, NISTObjectIdentifiers.id_sha256); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, NISTObjectIdentifiers.id_sha256); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, NISTObjectIdentifiers.id_sha256); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, NISTObjectIdentifiers.id_sha256); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, NISTObjectIdentifiers.id_sha512); + + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_shake_128s, NISTObjectIdentifiers.id_shake128); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_shake_128f, NISTObjectIdentifiers.id_shake128); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_shake_192s, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_shake_192f, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_shake_256s, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_slh_dsa_shake_256f, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, NISTObjectIdentifiers.id_shake128); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, NISTObjectIdentifiers.id_shake128); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, NISTObjectIdentifiers.id_shake256); + + digestOids.put(NISTObjectIdentifiers.id_ml_dsa_44, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_ml_dsa_65, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_ml_dsa_87, NISTObjectIdentifiers.id_shake256); + digestOids.put(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, NISTObjectIdentifiers.id_sha512); + digestOids.put(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, NISTObjectIdentifiers.id_sha512); + digestOids.put(BCObjectIdentifiers.falcon, NISTObjectIdentifiers.id_shake256); digestOids.put(BCObjectIdentifiers.falcon_512, NISTObjectIdentifiers.id_shake256); digestOids.put(BCObjectIdentifiers.falcon_1024, NISTObjectIdentifiers.id_shake256); @@ -152,10 +185,12 @@ public class DefaultDigestAlgorithmIdentifierFinder // digestOids.put(GMObjectIdentifiers.sm2sign_with_sha512, NISTObjectIdentifiers.id_sha512); digestOids.put(GMObjectIdentifiers.sm2sign_with_sm3, GMObjectIdentifiers.sm3); - digestOids.put(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128, NISTObjectIdentifiers.id_shake128); - digestOids.put(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256, NISTObjectIdentifiers.id_shake256); - digestOids.put(CMSObjectIdentifiers.id_ecdsa_with_shake128, NISTObjectIdentifiers.id_shake128); - digestOids.put(CMSObjectIdentifiers.id_ecdsa_with_shake256, NISTObjectIdentifiers.id_shake256); + digestOids.put(X509ObjectIdentifiers.id_rsassa_pss_shake128, NISTObjectIdentifiers.id_shake128); + digestOids.put(X509ObjectIdentifiers.id_rsassa_pss_shake256, NISTObjectIdentifiers.id_shake256); + digestOids.put(X509ObjectIdentifiers.id_ecdsa_with_shake128, NISTObjectIdentifiers.id_shake128); + digestOids.put(X509ObjectIdentifiers.id_ecdsa_with_shake256, NISTObjectIdentifiers.id_shake256); + + digestOids.put(EdECObjectIdentifiers.id_Ed25519, NISTObjectIdentifiers.id_sha512); digestNameToOids.put("SHA-1", OIWObjectIdentifiers.idSHA1); digestNameToOids.put("SHA-224", NISTObjectIdentifiers.id_sha224); @@ -212,8 +247,6 @@ public class DefaultDigestAlgorithmIdentifierFinder addDigestAlgId(NISTObjectIdentifiers.id_sha3_256, false); addDigestAlgId(NISTObjectIdentifiers.id_sha3_384, false); addDigestAlgId(NISTObjectIdentifiers.id_sha3_512, false); - - // RFC 8702 addDigestAlgId(NISTObjectIdentifiers.id_shake128, false); addDigestAlgId(NISTObjectIdentifiers.id_shake256, false); @@ -264,6 +297,8 @@ private static void addDigestAlgId(ASN1ObjectIdentifier oid, boolean withNullPar digestOidToAlgIds.put(oid, algId); } + public static DigestAlgorithmIdentifierFinder INSTANCE = new DefaultDigestAlgorithmIdentifierFinder(); + public AlgorithmIdentifier find(AlgorithmIdentifier sigAlgId) { ASN1ObjectIdentifier sigAlgOid = sigAlgId.getAlgorithm(); @@ -284,19 +319,17 @@ public AlgorithmIdentifier find(AlgorithmIdentifier sigAlgId) { digAlgOid = RSASSAPSSparams.getInstance(sigAlgId.getParameters()).getHashAlgorithm().getAlgorithm(); } - else if (sigAlgOid.equals(EdECObjectIdentifiers.id_Ed25519)) - { - digAlgOid = NISTObjectIdentifiers.id_sha512; - } - else if (sigAlgOid.equals(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig)) - { - digAlgOid = NISTObjectIdentifiers.id_sha256; - } else { digAlgOid = (ASN1ObjectIdentifier)digestOids.get(sigAlgOid); } + if (digAlgOid == null) + { + return null; + } + + // keep looking! return find(digAlgOid); } diff --git a/pkix/src/main/java/org/bouncycastle/operator/DefaultKemEncapsulationLengthProvider.java b/pkix/src/main/java/org/bouncycastle/operator/DefaultKemEncapsulationLengthProvider.java new file mode 100644 index 0000000000..9d279ef64d --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/DefaultKemEncapsulationLengthProvider.java @@ -0,0 +1,40 @@ +package org.bouncycastle.operator; + +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.jcajce.spec.NTRUParameterSpec; +import org.bouncycastle.util.Integers; + +/** + * Look up provider for encapsulation lengths produced be KEM algorithms + */ +public class DefaultKemEncapsulationLengthProvider + implements KemEncapsulationLengthProvider +{ + private static Map kemEncapsulationLengths = new HashMap(); + + static + { + kemEncapsulationLengths.put(NISTObjectIdentifiers.id_alg_ml_kem_512, Integers.valueOf(768)); + kemEncapsulationLengths.put(NISTObjectIdentifiers.id_alg_ml_kem_768, Integers.valueOf(1088)); + kemEncapsulationLengths.put(NISTObjectIdentifiers.id_alg_ml_kem_1024, Integers.valueOf(1568)); + + kemEncapsulationLengths.put(BCObjectIdentifiers.ntruhps2048509, Integers.valueOf(699)); + kemEncapsulationLengths.put(BCObjectIdentifiers.ntruhps2048677, Integers.valueOf(930)); + kemEncapsulationLengths.put(BCObjectIdentifiers.ntruhps4096821, Integers.valueOf(1230)); + kemEncapsulationLengths.put(BCObjectIdentifiers.ntruhps40961229, Integers.valueOf(1842)); + kemEncapsulationLengths.put(BCObjectIdentifiers.ntruhrss701, Integers.valueOf(1138)); + kemEncapsulationLengths.put(BCObjectIdentifiers.ntruhrss1373, Integers.valueOf(2401)); + } + + public int getEncapsulationLength(AlgorithmIdentifier kemAlgorithm) + { + return ((Integer)kemEncapsulationLengths.get(kemAlgorithm.getAlgorithm())).intValue(); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureAlgorithmIdentifierFinder.java b/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureAlgorithmIdentifierFinder.java index 93807dcd06..dab046e35d 100644 --- a/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureAlgorithmIdentifierFinder.java +++ b/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureAlgorithmIdentifierFinder.java @@ -11,7 +11,6 @@ import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; @@ -25,11 +24,12 @@ import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.util.Strings; public class DefaultSignatureAlgorithmIdentifierFinder - implements SignatureAlgorithmIdentifierFinder + implements SignatureAlgorithmIdentifierFinder { private static Map algorithms = new HashMap(); private static Set noParams = new HashSet(); @@ -37,219 +37,308 @@ public class DefaultSignatureAlgorithmIdentifierFinder private static Set pkcs15RsaEncryption = new HashSet(); private static Map digestOids = new HashMap(); + private static void addAlgorithm(String algorithmName, ASN1ObjectIdentifier algOid) + { + if (algorithms.containsKey(algorithmName)) + { + throw new IllegalStateException("algorithmName already present in addAlgorithm"); + } + + algorithms.put(algorithmName, algOid); + } + + private static void addDigestOid(ASN1ObjectIdentifier signatureOid, ASN1ObjectIdentifier digestOid) + { + if (digestOids.containsKey(signatureOid)) + { + throw new IllegalStateException("signatureOid already present in addDigestOid"); + } + + digestOids.put(signatureOid, digestOid); + } + + private static void addParameters(String algorithmName, ASN1Encodable parameters) + { + if (parameters == null) + { + throw new IllegalArgumentException("use 'noParams' instead for absent parameters"); + } + if (params.containsKey(algorithmName)) + { + throw new IllegalStateException("algorithmName already present in addParameters"); + } + + params.put(algorithmName, parameters); + } + + private static RSASSAPSSparams createPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) + { + return new RSASSAPSSparams( + hashAlgId, + new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), + new ASN1Integer(saltSize), + new ASN1Integer(1)); + } + static { - algorithms.put("COMPOSITE", MiscObjectIdentifiers.id_alg_composite); - - algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512(224)WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512_224WithRSAEncryption); - algorithms.put("SHA512(224)WITHRSA", PKCSObjectIdentifiers.sha512_224WithRSAEncryption); - algorithms.put("SHA512(256)WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512_256WithRSAEncryption); - algorithms.put("SHA512(256)WITHRSA", PKCSObjectIdentifiers.sha512_256WithRSAEncryption); - algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA3-224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA3-256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA3-384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA3-512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); - algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); - algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); - algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); - algorithms.put("SHA3-224WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_224); - algorithms.put("SHA3-256WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_256); - algorithms.put("SHA3-384WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_384); - algorithms.put("SHA3-512WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_512); - algorithms.put("SHA3-224WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_224); - algorithms.put("SHA3-256WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_256); - algorithms.put("SHA3-384WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_384); - algorithms.put("SHA3-512WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_512); - algorithms.put("SHA3-224WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224); - algorithms.put("SHA3-256WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256); - algorithms.put("SHA3-384WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384); - algorithms.put("SHA3-512WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512); - algorithms.put("SHA3-224WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224); - algorithms.put("SHA3-256WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256); - algorithms.put("SHA3-384WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384); - algorithms.put("SHA3-512WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512); - algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHECGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); - algorithms.put("GOST3411WITHECGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); - algorithms.put("GOST3411WITHGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); - algorithms.put("GOST3411WITHGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); - algorithms.put("GOST3411-2012-256WITHECGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); - algorithms.put("GOST3411-2012-512WITHECGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); - algorithms.put("GOST3411-2012-256WITHGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); - algorithms.put("GOST3411-2012-512WITHGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); - - algorithms.put("SHA1WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); - algorithms.put("SHA224WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); - algorithms.put("SHA256WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); - algorithms.put("SHA384WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); - algorithms.put("SHA512WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); - algorithms.put("SHA3-512WITHSPHINCS256", BCObjectIdentifiers.sphincs256_with_SHA3_512); - algorithms.put("SHA512WITHSPHINCS256", BCObjectIdentifiers.sphincs256_with_SHA512); - - algorithms.put("SHA1WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA1); - algorithms.put("RIPEMD160WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_RIPEMD160); - algorithms.put("SHA224WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA224); - algorithms.put("SHA256WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA256); - algorithms.put("SHA384WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA384); - algorithms.put("SHA512WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA512); - algorithms.put("SHA3-224WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_224); - algorithms.put("SHA3-256WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_256); - algorithms.put("SHA3-384WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_384); - algorithms.put("SHA3-512WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_512); - - algorithms.put("ED25519", EdECObjectIdentifiers.id_Ed25519); - algorithms.put("ED448", EdECObjectIdentifiers.id_Ed448); - - // RFC 8702 - algorithms.put("SHAKE128WITHRSAPSS", CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128); - algorithms.put("SHAKE256WITHRSAPSS", CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256); - algorithms.put("SHAKE128WITHRSASSA-PSS", CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128); - algorithms.put("SHAKE256WITHRSASSA-PSS", CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256); - algorithms.put("SHAKE128WITHECDSA", CMSObjectIdentifiers.id_ecdsa_with_shake128); - algorithms.put("SHAKE256WITHECDSA", CMSObjectIdentifiers.id_ecdsa_with_shake256); - -// algorithms.put("RIPEMD160WITHSM2", GMObjectIdentifiers.sm2sign_with_rmd160); -// algorithms.put("SHA1WITHSM2", GMObjectIdentifiers.sm2sign_with_sha1); -// algorithms.put("SHA224WITHSM2", GMObjectIdentifiers.sm2sign_with_sha224); - algorithms.put("SHA256WITHSM2", GMObjectIdentifiers.sm2sign_with_sha256); -// algorithms.put("SHA384WITHSM2", GMObjectIdentifiers.sm2sign_with_sha384); -// algorithms.put("SHA512WITHSM2", GMObjectIdentifiers.sm2sign_with_sha512); - algorithms.put("SM3WITHSM2", GMObjectIdentifiers.sm2sign_with_sm3); - - algorithms.put("SHA256WITHXMSS", BCObjectIdentifiers.xmss_SHA256ph); - algorithms.put("SHA512WITHXMSS", BCObjectIdentifiers.xmss_SHA512ph); - algorithms.put("SHAKE128WITHXMSS", BCObjectIdentifiers.xmss_SHAKE128ph); - algorithms.put("SHAKE256WITHXMSS", BCObjectIdentifiers.xmss_SHAKE256ph); - algorithms.put("SHAKE128(512)WITHXMSS", BCObjectIdentifiers.xmss_SHAKE128_512ph); - algorithms.put("SHAKE256(1024)WITHXMSS", BCObjectIdentifiers.xmss_SHAKE256_1024ph); - - algorithms.put("SHA256WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHA256ph); - algorithms.put("SHA512WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHA512ph); - algorithms.put("SHAKE128WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHAKE128ph); - algorithms.put("SHAKE256WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHAKE256ph); - - algorithms.put("SHA256WITHXMSS-SHA256", BCObjectIdentifiers.xmss_SHA256ph); - algorithms.put("SHA512WITHXMSS-SHA512", BCObjectIdentifiers.xmss_SHA512ph); - algorithms.put("SHAKE128WITHXMSS-SHAKE128", BCObjectIdentifiers.xmss_SHAKE128ph); - algorithms.put("SHAKE256WITHXMSS-SHAKE256", BCObjectIdentifiers.xmss_SHAKE256ph); - - algorithms.put("SHA256WITHXMSSMT-SHA256", BCObjectIdentifiers.xmss_mt_SHA256ph); - algorithms.put("SHA512WITHXMSSMT-SHA512", BCObjectIdentifiers.xmss_mt_SHA512ph); - algorithms.put("SHAKE128WITHXMSSMT-SHAKE128", BCObjectIdentifiers.xmss_mt_SHAKE128ph); - algorithms.put("SHAKE256WITHXMSSMT-SHAKE256", BCObjectIdentifiers.xmss_mt_SHAKE256ph); - algorithms.put("SHAKE128(512)WITHXMSSMT-SHAKE128", BCObjectIdentifiers.xmss_mt_SHAKE128_512ph); - algorithms.put("SHAKE256(1024)WITHXMSSMT-SHAKE256", BCObjectIdentifiers.xmss_mt_SHAKE256_1024ph); - - algorithms.put("LMS", PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); - - algorithms.put("XMSS", IsaraObjectIdentifiers.id_alg_xmss); - algorithms.put("XMSS-SHA256", BCObjectIdentifiers.xmss_SHA256); - algorithms.put("XMSS-SHA512", BCObjectIdentifiers.xmss_SHA512); - algorithms.put("XMSS-SHAKE128", BCObjectIdentifiers.xmss_SHAKE128); - algorithms.put("XMSS-SHAKE256", BCObjectIdentifiers.xmss_SHAKE256); - - algorithms.put("XMSSMT", IsaraObjectIdentifiers.id_alg_xmssmt); - algorithms.put("XMSSMT-SHA256", BCObjectIdentifiers.xmss_mt_SHA256); - algorithms.put("XMSSMT-SHA512", BCObjectIdentifiers.xmss_mt_SHA512); - algorithms.put("XMSSMT-SHAKE128", BCObjectIdentifiers.xmss_mt_SHAKE128); - algorithms.put("XMSSMT-SHAKE256", BCObjectIdentifiers.xmss_mt_SHAKE256); - - algorithms.put("SPHINCS+", BCObjectIdentifiers.sphincsPlus); - algorithms.put("SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus); - algorithms.put("SPHINCS+-SHA2-128S", BCObjectIdentifiers.sphincsPlus_sha2_128s); - algorithms.put("SPHINCS+-SHA2-128F", BCObjectIdentifiers.sphincsPlus_sha2_128f); - algorithms.put("SPHINCS+-SHA2-192S", BCObjectIdentifiers.sphincsPlus_sha2_192s); - algorithms.put("SPHINCS+-SHA2-192F", BCObjectIdentifiers.sphincsPlus_sha2_192f); - algorithms.put("SPHINCS+-SHA2-256S", BCObjectIdentifiers.sphincsPlus_sha2_256s); - algorithms.put("SPHINCS+-SHA2-256F", BCObjectIdentifiers.sphincsPlus_sha2_256f); - algorithms.put("SPHINCS+-SHAKE-128S", BCObjectIdentifiers.sphincsPlus_shake_128s); - algorithms.put("SPHINCS+-SHAKE-128F", BCObjectIdentifiers.sphincsPlus_shake_128f); - algorithms.put("SPHINCS+-SHAKE-192S", BCObjectIdentifiers.sphincsPlus_shake_192s); - algorithms.put("SPHINCS+-SHAKE-192F", BCObjectIdentifiers.sphincsPlus_shake_192f); - algorithms.put("SPHINCS+-SHAKE-256S", BCObjectIdentifiers.sphincsPlus_shake_256s); - algorithms.put("SPHINCS+-SHAKE-256F", BCObjectIdentifiers.sphincsPlus_shake_256f); - algorithms.put("SPHINCS+-HARAKA-128S-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_128s_r3); - algorithms.put("SPHINCS+-HARAKA-128F-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_128f_r3); - algorithms.put("SPHINCS+-HARAKA-192S-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_192s_r3); - algorithms.put("SPHINCS+-HARAKA-192F-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_192f_r3); - algorithms.put("SPHINCS+-HARAKA-256S-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_256s_r3); - algorithms.put("SPHINCS+-HARAKA-256F-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_256f_r3); - algorithms.put("SPHINCS+-HARAKA-128S-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple); - algorithms.put("SPHINCS+-HARAKA-128F-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple); - algorithms.put("SPHINCS+-HARAKA-192S-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple); - algorithms.put("SPHINCS+-HARAKA-192F-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple); - algorithms.put("SPHINCS+-HARAKA-256S-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple); - algorithms.put("SPHINCS+-HARAKA-256F-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple); - algorithms.put("SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus); - algorithms.put("DILITHIUM2", BCObjectIdentifiers.dilithium2); - algorithms.put("DILITHIUM3", BCObjectIdentifiers.dilithium3); - algorithms.put("DILITHIUM5", BCObjectIdentifiers.dilithium5); - algorithms.put("DILITHIUM2-AES", BCObjectIdentifiers.dilithium2_aes); - algorithms.put("DILITHIUM3-AES", BCObjectIdentifiers.dilithium3_aes); - algorithms.put("DILITHIUM5-AES", BCObjectIdentifiers.dilithium5_aes); - - algorithms.put("FALCON-512", BCObjectIdentifiers.falcon_512); - algorithms.put("FALCON-1024", BCObjectIdentifiers.falcon_1024); - - algorithms.put("PICNIC", BCObjectIdentifiers.picnic_signature); - algorithms.put("SHA512WITHPICNIC", BCObjectIdentifiers.picnic_with_sha512); - algorithms.put("SHA3-512WITHPICNIC", BCObjectIdentifiers.picnic_with_sha3_512); - algorithms.put("SHAKE256WITHPICNIC", BCObjectIdentifiers.picnic_with_shake256); - - algorithms.put("MLDSA44-RSA2048-PSS-SHA256", MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256); - algorithms.put("MLDSA44-RSA2048-PKCS15-SHA256", MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256); - algorithms.put("MLDSA44-ECDSA-P256-SHA256", MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); - algorithms.put("MLDSA44-ECDSA-BRAINPOOLP256R1-SHA256", MiscObjectIdentifiers.id_MLDSA44_ECDSA_brainpoolP256r1_SHA256); - algorithms.put("MLDSA44-ED25519-SHA512", MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512); - algorithms.put("MLDSA65-RSA3072-PSS-SHA512", MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA512); - algorithms.put("MLDSA65-RSA3072-PKCS15-SHA512", MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA512); - algorithms.put("MLDSA65-ECDSA-BRAINPOOLP256R1-SHA512", MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA512); - algorithms.put("MLDSA65-ECDSA-P256-SHA512", MiscObjectIdentifiers.id_MLDSA65_ECDSA_P256_SHA512); - algorithms.put("MLDSA65-ED25519-SHA512", MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512); - algorithms.put("MLDSA87-ECDSA-P384-SHA512", MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA512); - algorithms.put("MLDSA87-ECDSA-BRAINPOOLP384R1-SHA512", MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA512); - algorithms.put("MLDSA87-ED448-SHA512", MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512); - algorithms.put("FALCON512-ECDSA-P256-SHA256", MiscObjectIdentifiers.id_Falcon512_ECDSA_P256_SHA256); - algorithms.put("FALCON512-ECDSA-BRAINPOOLP256R1-SHA256", MiscObjectIdentifiers.id_Falcon512_ECDSA_brainpoolP256r1_SHA256); - algorithms.put("FALCON512-ED25519-SHA512", MiscObjectIdentifiers.id_Falcon512_Ed25519_SHA512); + addAlgorithm("COMPOSITE", MiscObjectIdentifiers.id_alg_composite); + + addAlgorithm("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption); + addAlgorithm("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption); + addAlgorithm("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption); + addAlgorithm("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption); + addAlgorithm("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption); + addAlgorithm("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption); + addAlgorithm("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); + addAlgorithm("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); + addAlgorithm("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); + addAlgorithm("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); + addAlgorithm("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); + addAlgorithm("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); + addAlgorithm("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); + addAlgorithm("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); + addAlgorithm("SHA512(224)WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512_224WithRSAEncryption); + addAlgorithm("SHA512(224)WITHRSA", PKCSObjectIdentifiers.sha512_224WithRSAEncryption); + addAlgorithm("SHA512(256)WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512_256WithRSAEncryption); + addAlgorithm("SHA512(256)WITHRSA", PKCSObjectIdentifiers.sha512_256WithRSAEncryption); + addAlgorithm("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA3-224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA3-256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA3-384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("SHA3-512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); + addAlgorithm("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); + addAlgorithm("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); + addAlgorithm("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); + addAlgorithm("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); + addAlgorithm("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); + addAlgorithm("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); + addAlgorithm("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1); + addAlgorithm("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1); + addAlgorithm("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); + addAlgorithm("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); + addAlgorithm("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); + addAlgorithm("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); + addAlgorithm("SHA3-224WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_224); + addAlgorithm("SHA3-256WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_256); + addAlgorithm("SHA3-384WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_384); + addAlgorithm("SHA3-512WITHDSA", NISTObjectIdentifiers.id_dsa_with_sha3_512); + addAlgorithm("SHA3-224WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_224); + addAlgorithm("SHA3-256WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_256); + addAlgorithm("SHA3-384WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_384); + addAlgorithm("SHA3-512WITHECDSA", NISTObjectIdentifiers.id_ecdsa_with_sha3_512); + addAlgorithm("SHA3-224WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224); + addAlgorithm("SHA3-256WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256); + addAlgorithm("SHA3-384WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384); + addAlgorithm("SHA3-512WITHRSA", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512); + addAlgorithm("SHA3-224WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224); + addAlgorithm("SHA3-256WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256); + addAlgorithm("SHA3-384WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384); + addAlgorithm("SHA3-512WITHRSAENCRYPTION", NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512); + addAlgorithm("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); + addAlgorithm("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); + addAlgorithm("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); + addAlgorithm("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); + addAlgorithm("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); + addAlgorithm("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); + addAlgorithm("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); + addAlgorithm("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); + addAlgorithm("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); + addAlgorithm("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); + addAlgorithm("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); + addAlgorithm("GOST3411WITHECGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + addAlgorithm("GOST3411WITHECGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + addAlgorithm("GOST3411WITHGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + addAlgorithm("GOST3411WITHGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + addAlgorithm("GOST3411-2012-256WITHECGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + addAlgorithm("GOST3411-2012-512WITHECGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + addAlgorithm("GOST3411-2012-256WITHGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + addAlgorithm("GOST3411-2012-512WITHGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + + addAlgorithm("SHA1WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); + addAlgorithm("SHA224WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); + addAlgorithm("SHA256WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); + addAlgorithm("SHA384WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); + addAlgorithm("SHA512WITHCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); + addAlgorithm("SHA3-512WITHSPHINCS256", BCObjectIdentifiers.sphincs256_with_SHA3_512); + addAlgorithm("SHA512WITHSPHINCS256", BCObjectIdentifiers.sphincs256_with_SHA512); + + addAlgorithm("SHA1WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA1); + addAlgorithm("RIPEMD160WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_RIPEMD160); + addAlgorithm("SHA224WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA224); + addAlgorithm("SHA256WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA256); + addAlgorithm("SHA384WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA384); + addAlgorithm("SHA512WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA512); + addAlgorithm("SHA3-224WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_224); + addAlgorithm("SHA3-256WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_256); + addAlgorithm("SHA3-384WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_384); + addAlgorithm("SHA3-512WITHPLAIN-ECDSA", BSIObjectIdentifiers.ecdsa_plain_SHA3_512); + + addAlgorithm("ED25519", EdECObjectIdentifiers.id_Ed25519); + addAlgorithm("ED448", EdECObjectIdentifiers.id_Ed448); + + // RFC 8692 + addAlgorithm("SHAKE128WITHRSAPSS", X509ObjectIdentifiers.id_rsassa_pss_shake128); + addAlgorithm("SHAKE256WITHRSAPSS", X509ObjectIdentifiers.id_rsassa_pss_shake256); + addAlgorithm("SHAKE128WITHRSASSA-PSS", X509ObjectIdentifiers.id_rsassa_pss_shake128); + addAlgorithm("SHAKE256WITHRSASSA-PSS", X509ObjectIdentifiers.id_rsassa_pss_shake256); + addAlgorithm("SHAKE128WITHECDSA", X509ObjectIdentifiers.id_ecdsa_with_shake128); + addAlgorithm("SHAKE256WITHECDSA", X509ObjectIdentifiers.id_ecdsa_with_shake256); + +// addAlgorithm("RIPEMD160WITHSM2", GMObjectIdentifiers.sm2sign_with_rmd160); +// addAlgorithm("SHA1WITHSM2", GMObjectIdentifiers.sm2sign_with_sha1); +// addAlgorithm("SHA224WITHSM2", GMObjectIdentifiers.sm2sign_with_sha224); + addAlgorithm("SHA256WITHSM2", GMObjectIdentifiers.sm2sign_with_sha256); +// addAlgorithm("SHA384WITHSM2", GMObjectIdentifiers.sm2sign_with_sha384); +// addAlgorithm("SHA512WITHSM2", GMObjectIdentifiers.sm2sign_with_sha512); + addAlgorithm("SM3WITHSM2", GMObjectIdentifiers.sm2sign_with_sm3); + + addAlgorithm("SHA256WITHXMSS", BCObjectIdentifiers.xmss_SHA256ph); + addAlgorithm("SHA512WITHXMSS", BCObjectIdentifiers.xmss_SHA512ph); + addAlgorithm("SHAKE128WITHXMSS", BCObjectIdentifiers.xmss_SHAKE128ph); + addAlgorithm("SHAKE256WITHXMSS", BCObjectIdentifiers.xmss_SHAKE256ph); + addAlgorithm("SHAKE128(512)WITHXMSS", BCObjectIdentifiers.xmss_SHAKE128_512ph); + addAlgorithm("SHAKE256(1024)WITHXMSS", BCObjectIdentifiers.xmss_SHAKE256_1024ph); + + addAlgorithm("SHA256WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHA256ph); + addAlgorithm("SHA512WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHA512ph); + addAlgorithm("SHAKE128WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHAKE128ph); + addAlgorithm("SHAKE256WITHXMSSMT", BCObjectIdentifiers.xmss_mt_SHAKE256ph); + + addAlgorithm("SHA256WITHXMSS-SHA256", BCObjectIdentifiers.xmss_SHA256ph); + addAlgorithm("SHA512WITHXMSS-SHA512", BCObjectIdentifiers.xmss_SHA512ph); + addAlgorithm("SHAKE128WITHXMSS-SHAKE128", BCObjectIdentifiers.xmss_SHAKE128ph); + addAlgorithm("SHAKE256WITHXMSS-SHAKE256", BCObjectIdentifiers.xmss_SHAKE256ph); + + addAlgorithm("SHA256WITHXMSSMT-SHA256", BCObjectIdentifiers.xmss_mt_SHA256ph); + addAlgorithm("SHA512WITHXMSSMT-SHA512", BCObjectIdentifiers.xmss_mt_SHA512ph); + addAlgorithm("SHAKE128WITHXMSSMT-SHAKE128", BCObjectIdentifiers.xmss_mt_SHAKE128ph); + addAlgorithm("SHAKE256WITHXMSSMT-SHAKE256", BCObjectIdentifiers.xmss_mt_SHAKE256ph); + addAlgorithm("SHAKE128(512)WITHXMSSMT-SHAKE128", BCObjectIdentifiers.xmss_mt_SHAKE128_512ph); + addAlgorithm("SHAKE256(1024)WITHXMSSMT-SHAKE256", BCObjectIdentifiers.xmss_mt_SHAKE256_1024ph); + + addAlgorithm("LMS", PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); + + addAlgorithm("XMSS", IsaraObjectIdentifiers.id_alg_xmss); + addAlgorithm("XMSS-SHA256", BCObjectIdentifiers.xmss_SHA256); + addAlgorithm("XMSS-SHA512", BCObjectIdentifiers.xmss_SHA512); + addAlgorithm("XMSS-SHAKE128", BCObjectIdentifiers.xmss_SHAKE128); + addAlgorithm("XMSS-SHAKE256", BCObjectIdentifiers.xmss_SHAKE256); + + addAlgorithm("XMSSMT", IsaraObjectIdentifiers.id_alg_xmssmt); + addAlgorithm("XMSSMT-SHA256", BCObjectIdentifiers.xmss_mt_SHA256); + addAlgorithm("XMSSMT-SHA512", BCObjectIdentifiers.xmss_mt_SHA512); + addAlgorithm("XMSSMT-SHAKE128", BCObjectIdentifiers.xmss_mt_SHAKE128); + addAlgorithm("XMSSMT-SHAKE256", BCObjectIdentifiers.xmss_mt_SHAKE256); + + addAlgorithm("SPHINCS+", BCObjectIdentifiers.sphincsPlus); + addAlgorithm("SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus); + addAlgorithm("SPHINCS+-SHA2-128S", BCObjectIdentifiers.sphincsPlus_sha2_128s); + addAlgorithm("SPHINCS+-SHA2-128F", BCObjectIdentifiers.sphincsPlus_sha2_128f); + addAlgorithm("SPHINCS+-SHA2-192S", BCObjectIdentifiers.sphincsPlus_sha2_192s); + addAlgorithm("SPHINCS+-SHA2-192F", BCObjectIdentifiers.sphincsPlus_sha2_192f); + addAlgorithm("SPHINCS+-SHA2-256S", BCObjectIdentifiers.sphincsPlus_sha2_256s); + addAlgorithm("SPHINCS+-SHA2-256F", BCObjectIdentifiers.sphincsPlus_sha2_256f); + addAlgorithm("SPHINCS+-SHAKE-128S", BCObjectIdentifiers.sphincsPlus_shake_128s); + addAlgorithm("SPHINCS+-SHAKE-128F", BCObjectIdentifiers.sphincsPlus_shake_128f); + addAlgorithm("SPHINCS+-SHAKE-192S", BCObjectIdentifiers.sphincsPlus_shake_192s); + addAlgorithm("SPHINCS+-SHAKE-192F", BCObjectIdentifiers.sphincsPlus_shake_192f); + addAlgorithm("SPHINCS+-SHAKE-256S", BCObjectIdentifiers.sphincsPlus_shake_256s); + addAlgorithm("SPHINCS+-SHAKE-256F", BCObjectIdentifiers.sphincsPlus_shake_256f); + addAlgorithm("SPHINCS+-HARAKA-128S-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_128s_r3); + addAlgorithm("SPHINCS+-HARAKA-128F-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_128f_r3); + addAlgorithm("SPHINCS+-HARAKA-192S-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_192s_r3); + addAlgorithm("SPHINCS+-HARAKA-192F-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_192f_r3); + addAlgorithm("SPHINCS+-HARAKA-256S-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_256s_r3); + addAlgorithm("SPHINCS+-HARAKA-256F-ROBUST", BCObjectIdentifiers.sphincsPlus_haraka_256f_r3); + addAlgorithm("SPHINCS+-HARAKA-128S-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_128s_r3_simple); + addAlgorithm("SPHINCS+-HARAKA-128F-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_128f_r3_simple); + addAlgorithm("SPHINCS+-HARAKA-192S-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_192s_r3_simple); + addAlgorithm("SPHINCS+-HARAKA-192F-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_192f_r3_simple); + addAlgorithm("SPHINCS+-HARAKA-256S-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple); + addAlgorithm("SPHINCS+-HARAKA-256F-SIMPLE", BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple); + addAlgorithm("DILITHIUM2", NISTObjectIdentifiers.id_ml_dsa_44); + addAlgorithm("DILITHIUM3", NISTObjectIdentifiers.id_ml_dsa_65); + addAlgorithm("DILITHIUM5", NISTObjectIdentifiers.id_ml_dsa_87); + addAlgorithm("DILITHIUM2-AES", BCObjectIdentifiers.dilithium2_aes); + addAlgorithm("DILITHIUM3-AES", BCObjectIdentifiers.dilithium3_aes); + addAlgorithm("DILITHIUM5-AES", BCObjectIdentifiers.dilithium5_aes); + + addAlgorithm("ML-DSA-44", NISTObjectIdentifiers.id_ml_dsa_44); + addAlgorithm("ML-DSA-65", NISTObjectIdentifiers.id_ml_dsa_65); + addAlgorithm("ML-DSA-87", NISTObjectIdentifiers.id_ml_dsa_87); + + addAlgorithm("ML-DSA-44-WITH-SHA512", NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + addAlgorithm("ML-DSA-65-WITH-SHA512", NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + addAlgorithm("ML-DSA-87-WITH-SHA512", NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + + addAlgorithm("SLH-DSA-SHA2-128S", NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + addAlgorithm("SLH-DSA-SHA2-128F", NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + addAlgorithm("SLH-DSA-SHA2-192S", NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + addAlgorithm("SLH-DSA-SHA2-192F", NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + addAlgorithm("SLH-DSA-SHA2-256S", NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + addAlgorithm("SLH-DSA-SHA2-256F", NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + addAlgorithm("SLH-DSA-SHAKE-128S", NISTObjectIdentifiers.id_slh_dsa_shake_128s); + addAlgorithm("SLH-DSA-SHAKE-128F", NISTObjectIdentifiers.id_slh_dsa_shake_128f); + addAlgorithm("SLH-DSA-SHAKE-192S", NISTObjectIdentifiers.id_slh_dsa_shake_192s); + addAlgorithm("SLH-DSA-SHAKE-192F", NISTObjectIdentifiers.id_slh_dsa_shake_192f); + addAlgorithm("SLH-DSA-SHAKE-256S", NISTObjectIdentifiers.id_slh_dsa_shake_256s); + addAlgorithm("SLH-DSA-SHAKE-256F", NISTObjectIdentifiers.id_slh_dsa_shake_256f); + + addAlgorithm("SLH-DSA-SHA2-128S-WITH-SHA256", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + addAlgorithm("SLH-DSA-SHA2-128F-WITH-SHA256", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + addAlgorithm("SLH-DSA-SHA2-192S-WITH-SHA512", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + addAlgorithm("SLH-DSA-SHA2-192F-WITH-SHA512", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + addAlgorithm("SLH-DSA-SHA2-256S-WITH-SHA512", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + addAlgorithm("SLH-DSA-SHA2-256F-WITH-SHA512", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + addAlgorithm("SLH-DSA-SHAKE-128S-WITH-SHAKE128", NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + addAlgorithm("SLH-DSA-SHAKE-128F-WITH-SHAKE128", NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + addAlgorithm("SLH-DSA-SHAKE-192S-WITH-SHAKE256", NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + addAlgorithm("SLH-DSA-SHAKE-192F-WITH-SHAKE256", NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + addAlgorithm("SLH-DSA-SHAKE-256S-WITH-SHAKE256", NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + addAlgorithm("SLH-DSA-SHAKE-256F-WITH-SHAKE256", NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + + addAlgorithm("FALCON-512", BCObjectIdentifiers.falcon_512); + addAlgorithm("FALCON-1024", BCObjectIdentifiers.falcon_1024); + + addAlgorithm("PICNIC", BCObjectIdentifiers.picnic_signature); + addAlgorithm("SHA512WITHPICNIC", BCObjectIdentifiers.picnic_with_sha512); + addAlgorithm("SHA3-512WITHPICNIC", BCObjectIdentifiers.picnic_with_sha3_512); + addAlgorithm("SHAKE256WITHPICNIC", BCObjectIdentifiers.picnic_with_shake256); + + addAlgorithm("MLDSA44-RSA2048-PSS-SHA256", MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256); + addAlgorithm("MLDSA44-RSA2048-PKCS15-SHA256", MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256); + addAlgorithm("MLDSA44-ED25519-SHA512", MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512); + addAlgorithm("MLDSA44-ECDSA-P256-SHA256", MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); + addAlgorithm("MLDSA65-RSA3072-PSS-SHA256", MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256); + addAlgorithm("MLDSA65-RSA3072-PKCS15-SHA256", MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256); + addAlgorithm("MLDSA65-RSA4096-PSS-SHA384", MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384); + addAlgorithm("MLDSA65-RSA4096-PKCS15-SHA384", MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384); + addAlgorithm("MLDSA65-ECDSA-P384-SHA384", MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384); + addAlgorithm("MLDSA65-ECDSA-BRAINPOOLP256R1-SHA256", MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256); + addAlgorithm("MLDSA65-ED25519-SHA512", MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512); + addAlgorithm("MLDSA87-ECDSA-P384-SHA384", MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384); + addAlgorithm("MLDSA87-ECDSA-BRAINPOOLP384R1-SHA384", MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384); + addAlgorithm("MLDSA87-ED448-SHA512", MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512); + + addAlgorithm("HASHMLDSA44-RSA2048-PSS-SHA256", MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256); + addAlgorithm("HASHMLDSA44-RSA2048-PKCS15-SHA256", MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256); + addAlgorithm("HASHMLDSA44-ED25519-SHA512", MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512); + addAlgorithm("HASHMLDSA44-ECDSA-P256-SHA256", MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256); + addAlgorithm("HASHMLDSA65-RSA3072-PSS-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512); + addAlgorithm("HASHMLDSA65-RSA3072-PKCS15-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512); + addAlgorithm("HASHMLDSA65-RSA4096-PSS-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512); + addAlgorithm("HASHMLDSA65-RSA4096-PKCS15-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512); + addAlgorithm("HASHMLDSA65-ECDSA-P384-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512); + addAlgorithm("HASHMLDSA65-ECDSA-BRAINPOOLP256R1-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512); + addAlgorithm("HASHMLDSA65-ED25519-SHA512", MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512); + addAlgorithm("HASHMLDSA87-ECDSA-P384-SHA512", MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512); + addAlgorithm("HASHMLDSA87-ECDSA-BRAINPOOLP384R1-SHA512", MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512); + addAlgorithm("HASHMLDSA87-ED448-SHA512", MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512); // // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. @@ -301,6 +390,31 @@ public class DefaultSignatureAlgorithmIdentifierFinder // // SPHINCS-PLUS // + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_128s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_128f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_192s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_192f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_256s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_256f); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + noParams.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + noParams.add(BCObjectIdentifiers.sphincsPlus); noParams.add(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3); noParams.add(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3); @@ -337,13 +451,19 @@ public class DefaultSignatureAlgorithmIdentifierFinder // Dilithium // noParams.add(BCObjectIdentifiers.dilithium); - noParams.add(BCObjectIdentifiers.dilithium2); - noParams.add(BCObjectIdentifiers.dilithium3); - noParams.add(BCObjectIdentifiers.dilithium5); noParams.add(BCObjectIdentifiers.dilithium2_aes); noParams.add(BCObjectIdentifiers.dilithium3_aes); noParams.add(BCObjectIdentifiers.dilithium5_aes); + noParams.add(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); + noParams.add(NISTObjectIdentifiers.id_ml_dsa_44); + noParams.add(NISTObjectIdentifiers.id_ml_dsa_65); + noParams.add(NISTObjectIdentifiers.id_ml_dsa_87); + noParams.add(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + noParams.add(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + noParams.add(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + + // // Falcon // @@ -406,31 +526,44 @@ public class DefaultSignatureAlgorithmIdentifierFinder noParams.add(EdECObjectIdentifiers.id_Ed25519); noParams.add(EdECObjectIdentifiers.id_Ed448); - // RFC 8702 - noParams.add(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128); - noParams.add(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256); - noParams.add(CMSObjectIdentifiers.id_ecdsa_with_shake128); - noParams.add(CMSObjectIdentifiers.id_ecdsa_with_shake256); + // RFC 8692 + noParams.add(X509ObjectIdentifiers.id_rsassa_pss_shake128); + noParams.add(X509ObjectIdentifiers.id_rsassa_pss_shake256); + noParams.add(X509ObjectIdentifiers.id_ecdsa_with_shake128); + noParams.add(X509ObjectIdentifiers.id_ecdsa_with_shake256); // // Composite - Draft 13 // noParams.add(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256); noParams.add(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256); - noParams.add(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); - noParams.add(MiscObjectIdentifiers.id_MLDSA44_ECDSA_brainpoolP256r1_SHA256); noParams.add(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512); - noParams.add(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA512); - noParams.add(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA512); - noParams.add(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA512); - noParams.add(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P256_SHA512); + noParams.add(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); + noParams.add(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256); + noParams.add(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256); + noParams.add(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384); + noParams.add(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384); + noParams.add(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384); + noParams.add(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256); noParams.add(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512); - noParams.add(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA512); - noParams.add(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA512); + noParams.add(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384); + noParams.add(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384); noParams.add(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512); - noParams.add(MiscObjectIdentifiers.id_Falcon512_ECDSA_P256_SHA256); - noParams.add(MiscObjectIdentifiers.id_Falcon512_ECDSA_brainpoolP256r1_SHA256); - noParams.add(MiscObjectIdentifiers.id_Falcon512_Ed25519_SHA512); + + noParams.add(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512); + noParams.add(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512); // // PKCS 1.5 encrypted algorithms @@ -454,154 +587,175 @@ public class DefaultSignatureAlgorithmIdentifierFinder // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE); - params.put("SHA1WITHRSAANDMGF1", createPSSParams(sha1AlgId, 20)); + addParameters("SHA1WITHRSAANDMGF1", createPSSParams(sha1AlgId, 20)); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE); - params.put("SHA224WITHRSAANDMGF1", createPSSParams(sha224AlgId, 28)); + addParameters("SHA224WITHRSAANDMGF1", createPSSParams(sha224AlgId, 28)); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE); - params.put("SHA256WITHRSAANDMGF1", createPSSParams(sha256AlgId, 32)); + addParameters("SHA256WITHRSAANDMGF1", createPSSParams(sha256AlgId, 32)); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE); - params.put("SHA384WITHRSAANDMGF1", createPSSParams(sha384AlgId, 48)); + addParameters("SHA384WITHRSAANDMGF1", createPSSParams(sha384AlgId, 48)); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, DERNull.INSTANCE); - params.put("SHA512WITHRSAANDMGF1", createPSSParams(sha512AlgId, 64)); + addParameters("SHA512WITHRSAANDMGF1", createPSSParams(sha512AlgId, 64)); AlgorithmIdentifier sha3_224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha3_224, DERNull.INSTANCE); - params.put("SHA3-224WITHRSAANDMGF1", createPSSParams(sha3_224AlgId, 28)); + addParameters("SHA3-224WITHRSAANDMGF1", createPSSParams(sha3_224AlgId, 28)); AlgorithmIdentifier sha3_256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha3_256, DERNull.INSTANCE); - params.put("SHA3-256WITHRSAANDMGF1", createPSSParams(sha3_256AlgId, 32)); + addParameters("SHA3-256WITHRSAANDMGF1", createPSSParams(sha3_256AlgId, 32)); AlgorithmIdentifier sha3_384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha3_384, DERNull.INSTANCE); - params.put("SHA3-384WITHRSAANDMGF1", createPSSParams(sha3_384AlgId, 48)); + addParameters("SHA3-384WITHRSAANDMGF1", createPSSParams(sha3_384AlgId, 48)); AlgorithmIdentifier sha3_512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha3_512, DERNull.INSTANCE); - params.put("SHA3-512WITHRSAANDMGF1", createPSSParams(sha3_512AlgId, 64)); + addParameters("SHA3-512WITHRSAANDMGF1", createPSSParams(sha3_512AlgId, 64)); // // digests // - digestOids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, NISTObjectIdentifiers.id_sha224); - digestOids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, NISTObjectIdentifiers.id_sha256); - digestOids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, NISTObjectIdentifiers.id_sha384); - digestOids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, NISTObjectIdentifiers.id_sha512); - digestOids.put(PKCSObjectIdentifiers.sha512_224WithRSAEncryption, NISTObjectIdentifiers.id_sha512_224); - digestOids.put(PKCSObjectIdentifiers.sha512_256WithRSAEncryption, NISTObjectIdentifiers.id_sha512_256); - digestOids.put(NISTObjectIdentifiers.dsa_with_sha224, NISTObjectIdentifiers.id_sha224); - digestOids.put(NISTObjectIdentifiers.dsa_with_sha256, NISTObjectIdentifiers.id_sha256); - digestOids.put(NISTObjectIdentifiers.dsa_with_sha384, NISTObjectIdentifiers.id_sha384); - digestOids.put(NISTObjectIdentifiers.dsa_with_sha512, NISTObjectIdentifiers.id_sha512); - digestOids.put(NISTObjectIdentifiers.id_dsa_with_sha3_224, NISTObjectIdentifiers.id_sha3_224); - digestOids.put(NISTObjectIdentifiers.id_dsa_with_sha3_256, NISTObjectIdentifiers.id_sha3_256); - digestOids.put(NISTObjectIdentifiers.id_dsa_with_sha3_384, NISTObjectIdentifiers.id_sha3_384); - digestOids.put(NISTObjectIdentifiers.id_dsa_with_sha3_512, NISTObjectIdentifiers.id_sha3_512); - digestOids.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, NISTObjectIdentifiers.id_sha3_224); - digestOids.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, NISTObjectIdentifiers.id_sha3_256); - digestOids.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, NISTObjectIdentifiers.id_sha3_384); - digestOids.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, NISTObjectIdentifiers.id_sha3_512); - digestOids.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224, NISTObjectIdentifiers.id_sha3_224); - digestOids.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, NISTObjectIdentifiers.id_sha3_256); - digestOids.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, NISTObjectIdentifiers.id_sha3_384); - digestOids.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, NISTObjectIdentifiers.id_sha3_512); - - digestOids.put(PKCSObjectIdentifiers.md2WithRSAEncryption, PKCSObjectIdentifiers.md2); - digestOids.put(PKCSObjectIdentifiers.md4WithRSAEncryption, PKCSObjectIdentifiers.md4); - digestOids.put(PKCSObjectIdentifiers.md5WithRSAEncryption, PKCSObjectIdentifiers.md5); - digestOids.put(PKCSObjectIdentifiers.sha1WithRSAEncryption, OIWObjectIdentifiers.idSHA1); - digestOids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, TeleTrusTObjectIdentifiers.ripemd128); - digestOids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, TeleTrusTObjectIdentifiers.ripemd160); - digestOids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, TeleTrusTObjectIdentifiers.ripemd256); - digestOids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, CryptoProObjectIdentifiers.gostR3411); - digestOids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, CryptoProObjectIdentifiers.gostR3411); - digestOids.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256); - digestOids.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512); - - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_128f_r3, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_192s_r3, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_192f_r3, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, NISTObjectIdentifiers.id_shake256); - - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_128f_r3_simple, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3_simple, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3_simple, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_192s_r3_simple, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_192f_r3_simple, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3_simple, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3_simple, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, NISTObjectIdentifiers.id_shake256); - - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_128s, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_128f, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_128s, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_128f, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_192s, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_192f, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_192s, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_192f, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_256s, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_sha2_256f, NISTObjectIdentifiers.id_sha256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256s, NISTObjectIdentifiers.id_shake256); - digestOids.put(BCObjectIdentifiers.sphincsPlus_shake_256f, NISTObjectIdentifiers.id_shake256); - -// digestOids.put(GMObjectIdentifiers.sm2sign_with_rmd160, TeleTrusTObjectIdentifiers.ripemd160); -// digestOids.put(GMObjectIdentifiers.sm2sign_with_sha1, OIWObjectIdentifiers.idSHA1); -// digestOids.put(GMObjectIdentifiers.sm2sign_with_sha224, NISTObjectIdentifiers.id_sha224); - digestOids.put(GMObjectIdentifiers.sm2sign_with_sha256, NISTObjectIdentifiers.id_sha256); -// digestOids.put(GMObjectIdentifiers.sm2sign_with_sha384, NISTObjectIdentifiers.id_sha384); -// digestOids.put(GMObjectIdentifiers.sm2sign_with_sha512, NISTObjectIdentifiers.id_sha512); - digestOids.put(GMObjectIdentifiers.sm2sign_with_sm3, GMObjectIdentifiers.sm3); - - digestOids.put(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128, NISTObjectIdentifiers.id_shake128); - digestOids.put(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256, NISTObjectIdentifiers.id_shake256); - digestOids.put(CMSObjectIdentifiers.id_ecdsa_with_shake128, NISTObjectIdentifiers.id_shake128); - digestOids.put(CMSObjectIdentifiers.id_ecdsa_with_shake256, NISTObjectIdentifiers.id_shake256); - } - - private static RSASSAPSSparams createPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) - { - return new RSASSAPSSparams( - hashAlgId, - new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), - new ASN1Integer(saltSize), - new ASN1Integer(1)); + addDigestOid(PKCSObjectIdentifiers.sha224WithRSAEncryption, NISTObjectIdentifiers.id_sha224); + addDigestOid(PKCSObjectIdentifiers.sha256WithRSAEncryption, NISTObjectIdentifiers.id_sha256); + addDigestOid(PKCSObjectIdentifiers.sha384WithRSAEncryption, NISTObjectIdentifiers.id_sha384); + addDigestOid(PKCSObjectIdentifiers.sha512WithRSAEncryption, NISTObjectIdentifiers.id_sha512); + addDigestOid(PKCSObjectIdentifiers.sha512_224WithRSAEncryption, NISTObjectIdentifiers.id_sha512_224); + addDigestOid(PKCSObjectIdentifiers.sha512_256WithRSAEncryption, NISTObjectIdentifiers.id_sha512_256); + addDigestOid(NISTObjectIdentifiers.dsa_with_sha224, NISTObjectIdentifiers.id_sha224); + addDigestOid(NISTObjectIdentifiers.dsa_with_sha256, NISTObjectIdentifiers.id_sha256); + addDigestOid(NISTObjectIdentifiers.dsa_with_sha384, NISTObjectIdentifiers.id_sha384); + addDigestOid(NISTObjectIdentifiers.dsa_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_dsa_with_sha3_224, NISTObjectIdentifiers.id_sha3_224); + addDigestOid(NISTObjectIdentifiers.id_dsa_with_sha3_256, NISTObjectIdentifiers.id_sha3_256); + addDigestOid(NISTObjectIdentifiers.id_dsa_with_sha3_384, NISTObjectIdentifiers.id_sha3_384); + addDigestOid(NISTObjectIdentifiers.id_dsa_with_sha3_512, NISTObjectIdentifiers.id_sha3_512); + addDigestOid(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, NISTObjectIdentifiers.id_sha3_224); + addDigestOid(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, NISTObjectIdentifiers.id_sha3_256); + addDigestOid(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, NISTObjectIdentifiers.id_sha3_384); + addDigestOid(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, NISTObjectIdentifiers.id_sha3_512); + addDigestOid(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224, NISTObjectIdentifiers.id_sha3_224); + addDigestOid(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, NISTObjectIdentifiers.id_sha3_256); + addDigestOid(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, NISTObjectIdentifiers.id_sha3_384); + addDigestOid(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, NISTObjectIdentifiers.id_sha3_512); + + addDigestOid(PKCSObjectIdentifiers.md2WithRSAEncryption, PKCSObjectIdentifiers.md2); + addDigestOid(PKCSObjectIdentifiers.md4WithRSAEncryption, PKCSObjectIdentifiers.md4); + addDigestOid(PKCSObjectIdentifiers.md5WithRSAEncryption, PKCSObjectIdentifiers.md5); + addDigestOid(PKCSObjectIdentifiers.sha1WithRSAEncryption, OIWObjectIdentifiers.idSHA1); + addDigestOid(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, TeleTrusTObjectIdentifiers.ripemd128); + addDigestOid(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, TeleTrusTObjectIdentifiers.ripemd160); + addDigestOid(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, TeleTrusTObjectIdentifiers.ripemd256); + addDigestOid(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, CryptoProObjectIdentifiers.gostR3411); + addDigestOid(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, CryptoProObjectIdentifiers.gostR3411); + addDigestOid(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256); + addDigestOid(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512); + + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_128f_r3, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_192s_r3, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_192f_r3, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_256s_r3, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_256f_r3, NISTObjectIdentifiers.id_shake256); + + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3_simple, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3_simple, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_128s_r3_simple, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_128f_r3_simple, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_192s_r3_simple, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_192f_r3_simple, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_192s_r3_simple, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_192f_r3_simple, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_256s_r3_simple, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_256f_r3_simple, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_256s_r3_simple, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_256f_r3_simple, NISTObjectIdentifiers.id_shake256); + + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_128s, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_128f, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_128s, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_128f, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_192s, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_192f, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_192s, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_192f, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_256s, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_sha2_256f, NISTObjectIdentifiers.id_sha256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_256s, NISTObjectIdentifiers.id_shake256); + addDigestOid(BCObjectIdentifiers.sphincsPlus_shake_256f, NISTObjectIdentifiers.id_shake256); + +// addDigestOid(GMObjectIdentifiers.sm2sign_with_rmd160, TeleTrusTObjectIdentifiers.ripemd160); +// addDigestOid(GMObjectIdentifiers.sm2sign_with_sha1, OIWObjectIdentifiers.idSHA1); +// addDigestOid(GMObjectIdentifiers.sm2sign_with_sha224, NISTObjectIdentifiers.id_sha224); + addDigestOid(GMObjectIdentifiers.sm2sign_with_sha256, NISTObjectIdentifiers.id_sha256); +// addDigestOid(GMObjectIdentifiers.sm2sign_with_sha384, NISTObjectIdentifiers.id_sha384); +// addDigestOid(GMObjectIdentifiers.sm2sign_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(GMObjectIdentifiers.sm2sign_with_sm3, GMObjectIdentifiers.sm3); + + addDigestOid(X509ObjectIdentifiers.id_rsassa_pss_shake128, NISTObjectIdentifiers.id_shake128); + addDigestOid(X509ObjectIdentifiers.id_rsassa_pss_shake256, NISTObjectIdentifiers.id_shake256); + addDigestOid(X509ObjectIdentifiers.id_ecdsa_with_shake128, NISTObjectIdentifiers.id_shake128); + addDigestOid(X509ObjectIdentifiers.id_ecdsa_with_shake256, NISTObjectIdentifiers.id_shake256); + + addDigestOid(NISTObjectIdentifiers.id_ml_dsa_44, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_ml_dsa_65, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_ml_dsa_87, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, NISTObjectIdentifiers.id_sha512); + + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, NISTObjectIdentifiers.id_sha256); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, NISTObjectIdentifiers.id_sha256); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_shake_128s, NISTObjectIdentifiers.id_shake128); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_shake_128f, NISTObjectIdentifiers.id_shake128); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_shake_192s, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_shake_192f, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_shake_256s, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_slh_dsa_shake_256f, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, NISTObjectIdentifiers.id_sha256); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, NISTObjectIdentifiers.id_sha256); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, NISTObjectIdentifiers.id_sha512); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, NISTObjectIdentifiers.id_shake128); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, NISTObjectIdentifiers.id_shake128); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, NISTObjectIdentifiers.id_shake256); + addDigestOid(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, NISTObjectIdentifiers.id_shake256); } public AlgorithmIdentifier find(String sigAlgName) { String algorithmName = Strings.toUpperCase(sigAlgName); - ASN1ObjectIdentifier sigOID = (ASN1ObjectIdentifier) algorithms.get(algorithmName); + ASN1ObjectIdentifier sigOID = (ASN1ObjectIdentifier)algorithms.get(algorithmName); if (sigOID == null) { throw new IllegalArgumentException("Unknown signature type requested: " + sigAlgName); } - AlgorithmIdentifier sigAlgId; if (noParams.contains(sigOID)) { - sigAlgId = new AlgorithmIdentifier(sigOID); - } - else if (params.containsKey(algorithmName)) - { - sigAlgId = new AlgorithmIdentifier(sigOID, (ASN1Encodable) params.get(algorithmName)); + return new AlgorithmIdentifier(sigOID); } - else + + ASN1Encodable sigAlgParams = (ASN1Encodable)params.get(algorithmName); + if (sigAlgParams == null) { - sigAlgId = new AlgorithmIdentifier(sigOID, DERNull.INSTANCE); + sigAlgParams = DERNull.INSTANCE; } - return sigAlgId; + + return new AlgorithmIdentifier(sigOID, sigAlgParams); } } diff --git a/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureNameFinder.java b/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureNameFinder.java index a0a1426ea5..3765769abb 100644 --- a/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureNameFinder.java +++ b/pkix/src/main/java/org/bouncycastle/operator/DefaultSignatureNameFinder.java @@ -7,7 +7,6 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; @@ -19,6 +18,7 @@ import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; /** @@ -30,65 +30,115 @@ public class DefaultSignatureNameFinder private static final Map oids = new HashMap(); private static final Map digests = new HashMap(); + private static void addSignatureName(ASN1ObjectIdentifier sigOid, String sigName) + { + if (oids.containsKey(sigOid)) + { + throw new IllegalStateException("object identifier already present in addSignatureName"); + } + + oids.put(sigOid, sigName); + } + static { // // reverse mappings // - oids.put(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSASSA-PSS"); - oids.put(EdECObjectIdentifiers.id_Ed25519, "ED25519"); - oids.put(EdECObjectIdentifiers.id_Ed448, "ED448"); - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - oids.put(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE128, "SHAKE128WITHRSAPSS"); - oids.put(CMSObjectIdentifiers.id_RSASSA_PSS_SHAKE256, "SHAKE256WITHRSAPSS"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); - oids.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "GOST3411-2012-256WITHECGOST3410-2012-256"); - oids.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "GOST3411-2012-512WITHECGOST3410-2012-512"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA1, "SHA1WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA224, "SHA224WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA256, "SHA256WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA384, "SHA384WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA512, "SHA512WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA3_224, "SHA3-224WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA3_256, "SHA3-256WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA3_384, "SHA3-384WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_SHA3_512, "SHA3-512WITHPLAIN-ECDSA"); - oids.put(BSIObjectIdentifiers.ecdsa_plain_RIPEMD160, "RIPEMD160WITHPLAIN-ECDSA"); - oids.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1WITHCVC-ECDSA"); - oids.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224WITHCVC-ECDSA"); - oids.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256WITHCVC-ECDSA"); - oids.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384WITHCVC-ECDSA"); - oids.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512WITHCVC-ECDSA"); - oids.put(IsaraObjectIdentifiers.id_alg_xmss, "XMSS"); - oids.put(IsaraObjectIdentifiers.id_alg_xmssmt, "XMSSMT"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - oids.put(CMSObjectIdentifiers.id_ecdsa_with_shake128, "SHAKE128WITHECDSA"); - oids.put(CMSObjectIdentifiers.id_ecdsa_with_shake256, "SHAKE256WITHECDSA"); - oids.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); - oids.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); + addSignatureName(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSASSA-PSS"); + addSignatureName(EdECObjectIdentifiers.id_Ed25519, "ED25519"); + addSignatureName(EdECObjectIdentifiers.id_Ed448, "ED448"); + addSignatureName(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); + addSignatureName(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); + addSignatureName(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); + addSignatureName(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); + addSignatureName(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); + addSignatureName(X509ObjectIdentifiers.id_rsassa_pss_shake128, "SHAKE128WITHRSAPSS"); + addSignatureName(X509ObjectIdentifiers.id_rsassa_pss_shake256, "SHAKE256WITHRSAPSS"); + addSignatureName(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); + addSignatureName(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); + addSignatureName(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "GOST3411-2012-256WITHECGOST3410-2012-256"); + addSignatureName(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "GOST3411-2012-512WITHECGOST3410-2012-512"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA1, "SHA1WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA224, "SHA224WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA256, "SHA256WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA384, "SHA384WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA512, "SHA512WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA3_224, "SHA3-224WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA3_256, "SHA3-256WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA3_384, "SHA3-384WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_SHA3_512, "SHA3-512WITHPLAIN-ECDSA"); + addSignatureName(BSIObjectIdentifiers.ecdsa_plain_RIPEMD160, "RIPEMD160WITHPLAIN-ECDSA"); + addSignatureName(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1WITHCVC-ECDSA"); + addSignatureName(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224WITHCVC-ECDSA"); + addSignatureName(EACObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256WITHCVC-ECDSA"); + addSignatureName(EACObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384WITHCVC-ECDSA"); + addSignatureName(EACObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512WITHCVC-ECDSA"); + addSignatureName(IsaraObjectIdentifiers.id_alg_xmss, "XMSS"); + addSignatureName(IsaraObjectIdentifiers.id_alg_xmssmt, "XMSSMT"); + addSignatureName(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); + addSignatureName(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); + addSignatureName(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); + addSignatureName(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); + addSignatureName(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); + addSignatureName(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); + addSignatureName(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); + addSignatureName(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); + addSignatureName(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); + addSignatureName(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); + addSignatureName(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); + addSignatureName(X509ObjectIdentifiers.id_ecdsa_with_shake128, "SHAKE128WITHECDSA"); + addSignatureName(X509ObjectIdentifiers.id_ecdsa_with_shake256, "SHAKE256WITHECDSA"); + addSignatureName(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); + addSignatureName(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); + addSignatureName(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); + addSignatureName(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); + + addSignatureName(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); + + addSignatureName(NISTObjectIdentifiers.id_ml_dsa_44, "ML-DSA-44"); + addSignatureName(NISTObjectIdentifiers.id_ml_dsa_65, "ML-DSA-65"); + addSignatureName(NISTObjectIdentifiers.id_ml_dsa_87, "ML-DSA-87"); + + addSignatureName(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, "ML-DSA-44-WITH-SHA512"); + addSignatureName(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, "ML-DSA-65-WITH-SHA512"); + addSignatureName(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, "ML-DSA-87-WITH-SHA512"); + + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_sha2_128s, "SLH-DSA-SHA2-128S"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_sha2_128f, "SLH-DSA-SHA2-128F"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_sha2_192s, "SLH-DSA-SHA2-192S"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_sha2_192f, "SLH-DSA-SHA2-192F"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_sha2_256s, "SLH-DSA-SHA2-256S"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_sha2_256f, "SLH-DSA-SHA2-256F"); + + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_shake_128s, "SLH-DSA-SHAKE-128S"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_shake_128f, "SLH-DSA-SHAKE-128F"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_shake_192s, "SLH-DSA-SHAKE-192S"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_shake_192f, "SLH-DSA-SHAKE-192F"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_shake_256s, "SLH-DSA-SHAKE-256S"); + addSignatureName(NISTObjectIdentifiers.id_slh_dsa_shake_256f, "SLH-DSA-SHAKE-256F"); + + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, "SLH-DSA-SHA2-128S-WITH-SHA256"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, "SLH-DSA-SHA2-128F-WITH-SHA256"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, "SLH-DSA-SHA2-192S-WITH-SHA512"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, "SLH-DSA-SHA2-192F-WITH-SHA512"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, "SLH-DSA-SHA2-256S-WITH-SHA512"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, "SLH-DSA-SHA2-256F-WITH-SHA512"); + + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, "SLH-DSA-SHAKE-128S-WITH-SHAKE128"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, "SLH-DSA-SHAKE-128F-WITH-SHAKE128"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, "SLH-DSA-SHAKE-192S-WITH-SHAKE256"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, "SLH-DSA-SHAKE-192F-WITH-SHAKE256"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, "SLH-DSA-SHAKE-256S-WITH-SHAKE256"); + addSignatureName(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, "SLH-DSA-SHAKE-256F-WITH-SHAKE256"); digests.put(OIWObjectIdentifiers.idSHA1, "SHA1"); digests.put(NISTObjectIdentifiers.id_sha224, "SHA224"); digests.put(NISTObjectIdentifiers.id_sha256, "SHA256"); digests.put(NISTObjectIdentifiers.id_sha384, "SHA384"); digests.put(NISTObjectIdentifiers.id_sha512, "SHA512"); + digests.put(NISTObjectIdentifiers.id_shake128, "SHAKE128"); + digests.put(NISTObjectIdentifiers.id_shake256, "SHAKE256"); digests.put(NISTObjectIdentifiers.id_sha3_224, "SHA3-224"); digests.put(NISTObjectIdentifiers.id_sha3_256, "SHA3-256"); digests.put(NISTObjectIdentifiers.id_sha3_384, "SHA3-384"); diff --git a/pkix/src/main/java/org/bouncycastle/operator/ExtendedContentSigner.java b/pkix/src/main/java/org/bouncycastle/operator/ExtendedContentSigner.java new file mode 100644 index 0000000000..115e056c37 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/ExtendedContentSigner.java @@ -0,0 +1,18 @@ +package org.bouncycastle.operator; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; + +/** + * A Content Signer which also provides details of the digest algorithm used internally. + */ +public interface ExtendedContentSigner + extends ContentSigner +{ + /** + * Return the algorithm identifier describing the digest algorithm used by + * this signature algorithm and parameters this signer generates. + * + * @return algorithm oid and parameters, null if unknown. + */ + AlgorithmIdentifier getDigestAlgorithmIdentifier(); +} diff --git a/pkix/src/main/java/org/bouncycastle/operator/KemEncapsulationLengthProvider.java b/pkix/src/main/java/org/bouncycastle/operator/KemEncapsulationLengthProvider.java new file mode 100644 index 0000000000..0d7df26d66 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/KemEncapsulationLengthProvider.java @@ -0,0 +1,8 @@ +package org.bouncycastle.operator; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; + +public interface KemEncapsulationLengthProvider +{ + int getEncapsulationLength(AlgorithmIdentifier kemAlgorithm); +} diff --git a/pkix/src/main/java/org/bouncycastle/operator/NoSignatureContentSigner.java b/pkix/src/main/java/org/bouncycastle/operator/NoSignatureContentSigner.java new file mode 100644 index 0000000000..95916074f5 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/NoSignatureContentSigner.java @@ -0,0 +1,48 @@ +package org.bouncycastle.operator; + +import java.io.IOException; +import java.io.OutputStream; + +import org.bouncycastle.asn1.DERNull; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; + +/** + * ContentSigner for "Unsigned X.509 Certificates" + */ +public class NoSignatureContentSigner + implements ContentSigner +{ + @Override + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return new AlgorithmIdentifier(X509ObjectIdentifiers.id_alg_noSignature, DERNull.INSTANCE); + } + + @Override + public OutputStream getOutputStream() + { + return new OutputStream() + { + @Override + public void write(byte[] buf, int off, int len) + throws IOException + { + // do nothing + } + + @Override + public void write(int i) + throws IOException + { + // do nothing + } + }; + } + + @Override + public byte[] getSignature() + { + return new byte[0]; + } +} diff --git a/pkix/src/main/java/org/bouncycastle/operator/bc/BcHssLmsContentSignerBuilder.java b/pkix/src/main/java/org/bouncycastle/operator/bc/BcHssLmsContentSignerBuilder.java new file mode 100644 index 0000000000..ac31c39883 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/bc/BcHssLmsContentSignerBuilder.java @@ -0,0 +1,106 @@ +package org.bouncycastle.operator.bc; + +import java.io.ByteArrayOutputStream; + +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoException; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.pqc.crypto.MessageSigner; +import org.bouncycastle.pqc.crypto.lms.HSSPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.lms.HSSPublicKeyParameters; +import org.bouncycastle.pqc.crypto.lms.HSSSigner; +import org.bouncycastle.pqc.crypto.lms.LMSPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.lms.LMSPublicKeyParameters; +import org.bouncycastle.pqc.crypto.lms.LMSSigner; + +/** + * Builder for creating content signers that use the HSS/LMS Hash-Based Signature Algorithm. + * + * Reference: Use of the HSS/LMS Hash-Based Signature Algorithm in the Cryptographic Message Syntax (CMS) + * RFC 9708. + */ +public class BcHssLmsContentSignerBuilder + extends BcContentSignerBuilder +{ + private static final AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig); + + public BcHssLmsContentSignerBuilder() + { + super(sigAlgId, null); + } + + protected Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId) + throws OperatorCreationException + { + return new HssSigner(); + } + + static class HssSigner + implements Signer + { + private MessageSigner signer; + private final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + public HssSigner() + { + } + + @Override + public void init(boolean forSigning, CipherParameters param) + { + if (param instanceof HSSPublicKeyParameters || param instanceof HSSPrivateKeyParameters) + { + signer = new HSSSigner(); + } + else if (param instanceof LMSPublicKeyParameters || param instanceof LMSPrivateKeyParameters) + { + signer = new LMSSigner(); + } + else + { + throw new IllegalArgumentException("Incorrect Key Parameters"); + } + + signer.init(forSigning, param); + } + + @Override + public void update(byte b) + { + stream.write(b); + } + + @Override + public void update(byte[] in, int off, int len) + { + stream.write(in, off, len); + } + + @Override + public byte[] generateSignature() + throws CryptoException, DataLengthException + { + byte[] msg = stream.toByteArray(); + stream.reset(); + return signer.generateSignature(msg); + } + + @Override + public boolean verifySignature(byte[] signature) + { + byte[] msg = stream.toByteArray(); + stream.reset(); + return signer.verifySignature(msg, signature); + } + + @Override + public void reset() + { + stream.reset(); + } + } +} diff --git a/pkix/src/main/java/org/bouncycastle/operator/bc/BcHssLmsContentVerifierProviderBuilder.java b/pkix/src/main/java/org/bouncycastle/operator/bc/BcHssLmsContentVerifierProviderBuilder.java new file mode 100644 index 0000000000..e552ffa6d8 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/bc/BcHssLmsContentVerifierProviderBuilder.java @@ -0,0 +1,37 @@ +package org.bouncycastle.operator.bc; + +import java.io.IOException; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.crypto.Signer; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; + +/** + * Builder for creating content verifier providers that support the HSS/LMS Hash-Based Signature Algorithm. + * + * Reference: Use of the HSS/LMS Hash-Based Signature Algorithm in the Cryptographic Message Syntax (CMS) + * RFC 9708. + *

      + */ +public class BcHssLmsContentVerifierProviderBuilder + extends BcContentVerifierProviderBuilder +{ + public BcHssLmsContentVerifierProviderBuilder() + { + } + + protected Signer createSigner(AlgorithmIdentifier sigAlgId) + throws OperatorCreationException + { + return new BcHssLmsContentSignerBuilder.HssSigner(); + } + + protected AsymmetricKeyParameter extractKeyParameters(SubjectPublicKeyInfo publicKeyInfo) + throws IOException + { + return PublicKeyFactory.createKey(publicKeyInfo); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/operator/bc/package-info.java b/pkix/src/main/java/org/bouncycastle/operator/bc/package-info.java new file mode 100644 index 0000000000..ecdc9f92fe --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/bc/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic operator implementations for doing encryption, signing, and digest operations using the BC lightweight API. + */ +package org.bouncycastle.operator.bc; diff --git a/pkix/src/main/java/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java b/pkix/src/main/java/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java index 7d8b24c35a..3e0b121c22 100644 --- a/pkix/src/main/java/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java @@ -5,6 +5,7 @@ import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.Provider; +import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; @@ -27,6 +28,7 @@ import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.jcajce.CompositePrivateKey; import org.bouncycastle.jcajce.io.OutputStreamFactory; import org.bouncycastle.jcajce.spec.CompositeAlgorithmSpec; @@ -37,24 +39,36 @@ import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; +import org.bouncycastle.operator.ExtendedContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.RuntimeOperatorException; import org.bouncycastle.operator.SignatureAlgorithmIdentifierFinder; +import org.bouncycastle.pqc.crypto.lms.LMSigParameters; +import org.bouncycastle.util.Pack; import org.bouncycastle.util.Strings; import org.bouncycastle.util.io.TeeOutputStream; +/** + * General builder class for ContentSigner operators based on the JCA. + */ public class JcaContentSignerBuilder { private static final Set isAlgIdFromPrivate = new HashSet(); + private static final DefaultSignatureAlgorithmIdentifierFinder SIGNATURE_ALGORITHM_IDENTIFIER_FINDER = new DefaultSignatureAlgorithmIdentifierFinder(); static { isAlgIdFromPrivate.add("DILITHIUM"); isAlgIdFromPrivate.add("SPHINCS+"); isAlgIdFromPrivate.add("SPHINCSPlus"); + isAlgIdFromPrivate.add("ML-DSA"); + isAlgIdFromPrivate.add("SLH-DSA"); + isAlgIdFromPrivate.add("HASH-ML-DSA"); + isAlgIdFromPrivate.add("HASH-SLH-DSA"); } private final String signatureAlgorithm; + private final AlgorithmIdentifier signatureDigestAlgorithm; private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); private SecureRandom random; @@ -62,15 +76,82 @@ public class JcaContentSignerBuilder private AlgorithmIdentifier sigAlgId; private AlgorithmParameterSpec sigAlgSpec; + /** + * Construct a basic content signer where the signature algorithm name + * tells us all we need to know. + * + * @param signatureAlgorithm the signature algorithm we perform. + */ public JcaContentSignerBuilder(String signatureAlgorithm) { - this.signatureAlgorithm = signatureAlgorithm; + this(signatureAlgorithm, (AlgorithmIdentifier)null); } - public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmParameterSpec sigParamSpec) + // + // at the moment LMS is the only algorithm like this, we can wing it with other public keys. + // + private static AlgorithmIdentifier getSigDigAlgId(PublicKey publicKey) + { + byte[] encoded = publicKey.getEncoded(); + SubjectPublicKeyInfo subInfo = SubjectPublicKeyInfo.getInstance(encoded); + + if (subInfo.getAlgorithm().getAlgorithm().equals(PKCSObjectIdentifiers.id_alg_hss_lms_hashsig)) + { + byte[] keyData = subInfo.getPublicKeyData().getOctets(); + + int type = Pack.bigEndianToInt(keyData, 4); + LMSigParameters sigParams = LMSigParameters.getParametersForType(type); + + return new AlgorithmIdentifier(sigParams.getDigestOID()); + } + + return null; + } + + /** + * Constructor which calculates the digest algorithm used from the public key, if necessary. + *

      + * Some PKIX operations, such as CMS signing, require the digest algorithm used for in the + * signature. Some algorithms, such as LMS, use different digests with different parameter sets but the same OID + * is used to represent the signature. In this case we either need to be told what digest is associated + * with the parameter set, or we need the public key so we can work it out. + *

      + * + * @param signatureAlgorithm the signature algorithm we perform. + * @param verificationKey the public key associated with our private key. + */ + public JcaContentSignerBuilder(String signatureAlgorithm, PublicKey verificationKey) + { + this(signatureAlgorithm, getSigDigAlgId(verificationKey)); + } + + /** + * Constructor which includes the digest algorithm identifier used. + *

      + * Some PKIX operations, such as CMS signing, require the digest algorithm used for in the + * signature, this constructor allows the digest algorithm identifier to + * be explicitly specified. + *

      + * + * @param signatureAlgorithm the signature algorithm we perform. + * @param signatureDigestAlgorithmID the public key associated with our private key. + */ + public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmIdentifier signatureDigestAlgorithmID) { this.signatureAlgorithm = signatureAlgorithm; + this.signatureDigestAlgorithm = signatureDigestAlgorithmID; + } + + public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmParameterSpec sigParamSpec) + { + this(signatureAlgorithm, sigParamSpec, null); + } + public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmParameterSpec sigParamSpec, AlgorithmIdentifier signatureDigestAlgorithmID) + { + this.signatureAlgorithm = signatureAlgorithm; + this.signatureDigestAlgorithm = signatureDigestAlgorithmID; + if (sigParamSpec instanceof PSSParameterSpec) { PSSParameterSpec pssSpec = (PSSParameterSpec)sigParamSpec; @@ -128,17 +209,9 @@ public ContentSigner build(PrivateKey privateKey) { if (sigAlgSpec == null) { - if (isAlgIdFromPrivate.contains(Strings.toUpperCase(signatureAlgorithm))) - { - sigAlgId = PrivateKeyInfo.getInstance(privateKey.getEncoded()).getPrivateKeyAlgorithm(); - this.sigAlgSpec = null; - } - else - { - this.sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm); - this.sigAlgSpec = null; - } + this.sigAlgId = getSigAlgId(privateKey); } + final AlgorithmIdentifier signatureAlgId = sigAlgId; final Signature sig = helper.createSignature(sigAlgId); @@ -151,7 +224,7 @@ public ContentSigner build(PrivateKey privateKey) sig.initSign(privateKey); } - return new ContentSigner() + final ContentSigner contentSigner = new ContentSigner() { private OutputStream stream = OutputStreamFactory.createStream(sig); @@ -177,6 +250,39 @@ public byte[] getSignature() } } }; + + if (signatureDigestAlgorithm != null) + { + return new ExtendedContentSigner() + { + private final AlgorithmIdentifier digestAlgorithm = signatureDigestAlgorithm; + private final ContentSigner signer = contentSigner; + + public AlgorithmIdentifier getDigestAlgorithmIdentifier() + { + return digestAlgorithm; + } + + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return signer.getAlgorithmIdentifier(); + } + + public OutputStream getOutputStream() + { + return signer.getOutputStream(); + } + + public byte[] getSignature() + { + return signer.getSignature(); + } + }; + } + else + { + return contentSigner; + } } catch (GeneralSecurityException e) { @@ -184,6 +290,23 @@ public byte[] getSignature() } } + private AlgorithmIdentifier getSigAlgId(PrivateKey privateKey) + { + if (isAlgIdFromPrivate.contains(Strings.toUpperCase(signatureAlgorithm))) + { + AlgorithmIdentifier sigAlgId = SIGNATURE_ALGORITHM_IDENTIFIER_FINDER.find(privateKey.getAlgorithm()); + if (sigAlgId == null) + { + return PrivateKeyInfo.getInstance(privateKey.getEncoded()).getPrivateKeyAlgorithm(); + } + return sigAlgId; + } + else + { + return SIGNATURE_ALGORITHM_IDENTIFIER_FINDER.find(signatureAlgorithm); + } + } + private ContentSigner buildComposite(CompositePrivateKey privateKey) throws OperatorCreationException { diff --git a/pkix/src/main/java/org/bouncycastle/operator/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/operator/jcajce/package-info.java new file mode 100644 index 0000000000..6db5cb807a --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/jcajce/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic operator implementations for doing encryption, signing, and digest operations using the JCA and the JCE. + */ +package org.bouncycastle.operator.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/operator/package-info.java b/pkix/src/main/java/org/bouncycastle/operator/package-info.java new file mode 100644 index 0000000000..b3d007b6b0 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/operator/package-info.java @@ -0,0 +1,4 @@ +/** + * Basic operator definitions for doing encryption, signing, and digest operations. + */ +package org.bouncycastle.operator; diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValue.java b/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValue.java index 58aec1dadd..dc296b93ff 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValue.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValue.java @@ -7,6 +7,7 @@ import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.DeltaCertificateDescriptor; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; @@ -27,6 +28,21 @@ public DeltaCertificateRequestAttributeValue(Attribute attribute) this(ASN1Sequence.getInstance(attribute.getAttributeValues()[0])); } + public static DeltaCertificateRequestAttributeValue getInstance(Object o) + { + if (o instanceof DeltaCertificateDescriptor) + { + return (DeltaCertificateRequestAttributeValue)o; + } + + if (o != null) + { + new DeltaCertificateRequestAttributeValue(ASN1Sequence.getInstance(o)); + } + + return null; + } + DeltaCertificateRequestAttributeValue(ASN1Sequence attrSeq) { this.attrSeq = attrSeq; @@ -56,11 +72,11 @@ public DeltaCertificateRequestAttributeValue(Attribute attribute) ASN1TaggedObject tagObj = ASN1TaggedObject.getInstance(attrSeq.getObjectAt(idx)); if (tagObj.getTagNo() == 1) { - ext = Extensions.getInstance(tagObj, false); + ext = Extensions.getInstance(tagObj, true); } else if (tagObj.getTagNo() == 2) { - sigAlg = AlgorithmIdentifier.getInstance(tagObj, false); + sigAlg = AlgorithmIdentifier.getInstance(tagObj, true); } else { diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValueBuilder.java b/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValueBuilder.java index 1c844f287a..3f07a4d6de 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValueBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/DeltaCertificateRequestAttributeValueBuilder.java @@ -42,12 +42,12 @@ public DeltaCertificateRequestAttributeValue build() if (subject != null) { - v.add(new DERTaggedObject(false, 0, subject)); + v.add(new DERTaggedObject(true, 0, subject)); } v.add(subjectPublicKey); if (signatureAlgorithm != null) { - v.add(new DERTaggedObject(false, 2, signatureAlgorithm)); + v.add(new DERTaggedObject(true, 2, signatureAlgorithm)); } diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/MacDataGenerator.java b/pkix/src/main/java/org/bouncycastle/pkcs/MacDataGenerator.java index 7b9daa8b81..5ef4fc0dea 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/MacDataGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/MacDataGenerator.java @@ -1,14 +1,16 @@ package org.bouncycastle.pkcs; -import java.io.IOException; + import java.io.OutputStream; import org.bouncycastle.asn1.pkcs.MacData; import org.bouncycastle.asn1.pkcs.PKCS12PBEParams; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DigestInfo; import org.bouncycastle.operator.MacCalculator; +import org.bouncycastle.util.Strings; class MacDataGenerator { @@ -42,8 +44,21 @@ public MacData build(char[] password, byte[] data) AlgorithmIdentifier algId = macCalculator.getAlgorithmIdentifier(); DigestInfo dInfo = new DigestInfo(builder.getDigestAlgorithmIdentifier(), macCalculator.getMac()); - PKCS12PBEParams params = PKCS12PBEParams.getInstance(algId.getParameters()); - - return new MacData(dInfo, params.getIV(), params.getIterations().intValue()); + byte[] salt; + int iterations; + + if (PKCSObjectIdentifiers.id_PBMAC1.equals(dInfo.getAlgorithmId().getAlgorithm())) + { + salt = Strings.toUTF8ByteArray("NOT USED".toCharArray()); + iterations = 1; + } + else + { + PKCS12PBEParams params = PKCS12PBEParams.getInstance(algId.getParameters()); + salt = params.getIV(); + iterations = params.getIterations().intValue(); + } + + return new MacData(dInfo, salt, iterations); } } diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/PKCS10CertificationRequest.java b/pkix/src/main/java/org/bouncycastle/pkcs/PKCS10CertificationRequest.java index 67ebd62469..ad470c89a8 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/PKCS10CertificationRequest.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/PKCS10CertificationRequest.java @@ -80,7 +80,7 @@ private static ASN1Encodable getSingleValue(Attribute at) } /** - * Create a PKCS10CertificationRequestHolder from an underlying ASN.1 structure. + * Create a PKCS10CertificationRequest from an underlying ASN.1 structure. * * @param certificationRequest the underlying ASN.1 structure representing a request. */ @@ -134,7 +134,7 @@ public PKCS10CertificationRequest(CertificationRequest certificationRequest) } /** - * Create a PKCS10CertificationRequestHolder from the passed in bytes. + * Create a PKCS10CertificationRequest from the passed in bytes. * * @param encoded BER/DER encoding of the CertificationRequest structure. * @throws IOException in the event of corrupted data, or an incorrect structure. diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/PKCS12PfxPdu.java b/pkix/src/main/java/org/bouncycastle/pkcs/PKCS12PfxPdu.java index 1e7096312e..12d5550080 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/PKCS12PfxPdu.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/PKCS12PfxPdu.java @@ -7,7 +7,9 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.pkcs.ContentInfo; import org.bouncycastle.asn1.pkcs.MacData; +import org.bouncycastle.asn1.pkcs.PBMAC1Params; import org.bouncycastle.asn1.pkcs.PKCS12PBEParams; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.Pfx; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.util.Arrays; @@ -107,8 +109,21 @@ public boolean isMacValid(PKCS12MacCalculatorBuilderProvider macCalcProviderBuil if (hasMac()) { MacData pfxmData = pfx.getMacData(); - MacDataGenerator mdGen = new MacDataGenerator(macCalcProviderBuilder.get(new AlgorithmIdentifier(pfxmData.getMac().getAlgorithmId().getAlgorithm(), new PKCS12PBEParams(pfxmData.getSalt(), pfxmData.getIterationCount().intValue())))); - + MacDataGenerator mdGen; + if (PKCSObjectIdentifiers.id_PBMAC1.equals(pfxmData.getMac().getAlgorithmId().getAlgorithm())) + { + PBMAC1Params pbmac1Params = PBMAC1Params.getInstance(pfxmData.getMac().getAlgorithmId().getParameters()); + if (pbmac1Params == null) + { + throw new PKCSException("If the DigestAlgorithmIdentifier is id-PBMAC1, then the parameters field must contain valid PBMAC1-params parameters."); + } + mdGen = new MacDataGenerator(macCalcProviderBuilder.get(new AlgorithmIdentifier(pfxmData.getMac().getAlgorithmId().getAlgorithm(), pbmac1Params))); + } + else + { + mdGen = new MacDataGenerator(macCalcProviderBuilder.get(new AlgorithmIdentifier(pfxmData.getMac().getAlgorithmId().getAlgorithm(), new PKCS12PBEParams(pfxmData.getSalt(), pfxmData.getIterationCount().intValue())))); + } + try { MacData mData = mdGen.build( diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/bc/BcPKCS12PBMac1CalculatorBuilder.java b/pkix/src/main/java/org/bouncycastle/pkcs/bc/BcPKCS12PBMac1CalculatorBuilder.java new file mode 100644 index 0000000000..bc3480cf46 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/pkcs/bc/BcPKCS12PBMac1CalculatorBuilder.java @@ -0,0 +1,47 @@ +package org.bouncycastle.pkcs.bc; + +import java.io.IOException; + +import org.bouncycastle.asn1.pkcs.PBKDF2Params; +import org.bouncycastle.asn1.pkcs.PBMAC1Params; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.operator.MacCalculator; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.pkcs.PKCS12MacCalculatorBuilder; + +public class BcPKCS12PBMac1CalculatorBuilder + implements PKCS12MacCalculatorBuilder +{ + private final PBMAC1Params pbmac1Params; + private PBKDF2Params pbkdf2Params = null; + + public BcPKCS12PBMac1CalculatorBuilder(PBMAC1Params pbeMacParams) throws IOException + { + this.pbmac1Params = pbeMacParams; + if (PKCSObjectIdentifiers.id_PBKDF2.equals(pbeMacParams.getKeyDerivationFunc().getAlgorithm())) + { + this.pbkdf2Params = PBKDF2Params.getInstance(pbeMacParams.getKeyDerivationFunc().getParameters()); + if (pbkdf2Params.getKeyLength() == null) + { + throw new IOException("Key length must be present when using PBMAC1."); + } + } + else + { + // TODO: add scrypt support. + throw new IllegalArgumentException("unrecognised PBKDF"); + } + } + + @Override + public AlgorithmIdentifier getDigestAlgorithmIdentifier() + { + return new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBMAC1, pbmac1Params); + } + + public MacCalculator build(final char[] password) throws OperatorCreationException + { + return PKCS12PBEUtils.createPBMac1Calculator(pbmac1Params, pbkdf2Params, password); + } +} diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/bc/BcPKCS12PBMac1CalculatorBuilderProvider.java b/pkix/src/main/java/org/bouncycastle/pkcs/bc/BcPKCS12PBMac1CalculatorBuilderProvider.java new file mode 100644 index 0000000000..fdbb5c76f0 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/pkcs/bc/BcPKCS12PBMac1CalculatorBuilderProvider.java @@ -0,0 +1,46 @@ +package org.bouncycastle.pkcs.bc; + +import org.bouncycastle.asn1.pkcs.PBMAC1Params; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.operator.MacCalculator; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.pkcs.PKCS12MacCalculatorBuilder; +import org.bouncycastle.pkcs.PKCS12MacCalculatorBuilderProvider; + +import java.io.IOException; + +public class BcPKCS12PBMac1CalculatorBuilderProvider + implements PKCS12MacCalculatorBuilderProvider +{ + public PKCS12MacCalculatorBuilder get(final AlgorithmIdentifier algorithmIdentifier) + { + return new PKCS12MacCalculatorBuilder() + { + public MacCalculator build(final char[] password) + throws OperatorCreationException + { + if (!PKCSObjectIdentifiers.id_PBMAC1.equals(algorithmIdentifier.getAlgorithm())) + { + throw new OperatorCreationException("protection algorithm not PB mac based"); + } + + BcPKCS12PBMac1CalculatorBuilder bldr; + try + { + bldr = new BcPKCS12PBMac1CalculatorBuilder(PBMAC1Params.getInstance(algorithmIdentifier.getParameters())); + } + catch (IOException e) + { + throw new OperatorCreationException("invalid parameters in protection algorithm: " + e.getMessage()); + } + return bldr.build(password); + } + + public AlgorithmIdentifier getDigestAlgorithmIdentifier() + { + return new AlgorithmIdentifier(algorithmIdentifier.getAlgorithm(), algorithmIdentifier.getParameters()); + } + }; + } +} diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/bc/PKCS12PBEUtils.java b/pkix/src/main/java/org/bouncycastle/pkcs/bc/PKCS12PBEUtils.java index d83c563764..9dfef14807 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/bc/PKCS12PBEUtils.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/bc/PKCS12PBEUtils.java @@ -7,15 +7,22 @@ import java.util.Set; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.pkcs.PBKDF2Params; +import org.bouncycastle.asn1.pkcs.PBMAC1Params; import org.bouncycastle.asn1.pkcs.PKCS12PBEParams; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.ExtendedDigest; +import org.bouncycastle.crypto.PBEParametersGenerator; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.RC2Engine; import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator; +import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; import org.bouncycastle.crypto.io.MacOutputStream; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; @@ -26,7 +33,9 @@ import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.operator.GenericKey; import org.bouncycastle.operator.MacCalculator; +import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Integers; +import org.bouncycastle.util.Strings; class PKCS12PBEUtils { @@ -127,6 +136,65 @@ public GenericKey getKey() }; } + static MacCalculator createPBMac1Calculator(final PBMAC1Params pbmac1Params, final PBKDF2Params pbkdf2Params, final char[] password) + { + final HMac hMac = new HMac(getPrf(pbmac1Params.getMessageAuthScheme().getAlgorithm())); + + PBEParametersGenerator generator = new PKCS5S2ParametersGenerator(getPrf(pbkdf2Params.getPrf().getAlgorithm())); + + generator.init( + Strings.toUTF8ByteArray(password), + pbkdf2Params.getSalt(), + BigIntegers.intValueExact(pbkdf2Params.getIterationCount())); + + CipherParameters key = generator.generateDerivedParameters(BigIntegers.intValueExact(pbkdf2Params.getKeyLength()) * 8); + + hMac.init(key); + + return new MacCalculator() + { + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBMAC1, pbmac1Params); + } + + public OutputStream getOutputStream() + { + return new MacOutputStream(hMac); + } + + public byte[] getMac() + { + byte[] res = new byte[hMac.getMacSize()]; + + hMac.doFinal(res, 0); + + return res; + } + + public GenericKey getKey() + { + return new GenericKey(getAlgorithmIdentifier(), Strings.toUTF8ByteArray(password)); + } + }; + } + + private static Digest getPrf(ASN1ObjectIdentifier prfId) + { + if (PKCSObjectIdentifiers.id_hmacWithSHA256.equals(prfId)) + { + return new SHA256Digest(); + } + else if (PKCSObjectIdentifiers.id_hmacWithSHA512.equals(prfId)) + { + return new SHA512Digest(); + } + else + { + throw new IllegalArgumentException("unknown prf id " + prfId); + } + } + static CipherParameters createCipherParameters(ASN1ObjectIdentifier algorithm, ExtendedDigest digest, int blockSize, PKCS12PBEParams pbeParams, char[] password) { PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest); diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/bc/package-info.java b/pkix/src/main/java/org/bouncycastle/pkcs/bc/package-info.java new file mode 100644 index 0000000000..626ad954e8 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/pkcs/bc/package-info.java @@ -0,0 +1,6 @@ +/** + * + * BC lightweight API extensions and operators for the PKCS#10 certification request package. + */ +package org.bouncycastle.pkcs.bc; diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/JcePBMac1CalculatorBuilder.java b/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/JcePBMac1CalculatorBuilder.java index 2869097e8d..18d47405cb 100644 --- a/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/JcePBMac1CalculatorBuilder.java +++ b/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/JcePBMac1CalculatorBuilder.java @@ -187,6 +187,7 @@ public MacCalculator build(final char[] password) salt = pbeParams.getSalt(); iterationCount = BigIntegers.intValueExact(pbeParams.getIterationCount()); keySize = BigIntegers.intValueExact(pbeParams.getKeyLength()) * 8; + prf = pbeParams.getPrf(); } SecretKeyFactory secFact = helper.createSecretKeyFactory("PBKDF2"); diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/package-info.java b/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/package-info.java new file mode 100644 index 0000000000..ae08d7919c --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/pkcs/jcajce/package-info.java @@ -0,0 +1,6 @@ +/** + * + * JCA extensions and operators for the PKCS#10 certification request package. + */ +package org.bouncycastle.pkcs.jcajce; diff --git a/pkix/src/main/java/org/bouncycastle/pkcs/package-info.java b/pkix/src/main/java/org/bouncycastle/pkcs/package-info.java new file mode 100644 index 0000000000..32639488d6 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/pkcs/package-info.java @@ -0,0 +1,6 @@ +/** + * + * Basic support package for handling and creating PKCS#10 certification requests, PKCS#8 encrypted keys and PKCS#12 keys stores. + */ +package org.bouncycastle.pkcs; diff --git a/pkix/src/main/java/org/bouncycastle/pkix/jcajce/PKIXCertPathReviewer.java b/pkix/src/main/java/org/bouncycastle/pkix/jcajce/PKIXCertPathReviewer.java index 891b2f4e84..2234ca031e 100644 --- a/pkix/src/main/java/org/bouncycastle/pkix/jcajce/PKIXCertPathReviewer.java +++ b/pkix/src/main/java/org/bouncycastle/pkix/jcajce/PKIXCertPathReviewer.java @@ -89,6 +89,8 @@ public class PKIXCertPathReviewer extends CertPathValidatorUtilities private static final String RESOURCE_NAME = "org.bouncycastle.pkix.CertPathReviewerMessages"; + private static final int NAME_CHECK_MAX = (1 << 10); + // input parameters protected CertPath certPath; @@ -498,9 +500,20 @@ private void checkNameConstraints() ErrorBundle msg = createErrorBundle("CertPathReviewer.subjAltNameExtError"); throw new CertPathReviewerException(msg,ae,certPath,index); } - + + /* + * TODO RFC3280CertPathUtilities (used in CertPath validation) has a block checking name + * constraints against subject's EmailAddress, which could be worth adding here too. + */ + if (altName != null) { + if (altName.size() > NAME_CHECK_MAX) + { + ErrorBundle msg = createErrorBundle("CertPathReviewer.subjAltNameExtError"); + throw new CertPathReviewerException(msg,certPath,index); + } + for (int j = 0; j < altName.size(); j++) { GeneralName name = GeneralName.getInstance(altName.getObjectAt(j)); @@ -516,87 +529,6 @@ private void checkNameConstraints() new Object[] {new UntrustedInput(name)}); throw new CertPathReviewerException(msg,cpve,certPath,index); } -// switch(o.getTagNo()) TODO - move resources to PKIXNameConstraints -// { -// case 1: -// String email = ASN1IA5String.getInstance(o, true).getString(); -// -// try -// { -// checkPermittedEmail(permittedSubtreesEmail, email); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = createErrorBundle("CertPathReviewer.notPermittedEmail", -// new Object[] {new UntrustedInput(email)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// try -// { -// checkExcludedEmail(excludedSubtreesEmail, email); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = createErrorBundle("CertPathReviewer.excludedEmail", -// new Object[] {new UntrustedInput(email)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// break; -// case 4: -// ASN1Sequence altDN = ASN1Sequence.getInstance(o, true); -// -// try -// { -// checkPermittedDN(permittedSubtreesDN, altDN); -// } -// catch (CertPathValidatorException cpve) -// { -// X509Name altDNName = new X509Name(altDN); -// ErrorBundle msg = createErrorBundle("CertPathReviewer.notPermittedDN", -// new Object[] {new UntrustedInput(altDNName)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// try -// { -// checkExcludedDN(excludedSubtreesDN, altDN); -// } -// catch (CertPathValidatorException cpve) -// { -// X509Name altDNName = new X509Name(altDN); -// ErrorBundle msg = createErrorBundle("CertPathReviewer.excludedDN", -// new Object[] {new UntrustedInput(altDNName)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// break; -// case 7: -// byte[] ip = ASN1OctetString.getInstance(o, true).getOctets(); -// -// try -// { -// checkPermittedIP(permittedSubtreesIP, ip); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = createErrorBundle("CertPathReviewer.notPermittedIP", -// new Object[] {IPtoString(ip)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// try -// { -// checkExcludedIP(excludedSubtreesIP, ip); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = createErrorBundle("CertPathReviewer.excludedIP", -// new Object[] {IPtoString(ip)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// } } } } diff --git a/pkix/src/main/java/org/bouncycastle/pkix/jcajce/RFC3280CertPathUtilities.java b/pkix/src/main/java/org/bouncycastle/pkix/jcajce/RFC3280CertPathUtilities.java index 83b8ddc4d7..7977ecad26 100644 --- a/pkix/src/main/java/org/bouncycastle/pkix/jcajce/RFC3280CertPathUtilities.java +++ b/pkix/src/main/java/org/bouncycastle/pkix/jcajce/RFC3280CertPathUtilities.java @@ -40,6 +40,7 @@ import org.bouncycastle.jcajce.PKIXExtendedParameters; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Properties; class RFC3280CertPathUtilities { @@ -506,14 +507,29 @@ protected static Set processCRLF( X509Certificate signCert = (X509Certificate)validCerts.get(i); boolean[] keyUsage = signCert.getKeyUsage(); - if (keyUsage != null && (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN])) + if (keyUsage == null) { - lastException = new AnnotatedException( - "Issuer certificate key usage extension does not permit CRL signing."); + if (Properties.isOverrideSet("org.bouncycastle.x509.allow_ca_without_crl_sign", true)) + { + checkKeys.add(validKeys.get(i)); + } + else + { + lastException = new AnnotatedException( + "No key usage extension on issuer certificate."); + } } else { - checkKeys.add(validKeys.get(i)); + if (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN]) + { + lastException = new AnnotatedException( + "Issuer certificate key usage extension does not permit CRL signing."); + } + else + { + checkKeys.add(validKeys.get(i)); + } } } diff --git a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequest.java b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequest.java index 4152a02fb6..8760188d13 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequest.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequest.java @@ -1,6 +1,5 @@ package org.bouncycastle.tsp; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; @@ -15,6 +14,7 @@ import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.cmp.PKIFailureInfo; +import org.bouncycastle.asn1.tsp.MessageImprint; import org.bouncycastle.asn1.tsp.TimeStampReq; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Extension; @@ -27,6 +27,40 @@ public class TimeStampRequest { private static Set EMPTY_SET = Collections.unmodifiableSet(new HashSet()); + private static TimeStampReq parseTimeStampReq(byte[] encoding) + throws IOException + { + try + { + return TimeStampReq.getInstance(encoding); + } + catch (ClassCastException e) + { + throw new IOException("malformed request: " + e); + } + catch (IllegalArgumentException e) + { + throw new IOException("malformed request: " + e); + } + } + + private static TimeStampReq parseTimeStampReq(InputStream in) + throws IOException + { + try + { + return TimeStampReq.getInstance(new ASN1InputStream(in).readObject()); + } + catch (ClassCastException e) + { + throw new IOException("malformed request: " + e); + } + catch (IllegalArgumentException e) + { + throw new IOException("malformed request: " + e); + } + } + private TimeStampReq req; private Extensions extensions; @@ -45,7 +79,7 @@ public TimeStampRequest(TimeStampReq req) public TimeStampRequest(byte[] req) throws IOException { - this(new ByteArrayInputStream(req)); + this(parseTimeStampReq(req)); } /** @@ -57,24 +91,12 @@ public TimeStampRequest(byte[] req) public TimeStampRequest(InputStream in) throws IOException { - this(loadRequest(in)); + this(parseTimeStampReq(in)); } - private static TimeStampReq loadRequest(InputStream in) - throws IOException + public TimeStampReq toASN1Structure() { - try - { - return TimeStampReq.getInstance(new ASN1InputStream(in).readObject()); - } - catch (ClassCastException e) - { - throw new IOException("malformed request: " + e); - } - catch (IllegalArgumentException e) - { - throw new IOException("malformed request: " + e); - } + return req; } public int getVersion() @@ -82,6 +104,11 @@ public int getVersion() return req.getVersion().intValueExact(); } + public MessageImprint getMessageImprint() + { + return req.getMessageImprint(); + } + public ASN1ObjectIdentifier getMessageImprintAlgOID() { return req.getMessageImprint().getHashAlgorithm().getAlgorithm(); @@ -152,6 +179,11 @@ public void validate( policies = convert(policies); extensions = convert(extensions); + if (algorithms == null) + { + throw new TSPValidationException("no algorithms associated with request", PKIFailureInfo.badAlg); + } + if (!algorithms.contains(this.getMessageImprintAlgOID())) { throw new TSPValidationException("request contains unknown algorithm", PKIFailureInfo.badAlg); @@ -167,7 +199,7 @@ public void validate( Enumeration en = this.getExtensions().oids(); while(en.hasMoreElements()) { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)en.nextElement(); + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)en.nextElement(); if (!extensions.contains(oid)) { throw new TSPValidationException("request contains unknown extension", PKIFailureInfo.unacceptedExtension); @@ -177,7 +209,7 @@ public void validate( int digestLength = TSPUtil.getDigestLength(this.getMessageImprintAlgOID().getId()); - if (digestLength != this.getMessageImprintDigest().length) + if (digestLength != this.getMessageImprint().getHashedMessageLength()) { throw new TSPValidationException("imprint digest the wrong length", PKIFailureInfo.badDataFormat); } diff --git a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequestGenerator.java b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequestGenerator.java index 0c68c58ac1..07203e8629 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequestGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampRequestGenerator.java @@ -13,43 +13,60 @@ import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.ExtensionsGenerator; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; +import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; /** * Generator for RFC 3161 Time Stamp Request objects. */ public class TimeStampRequestGenerator { - private static final DefaultDigestAlgorithmIdentifierFinder dgstAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); + private static final DefaultDigestAlgorithmIdentifierFinder DEFAULT_DIGEST_ALG_FINDER = + new DefaultDigestAlgorithmIdentifierFinder(); - private ASN1ObjectIdentifier reqPolicy; + private final ExtensionsGenerator extGenerator = new ExtensionsGenerator(); + + private final DigestAlgorithmIdentifierFinder digestAlgFinder; + private ASN1ObjectIdentifier reqPolicy; private ASN1Boolean certReq; - private ExtensionsGenerator extGenerator = new ExtensionsGenerator(); public TimeStampRequestGenerator() { + this(DEFAULT_DIGEST_ALG_FINDER); + } + + public TimeStampRequestGenerator(DigestAlgorithmIdentifierFinder digestAlgFinder) + { + if (digestAlgFinder == null) + { + throw new NullPointerException("'digestAlgFinder' cannot be null"); + } + + this.digestAlgFinder = digestAlgFinder; } + public void setReqPolicy(ASN1ObjectIdentifier reqPolicy) + { + this.reqPolicy = reqPolicy; + } + /** * @deprecated use method taking ASN1ObjectIdentifier * @param reqPolicy */ - public void setReqPolicy( - String reqPolicy) + public void setReqPolicy(String reqPolicy) { - this.reqPolicy= new ASN1ObjectIdentifier(reqPolicy); + setReqPolicy(new ASN1ObjectIdentifier(reqPolicy)); } - public void setReqPolicy( - ASN1ObjectIdentifier reqPolicy) + public void setCertReq(ASN1Boolean certReq) { - this.reqPolicy= reqPolicy; + this.certReq = certReq; } - public void setCertReq( - boolean certReq) + public void setCertReq(boolean certReq) { - this.certReq = ASN1Boolean.getInstance(certReq); + setCertReq(ASN1Boolean.getInstance(certReq)); } /** @@ -57,13 +74,9 @@ public void setCertReq( * @throws IOException * @deprecated use method taking ASN1ObjectIdentifier */ - public void addExtension( - String OID, - boolean critical, - ASN1Encodable value) - throws IOException + public void addExtension(String OID, boolean critical, ASN1Encodable value) throws IOException { - this.addExtension(OID, critical, value.toASN1Primitive().getEncoded()); + addExtension(new ASN1ObjectIdentifier(OID), critical, value); } /** @@ -72,23 +85,16 @@ public void addExtension( * with the extension. * @deprecated use method taking ASN1ObjectIdentifier */ - public void addExtension( - String OID, - boolean critical, - byte[] value) + public void addExtension(String OID, boolean critical, byte[] value) { - extGenerator.addExtension(new ASN1ObjectIdentifier(OID), critical, value); + addExtension(new ASN1ObjectIdentifier(OID), critical, value); } /** * add a given extension field for the standard extensions tag (tag 3) * @throws TSPIOException */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean isCritical, - ASN1Encodable value) - throws TSPIOException + public void addExtension(ASN1ObjectIdentifier oid, boolean isCritical, ASN1Encodable value) throws TSPIOException { TSPUtil.addExtension(extGenerator, oid, isCritical, value); } @@ -98,106 +104,58 @@ public void addExtension( * The value parameter becomes the contents of the octet string associated * with the extension. */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean isCritical, - byte[] value) + public void addExtension(ASN1ObjectIdentifier oid, boolean isCritical, byte[] value) { extGenerator.addExtension(oid, isCritical, value); } /** - * @deprecated use method taking ANS1ObjectIdentifier + * @deprecated use method taking ANS1ObjectIdentifier or AlgorithmIdentifier */ - public TimeStampRequest generate( - String digestAlgorithm, - byte[] digest) + public TimeStampRequest generate(String digestAlgorithm, byte[] digest) { - return this.generate(digestAlgorithm, digest, null); + return generate(digestAlgorithm, digest, null); } /** - * @deprecated use method taking ANS1ObjectIdentifier + * @deprecated use method taking ANS1ObjectIdentifier or AlgorithmIdentifier */ - public TimeStampRequest generate( - String digestAlgorithmOID, - byte[] digest, - BigInteger nonce) + public TimeStampRequest generate(String digestAlgorithmOID, byte[] digest, BigInteger nonce) { if (digestAlgorithmOID == null) { - throw new IllegalArgumentException("No digest algorithm specified"); + throw new NullPointerException("'digestAlgorithmOID' cannot be null"); } - ASN1ObjectIdentifier digestAlgOID = new ASN1ObjectIdentifier(digestAlgorithmOID); - - AlgorithmIdentifier algID = dgstAlgFinder.find(digestAlgOID); - MessageImprint messageImprint = new MessageImprint(algID, digest); - - Extensions ext = null; - - if (!extGenerator.isEmpty()) - { - ext = extGenerator.generate(); - } - - if (nonce != null) - { - return new TimeStampRequest(new TimeStampReq(messageImprint, - reqPolicy, new ASN1Integer(nonce), certReq, ext)); - } - else - { - return new TimeStampRequest(new TimeStampReq(messageImprint, - reqPolicy, null, certReq, ext)); - } + return generate(new ASN1ObjectIdentifier(digestAlgorithmOID), digest, nonce); } public TimeStampRequest generate(ASN1ObjectIdentifier digestAlgorithm, byte[] digest) { - return generate(dgstAlgFinder.find(digestAlgorithm), digest); + return generate(digestAlgorithm, digest, null); } public TimeStampRequest generate(ASN1ObjectIdentifier digestAlgorithm, byte[] digest, BigInteger nonce) { - return generate(dgstAlgFinder.find(digestAlgorithm), digest, nonce); + return generate(digestAlgFinder.find(digestAlgorithm), digest, nonce); } - public TimeStampRequest generate( - AlgorithmIdentifier digestAlgorithmID, - byte[] digest) + public TimeStampRequest generate(AlgorithmIdentifier digestAlgorithmID, byte[] digest) { return generate(digestAlgorithmID, digest, null); } - public TimeStampRequest generate( - AlgorithmIdentifier digestAlgorithmID, - byte[] digest, - BigInteger nonce) + public TimeStampRequest generate(AlgorithmIdentifier digestAlgorithmID, byte[] digest, BigInteger nonce) { if (digestAlgorithmID == null) { - throw new IllegalArgumentException("digest algorithm not specified"); + throw new NullPointerException("'digestAlgorithmID' cannot be null"); } MessageImprint messageImprint = new MessageImprint(digestAlgorithmID, digest); + ASN1Integer reqNonce = nonce == null ? null : new ASN1Integer(nonce); + Extensions ext = extGenerator.isEmpty() ? null : extGenerator.generate(); - Extensions ext = null; - - if (!extGenerator.isEmpty()) - { - ext = extGenerator.generate(); - } - - if (nonce != null) - { - return new TimeStampRequest(new TimeStampReq(messageImprint, - reqPolicy, new ASN1Integer(nonce), certReq, ext)); - } - else - { - return new TimeStampRequest(new TimeStampReq(messageImprint, - reqPolicy, null, certReq, ext)); - } + return new TimeStampRequest(new TimeStampReq(messageImprint, reqPolicy, reqNonce, certReq, ext)); } } diff --git a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampResponse.java b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampResponse.java index 9d399b00a1..b5e8c3258f 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampResponse.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampResponse.java @@ -1,12 +1,11 @@ package org.bouncycastle.tsp; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.DLSequence; import org.bouncycastle.asn1.cmp.PKIFailureInfo; import org.bouncycastle.asn1.cmp.PKIFreeText; @@ -22,18 +21,50 @@ */ public class TimeStampResponse { - TimeStampResp resp; - TimeStampToken timeStampToken; + private static TimeStampResp parseTimeStampResp(byte[] encoding) + throws IOException, TSPException + { + try + { + return TimeStampResp.getInstance(encoding); + } + catch (IllegalArgumentException e) + { + throw new TSPException("malformed timestamp response: " + e, e); + } + catch (ClassCastException e) + { + throw new TSPException("malformed timestamp response: " + e, e); + } + } + + private static TimeStampResp parseTimeStampResp(InputStream in) + throws IOException, TSPException + { + try + { + return TimeStampResp.getInstance(new ASN1InputStream(in).readObject()); + } + catch (IllegalArgumentException e) + { + throw new TSPException("malformed timestamp response: " + e, e); + } + catch (ClassCastException e) + { + throw new TSPException("malformed timestamp response: " + e, e); + } + } + + private final TimeStampResp resp; + private final TimeStampToken timeStampToken; public TimeStampResponse(TimeStampResp resp) throws TSPException, IOException { this.resp = resp; - - if (resp.getTimeStampToken() != null) - { - timeStampToken = new TimeStampToken(resp.getTimeStampToken()); - } + + ContentInfo timeStampToken = resp.getTimeStampToken(); + this.timeStampToken = timeStampToken == null ? null : new TimeStampToken(timeStampToken); } /** @@ -46,7 +77,7 @@ public TimeStampResponse(TimeStampResp resp) public TimeStampResponse(byte[] resp) throws TSPException, IOException { - this(new ByteArrayInputStream(resp)); + this(parseTimeStampResp(resp)); } /** @@ -59,7 +90,7 @@ public TimeStampResponse(byte[] resp) public TimeStampResponse(InputStream in) throws TSPException, IOException { - this(readTimeStampResp(in)); + this(parseTimeStampResp(in)); } TimeStampResponse(DLSequence dlSequence) @@ -80,45 +111,25 @@ public TimeStampResponse(InputStream in) } } - private static TimeStampResp readTimeStampResp( - InputStream in) - throws IOException, TSPException - { - try - { - return TimeStampResp.getInstance(new ASN1InputStream(in).readObject()); - } - catch (IllegalArgumentException e) - { - throw new TSPException("malformed timestamp response: " + e, e); - } - catch (ClassCastException e) - { - throw new TSPException("malformed timestamp response: " + e, e); - } - } - public int getStatus() { - return resp.getStatus().getStatus().intValue(); + return resp.getStatus().getStatusObject().intValueExact(); } public String getStatusString() { - if (resp.getStatus().getStatusString() != null) + if (resp.getStatus().getStatusString() == null) { - StringBuffer statusStringBuf = new StringBuffer(); - PKIFreeText text = resp.getStatus().getStatusString(); - for (int i = 0; i != text.size(); i++) - { - statusStringBuf.append(text.getStringAtUTF8(i).getString()); - } - return statusStringBuf.toString(); + return null; } - else + + StringBuffer statusStringBuf = new StringBuffer(); + PKIFreeText text = resp.getStatus().getStatusString(); + for (int i = 0; i != text.size(); i++) { - return null; + statusStringBuf.append(text.getStringAtUTF8(i).getString()); } + return statusStringBuf.toString(); } public PKIFailureInfo getFailInfo() @@ -152,7 +163,7 @@ public void validate( if (tok != null) { - TimeStampTokenInfo tstInfo = tok.getTimeStampInfo(); + TimeStampTokenInfo tstInfo = tok.getTimeStampInfo(); if (request.getNonce() != null && !request.getNonce().equals(tstInfo.getNonce())) { @@ -163,17 +174,18 @@ public void validate( { throw new TSPValidationException("time stamp token found in failed request."); } - - if (!Arrays.constantTimeAreEqual(request.getMessageImprintDigest(), tstInfo.getMessageImprintDigest())) - { - throw new TSPValidationException("response for different message imprint digest."); - } - + + // TODO Should be (absent-parameters-flexible) equality of the whole AlgorithmIdentifier? if (!tstInfo.getMessageImprintAlgOID().equals(request.getMessageImprintAlgOID())) { throw new TSPValidationException("response for different message imprint algorithm."); } + if (!Arrays.constantTimeAreEqual(request.getMessageImprintDigest(), tstInfo.getMessageImprintDigest())) + { + throw new TSPValidationException("response for different message imprint digest."); + } + Attribute scV1 = tok.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate); Attribute scV2 = tok.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2); @@ -216,16 +228,13 @@ public byte[] getEncoded() throws IOException */ public byte[] getEncoded(String encoding) throws IOException { + ASN1Object asn1Object = resp; if (ASN1Encoding.DL.equals(encoding)) { - if (timeStampToken == null) - { - return new DLSequence(resp.getStatus()).getEncoded(encoding); - } - - return new DLSequence(new ASN1Encodable[] { resp.getStatus(), - timeStampToken.toCMSSignedData().toASN1Structure() }).getEncoded(encoding); + asn1Object = timeStampToken == null + ? new DLSequence(resp.getStatus()) + : new DLSequence(resp.getStatus(), timeStampToken.toCMSSignedData().toASN1Structure()); } - return resp.getEncoded(encoding); + return asn1Object.getEncoded(encoding); } } diff --git a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampToken.java b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampToken.java index 7556c23dfe..d6713cf427 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampToken.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampToken.java @@ -6,20 +6,17 @@ import java.util.Collection; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.ContentInfo; -import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; import org.bouncycastle.asn1.ess.ESSCertID; import org.bouncycastle.asn1.ess.ESSCertIDv2; import org.bouncycastle.asn1.ess.SigningCertificate; import org.bouncycastle.asn1.ess.SigningCertificateV2; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.tsp.TSTInfo; import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.IssuerSerial; import org.bouncycastle.cert.X509AttributeCertificateHolder; @@ -47,7 +44,7 @@ public class TimeStampToken TimeStampTokenInfo tstInfo; - CertID certID; + ESSCertIDv2 certID; public TimeStampToken(ContentInfo contentInfo) throws TSPException, IOException @@ -96,15 +93,15 @@ public TimeStampToken(CMSSignedData signedData) content.write(bOut); - this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(ASN1Primitive.fromByteArray(bOut.toByteArray()))); - + this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(bOut.toByteArray())); + Attribute attr = tsaSignerInfo.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate); if (attr != null) { SigningCertificate signCert = SigningCertificate.getInstance(attr.getAttrValues().getObjectAt(0)); - this.certID = new CertID(ESSCertID.getInstance(signCert.getCerts()[0])); + this.certID = ESSCertIDv2.from(ESSCertID.getInstance(signCert.getCerts()[0])); } else { @@ -117,7 +114,7 @@ public TimeStampToken(CMSSignedData signedData) SigningCertificateV2 signCertV2 = SigningCertificateV2.getInstance(attr.getAttrValues().getObjectAt(0)); - this.certID = new CertID(ESSCertIDv2.getInstance(signCertV2.getCerts()[0])); + this.certID = ESSCertIDv2.getInstance(signCertV2.getCerts()[0]); } } catch (CMSException e) @@ -195,30 +192,31 @@ public void validate( DigestCalculator calc = sigVerifier.getDigestCalculator(certID.getHashAlgorithm()); OutputStream cOut = calc.getOutputStream(); - cOut.write(certHolder.getEncoded()); cOut.close(); - if (!Arrays.constantTimeAreEqual(certID.getCertHash(), calc.getDigest())) + if (!Arrays.constantTimeAreEqual(certID.getCertHashObject().getOctets(), calc.getDigest())) { throw new TSPValidationException("certificate hash does not match certID hash."); } - if (certID.getIssuerSerial() != null) + IssuerSerial issuerSerial = certID.getIssuerSerial(); + if (issuerSerial != null) { - IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(certHolder.toASN1Structure()); + Certificate c = certHolder.toASN1Structure(); - if (!certID.getIssuerSerial().getSerial().equals(issuerSerial.getSerialNumber())) + if (!issuerSerial.getSerial().equals(c.getSerialNumber())) { throw new TSPValidationException("certificate serial number does not match certID for signature."); } - GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames(); - boolean found = false; + GeneralName[] names = issuerSerial.getIssuer().getNames(); + boolean found = false; for (int i = 0; i != names.length; i++) { - if (names[i].getTagNo() == 4 && X500Name.getInstance(names[i].getName()).equals(X500Name.getInstance(issuerSerial.getName()))) + if (names[i].getTagNo() == GeneralName.directoryName && + X500Name.getInstance(names[i].getName()).equals(c.getIssuer())) { found = true; break; @@ -326,59 +324,4 @@ public byte[] getEncoded(String encoding) { return tsToken.getEncoded(encoding); } - - // perhaps this should be done using an interface on the ASN.1 classes... - private static class CertID - { - private ESSCertID certID; - private ESSCertIDv2 certIDv2; - - CertID(ESSCertID certID) - { - this.certID = certID; - this.certIDv2 = null; - } - - CertID(ESSCertIDv2 certID) - { - this.certIDv2 = certID; - this.certID = null; - } - - public AlgorithmIdentifier getHashAlgorithm() - { - if (certID != null) - { - return new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1); - } - else - { - return certIDv2.getHashAlgorithm(); - } - } - - public byte[] getCertHash() - { - if (certID != null) - { - return certID.getCertHash(); - } - else - { - return certIDv2.getCertHash(); - } - } - - public IssuerSerial getIssuerSerial() - { - if (certID != null) - { - return certID.getIssuerSerial(); - } - else - { - return certIDv2.getIssuerSerial(); - } - } - } } diff --git a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampTokenGenerator.java b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampTokenGenerator.java index 274e6cdf9a..3c353feed1 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/TimeStampTokenGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/TimeStampTokenGenerator.java @@ -20,6 +20,7 @@ import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.LocaleUtil; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.ess.ESSCertID; @@ -31,6 +32,7 @@ import org.bouncycastle.asn1.tsp.Accuracy; import org.bouncycastle.asn1.tsp.MessageImprint; import org.bouncycastle.asn1.tsp.TSTInfo; +import org.bouncycastle.asn1.tsp.TimeStampReq; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.ExtensionsGenerator; @@ -175,19 +177,28 @@ public TimeStampTokenGenerator( X509CertificateHolder assocCert = signerInfoGen.getAssociatedCertificate(); TSPUtil.validateCertificate(assocCert); + AlgorithmIdentifier digestAlgID = digestCalculator.getAlgorithmIdentifier(); + ASN1ObjectIdentifier digestAlgOid = digestAlgID.getAlgorithm(); + try { OutputStream dOut = digestCalculator.getOutputStream(); - dOut.write(assocCert.getEncoded()); - dOut.close(); - if (digestCalculator.getAlgorithmIdentifier().getAlgorithm().equals(OIWObjectIdentifiers.idSHA1)) + DEROctetString certHash = new DEROctetString(digestCalculator.getDigest()); + + IssuerSerial issuerSerial = null; + if (isIssuerSerialIncluded) { - final ESSCertID essCertid = new ESSCertID(digestCalculator.getDigest(), - isIssuerSerialIncluded ? new IssuerSerial(new GeneralNames(new GeneralName(assocCert.getIssuer())), assocCert.getSerialNumber()) - : null); + GeneralNames issuer = new GeneralNames(new GeneralName(assocCert.getIssuer())); + ASN1Integer serial = assocCert.toASN1Structure().getSerialNumber(); + issuerSerial = new IssuerSerial(issuer, serial); + } + + if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOid)) + { + final ESSCertID essCertID = new ESSCertID(certHash, issuerSerial); this.signerInfoGen = new SignerInfoGenerator(signerInfoGen, new CMSAttributeTableGenerator() { @@ -198,7 +209,8 @@ public AttributeTable getAttributes(Map parameters) if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) { - return table.add(PKCSObjectIdentifiers.id_aa_signingCertificate, new SigningCertificate(essCertid)); + return table.add(PKCSObjectIdentifiers.id_aa_signingCertificate, + new SigningCertificate(essCertID)); } return table; @@ -207,10 +219,9 @@ public AttributeTable getAttributes(Map parameters) } else { - AlgorithmIdentifier digAlgID = new AlgorithmIdentifier(digestCalculator.getAlgorithmIdentifier().getAlgorithm()); - final ESSCertIDv2 essCertid = new ESSCertIDv2(digAlgID, digestCalculator.getDigest(), - isIssuerSerialIncluded ? new IssuerSerial(new GeneralNames(new GeneralName(assocCert.getIssuer())), new ASN1Integer(assocCert.getSerialNumber())) - : null); + digestAlgID = new AlgorithmIdentifier(digestAlgOid); + + final ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(digestAlgID, certHash, issuerSerial); this.signerInfoGen = new SignerInfoGenerator(signerInfoGen, new CMSAttributeTableGenerator() { @@ -221,7 +232,8 @@ public AttributeTable getAttributes(Map parameters) if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) == null) { - return table.add(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new SigningCertificateV2(essCertid)); + return table.add(PKCSObjectIdentifiers.id_aa_signingCertificateV2, + new SigningCertificateV2(essCertIDv2)); } return table; @@ -360,8 +372,9 @@ public TimeStampToken generate( Extensions additionalExtensions) throws TSPException { - AlgorithmIdentifier algID = request.getMessageImprintAlgID(); - MessageImprint messageImprint = new MessageImprint(algID, request.getMessageImprintDigest()); + TimeStampReq timeStampReq = request.toASN1Structure(); + + MessageImprint messageImprint = timeStampReq.getMessageImprint(); Accuracy accuracy = null; if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) @@ -393,16 +406,12 @@ public TimeStampToken generate( derOrdering = ASN1Boolean.getInstance(ordering); } - ASN1Integer nonce = null; - if (request.getNonce() != null) - { - nonce = new ASN1Integer(request.getNonce()); - } + ASN1Integer nonce = timeStampReq.getNonce(); - ASN1ObjectIdentifier tsaPolicy = tsaPolicyOID; - if (request.getReqPolicy() != null) + ASN1ObjectIdentifier tsaPolicy = timeStampReq.getReqPolicy(); + if (tsaPolicy == null) { - tsaPolicy = request.getReqPolicy(); + tsaPolicy = this.tsaPolicyOID; } Extensions respExtensions = request.getExtensions(); diff --git a/pkix/src/main/java/org/bouncycastle/tsp/cms/CMSTimeStampedDataGenerator.java b/pkix/src/main/java/org/bouncycastle/tsp/cms/CMSTimeStampedDataGenerator.java index fd1e6030c9..6484a10677 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/cms/CMSTimeStampedDataGenerator.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/cms/CMSTimeStampedDataGenerator.java @@ -35,10 +35,10 @@ public CMSTimeStampedData generate(TimeStampToken timeStamp, byte[] content) thr public CMSTimeStampedData generate(TimeStampToken timeStamp, InputStream content) throws CMSException { - ByteArrayOutputStream contentOut = new ByteArrayOutputStream(); - + ASN1OctetString encContent = null; if (content != null) { + ByteArrayOutputStream contentOut = new ByteArrayOutputStream(); try { Streams.pipeAll(content, contentOut); @@ -47,13 +47,11 @@ public CMSTimeStampedData generate(TimeStampToken timeStamp, InputStream content { throw new CMSException("exception encapsulating content: " + e.getMessage(), e); } - } - - ASN1OctetString encContent = null; - if (contentOut.size() != 0) - { - encContent = new BEROctetString(contentOut.toByteArray()); + if (contentOut.size() != 0) + { + encContent = new BEROctetString(contentOut.toByteArray()); + } } TimeStampAndCRL stamp = new TimeStampAndCRL(timeStamp.toCMSSignedData().toASN1Structure()); @@ -64,8 +62,11 @@ public CMSTimeStampedData generate(TimeStampToken timeStamp, InputStream content { asn1DataUri = new DERIA5String(dataUri.toString()); } - - return new CMSTimeStampedData(new ContentInfo(CMSObjectIdentifiers.timestampedData, new TimeStampedData(asn1DataUri, metaData, encContent, new Evidence(new TimeStampTokenEvidence(stamp))))); + + TimeStampedData timeStampedData = new TimeStampedData(asn1DataUri, metaData, encContent, + new Evidence(new TimeStampTokenEvidence(stamp))); + + return new CMSTimeStampedData(new ContentInfo(CMSObjectIdentifiers.timestampedData, timeStampedData)); } } diff --git a/pkix/src/main/java/org/bouncycastle/tsp/cms/package-info.java b/pkix/src/main/java/org/bouncycastle/tsp/cms/package-info.java new file mode 100644 index 0000000000..b37a019ead --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/tsp/cms/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for dealing Syntax for Binding Documents with Time-Stamps - RFC 5544. + */ +package org.bouncycastle.tsp.cms; diff --git a/pkix/src/main/java/org/bouncycastle/tsp/ers/ERSInputStreamData.java b/pkix/src/main/java/org/bouncycastle/tsp/ers/ERSInputStreamData.java index 7b3757d047..f37d44ffb1 100644 --- a/pkix/src/main/java/org/bouncycastle/tsp/ers/ERSInputStreamData.java +++ b/pkix/src/main/java/org/bouncycastle/tsp/ers/ERSInputStreamData.java @@ -3,9 +3,11 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.io.IOException; import java.io.InputStream; import org.bouncycastle.operator.DigestCalculator; +import org.bouncycastle.util.io.Streams; /** * Generic class for processing an InputStream of data RFC 4998 ERS. @@ -13,7 +15,8 @@ public class ERSInputStreamData extends ERSCachingData { - private final InputStream content; + private final File contentFile; + private final byte[] contentBytes; public ERSInputStreamData(File content) throws FileNotFoundException @@ -22,17 +25,47 @@ public ERSInputStreamData(File content) { throw new IllegalArgumentException("directory not allowed"); } - this.content = new FileInputStream(content); + if (!content.exists()) + { + throw new FileNotFoundException(content + " not found"); + } + this.contentBytes = null; + this.contentFile = content; } public ERSInputStreamData(InputStream content) { - this.content = content; + try + { + this.contentBytes = Streams.readAll(content); + } + catch (IOException e) + { + throw ExpUtil.createIllegalState("unable to open content: " + e.getMessage(), e); + } + this.contentFile = null; } protected byte[] calculateHash(DigestCalculator digestCalculator, byte[] previousChainHash) { - byte[] hash = ERSUtil.calculateDigest(digestCalculator, content); + byte[] hash; + if (contentBytes != null) + { + hash = ERSUtil.calculateDigest(digestCalculator, contentBytes); + } + else + { + try + { + InputStream content = new FileInputStream(contentFile); + hash = ERSUtil.calculateDigest(digestCalculator, content); + content.close(); + } + catch (IOException e) + { + throw ExpUtil.createIllegalState("unable to open content: " + e.getMessage(), e); + } + } if (previousChainHash != null) { diff --git a/pkix/src/main/java/org/bouncycastle/tsp/package-info.java b/pkix/src/main/java/org/bouncycastle/tsp/package-info.java new file mode 100644 index 0000000000..cabbd370d0 --- /dev/null +++ b/pkix/src/main/java/org/bouncycastle/tsp/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for dealing Time Stamp Protocol (TSP) - RFC 3161. + */ +package org.bouncycastle.tsp; diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/RecipientId.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/RecipientId.java index 7ea1f329c5..c96f679255 100644 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/RecipientId.java +++ b/pkix/src/main/jdk1.1/org/bouncycastle/cms/RecipientId.java @@ -9,6 +9,7 @@ public abstract class RecipientId public static final int kek = 1; public static final int keyAgree = 2; public static final int password = 3; + public static final int kem = 4; private int type; diff --git a/pkix/src/main/jdk1.3/org/bouncycastle/cms/jcajce/JceKEMRecipientId.java b/pkix/src/main/jdk1.3/org/bouncycastle/cms/jcajce/JceKEMRecipientId.java new file mode 100644 index 0000000000..f3f73ba28e --- /dev/null +++ b/pkix/src/main/jdk1.3/org/bouncycastle/cms/jcajce/JceKEMRecipientId.java @@ -0,0 +1,70 @@ +package org.bouncycastle.cms.jcajce; + +import java.math.BigInteger; +import java.security.cert.X509Certificate; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cms.KEMRecipientId; +import org.bouncycastle.jce.X509Principal; +import org.bouncycastle.jce.PrincipalUtil; + +public class JceKEMRecipientId + extends KEMRecipientId +{ + private static X509Principal extractIssuer(X509Certificate certificate) + { + try + { + return PrincipalUtil.getIssuerX509Principal(certificate); + } + catch (Exception e) + { + throw new IllegalStateException(e.toString()); + } + } + + + /** + * Construct a recipient id based on the issuer, serial number and subject key identifier (if present) of the passed in + * certificate. + * + * @param certificate certificate providing the issue and serial number and subject key identifier. + */ + public JceKEMRecipientId(X509Certificate certificate) + { + super(convertPrincipal(extractIssuer(certificate)), certificate.getSerialNumber(), CMSUtils.getSubjectKeyId(certificate)); + } + + /** + * Construct a recipient id based on the provided issuer and serial number.. + * + * @param issuer the issuer to use. + * @param serialNumber the serial number to use. + */ + public JceKEMRecipientId(X509Principal issuer, BigInteger serialNumber) + { + super(convertPrincipal(issuer), serialNumber); + } + + /** + * Construct a recipient id based on the provided issuer, serial number, and subjectKeyId.. + * + * @param issuer the issuer to use. + * @param serialNumber the serial number to use. + * @param subjectKeyId the subject key ID to use. + */ + public JceKEMRecipientId(X509Principal issuer, BigInteger serialNumber, byte[] subjectKeyId) + { + super(convertPrincipal(issuer), serialNumber, subjectKeyId); + } + + private static X500Name convertPrincipal(X509Principal issuer) + { + if (issuer == null) + { + return null; + } + + return X500Name.getInstance(issuer.getEncoded()); + } +} diff --git a/pkix/src/main/jdk1.4/org/bouncycastle/cms/jcajce/CMSInputAEADDecryptor.java b/pkix/src/main/jdk1.4/org/bouncycastle/cms/jcajce/CMSInputAEADDecryptor.java new file mode 100644 index 0000000000..56a900466c --- /dev/null +++ b/pkix/src/main/jdk1.4/org/bouncycastle/cms/jcajce/CMSInputAEADDecryptor.java @@ -0,0 +1,54 @@ +package org.bouncycastle.cms.jcajce; + +import java.io.InputStream; +import java.io.OutputStream; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import javax.crypto.Cipher; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cms.InputStreamWithMAC; +import org.bouncycastle.jcajce.io.CipherInputStream; +import org.bouncycastle.operator.InputAEADDecryptor; + +class CMSInputAEADDecryptor + implements InputAEADDecryptor +{ + private final AlgorithmIdentifier contentEncryptionAlgorithm; + + private final Cipher dataCipher; + + private InputStream inputStream; + + CMSInputAEADDecryptor(AlgorithmIdentifier contentEncryptionAlgorithm, Cipher dataCipher) + { + this.contentEncryptionAlgorithm = contentEncryptionAlgorithm; + this.dataCipher = dataCipher; + } + + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return contentEncryptionAlgorithm; + } + + public InputStream getInputStream(InputStream dataIn) + { + inputStream = dataIn; + return new CipherInputStream(dataIn, dataCipher); + } + + public OutputStream getAADStream() + { + return null; // TODO: okay this is awful, we could use AEADParameterSpec for earlier JDKs. + } + + public byte[] getMAC() + { + if (inputStream instanceof InputStreamWithMAC) + { + return ((InputStreamWithMAC)inputStream).getMAC(); + } + return null; + } +} diff --git a/pkix/src/main/jdk1.4/org/bouncycastle/eac/jcajce/JcaPublicKeyConverter.java b/pkix/src/main/jdk1.4/org/bouncycastle/eac/jcajce/JcaPublicKeyConverter.java index f412e8e009..a156d107e3 100644 --- a/pkix/src/main/jdk1.4/org/bouncycastle/eac/jcajce/JcaPublicKeyConverter.java +++ b/pkix/src/main/jdk1.4/org/bouncycastle/eac/jcajce/JcaPublicKeyConverter.java @@ -128,11 +128,13 @@ public PublicKeyDataObject getPublicKeyDataObject(ASN1ObjectIdentifier usage, Pu ECPublicKey pubKey = (ECPublicKey)publicKey; ECParameterSpec params = pubKey.getParameters(); + ECCurve.AbstractFp curve = (ECCurve.AbstractFp)params.getCurve(); + return new ECDSAPublicKey( usage, - ((ECCurve.Fp)params.getCurve()).getQ(), - ((ECFieldElement.Fp)params.getCurve().getA()).toBigInteger(), - ((ECFieldElement.Fp)params.getCurve().getB()).toBigInteger(), + curve.getQ(), + curve.getA().toBigInteger(), + curve.getB().toBigInteger(), params.getG().getEncoded(false), params.getN(), pubKey.getQ().getEncoded(false), diff --git a/pkix/src/main/jdk1.4/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java b/pkix/src/main/jdk1.4/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java index 80e099fe11..0d67eb07a0 100644 --- a/pkix/src/main/jdk1.4/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java +++ b/pkix/src/main/jdk1.4/org/bouncycastle/operator/jcajce/JcaContentSignerBuilder.java @@ -5,16 +5,32 @@ import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.Provider; +import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.PSSParameterSpec; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.DERNull; +import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.CompositePrivateKey; +import org.bouncycastle.jcajce.io.OutputStreamFactory; +import org.bouncycastle.jcajce.spec.CompositeAlgorithmSpec; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; @@ -22,28 +38,77 @@ import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; +import org.bouncycastle.operator.ExtendedContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.OperatorStreamException; import org.bouncycastle.operator.RuntimeOperatorException; +import org.bouncycastle.operator.SignatureAlgorithmIdentifierFinder; +import org.bouncycastle.util.Pack; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.io.TeeOutputStream; public class JcaContentSignerBuilder { + private static final Set isAlgIdFromPrivate = new HashSet(); + private static final DefaultSignatureAlgorithmIdentifierFinder SIGNATURE_ALGORITHM_IDENTIFIER_FINDER = new DefaultSignatureAlgorithmIdentifierFinder(); + + static + { + isAlgIdFromPrivate.add("DILITHIUM"); + isAlgIdFromPrivate.add("SPHINCS+"); + isAlgIdFromPrivate.add("SPHINCSPlus"); + isAlgIdFromPrivate.add("ML-DSA"); + isAlgIdFromPrivate.add("SLH-DSA"); + isAlgIdFromPrivate.add("HASH-ML-DSA"); + isAlgIdFromPrivate.add("HASH-SLH-DSA"); + } + + private final String signatureAlgorithm; + private final AlgorithmIdentifier signatureDigestAlgorithm; + private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); private SecureRandom random; - private String signatureAlgorithm; + private AlgorithmIdentifier sigAlgId; private AlgorithmParameterSpec sigAlgSpec; + /** + * Construct a basic content signer where the signature algorithm name + * tells us all we need to know. + * + * @param signatureAlgorithm the signature algorithm we perform. + */ public JcaContentSignerBuilder(String signatureAlgorithm) + { + this(signatureAlgorithm, (AlgorithmIdentifier)null); + } + + /** + * Constructor which includes the digest algorithm identifier used. + *

      + * Some PKIX operations, such as CMS signing, require the digest algorithm used for in the + * signature, this constructor allows the digest algorithm identifier to + * be explicitly specified. + *

      + * + * @param signatureAlgorithm the signature algorithm we perform. + * @param signatureDigestAlgorithmID the public key associated with our private key. + */ + public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmIdentifier signatureDigestAlgorithmID) { this.signatureAlgorithm = signatureAlgorithm; - this.sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm); - this.sigAlgSpec = null; + this.signatureDigestAlgorithm = signatureDigestAlgorithmID; } public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmParameterSpec sigParamSpec) + { + this(signatureAlgorithm, sigParamSpec, null); + } + + public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmParameterSpec sigParamSpec, AlgorithmIdentifier signatureDigestAlgorithmID) { this.signatureAlgorithm = signatureAlgorithm; + this.signatureDigestAlgorithm = signatureDigestAlgorithmID; if (sigParamSpec instanceof PSSParameterSpec) { @@ -51,12 +116,20 @@ public JcaContentSignerBuilder(String signatureAlgorithm, AlgorithmParameterSpec this.sigAlgSpec = pssSpec; this.sigAlgId = new AlgorithmIdentifier( - PKCSObjectIdentifiers.id_RSASSA_PSS, createPSSParams(signatureAlgorithm, pssSpec)); + PKCSObjectIdentifiers.id_RSASSA_PSS, createPSSParams(signatureAlgorithm, pssSpec)); + } + else if (sigParamSpec instanceof CompositeAlgorithmSpec) + { + CompositeAlgorithmSpec compSpec = (CompositeAlgorithmSpec)sigParamSpec; + + this.sigAlgSpec = compSpec; + this.sigAlgId = new AlgorithmIdentifier( + MiscObjectIdentifiers.id_alg_composite, createCompParams(compSpec)); } else { throw new IllegalArgumentException("unknown sigParamSpec: " - + ((sigParamSpec == null) ? "null" : sigParamSpec.getClass().getName())); + + ((sigParamSpec == null) ? "null" : sigParamSpec.getClass().getName())); } } @@ -86,6 +159,11 @@ public ContentSigner build(PrivateKey privateKey) { try { + if (sigAlgSpec == null) + { + this.sigAlgId = getSigAlgId(privateKey); + } + final Signature sig = helper.createSignature(sigAlgId); final AlgorithmIdentifier signatureAlgId = sigAlgId; @@ -131,6 +209,23 @@ public byte[] getSignature() } } + private AlgorithmIdentifier getSigAlgId(PrivateKey privateKey) + { + if (isAlgIdFromPrivate.contains(Strings.toUpperCase(signatureAlgorithm))) + { + AlgorithmIdentifier sigAlgId = SIGNATURE_ALGORITHM_IDENTIFIER_FINDER.find(privateKey.getAlgorithm()); + if (sigAlgId == null) + { + return PrivateKeyInfo.getInstance(privateKey.getEncoded()).getPrivateKeyAlgorithm(); + } + return sigAlgId; + } + else + { + return SIGNATURE_ALGORITHM_IDENTIFIER_FINDER.find(signatureAlgorithm); + } + } + private class SignatureOutputStream extends OutputStream { @@ -190,8 +285,8 @@ byte[] getSignature() private static RSASSAPSSparams createPSSParams(String signatureAlgorithm, PSSParameterSpec pssSpec) { DigestAlgorithmIdentifierFinder digFinder = new DefaultDigestAlgorithmIdentifierFinder(); - AlgorithmIdentifier digId = digFinder.find(signatureAlgorithm.substring(0, signatureAlgorithm.indexOf("w"))); - AlgorithmIdentifier mgfDig = digFinder.find(signatureAlgorithm.substring(0, signatureAlgorithm.indexOf("w"))); + AlgorithmIdentifier digId = digFinder.find(signatureAlgorithm.substring(0, signatureAlgorithm.indexOf("w"))); + AlgorithmIdentifier mgfDig = digFinder.find(signatureAlgorithm.substring(0, signatureAlgorithm.indexOf("w"))); return new RSASSAPSSparams( digId, @@ -199,4 +294,32 @@ private static RSASSAPSSparams createPSSParams(String signatureAlgorithm, PSSPar new ASN1Integer(pssSpec.getSaltLength()), RSASSAPSSparams.DEFAULT_TRAILER_FIELD); } + + private static ASN1Sequence createCompParams(CompositeAlgorithmSpec compSpec) + { + SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder(); + ASN1EncodableVector v = new ASN1EncodableVector(); + + List algorithmNames = compSpec.getAlgorithmNames(); + List algorithmSpecs = compSpec.getParameterSpecs(); + + for (int i = 0; i != algorithmNames.size(); i++) + { + AlgorithmParameterSpec sigSpec = (AlgorithmParameterSpec)algorithmSpecs.get(i); + if (sigSpec == null) + { + v.add(algFinder.find((String)algorithmNames.get(i))); + } + else if (sigSpec instanceof PSSParameterSpec) + { + v.add(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_RSASSA_PSS, createPSSParams((String)algorithmNames.get(i), (PSSParameterSpec)sigSpec))); + } + else + { + throw new IllegalArgumentException("unrecognized parameterSpec"); + } + } + + return new DERSequence(v); + } } diff --git a/pkix/src/test/java/org/bouncycastle/cert/cmp/test/PQCTest.java b/pkix/src/test/java/org/bouncycastle/cert/cmp/test/PQCTest.java index 527d3c2fce..4f0541ba1a 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/cmp/test/PQCTest.java +++ b/pkix/src/test/java/org/bouncycastle/cert/cmp/test/PQCTest.java @@ -6,11 +6,14 @@ import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; +import java.io.FileWriter; import java.util.Arrays; import java.util.Collection; import java.util.Date; import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.cmp.CMPCertificate; import org.bouncycastle.asn1.cmp.PKIBody; @@ -19,6 +22,7 @@ import org.bouncycastle.asn1.crmf.CertTemplate; import org.bouncycastle.asn1.crmf.SubsequentMessage; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.BasicConstraints; @@ -52,6 +56,8 @@ import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; import org.bouncycastle.cms.jcajce.JceKEMEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKEMRecipientInfoGenerator; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; @@ -61,14 +67,13 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.pkcs.jcajce.JcePBMac1CalculatorBuilder; import org.bouncycastle.pkcs.jcajce.JcePBMac1CalculatorProviderBuilder; import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; import org.bouncycastle.pqc.jcajce.spec.BIKEParameterSpec; import org.bouncycastle.pqc.jcajce.spec.CMCEParameterSpec; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; import org.bouncycastle.pqc.jcajce.spec.HQCParameterSpec; -import org.bouncycastle.pqc.jcajce.spec.KyberParameterSpec; import org.bouncycastle.pqc.jcajce.spec.NTRUParameterSpec; import org.bouncycastle.util.BigIntegers; @@ -86,24 +91,24 @@ public void tearDown() } - public void testKyberRequestWithDilithiumCA() + public void testMlKemRequestWithMlDsaCA() throws Exception { char[] senderMacPassword = "secret".toCharArray(); - GeneralName sender = new GeneralName(new X500Name("CN=Kyber Subject")); - GeneralName recipient = new GeneralName(new X500Name("CN=Dilithium Issuer")); + GeneralName sender = new GeneralName(new X500Name("CN=ML-KEM Subject")); + GeneralName recipient = new GeneralName(new X500Name("CN=ML-DSA Issuer")); - KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dilKpGen.initialize(DilithiumParameterSpec.dilithium2); + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_65); KeyPair dilKp = dilKpGen.generateKeyPair(); - X509CertificateHolder caCert = makeV3Certificate("CN=Dilithium Issuer", dilKp); + X509CertificateHolder caCert = makeV3Certificate("CN=ML-DSA Issuer", dilKp); - KeyPairGenerator kybKpGen = KeyPairGenerator.getInstance("Kyber", "BCPQC"); + KeyPairGenerator kybKpGen = KeyPairGenerator.getInstance("ML-KEM", "BC"); - kybKpGen.initialize(KyberParameterSpec.kyber512); + kybKpGen.initialize(MLKEMParameterSpec.ml_kem_768); KeyPair kybKp = kybKpGen.generateKeyPair(); @@ -140,7 +145,7 @@ public void testKyberRequestWithDilithiumCA() CertificateRequestMessage senderReqMessage = requestMessages.getRequests()[0]; CertTemplate certTemplate = senderReqMessage.getCertTemplate(); - X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=Dilithium Issuer"); + X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=ML-DSA Issuer"); // Send response with encrypted certificate CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); @@ -155,6 +160,7 @@ public void testKyberRequestWithDilithiumCA() new CMSProcessableCMPCertificate(cert), new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build()); +// System.err.println(ASN1Dump.dumpAsString(encryptedCert.toASN1Structure())); CertificateResponseBuilder certRespBuilder = new CertificateResponseBuilder(senderReqMessage.getCertReqId(), new PKIStatusInfo(PKIStatus.granted)); certRespBuilder.withCertificate(encryptedCert); @@ -163,7 +169,7 @@ public void testKyberRequestWithDilithiumCA() repMessageBuilder.addCertificateResponse(certRespBuilder.build()); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(dilKp.getPrivate()); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate()); CertificateRepMessage repMessage = repMessageBuilder.build(); @@ -182,23 +188,23 @@ public void testKyberRequestWithDilithiumCA() assertEquals(true, certResp.hasEncryptedCertificate()); // this is the long-way to decrypt, for testing - CMSEnvelopedData receivedEnvelope = certResp.getEncryptedCertificate(); + CMSEnvelopedData receivedEnvelope = new CMSEnvelopedData(certResp.getEncryptedCertificate().toASN1Structure().getEncoded(ASN1Encoding.DL)); -// JcaPEMWriter pOut = new JcaPEMWriter(new FileWriter("/tmp/kyber_cms/kyber_cert_enveloped.pem")); -// pOut.writeObject(receivedEnvelope.toASN1Structure()); -// pOut.close(); -// -// pOut = new JcaPEMWriter(new FileWriter("/tmp/kyber_cms/kyber_priv.pem")); -// pOut.writeObject(kybKp.getPrivate()); -// pOut.close(); -// -// pOut = new JcaPEMWriter(new FileWriter("/tmp/kyber_cms/kyber_cert.pem")); -// pOut.writeObject(cert); -// pOut.close(); -// -// pOut = new JcaPEMWriter(new FileWriter("/tmp/kyber_cms/issuer_cert.pem")); -// pOut.writeObject(caCert); -// pOut.close(); + JcaPEMWriter pOut = new JcaPEMWriter(new FileWriter("/tmp/mlkem_cms/mlkem_cert_enveloped.pem")); + pOut.writeObject(receivedEnvelope.toASN1Structure()); + pOut.close(); + + pOut = new JcaPEMWriter(new FileWriter("/tmp/mlkem_cms/mlkem_priv.pem")); + pOut.writeObject(kybKp.getPrivate()); + pOut.close(); + + pOut = new JcaPEMWriter(new FileWriter("/tmp/mlkem_cms/mlkem_cert.pem")); + pOut.writeObject(cert); + pOut.close(); + + pOut = new JcaPEMWriter(new FileWriter("/tmp/mlkem_cms/mlkem_cert.pem")); + pOut.writeObject(caCert); + pOut.close(); // // System.err.println(ASN1Dump.dumpAsString(receivedEnvelope.toASN1Structure())); @@ -210,11 +216,9 @@ public void testKyberRequestWithDilithiumCA() RecipientInformation recInfo = (RecipientInformation)c.iterator().next(); - assertEquals(recInfo.getKeyEncryptionAlgOID(), BCObjectIdentifiers.kyber512.getId()); - - // Note: we don't specify the provider here as we're actually using both BC and BCPQC + assertEquals(recInfo.getKeyEncryptionAlgOID(), NISTObjectIdentifiers.id_alg_ml_kem_768.getId()); - byte[] recData = recInfo.getContent(new JceKEMEnvelopedRecipient(kybKp.getPrivate())); + byte[] recData = recInfo.getContent(new JceKEMEnvelopedRecipient(kybKp.getPrivate()).setProvider("BC")); assertEquals(true, Arrays.equals(new CMPCertificate(cert.toASN1Structure()).getEncoded(), recData)); @@ -248,20 +252,20 @@ public void testKyberRequestWithDilithiumCA() assertTrue(recContent.getStatusMessages()[0].isVerified(receivedCert, new JcaDigestCalculatorProviderBuilder().build())); } - public void testNTRURequestWithDilithiumCA() + public void testNTRURequestWithMlDsaCA() throws Exception { char[] senderMacPassword = "secret".toCharArray(); GeneralName sender = new GeneralName(new X500Name("CN=NTRU Subject")); - GeneralName recipient = new GeneralName(new X500Name("CN=Dilithium Issuer")); + GeneralName recipient = new GeneralName(new X500Name("CN=ML-DSA Issuer")); - KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dilKpGen.initialize(DilithiumParameterSpec.dilithium2); + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpGen.generateKeyPair(); - X509CertificateHolder caCert = makeV3Certificate("CN=Dilithium Issuer", dilKp); + X509CertificateHolder caCert = makeV3Certificate("CN=ML-DSA Issuer", dilKp); KeyPairGenerator kybKpGen = KeyPairGenerator.getInstance("NTRU", "BCPQC"); @@ -302,7 +306,7 @@ public void testNTRURequestWithDilithiumCA() CertificateRequestMessage senderReqMessage = requestMessages.getRequests()[0]; CertTemplate certTemplate = senderReqMessage.getCertTemplate(); - X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=Dilithium Issuer"); + X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=ML-DSA Issuer"); // Send response with encrypted certificate CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); @@ -325,7 +329,7 @@ public void testNTRURequestWithDilithiumCA() repMessageBuilder.addCertificateResponse(certRespBuilder.build()); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(dilKp.getPrivate()); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate()); CertificateRepMessage repMessage = repMessageBuilder.build(); @@ -420,20 +424,20 @@ public void testNTRURequestWithDilithiumCA() // System.err.println(ASN1Dump.dumpAsString(receivedEnvelope.toASN1Structure())); } - public void testBIKERequestWithDilithiumCA() + public void testBIKERequestWithMlDsaCA() throws Exception { char[] senderMacPassword = "secret".toCharArray(); GeneralName sender = new GeneralName(new X500Name("CN=Bike128 Subject")); - GeneralName recipient = new GeneralName(new X500Name("CN=Dilithium Issuer")); + GeneralName recipient = new GeneralName(new X500Name("CN=ML-DSA Issuer")); - KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dilKpGen.initialize(DilithiumParameterSpec.dilithium2); + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpGen.generateKeyPair(); - X509CertificateHolder caCert = makeV3Certificate("CN=Dilithium Issuer", dilKp); + X509CertificateHolder caCert = makeV3Certificate("CN=ML-DSA Issuer", dilKp); KeyPairGenerator kybKpGen = KeyPairGenerator.getInstance("BIKE", "BCPQC"); @@ -474,7 +478,7 @@ public void testBIKERequestWithDilithiumCA() CertificateRequestMessage senderReqMessage = requestMessages.getRequests()[0]; CertTemplate certTemplate = senderReqMessage.getCertTemplate(); - X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=Dilithium Issuer"); + X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=ML-DSA Issuer"); // Send response with encrypted certificate CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); @@ -497,7 +501,7 @@ public void testBIKERequestWithDilithiumCA() repMessageBuilder.addCertificateResponse(certRespBuilder.build()); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(dilKp.getPrivate()); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate()); CertificateRepMessage repMessage = repMessageBuilder.build(); @@ -592,20 +596,20 @@ public void testBIKERequestWithDilithiumCA() // System.err.println(ASN1Dump.dumpAsString(receivedEnvelope.toASN1Structure())); } - public void testHQCRequestWithDilithiumCA() + public void testHQCRequestWithMlDsaCA() throws Exception { char[] senderMacPassword = "secret".toCharArray(); GeneralName sender = new GeneralName(new X500Name("CN=HQC128 Subject")); - GeneralName recipient = new GeneralName(new X500Name("CN=Dilithium Issuer")); + GeneralName recipient = new GeneralName(new X500Name("CN=ML-DSA Issuer")); - KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dilKpGen.initialize(DilithiumParameterSpec.dilithium2); + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpGen.generateKeyPair(); - X509CertificateHolder caCert = makeV3Certificate("CN=Dilithium Issuer", dilKp); + X509CertificateHolder caCert = makeV3Certificate("CN=ML-DSA Issuer", dilKp); KeyPairGenerator kybKpGen = KeyPairGenerator.getInstance("HQC", "BCPQC"); @@ -646,7 +650,7 @@ public void testHQCRequestWithDilithiumCA() CertificateRequestMessage senderReqMessage = requestMessages.getRequests()[0]; CertTemplate certTemplate = senderReqMessage.getCertTemplate(); - X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=Dilithium Issuer"); + X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=ML-DSA Issuer"); // Send response with encrypted certificate CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); @@ -669,7 +673,7 @@ public void testHQCRequestWithDilithiumCA() repMessageBuilder.addCertificateResponse(certRespBuilder.build()); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(dilKp.getPrivate()); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate()); CertificateRepMessage repMessage = repMessageBuilder.build(); @@ -764,20 +768,20 @@ public void testHQCRequestWithDilithiumCA() // System.err.println(ASN1Dump.dumpAsString(receivedEnvelope.toASN1Structure())); } - public void testCMCERequestWithDilithiumCA() + public void testCMCERequestWithMlDsaCA() throws Exception { char[] senderMacPassword = "secret".toCharArray(); GeneralName sender = new GeneralName(new X500Name("CN=mceliece3488864 Subject")); - GeneralName recipient = new GeneralName(new X500Name("CN=Dilithium Issuer")); + GeneralName recipient = new GeneralName(new X500Name("CN=ML-DSA Issuer")); - KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dilKpGen.initialize(DilithiumParameterSpec.dilithium2); + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpGen.generateKeyPair(); - X509CertificateHolder caCert = makeV3Certificate("CN=Dilithium Issuer", dilKp); + X509CertificateHolder caCert = makeV3Certificate("CN=ML-DSA Issuer", dilKp); KeyPairGenerator cmceKpGen = KeyPairGenerator.getInstance("CMCE", "BCPQC"); @@ -818,7 +822,7 @@ public void testCMCERequestWithDilithiumCA() CertificateRequestMessage senderReqMessage = requestMessages.getRequests()[0]; CertTemplate certTemplate = senderReqMessage.getCertTemplate(); - X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=Dilithium Issuer"); + X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=ML-DSA Issuer"); // Send response with encrypted certificate CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); @@ -841,7 +845,7 @@ public void testCMCERequestWithDilithiumCA() repMessageBuilder.addCertificateResponse(certRespBuilder.build()); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(dilKp.getPrivate()); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate()); CertificateRepMessage repMessage = repMessageBuilder.build(); @@ -936,20 +940,20 @@ public void testCMCERequestWithDilithiumCA() // System.err.println(ASN1Dump.dumpAsString(receivedEnvelope.toASN1Structure())); } - public void testExternalCMCERequestWithDilithiumCA() + public void testExternalCMCERequestWithMlDsaCA() throws Exception { char[] senderMacPassword = "secret".toCharArray(); GeneralName sender = new GeneralName(new X500Name("CN=mceliece3488864 Subject")); - GeneralName recipient = new GeneralName(new X500Name("CN=Dilithium Issuer")); + GeneralName recipient = new GeneralName(new X500Name("CN=ML-DSA Issuer")); - KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dilKpGen.initialize(DilithiumParameterSpec.dilithium2); + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpGen.generateKeyPair(); - X509CertificateHolder caCert = makeV3Certificate("CN=Dilithium Issuer", dilKp); + X509CertificateHolder caCert = makeV3Certificate("CN=ML-DSA Issuer", dilKp); KeyPairGenerator cmceKpGen = KeyPairGenerator.getInstance("CMCE", "BCPQC"); @@ -990,7 +994,7 @@ public void testExternalCMCERequestWithDilithiumCA() CertificateRequestMessage senderReqMessage = requestMessages.getRequests()[0]; CertTemplate certTemplate = senderReqMessage.getCertTemplate(); - X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=Dilithium Issuer"); + X509CertificateHolder cert = makeV3Certificate(certTemplate.getPublicKey(), certTemplate.getSubject(), dilKp, "CN=ML-DSA Issuer"); // Send response with encrypted certificate CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); @@ -1013,7 +1017,7 @@ public void testExternalCMCERequestWithDilithiumCA() repMessageBuilder.addCertificateResponse(certRespBuilder.build()); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(dilKp.getPrivate()); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate()); CertificateRepMessage repMessage = repMessageBuilder.build(); @@ -1124,7 +1128,7 @@ private static X509CertificateHolder makeV3Certificate(String _subDN, KeyPair is certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").build(issPriv); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").build(issPriv); X509CertificateHolder certHolder = certGen.build(signer); @@ -1151,7 +1155,7 @@ private static X509CertificateHolder makeV3Certificate(SubjectPublicKeyInfo pubK certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); - ContentSigner signer = new JcaContentSignerBuilder("Dilithium").build(issPriv); + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").build(issPriv); X509CertificateHolder certHolder = certGen.build(signer); diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/AllTests.java b/pkix/src/test/java/org/bouncycastle/cert/test/AllTests.java index d42ff79096..f71b205e71 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/test/AllTests.java +++ b/pkix/src/test/java/org/bouncycastle/cert/test/AllTests.java @@ -13,10 +13,31 @@ public class AllTests extends TestCase { + public void setUp() + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + public void testSimpleTests() { - org.bouncycastle.util.test.Test[] tests = new org.bouncycastle.util.test.Test[] { new CertTest(), new DANETest(), new PKCS10Test(), new AttrCertSelectorTest(), new AttrCertTest(), new X509ExtensionUtilsTest(), - new CertPathLoopTest(), new GOST3410_2012CMSTest(), new ExternalKeyTest() }; + org.bouncycastle.util.test.Test[] tests = new org.bouncycastle.util.test.Test[] + { + new AttrCertSelectorTest(), + new AttrCertTest(), + new CertPathLoopTest(), + new CertTest(), + new DANETest(), + new ExternalKeyTest(), + new GOST3410_2012CMSTest(), + new GOSTR3410_2012_256GenerateCertificate(), + new MLDSACredentialsTest(), + new PKCS10Test(), + new SLHDSACredentialsTest(), + new X509ExtensionUtilsTest(), + }; for (int i = 0; i != tests.length; i++) { @@ -53,6 +74,7 @@ public static Test suite() suite.addTestSuite(BcAttrCertTest.class); suite.addTestSuite(BcCertTest.class); suite.addTestSuite(BcPKCS10Test.class); + suite.addTestSuite(PQCPKCS10Test.class); suite.addTest(ConverterTest.suite()); return new BCTestSetup(suite); diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java b/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java index 9b7facf878..cf4ebacefc 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java +++ b/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java @@ -3,7 +3,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; @@ -61,7 +60,6 @@ import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSAPublicKey; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; @@ -79,6 +77,7 @@ import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.SubjectAltPublicKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; @@ -104,8 +103,9 @@ import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.jcajce.CompositePrivateKey; import org.bouncycastle.jcajce.CompositePublicKey; -import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeSignaturesConstants; import org.bouncycastle.jcajce.spec.CompositeAlgorithmSpec; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; import org.bouncycastle.jce.X509KeyUsage; import org.bouncycastle.jce.interfaces.ECPointEncoder; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -115,12 +115,11 @@ import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.jce.spec.GOST3410ParameterSpec; import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; -import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.NoSignatureContentSigner; import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; import org.bouncycastle.operator.bc.BcRSAContentVerifierProviderBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; @@ -137,13 +136,11 @@ import org.bouncycastle.pqc.jcajce.spec.SPHINCSPlusParameterSpec; import org.bouncycastle.pqc.jcajce.spec.XMSSMTParameterSpec; import org.bouncycastle.pqc.jcajce.spec.XMSSParameterSpec; -import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Encodable; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.util.test.TestFailedException; public class CertTest extends SimpleTest @@ -2867,7 +2864,7 @@ public void checkCRLCreation5() { ASN1Enumerated reasonCode = (ASN1Enumerated)fromExtensionValue(ext); - if (reasonCode.intValueExact() != CRLReason.privilegeWithdrawn) + if (!reasonCode.hasValue(CRLReason.privilegeWithdrawn)) { fail("CRL entry reasonCode wrong"); } @@ -3040,9 +3037,9 @@ public void checkCrlECDSAwithDilithiumCreation() PrivateKey ecPriv = ecKp.getPrivate(); PublicKey ecPub = ecKp.getPublic(); - KeyPairGenerator dlKpg = KeyPairGenerator.getInstance("Dilithium2", "BCPQC"); + KeyPairGenerator dlKpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); - dlKpg.initialize(DilithiumParameterSpec.dilithium2); + dlKpg.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dlKp = dlKpg.generateKeyPair(); @@ -3058,7 +3055,7 @@ public void checkCrlECDSAwithDilithiumCreation() // create the CRL - version 2 // ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withECDSA").setProvider(BC).build(ecPriv); - ContentSigner altSigGen = new JcaContentSignerBuilder("Dilithium2").setProvider("BCPQC").build(dlPriv); + ContentSigner altSigGen = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(dlPriv); Date now = new Date(); @@ -3099,7 +3096,7 @@ public void checkCrlECDSAwithDilithiumCreation() crl.verify(ecPub, BC); isTrue("crl primary failed", crlHolder.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider(BC).build(ecPub))); - isTrue("crl secondary failed", crlHolder.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BCPQC").build(dlPub))); + isTrue("crl secondary failed", crlHolder.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(dlPub))); if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) { @@ -3622,9 +3619,9 @@ public void checkCreationSPHINCSPlus() // // set up the keys // - KeyPairGenerator kpg = KeyPairGenerator.getInstance("SPHINCSPlus", BC); + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", BC); - kpg.initialize(SPHINCSPlusParameterSpec.sha2_256s, new SecureRandom()); + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_256f, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); @@ -3675,7 +3672,7 @@ public void checkCreationSPHINCSPlusSimple() // KeyPairGenerator kpg = KeyPairGenerator.getInstance("SPHINCSPlus", BC); - kpg.initialize(SPHINCSPlusParameterSpec.sha2_256f, new SecureRandom()); + kpg.initialize(SPHINCSPlusParameterSpec.haraka_128f, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); @@ -3978,6 +3975,60 @@ public void checkCreationRSAPSS() isTrue(null == crt.getSubjectPublicKeyInfo().getAlgorithm().getParameters()); } + public void checkCreationNoSignature() + throws Exception + { + // + // set up the keys + // + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSASSA-PSS", BC); + + KeyPair kp = kpg.generateKeyPair(); + + PrivateKey privKey = kp.getPrivate(); + PublicKey pubKey = kp.getPublic(); + + // + // distinguished name table. + // + X500NameBuilder builder = createStdBuilder(); + + // + // create the certificate - version 3 + // + ContentSigner sigGen = new NoSignatureContentSigner(); + X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubKey); + + X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen)); + + cert.checkValidity(new Date()); + + // + // check fails on verify + // + try + { + cert.verify(pubKey); + fail("no exception"); + } + catch (InvalidKeyException e) + { + isEquals(e.getMessage(), "attempt to pass public key to NoSig"); + } + + // convert and check components. + ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); + CertificateFactory fact = CertificateFactory.getInstance("X.509", BC); + + cert = (X509Certificate)fact.generateCertificate(bIn); + + org.bouncycastle.asn1.x509.Certificate crt = org.bouncycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()); + + isTrue(new AlgorithmIdentifier(X509ObjectIdentifiers.id_alg_noSignature, DERNull.INSTANCE).equals(crt.getTBSCertificate().getSignature())); + isTrue(new AlgorithmIdentifier(X509ObjectIdentifiers.id_alg_noSignature, DERNull.INSTANCE).equals(crt.getSignatureAlgorithm())); + isTrue(0 == cert.getSignature().length); + } + /* * we generate a self signed certificate across the range of ECDSA algorithms */ @@ -4254,9 +4305,9 @@ public void checkCreationDilithium() Security.addProvider(new BouncyCastlePQCProvider()); } - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA-65", "BC"); - kpGen.initialize(DilithiumParameterSpec.dilithium2, new SecureRandom()); + kpGen.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom()); KeyPair kp = kpGen.generateKeyPair(); @@ -4271,7 +4322,7 @@ public void checkCreationDilithium() // // create base certificate - version 3 // - ContentSigner sigGen = new JcaContentSignerBuilder("Dilithium2").setProvider("BCPQC").build(privKey); + ContentSigner sigGen = new JcaContentSignerBuilder("ML-DSA-65").setProvider("BC").build(privKey); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), @@ -4286,7 +4337,7 @@ public void checkCreationDilithium() X509Certificate baseCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen)); - isTrue("oid wrong", BCObjectIdentifiers.dilithium2.getId().equals(baseCert.getSigAlgOID())); + isTrue("oid wrong", NISTObjectIdentifiers.id_ml_dsa_65.getId().equals(baseCert.getSigAlgOID())); isTrue("params wrong", null == baseCert.getSigAlgParams()); // @@ -4303,7 +4354,7 @@ public void checkCreationDilithium() cert.verify(cert.getPublicKey()); - isEquals("name mismatch: " + cert.getSigAlgName(), "DILITHIUM2", cert.getSigAlgName()); + isEquals("name mismatch: " + cert.getSigAlgName(), "ML-DSA-65", cert.getSigAlgName()); // check encoded works cert.getEncoded(); @@ -4430,14 +4481,9 @@ public void checkCreationDilithiumWithECDSA() public void checkCreationDilithiumSigWithECDSASig() throws Exception { - if (Security.getProvider("BCPQC") == null) - { - Security.addProvider(new BouncyCastlePQCProvider()); - } + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); - - kpGen.initialize(DilithiumParameterSpec.dilithium2, new SecureRandom()); + kpGen.initialize(MLDSAParameterSpec.ml_dsa_44, new SecureRandom()); KeyPair kp = kpGen.generateKeyPair(); @@ -4463,7 +4509,7 @@ public void checkCreationDilithiumSigWithECDSASig() // ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withECDSA").setProvider(BC).build(ecPrivKey); - ContentSigner altSigGen = new JcaContentSignerBuilder("Dilithium2").setProvider("BCPQC").build(privKey); + ContentSigner altSigGen = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(privKey); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( builder.build(), BigInteger.valueOf(1), @@ -4501,7 +4547,7 @@ public void checkCreationDilithiumSigWithECDSASig() isTrue("alt sig alg wrong", AltSignatureAlgorithm.fromExtensions(certHolder.getExtensions()).equals(altSigGen.getAlgorithmIdentifier())); isTrue("alt key wrong", SubjectAltPublicKeyInfo.fromExtensions(certHolder.getExtensions()).equals(ASN1Primitive.fromByteArray(pubKey.getEncoded()))); - isTrue("alt sig value wrong", certHolder.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BCPQC").build(pubKey))); + isTrue("alt sig value wrong", certHolder.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(pubKey))); } public void checkCreationComposite() @@ -5424,42 +5470,29 @@ private void checkSerialisation() // TESTS REGARDING COMPOSITES https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html private static String[] compositeSignaturesOIDs = { - "2.16.840.1.114027.80.8.1.1", //id-MLDSA44-RSA2048-PSS-SHA256 - "2.16.840.1.114027.80.8.1.2", //id-MLDSA44-RSA2048-PKCS15-SHA256 - "2.16.840.1.114027.80.8.1.3", //id-MLDSA44-Ed25519-SHA512 - "2.16.840.1.114027.80.8.1.4", //id-MLDSA44-ECDSA-P256-SHA256 - "2.16.840.1.114027.80.8.1.5", //id-MLDSA44-ECDSA-brainpoolP256r1-SHA256 - "2.16.840.1.114027.80.8.1.6", //id-MLDSA65-RSA3072-PSS-SHA512 - "2.16.840.1.114027.80.8.1.7", //id-MLDSA65-RSA3072-PKCS15-SHA512 - "2.16.840.1.114027.80.8.1.8", //id-MLDSA65-ECDSA-P256-SHA512 - "2.16.840.1.114027.80.8.1.9", //id-MLDSA65-ECDSA-brainpoolP256r1-SHA512 - "2.16.840.1.114027.80.8.1.10", //id-MLDSA65-Ed25519-SHA512 - "2.16.840.1.114027.80.8.1.11", //id-MLDSA87-ECDSA-P384-SHA512 - "2.16.840.1.114027.80.8.1.12", //id-MLDSA87-ECDSA-brainpoolP384r1-SHA512 - "2.16.840.1.114027.80.8.1.13", //id-MLDSA87-Ed448-SHA512 - // Falcon composites below were excluded from the draft. See MiscObjectIdentifiers for details. - "2.16.840.1.114027.80.8.1.14", //id-Falcon512-ECDSA-P256-SHA256 - "2.16.840.1.114027.80.8.1.15", //id-Falcon512-ECDSA-brainpoolP256r1-SHA256 - "2.16.840.1.114027.80.8.1.16", //id-Falcon512-Ed25519-SHA512 + "2.16.840.1.114027.80.8.1.21", //id-MLDSA44-RSA2048-PSS-SHA256 + "2.16.840.1.114027.80.8.1.22", //id-MLDSA44-RSA2048-PKCS15-SHA256 + "2.16.840.1.114027.80.8.1.23", //id-MLDSA44-Ed25519-SHA512 + "2.16.840.1.114027.80.8.1.24", //id-MLDSA44-ECDSA-P256-SHA256 + "2.16.840.1.114027.80.8.1.26", //id-MLDSA65-RSA3072-PSS-SHA512 + "2.16.840.1.114027.80.8.1.27", //id-MLDSA65-RSA3072-PKCS15-SHA512 + "2.16.840.1.114027.80.8.1.30", //id-MLDSA65-Ed25519-SHA512 + "2.16.840.1.114027.80.8.1.31", //id-MLDSA87-ECDSA-P384-SHA512 + "2.16.840.1.114027.80.8.1.32", //id-MLDSA87-ECDSA-brainpoolP384r1-SHA512 + "2.16.840.1.114027.80.8.1.33", //id-MLDSA87-Ed448-SHA512 }; private static String[] compositeSignaturesIDs = { "MLDSA44-RSA2048-PSS-SHA256", "MLDSA44-RSA2048-PKCS15-SHA256", "MLDSA44-ED25519-SHA512", - "MLDSA44-ECDSA-P256-SHA256", - "MLDSA44-ECDSA-BRAINPOOLP256R1-SHA256", - "MLDSA65-RSA3072-PSS-SHA512", - "MLDSA65-RSA3072-PKCS15-SHA512", - "MLDSA65-ECDSA-P256-SHA512", - "MLDSA65-ECDSA-BRAINPOOLP256R1-SHA512", + "MLDSA44-ECDSA-P256-SHA256", + "MLDSA65-RSA3072-PSS-SHA256", + "MLDSA65-RSA3072-PKCS15-SHA256", "MLDSA65-ED25519-SHA512", - "MLDSA87-ECDSA-P384-SHA512", - "MLDSA87-ECDSA-BRAINPOOLP384R1-SHA512", - "MLDSA87-ED448-SHA512", - "FALCON512-ECDSA-P256-SHA256", - "FALCON512-ECDSA-BRAINPOOLP256R1-SHA256", - "FALCON512-ED25519-SHA512" + "MLDSA87-ECDSA-P384-SHA384", + "MLDSA87-ECDSA-brainpoolP384r1-SHA384", + "MLDSA87-ED448-SHA512", }; private void checkCompositeSignatureCertificateCreation() @@ -5485,7 +5518,7 @@ private void checkCompositeSignatureCertificateCreation() isEquals(oid, cert.getSigAlgOID()); CompositePublicKey compositePublicKey = (CompositePublicKey)cert.getPublicKey(); - isEquals(CompositeSignaturesConstants.ASN1IdentifierAlgorithmNameMap.get(new ASN1ObjectIdentifier(oid)).getId(), compositePublicKey.getAlgorithm()); + // isEquals(CompositeSignaturesConstants.ASN1IdentifierAlgorithmNameMap.get(new ASN1ObjectIdentifier(oid)).getId(), compositePublicKey.getAlgorithm()); isEquals(subjectName, cert.getSubjectX500Principal().getName()); @@ -5496,68 +5529,70 @@ private void checkCompositeSignatureCertificateCreation() private void checkParseCompositePublicKey() { - try - { - //compositePublicKeyExampleRFC.pem contains the sample public key from https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html - PEMParser pemParser = new PEMParser(new InputStreamReader(TestResourceFinder.findTestResource("pqc/composite", "compositePublicKeyExampleRFC.pem"))); - SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo)pemParser.readObject(); - isEquals(subjectPublicKeyInfo.getAlgorithm().getAlgorithm(), MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); - - CompositePublicKey compositePublicKey = new CompositePublicKey(subjectPublicKeyInfo); - - isEquals(compositePublicKey.getPublicKeys().get(0).getAlgorithm(), "DILITHIUM2"); - isEquals(compositePublicKey.getPublicKeys().get(1).getAlgorithm(), "ECDSA"); - } - catch (Exception e) - { - fail("checkParseCompositePublicKey failed: " + e.getMessage()); - } +// try +// { +// //compositePublicKeyExampleRFC.pem contains the sample public key from https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html +// PEMParser pemParser = new PEMParser(new InputStreamReader(TestResourceFinder.findTestResource("pqc/composite", "compositePublicKeyExampleRFC.pem"))); +// SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo)pemParser.readObject(); +// isEquals(subjectPublicKeyInfo.getAlgorithm().getAlgorithm(), MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); +// +// CompositePublicKey compositePublicKey = new CompositePublicKey(subjectPublicKeyInfo); +// +// isEquals(compositePublicKey.getPublicKeys().get(0).getAlgorithm(), "ML-DSA-44"); +// isEquals(compositePublicKey.getPublicKeys().get(1).getAlgorithm(), "ECDSA"); +// } +// catch (Exception e) +// { +// fail("checkParseCompositePublicKey failed: " + e.getMessage()); +// } } - private void checkParseCompositePrivateKey() - { - try - { - //compositePrivateKeyExample.pem does NOT contain the sample private key from https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html - //because the at this moment, the Dilithium private key formats don't match. - //this sample was generated from this BC implementation - PEMParser pemParser = new PEMParser(new InputStreamReader(TestResourceFinder.findTestResource("pqc/composite", "compositePrivateKeyExample.pem"))); - PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo)pemParser.readObject(); - - isEquals(privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm(), MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); - - CompositePrivateKey compositePrivateKey = new CompositePrivateKey(privateKeyInfo); - - isEquals(compositePrivateKey.getPrivateKeys().get(0).getAlgorithm(), "DILITHIUM2"); - isEquals(compositePrivateKey.getPrivateKeys().get(1).getAlgorithm(), "ECDSA"); - } - catch (Exception e) - { - fail("checkParseCompositePrivateKey failed: " + e.getMessage()); - } - } + // TODO: OIDS no updated +// private void checkParseCompositePrivateKey() +// { +// try +// { +// //compositePrivateKeyExample.pem does NOT contain the sample private key from https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html +// //because the at this moment, the Dilithium private key formats don't match. +// //this sample was generated from this BC implementation +// PEMParser pemParser = new PEMParser(new InputStreamReader(TestResourceFinder.findTestResource("pqc/composite", "compositePrivateKeyExample.pem"))); +// PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo)pemParser.readObject(); +// +// isEquals(privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm(), MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); +// +// CompositePrivateKey compositePrivateKey = new CompositePrivateKey(privateKeyInfo); +// +// isEquals(compositePrivateKey.getPrivateKeys().get(0).getAlgorithm(), "DILITHIUM2"); +// isEquals(compositePrivateKey.getPrivateKeys().get(1).getAlgorithm(), "ECDSA"); +// } +// catch (Exception e) +// { +// fail("checkParseCompositePrivateKey failed: " + e.getMessage()); +// } +// } private void checkParseAndVerifyCompositeCertificate() { try { //compositeCertificateExampleRFC.pem contains the sample certificate from https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html - PEMParser pemParser = new PEMParser(new InputStreamReader(TestResourceFinder.findTestResource("pqc/composite", "compositeCertificateExampleRFC.pem"))); - X509CertificateHolder certificateHolder = (X509CertificateHolder)pemParser.readObject(); - JcaX509CertificateConverter x509Converter = new JcaX509CertificateConverter().setProvider("BC"); - X509Certificate certificate = x509Converter.getCertificate(certificateHolder); - - isEquals(certificate.getSigAlgOID(), MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256.toString()); - - CompositePublicKey compositePublicKey = (CompositePublicKey)certificate.getPublicKey(); - - isEquals(compositePublicKey.getPublicKeys().get(0).getAlgorithm(), "DILITHIUM2"); - isEquals(compositePublicKey.getPublicKeys().get(1).getAlgorithm(), "ECDSA"); +// PEMParser pemParser = new PEMParser(new InputStreamReader(TestResourceFinder.findTestResource("pqc/composite", "compositeCertificateExampleRFC.pem"))); +// X509CertificateHolder certificateHolder = (X509CertificateHolder)pemParser.readObject(); +// JcaX509CertificateConverter x509Converter = new JcaX509CertificateConverter().setProvider("BC"); +// X509Certificate certificate = x509Converter.getCertificate(certificateHolder); +// +// isEquals(certificate.getSigAlgOID(), MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256.toString()); +// +// CompositePublicKey compositePublicKey = (CompositePublicKey)certificate.getPublicKey(); +// +// isEquals(compositePublicKey.getPublicKeys().get(0).getAlgorithm(), "ML-DSA-44"); +// isEquals(compositePublicKey.getPublicKeys().get(1).getAlgorithm(), "ECDSA"); - certificate.verify(compositePublicKey); + // TODO: dilithium was used in the sample. + //certificate.verify(compositePublicKey); } catch (Exception e) - { + { e.printStackTrace(); fail("checkParseAndVerifyCompositeCertificate failed: " + e.getMessage()); } } @@ -5665,6 +5700,7 @@ public void performTest() checkCreationECDSA(); checkCreationRSA(); checkCreationRSAPSS(); + checkCreationNoSignature(); checkCreationFalcon(); checkCreationDilithium(); @@ -5713,7 +5749,7 @@ public void performTest() checkCompositeSignatureCertificateCreation(); checkParseCompositePublicKey(); - checkParseCompositePrivateKey(); +// checkParseCompositePrivateKey(); checkParseAndVerifyCompositeCertificate(); } diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/DeltaCertTest.java b/pkix/src/test/java/org/bouncycastle/cert/test/DeltaCertTest.java index 7a514b784f..23ef20ee95 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/test/DeltaCertTest.java +++ b/pkix/src/test/java/org/bouncycastle/cert/test/DeltaCertTest.java @@ -1,5 +1,6 @@ package org.bouncycastle.cert.test; +import java.io.InputStreamReader; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; @@ -9,16 +10,12 @@ import java.security.Security; import java.security.cert.X509Certificate; import java.util.Date; -import java.util.Enumeration; import junit.framework.TestCase; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.DeltaCertificateDescriptor; import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.SubjectAltPublicKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.cert.DeltaCertificateTool; @@ -27,257 +24,18 @@ import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; -import org.bouncycastle.pkcs.DeltaCertAttributeUtils; -import org.bouncycastle.pkcs.DeltaCertificateRequestAttributeValue; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; import org.bouncycastle.util.encoders.Base64; public class DeltaCertTest extends TestCase { - private static byte[] baseCertData = Base64.decode( - "MIIREzCCELigAwIBAgIUSq2wnmbyhuz2O1DahpLbE0N075owCgYIKoZIzj0EAwIw\n" + - "NTEzMDEGA1UEAwwqQkMgU0hBMjU2d2l0aEVDRFNBIFRlc3QgQ2hhbWVsZW9uIE91\n" + - "dGVyIFRBMB4XDTIzMDgzMDAwNDAxOVoXDTI0MDgyOTAwNDExOVowNTEzMDEGA1UE\n" + - "AwwqQkMgU0hBMjU2d2l0aEVDRFNBIFRlc3QgQ2hhbWVsZW9uIE91dGVyIFRBMFkw\n" + - "EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE9awTIuRdm93biCGi7O3DDopxiMa1lR0v\n" + - "qdFNmf7vrjlAsB5BKyTeFpxqLOLwJAbDIkr9O1o7HDgU7DOs+nFCKKOCD6Qwgg+g\n" + - "MBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMIIPeAYKYIZIAYb6\n" + - "a1AGAQSCD2gwgg9kAhRKrbCeZvKG7PY7UNqGktsTQ3TvmqANBgsrBgEEAQKCCwwE\n" + - "BKEyMDAxLjAsBgNVBAMMJUJDIERpbGl0aGl1bTIgVGVzdCBDaGFtZWxlb24gSW5u\n" + - "ZXIgVEGjMjAwMS4wLAYDVQQDDCVCQyBEaWxpdGhpdW0yIFRlc3QgQ2hhbWVsZW9u\n" + - "IElubmVyIFRBMIIFNDANBgsrBgEEAQKCCwwEBAOCBSEAsPv1ri6Gd2zXktq/CPlP\n" + - "cJbHy2Lra4mc/7PV5g0scKx3os5VS8RWZ7NrRjszXhKEU+uEAelmd6PuE2biKNv/\n" + - "iZMHaXqdLYYYBNhC4j8ppBu0rXaIEtNEsmv2oV8X8fbA2HU63/ctz6GHdOY57mlJ\n" + - "0l7cnyRCVmSofTGcLQjgjnfXhQeEvIqoDndyqbitSIsxyrnb46C3LbI5VElbuAOH\n" + - "VPLaMw2c09f3c5Ab4YmJwgVBomk0yeePDUxYdbVFWAvN+Ez/PX8sickVm/zeFzYD\n" + - "xQtwLl+CTCOIdiSn+dMEmM0fxrOUutHPVLoKqAxaTrSrKoe18o+ovj+tcNDBgd9I\n" + - "K9yWHg9aJQwMHhlyzbe6AMOz4jK54JCn/GpX66tRBhrNKDa/jmZm5pNO7hiw3UUk\n" + - "1OOy7mwMNuGJgMiMxi/Oh1zBtJnmJi+SvoNYEQrl/5P7hvM0oTalzLkRadIouGuy\n" + - "2fjgyPF5N8IO+OHoSrpOnKv0pBEN/JXZzDETRvz6FQigY07a2RFCWZ43886oDol/\n" + - "jSc2+z4IhMAb78Y+8gdZ08C25cle4xnZ00aEce9LOmu2SqvUEAt0doqOk9KxxOeq\n" + - "gqUUMPqn70LQVb7RxQq6yOfIuNyigJWQJdbh5IpeLzmJUd01oGYxzbX7EMFOsNRu\n" + - "nWisj9MxtuYb/QzyBCd23g0rXidcKmRXQnt1PUV6XAaHdH7LGPITivkIjAryY3Hu\n" + - "gwLt74CzcyBL4FsXEe2nU+zvwGINc1cYP9E76Qh/OTdZysphWsDWm3Q2CP2RS0oc\n" + - "I9eBboUwS+m7uV//nc+N+jfkTE0SaaFroZCYkmkmhVFMT2IatFBeDNXGyUp4EsyM\n" + - "SVMIlS3HAhly+AuYOseA6JHLCvvLwEcm34B9Lg/9LuKuYZ22gqLdE7JqyC1lQ5KQ\n" + - "waGb1vvmcGSQ8sRWDst6KjiXae7IKZbqTKUMQWf9GXxuCyHD7pHAIleFvvndsFq8\n" + - "sgxdsFnTM5JWD9uqzdICMxh/5EUCaPgiGfmCFCAd3KhuqjtXSeRP1X67pMvBVTZ4\n" + - "hF4JyNIvjb4L+VtByo20VuMijD6YNGJupI6eTBmYKsGcue6iVcPBgXgYnHFZHVM5\n" + - "Lt/TecoUIkqaZNIM8cWorSAnRe4WvPUvmgW+BbvTkFJoq8UlTtfu688Rd7qbfblQ\n" + - "pKW6m92tx9LnlaQBUoaGrq2CfFSERM0fSbxxJkKW7pcTzPoVsfUqqag9AiVA6Dmn\n" + - "7kpIWWI+NB1gZIj28O0aZcXxycmuKxWkQlNFe4OcS6mRobZzZRU61HPZka84SID8\n" + - "sDc4/a2foUk2MFgJLXuBJldq+N80/iCf1V6U60XdN68tH1PBkQzxfcC0EVkrudBu\n" + - "yNSlkB3ZIBM7qHyQKf+y9+WnNoAQuUXucUhbpRPobXXo7WQstCJ18TDJMLys8bDj\n" + - "X2EvPJgoqdsJXa4w9EKQHQdfkxLJC//8tgY4LwQTu9xGJ1s9zJIDW953dsmIZJxj\n" + - "xdzn7ePdS9QiT/ioVbwBrVaMkHQeJzGhKMrn9AJE4rO8C1XkEqbHk9N4h5E9XPjh\n" + - "82UM2/LOAwhyh/D1pVgPWKru5Xrkp5YTP5OnRWj3V45P2c2H5nA0thGx+JKdrTqW\n" + - "GQW/UlTKnN6eo2V9dK56chjRqYK72sU8VmoKO/2eroj5s21uMPXfiePJLWtOqBkz\n" + - "4N+KpkvvKCEBjlJJEq7mnxVemqtQ8QyadY+tCqkbeRLLdTLhsGtwL933B+vCYpy7\n" + - "6KQkMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGA4IJdQDn8Wf+\n" + - "2R9iyvWAzo6cjFGzkcNYPoTG1SCwCacMJVVKX5S8vf+zJjVuNX/7t5ckc/Swwp2J\n" + - "0x7bcIFiDFv8gR1PtT1jkR7Fo7s2vgomkIgtXVGwK6Q/GGZQ/UUpcnceIuAlVe88\n" + - "WS9otArc+ij5YTgsE9P9/49jPZAukn2T9XLaH9W30sEPpoPXVRcK2zlpkMmL3SHp\n" + - "Cg6bzt7GN6OLdJqioBtuKY0TAZcrVwJ0Sj8fnF5j1fnQ5qU4bP0QGrkWQNl2p2IZ\n" + - "340+PdYXYumPW0aU5KsQCcFnGz2TyoggUbKXyELj86rBTlzKrPlW2PQFZK9/FGfz\n" + - "YZ6dHszRbcbuyu3eaikoW53OMxbpCrl9dCNEdyE9lwtGz+DvgDk8NJeCvZbeNf9Q\n" + - "FaE65gOkG1DC46JCluChxa0hRNvxOK9P+M8tijz9JlsKlbtkSjpqWnUPoMdjAnJ0\n" + - "+iN6kr7LVOW6mppErnazK5hmFiGPu3P8KvqWKaAR+71161S+tuPENWbKDyq4U1wg\n" + - "Em3xgppCTGb6BHhGT+55oUr8syLHjk60rC9CsdZfdY4RhYtIKVjL8SUhLMELwK6R\n" + - "Dq9RUiu6sJP8Z8XZEvnQ/y720lVVuA/7BKGB+y4+B//HUk+OLhGx7W7aF78aPSa9\n" + - "ZwMPEaTv6bDPdSY/yKxlTCPGKbDU+RAepzk8GOw9g6Ku8MPZUH9BSjm5xRI/Qztl\n" + - "xWN7MHlQaCSTlFpAPZEZU/v2VaXnAxRsxbYfIWxAjNUImE4L51u58juR97H/Fb7r\n" + - "jfaM8M5jLfBQvSKHER7zvSHVBHcNTzBUsXdT3zAw/XbKwPwYOT+LCxqGaksKVVBV\n" + - "MgAIWBVvPkX8rwSCDNHMH6U1AtadSF6WT4Lsz272l8ihfZ8py0QHBVtPvjySB+yA\n" + - "Jwwcv2/DL9EO8ozBxyJDPhTTAmqYHNgPwZ8TpzhjfF3eKPOmNbTySNG8osrKONtJ\n" + - "+2l2RpicqeuQg3q3CF362DyGSywrxkPkx4j/JObA7o0ZQPZQ6IddVaA3jMBA3lNq\n" + - "YkuXgZ1NSH94F1TtoKrhd+50EtjrypK43kRwvVsWkXzpbhpzSEoTZQSbQjH0y/9+\n" + - "ceBOTr2v5TdxXkEiceTto99QfutB1yhhVo/3V8lkmcFX03A8sOFtPaeWOyIpje12\n" + - "P4v+fuRfolNYynEUTxyoHlohMwL9hwINqKT7IcIu/40N2guerUUDkS6AJdQ/Cpgt\n" + - "8ojDki61EgvFRQm32WuN66Pp+DADM0vqNyXw9ZWtoM79lWrnRApuyJQ7YnNFWEe7\n" + - "nclgNBqXEafaF2eRENGZg1VxruRGRgpa8Oj0Y1lJ9e6JGVi0uGyFDIM3bttuxs1e\n" + - "6li+j6MB65aCk6bfX79Binzf6xjCQ3jSZXlfqj4aIpcPgzVNmSz8951/5QSnGWLm\n" + - "ke4muuEUrz23g29+zEBHJ8Lnz2TF8Dnu7M0AvsgnPc02qO1H7tr+58uydeVvgGqE\n" + - "RJv0Gdfb7wqqvw91DK+gVrfj8G5Jr52D7NANA7H6sq28lAxVDBDfIjbjqz1+cQai\n" + - "79O9l7NNPoz38YvCnHJke9HGSX1s6X717DSpptYn7hZ6NBZVwGDAglPhDlx0MkbQ\n" + - "uUs1pZ62SGCq50MImOq//lh2wDhAx32E0M5SMEHUSyHiWm9SLDx09sTZ1kiP0dXQ\n" + - "BcDI6obBu0Y7/2GMN7gYkoKxL2+WNqSrxni+aCLNhyAlAJsr/5aAEqlWpWLQrFyB\n" + - "WNPxCpj3+tm06kUTtrSqgHp6vclXkbPefTJuDP9losLG1DYu6n6Ylp5tVgEOi9mI\n" + - "rJdMpRd6c0h8bZThTxCosR6230iKwBbfW3NEAurrALd7vEMrINCxia4yWCpH1v1t\n" + - "wSdF1cuugzMr16MyBlUTJVf6jf5hTo44TzR+tGOAON+rNNJms9s61Ia/ZSDQqy+W\n" + - "zIKucLvKUiAECoqLpMn1ZYAfg2iUjdVc6MiJAQh6bIVXzmTqH2RtIXMg9dOl7iLO\n" + - "a5xgyH0kjrFPUt0ObOCLuF6RnL97XHwONEXskfAmK6qJOsFJnauYkxAHoQlz4xyY\n" + - "mTDbcLH52T/jOD7o7t5FvxMZbu1DT8NYwnoVpC9YSDUWxGJUNX20ISFcGUJmHFWw\n" + - "7anRgfyQ1hTlMncbaDpOepP9xMh6oVmDr+QT3KUjKGePMIKXhuTSrwczRAafnkp/\n" + - "WxYxKWLGM30FJyAvf1o9Jk+jIFAXwXyeaCnHeCxtZbOO+oxug4oRipMMqE0IeG1a\n" + - "fe1wZNwg6F6H7RHjayubHZZQLkQ5lsT0EX8o5FpzzfpuDFTQlWx9R3XIYZLJsIAE\n" + - "8zDt5nV5N0ZepX2AURo0cW+fR0mn2aK3AqvApL9m3mgCtRR2NfVZCAXw3Wc+BmSl\n" + - "rLAZH5Y2Lxmxi0m6q8AL6HPnVp/+LjlHhhnl8ZWTVdN7nDN5m+cnemR/LMv9IEZ9\n" + - "3Jp4i5B0OD7p1rpYFAp0Ae/EPu1LQxn3htGNuBXTUq6zU723uVMjHaoX9IIUSg/W\n" + - "1BgW9HnCgyafWn97m/IVUDFVvCVxI1m6ohLSeiY2/y7MvEsgJzotnXk21VsZBxxs\n" + - "eIS3mqWCfbcH1R/8hLvDeulWgkz1rUHoYyZsBfBe2MpfYapkp2kwj/JCQ2Bse7bW\n" + - "lI6cQJDjta3/fAqmCW6xrU5THGSCaoFnpLVx2Ya74XsywaKnXGFPBAcanFOm0/3n\n" + - "JW5jYLorvjDYhoMcK4iUG4b58hZZckStm5ZrPsx4oJ8Fhk6IljrQVbFci0HPz74+\n" + - "JnNDDif1yTVGQ8Mp4zwtj7yCVJWnkxvXOxy0T3GPFNlOPXlMcq0Waw2c50SgPOQk\n" + - "upIuizdkXdB5IU89F76pKuW+cH71fn5qkOclVp99lcXfSsxBwBGO5iEc4+mjibYv\n" + - "3DLoCLj/WnH3IHTx7l6809pxa7eFr1YkU+X36OJGs9sHUX5ohlE+LJHA1qfS5SRm\n" + - "srbT93DNJlfgKXRY7vDwl1Ng253cqoytLg77LXl9R+yFn5C3DTFfXuiIBVI/it5Q\n" + - "xiBmQ7++8vHJjr9nk41dlG/GFSOq2Yzc0at75O8VkJvY84PkhbdHrX+ZovCIU62q\n" + - "qYX2tCcwch6qRNaIovJf5t89jyIbdyWBIjM+IgABCi82QE2QmJvLztbm5wQiKDlN\n" + - "T151dnh+f4mcsgkfIEBRW2tudHeLjLXI8vr/CCQtNjg8Ql1qa2yNrrPD2ODo/wAA\n" + - "AAAAAAAAAAAAAAAADx4vQjAKBggqhkjOPQQDAgNJADBGAiEA8LEHD5VbzlvCpRvi\n" + - "rZ3JDSHcUEFHI3GeeOOhMN6isdACIQDPvRrMrkhjfT0SXlwnCShrK9QjnLjSAIIL\n" + - "j7Gi9ZksbQ=="); - - private static byte[] extracted = Base64.decode( - "MIIPmjCCBg6gAwIBAgIUSq2wnmbyhuz2O1DahpLbE0N075owDQYLKwYBBAECggsMBAQw" + - "MDEuMCwGA1UEAwwlQkMgRGlsaXRoaXVtMiBUZXN0IENoYW1lbGVvbiBJbm5lciBUQT" + - "AeFw0yMzA4MzAwMDQwMTlaFw0yNDA4MjkwMDQxMTlaMDAxLjAsBgNVBAMMJUJDIERp" + - "bGl0aGl1bTIgVGVzdCBDaGFtZWxlb24gSW5uZXIgVEEwggU0MA0GCysGAQQBAoILDA" + - "QEA4IFIQCw+/WuLoZ3bNeS2r8I+U9wlsfLYutriZz/s9XmDSxwrHeizlVLxFZns2tG" + - "OzNeEoRT64QB6WZ3o+4TZuIo2/+Jkwdpep0thhgE2ELiPymkG7StdogS00Sya/ahXx" + - "fx9sDYdTrf9y3PoYd05jnuaUnSXtyfJEJWZKh9MZwtCOCOd9eFB4S8iqgOd3KpuK1I" + - "izHKudvjoLctsjlUSVu4A4dU8tozDZzT1/dzkBvhiYnCBUGiaTTJ548NTFh1tUVYC8" + - "34TP89fyyJyRWb/N4XNgPFC3AuX4JMI4h2JKf50wSYzR/Gs5S60c9UugqoDFpOtKsq" + - "h7Xyj6i+P61w0MGB30gr3JYeD1olDAweGXLNt7oAw7PiMrngkKf8alfrq1EGGs0oNr" + - "+OZmbmk07uGLDdRSTU47LubAw24YmAyIzGL86HXMG0meYmL5K+g1gRCuX/k/uG8zSh" + - "NqXMuRFp0ii4a7LZ+ODI8Xk3wg744ehKuk6cq/SkEQ38ldnMMRNG/PoVCKBjTtrZEU" + - "JZnjfzzqgOiX+NJzb7PgiEwBvvxj7yB1nTwLblyV7jGdnTRoRx70s6a7ZKq9QQC3R2" + - "io6T0rHE56qCpRQw+qfvQtBVvtHFCrrI58i43KKAlZAl1uHkil4vOYlR3TWgZjHNtf" + - "sQwU6w1G6daKyP0zG25hv9DPIEJ3beDSteJ1wqZFdCe3U9RXpcBod0fssY8hOK+QiM" + - "CvJjce6DAu3vgLNzIEvgWxcR7adT7O/AYg1zVxg/0TvpCH85N1nKymFawNabdDYI/Z" + - "FLShwj14FuhTBL6bu5X/+dz436N+RMTRJpoWuhkJiSaSaFUUxPYhq0UF4M1cbJSngS" + - "zIxJUwiVLccCGXL4C5g6x4DokcsK+8vARybfgH0uD/0u4q5hnbaCot0TsmrILWVDkp" + - "DBoZvW++ZwZJDyxFYOy3oqOJdp7sgplupMpQxBZ/0ZfG4LIcPukcAiV4W++d2wWryy" + - "DF2wWdMzklYP26rN0gIzGH/kRQJo+CIZ+YIUIB3cqG6qO1dJ5E/Vfruky8FVNniEXg" + - "nI0i+Nvgv5W0HKjbRW4yKMPpg0Ym6kjp5MGZgqwZy57qJVw8GBeBiccVkdUzku39N5" + - "yhQiSppk0gzxxaitICdF7ha89S+aBb4Fu9OQUmirxSVO1+7rzxF3upt9uVCkpbqb3a" + - "3H0ueVpAFShoaurYJ8VIREzR9JvHEmQpbulxPM+hWx9SqpqD0CJUDoOafuSkhZYj40" + - "HWBkiPbw7RplxfHJya4rFaRCU0V7g5xLqZGhtnNlFTrUc9mRrzhIgPywNzj9rZ+hST" + - "YwWAkte4EmV2r43zT+IJ/VXpTrRd03ry0fU8GRDPF9wLQRWSu50G7I1KWQHdkgEzuo" + - "fJAp/7L35ac2gBC5Re5xSFulE+htdejtZCy0InXxMMkwvKzxsONfYS88mCip2wldrj" + - "D0QpAdB1+TEskL//y2BjgvBBO73EYnWz3MkgNb3nd2yYhknGPF3Oft491L1CJP+KhV" + - "vAGtVoyQdB4nMaEoyuf0AkTis7wLVeQSpseT03iHkT1c+OHzZQzb8s4DCHKH8PWlWA" + - "9Yqu7leuSnlhM/k6dFaPdXjk/ZzYfmcDS2EbH4kp2tOpYZBb9SVMqc3p6jZX10rnpy" + - "GNGpgrvaxTxWago7/Z6uiPmzbW4w9d+J48kta06oGTPg34qmS+8oIQGOUkkSruafFV" + - "6aq1DxDJp1j60KqRt5Est1MuGwa3Av3fcH68JinLvooyYwJDASBgNVHRMBAf8ECDAG" + - "AQH/AgEAMA4GA1UdDwEB/wQEAwIBBjANBgsrBgEEAQKCCwwEBAOCCXUA5/Fn/tkfYs" + - "r1gM6OnIxRs5HDWD6ExtUgsAmnDCVVSl+UvL3/syY1bjV/+7eXJHP0sMKdidMe23CB" + - "Ygxb/IEdT7U9Y5EexaO7Nr4KJpCILV1RsCukPxhmUP1FKXJ3HiLgJVXvPFkvaLQK3P" + - "oo+WE4LBPT/f+PYz2QLpJ9k/Vy2h/Vt9LBD6aD11UXCts5aZDJi90h6QoOm87exjej" + - "i3SaoqAbbimNEwGXK1cCdEo/H5xeY9X50OalOGz9EBq5FkDZdqdiGd+NPj3WF2Lpj1" + - "tGlOSrEAnBZxs9k8qIIFGyl8hC4/OqwU5cyqz5Vtj0BWSvfxRn82GenR7M0W3G7srt" + - "3mopKFudzjMW6Qq5fXQjRHchPZcLRs/g74A5PDSXgr2W3jX/UBWhOuYDpBtQwuOiQp" + - "bgocWtIUTb8TivT/jPLYo8/SZbCpW7ZEo6alp1D6DHYwJydPojepK+y1TlupqaRK52" + - "syuYZhYhj7tz/Cr6limgEfu9detUvrbjxDVmyg8quFNcIBJt8YKaQkxm+gR4Rk/uea" + - "FK/LMix45OtKwvQrHWX3WOEYWLSClYy/ElISzBC8CukQ6vUVIrurCT/GfF2RL50P8u" + - "9tJVVbgP+wShgfsuPgf/x1JPji4Rse1u2he/Gj0mvWcDDxGk7+mwz3UmP8isZUwjxi" + - "mw1PkQHqc5PBjsPYOirvDD2VB/QUo5ucUSP0M7ZcVjezB5UGgkk5RaQD2RGVP79lWl" + - "5wMUbMW2HyFsQIzVCJhOC+dbufI7kfex/xW+6432jPDOYy3wUL0ihxEe870h1QR3DU" + - "8wVLF3U98wMP12ysD8GDk/iwsahmpLClVQVTIACFgVbz5F/K8EggzRzB+lNQLWnUhe" + - "lk+C7M9u9pfIoX2fKctEBwVbT748kgfsgCcMHL9vwy/RDvKMwcciQz4U0wJqmBzYD8" + - "GfE6c4Y3xd3ijzpjW08kjRvKLKyjjbSftpdkaYnKnrkIN6twhd+tg8hkssK8ZD5MeI" + - "/yTmwO6NGUD2UOiHXVWgN4zAQN5TamJLl4GdTUh/eBdU7aCq4XfudBLY68qSuN5EcL" + - "1bFpF86W4ac0hKE2UEm0Ix9Mv/fnHgTk69r+U3cV5BInHk7aPfUH7rQdcoYVaP91fJ" + - "ZJnBV9NwPLDhbT2nljsiKY3tdj+L/n7kX6JTWMpxFE8cqB5aITMC/YcCDaik+yHCLv" + - "+NDdoLnq1FA5EugCXUPwqYLfKIw5IutRILxUUJt9lrjeuj6fgwAzNL6jcl8PWVraDO" + - "/ZVq50QKbsiUO2JzRVhHu53JYDQalxGn2hdnkRDRmYNVca7kRkYKWvDo9GNZSfXuiR" + - "lYtLhshQyDN27bbsbNXupYvo+jAeuWgpOm31+/QYp83+sYwkN40mV5X6o+GiKXD4M1" + - "TZks/Pedf+UEpxli5pHuJrrhFK89t4NvfsxARyfC589kxfA57uzNAL7IJz3NNqjtR+" + - "7a/ufLsnXlb4BqhESb9BnX2+8Kqr8PdQyvoFa34/BuSa+dg+zQDQOx+rKtvJQMVQwQ" + - "3yI246s9fnEGou/TvZezTT6M9/GLwpxyZHvRxkl9bOl+9ew0qabWJ+4WejQWVcBgwI" + - "JT4Q5cdDJG0LlLNaWetkhgqudDCJjqv/5YdsA4QMd9hNDOUjBB1Esh4lpvUiw8dPbE" + - "2dZIj9HV0AXAyOqGwbtGO/9hjDe4GJKCsS9vljakq8Z4vmgizYcgJQCbK/+WgBKpVq" + - "Vi0KxcgVjT8QqY9/rZtOpFE7a0qoB6er3JV5Gz3n0ybgz/ZaLCxtQ2Lup+mJaebVYB" + - "DovZiKyXTKUXenNIfG2U4U8QqLEett9IisAW31tzRALq6wC3e7xDKyDQsYmuMlgqR9" + - "b9bcEnRdXLroMzK9ejMgZVEyVX+o3+YU6OOE80frRjgDjfqzTSZrPbOtSGv2Ug0Ksv" + - "lsyCrnC7ylIgBAqKi6TJ9WWAH4NolI3VXOjIiQEIemyFV85k6h9kbSFzIPXTpe4izm" + - "ucYMh9JI6xT1LdDmzgi7hekZy/e1x8DjRF7JHwJiuqiTrBSZ2rmJMQB6EJc+McmJkw" + - "23Cx+dk/4zg+6O7eRb8TGW7tQ0/DWMJ6FaQvWEg1FsRiVDV9tCEhXBlCZhxVsO2p0Y" + - "H8kNYU5TJ3G2g6TnqT/cTIeqFZg6/kE9ylIyhnjzCCl4bk0q8HM0QGn55Kf1sWMSli" + - "xjN9BScgL39aPSZPoyBQF8F8nmgpx3gsbWWzjvqMboOKEYqTDKhNCHhtWn3tcGTcIO" + - "heh+0R42srmx2WUC5EOZbE9BF/KORac836bgxU0JVsfUd1yGGSybCABPMw7eZ1eTdG" + - "XqV9gFEaNHFvn0dJp9mitwKrwKS/Zt5oArUUdjX1WQgF8N1nPgZkpaywGR+WNi8ZsY" + - "tJuqvAC+hz51af/i45R4YZ5fGVk1XTe5wzeZvnJ3pkfyzL/SBGfdyaeIuQdDg+6da6" + - "WBQKdAHvxD7tS0MZ94bRjbgV01Kus1O9t7lTIx2qF/SCFEoP1tQYFvR5woMmn1p/e5" + - "vyFVAxVbwlcSNZuqIS0nomNv8uzLxLICc6LZ15NtVbGQccbHiEt5qlgn23B9Uf/IS7" + - "w3rpVoJM9a1B6GMmbAXwXtjKX2GqZKdpMI/yQkNgbHu21pSOnECQ47Wt/3wKpglusa" + - "1OUxxkgmqBZ6S1cdmGu+F7MsGip1xhTwQHGpxTptP95yVuY2C6K74w2IaDHCuIlBuG" + - "+fIWWXJErZuWaz7MeKCfBYZOiJY60FWxXItBz8++PiZzQw4n9ck1RkPDKeM8LY+8gl" + - "SVp5Mb1zsctE9xjxTZTj15THKtFmsNnOdEoDzkJLqSLos3ZF3QeSFPPRe+qSrlvnB+" + - "9X5+apDnJVaffZXF30rMQcARjuYhHOPpo4m2L9wy6Ai4/1px9yB08e5evNPacWu3ha" + - "9WJFPl9+jiRrPbB1F+aIZRPiyRwNan0uUkZrK20/dwzSZX4Cl0WO7w8JdTYNud3KqM" + - "rS4O+y15fUfshZ+Qtw0xX17oiAVSP4reUMYgZkO/vvLxyY6/Z5ONXZRvxhUjqtmM3N" + - "Gre+TvFZCb2POD5IW3R61/maLwiFOtqqmF9rQnMHIeqkTWiKLyX+bfPY8iG3clgSIz" + - "PiIAAQovNkBNkJiby87W5ucEIig5TU9edXZ4fn+JnLIJHyBAUVtrbnR3i4y1yPL6/w" + - "gkLTY4PEJdamtsja6zw9jg6P8AAAAAAAAAAAAAAAAAAA8eL0I=" - ); - - - private static byte[] rsa_ec_cert = Base64.decode( - "MIIFKzCCBBOgAwIBAgIIaLtn+ZoOPkAwDQYJKoZIhvcNAQELBQAwMTELMAkGA1UE\n" + - "\n" + - "BhMCY2ExCzAJBgNVBAsTAkNUMRUwEwYDVQQDEwxKb2huIEdyYXkgQ0EwHhcNMjMw\n" + - "\n" + - "NTIzMjI1MTU0WhcNMjQwNTIzMDA1MTU0WjAxMQswCQYDVQQGEwJjYTELMAkGA1UE\n" + - "\n" + - "CxMCQ1QxFTATBgNVBAMTDEpvaG4gR3JheSBDQTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + - "\n" + - "ggEPADCCAQoCggEBAPTegns+vTNALyCqUhWCAe22B1hDi63F4orq48sgQDl98zLd\n" + - "\n" + - "xrr4BwpJ3Q+9y8f2SiRjH7rjMo8+Ry/o0H+etSzYi/7nf8sffc2+w3cVRzYd3GBV\n" + - "\n" + - "bXaFb+7OP0AlBS6lc2w4j7zm6thV2hz9L7XKEEt8O8MHCttbODVGXGihb3Dvw0XV\n" + - "\n" + - "UEDarspb4/zN1eKhK+6uZLyl+WkdX3Pev2RDbUH/Mz990YCpC5eWozDpA0NxgOP8\n" + - "\n" + - "RDxkBwx2TuUYwB2oCmyVsZ6vaGVCSL2kSWjdBVM6f60LgyMvneanx+PET5IX/znH\n" + - "\n" + - "+NQoiJz3Hb82KuPZLg+L/CIG0DiDEYJvD1yYY/UCAwEAAaOCAkUwggJBMBEGCWCG\n" + - "\n" + - "SAGG+EIBAQQEAwIABzBOBgNVHR8ERzBFMEOgQaA/pD0wOzELMAkGA1UEBhMCY2Ex\n" + - "\n" + - "EDAOBgNVBAoTB2VudHJ1c3QxCzAJBgNVBAMTAmNhMQ0wCwYDVQQDEwRDUkwxMCsG\n" + - "\n" + - "A1UdEAQkMCKADzIwMDkwNzA3MTg0NzU4WoEPMjAzNDA3MDcxOTE3NThaMAsGA1Ud\n" + - "\n" + - "DwQEAwIBBjAfBgNVHSMEGDAWgBSLhHJw3CWoK6tG+vDHA4+A3WZQfTAdBgNVHQ4E\n" + - "\n" + - "FgQUi4RycNwlqCurRvrwxwOPgN1mUH0wDAYDVR0TBAUwAwEB/zAdBgkqhkiG9n0H\n" + - "\n" + - "QQAEEDAOGwhWOC4wOjQuMAMCBJAwggEzBgpghkgBhvprUAYBBIIBIzCCAR8CCC8r\n" + - "\n" + - "86yn2wm8oAwGCCqGSM49BAMCBQCiHhcNMjMwNTIzMjI1MTU1WhcNMjQwNTIzMDA1\n" + - "\n" + - "MTU1WjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABENMAU79zHGMdY7BrUcoi10Y\n" + - "\n" + - "2v9yGwq6rF/el0HFrAVIW1f9GfPZZQI5OJnqf60/X2IRc4KecyfqiVjkD3GEWJyk\n" + - "\n" + - "QDAfBgNVHSMEGDAWgBTWuDKUFK1U61Y5aP6Gm9/hU/81LDAdBgNVHQ4EFgQU1rgy\n" + - "\n" + - "lBStVOtWOWj+hpvf4VP/NSwDSAAwRQIgH6haXFeIfy+TOPWFEsxfFzehVcQAy4NL\n" + - "\n" + - "gH1wiKp61ecCIQDGD0NqMadMAnrfIy8MiH6kkZ0LEKDVpbh3k1CvaXVB+jANBgkq\n" + - "\n" + - "hkiG9w0BAQsFAAOCAQEATtjhu3Yuy8mw0FIbvxm8LwE18OAb4De7XZXBBQrHHlA5\n" + - "\n" + - "HNkvcPPba7171LcpIZx/SW4C5sIxfwn0rFZ8uTUKdiQSmmqfwH1t2NZ1fF+oADF3\n" + - "\n" + - "goxuxEYHczqVUYSugllqMJx0T/7HgD3JEd3DOYrk4k2ksE557xVwEm5OBBNTiz0/\n" + - "\n" + - "2M72GRsSbma2xo6tFiQ6iYfI3B2NgW0jekN9wOlF7p+SZFeq1afSEDrfVSi0DkVQ\n" + - "\n" + - "zyn7PMrrZgyYpjWr1GpnvNBcZDEpH7TML9GUxchn31w0FvaLMMgYJJ2ha2ohPQxV\n" + - "\n" + - "tV9dNL7ivNP74nJQqT1x05vXhjrL86VOlwxa385geA=="); - private static byte[] deltaCertReq = Base64.decode( "MIIP2zCCD4ACAQAwDzENMAsGA1UEAwwEVGVzdDBZMBMGByqGSM49AgEGCCqGSM49\n" + "AwEHA0IABEqIRHVQv5GkHTHTBzPZFAiCVbMB8h+uTZ1gV58O2rnCBn4YNqpIj8j0\n" + @@ -365,434 +123,116 @@ public class DeltaCertTest "PQQDAgNJADBGAiEA8Yi24L05Pkn0y6Umltpd6Hhw/TyFzB7SmaEEEcn9+iYCIQCA\n" + "ahofKFqOtfmLrzh+a8VCq30wqdJhqf+imN28KcziNA=="); - private static byte[] draft_dilithium_root = Base64.decode( - "MIIZTzCCDFqgAwIBAgIUONT0zs5OI1dwa7N+gcOBNTQEwSAwDQYLKwYBBAECggsH\n" + - "BgUwgY8xCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2Yg\n" + - "UHVibGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1\n" + - "bXAgUmVzZWFyY2ggRGVwYXJ0bWVudDEcMBoGA1UEAwwTRGlsaXRoaXVtIFJvb3Qg\n" + - "LSBHMTAeFw0yMzA1MjUxNjUxMzhaFw0zMzA1MTIxNjUxMzhaMIGPMQswCQYDVQQG\n" + - "EwJYWDE1MDMGA1UECgwsUm95YWwgSW5zdGl0dXRlIG9mIFB1YmxpYyBLZXkgSW5m\n" + - "cmFzdHJ1Y3R1cmUxKzApBgNVBAsMIlBvc3QtSGVmZmFsdW1wIFJlc2VhcmNoIERl\n" + - "cGFydG1lbnQxHDAaBgNVBAMME0RpbGl0aGl1bSBSb290IC0gRzEwgge0MA0GCysG\n" + - "AQQBAoILBwYFA4IHoQBxNIVkcLajfd6f/9uOqGfiWPTxem6oTmbQ5N0TOS/j0tfI\n" + - "qxjz2CW2h5wcbs4UYc4KylsmNbhy+lo/3s0jbRmOOPuBVmv8dG8NmDty2ZWK5m3Y\n" + - "hJIaujOAYSNfzRPax/7pDX4+oDL0zfO0i6S71BmBzcamX/11WxdI9okKN3Z7NQns\n" + - "CMmfBtWab1POC/eoRwQ4+Sk39xpp2NPlSEeLVoQtgdLvmc0DNL87Gcoao2YfxXbf\n" + - "Gyx/HsKbi03o7/nmLuT0LvTe0YhQ1dE5c1fxCVQHUeXFwyW10TyHfZMK+0mT77ig\n" + - "NSfsUeHMEjqNPNhO94QLds26awaJAbnZDR9LJQ//TvI91FlwruBxnZtp0+2DR6jN\n" + - "4lTIuaKjEX+HzxZe6k+jjg35erc3PEXNH3+kzIEWHgjYmANftoI4wulK9FOf7RVD\n" + - "6k/G1/vIupQUZQ7brIVbWsevwUWgxpxNs0+noedA02nLjjqZhkM1bIqOt8AKZJgX\n" + - "5ie6btnrkMMUFocxG5yvuO4fn7rreWv2T/S+kmKGou7scEyUowwjYv4t3sgFw0tN\n" + - "4iK6htNyNo/9jX1Tei9QUibhlcqcMkVw6dGZAGSxdAvH0hD5NXi/dweENCaOGCPn\n" + - "9Wza/g44TnLpXLH97U47tC0Gg2+do8jspmBBu3CQ6i51qJUE5vJxUCmlZy44PRXc\n" + - "E9K8VUwtlma44yyfGmg9tZdWwZggt+gv+PION2T35HGzA5Nih7zCRK8knn4yhKoR\n" + - "0H4IV0f5JrtoS1QlqTkaCJ5cv7I71hPPjQ3Ghtq3pudHDL/taFUApcgcaIsHQTPO\n" + - "Sicp5/yW6+8xjEwiW3p//XYlrB6tsLkSXAz5UyxiIjwdgnZra/225ORg2a+bvfHb\n" + - "wEircmGzVQEAqem+60l+J44slM1pR+tWSKi/AUPHl2yK7W83/uz4uZmYrqO1GWCc\n" + - "2cb7va/nWPCKFEcX3JbBXpT9Xvyy1VFDf8WV6CxRgIk3E7ZxK04hLnTRCYNLuTc4\n" + - "Bp3Io6nWmE0VgJs+jl/n5kcimU76p7s3YfnF9TOCtoQbrfIRX2FhBFsOeKZsbMDQ\n" + - "zlsBZroMOAQ+cr+UwohSYX+yXKKK1ARPFFYdyYgLaOYzYB5pFr1BeM4fQrCoF7EV\n" + - "PvWvYcaeoBQ0y7mpGVsKbPsp2EIZUIt/HY519acbHjkbIoAgTijBKBZuXbHOm5xj\n" + - "58bvUeZt9k61U/c+AzJc7NnNf3HfHEBaXhvT5pm4GiVoFKmQZ9v8kIRNhuJ/ZGu5\n" + - "Jhw7s/E/kznehECO8/iKn/gwoNiBCHWdyYrokv08G7XzMVunma9EvZCYY0O6bZiq\n" + - "n2r0m7rvhMLkLHTrzGm9Ar6W0aXBwm03yeFo+zQIBr4AdNWXpy2Tt4NJYa4iIW5x\n" + - "RuIyA6yDiPICBrT0VAWadtalLNf+t2ZUgAB7QPX7Ixh5gUBlBRa6EUqCvQ05GzZP\n" + - "o689fzDqej+HQcRO0mU9QELnD6GsvA/+FWPaI0Cx0ONN/fpq8F7/GscTQkxWocEp\n" + - "nWgWnqGh2k7rIoPBSzZ4MRG9bqeYJkQrUv+Ky8gwnRD3sUTWs3DZgVKvhd2X8PRz\n" + - "Q5Dmqv8XIcY7mpR5nBDdY4O6z7jc8pblnJsjWNBd/mx5j2DRlH9mF1z8pACIXYNY\n" + - "/YJ5him7ZN8M0Wk9q/Dp1HK40EQMfRjg3budcRpg9a+sUMeq7cljfPaw/RPv06Lx\n" + - "rtbege1o6va0AE0s9QUrPRUS46H+VmQmth/QW8+P0MDEGyPsOh92NUprbQmgVTf/\n" + - "hACbb6sMeLEx3Kw0mndUz8PieOdt2d05RkfGE9SXjMLLV27NMRUocd9x4wCj2j7J\n" + - "2kNp8ujQIg/CoYdVa5pEdmG7FlD4UBnRsoPjCgX6vC2Lnjl5y+AXtWzrQ4d6LSnI\n" + - "dZpH+5kRPssNtIRdm70jZgRq+KDYWQwvKbu5+5lXdQn2Fodgj96cQJbFfKlC9kfh\n" + - "efykwuSn8uE8bYRwegx32px9UkeDhaPwUcLF6OC0OGgpbxyfbcqhdWhGGvTFhh3G\n" + - "oZrm8ssBJDiiLA6azYJs2pCh9CG43CCRoB+DwS4c6xLkCWU779Pi8gIovpUQBwUx\n" + - "EdQu/d1GTN9J6Vy36ZEoc7KIiddC5sH+CHxju+LX2IIv2OzqLwFiwH6r+7NQ378z\n" + - "aCOMMBTNMEQsyauJS1vfLkl/mnHyxVYpbwi9NoJCfAnUZntsEEP1mn7G3S4+IPYe\n" + - "Qy7hBUQamFs3uT7xaOcbnoiHvlQ1rm88HrohWtVQV4FmODrKHut4meBLUdV/ZVIC\n" + - "acel/kmq/767H28n8PaKiQOrXnPSpwpXxeKKtO+aMdvFhL9ytVOh3JTdX7y2rO6m\n" + - "XmauwfpcEWh1P04kCSl39Q0fi1ZzNw2O3/fdEdn+k1hNd05utNuD4YPF8t3ph+Gm\n" + - "fybXAgWaKx5qEyrBKPKGSpHNVCM++9nrVNzSlPcDcrtrGTd2E1iQ/eWdoN2hCi2v\n" + - "m7EctANAg+XPcrCUYRqV8FDqP7BabLLXvl/2aJ4tEwYq2MkgA/K2svXK0NsUbzC/\n" + - "703auA9NG0XnSGsM2ir4ZzHtrbb1jW6ipAvc3sdlDI+y6Mv8Ju/mJUPQouvsfaOC\n" + - "AzAwggMsMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQW\n" + - "BBQu8UGIwoTmWRQQ7brqObj6sy3nPjAfBgNVHSMEGDAWgBQu8UGIwoTmWRQQ7brq\n" + - "Obj6sy3nPjCCAscGCmCGSAGG+mtQBgEEggK3MIICswIUTggpfah2kbN+5mHbCwF8\n" + - "takhZ/ygCgYIKoZIzj0EAwShgY4wgYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxS\n" + - "b3lhbCBJbnN0aXR1dGUgb2YgUHVibGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkG\n" + - "A1UECwwiUG9zdC1IZWZmYWx1bXAgUmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UE\n" + - "AwwPRUNEU0EgUm9vdCAtIEcxo4GOMIGLMQswCQYDVQQGEwJYWDE1MDMGA1UECgws\n" + - "Um95YWwgSW5zdGl0dXRlIG9mIFB1YmxpYyBLZXkgSW5mcmFzdHJ1Y3R1cmUxKzAp\n" + - "BgNVBAsMIlBvc3QtSGVmZmFsdW1wIFJlc2VhcmNoIERlcGFydG1lbnQxGDAWBgNV\n" + - "BAMMD0VDRFNBIFJvb3QgLSBHMTCBmzAQBgcqhkjOPQIBBgUrgQQAIwOBhgAEAdD9\n" + - "cleoTHR/ViV1wHOF2+vy9SvqWAg9uC/dFTHYquPMh1/wL/f6LaJg2Oti1tL11kkn\n" + - "jjIXNqBijLuzAwi25hjbAPYq0gTGRgNZvIGKuJYb8PD8DsWq6KQoFzzlbwDemxV8\n" + - "HlyCxk9WL8re/EpMKPbTQs8+9hb8gtM7coXJIfK/Nv3YpEAwHQYDVR0OBBYEFI7C\n" + - "FAlgduqQOOk5rhttUsQXfZ++MB8GA1UdIwQYMBaAFI7CFAlgduqQOOk5rhttUsQX\n" + - "fZ++A4GMADCBiAJCAYVKnORbBIaDuB43sDb38eb4BB5y9o+wTLrIGV5DGA2yOUck\n" + - "H56/L7H4yVFatiUZok6sRMOgGR7BY6BvuczFo22UAkIBGEMII9tQkwp/0oikSbkp\n" + - "OMZH5UGlq8AL6TnD+YzMBgRq6dGZE/spGKLef6gyKQ1dKEatK/oLSgf9l7jgandU\n" + - "ENswDQYLKwYBBAECggsHBgUDggzeAGjxVa2J1Vv0ogdEFtU61BqPvtG23l6GBrsg\n" + - "kqPSt+6WHeHypIpiah5DKuCbbt27HvgnCe87G9+ktKlfx8N0+Sa8Y9QXfQ1gODHL\n" + - "9GeDBx6AWrLFoZ9mcXcc2VrFgFwMqCgaUj9KqeQp69r4oHWsnm/1AaxdswKMakev\n" + - "xqlYIeQDSspshGjWdxO8AuUd9ytW3f3P+IitJbG8wLnw98+LTotxgXwL4zOagkZW\n" + - "KsIC0qCq/m/RUAA7SZIf1SXyJu5tdA/b1JK4NT6H74K47mk/j+RpF320DCrVPHkB\n" + - "eyb/JmfEGuh4oJPyNL1Y5aYoGcX9c9WZpso8Hx6qndFeBpXsLGBU3XBwoKoUTiYb\n" + - "JTmZmjcUHmYH3FXfHs+2HgtyoQ+tsnN9HaLkzJzwvbxZ4dYtGXm4uz3xj7mGGKkZ\n" + - "j3LJyxzIuoW7yeOOKYXJTK+9pmmZTJw8m7qC4yXGesy7KhnoZ1/eujIFfZj5CP0E\n" + - "RfRhj9wXS3YNLDvJ1LnKtA5syjR1oYuoQ/BkfdwULtTHeuzykf074/z+nqWGOpZU\n" + - "K/Js+GJlVm+Hdi9YwS2c/QbzRkXj67gc2JNnRFid/omBJGt9bSqM04muf7kgn/FQ\n" + - "ijcj9ANPvCs9Ltgnn5bYU7RpGJZQWO13u6KwYAkbYwGHyDm3WAH8CWUduxBPj2BB\n" + - "GHyYhRV8hM0AVlOzGA2ZquzIDnnR+rzbBd6GjEuW41ZMTpKFPE1aUh8uC13biPjT\n" + - "FpEptBLEsd/69umHSoME9EpQKAE57vV22NYtSqfPiiD4KFbKHn/hQ/VsIkLsi5Lo\n" + - "9Ae5YVQoXMagHrl5R77s5fFKcjN+enRt6VyfC2mIWtBRU+QqTyd+cGTHgu9oKMsm\n" + - "x8MAzsvKe+MjmQEUe2OdcRCYMqcf0m5bbpaeIBPdqHmdLAOepCGI43CAyJGPKzEq\n" + - "+hz+iQZ1d3bG76qUErqDDGD+VEWlwcxf3qc3U5OJRb1SoA1ctLQ1d/Qp6u0MDFPN\n" + - "O0yYoby4+ai3KCGGs6xPE8N/kqFpa8vyqlQzWeKkLPJ7rdJF/JWBWag4v1noHHdD\n" + - "CvEA6x5z2UnntXr5FaZvbZV0SeDMIZz8bDeMOiHJ2np8hWoEFIqw+s7gz2IIxTvl\n" + - "pFYiayZYy0Wjo+HfzetxOUFM5as7NmC1TClVy27+I1DgVZoBVjMkXYjlGmT4u0dc\n" + - "GvIhkm5FE0o/BiNDRYB3UHAXW02Zzz6qa/xHLAQU4gdQyfIsv4D55NKlv4CoGhDf\n" + - "+gj7AYa17InmHlbux7lgDoV88mUkf+po8iCX6EeyFmbBxH5p4zYjzECdJP/Sd36S\n" + - "mj1qtSRA8oiV5q9gtW0wuXH94O9AHJjRdAqkyVhya4mzbVHZGz1MeRlUxZYUIX1k\n" + - "Cfxf6JSxbz5yXYn5e3DD3cdCX5wUT+ueJHdNlvLPyc4/dzMovY5PGzGH8/yhSwD8\n" + - "EAxFnSZEfUKdx/0crZ+nQn2AVDW+bGMPYMgCf86M35Jf0rk3AWUUwzQiGJ7Ifb/f\n" + - "txfhbn5LdMzUnvFaMulf94YWBUMNPw2rFypSACWjYwN3JF03aDipiubDt+5O33pa\n" + - "YRq5AfaFMNNRltdLfm0hZyyv8Qn7aNuDpVNsct0RrRl/lMAfLuCOv3tamh8Gsuci\n" + - "hC/qORpytvzwDBwh8GTstiJ8T6IAKTjgPDmVW633YVS0YRAEB4lTGIRMchG2APek\n" + - "qZ23L3JpHujColFHaQrHBSKh4ktZJwRjaaziwG0MEFQR0D/UBgjFCeIEj1ZaQb4C\n" + - "UOAx2+A1qpoYmIRywEPLXyF28e+UmstIEMymLZy03AZknIK43KuMPpA4J+gxjsHF\n" + - "/PjypAzKb07ey6xArZaW3PXIr7EGB16NDaAG1CdL8J2uDkt7vKNWL2Mxj2+JgzId\n" + - "VsbZkQoOaCO94Uz69Yg3aoLIlWukWWcHYxIH2bBouvOpKOVr27PNKRoZ7KvCke/l\n" + - "Sqa4BzPa0u23/oWqdrXrcaYdecDAv3Hdz29TSMu5Bzqz/XuCS/6ALCzzOPBzCmlB\n" + - "JdeLADlS+Vj2BEA6/rtJjxXSMAaWnHZzcepsYxsKoUX3qY61JjxX14YHnQjJ54QR\n" + - "DiKDhzmg1UahmdO0XaUqGnjYSf8sCGM4pkqik97GwgJWYy84QM/5YIvQBCJxWggd\n" + - "00IG3rFm0XiwbVmhcVrXazh4q7YflE3eN00tQVznmiuFZS+l+o1Y0L0VulinBSJ3\n" + - "bmyHn7TLIMCyZ5TN8Kbh6qTl+h/DPgKWkqIrACeTZ9gHOmzuxi6JppfKp17b0SLp\n" + - "E2YM24TIHNxl5b/pHmivnH1QsbwrBRc9EydHrIlGTC+NZfOCQ8vdlQkNK/gxe4ta\n" + - "O6bmloP0aryQWAB5C6RxLjA4Gh7zGsc16QovsZ5+BbdiW3XxQ/f/ESAkV77t3Luv\n" + - "+X1sVLBlsXlFn45PpJ5br0ncnBx2p0yihy2wCBPq1Sa7JkR/0AlhNSf5e0G7Ii0M\n" + - "4ZyKThRng3uy5Axu8H8F7TUE1gm8JAkkOl948JN4GutSypBbhiLABzbtmQOzE1E7\n" + - "8gOZYtlxgtmxJcPsC7bUiwaDCGcI6hzb4hGyCEWzPlqK9QqUP3fjoXPN0rJ08qlc\n" + - "rhFwTkrHuDn3KSvZTsJuyKeyI1MwYFEFyH2zA3rWY69QNvOgOp4J8qLNNByFWg5i\n" + - "Z5bBe8ewqAh6Rqvco9kFp5IPbHM2ZTCJFKe0CJIuJ5x6zJdfpuAwoxXNJkgqzojS\n" + - "MzjiU2HWsHUO3cU7T/qhDlKyVzXiz7SOq0j2+S0myeAz727WXPC4Ost6omCUDHqb\n" + - "M/sRXzWjJ/Egg3UftE76/d8yes8FVT4hAohLxaTGeUh9X3BwYCtsLJt8uyxvSiIR\n" + - "yE56oMVIcO/SpKHFQ+g9YRJgosYLZ0XOTSw9NM1T3eaAFjf18bLrH8VU5gbE4zul\n" + - "oDP2gv8MwMPwZzsgWlZ2da5JBwkj3KVvaNAaWSZXiHl7rrpQwt3fD3v3cZHaVD4h\n" + - "8/FQEyDA97cb/ZD4qU9KpR6rCM3GkZMy6ouAVd7/sQ6jhijBYd8wmc6IW+6uZ9kf\n" + - "uq7eWp8jvKKeSoXLcp0cHwLGw5NX47t0Y/o3O0ZGJLnyjTOlqh1n8eWZ1LFOar1y\n" + - "iEwsdw6HyemvrviZB1xSeAwentJFkq2V/GWDmlOnePWLT+uROA8FC5Qe59yLHem4\n" + - "R8U7fMUvNEhVY3c4ROptveN6/58rd1X0xqdxjQrMxH3+Powj0ZORPe68vLGT/uKc\n" + - "rwsgIGqzky+XHwT9HDOWEaKKctSqArRYqR5NdyoRb9zv6taByUjLkjgt3pXYsWjL\n" + - "5LfKusuyrtGcMFaZxiIBYtr7Sm1zmXUxikcT3Dgzt8McjwDPyonh9EtkHSyk8GFj\n" + - "cSQoNTOYPbteQpMeKbPYwkW3dCwxBABSVO7wTHXT4AxyUFMvFTIeG/mGG8KOsNsY\n" + - "iH1DhqJecXaI8fu0mvlTELyZ+KeBBd6/nrCWVvnNYiRjJX/oKvos+wqQ/vxgYQX0\n" + - "tnJnxvttNmHooO3GyQD+VOOZObpT2AhyIbVY3mxow5MnfYji8/jNwcUaGeqS5WQp\n" + - "+y5NaQ7Dj/xzp4rQDfncHt3k0JJW9do714CsKvMM9uZfCuwwBXXA2ygB68oesbWi\n" + - "QUpq65ClVmjwdzQunQb5gm1Bkwunx5wAKp1ipH2wl5XbOaG2cP0iw01pJrG/RveQ\n" + - "TlWKIDbHd+82IsdvtKMOr9Vv/KEnT4N5Cc41li76PbvWo1O9scTJu17xCfw+D7Qd\n" + - "Rghvih8CcZH2icbWncBdb79tIQUVA0vH7wSoE/HRu49OLewnZcTPy49DvMcabE+b\n" + - "YkZQD8fzKsJZ1EtQz4bGCRppezLdepIiVhO0uYRQ2JAW34deFEd4dA6EYAjg3QRm\n" + - "S5CZia8XIKguANXsX7Hl3Yqce9uERhs7XW9w7I7NT6WNYnLQXARwaDWMT20Sy029\n" + - "ny4awNVQmqWSxdE3tL3BsN3KRuKyxSEdAqDSBOpOOXDn+7ola7sQje5v7beWjglD\n" + - "4EHlMScraxoaHHPnqhB3AxbEslqArMKvF0rHJfYI03xMeYJDTBhOhbDax66NI64O\n" + - "vZPiMcb6KcZqFmNBw0taYxWO90jBAL2mvmMuYrlFP4ymr3kEksj+lgB4Aawy1VBj\n" + - "y1QVDimOJv27Fm1hDKeYavmrKgx4o7QV8mLu/xmdzS9rUKnj8ByX8thTW8/e9R9g\n" + - "VlLsaegFmjV7v9mgTRl9hw+OsAKK+HSonuU/Uor/ZJzYIhT8iWYgA0/a7cW94VhN\n" + - "CeFwA/1VH/19lcanYM58D+mnaJkSUnQzM1VupAAn8/nxthCMN7QNLjN/zvMoRFBs\n" + - "e0V7qq1OZoOYnKvoR01jp7MTIi5UuwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgsP\n" + - "Fhsg"); - - private static byte[] draft_dilithium_end_entity = Base64.decode( - "MIIYFjCCCyGgAwIBAgIUTVOt1yqx2TcoR2H+lxsPUk2gCzQwDQYLKwYBBAECggsH\n" + - "BgUwgY8xCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2Yg\n" + - "UHVibGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1\n" + - "bXAgUmVzZWFyY2ggRGVwYXJ0bWVudDEcMBoGA1UEAwwTRGlsaXRoaXVtIFJvb3Qg\n" + - "LSBHMTAeFw0yMzA1MjUxNjUxMzhaFw0yNjA1MjExNjUxMzhaMC8xCzAJBgNVBAYT\n" + - "AlhYMQ8wDQYDVQQEDAZZYW1hZGExDzANBgNVBCoMBkhhbmFrbzCCB7QwDQYLKwYB\n" + - "BAECggsHBgUDggehAA/E/9EKaexVsYAlE0FBfYaEOa/5RbzDfHLkzkymPIWn2uCy\n" + - "TdSVMPHt3n9DjdYEAXZD+sAyKiRRXKmqtgN4Cl7o96+9V+zqDXNNuD+Ol3uJ1fUf\n" + - "UxDQDoSHmEPSJFUl5sm9veB6g+CEymf6fHRVJmqMe5m3fo5SBj/v1WT8o6blqQhd\n" + - "pOn5QdrGLkri2OHEBwyrfOrhRJuXLK7867q0rzCHGecHXb7M27GtY1JdsS3f6LR6\n" + - "Xilrw77tEJTeXOw7wkEWTqVuWOQk0MteZpb4Bnyvpt6q1z/M8w8M/Xng5O9h6vEv\n" + - "k2drOrJbtYWaAaemyW7oZq0OPDQSKJuV0BzhEc97cZEW1JG7CFyO8WutBnMVaD59\n" + - "DbVu6I3UdSIeqmtGRpG5DiNn5OH8yw/6KcTB8C24GunblXbz/EBqhvaM2DGX5/4t\n" + - "V/QvnWK3LwWraYD/tby44cRhhZ95Qtvo5nX+yQMDT2gNQX3Z1X3G6ttjey9nbFhf\n" + - "vtAKXvD9n4bbNtKwXFDxIjNpf5dswLaG23eemRp06hX6TNefPIRbjcfpiaxwNs6r\n" + - "XxNYCphrLNS8ul48D+GLaYs2lto42xhOzjdPlvsSQz+kItEWZ4tqoolQXcW4BNGK\n" + - "syDtTxJQxLaUCNVoSoQ8PRcFXVGc18sk125/qp7TOKVFZ0ygGJ3RO34wjSIbqfaP\n" + - "KV7o6eWPEFbYy545M8uUG+nDAlS/aj+TYi5nEmvnDYfzzQGfUQuEswu9IdYZSXhg\n" + - "W4IPZU7TGayxNFNE1FTK0BnOyw256LD7yZvu30bAwOUphxo+8bWCgrYXe6hHLkx8\n" + - "ceXSpCmKr8y2Pibzw5NrtqpstFj/SN1HMo1p3OZrALdTPBKqHmpWMXodNWUJ0H82\n" + - "yLKxvZyTOKXpPzK1fKTQTriwnxSRiwXq83E0DJqGaukbBEEqAEa9DYkj37f3E1j+\n" + - "pqtdEMmd+zmwY+zcPOPbzZHnHjICnNHlGQboNSXuGD9AOes1IUqDpnFh3MJYAjeP\n" + - "nUAxLVjrUqTCaCZZHMutZeNT1IxuBNrkxOL+Fv/uw6XplXGUUvVl2frp6z4t+4uA\n" + - "OyIt+aNtT+WRdMB8/dJT56TjkOvJXXZxS5KBE8ru+kIqTFTBG5+3qSPYVe35qXRS\n" + - "XMpNZGZ2GJrcxdKpsAegAH+XCN0u+fIR6QrhXphVrE77/tISp+S3dQLrXpq9eDqa\n" + - "xACaTtj0rxvIgzYp86lqtvNqcXjB9t3AsZxZzVyQT+Ih55Ak68YmPinnLHQxuSMC\n" + - "XG88e1EQqPh1Tldt8n4xpY3z4aBJ9aH/4UPLBvYsm9N9eycf7uXZjOXYhqombmKn\n" + - "KeR2c4pc3mqEAjsI6QvbxMtS8pnyNS6gIhtT2DQLVTMu3V4URxDFR8LU9Ky7NdRd\n" + - "Z2KaUqwAaw9V4FmB4ycaPWyo9xaYH4hQldgk8/Zaf+Segz4llDEK6qcqeQaavvnZ\n" + - "2a4r3DO87Yw8Vy9OCfmUXCtSOXCaZXqHnwXEMTIcThqEKdqkFxLEaPE0M0kTnXAd\n" + - "uWb6JFELV3h0Q8QcxK9QLiWfNTjy/lVZ/r4eqAnrtBAIFQYYJBfA7rryu5MXIPmp\n" + - "w2F1Ei3kP/2BnZ5XD+i5nRNOo6cOEcTUi8oPvidfj2LqQAOIlID8rKhtx1FmeJJ+\n" + - "IH/wOkifcduGVlLDQKagJI7AXzkgkxFyQxnp5g34I0IRBXtsrZdmqOlv+JA08uPP\n" + - "I+vaPzvRL66vG7djHCbiLjdumwTrqbfiXeIoZjF2nP4O+X3+fjSckPOT8Dr+OMSx\n" + - "E2nEsb1lYiQcguoF52gn0Ltcf585pa6Lezey7S6Qc+3j7XdhLH2OczWgJ4zc5SBP\n" + - "9t1EzOpVFiCMQ5V4GWS6OEizdkbaKDTAEY+9TyiXXwxU5nrMWxzGhwQ7XNaT4qpt\n" + - "Z5TFEJBF94xciP4+4EkwbBFdPo02n5AD4K8PAbXj5MuySnPSYkBfMq6DwB/BlFfc\n" + - "RKVz4Yt6KR//jJjiM93G80WhlL+DAYx3w2VtWrNXhn/W9VP0KK5Jfaecbl+tHWfQ\n" + - "87HdXqx/Z8hmPEYDXidLNGOLLj7GIt2I2ZUtC7+49q6qQEL/8y78J2q1Ef1F/jUP\n" + - "xsBMzMgGTolEyz1i6X7fO+yHY5CkJAnNVkZK2wvpSGFqIuyO3BjCJfNMlpUCmhMS\n" + - "gmv6KQ9sEdF8tbYsk9ICVzqXV3O+03y4swUaIe6o0MIiL5X45SZv9HArhjs9Laku\n" + - "BjgQ3BSWtyfFRqdsLZn+MWBX4H8YkhTxfJzofSJPqNuPUwdcdIxc7LOpkOGPkAfy\n" + - "yI2uqo6YGcgMTGMBGk5iJ3SBelrz4k9YlVi3gy7gsW4FbIvXD97h3Gqd4tkM5S8L\n" + - "A9FGl2nT/0RNag91vJ+89Zls55sm3d3Hi3ZxuNr9KgNiIuNuZaFSXdrHDo/ZinFV\n" + - "BSn6YakeJCkUkqA4kqjcoxrIF6bQWu2LcM/7PeCBPhtVH6hMn5hAF+OymGCw62+m\n" + - "ha72rqBrkUhdAMjrv3eubo0AdlUD9v1z45fs68kPEsZisHBbmAZWBcGGGieupmv2\n" + - "VYkELI9mBUYJdnDhfFVSqdmqQ68xveMvb3VxIyo/eYTLuofVJp3DJ4IbhB6ro4IC\n" + - "WDCCAlQwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFANK\n" + - "iIG5mZXV+IMcuSPREB/od032MB8GA1UdIwQYMBaAFC7xQYjChOZZFBDtuuo5uPqz\n" + - "Lec+MIIB8gYKYIZIAYb6a1AGAQSCAeIwggHeAhQs36ItK8bqD/FlXfx+e3IJLemk\n" + - "uKAKBggqhkjOPQQDBKGBjjCBizELMAkGA1UEBhMCWFgxNTAzBgNVBAoMLFJveWFs\n" + - "IEluc3RpdHV0ZSBvZiBQdWJsaWMgS2V5IEluZnJhc3RydWN0dXJlMSswKQYDVQQL\n" + - "DCJQb3N0LUhlZmZhbHVtcCBSZXNlYXJjaCBEZXBhcnRtZW50MRgwFgYDVQQDDA9F\n" + - "Q0RTQSBSb290IC0gRzEwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARCJUj4j7eC\n" + - "/7Xso3REUscqHlWPvW9zvl5I6TIyzEXFsWxM0QxMuNW4oXE56UiCyJklcpk0JfQU\n" + - "Gat+kKQqSUJypEAwHQYDVR0OBBYEFFtwp5gX95/2N9L349xEbCEJ17vUMB8GA1Ud\n" + - "IwQYMBaAFI7CFAlgduqQOOk5rhttUsQXfZ++A4GLADCBhwJBJyKG5vGDiDA8iddl\n" + - "vY44yI0wK5D8ayYCx2aM8fuh5XjZA+14rI50v21a41uObnW1KXRHoQeW4SZTUBuz\n" + - "yo/w7B8CQgCqwK1+cbH+YecTjnfWQHgSk1dqgPCDi0ezo+QVOHhtzfXbIs1y1z1k\n" + - "SU/BF4spioFCeKIkkJaLs+8Evy5gdx+u6DANBgsrBgEEAQKCCwcGBQOCDN4Azno4\n" + - "4bYnpwVdpeaWAaNjchhKdPxrpn4JresJGnrJnsLUrUFtUdzipe4ZhLsLRJKRC41b\n" + - "Rg0zwf4eIxRBaERbWnWDzBl5x6LlnNNtkNsBzSVyc2OkyC6Js/AFKueK7348ZSAk\n" + - "0CeWiWRCAvg8o3o1YX+Nk0J3BYcLWyf4ZH6fyExqjnikx2NgXZhPe48l8nqjAkct\n" + - "f9tdKBkMOqP3GAKvQWhDtMNDMeUoUBXXJfJWdIfclgoGmqLe74N1wgIIDCMkMmZ1\n" + - "+G8W2E9Xix7nvwzvjFZSqcnjP17yPizCAOeRAYP3FyaZb6lMZ1Pusc9Uun9c5E8P\n" + - "8vJG7CXPYH8lVrhNpMG8y3jDAW30xphkeE8yxnYKa2k4nutAijt1XPb0p9ihTcM+\n" + - "K56fSCnFFlgXZYsyEI4oCqJQFgUf+BKe+XVSR5K5hpjkH6WT+LoAgWhm5ocyUasz\n" + - "2x2vvMeo282bdFhdnHAyaDCYBG/XjEggFpzXQ1G7Dv7ECiVjdbAnLREViMSu2sDv\n" + - "dFgE+Hzmv6IpFdh1OynxkUJ2k22do/YDvo3x9008M5HjqMYGp1I4i1wfx6X9zCNZ\n" + - "k+mzPX1QQpMoZFC9RK52XpgPECe4ssDA2vVIn3t9ZufE6M8Pzc7SgMk+gANs9yKy\n" + - "1GZyTG6CxGjVpuupXtlWFyT40U9G/GZF/AYSG/qguFu4kG5QxtafpfD+g267pX4Z\n" + - "eM2p7x0J+CCUlVr81vYs9jrhBSPnc2CVxDyj+9Jokn16ek7Ulmhu34mS5TWA9Qn2\n" + - "h3eDpTDAILyPEyKEa5mWc8WnHKtfYBl4L13QUT9VScOHvGszmrN1evuqsXdblxgL\n" + - "DH3u3cDWoF90M9Y7Avu4mS38q0bnbN8emUZRTbBlH2vHcWrOTuAWmhVpNDXlmPuM\n" + - "KV/9l9cN2B2xn+vUXccGgzltZk2hjXTigi+/ZUXAeGAq8n74LkjBkwUh4RQCwH2e\n" + - "p/5VyoAGAHwtFLOLVO+OJyE+SeRtEdV4hAeqSiXl7pwqJtO3/DcQX2bxEuolZirK\n" + - "l/THY+2hm6FE8SyZwMfyj1yjzsgJ9fK/bm7pe1g7UmDNEfepnzntPUcrRYvzD1U4\n" + - "BJ1UliWDehPf3qXolcFT0lrfxeutiFz9xkytlx/MFnDReqRKBNhZ36sq4p96o8V7\n" + - "b9+X3SZrI3fF07R5C0SgBCcZK4W/p06ZUcAS9CX+g8g7H+4mupZxe1MXuetgBPZF\n" + - "rYe6xOI6OoELchWdpuIrXq9UWLJUEUjS+Cr3HKlOJWp2+xJqV7qzMKN9ky6VgfnL\n" + - "TC7smRxGPAViMsTHaJ8FnuzZeriYr6+2n2TmpL8Ubj5iYnSW7E5zFmCO1JZOPxWF\n" + - "jwfZz6RmZUBzJCf7MBxoPdPGihpWWRheyQ9gPC3TjOBV8XRPKh+OsWkeYd2cvPSy\n" + - "xNzpPgAhnpuU36kRUarmOEJANc+p7HoTENfwzQrydDmp4NXmJNV6yWNewD8knczL\n" + - "Dp6uhlWMmm5K1o8LRWhf/BMvQkVhI92FbM7RJFwI7YoxwX+hdKX44z1cIPP+CNKJ\n" + - "3YQ4GsAbWFkuDmGjKroTmFfMaDIUioci7k49YigCWgcWfCJq1YpMnUy6U31t0lPS\n" + - "/AOAmkln/D3osf1OwQLHArH4c7rdRwrOwmzM6FaG2iyQPoF4xVWNSLYFP6tUA+JS\n" + - "C2OiSFvrN1EzBfqWRXTwMjGlBXf3WQg2nEm2n/JU7i6QVXw5kQiQICN+koCHqoWc\n" + - "0dAxxNoSq52byCXbn94aR2Hc9ycyxNLOB1om4uemIuE8JeoD6V+HQeaa113LsK06\n" + - "U3ypdmZ8LMKuPMjQYG8iBC1NB+q9j2b1NRMi2DNZmDrpG5IGEh6KLISWN6cB4NOl\n" + - "EA2D7o6SZ69emLjpwaO/IX2pS6vzZnraLvCqaWr5CJo8Exp37kAqHTU4Y0EO5h8V\n" + - "Y3h8bpebYRgGIl6iypPlyDz4zzVj51zUudI+TH8z4t5eazXSkMcHiev8qpb5kVYH\n" + - "JTtut0ndqY2u9Y5GcMc7uFHnKr2jen1DAVEFol86xikRL27nJtCpZ88IXTfrKloJ\n" + - "k8vN8guI+PU1Wd7lEOnKwXScHhbmYSrz9FQqizACRtuYiqCUv5GrPX7E31bY+B0p\n" + - "lhoVO4ZRMmFAOWNkgi9x6kMeJFhlS25t8vKspE+DJOuW+Enz7uneig5K3yiI00NW\n" + - "GveQTkoVnO4eoSjwj5+JuVNlBlZdKbfX6T0ycS4QqnH+HOEF/SJvot4Coae0Fi0x\n" + - "z8/11jAGU//CeCktsysFcUMd640JIrxb8EnB8AdG8CPp9Vpv13emPnORusIXPZKf\n" + - "33B8n8MGl09c5fh9KhGtdYV9/bnNFTIxTlRi5tNBLdOQb1t3MVuv4csBI1SR2qLr\n" + - "cWA+PUddLG9d+hoRdfy4uGb5uLkRM8ckPqtHhpOsrxdVlyDKMQt0HxniG7tZXmdo\n" + - "LhdvDOZdDqRjh8Ms94WXf0TDLrlRfefEoZ4T96aZW4qeFukBvR2rEfItRd3os2Z7\n" + - "JD7yS6RPUfBAqzGWSTsDcmjxWXZQZYO6ygd1rMkr7EbabS7FJXqb/VxVEMrMFKGx\n" + - "BFy4ujJf+cJtIDw6y59rmnaVOyAD9b4a++Zz06PnymlFEi/jlLy92xYWxt+hOaJC\n" + - "AeiUoKHLbH5KiSTWlwdbjshGytlZaAjLyuC0BxfGrQurl8VJ3OkfeDX20HgntkTu\n" + - "wJhvZpbhzth9y0cpo1z/JLyMfZV6yGccEATgRP2gciEgssBFhB6FT8tWmf5IgjkS\n" + - "pYUaCqnSn2gu3MmYZF8+h++tJGpH0hrq/MhXrqwJnx3e0c1nTC6IWbrR12s8RWig\n" + - "RjEBlFt5cfgswMeWnb7UdM/vXkefNBjiWEiDGU5R+Od9N+siYh+ZyFVkrXeD1nab\n" + - "YOTtolImcu1fP/jG2v62XVC4KoBGG53Ym2fIfkDwIjQFO6exl1/d6FoVsX3D90Hd\n" + - "7+njwh8+2eJ9AU7XXwlNi8eOklxMxPeMcCFANAx+kRy9jqKvc6p1LziOXDT3yaqT\n" + - "OPHnGffVXL966PtdGK4sP5Hf2BwMpIPv6fAjprndFKDcqUOYFjGEf9wyCnrWy/+U\n" + - "TIY1PHwtgLPqVA3Rm7lThze+OAglbFG34ErkZEprLuNxtfei3hzWE5f13O47di35\n" + - "OBnxlv/LtD190fZC1rKJjU5RT9q+foWeGtSca8McXVQ39fO1QdaGm5EGpRN0DyaK\n" + - "JbVQkNDnXkHRvgZ78npwo8pmZ2Tcw8ocnHW4KCj6CT0lf4Q7THnS4BYfLtU622Nf\n" + - "LcThYTR46ItceHlsB2Kksyx0oamRCj1kvUURCj9Pl1A9Z30xeFcJnHLaRA6BJutQ\n" + - "J17N/gF4DNzAMQK8mLNEESocdeFe6l7cWWhpjZUY4QydooN2Cv1l0REehFNiDKNz\n" + - "UUK0iJ/HbxfkI6IHtR31pq70mttHeJA4UIIdU9HbytqSehKXxSrSGeXMft0tqTG5\n" + - "pu09xlcKbP800gVp680ZMye2Jsg6ebyxEz7AKmbTDoR+30o2n5IwR/wFyrSLYgp0\n" + - "cAkBozlDWndEVdACXDCKcS/WWHhHMtU7CDUlM52UWQ9Ofsj9smfv0Q24bIEadsLX\n" + - "WGiJdYWGU4iSyn6iwPqFpWFIIASuKCom6lRhNHpumcqWaNks8oGBfb2XNbFVerK6\n" + - "WxuJhDU2d9MTtfbubfAS/ll7VFChbSML3WMfZuGEHILCwtc+MhuMsQkllii7APwv\n" + - "kicHmTTTS3gg+3yLIZT0VkBcAQfAPW9WaHz28TIFhHPt8omBLP+oB+eGcYPZL4+1\n" + - "biS3ulxNNQeV/xagXVBnQsW6NBermbpR04YHrRatkv6hddsHY7cAd+c28hMr+RLw\n" + - "/aeOG2LyZw0nOuvDHYURFnarBaZJpehAZ2Im3IQjY4riBacR/nlLJy7rznZltAoP\n" + - "A+2AdIXEWX7JfnpbtS1joXLB8kbCAsBVsQ46D4S5egFMmRDNlwPf1hrnbLR69lCR\n" + - "ugT7T0IL1tbC67ieAh5QknesVLq17hPIPECQeYTOAJksr7eT9G6M8SAKevQVOipd\n" + - "ANLVQ9/jLJUQUp5lUJOK+jduoWFUHGMV6lguHzUHT3KPXIFfQrpNOJoI1t4tEewC\n" + - "7LlbOrHF2vFU3YPoltp/gpWDEfDqRUVBEgU9gMdVDkYVn+yZwxUpRhaxihKW61yx\n" + - "P4AHo26WMuoNKJ0ALgxJ4zVYFa+O+kzdNP6Lul7ihUdAVjFXUVErhJ7d7tM+GL69\n" + - "gvN0QJgd6aHYmSZ/7QjSfsVti9WcRzCh4LZHUbmW05In8LHxvNZ1/nNyVz0iUL4P\n" + - "0C7Ox1btY/JsFYAcXRggSVR+qcDFO2J9J1CCz/Akk5W2vCktmaPtDx8nTX+s4QAA\n" + - "AAAAAAAAAAAAAAAAAAAAAAAAAAAICxAVGiE="); - - private static byte[] draft_p521_root = Base64.decode( - "MIIDBTCCAmagAwIBAgIUTggpfah2kbN+5mHbCwF8takhZ/wwCgYIKoZIzj0EAwQw\n" + - "gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi\n" + - "bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg\n" + - "UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X\n" + - "DTIzMDUyNTE2NTEzOFoXDTMzMDUxMjE2NTEzOFowgYsxCzAJBgNVBAYTAlhYMTUw\n" + - "MwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVibGljIEtleSBJbmZyYXN0cnVj\n" + - "dHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAgUmVzZWFyY2ggRGVwYXJ0bWVu\n" + - "dDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMIGbMBAGByqGSM49AgEGBSuBBAAj\n" + - "A4GGAAQB0P1yV6hMdH9WJXXAc4Xb6/L1K+pYCD24L90VMdiq48yHX/Av9/otomDY\n" + - "62LW0vXWSSeOMhc2oGKMu7MDCLbmGNsA9irSBMZGA1m8gYq4lhvw8PwOxaropCgX\n" + - "POVvAN6bFXweXILGT1Yvyt78Skwo9tNCzz72FvyC0ztyhckh8r82/dijYzBhMA8G\n" + - "A1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSOwhQJYHbq\n" + - "kDjpOa4bbVLEF32fvjAfBgNVHSMEGDAWgBSOwhQJYHbqkDjpOa4bbVLEF32fvjAK\n" + - "BggqhkjOPQQDBAOBjAAwgYgCQgGFSpzkWwSGg7geN7A29/Hm+AQecvaPsEy6yBle\n" + - "QxgNsjlHJB+evy+x+MlRWrYlGaJOrETDoBkewWOgb7nMxaNtlAJCARhDCCPbUJMK\n" + - "f9KIpEm5KTjGR+VBpavAC+k5w/mMzAYEaunRmRP7KRii3n+oMikNXShGrSv6C0oH\n" + - "/Ze44Gp3VBDb\n"); - - private static byte[] draft_ecdsa_signing_end_entity = Base64.decode( - "MIICYTCCAcOgAwIBAgIULN+iLSvG6g/xZV38fntyCS3ppLgwCgYIKoZIzj0EAwQw\n" + - "gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi\n" + - "bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg\n" + - "UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X\n" + - "DTIzMDUyNTE2NTEzOFoXDTI2MDUyMTE2NTEzOFowLzELMAkGA1UEBhMCWFgxDzAN\n" + - "BgNVBAQMBllhbWFkYTEPMA0GA1UEKgwGSGFuYWtvMFkwEwYHKoZIzj0CAQYIKoZI\n" + - "zj0DAQcDQgAEQiVI+I+3gv+17KN0RFLHKh5Vj71vc75eSOkyMsxFxbFsTNEMTLjV\n" + - "uKFxOelIgsiZJXKZNCX0FBmrfpCkKklCcqNgMF4wDAYDVR0TAQH/BAIwADAOBgNV\n" + - "HQ8BAf8EBAMCB4AwHQYDVR0OBBYEFFtwp5gX95/2N9L349xEbCEJ17vUMB8GA1Ud\n" + - "IwQYMBaAFI7CFAlgduqQOOk5rhttUsQXfZ++MAoGCCqGSM49BAMEA4GLADCBhwJB\n" + - "JyKG5vGDiDA8iddlvY44yI0wK5D8ayYCx2aM8fuh5XjZA+14rI50v21a41uObnW1\n" + - "KXRHoQeW4SZTUBuzyo/w7B8CQgCqwK1+cbH+YecTjnfWQHgSk1dqgPCDi0ezo+QV\n" + - "OHhtzfXbIs1y1z1kSU/BF4spioFCeKIkkJaLs+8Evy5gdx+u6A=="); - - private static byte[] draft_ecdsa_dual_use_end_entity = Base64.decode( - "MIIDyzCCAyygAwIBAgIUHfGFg4ZrE6+0wdcuN8sDeelJ0vswCgYIKoZIzj0EAwQw\n" + - "gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi\n" + - "bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg\n" + - "UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X\n" + - "DTIzMDUyNTE2NTEzOFoXDTI2MDUyMTE2NTEzOFowLzELMAkGA1UEBhMCWFgxDzAN\n" + - "BgNVBAQMBllhbWFkYTEPMA0GA1UEKgwGSGFuYWtvMHYwEAYHKoZIzj0CAQYFK4EE\n" + - "ACIDYgAEWwkBuIUjKW65GdUP+hqcs3S8TUCVhigr/soRsdla27VHNK9XC/grcijP\n" + - "ImvPTCXdvP47GjrTlDDv92Ph1o0uFR2Rcgt3lbWNprNGOWE6j7m1qNpIxnRxF/mR\n" + - "noQk837Io4IBqjCCAaYwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCAwgwHQYD\n" + - "VR0OBBYEFArjoP6d1CV2mLXrcuvKDOe/PfXxMB8GA1UdIwQYMBaAFI7CFAlgduqQ\n" + - "OOk5rhttUsQXfZ++MIIBRAYKYIZIAYb6a1AGAQSCATQwggEwAhQs36ItK8bqD/Fl\n" + - "Xfx+e3IJLemkuDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEIlSPiPt4L/teyj\n" + - "dERSxyoeVY+9b3O+XkjpMjLMRcWxbEzRDEy41bihcTnpSILImSVymTQl9BQZq36Q\n" + - "pCpJQnKkLzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFFtwp5gX95/2N9L349xE\n" + - "bCEJ17vUA4GLADCBhwJBJyKG5vGDiDA8iddlvY44yI0wK5D8ayYCx2aM8fuh5XjZ\n" + - "A+14rI50v21a41uObnW1KXRHoQeW4SZTUBuzyo/w7B8CQgCqwK1+cbH+YecTjnfW\n" + - "QHgSk1dqgPCDi0ezo+QVOHhtzfXbIs1y1z1kSU/BF4spioFCeKIkkJaLs+8Evy5g\n" + - "dx+u6DAKBggqhkjOPQQDBAOBjAAwgYgCQgDrJbcn+dLO5HqHlhaW6G1FuNWLz1h3\n" + - "OXYNb92b7aSsa478EsE7hE40her99+33/ws5EJp4+mtWBb6+09Be8ARC0AJCAJ9C\n" + - "q55HKUbwR5+sYUtXk1021jyjhTeRVzCXcq1AiVYriSSC9ZbBGjdzPmhtmuHWRXKY\n" + - "5vbNh5DO/8/9ucvLiIrS\n"); - public void setUp() { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } - if (Security.getProvider("BCPQC") == null) - { - Security.addProvider(new BouncyCastlePQCProvider()); - } } - public void testDeltaExtract() + public void testSameName() throws Exception { - X509CertificateHolder baseCert = new X509CertificateHolder(baseCertData); - - assertTrue(baseCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(baseCert.getSubjectPublicKeyInfo()))); - - X509CertificateHolder deltaCert = DeltaCertificateTool.extractDeltaCertificate(baseCert); - - assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BCPQC").build(deltaCert.getSubjectPublicKeyInfo()))); - - X509CertificateHolder extCert = new X509CertificateHolder(extracted); - - assertTrue(extCert.equals(deltaCert)); - } - - public void testDeltaRsaEC() - throws Exception - { - X509CertificateHolder baseCert = new X509CertificateHolder(rsa_ec_cert); - - assertTrue(baseCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(baseCert.getSubjectPublicKeyInfo()))); - - X509CertificateHolder deltaCert = DeltaCertificateTool.extractDeltaCertificate(baseCert); - - assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(deltaCert.getSubjectPublicKeyInfo()))); - } - - public void testDeltaCertRequest() - throws Exception - { - PKCS10CertificationRequest pkcs10CertReq = new PKCS10CertificationRequest(deltaCertReq); - - assertTrue(pkcs10CertReq.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(pkcs10CertReq.getSubjectPublicKeyInfo()))); - - Attribute[] attributes = pkcs10CertReq.getAttributes(new ASN1ObjectIdentifier("2.16.840.1.114027.80.6.2")); - - DeltaCertificateRequestAttributeValue deltaReq = new DeltaCertificateRequestAttributeValue(attributes[0]); - - assertTrue(DeltaCertAttributeUtils.isDeltaRequestSignatureValid(pkcs10CertReq, new JcaContentVerifierProviderBuilder().setProvider("BC").build(deltaReq.getSubjectPKInfo()))); - - KeyPairGenerator kpgB = KeyPairGenerator.getInstance("EC", "BC"); - - kpgB.initialize(new ECNamedCurveGenParameterSpec("P-256")); - - KeyPair kpB = kpgB.generateKeyPair(); - - Date notBefore = new Date(System.currentTimeMillis() - 5000); - Date notAfter = new Date(System.currentTimeMillis() + 1000 * 60 * 60); - X509v3CertificateBuilder bldr = new X509v3CertificateBuilder( - new X500Name("CN=Chameleon CA 1"), - BigInteger.valueOf(System.currentTimeMillis()), - notBefore, - notAfter, - pkcs10CertReq.getSubject(), - pkcs10CertReq.getSubjectPublicKeyInfo()); - - ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(kpB.getPrivate()); - - X509v3CertificateBuilder deltaBldr = new X509v3CertificateBuilder( - new X500Name("CN=Chameleon CA 2"), - BigInteger.valueOf(System.currentTimeMillis()), - notBefore, - notAfter, - deltaReq.getSubject(), - deltaReq.getSubjectPKInfo()); - if (deltaReq.getExtensions() != null) - { - Extensions extensions = deltaReq.getExtensions(); - for (Enumeration e = extensions.oids(); e.hasMoreElements();) - { - deltaBldr.addExtension(extensions.getExtension((ASN1ObjectIdentifier)e.nextElement())); - } - } - - X509CertificateHolder deltaCert = deltaBldr.build(signer); - - Extension deltaExt = DeltaCertificateTool.makeDeltaCertificateExtension( - false, - deltaCert); - bldr.addExtension(deltaExt); - - X509CertificateHolder chameleonCert = bldr.build(signer); - - assertTrue(chameleonCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kpB.getPublic()))); - - X509CertificateHolder exDeltaCert = DeltaCertificateTool.extractDeltaCertificate(chameleonCert); - - assertTrue(exDeltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kpB.getPublic()))); + KeyPairGenerator rsaKeyGen = KeyPairGenerator.getInstance("RSA", "BC"); + rsaKeyGen.initialize(2048, new java.security.SecureRandom()); + java.security.KeyPair deltaKeyPair = rsaKeyGen.generateKeyPair(); + java.security.KeyPair baseKeyPair = rsaKeyGen.generateKeyPair(); + + // Generate a self-signed Delta Certificate + X509v3CertificateBuilder deltaCertBuilder = new X509v3CertificateBuilder( + new X500Name("CN=Issuer"), + java.math.BigInteger.valueOf(1L), + new java.util.Date(System.currentTimeMillis()), + new java.util.Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000), + new X500Name("CN=Subject"), + SubjectPublicKeyInfo.getInstance(deltaKeyPair.getPublic().getEncoded()) + ); + ContentSigner deltaRootSigner = new JcaContentSignerBuilder("SHA256withRSA").build(deltaKeyPair.getPrivate()); + X509CertificateHolder deltaCert = deltaCertBuilder.build(deltaRootSigner); + + // Generate a self-signed Base Certificate + X509v3CertificateBuilder baseCertBuilder = new X509v3CertificateBuilder( + new X500Name("CN=Issuer"), // Same as Delta Certificate + java.math.BigInteger.valueOf(2L), + new java.util.Date(System.currentTimeMillis()), + new java.util.Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000), + new X500Name("CN=Subject"), // Same as Delta Certificate + SubjectPublicKeyInfo.getInstance(baseKeyPair.getPublic().getEncoded()) + ); + + // Create Delta Extension + Extension deltaCertExtension = DeltaCertificateTool.makeDeltaCertificateExtension(false, deltaCert); + // Add Delta Extension to Base Certificate + baseCertBuilder.addExtension(deltaCertExtension); + // Build Base Certificate + ContentSigner baseRootSigner = new JcaContentSignerBuilder("SHA256withRSA").build(baseKeyPair.getPrivate()); + X509CertificateHolder baseCert = baseCertBuilder.build(baseRootSigner); // <= Exception thrown here } + + // TODO: add new request data (change to explicit tags) +// public void testDeltaCertRequest() +// throws Exception +// { +// PKCS10CertificationRequest pkcs10CertReq = new PKCS10CertificationRequest(deltaCertReq); +// +// assertTrue(pkcs10CertReq.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(pkcs10CertReq.getSubjectPublicKeyInfo()))); +// +// Attribute[] attributes = pkcs10CertReq.getAttributes(new ASN1ObjectIdentifier("2.16.840.1.114027.80.6.2")); +// +// DeltaCertificateRequestAttributeValue deltaReq = new DeltaCertificateRequestAttributeValue(attributes[0]); +// +// assertTrue(DeltaCertAttributeUtils.isDeltaRequestSignatureValid(pkcs10CertReq, new JcaContentVerifierProviderBuilder().setProvider("BC").build(deltaReq.getSubjectPKInfo()))); +// +// KeyPairGenerator kpgB = KeyPairGenerator.getInstance("EC", "BC"); +// +// kpgB.initialize(new ECNamedCurveGenParameterSpec("P-256")); +// +// KeyPair kpB = kpgB.generateKeyPair(); +// +// Date notBefore = new Date(System.currentTimeMillis() - 5000); +// Date notAfter = new Date(System.currentTimeMillis() + 1000 * 60 * 60); +// X509v3CertificateBuilder bldr = new X509v3CertificateBuilder( +// new X500Name("CN=Chameleon CA 1"), +// BigInteger.valueOf(System.currentTimeMillis()), +// notBefore, +// notAfter, +// pkcs10CertReq.getSubject(), +// pkcs10CertReq.getSubjectPublicKeyInfo()); +// +// ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(kpB.getPrivate()); +// +// X509v3CertificateBuilder deltaBldr = new X509v3CertificateBuilder( +// new X500Name("CN=Chameleon CA 2"), +// BigInteger.valueOf(System.currentTimeMillis()), +// notBefore, +// notAfter, +// deltaReq.getSubject(), +// deltaReq.getSubjectPKInfo()); +// if (deltaReq.getExtensions() != null) +// { +// Extensions extensions = deltaReq.getExtensions(); +// for (Enumeration e = extensions.oids(); e.hasMoreElements();) +// { +// deltaBldr.addExtension(extensions.getExtension((ASN1ObjectIdentifier)e.nextElement())); +// } +// } +// +// X509CertificateHolder deltaCert = deltaBldr.build(signer); +// +// Extension deltaExt = DeltaCertificateTool.makeDeltaCertificateExtension( +// false, +// deltaCert); +// bldr.addExtension(deltaExt); +// +// X509CertificateHolder chameleonCert = bldr.build(signer); +// +// assertTrue(chameleonCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kpB.getPublic()))); +// +// X509CertificateHolder exDeltaCert = DeltaCertificateTool.extractDeltaCertificate(chameleonCert); +// +// assertTrue(exDeltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kpB.getPublic()))); +// } public void testDeltaCertWithExtensions() throws Exception @@ -828,13 +268,13 @@ public void testDeltaCertWithExtensions() ContentSigner signerB = new JcaContentSignerBuilder("SHA256withECDSA").build(kpB.getPrivate()); X509v3CertificateBuilder deltaBldr = new X509v3CertificateBuilder( - new X500Name("CN=Chameleon CA 2"), - BigInteger.valueOf(System.currentTimeMillis()), - notBefore, - notAfter, - subject, - SubjectPublicKeyInfo.getInstance(kpB.getPublic().getEncoded())); - + new X500Name("CN=Chameleon CA 2"), + BigInteger.valueOf(System.currentTimeMillis()), + notBefore, + notAfter, + subject, + SubjectPublicKeyInfo.getInstance(kpB.getPublic().getEncoded())); + deltaBldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); X509CertificateHolder deltaCert = deltaBldr.build(signerB); @@ -855,27 +295,22 @@ public void testDeltaCertWithExtensions() assertNotNull(deltaCertDesc.getIssuer()); X509CertificateHolder exDeltaCert = DeltaCertificateTool.extractDeltaCertificate(chameleonCert); - + assertTrue(exDeltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kpB.getPublic()))); } public void testCheckCreationAltCertWithDelta() throws Exception { - if (Security.getProvider("BCPQC") == null) - { - Security.addProvider(new BouncyCastlePQCProvider()); - } - KeyPairGenerator kpgB = KeyPairGenerator.getInstance("EC", "BC"); kpgB.initialize(new ECNamedCurveGenParameterSpec("P-256")); KeyPair kpB = kpgB.generateKeyPair(); - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); - kpGen.initialize(DilithiumParameterSpec.dilithium2, new SecureRandom()); + kpGen.initialize(MLDSAParameterSpec.ml_dsa_44, new SecureRandom()); KeyPair kp = kpGen.generateKeyPair(); @@ -905,7 +340,7 @@ public void testCheckCreationAltCertWithDelta() // ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(ecPrivKey); - ContentSigner altSigGen = new JcaContentSignerBuilder("Dilithium2").setProvider("BCPQC").build(privKey); + ContentSigner altSigGen = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(privKey); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( issuer, @@ -920,16 +355,16 @@ public void testCheckCreationAltCertWithDelta() ContentSigner signerB = new JcaContentSignerBuilder("SHA256withECDSA").build(kpB.getPrivate()); X509v3CertificateBuilder deltaBldr = new X509v3CertificateBuilder( - new X500Name("CN=Chameleon CA 2"), - BigInteger.valueOf(System.currentTimeMillis()), - notBefore, - notAfter, - subject, - SubjectPublicKeyInfo.getInstance(kpB.getPublic().getEncoded())); + new X500Name("CN=Chameleon CA 2"), + BigInteger.valueOf(System.currentTimeMillis()), + notBefore, + notAfter, + subject, + SubjectPublicKeyInfo.getInstance(kpB.getPublic().getEncoded())); deltaBldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) - .addExtension(Extension.subjectAltPublicKeyInfo, false, SubjectAltPublicKeyInfo.getInstance(kp.getPublic().getEncoded())); - + .addExtension(Extension.subjectAltPublicKeyInfo, false, SubjectAltPublicKeyInfo.getInstance(kp.getPublic().getEncoded())); + X509CertificateHolder deltaCert = deltaBldr.build(signerB, false, altSigGen); assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kpB.getPublic()))); @@ -955,7 +390,7 @@ public void testCheckCreationAltCertWithDelta() X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); - // assertTrue("alt sig value wrong", certHolder.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BCPQC").build(pubKey))); + // assertTrue("alt sig value wrong", certHolder.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BCPQC").build(pubKey))); X509CertificateHolder exDeltaCert = DeltaCertificateTool.extractDeltaCertificate(new X509CertificateHolder(cert.getEncoded())); @@ -966,11 +401,10 @@ public void testCheckCreationAltCertWithDelta() assertTrue(certHldr.isAlternativeSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(pubKey))); } - /* - public void testDraftDilithiumRoot() + public void testDraftMLDSARoot() throws Exception { - X509CertificateHolder baseCert = new X509CertificateHolder(draft_dilithium_root); + X509CertificateHolder baseCert = readCert("ml_dsa_root.pem"); assertTrue(baseCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(baseCert.getSubjectPublicKeyInfo()))); @@ -978,25 +412,25 @@ public void testDraftDilithiumRoot() assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(deltaCert.getSubjectPublicKeyInfo()))); - X509CertificateHolder extCert = new X509CertificateHolder(draft_p521_root); + X509CertificateHolder extCert = readCert("ec_dsa_root.pem"); assertTrue(extCert.equals(deltaCert)); } - public void testDraftDilithiumEndEntity() + public void testDraftMLDSAEndEntity() throws Exception { - X509CertificateHolder rootCert = new X509CertificateHolder(draft_dilithium_root); - X509CertificateHolder ecRootCert = new X509CertificateHolder(draft_p521_root); - X509CertificateHolder baseCert = new X509CertificateHolder(draft_dilithium_end_entity); + X509CertificateHolder rootCert = readCert("ml_dsa_root.pem"); + X509CertificateHolder ecRootCert = readCert("ec_dsa_root.pem"); + X509CertificateHolder baseCert = readCert("ec_dsa_ee.pem"); - assertTrue(baseCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(rootCert.getSubjectPublicKeyInfo()))); + assertTrue(baseCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(ecRootCert.getSubjectPublicKeyInfo()))); X509CertificateHolder deltaCert = DeltaCertificateTool.extractDeltaCertificate(baseCert); - assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(ecRootCert.getSubjectPublicKeyInfo()))); - - X509CertificateHolder extCert = new X509CertificateHolder(draft_ecdsa_signing_end_entity); + assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(rootCert.getSubjectPublicKeyInfo()))); + + X509CertificateHolder extCert = readCert("ml_dsa_ee.pem"); assertTrue(extCert.equals(deltaCert)); } @@ -1004,28 +438,29 @@ public void testDraftDilithiumEndEntity() public void testDraftDualUseEcDsaEndEntity() throws Exception { - X509CertificateHolder ecRootCert = new X509CertificateHolder(draft_p521_root); - X509CertificateHolder baseCert = new X509CertificateHolder(draft_ecdsa_dual_use_end_entity); + X509CertificateHolder ecRootCert = readCert("ec_dsa_root.pem"); + X509CertificateHolder baseCert = readCert("ec_dsa_dual_xch_ee.pem"); assertTrue(baseCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(ecRootCert.getSubjectPublicKeyInfo()))); X509CertificateHolder deltaCert = DeltaCertificateTool.extractDeltaCertificate(baseCert); - X509CertificateHolder extCert = new X509CertificateHolder(draft_ecdsa_signing_end_entity); + X509CertificateHolder extCert = readCert("ec_dsa_dual_sig_ee.pem"); assertTrue(extCert.equals(deltaCert)); - + assertTrue(deltaCert.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(ecRootCert.getSubjectPublicKeyInfo()))); } - */ -// public static void main(String[] args) -// throws Exception -// { -// X509CertificateHolder x509cert = (X509CertificateHolder)new PEMParser(new FileReader("../bc-kotlin/ta_dil_cert.pem")).readObject(); -// -// Extension ext = x509cert.getExtension(new ASN1ObjectIdentifier("2.16.840.1.114027.80.6.1")); -// -// System.err.println(ASN1Dump.dumpAsString(ext.getParsedValue())); -// } -} \ No newline at end of file + private static X509CertificateHolder readCert(String name) + throws Exception + { + PEMParser p = new PEMParser(new InputStreamReader(DeltaCertTest.class.getResourceAsStream("delta/" + name))); + + X509CertificateHolder cert = (X509CertificateHolder)p.readObject(); + + p.close(); + + return cert; + } +} diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/ExternalKeyTest.java b/pkix/src/test/java/org/bouncycastle/cert/test/ExternalKeyTest.java index e13b1460f2..20286b05b6 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/test/ExternalKeyTest.java +++ b/pkix/src/test/java/org/bouncycastle/cert/test/ExternalKeyTest.java @@ -1,7 +1,6 @@ package org.bouncycastle.cert.test; import java.io.IOException; -import java.io.StringWriter; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; @@ -12,11 +11,9 @@ import java.security.cert.X509Certificate; import java.util.Date; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.bc.ExternalValue; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.GeneralName; @@ -26,7 +23,6 @@ import org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder; import org.bouncycastle.jcajce.ExternalPublicKey; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; import org.bouncycastle.util.BigIntegers; @@ -96,7 +92,7 @@ private void checkCertificate() private void checkCertificateDilithium() throws Exception { - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Dilithium5"); + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA-87"); KeyPair kp = kpGen.generateKeyPair(); @@ -109,7 +105,7 @@ private void checkCertificateDilithium() JcaX509v1CertificateBuilder certBldr = new JcaX509v1CertificateBuilder( name, BigInteger.valueOf(System.currentTimeMillis()), new Date(time - 5000), new Date(time + 365L * 24L * 60 * 60 * 5000), name, externalKey); - X509CertificateHolder certHolder = certBldr.build(new JcaContentSignerBuilder("Dilithium5").build(kp.getPrivate())); + X509CertificateHolder certHolder = certBldr.build(new JcaContentSignerBuilder("ML-DSA-87").build(kp.getPrivate())); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); // System.err.println(ASN1Dump.dumpAsString(ASN1Primitive.fromByteArray(cert.getEncoded()))); diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/GOSTR3410_2012_256GenerateCertificate.java b/pkix/src/test/java/org/bouncycastle/cert/test/GOSTR3410_2012_256GenerateCertificate.java index 8ef1842940..ac2e486f79 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/test/GOSTR3410_2012_256GenerateCertificate.java +++ b/pkix/src/test/java/org/bouncycastle/cert/test/GOSTR3410_2012_256GenerateCertificate.java @@ -9,7 +9,6 @@ import java.security.Provider; import java.security.Security; import java.security.spec.ECGenParameterSpec; -import java.time.ZonedDateTime; import java.util.Date; import org.bouncycastle.asn1.ASN1Sequence; @@ -60,14 +59,14 @@ private static X509CertificateHolder generateSelfSignedCertificate() X500Name subject = new X500Name("CN=TEST"); X500Name issuer = subject; BigInteger serial = BigInteger.ONE; - ZonedDateTime notBefore = ZonedDateTime.now(); - ZonedDateTime notAfter = notBefore.plusYears(1); + Date notBefore = new Date(); + Date notAfter = new Date(notBefore.getTime() + 1000L * 60 * 60 * 24 * 365); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( issuer, serial, - Date.from(notBefore.toInstant()), - Date.from(notAfter.toInstant()), + notBefore, + notAfter, subject, keyPair.getPublic() ); diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/MLDSACredentialsTest.java b/pkix/src/test/java/org/bouncycastle/cert/test/MLDSACredentialsTest.java new file mode 100644 index 0000000000..09a3f70f38 --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/cert/test/MLDSACredentialsTest.java @@ -0,0 +1,41 @@ +package org.bouncycastle.cert.test; + +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import java.security.Security; +import java.security.cert.X509Certificate; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.test.SimpleTest; + +public class MLDSACredentialsTest + extends SimpleTest +{ + public String getName() + { + return "MLDSACredentials"; + } + + public void performTest() + throws Exception + { + checkSampleCredentials(SampleCredentials.ML_DSA_44); + checkSampleCredentials(SampleCredentials.ML_DSA_65); + checkSampleCredentials(SampleCredentials.ML_DSA_87); + } + + private static void checkSampleCredentials(SampleCredentials creds) + throws GeneralSecurityException + { + X509Certificate cert = creds.getCertificate(); + PublicKey pubKey = cert.getPublicKey(); + cert.verify(pubKey, BouncyCastleProvider.PROVIDER_NAME); + } + + public static void main(String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new MLDSACredentialsTest()); + } +} diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/PQCPKCS10Test.java b/pkix/src/test/java/org/bouncycastle/cert/test/PQCPKCS10Test.java new file mode 100644 index 0000000000..c81c84123b --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/cert/test/PQCPKCS10Test.java @@ -0,0 +1,147 @@ +package org.bouncycastle.cert.test; + +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.util.Date; + +import javax.security.auth.x500.X500Principal; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.BCStyle; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; +import org.bouncycastle.pkcs.PKCS10CertificationRequest; +import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; +import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest; +import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; +import org.bouncycastle.util.Arrays; + +/** + **/ +public class PQCPKCS10Test + extends TestCase +{ + private static final String BC = BouncyCastleProvider.PROVIDER_NAME; + + public String getName() + { + return "PKCS10CertRequest"; + } + + public void setUp() + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public void testMLDsa() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_65); + + KeyPair kp = kpg.genKeyPair(); + + X500Name subject = getSubjectName(); + + PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic()); + + PKCS10CertificationRequest req1 = requestBuilder.build(new JcaContentSignerBuilder("ML-DSA").setProvider(BC).build(kp.getPrivate())); + + JcaPKCS10CertificationRequest req2 = new JcaPKCS10CertificationRequest(req1.getEncoded()).setProvider(BC); + + if (!req2.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider(BC).build(kp.getPublic()))) + { + fail("ML-DSA: Failed verify check."); + } + + if (!Arrays.areEqual(req2.getPublicKey().getEncoded(), req1.getSubjectPublicKeyInfo().getEncoded())) + { + fail("ML-DSA: Failed public key check."); + } + } + + /** + * ML-KEM basesd PKCS#10 request using ML-DSA signing key. + */ + public void testMLKem() + throws Exception + { + KeyPairGenerator signKpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + signKpg.initialize(MLDSAParameterSpec.ml_dsa_65); + + KeyPair signKp = signKpg.genKeyPair(); + X509Certificate signCert = getMLDSACertificate(signKp); + + KeyPairGenerator kemKpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + kemKpg.initialize(MLKEMParameterSpec.ml_kem_768); + + KeyPair kemKp = kemKpg.genKeyPair(); + + X500Principal subject = signCert.getSubjectX500Principal(); + + PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject, kemKp.getPublic()); + + PKCS10CertificationRequest req1 = requestBuilder.build(new JcaContentSignerBuilder("ML-DSA").setProvider(BC).build(signKp.getPrivate())); + + JcaPKCS10CertificationRequest req2 = new JcaPKCS10CertificationRequest(req1.getEncoded()).setProvider(BC); + + if (!req2.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider(BC).build(signCert.getPublicKey()))) + { + fail("ML-KEM: Failed verify check."); + } + + if (!Arrays.areEqual(req2.getPublicKey().getEncoded(), req1.getSubjectPublicKeyInfo().getEncoded())) + { + fail("ML-KEM: Failed public key check."); + } + } + + private X500Name getSubjectName() + { + X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE); + + x500NameBld.addRDN(BCStyle.C, "AU"); + x500NameBld.addRDN(BCStyle.O, "The Legion of the Bouncy Castle"); + x500NameBld.addRDN(BCStyle.L, "Melbourne"); + x500NameBld.addRDN(BCStyle.ST, "Victoria"); + x500NameBld.addRDN(BCStyle.EmailAddress, "feedback-crypto@bouncycastle.org"); + + X500Name subject = x500NameBld.build(); + return subject; + } + + private X509Certificate getMLDSACertificate(KeyPair kp) + throws Exception + { + X500Name issuer = getSubjectName(); // self signed + X509v3CertificateBuilder v3certBldr = new JcaX509v3CertificateBuilder(issuer, + BigInteger.valueOf(System.currentTimeMillis()), + new Date(System.currentTimeMillis() - 5000L), + new Date(System.currentTimeMillis() + 15000L), + issuer, kp.getPublic()).addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); + + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").setProvider(BC).build(kp.getPrivate()); + + return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3certBldr.build(signer)); + } +} diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/SLHDSACredentialsTest.java b/pkix/src/test/java/org/bouncycastle/cert/test/SLHDSACredentialsTest.java new file mode 100644 index 0000000000..c11a5a8131 --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/cert/test/SLHDSACredentialsTest.java @@ -0,0 +1,39 @@ +package org.bouncycastle.cert.test; + +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import java.security.Security; +import java.security.cert.X509Certificate; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.test.SimpleTest; + +public class SLHDSACredentialsTest + extends SimpleTest +{ + public String getName() + { + return "SLHDSACredentials"; + } + + public void performTest() + throws Exception + { + checkSampleCredentials(SampleCredentials.SLH_DSA_SHA2_128S); + } + + private static void checkSampleCredentials(SampleCredentials creds) + throws GeneralSecurityException + { + X509Certificate cert = creds.getCertificate(); + PublicKey pubKey = cert.getPublicKey(); + cert.verify(pubKey, BouncyCastleProvider.PROVIDER_NAME); + } + + public static void main(String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new SLHDSACredentialsTest()); + } +} diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/SampleCredentials.java b/pkix/src/test/java/org/bouncycastle/cert/test/SampleCredentials.java new file mode 100644 index 0000000000..60a83f1f29 --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/cert/test/SampleCredentials.java @@ -0,0 +1,103 @@ +package org.bouncycastle.cert.test; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Security; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; + +public class SampleCredentials +{ + public static final SampleCredentials ML_DSA_44 = load("ML-DSA-44", "pkix/cert/mldsa", "ML-DSA-44.pem"); + public static final SampleCredentials ML_DSA_65 = load("ML-DSA-65", "pkix/cert/mldsa", "ML-DSA-65.pem"); + public static final SampleCredentials ML_DSA_87 = load("ML-DSA-87", "pkix/cert/mldsa", "ML-DSA-87.pem"); + + public static final SampleCredentials SLH_DSA_SHA2_128S = load("SLH-DSA-SHA2-128S", "pkix/cert/slhdsa", + "SLH-DSA-SHA2-128S.pem"); + + private static PemObject expectPemObject(PemReader pemReader, String type) + throws IOException + { + PemObject result = pemReader.readPemObject(); + if (!type.equals(result.getType())) + { + throw new IllegalStateException(); + } + return result; + } + + private static SampleCredentials load(String algorithm, String path, String name) + { + try + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + + InputStream input = new BufferedInputStream(TestResourceFinder.findTestResource(path, name)); + Reader reader = new InputStreamReader(input); + + PemReader pemReader = new PemReader(reader); + PemObject pemPriv = expectPemObject(pemReader, "PRIVATE KEY"); + PemObject pemPub = expectPemObject(pemReader, "PUBLIC KEY"); + PemObject pemCert = expectPemObject(pemReader, "CERTIFICATE"); + pemReader.close(); + + KeyFactory kf = KeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME); + CertificateFactory cf = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); + + PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(pemPriv.getContent())); + PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(pemPub .getContent())); + KeyPair keyPair = new KeyPair(publicKey, privateKey); + + X509Certificate certificate = (X509Certificate)cf.generateCertificate( + new ByteArrayInputStream(pemCert.getContent())); + + if (!publicKey.equals(certificate.getPublicKey())) + { + throw new IllegalStateException("public key mismatch"); + } + + return new SampleCredentials(keyPair, certificate); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } + + private final KeyPair keyPair; + private final X509Certificate certificate; + + private SampleCredentials(KeyPair keyPair, X509Certificate certificate) + { + this.keyPair = keyPair; + this.certificate = certificate; + } + + public X509Certificate getCertificate() + { + return certificate; + } + + public KeyPair getKeyPair() + { + return keyPair; + } +} diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/AllTests.java b/pkix/src/test/java/org/bouncycastle/cms/test/AllTests.java index edc7aff46d..fd911806be 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/AllTests.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/AllTests.java @@ -28,6 +28,7 @@ public static Test suite() suite.addTest(NewAuthenticatedDataStreamTest.suite()); suite.addTest(NewCompressedDataStreamTest.suite()); suite.addTest(NewSignedDataStreamTest.suite()); + suite.addTest(NewAuthEnvelopedDataStreamTest.suite()); suite.addTest(NewEnvelopedDataStreamTest.suite()); suite.addTest(AuthEnvelopedDataTest.suite()); diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/AuthEnvelopedDataTest.java b/pkix/src/test/java/org/bouncycastle/cms/test/AuthEnvelopedDataTest.java index 1f6736766a..3472aa57f5 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/AuthEnvelopedDataTest.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/AuthEnvelopedDataTest.java @@ -22,6 +22,7 @@ import org.bouncycastle.asn1.cms.GCMParameters; import org.bouncycastle.asn1.cms.Time; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.cms.CMSAttributeTableGenerationException; import org.bouncycastle.cms.CMSAttributeTableGenerator; @@ -207,6 +208,53 @@ public AttributeTable getAttributes(Map parameters) assertEquals("Hello, world!", Strings.fromByteArray(recData)); } + public void testChacha20Poly1305() + throws Exception + { + if (!CMSTestUtil.isAeadAvailable()) + { + return; + } + byte[] message = Strings.toByteArray("Hello, world!"); + OutputEncryptor candidate = new JceCMSContentEncryptorBuilder(PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305).setProvider(BC).build(); + + assertEquals(PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305, candidate.getAlgorithmIdentifier().getAlgorithm()); + //assertNotNull(GCMParameters.getInstance(candidate.getAlgorithmIdentifier().getParameters())); + + assertTrue(candidate instanceof OutputAEADEncryptor); + + OutputAEADEncryptor macProvider = (OutputAEADEncryptor)candidate; + + CMSAuthEnvelopedDataGenerator authGen = new CMSAuthEnvelopedDataGenerator(); + + authGen.setAuthenticatedAttributeGenerator(new CMSAttributeTableGenerator() + { + public AttributeTable getAttributes(Map parameters) + throws CMSAttributeTableGenerationException + { + Hashtable attrs = new Hashtable(); + Attribute testAttr = new Attribute(CMSAttributes.signingTime, + new DERSet(new Time(new Date()))); + attrs.put(testAttr.getAttrType(), testAttr); + return new AttributeTable(attrs); + } + }); + + authGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert)); + + CMSAuthEnvelopedData authData = authGen.generate(new CMSProcessableByteArray(message), macProvider); + + CMSAuthEnvelopedData encAuthData = new CMSAuthEnvelopedData(authData.getEncoded()); + + RecipientInformationStore recipients = encAuthData.getRecipientInfos(); + + RecipientInformation recipient = (RecipientInformation)recipients.getRecipients().iterator().next(); + + byte[] recData = recipient.getContent(new JceKeyTransAuthEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)); + + assertEquals("Hello, world!", Strings.fromByteArray(recData)); + } + public void testGCMwithHKDF() throws Exception { diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/CMSTestUtil.java b/pkix/src/test/java/org/bouncycastle/cms/test/CMSTestUtil.java index 271188ebd5..d143965ede 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/CMSTestUtil.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/CMSTestUtil.java @@ -20,6 +20,7 @@ import javax.crypto.SecretKey; import javax.crypto.spec.DHParameterSpec; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSAESOAEPparams; @@ -60,6 +61,25 @@ public class CMSTestUtil public static KeyPairGenerator ecDsaKpg; public static KeyPairGenerator ed25519Kpg; public static KeyPairGenerator ed448Kpg; + public static KeyPairGenerator mlDsa44Kpg; + public static KeyPairGenerator mlDsa65Kpg; + public static KeyPairGenerator mlDsa87Kpg; + public static KeyPairGenerator mlKem512Kpg; + public static KeyPairGenerator mlKem768Kpg; + public static KeyPairGenerator mlKem1024Kpg; + public static KeyPairGenerator ntruKpg; + public static KeyPairGenerator slhDsa_Sha2_128f_Kpg; + public static KeyPairGenerator slhDsa_Sha2_128s_Kpg; + public static KeyPairGenerator slhDsa_Sha2_192f_Kpg; + public static KeyPairGenerator slhDsa_Sha2_192s_Kpg; + public static KeyPairGenerator slhDsa_Sha2_256f_Kpg; + public static KeyPairGenerator slhDsa_Sha2_256s_Kpg; + public static KeyPairGenerator slhDsa_Shake_128f_Kpg; + public static KeyPairGenerator slhDsa_Shake_128s_Kpg; + public static KeyPairGenerator slhDsa_Shake_192f_Kpg; + public static KeyPairGenerator slhDsa_Shake_192s_Kpg; + public static KeyPairGenerator slhDsa_Shake_256f_Kpg; + public static KeyPairGenerator slhDsa_Shake_256s_Kpg; public static KeyGenerator aes192kg; public static KeyGenerator desede128kg; public static KeyGenerator desede192kg; @@ -164,6 +184,29 @@ public class CMSTestUtil ed25519Kpg = KeyPairGenerator.getInstance("Ed25519", "BC"); ed448Kpg = KeyPairGenerator.getInstance("Ed448", "BC"); + ntruKpg = KeyPairGenerator.getInstance(BCObjectIdentifiers.ntruhps2048509.getId(), "BC"); + + mlDsa44Kpg = KeyPairGenerator.getInstance("ML-DSA-44", "BC"); + mlDsa65Kpg = KeyPairGenerator.getInstance("ML-DSA-65", "BC"); + mlDsa87Kpg = KeyPairGenerator.getInstance("ML-DSA-87", "BC"); + + mlKem512Kpg = KeyPairGenerator.getInstance("ML-KEM-512", "BC"); + mlKem768Kpg = KeyPairGenerator.getInstance("ML-KEM-768", "BC"); + mlKem1024Kpg = KeyPairGenerator.getInstance("ML-KEM-1024", "BC"); + + slhDsa_Sha2_128f_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHA2-128F", "BC"); + slhDsa_Sha2_128s_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHA2-128S", "BC"); + slhDsa_Sha2_192f_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHA2-192F", "BC"); + slhDsa_Sha2_192s_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHA2-192S", "BC"); + slhDsa_Sha2_256f_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHA2-256F", "BC"); + slhDsa_Sha2_256s_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHA2-256S", "BC"); + slhDsa_Shake_128f_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHAKE-128F", "BC"); + slhDsa_Shake_128s_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHAKE-128S", "BC"); + slhDsa_Shake_192f_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHAKE-192F", "BC"); + slhDsa_Shake_192s_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHAKE-192S", "BC"); + slhDsa_Shake_256f_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHAKE-256F", "BC"); + slhDsa_Shake_256s_Kpg = KeyPairGenerator.getInstance("SLH-DSA-SHAKE-256S", "BC"); + aes192kg = KeyGenerator.getInstance("AES", "BC"); aes192kg.init(192, rand); @@ -270,6 +313,101 @@ public static KeyPair makeEcGostKeyPair() return ecGostKpg.generateKeyPair(); } + public static KeyPair makeNtruKeyPair() + { + return ntruKpg.generateKeyPair(); + } + + public static KeyPair makeMLKem512KeyPair() + { + return mlKem512Kpg.generateKeyPair(); + } + + public static KeyPair makeMLKem768KeyPair() + { + return mlKem768Kpg.generateKeyPair(); + } + + public static KeyPair makeMLKem1024KeyPair() + { + return mlKem1024Kpg.generateKeyPair(); + } + + public static KeyPair makeMLDsa44KeyPair() + { + return mlDsa44Kpg.generateKeyPair(); + } + + public static KeyPair makeMLDsa65KeyPair() + { + return mlDsa65Kpg.generateKeyPair(); + } + + public static KeyPair makeMLDsa87KeyPair() + { + return mlDsa87Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Sha2_128f_KeyPair() + { + return slhDsa_Sha2_128f_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Sha2_128s_KeyPair() + { + return slhDsa_Sha2_128s_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Sha2_192f_KeyPair() + { + return slhDsa_Sha2_192f_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Sha2_192s_KeyPair() + { + return slhDsa_Sha2_192s_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Sha2_256f_KeyPair() + { + return slhDsa_Sha2_256f_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Sha2_256s_KeyPair() + { + return slhDsa_Sha2_256s_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Shake_128f_KeyPair() + { + return slhDsa_Shake_128f_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Shake_128s_KeyPair() + { + return slhDsa_Shake_128s_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Shake_192f_KeyPair() + { + return slhDsa_Shake_192f_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Shake_192s_KeyPair() + { + return slhDsa_Shake_192s_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Shake_256f_KeyPair() + { + return slhDsa_Shake_256f_Kpg.generateKeyPair(); + } + + public static KeyPair makeSlhDsa_Shake_256s_KeyPair() + { + return slhDsa_Shake_256s_Kpg.generateKeyPair(); + } + public static SecretKey makeDesede128Key() { return desede128kg.generateKey(); @@ -488,6 +626,10 @@ public static X509Certificate makeOaepCertificate(KeyPair subKP, String _subDN, private static JcaContentSignerBuilder makeContentSignerBuilder(PublicKey issPub) { + /* + * NOTE: Current ALL test certificates are issued under a SHA1withRSA root, so this list is mostly + * redundant (and also incomplete in that it doesn't handle EdDSA or ML-DSA issuers). + */ JcaContentSignerBuilder contentSignerBuilder; if (issPub instanceof RSAPublicKey) { @@ -505,10 +647,14 @@ else if (issPub.getAlgorithm().equals("ECGOST3410")) { contentSignerBuilder = new JcaContentSignerBuilder("GOST3411withECGOST3410"); } - else + else if (issPub.getAlgorithm().equals("GOST3410")) { contentSignerBuilder = new JcaContentSignerBuilder("GOST3411WithGOST3410"); } + else + { + throw new UnsupportedOperationException("Algorithm handlers incomplete"); + } contentSignerBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/GOSTR3410_2012_256CmsSignVerifyDetached.java b/pkix/src/test/java/org/bouncycastle/cms/test/GOSTR3410_2012_256CmsSignVerifyDetached.java index a82ea627cd..91918de68b 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/GOSTR3410_2012_256CmsSignVerifyDetached.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/GOSTR3410_2012_256CmsSignVerifyDetached.java @@ -9,6 +9,7 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; +import java.util.Date; import java.util.HashSet; import java.util.List; @@ -121,9 +122,13 @@ private static boolean verifyDetached(byte[] data, byte[] detachedCms, // Validate signer's certificate chain X509CertSelector constraints = new X509CertSelector(); - constraints.setCertificate(getX509Certificate(signerCert)); + X509Certificate x509Certificate = getX509Certificate(signerCert); + constraints.setCertificate(x509Certificate); + PKIXBuilderParameters params = new PKIXBuilderParameters(trustAnchors, constraints); + params.setDate(new Date(x509Certificate.getNotAfter().getTime() - 5000L)); + JcaCertStoreBuilder certStoreBuilder = new JcaCertStoreBuilder(); certStoreBuilder.addCertificate(signerCert); diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/NewAuthEnvelopedDataStreamTest.java b/pkix/src/test/java/org/bouncycastle/cms/test/NewAuthEnvelopedDataStreamTest.java new file mode 100644 index 0000000000..1ab81dbfa5 --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/cms/test/NewAuthEnvelopedDataStreamTest.java @@ -0,0 +1,747 @@ +package org.bouncycastle.cms.test; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.KeyPair; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; + +import javax.crypto.SecretKey; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERSet; +import org.bouncycastle.asn1.DERUTF8String; +import org.bouncycastle.asn1.cms.Attribute; +import org.bouncycastle.asn1.cms.AttributeTable; +import org.bouncycastle.asn1.cms.CMSAttributes; +import org.bouncycastle.asn1.cms.Time; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cms.CMSAlgorithm; +import org.bouncycastle.cms.CMSAttributeTableGenerationException; +import org.bouncycastle.cms.CMSAttributeTableGenerator; +import org.bouncycastle.cms.CMSAuthEnvelopedData; +import org.bouncycastle.cms.CMSAuthEnvelopedDataGenerator; +import org.bouncycastle.cms.CMSAuthEnvelopedDataParser; +import org.bouncycastle.cms.CMSAuthEnvelopedDataStreamGenerator; +import org.bouncycastle.cms.CMSAuthenticatedDataGenerator; +import org.bouncycastle.cms.CMSEnvelopedDataParser; +import org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator; +import org.bouncycastle.cms.CMSProcessableByteArray; +import org.bouncycastle.cms.CMSTypedStream; +import org.bouncycastle.cms.KEKRecipientId; +import org.bouncycastle.cms.OriginatorInfoGenerator; +import org.bouncycastle.cms.PasswordRecipient; +import org.bouncycastle.cms.PasswordRecipientInformation; +import org.bouncycastle.cms.RecipientId; +import org.bouncycastle.cms.RecipientInformation; +import org.bouncycastle.cms.RecipientInformationStore; +import org.bouncycastle.cms.SimpleAttributeTableGenerator; +import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; +import org.bouncycastle.cms.jcajce.JceKEKAuthEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKEKRecipientInfoGenerator; +import org.bouncycastle.cms.jcajce.JceKeyAgreeAuthEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientId; +import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientInfoGenerator; +import org.bouncycastle.cms.jcajce.JceKeyTransAuthEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; +import org.bouncycastle.cms.jcajce.JcePasswordAuthEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JcePasswordRecipientInfoGenerator; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.OutputAEADEncryptor; +import org.bouncycastle.operator.OutputEncryptor; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class NewAuthEnvelopedDataStreamTest + extends TestCase +{ + + private static final String BC = BouncyCastleProvider.PROVIDER_NAME; + + private static final int BUFFER_SIZE = 4000; + private static String _signDN; + private static KeyPair _signKP; + private static X509Certificate _signCert; + + private static String _origDN; + private static KeyPair _origKP; + private static X509Certificate _origCert; + + private static String _reciDN; + private static KeyPair _reciKP; + private static X509Certificate _reciCert; + + private static KeyPair _origEcKP; + private static KeyPair _reciEcKP; + private static X509Certificate _reciEcCert; + + private static boolean _initialised = false; + + public NewAuthEnvelopedDataStreamTest() + { + } + + private static void init() + throws Exception + { + if (!_initialised) + { + _initialised = true; + + _signDN = "O=Bouncy Castle, C=AU"; + _signKP = CMSTestUtil.makeKeyPair(); + _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _signKP, _signDN); + + _origDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; + _origKP = CMSTestUtil.makeKeyPair(); + _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _signKP, _signDN); + + _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; + _reciKP = CMSTestUtil.makeKeyPair(); + _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); + + _origEcKP = CMSTestUtil.makeEcDsaKeyPair(); + _reciEcKP = CMSTestUtil.makeEcDsaKeyPair(); + _reciEcCert = CMSTestUtil.makeCertificate(_reciEcKP, _reciDN, _signKP, _signDN); + } + } + + public void setUp() + throws Exception + { + init(); + } + + private void verifyData( + ByteArrayOutputStream encodedStream, + String expectedOid, + byte[] expectedData) + throws Exception + { + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(encodedStream.toByteArray()); + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), expectedOid); + + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + while (it.hasNext()) + { + RecipientInformation recipient = (RecipientInformation)it.next(); + + assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); + + CMSTypedStream recData = recipient.getContentStream(new JceKeyTransAuthEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)); + + assertTrue(Arrays.equals(expectedData, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + } + } + + public void testUnprotectedAttributes() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + Hashtable attrs = new Hashtable(); + + attrs.put(PKCSObjectIdentifiers.id_aa_contentHint, new Attribute(PKCSObjectIdentifiers.id_aa_contentHint, new DERSet(new DERUTF8String("Hint")))); + attrs.put(PKCSObjectIdentifiers.id_aa_receiptRequest, new Attribute(PKCSObjectIdentifiers.id_aa_receiptRequest, new DERSet(new DERUTF8String("Request")))); + + AttributeTable attrTable = new AttributeTable(attrs); + + edGen.setUnprotectedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + OutputStream out = edGen.open( + bOut, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM).setProvider(BC).build()); + + out.write(data); + + out.close(); + + CMSEnvelopedDataParser ed = new CMSEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ed.getRecipientInfos(); + + Collection c = recipients.getRecipients(); + + assertEquals(1, c.size()); + + Iterator it = c.iterator(); + + while (it.hasNext()) + { + RecipientInformation recipient = it.next(); + + assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); + + byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)); + + assertTrue(Arrays.equals(data, recData)); + } + + attrTable = ed.getUnprotectedAttributes(); + + assertEquals(attrs.size(), 2); + + assertEquals(new DERUTF8String("Hint"), attrTable.get(PKCSObjectIdentifiers.id_aa_contentHint).getAttrValues().getObjectAt(0)); + assertEquals(new DERUTF8String("Request"), attrTable.get(PKCSObjectIdentifiers.id_aa_receiptRequest).getAttrValues().getObjectAt(0)); + } + + public void testKeyTransAES128GCM() + throws Exception + { + byte[] data = new byte[2000]; + + for (int i = 0; i != 2000; i++) + { + data[i] = (byte)(i & 0xff); + } + + // + // unbuffered + // + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + for (int i = 0; i != 2000; i++) + { + out.write(data[i]); + } + + out.close(); + + verifyData(bOut, CMSAlgorithm.AES128_GCM.getId(), data); + + int unbufferedLength = bOut.toByteArray().length; + + // + // Using buffered output - should be == to unbuffered + // + edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + bOut = new ByteArrayOutputStream(); + + out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + BufferedOutputStream bfOut = new BufferedOutputStream(out, 300); + + for (int i = 0; i != 2000; i++) + { + bfOut.write(data[i]); + } + + bfOut.close(); + + verifyData(bOut, CMSAlgorithm.AES128_GCM.getId(), data); + + assertEquals(bOut.toByteArray().length, unbufferedLength); + } + + public void testKeyTransAES128Der() + throws Exception + { + byte[] data = new byte[2000]; + + for (int i = 0; i != 2000; i++) + { + data[i] = (byte)(i & 0xff); + } + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + for (int i = 0; i != 2000; i++) + { + out.write(data[i]); + } + + out.close(); + + // convert to DER + ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray()); + + bOut.reset(); + + aIn.readObject().encodeTo(bOut, ASN1Encoding.DER); + + verifyData(bOut, CMSAlgorithm.AES128_GCM.getId(), data); + } + + public void testKeyTransAES128Throughput() + throws Exception + { + byte[] data = new byte[40001]; + + for (int i = 0; i != data.length; i++) + { + data[i] = (byte)(i & 0xff); + } + + // + // buffered + // + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + edGen.setBufferSize(BUFFER_SIZE); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + for (int i = 0; i != data.length; i++) + { + out.write(data[i]); + } + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + RecipientInformationStore recipients = ep.getRecipientInfos(); + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + if (it.hasNext()) + { + RecipientInformation recipient = it.next(); + + assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); + + CMSTypedStream recData = recipient.getContentStream( + new JceKeyTransAuthEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)); + + InputStream dataStream = recData.getContentStream(); + ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); + int len; + byte[] buf = new byte[BUFFER_SIZE]; + int count = 0; + + while (count != 10 && (len = dataStream.read(buf)) > 0) + { + assertEquals(buf.length, len); + + dataOut.write(buf); + count++; + } + + len = dataStream.read(buf); + dataOut.write(buf, 0, len); + + assertEquals(true, Arrays.equals(data, dataOut.toByteArray())); + } + else + { + fail("recipient not found."); + } + } + + public void testKeyTransAES128AndOriginatorInfo() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + X509CertificateHolder origCert = new X509CertificateHolder(_origCert.getEncoded()); + + edGen.setOriginatorInfo(new OriginatorInfoGenerator(origCert).generate()); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + assertTrue(ep.getOriginatorInfo().getCertificates().getMatches(null).contains(origCert)); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.AES128_GCM.getId()); + + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + while (it.hasNext()) + { + RecipientInformation recipient = it.next(); + + assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); + + CMSTypedStream recData = recipient.getContentStream( + new JceKeyTransAuthEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)); + + assertTrue(Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + } + + ep.close(); + } + + public void testKeyTransAES128() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.AES128_GCM.getId()); + + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + while (it.hasNext()) + { + RecipientInformation recipient = it.next(); + + assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); + + CMSTypedStream recData = recipient.getContentStream(new JceKeyTransAuthEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)); + + assertTrue(Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + } + + ep.close(); + } + + public void testAESKEK() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + SecretKey kek = CMSTestUtil.makeAES192Key(); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + byte[] kekId = new byte[]{1, 2, 3, 4, 5}; + + edGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId, kek).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.AES128_GCM.getId()); + + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + while (it.hasNext()) + { + RecipientInformation recipient = it.next(); + + CMSTypedStream recData = recipient.getContentStream(new JceKEKAuthEnvelopedRecipient(kek).setProvider(BC)); + + assertTrue(Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + } + + ep.close(); + } + + public void testChaCha20Poly1305KEK() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + SecretKey kek = CMSTestUtil.makeAES192Key(); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + byte[] kekId = new byte[]{1, 2, 3, 4, 5}; + + edGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId, kek).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.ChaCha20Poly1305); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.ChaCha20Poly1305.getId()); + + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + while (it.hasNext()) + { + RecipientInformation recipient = it.next(); + + CMSTypedStream recData = recipient.getContentStream(new JceKEKAuthEnvelopedRecipient(kek).setProvider(BC)); + + assertTrue(Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + } + + ep.close(); + } + + public void testTwoAESKEK() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + SecretKey kek1 = CMSTestUtil.makeAES192Key(); + SecretKey kek2 = CMSTestUtil.makeAES192Key(); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + byte[] kekId1 = new byte[]{1, 2, 3, 4, 5}; + byte[] kekId2 = new byte[]{5, 4, 3, 2, 1}; + + edGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId1, kek1).setProvider(BC)); + edGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId2, kek2).setProvider(BC)); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES192_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.AES192_GCM.getId()); + + RecipientId recSel = new KEKRecipientId(kekId2); + + RecipientInformation recipient = recipients.get(recSel); + + CMSTypedStream recData = recipient.getContentStream(new JceKEKAuthEnvelopedRecipient(kek2).setProvider(BC)); + + assertTrue(Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + + ep.close(); + } + + public void testECKeyAgree() + throws Exception + { + byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65"); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + JceKeyAgreeRecipientInfoGenerator recipientGenerator = new JceKeyAgreeRecipientInfoGenerator( + CMSAlgorithm.ECDH_SHA1KDF, _origEcKP.getPrivate(), _origEcKP.getPublic(), + CMSAlgorithm.AES128_WRAP).setProvider(BC); + + recipientGenerator.addRecipient(_reciEcCert); + + edGen.addRecipientInfoGenerator(recipientGenerator); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.AES128_GCM.getId()); + + RecipientId recSel = new JceKeyAgreeRecipientId(_reciEcCert); + + RecipientInformation recipient = recipients.get(recSel); + + CMSTypedStream recData = recipient.getContentStream( + new JceKeyAgreeAuthEnvelopedRecipient(_reciEcKP.getPrivate()).setProvider(BC)); + + assertEquals(true, Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + + ep.close(); + } + + public void testECKeyAgreeChacha20Poly1305() + throws Exception + { + byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65"); + + CMSAuthEnvelopedDataStreamGenerator edGen = new CMSAuthEnvelopedDataStreamGenerator(); + + JceKeyAgreeRecipientInfoGenerator recipientGenerator = new JceKeyAgreeRecipientInfoGenerator( + CMSAlgorithm.ECDH_SHA1KDF, _origEcKP.getPrivate(), _origEcKP.getPublic(), + CMSAlgorithm.AES128_WRAP).setProvider(BC); + + recipientGenerator.addRecipient(_reciEcCert); + + edGen.addRecipientInfoGenerator(recipientGenerator); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.ChaCha20Poly1305); + OutputStream out = edGen.open(bOut, (OutputAEADEncryptor)encryptorBuilder.setProvider(BC).build()); + out.write(data); + + out.close(); + + CMSAuthEnvelopedDataParser ep = new CMSAuthEnvelopedDataParser(bOut.toByteArray()); + + RecipientInformationStore recipients = ep.getRecipientInfos(); + + assertEquals(ep.getEncAlgOID(), CMSAlgorithm.ChaCha20Poly1305.getId()); + + RecipientId recSel = new JceKeyAgreeRecipientId(_reciEcCert); + + RecipientInformation recipient = recipients.get(recSel); + + CMSTypedStream recData = recipient.getContentStream( + new JceKeyAgreeAuthEnvelopedRecipient(_reciEcKP.getPrivate()).setProvider(BC)); + + assertEquals(true, Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); + + ep.close(); + } + + public void testPasswordChaCha20Poly1305() + throws Exception + { + if (!CMSTestUtil.isAeadAvailable()) + { + return; + } + byte[] message = Strings.toByteArray("Hello, world!"); + OutputEncryptor candidate = new JceCMSContentEncryptorBuilder(CMSAlgorithm.ChaCha20Poly1305).setProvider(BC).build(); + + assertEquals(CMSAlgorithm.ChaCha20Poly1305, candidate.getAlgorithmIdentifier().getAlgorithm()); + //assertNotNull(GCMParameters.getInstance(candidate.getAlgorithmIdentifier().getParameters())); + + assertTrue(candidate instanceof OutputAEADEncryptor); + + OutputAEADEncryptor macProvider = (OutputAEADEncryptor)candidate; + + CMSAuthEnvelopedDataGenerator authGen = new CMSAuthEnvelopedDataGenerator(); + + authGen.setAuthenticatedAttributeGenerator(new CMSAttributeTableGenerator() + { + public AttributeTable getAttributes(Map parameters) + throws CMSAttributeTableGenerationException + { + Hashtable attrs = new Hashtable(); + Attribute testAttr = new Attribute(CMSAttributes.signingTime, + new DERSet(new Time(new Date()))); + attrs.put(testAttr.getAttrType(), testAttr); + return new AttributeTable(attrs); + } + }); + + authGen.addRecipientInfoGenerator(new JcePasswordRecipientInfoGenerator(new ASN1ObjectIdentifier(CMSAuthenticatedDataGenerator.AES256_CBC), + "password".toCharArray()).setProvider(BC).setSaltAndIterationCount(new byte[20], 5)); + + CMSAuthEnvelopedData authData = authGen.generate(new CMSProcessableByteArray(message), macProvider); + + CMSAuthEnvelopedData encAuthData = new CMSAuthEnvelopedData(authData.getEncoded()); + + RecipientInformationStore recipients = encAuthData.getRecipientInfos(); + + Collection c = recipients.getRecipients(); + Iterator it = c.iterator(); + + if (it.hasNext()) + { + PasswordRecipientInformation recipient = (PasswordRecipientInformation)it.next(); + + PasswordRecipient pbeRep = new JcePasswordAuthEnvelopedRecipient("password".toCharArray()).setProvider(BC); + + byte[] recData = recipient.getContent(pbeRep); + + assertTrue(Arrays.equals(message, recData)); + assertTrue(Arrays.equals(authData.getMac(), recipient.getMac())); + } + else + { + fail("no recipient found"); + } + } + + public static Test suite() + throws Exception + { + return new CMSTestSetup(new TestSuite(NewAuthEnvelopedDataStreamTest.class)); + } + +// public static void main(String[] args) +// throws Exception +// { +// NewAuthEnvelopedDataStreamTest test = new NewAuthEnvelopedDataStreamTest(); +// test.setUp(); +// test.testPasswordChaCha20Poly1305(); +// test.testECKeyAgreeChacha20Poly1305(); +// test.testChaCha20Poly1305KEK(); +// System.out.println("OK"); +// } +} diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataStreamTest.java b/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataStreamTest.java index 535bbcc556..4786f62f30 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataStreamTest.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataStreamTest.java @@ -30,7 +30,6 @@ import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cms.CMSAlgorithm; -import org.bouncycastle.cms.CMSAuthEnvelopedDataStreamGenerator; import org.bouncycastle.cms.CMSEnvelopedDataGenerator; import org.bouncycastle.cms.CMSEnvelopedDataParser; import org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator; @@ -51,7 +50,6 @@ import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.operator.OutputAEADEncryptor; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataTest.java b/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataTest.java index 180056efb4..d8e8845400 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataTest.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/NewEnvelopedDataTest.java @@ -42,6 +42,7 @@ import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERUTF8String; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CCMParameters; @@ -61,6 +62,7 @@ import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; @@ -72,6 +74,7 @@ import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.CMSTypedStream; +import org.bouncycastle.cms.KEMRecipientInformation; import org.bouncycastle.cms.KeyAgreeRecipientInformation; import org.bouncycastle.cms.KeyTransRecipientInformation; import org.bouncycastle.cms.OriginatorInfoGenerator; @@ -89,6 +92,8 @@ import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; import org.bouncycastle.cms.jcajce.JceKEKEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKEKRecipientInfoGenerator; +import org.bouncycastle.cms.jcajce.JceKEMEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKEMRecipientInfoGenerator; import org.bouncycastle.cms.jcajce.JceKeyAgreeEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientId; import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientInfoGenerator; @@ -101,6 +106,7 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.operator.DefaultKemEncapsulationLengthProvider; import org.bouncycastle.operator.OutputEncryptor; import org.bouncycastle.operator.jcajce.JcaAlgorithmParametersConverter; import org.bouncycastle.util.Strings; @@ -135,6 +141,14 @@ public class NewEnvelopedDataTest private static X509Certificate _reciEcCert2; private static KeyPair _reciKemsKP; private static X509Certificate _reciKemsCert; + private static KeyPair _reciNtruKP; + private static X509Certificate _reciNtruCert; + private static KeyPair _reciMLKem512KP; + private static X509Certificate _reciMLKem512Cert; + private static KeyPair _reciMLKem768KP; + private static X509Certificate _reciMLKem768Cert; + private static KeyPair _reciMLKem1024KP; + private static X509Certificate _reciMLKem1024Cert; private static KeyPair _origDhKP; private static KeyPair _reciDhKP; @@ -595,6 +609,18 @@ private static void init() _reciKemsKP = CMSTestUtil.makeKeyPair(); _reciKemsCert = CMSTestUtil.makeCertificate(_reciKemsKP, _reciDN, _signKP, _signDN, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_rsa_KEM)); + + _reciNtruKP = CMSTestUtil.makeNtruKeyPair(); + _reciNtruCert = CMSTestUtil.makeCertificate(_reciNtruKP, _reciDN, _signKP, _signDN); + + _reciMLKem512KP = CMSTestUtil.makeMLKem512KeyPair(); + _reciMLKem512Cert = CMSTestUtil.makeCertificate(_reciMLKem512KP, _reciDN, _signKP, _signDN); + + _reciMLKem768KP = CMSTestUtil.makeMLKem768KeyPair(); + _reciMLKem768Cert = CMSTestUtil.makeCertificate(_reciMLKem768KP, _reciDN, _signKP, _signDN); + + _reciMLKem1024KP = CMSTestUtil.makeMLKem1024KeyPair(); + _reciMLKem1024Cert = CMSTestUtil.makeCertificate(_reciMLKem1024KP, _reciDN, _signKP, _signDN); } } @@ -700,6 +726,185 @@ public void testContentType() } } + public void testMLKem512() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + // Send response with encrypted certificate + CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); + + // note: use cert req ID as key ID, don't want to use issuer/serial in this case! + edGen.addRecipientInfoGenerator(new JceKEMRecipientInfoGenerator(_reciMLKem512Cert, CMSAlgorithm.AES128_WRAP) + .setKDF(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hkdf_with_sha256))); + + CMSEnvelopedData ed = edGen.generate( + new CMSProcessableByteArray(data), + new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build()); + + RecipientInformationStore recipients = ed.getRecipientInfos(); + + assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC); + + Collection c = recipients.getRecipients(); + + assertEquals(1, c.size()); + + Iterator it = c.iterator(); + + int expectedLength = new DefaultKemEncapsulationLengthProvider().getEncapsulationLength( + SubjectPublicKeyInfo.getInstance(_reciMLKem512KP.getPublic().getEncoded()).getAlgorithm()); + + while (it.hasNext()) + { + KEMRecipientInformation recipient = (KEMRecipientInformation)it.next(); + + assertEquals(expectedLength, recipient.getEncapsulation().length); + + assertEquals(NISTObjectIdentifiers.id_alg_ml_kem_512.getId(), recipient.getKeyEncryptionAlgOID()); + + CMSTypedStream contentStream = recipient.getContentStream( + new JceKEMEnvelopedRecipient(_reciMLKem512KP.getPrivate()).setProvider(BC)); + + assertEquals(PKCSObjectIdentifiers.data, contentStream.getContentType()); + assertEquals(true, Arrays.equals(data, Streams.readAll(contentStream.getContentStream()))); + } + } + + public void testMLKem768() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + // Send response with encrypted certificate + CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); + + // note: use cert req ID as key ID, don't want to use issuer/serial in this case! + edGen.addRecipientInfoGenerator(new JceKEMRecipientInfoGenerator(_reciMLKem768Cert, CMSAlgorithm.AES256_WRAP) + .setKDF(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hkdf_with_sha256))); + + CMSEnvelopedData ed = edGen.generate( + new CMSProcessableByteArray(data), + new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider("BC").build()); + + RecipientInformationStore recipients = ed.getRecipientInfos(); + + assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES256_CBC); + + Collection c = recipients.getRecipients(); + + assertEquals(1, c.size()); + + Iterator it = c.iterator(); + + int expectedLength = new DefaultKemEncapsulationLengthProvider().getEncapsulationLength( + SubjectPublicKeyInfo.getInstance(_reciMLKem768KP.getPublic().getEncoded()).getAlgorithm()); + + while (it.hasNext()) + { + KEMRecipientInformation recipient = (KEMRecipientInformation)it.next(); + + assertEquals(expectedLength, recipient.getEncapsulation().length); + + assertEquals(NISTObjectIdentifiers.id_alg_ml_kem_768.getId(), recipient.getKeyEncryptionAlgOID()); + + CMSTypedStream contentStream = recipient.getContentStream( + new JceKEMEnvelopedRecipient(_reciMLKem768KP.getPrivate()).setProvider(BC)); + + assertEquals(PKCSObjectIdentifiers.data, contentStream.getContentType()); + assertEquals(true, Arrays.equals(data, Streams.readAll(contentStream.getContentStream()))); + } + } + + public void testMLKem1024() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + // Send response with encrypted certificate + CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); + + // note: use cert req ID as key ID, don't want to use issuer/serial in this case! + edGen.addRecipientInfoGenerator(new JceKEMRecipientInfoGenerator(_reciMLKem1024Cert, CMSAlgorithm.AES256_WRAP) + .setKDF(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_alg_hkdf_with_sha256))); + + CMSEnvelopedData ed = edGen.generate( + new CMSProcessableByteArray(data), + new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider("BC").build()); + + RecipientInformationStore recipients = ed.getRecipientInfos(); + + assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES256_CBC); + + Collection c = recipients.getRecipients(); + + assertEquals(1, c.size()); + + Iterator it = c.iterator(); + + int expectedLength = new DefaultKemEncapsulationLengthProvider().getEncapsulationLength( + SubjectPublicKeyInfo.getInstance(_reciMLKem1024KP.getPublic().getEncoded()).getAlgorithm()); + + while (it.hasNext()) + { + KEMRecipientInformation recipient = (KEMRecipientInformation)it.next(); + + assertEquals(expectedLength, recipient.getEncapsulation().length); + + assertEquals(NISTObjectIdentifiers.id_alg_ml_kem_1024.getId(), recipient.getKeyEncryptionAlgOID()); + + CMSTypedStream contentStream = recipient.getContentStream( + new JceKEMEnvelopedRecipient(_reciMLKem1024KP.getPrivate()).setProvider(BC)); + + assertEquals(PKCSObjectIdentifiers.data, contentStream.getContentType()); + assertEquals(true, Arrays.equals(data, Streams.readAll(contentStream.getContentStream()))); + } + } + + public void testNtruKem() + throws Exception + { + byte[] data = "WallaWallaWashington".getBytes(); + + // Send response with encrypted certificate + CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); + + // note: use cert req ID as key ID, don't want to use issuer/serial in this case! + edGen.addRecipientInfoGenerator(new JceKEMRecipientInfoGenerator(_reciNtruCert, CMSAlgorithm.AES256_WRAP).setKDF( + new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256))); + + CMSEnvelopedData ed = edGen.generate( + new CMSProcessableByteArray(data), + new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build()); + + RecipientInformationStore recipients = ed.getRecipientInfos(); + + assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC); + + Collection c = recipients.getRecipients(); + + assertEquals(1, c.size()); + + Iterator it = c.iterator(); + + int expectedLength = new DefaultKemEncapsulationLengthProvider().getEncapsulationLength( + SubjectPublicKeyInfo.getInstance(_reciNtruKP.getPublic().getEncoded()).getAlgorithm()); + + while (it.hasNext()) + { + KEMRecipientInformation recipient = (KEMRecipientInformation)it.next(); + + assertEquals(expectedLength, recipient.getEncapsulation().length); + + assertEquals(BCObjectIdentifiers.ntruhps2048509.getId(), recipient.getKeyEncryptionAlgOID()); + + CMSTypedStream contentStream = recipient.getContentStream(new JceKEMEnvelopedRecipient(_reciNtruKP.getPrivate()).setProvider(BC)); + + assertEquals(PKCSObjectIdentifiers.data, contentStream.getContentType()); + assertEquals(true, Arrays.equals(data, Streams.readAll(contentStream.getContentStream()))); + } + } + // TODO: add KEMS to provider. // public void testRsaKEMS() // throws Exception diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java b/pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java index fa668e9321..5e41a1c9a0 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java @@ -1,7 +1,11 @@ package org.bouncycastle.cms.test; -import java.io.ByteArrayInputStream; +import java.io.BufferedInputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; import java.security.KeyFactory; import java.security.KeyPair; import java.security.MessageDigest; @@ -27,7 +31,6 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; @@ -48,12 +51,16 @@ import org.bouncycastle.asn1.cms.SignedData; import org.bouncycastle.asn1.cms.SignerInfo; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; +import org.bouncycastle.asn1.ess.ESSCertIDv2; +import org.bouncycastle.asn1.ess.SigningCertificateV2; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.ocsp.OCSPResponse; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; +import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.IssuerSerial; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.bouncycastle.cert.X509CertificateHolder; @@ -63,6 +70,7 @@ import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.cert.ocsp.OCSPResp; +import org.bouncycastle.cert.test.SampleCredentials; import org.bouncycastle.cms.CMSAbsentContent; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSAttributeTableGenerationException; @@ -76,6 +84,7 @@ import org.bouncycastle.cms.DefaultCMSSignatureAlgorithmNameGenerator; import org.bouncycastle.cms.DefaultSignedAttributeTableGenerator; import org.bouncycastle.cms.SignerId; +import org.bouncycastle.cms.SignerInfoGenerator; import org.bouncycastle.cms.SignerInfoGeneratorBuilder; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.SignerInformationStore; @@ -92,6 +101,7 @@ import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; +import org.bouncycastle.operator.DigestCalculator; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.bc.BcContentSignerBuilder; @@ -99,10 +109,13 @@ import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.CollectionStore; import org.bouncycastle.util.Store; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.io.Streams; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; public class NewSignedDataTest extends TestCase @@ -137,6 +150,38 @@ public class NewSignedDataTest private static KeyPair _signEd448KP; private static X509Certificate _signEd448Cert; + private static KeyPair _signMLDsa44KP; + private static X509Certificate _signMLDsa44Cert; + private static KeyPair _signMLDsa65KP; + private static X509Certificate _signMLDsa65Cert; + private static KeyPair _signMLDsa87KP; + private static X509Certificate _signMLDsa87Cert; + + private static KeyPair _signSlhDsa_Sha2_128f_KP; + private static X509Certificate _signSlhDsa_Sha2_128f_Cert; + private static KeyPair _signSlhDsa_Sha2_128s_KP; + private static X509Certificate _signSlhDsa_Sha2_128s_Cert; + private static KeyPair _signSlhDsa_Sha2_192f_KP; + private static X509Certificate _signSlhDsa_Sha2_192f_Cert; + private static KeyPair _signSlhDsa_Sha2_192s_KP; + private static X509Certificate _signSlhDsa_Sha2_192s_Cert; + private static KeyPair _signSlhDsa_Sha2_256f_KP; + private static X509Certificate _signSlhDsa_Sha2_256f_Cert; + private static KeyPair _signSlhDsa_Sha2_256s_KP; + private static X509Certificate _signSlhDsa_Sha2_256s_Cert; + private static KeyPair _signSlhDsa_Shake_128f_KP; + private static X509Certificate _signSlhDsa_Shake_128f_Cert; + private static KeyPair _signSlhDsa_Shake_128s_KP; + private static X509Certificate _signSlhDsa_Shake_128s_Cert; + private static KeyPair _signSlhDsa_Shake_192f_KP; + private static X509Certificate _signSlhDsa_Shake_192f_Cert; + private static KeyPair _signSlhDsa_Shake_192s_KP; + private static X509Certificate _signSlhDsa_Shake_192s_Cert; + private static KeyPair _signSlhDsa_Shake_256f_KP; + private static X509Certificate _signSlhDsa_Shake_256f_Cert; + private static KeyPair _signSlhDsa_Shake_256s_KP; + private static X509Certificate _signSlhDsa_Shake_256s_Cert; + private static String _reciDN; private static KeyPair _reciKP; private static X509Certificate _reciCert; @@ -675,6 +720,29 @@ public class NewSignedDataTest "CiwhMCLDeeEBOdxWZHVbIiFnnRTQqyIDGAOSSIUmjE/pMPKpPvumkCGq2r9GxPV9\n" + "YlpnThaYbDCnWg8tbWYAAAAAAAA="); + private static byte[] signedData_mldsa44 = loadPemContents("pkix/cms/mldsa", "SignedData_ML-DSA-44.pem"); + private static byte[] signedData_mldsa65 = loadPemContents("pkix/cms/mldsa", "SignedData_ML-DSA-65.pem"); + private static byte[] signedData_mldsa87 = loadPemContents("pkix/cms/mldsa", "SignedData_ML-DSA-87.pem"); + + private static byte[] loadPemContents(String path, String name) + { + try + { + InputStream input = new BufferedInputStream(TestResourceFinder.findTestResource(path, name)); + Reader reader = new InputStreamReader(input); + + PemReader pemReader = new PemReader(reader); + PemObject pemObject = pemReader.readPemObject(); + pemReader.close(); + + return pemObject.getContent(); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } + static { noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); @@ -697,8 +765,23 @@ public class NewSignedDataTest noParams.add(NISTObjectIdentifiers.id_ecdsa_with_sha3_512); noParams.add(EdECObjectIdentifiers.id_Ed25519); noParams.add(EdECObjectIdentifiers.id_Ed448); + noParams.add(NISTObjectIdentifiers.id_ml_dsa_44); + noParams.add(NISTObjectIdentifiers.id_ml_dsa_65); + noParams.add(NISTObjectIdentifiers.id_ml_dsa_87); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_128f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_128s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_192f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_192s); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_256f); + noParams.add(NISTObjectIdentifiers.id_slh_dsa_shake_256s); } - + public NewSignedDataTest(String name) { super(name); @@ -769,6 +852,51 @@ private static void init() _signEd448KP = CMSTestUtil.makeEd448KeyPair(); _signEd448Cert = CMSTestUtil.makeCertificate(_signEd448KP, _signDN, _origKP, _origDN); + _signMLDsa44KP = CMSTestUtil.makeMLDsa44KeyPair(); + _signMLDsa44Cert = CMSTestUtil.makeCertificate(_signMLDsa44KP, _signDN, _origKP, _origDN); + + _signMLDsa65KP = CMSTestUtil.makeMLDsa65KeyPair(); + _signMLDsa65Cert = CMSTestUtil.makeCertificate(_signMLDsa65KP, _signDN, _origKP, _origDN); + + _signMLDsa87KP = CMSTestUtil.makeMLDsa87KeyPair(); + _signMLDsa87Cert = CMSTestUtil.makeCertificate(_signMLDsa87KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Sha2_128f_KP = CMSTestUtil.makeSlhDsa_Sha2_128f_KeyPair(); + _signSlhDsa_Sha2_128f_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Sha2_128f_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Sha2_128s_KP = CMSTestUtil.makeSlhDsa_Sha2_128s_KeyPair(); + _signSlhDsa_Sha2_128s_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Sha2_128s_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Sha2_192f_KP = CMSTestUtil.makeSlhDsa_Sha2_192f_KeyPair(); + _signSlhDsa_Sha2_192f_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Sha2_192f_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Sha2_192s_KP = CMSTestUtil.makeSlhDsa_Sha2_192s_KeyPair(); + _signSlhDsa_Sha2_192s_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Sha2_192s_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Sha2_256f_KP = CMSTestUtil.makeSlhDsa_Sha2_256f_KeyPair(); + _signSlhDsa_Sha2_256f_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Sha2_256f_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Sha2_256s_KP = CMSTestUtil.makeSlhDsa_Sha2_256s_KeyPair(); + _signSlhDsa_Sha2_256s_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Sha2_256s_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Shake_128f_KP = CMSTestUtil.makeSlhDsa_Shake_128f_KeyPair(); + _signSlhDsa_Shake_128f_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Shake_128f_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Shake_128s_KP = CMSTestUtil.makeSlhDsa_Shake_128s_KeyPair(); + _signSlhDsa_Shake_128s_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Shake_128s_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Shake_192f_KP = CMSTestUtil.makeSlhDsa_Shake_192f_KeyPair(); + _signSlhDsa_Shake_192f_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Shake_192f_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Shake_192s_KP = CMSTestUtil.makeSlhDsa_Shake_192s_KeyPair(); + _signSlhDsa_Shake_192s_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Shake_192s_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Shake_256f_KP = CMSTestUtil.makeSlhDsa_Shake_256f_KeyPair(); + _signSlhDsa_Shake_256f_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Shake_256f_KP, _signDN, _origKP, _origDN); + + _signSlhDsa_Shake_256s_KP = CMSTestUtil.makeSlhDsa_Shake_256s_KeyPair(); + _signSlhDsa_Shake_256s_Cert = CMSTestUtil.makeCertificate(_signSlhDsa_Shake_256s_KP, _signDN, _origKP, _origDN); + _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; _reciKP = CMSTestUtil.makeKeyPair(); _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); @@ -928,10 +1056,7 @@ public void testSHA1AndMD5WithRSAEncapsulatedRepeated() CMSSignedData s = gen.generate(msg, true); - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + s = new CMSSignedData(s.getEncoded()); certs = s.getCertificates(); @@ -984,10 +1109,7 @@ public void testSHA1AndMD5WithRSAEncapsulatedRepeated() s = gen.generate(msg, true); - bIn = new ByteArrayInputStream(s.getEncoded()); - aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + s = new CMSSignedData(s.getEncoded()); certs = s.getCertificates(); @@ -1378,6 +1500,9 @@ public void testSHA1WithRSAAndAttributeTable() // compute expected content digest // + assertTrue(s.isDetachedSignature()); + assertFalse(s.isCertificateManagementMessage()); + verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } @@ -1782,25 +1907,36 @@ public void testSHA512_256ithRSADigest() public void testEd25519() throws Exception { - encapsulatedTest(_signEd25519KP, _signEd25519Cert, "Ed25519", EdECObjectIdentifiers.id_Ed25519, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512)); + /* + * RFC 8419 3.1. When signing with Ed25519, the digestAlgorithm MUST be id-sha512, and the algorithm + * parameters field MUST be absent. + * + * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. + */ + AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); + + detachedTest(_signEd25519KP, _signEd25519Cert, "Ed25519", EdECObjectIdentifiers.id_Ed25519, expectedDigAlgId); + + encapsulatedTest(_signEd25519KP, _signEd25519Cert, "Ed25519", EdECObjectIdentifiers.id_Ed25519, + expectedDigAlgId); } public void testEd448() throws Exception { - encapsulatedTest(_signEd448KP, _signEd448Cert, "Ed448", EdECObjectIdentifiers.id_Ed448, new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256_len, new ASN1Integer(512))); - } + /* + * RFC 8419 3.1. When signing with Ed448, the digestAlgorithm MUST be id-shake256-len, the algorithm + * parameters field MUST be present, and the parameter MUST contain 512, encoded as a positive integer + * value. + * + * We confirm here that our implementation defaults to id-shake256-len/512 for the digest algorithm. + */ + AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256_len, + new ASN1Integer(512)); - public void testDetachedEd25519() - throws Exception - { - detachedTest(_signEd25519KP, _signEd25519Cert, "Ed25519", EdECObjectIdentifiers.id_Ed25519, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512)); - } + detachedTest(_signEd448KP, _signEd448Cert, "Ed448", EdECObjectIdentifiers.id_Ed448, expectedDigAlgId); - public void testEdDetached448() - throws Exception - { - detachedTest(_signEd448KP, _signEd448Cert, "Ed448", EdECObjectIdentifiers.id_Ed448, new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256_len, new ASN1Integer(512))); + encapsulatedTest(_signEd448KP, _signEd448Cert, "Ed448", EdECObjectIdentifiers.id_Ed448, expectedDigAlgId); } public void testEd25519WithNoAttr() @@ -1931,6 +2067,17 @@ public void testECDSASHA512Encapsulated() encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA512withECDSA"); } + public void testECDSASHA512EncapsulatedWithKeyFactoryAsEC() + throws Exception + { + X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(_signEcDsaKP.getPublic().getEncoded()); + PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(_signEcDsaKP.getPrivate().getEncoded()); + KeyFactory keyFact = KeyFactory.getInstance("EC", BC); + KeyPair kp = new KeyPair(keyFact.generatePublic(pubSpec), keyFact.generatePrivate(privSpec)); + + encapsulatedTest(kp, _signEcDsaCert, "SHA512withECDSA"); + } + public void testECDSASHA3_224Encapsulated() throws Exception { @@ -2003,17 +2150,6 @@ public void testPLAIN_ECDSASHA3_512Encapsulated() encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA3-512withPLAIN-ECDSA"); } - public void testECDSASHA512EncapsulatedWithKeyFactoryAsEC() - throws Exception - { - X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(_signEcDsaKP.getPublic().getEncoded()); - PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(_signEcDsaKP.getPrivate().getEncoded()); - KeyFactory keyFact = KeyFactory.getInstance("EC", BC); - KeyPair kp = new KeyPair(keyFact.generatePublic(pubSpec), keyFact.generatePrivate(privSpec)); - - encapsulatedTest(kp, _signEcDsaCert, "SHA512withECDSA"); - } - public void testDSAEncapsulated() throws Exception { @@ -2263,6 +2399,270 @@ public SignerInformationVerifier get(SignerId signerId) assertTrue(digAlgs.contains(new AlgorithmIdentifier(TeleTrusTObjectIdentifiers.ripemd160, DERNull.INSTANCE))); } +// public void testMLDsa44() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-ml-dsa-02 3.3. SHA-512 [FIPS180] MUST be supported for use with the variants +// * of ML-DSA in this document; however, other hash functions MAY also be supported. When SHA-512 is +// * used, the id-sha512 [RFC5754] digest algorithm identifier is used and the parameters field MUST be +// * omitted. +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signMLDsa44KP, _signMLDsa44Cert, "ML-DSA-44", NISTObjectIdentifiers.id_ml_dsa_44, +// expectedDigAlgId); +// +// encapsulatedTest(_signMLDsa44KP, _signMLDsa44Cert, "ML-DSA-44", NISTObjectIdentifiers.id_ml_dsa_44, +// expectedDigAlgId); +// } +// +// public void testMLDsa65() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-ml-dsa-02 3.3. SHA-512 [FIPS180] MUST be supported for use with the variants +// * of ML-DSA in this document; however, other hash functions MAY also be supported. When SHA-512 is +// * used, the id-sha512 [RFC5754] digest algorithm identifier is used and the parameters field MUST be +// * omitted. +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signMLDsa65KP, _signMLDsa65Cert, "ML-DSA-65", NISTObjectIdentifiers.id_ml_dsa_65, +// expectedDigAlgId); +// +// encapsulatedTest(_signMLDsa65KP, _signMLDsa65Cert, "ML-DSA-65", NISTObjectIdentifiers.id_ml_dsa_65, +// expectedDigAlgId); +// } +// +// public void testMLDsa87() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-ml-dsa-02 3.3. SHA-512 [FIPS180] MUST be supported for use with the variants +// * of ML-DSA in this document; however, other hash functions MAY also be supported. When SHA-512 is +// * used, the id-sha512 [RFC5754] digest algorithm identifier is used and the parameters field MUST be +// * omitted. +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signMLDsa87KP, _signMLDsa87Cert, "ML-DSA-87", NISTObjectIdentifiers.id_ml_dsa_87, +// expectedDigAlgId); +// +// encapsulatedTest(_signMLDsa87KP, _signMLDsa87Cert, "ML-DSA-87", NISTObjectIdentifiers.id_ml_dsa_87, +// expectedDigAlgId); +// } + +// public void testSlhDsa_Sha2_128f() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHA-256 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256); +// +// detachedTest(_signSlhDsa_Sha2_128f_KP, _signSlhDsa_Sha2_128f_Cert, "SLH-DSA-SHA2-128F", +// NISTObjectIdentifiers.id_slh_dsa_sha2_128f, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Sha2_128f_KP, _signSlhDsa_Sha2_128f_Cert, "SLH-DSA-SHA2-128F", +// NISTObjectIdentifiers.id_slh_dsa_sha2_128f, expectedDigAlgId); +// } +// +// public void testSlhDsa_Sha2_128s() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHA-256 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256); +// +// detachedTest(_signSlhDsa_Sha2_128s_KP, _signSlhDsa_Sha2_128s_Cert, "SLH-DSA-SHA2-128S", +// NISTObjectIdentifiers.id_slh_dsa_sha2_128s, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Sha2_128s_KP, _signSlhDsa_Sha2_128s_Cert, "SLH-DSA-SHA2-128S", +// NISTObjectIdentifiers.id_slh_dsa_sha2_128s, expectedDigAlgId); +// } +// +// public void testSlhDsa_Sha2_192f() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signSlhDsa_Sha2_192f_KP, _signSlhDsa_Sha2_192f_Cert, "SLH-DSA-SHA2-192F", +// NISTObjectIdentifiers.id_slh_dsa_sha2_192f, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Sha2_192f_KP, _signSlhDsa_Sha2_192f_Cert, "SLH-DSA-SHA2-192F", +// NISTObjectIdentifiers.id_slh_dsa_sha2_192f, expectedDigAlgId); +// } +// +// public void testSlhDsa_Sha2_192s() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signSlhDsa_Sha2_192s_KP, _signSlhDsa_Sha2_192s_Cert, "SLH-DSA-SHA2-192S", +// NISTObjectIdentifiers.id_slh_dsa_sha2_192s, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Sha2_192s_KP, _signSlhDsa_Sha2_192s_Cert, "SLH-DSA-SHA2-192S", +// NISTObjectIdentifiers.id_slh_dsa_sha2_192s, expectedDigAlgId); +// } +// +// public void testSlhDsa_Sha2_256f() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signSlhDsa_Sha2_256f_KP, _signSlhDsa_Sha2_256f_Cert, "SLH-DSA-SHA2-256F", +// NISTObjectIdentifiers.id_slh_dsa_sha2_256f, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Sha2_256f_KP, _signSlhDsa_Sha2_256f_Cert, "SLH-DSA-SHA2-256F", +// NISTObjectIdentifiers.id_slh_dsa_sha2_256f, expectedDigAlgId); +// } +// +// public void testSlhDsa_Sha2_256s() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHA-512 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512); +// +// detachedTest(_signSlhDsa_Sha2_256s_KP, _signSlhDsa_Sha2_256s_Cert, "SLH-DSA-SHA2-256S", +// NISTObjectIdentifiers.id_slh_dsa_sha2_256s, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Sha2_256s_KP, _signSlhDsa_Sha2_256s_Cert, "SLH-DSA-SHA2-256S", +// NISTObjectIdentifiers.id_slh_dsa_sha2_256s, expectedDigAlgId); +// } +// +// public void testSlhDsa_Shake_128f() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHAKE-128 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake128); +// +// detachedTest(_signSlhDsa_Shake_128f_KP, _signSlhDsa_Shake_128f_Cert, "SLH-DSA-SHAKE-128F", +// NISTObjectIdentifiers.id_slh_dsa_shake_128f, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Shake_128f_KP, _signSlhDsa_Shake_128f_Cert, "SLH-DSA-SHAKE-128F", +// NISTObjectIdentifiers.id_slh_dsa_shake_128f, expectedDigAlgId); +// } +// +// public void testSlhDsa_Shake_128s() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHAKE-128 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake128); +// +// detachedTest(_signSlhDsa_Shake_128s_KP, _signSlhDsa_Shake_128s_Cert, "SLH-DSA-SHAKE-128S", +// NISTObjectIdentifiers.id_slh_dsa_shake_128s, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Shake_128s_KP, _signSlhDsa_Shake_128s_Cert, "SLH-DSA-SHAKE-128S", +// NISTObjectIdentifiers.id_slh_dsa_shake_128s, expectedDigAlgId); +// } +// +// public void testSlhDsa_Shake_192f() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHAKE-256 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256); +// +// detachedTest(_signSlhDsa_Shake_192f_KP, _signSlhDsa_Shake_192f_Cert, "SLH-DSA-SHAKE-192F", +// NISTObjectIdentifiers.id_slh_dsa_shake_192f, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Shake_192f_KP, _signSlhDsa_Shake_192f_Cert, "SLH-DSA-SHAKE-192F", +// NISTObjectIdentifiers.id_slh_dsa_shake_192f, expectedDigAlgId); +// } +// +// public void testSlhDsa_Shake_192s() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHAKE-256 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256); +// +// detachedTest(_signSlhDsa_Shake_192s_KP, _signSlhDsa_Shake_192s_Cert, "SLH-DSA-SHAKE-192S", +// NISTObjectIdentifiers.id_slh_dsa_shake_192s, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Shake_192s_KP, _signSlhDsa_Shake_192s_Cert, "SLH-DSA-SHAKE-192S", +// NISTObjectIdentifiers.id_slh_dsa_shake_192s, expectedDigAlgId); +// } +// +// public void testSlhDsa_Shake_256f() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHAKE-256 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256); +// +// detachedTest(_signSlhDsa_Shake_256f_KP, _signSlhDsa_Shake_256f_Cert, "SLH-DSA-SHAKE-256F", +// NISTObjectIdentifiers.id_slh_dsa_shake_256f, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Shake_256f_KP, _signSlhDsa_Shake_256f_Cert, "SLH-DSA-SHAKE-256F", +// NISTObjectIdentifiers.id_slh_dsa_shake_256f, expectedDigAlgId); +// } +// +// public void testSlhDsa_Shake_256s() +// throws Exception +// { +// /* +// * draft-ietf-lamps-cms-sphincs-plus-19 4. (we initially only support the MUST-support algorithm) +// * +// * We confirm here that our implementation defaults to SHAKE-256 for the digest algorithm. +// */ +// AlgorithmIdentifier expectedDigAlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_shake256); +// +// detachedTest(_signSlhDsa_Shake_256s_KP, _signSlhDsa_Shake_256s_Cert, "SLH-DSA-SHAKE-256S", +// NISTObjectIdentifiers.id_slh_dsa_shake_256s, expectedDigAlgId); +// +// encapsulatedTest(_signSlhDsa_Shake_256s_KP, _signSlhDsa_Shake_256s_Cert, "SLH-DSA-SHAKE-256S", +// NISTObjectIdentifiers.id_slh_dsa_shake_256s, expectedDigAlgId); +// } + private void rsaPSSTest(String signatureAlgorithmName) throws Exception { @@ -2392,11 +2792,8 @@ private void subjectKeyIDTest( CMSSignedData s = gen.generate(msg, true); assertEquals(3, s.getVersion()); - - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + s = new CMSSignedData(s.getEncoded()); certStore = s.getCertificates(); @@ -2436,10 +2833,7 @@ private void subjectKeyIDTest( s = gen.generate(msg, true); - bIn = new ByteArrayInputStream(s.getEncoded()); - aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + s = new CMSSignedData(s.getEncoded()); certStore = s.getCertificates(); @@ -2485,47 +2879,49 @@ private void encapsulatedTest( X509Certificate signatureCert, String signatureAlgorithm, ASN1ObjectIdentifier sigAlgOid, - AlgorithmIdentifier digAlgId) + AlgorithmIdentifier expectedDigAlgId) throws Exception { - List certList = new ArrayList(); - List crlList = new ArrayList(); - CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); - + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + List certList = new ArrayList(); + List crlList = new ArrayList(); + certList.add(signatureCert); certList.add(_origCert); crlList.add(_signCrl); - Store certs = new JcaCertStore(certList); - Store crlStore = new JcaCRLStore(crlList); + Store certStore = new JcaCertStore(certList); + Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC).build(signaturePair.getPrivate()); - gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(contentSigner, signatureCert)); + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); - gen.addCertificates(certs); - - CMSSignedData s = gen.generate(msg, true); + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(contentSigner, signatureCert)); - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); + gen.addCertificates(certStore); + gen.addCRLs(crlStore); - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + CMSSignedData s = gen.generate(msg, true); + + s = new CMSSignedData(s.getEncoded()); Set digestAlgorithms = new HashSet(s.getDigestAlgorithmIDs()); assertTrue(digestAlgorithms.size() > 0); - if (digAlgId != null) + if (expectedDigAlgId != null) { - assertTrue(digestAlgorithms.contains(digAlgId)); + assertTrue(digestAlgorithms.contains(expectedDigAlgId)); } - certs = s.getCertificates(); - + certStore = s.getCertificates(); + crlStore = s.getCRLs(); + SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); @@ -2533,7 +2929,7 @@ private void encapsulatedTest( while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getMatches(signer.getSID()); + Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); @@ -2585,18 +2981,17 @@ private void encapsulatedTest( gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); - + gen.addCertificates(s.getCertificates()); - + gen.addCRLs(s.getCRLs()); + s = gen.generate(msg, true); - - bIn = new ByteArrayInputStream(s.getEncoded()); - aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certs = s.getCertificates(); - + + s = new CMSSignedData(s.getEncoded()); + + certStore = s.getCertificates(); + crlStore = s.getCRLs(); + signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); @@ -2604,7 +2999,7 @@ private void encapsulatedTest( while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getMatches(signer.getSID()); + Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); @@ -2648,12 +3043,9 @@ private void detachedTest( gen.addCertificates(certs); - CMSSignedData s = gen.generate(msg, true); - - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); + CMSSignedData s = gen.generate(msg); - s = new CMSSignedData(msg, ContentInfo.getInstance(aIn.readObject())); + s = new CMSSignedData(msg, s.getEncoded()); Set digestAlgorithms = new HashSet(s.getDigestAlgorithmIDs()); @@ -2820,10 +3212,7 @@ public void testNullContentWithSigner() CMSSignedData s = gen.generate(new CMSAbsentContent(), false); - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + s = new CMSSignedData(s.getEncoded()); verifySignatures(s); } @@ -3167,11 +3556,14 @@ public void testCertificateManagement() CMSSignedData sData = sGen.generate(new CMSAbsentContent(), true); - CMSSignedData rsData = new CMSSignedData(sData.getEncoded()); - assertTrue(sData.isCertificateManagementMessage()); assertFalse(sData.isDetachedSignature()); + CMSSignedData rsData = new CMSSignedData(sData.getEncoded()); + + assertTrue(rsData.isCertificateManagementMessage()); + assertFalse(rsData.isDetachedSignature()); + assertEquals(2, rsData.getCertificates().getMatches(null).size()); } @@ -3203,6 +3595,54 @@ public void testMixed() } } + public void testSignerInfoGenCopyConstructor() + throws Exception + { + ContentSigner sha256Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider(BC).build(_origKP.getPrivate()); + final SignerInfoGenerator signerInfoGen = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha256Signer, _origCert); + + DigestCalculator digCalc = new SHA256DigestCalculator(); + + OutputStream dOut = digCalc.getOutputStream(); + + dOut.write(_origCert.getEncoded()); + + dOut.close(); + + byte[] certHash256 = digCalc.getDigest(); + final ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(certHash256, new IssuerSerial(X500Name.getInstance(_origCert.getIssuerX500Principal().getEncoded()), _origCert.getSerialNumber())); + + CMSAttributeTableGenerator signedAttrGen = new CMSAttributeTableGenerator() + { + public AttributeTable getAttributes(Map parameters) + throws CMSAttributeTableGenerationException + { + AttributeTable table = signerInfoGen.getSignedAttributeTableGenerator().getAttributes(parameters); + + if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) == null) + { + return table.add(PKCSObjectIdentifiers.id_aa_signingCertificateV2, + new SigningCertificateV2(essCertIDv2)); + } + + return table; + } + }; + SignerInfoGenerator newSignerInfoGen = new SignerInfoGenerator(signerInfoGen, signedAttrGen, signerInfoGen.getUnsignedAttributeTableGenerator()); + + assertTrue(signerInfoGen.hasAssociatedCertificate()); + assertTrue(newSignerInfoGen.hasAssociatedCertificate()); + assertTrue(signerInfoGen.getUnsignedAttributeTableGenerator() == newSignerInfoGen.getUnsignedAttributeTableGenerator()); + assertTrue(newSignerInfoGen.getSignedAttributeTableGenerator() == signedAttrGen); + } + + public void testEU() + throws Exception + { + System.setProperty("org.bouncycastle.asn1.allow_wrong_oid_enc", "true"); + CMSSignedData cmsSignedData = new CMSSignedData(this.getInput("bc1639test.p7m")); + System.setProperty("org.bouncycastle.asn1.allow_wrong_oid_enc", "false"); + } public void testMSPKCS7() throws Exception { @@ -3302,6 +3742,24 @@ public void testForMultipleCounterSignatures() } } + public void testVerifySignedDataMLDsa44() + throws Exception + { + implTestVerifySignedData(signedData_mldsa44, SampleCredentials.ML_DSA_44); + } + + public void testVerifySignedDataMLDsa65() + throws Exception + { + implTestVerifySignedData(signedData_mldsa65, SampleCredentials.ML_DSA_65); + } + + public void testVerifySignedDataMLDsa87() + throws Exception + { + implTestVerifySignedData(signedData_mldsa87, SampleCredentials.ML_DSA_87); + } + private void verifySignatures(CMSSignedDataParser sp) throws Exception { @@ -3323,6 +3781,40 @@ private void verifySignatures(CMSSignedDataParser sp) } } + private static void implTestVerifySignedData(byte[] signedData, final SampleCredentials credentials) + throws Exception + { + CMSSignedData sd = new CMSSignedData(signedData); + + // Verify using the certificate from the supplied credentials + SignerInformationVerifierProvider verifierProvider = new SignerInformationVerifierProvider() + { + public SignerInformationVerifier get(SignerId signerId) + throws OperatorCreationException + { + return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(credentials.getCertificate()); + } + }; + + // External signer verification + { + SignerInformationStore signers = sd.getSignerInfos(); + + Iterator it = signers.getSigners().iterator(); + while (it.hasNext()) + { + SignerInformation signer = (SignerInformation)it.next(); + + SignerInformationVerifier verifier = verifierProvider.get(signer.getSID()); + + assertTrue(signer.verify(verifier)); + } + } + + // Built-in signer verification + assertTrue(sd.verifySignatures(verifierProvider)); + } + private static class TestCMSSignatureAlgorithmNameGenerator extends DefaultCMSSignatureAlgorithmNameGenerator { diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/PQCSignedDataTest.java b/pkix/src/test/java/org/bouncycastle/cms/test/PQCSignedDataTest.java index af620646d4..414b5b4c9f 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/PQCSignedDataTest.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/PQCSignedDataTest.java @@ -1,12 +1,18 @@ package org.bouncycastle.cms.test; import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.math.BigInteger; import java.security.KeyPair; import java.security.MessageDigest; +import java.security.SecureRandom; import java.security.Security; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; +import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -22,8 +28,19 @@ import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.ContentInfo; +import org.bouncycastle.asn1.cms.SignerInfo; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.RFC4519Style; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v1CertificateBuilder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.bc.BcX509v1CertificateBuilder; +import org.bouncycastle.cert.bc.BcX509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaCertStore; +import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; @@ -33,10 +50,25 @@ import org.bouncycastle.cms.SignerInformationStore; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.DigestCalculatorProvider; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.bc.BcHssLmsContentSignerBuilder; +import org.bouncycastle.operator.bc.BcHssLmsContentVerifierProviderBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.bouncycastle.pqc.crypto.lms.HSSKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.lms.HSSKeyPairGenerator; +import org.bouncycastle.pqc.crypto.lms.HSSPublicKeyParameters; +import org.bouncycastle.pqc.crypto.lms.LMOtsParameters; +import org.bouncycastle.pqc.crypto.lms.LMSKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.lms.LMSKeyPairGenerator; +import org.bouncycastle.pqc.crypto.lms.LMSParameters; +import org.bouncycastle.pqc.crypto.lms.LMSigParameters; import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; import org.bouncycastle.util.Store; @@ -51,23 +83,32 @@ public class PQCSignedDataTest private static String _origDN; private static KeyPair _origKP; private static X509Certificate _origCert; + + private static KeyPair _origLmsKP; + private static X509Certificate _origLmsCert; private static KeyPair _origFalconKP; private static X509Certificate _origFalconCert; private static KeyPair _origPicnicKP; private static X509Certificate _origPicnicCert; - private static KeyPair _origDilithiumKP; - private static X509Certificate _origDilithiumCert; - + private static KeyPair _origMlDsaKP; + private static X509Certificate _origMlDsaCert; + private static KeyPair _origSlhDsaKP; + private static X509Certificate _origSlhDsaCert; + private static String _signDN; private static KeyPair _signKP; private static X509Certificate _signCert; + private static KeyPair _signLmsKP; + private static X509Certificate _signLmsCert; private static KeyPair _signFalconKP; private static X509Certificate _signFalconCert; private static KeyPair _signPicnicKP; private static X509Certificate _signPicnicCert; - private static KeyPair _signDilithiumKP; - private static X509Certificate _signDilithiumCert; - + private static KeyPair _signMlDsaKP; + private static X509Certificate _signMlDsaCert; + private static KeyPair _signSlhDsaKP; + private static X509Certificate _signSlhDsaCert; + private static boolean _initialised = false; private static final Set noParams = new HashSet(); @@ -87,7 +128,7 @@ public static void main(String args[]) throws Exception { init(); - + //checkCreationHssLms(); junit.textui.TestRunner.run(PQCSignedDataTest.class); } @@ -129,6 +170,12 @@ private static void init() _signKP = PQCTestUtil.makeKeyPair(); _signCert = PQCTestUtil.makeCertificate(_signKP, _signDN, _origKP, _origDN); + _origLmsKP = PQCTestUtil.makeLmsKeyPair(); + _origLmsCert = PQCTestUtil.makeCertificate(_origLmsKP, _origDN, _origLmsKP, _origDN); + + _signLmsKP = PQCTestUtil.makeLmsKeyPair(); + _signLmsCert = PQCTestUtil.makeCertificate(_signLmsKP, _signDN, _origLmsKP, _origDN); + _origFalconKP = PQCTestUtil.makeFalconKeyPair(); _origFalconCert = PQCTestUtil.makeCertificate(_origFalconKP, _origDN, _origFalconKP, _origDN); @@ -140,12 +187,18 @@ private static void init() _signPicnicKP = PQCTestUtil.makePicnicKeyPair(); _signPicnicCert = PQCTestUtil.makeCertificate(_signPicnicKP, _signDN, _origPicnicKP, _origDN); - - _origDilithiumKP = PQCTestUtil.makeDilithiumKeyPair(); - _origDilithiumCert = PQCTestUtil.makeCertificate(_origDilithiumKP, _origDN, _origDilithiumKP, _origDN); - - _signDilithiumKP = PQCTestUtil.makeDilithiumKeyPair(); - _signDilithiumCert = PQCTestUtil.makeCertificate(_signDilithiumKP, _signDN, _origDilithiumKP, _origDN); + + _origMlDsaKP = PQCTestUtil.makeMlDsaKeyPair(); + _origMlDsaCert = PQCTestUtil.makeCertificate(_origMlDsaKP, _origDN, _origMlDsaKP, _origDN); + + _signMlDsaKP = PQCTestUtil.makeMlDsaKeyPair(); + _signMlDsaCert = PQCTestUtil.makeCertificate(_signMlDsaKP, _signDN, _origMlDsaKP, _origDN); + + _origSlhDsaKP = PQCTestUtil.makeSlhDsaKeyPair(); + _origSlhDsaCert = PQCTestUtil.makeCertificate(_origSlhDsaKP, _origDN, _origSlhDsaKP, _origDN); + + _signSlhDsaKP = PQCTestUtil.makeSlhDsaKeyPair(); + _signSlhDsaCert = PQCTestUtil.makeCertificate(_signSlhDsaKP, _signDN, _origSlhDsaKP, _origDN); } } @@ -262,14 +315,14 @@ public void testFalconEncapsulated() } } - public void testPicnicEncapsulated() - throws Exception + public void testLmsEncapsulated() + throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); - certList.add(_origPicnicCert); - certList.add(_signPicnicCert); + certList.add(_origLmsCert); + certList.add(_signLmsCert); Store certs = new JcaCertStore(certList); @@ -277,7 +330,7 @@ public void testPicnicEncapsulated() DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); - gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("PICNIC").setProvider(BCPQC).build(_origPicnicKP.getPrivate()), _origPicnicCert)); + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("LMS", _origLmsCert.getPublicKey()).setProvider(BC).build(_origLmsKP.getPrivate()), _origLmsCert)); gen.addCertificates(certs); @@ -288,6 +341,11 @@ public void testPicnicEncapsulated() s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + Set digAlgIds = s.getDigestAlgorithmIDs(); + + assertTrue(digAlgIds.contains(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256))); + assertTrue(digAlgIds.size() == 1); + certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); @@ -295,7 +353,6 @@ public void testPicnicEncapsulated() Collection c = signers.getSigners(); Iterator it = c.iterator(); - while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); @@ -304,9 +361,7 @@ public void testPicnicEncapsulated() Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); - cert.getSubjectPublicKeyInfo(); - - assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))); + assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))); // // check content digest @@ -320,15 +375,180 @@ public void testPicnicEncapsulated() assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); } } - - public void testDilithiumEncapsulated() - throws Exception + + public void testCheckCreationHss() + throws Exception + { + // + // set up the keys + // + AsymmetricKeyParameter privKey; + AsymmetricKeyParameter pubKey; + + AsymmetricCipherKeyPairGenerator kpg = new HSSKeyPairGenerator(); + + kpg.init(new HSSKeyGenerationParameters( + new LMSParameters[]{new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w4), + new LMSParameters(LMSigParameters.lms_sha256_n24_h5, LMOtsParameters.sha256_n24_w4)}, new SecureRandom())); + + AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); + + privKey = (AsymmetricKeyParameter)pair.getPrivate(); + pubKey = (AsymmetricKeyParameter)pair.getPublic(); + + // + // distinguished name table. + // + X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); + + builder.addRDN(RFC4519Style.c, "AU"); + builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); + builder.addRDN(RFC4519Style.l, "Melbourne"); + builder.addRDN(RFC4519Style.st, "Victoria"); + builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); + + // + // extensions + // + + // + // create the certificate - version 3 + // + ContentSigner sigGen = new BcHssLmsContentSignerBuilder().build(privKey); + X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubKey); + + + X509CertificateHolder cert = certGen.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcHssLmsContentVerifierProviderBuilder().build(pubKey))); + + + // + // create the certificate - version 1 + // + sigGen = new BcHssLmsContentSignerBuilder().build(privKey); + X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubKey); + + cert = certGen1.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcHssLmsContentVerifierProviderBuilder().build(pubKey))); + + AsymmetricKeyParameter certPubKey = org.bouncycastle.pqc.crypto.util.PublicKeyFactory.createKey(cert.getSubjectPublicKeyInfo()); + + assertTrue(cert.isSignatureValid(new BcHssLmsContentVerifierProviderBuilder().build(certPubKey))); + + ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); + CertificateFactory fact = CertificateFactory.getInstance("X.509"); + + X509Certificate x509cert = (X509Certificate)fact.generateCertificate(bIn); + + //System.out.println(cert); + } + + public void testCheckCreationLms() + throws Exception + { + // + // set up the keys + // + AsymmetricKeyParameter privKey; + AsymmetricKeyParameter pubKey; + + AsymmetricCipherKeyPairGenerator kpg = new LMSKeyPairGenerator(); + + kpg.init(new LMSKeyGenerationParameters( + new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w4), new SecureRandom())); + + AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); + + privKey = (AsymmetricKeyParameter)pair.getPrivate(); + pubKey = (AsymmetricKeyParameter)pair.getPublic(); + + // + // distinguished name table. + // + X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); + + builder.addRDN(RFC4519Style.c, "AU"); + builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); + builder.addRDN(RFC4519Style.l, "Melbourne"); + builder.addRDN(RFC4519Style.st, "Victoria"); + builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); + + // + // extensions + // + + // + // create the certificate - version 3 + // + ContentSigner sigGen = new BcHssLmsContentSignerBuilder().build(privKey); + X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubKey); + + + X509CertificateHolder cert = certGen.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcHssLmsContentVerifierProviderBuilder().build(pubKey))); + + + // + // create the certificate - version 1 + // + + sigGen = new BcHssLmsContentSignerBuilder().build(privKey); + X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubKey); + + cert = certGen1.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcHssLmsContentVerifierProviderBuilder().build(pubKey))); + + AsymmetricKeyParameter certPubKey = ((HSSPublicKeyParameters)org.bouncycastle.pqc.crypto.util.PublicKeyFactory.createKey(cert.getSubjectPublicKeyInfo())).getLMSPublicKey(); + + assertTrue(cert.isSignatureValid(new BcHssLmsContentVerifierProviderBuilder().build(certPubKey))); + + ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); + CertificateFactory fact = CertificateFactory.getInstance("X.509"); + + X509Certificate x509cert = (X509Certificate)fact.generateCertificate(bIn); + + //System.out.println(new String(cert.getEncoded())); + } + + public void testTryLmsSettings() + throws Exception + { + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + try + { + new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("LMS").setProvider(BC).build(_origLmsKP.getPrivate()), _origLmsCert).generate(PKCSObjectIdentifiers.data); + } + catch (OperatorCreationException e) + { + assertEquals("no digest algorithm specified for signature algorithm", e.getMessage()); + } + + SignerInfo sigInfo = new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("LMS", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).setProvider(BC).build(_origLmsKP.getPrivate()), _origLmsCert).generate(PKCSObjectIdentifiers.data); + + assertEquals(sigInfo.getDigestAlgorithm(), new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)); + } + + public void testPicnicEncapsulated() + throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); - certList.add(_origDilithiumCert); - certList.add(_signDilithiumCert); + certList.add(_origPicnicCert); + certList.add(_signPicnicCert); Store certs = new JcaCertStore(certList); @@ -336,12 +556,115 @@ public void testDilithiumEncapsulated() DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); - gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("Dilithium").setProvider(BCPQC).build(_origDilithiumKP.getPrivate()), _origDilithiumCert)); + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("PICNIC").setProvider(BCPQC).build(_origPicnicKP.getPrivate()), _origPicnicCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, true); + checkSignature(s, gen); + } + + public void testMLDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origMlDsaCert); + certList.add(_signMlDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("ML-DSA").setProvider(BC).build(_origMlDsaKP.getPrivate()), _origMlDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testHashMLDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origMlDsaCert); + certList.add(_signMlDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("HASH-ML-DSA").setProvider(BC).build(_origMlDsaKP.getPrivate()), _origMlDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testSLHDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origSlhDsaCert); + certList.add(_signSlhDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("SLH-DSA").setProvider(BC).build(_origSlhDsaKP.getPrivate()), _origSlhDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testHashSLHDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origSlhDsaCert); + certList.add(_signSlhDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("HASH-SLH-DSA").setProvider(BC).build(_origSlhDsaKP.getPrivate()), _origSlhDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + private void checkSignature(CMSSignedData s, CMSSignedDataGenerator gen) + throws IOException, CMSException, OperatorCreationException, CertificateException + { + Store certs; ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/PQCTestUtil.java b/pkix/src/test/java/org/bouncycastle/cms/test/PQCTestUtil.java index 17cbb1d782..00488606e8 100644 --- a/pkix/src/test/java/org/bouncycastle/cms/test/PQCTestUtil.java +++ b/pkix/src/test/java/org/bouncycastle/cms/test/PQCTestUtil.java @@ -15,14 +15,20 @@ import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jcajce.interfaces.MLDSAKey; +import org.bouncycastle.jcajce.interfaces.SLHDSAKey; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; import org.bouncycastle.jce.X509KeyUsage; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.pqc.jcajce.interfaces.DilithiumKey; +import org.bouncycastle.pqc.crypto.lms.LMOtsParameters; +import org.bouncycastle.pqc.crypto.lms.LMSigParameters; import org.bouncycastle.pqc.jcajce.interfaces.FalconKey; +import org.bouncycastle.pqc.jcajce.interfaces.LMSKey; import org.bouncycastle.pqc.jcajce.interfaces.PicnicKey; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; import org.bouncycastle.pqc.jcajce.spec.FalconParameterSpec; +import org.bouncycastle.pqc.jcajce.spec.LMSKeyGenParameterSpec; import org.bouncycastle.pqc.jcajce.spec.PicnicParameterSpec; import org.bouncycastle.pqc.jcajce.spec.SPHINCS256KeyGenParameterSpec; import org.bouncycastle.pqc.jcajce.spec.SPHINCSPlusParameterSpec; @@ -49,6 +55,16 @@ public static KeyPair makeSphincsPlusKeyPair() return kpGen.generateKeyPair(); } + public static KeyPair makeLmsKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("LMS", "BCPQC"); + + kpGen.initialize(new LMSKeyGenParameterSpec(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w1), new SecureRandom()); + + return kpGen.generateKeyPair(); + } + public static KeyPair makeFalconKeyPair() throws Exception { @@ -69,12 +85,22 @@ public static KeyPair makePicnicKeyPair() return kpGen.generateKeyPair(); } - public static KeyPair makeDilithiumKeyPair() + public static KeyPair makeMlDsaKeyPair() throws Exception { - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); //TODO: divide into two with cases with digest and with parametersets - kpGen.initialize(DilithiumParameterSpec.dilithium2, new SecureRandom()); + kpGen.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static KeyPair makeSlhDsaKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + //TODO: divide into two with cases with digest and with parametersets + kpGen.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, new SecureRandom()); return kpGen.generateKeyPair(); } @@ -96,10 +122,17 @@ else if (issPriv instanceof PicnicKey) // sigGen = new JcaContentSignerBuilder(((PicnicKey)issPriv).getParameterSpec().getName()).setProvider("BCPQC").build(issPriv); sigGen = new JcaContentSignerBuilder("PICNIC").setProvider("BCPQC").build(issPriv); } - else if (issPriv instanceof DilithiumKey) + else if (issPriv instanceof MLDSAKey) { -// sigGen = new JcaContentSignerBuilder(((PicnicKey)issPriv).getParameterSpec().getName()).setProvider("BCPQC").build(issPriv); - sigGen = new JcaContentSignerBuilder("Dilithium").setProvider("BCPQC").build(issPriv); + sigGen = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(issPriv); + } + else if (issPriv instanceof SLHDSAKey) + { + sigGen = new JcaContentSignerBuilder("SLH-DSA").setProvider("BC").build(issPriv); + } + else if (issPriv instanceof LMSKey) + { + sigGen = new JcaContentSignerBuilder("LMS").setProvider("BC").build(issPriv); } else { diff --git a/pkix/src/test/java/org/bouncycastle/cms/test/SHA256DigestCalculator.java b/pkix/src/test/java/org/bouncycastle/cms/test/SHA256DigestCalculator.java new file mode 100644 index 0000000000..b8f85ce13f --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/cms/test/SHA256DigestCalculator.java @@ -0,0 +1,44 @@ +package org.bouncycastle.cms.test; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; + +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.operator.DigestCalculator; + + +class SHA256DigestCalculator + implements DigestCalculator +{ + private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256); + } + + public OutputStream getOutputStream() + { + return bOut; + } + + public byte[] getDigest() + { + byte[] bytes = bOut.toByteArray(); + + bOut.reset(); + + Digest sha256 = SHA256Digest.newInstance(); + + sha256.update(bytes, 0, bytes.length); + + byte[] digest = new byte[sha256.getDigestSize()]; + + sha256.doFinal(digest, 0); + + return digest; + } +} diff --git a/pkix/src/test/java/org/bouncycastle/openssl/test/CompositeKeyTest.java b/pkix/src/test/java/org/bouncycastle/openssl/test/CompositeKeyTest.java index efafecde5f..ae198ed68a 100644 --- a/pkix/src/test/java/org/bouncycastle/openssl/test/CompositeKeyTest.java +++ b/pkix/src/test/java/org/bouncycastle/openssl/test/CompositeKeyTest.java @@ -48,6 +48,7 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; @@ -451,6 +452,143 @@ public void testRSAAndECCompositeSignedDataGen() //doOutput("/tmp/comp_cms_1.pem", sWrt.toString()); } + public void testMLDSA44andP256() + throws Exception + { + // + // set up the keys + // + KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("EC", "BC"); + + ecKpg.initialize(new ECNamedCurveGenParameterSpec("P-256")); + + KeyPair ecKp = ecKpg.generateKeyPair(); + + PrivateKey ecPriv = ecKp.getPrivate(); + PublicKey ecPub = ecKp.getPublic(); + + KeyPairGenerator rmldsaKpg = KeyPairGenerator.getInstance("ML-DSA-44", "BC"); + + KeyPair mldsaKp = rmldsaKpg.generateKeyPair(); + + PrivateKey mldsaPriv = mldsaKp.getPrivate(); + PublicKey mldsaPub = mldsaKp.getPublic(); + + CompositePrivateKey mlecPriv = new CompositePrivateKey(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, mldsaPriv, ecPriv); + + StringWriter sWrt = new StringWriter(); + JcaPEMWriter pWrt = new JcaPEMWriter(sWrt); + + pWrt.writeObject(mlecPriv); + + pWrt.close(); + + CompositePublicKey mlecPub = new CompositePublicKey(mldsaPub, ecPub); + + pWrt = new JcaPEMWriter(sWrt); + + pWrt.writeObject(mlecPub); + + pWrt.close(); + + PEMParser pPrs = new PEMParser(new StringReader(sWrt.toString())); + + JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC"); + CompositePrivateKey prKey = (CompositePrivateKey)keyConverter.getPrivateKey((PrivateKeyInfo)pPrs.readObject()); + + CompositePublicKey puKey = (CompositePublicKey)keyConverter.getPublicKey((SubjectPublicKeyInfo)pPrs.readObject()); + } + + public void testMLDSA44andEd25519() + throws Exception + { + // + // set up the keys + // + KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("ED25519", "BC"); + + KeyPair ecKp = ecKpg.generateKeyPair(); + + PrivateKey ecPriv = ecKp.getPrivate(); + PublicKey ecPub = ecKp.getPublic(); + + KeyPairGenerator rmldsaKpg = KeyPairGenerator.getInstance("ML-DSA-44", "BC"); + + KeyPair mldsaKp = rmldsaKpg.generateKeyPair(); + + PrivateKey mldsaPriv = mldsaKp.getPrivate(); + PublicKey mldsaPub = mldsaKp.getPublic(); + + CompositePrivateKey mlecPriv = new CompositePrivateKey(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, mldsaPriv, ecPriv); + + StringWriter sWrt = new StringWriter(); + JcaPEMWriter pWrt = new JcaPEMWriter(sWrt); + + pWrt.writeObject(mlecPriv); + + pWrt.close(); + + CompositePublicKey mlecPub = new CompositePublicKey(mldsaPub, ecPub); + + pWrt = new JcaPEMWriter(sWrt); + + pWrt.writeObject(mlecPub); + + pWrt.close(); + + PEMParser pPrs = new PEMParser(new StringReader(sWrt.toString())); + + JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC"); + CompositePrivateKey prKey = (CompositePrivateKey)keyConverter.getPrivateKey((PrivateKeyInfo)pPrs.readObject()); + + CompositePublicKey puKey = (CompositePublicKey)keyConverter.getPublicKey((SubjectPublicKeyInfo)pPrs.readObject()); + } + + public void testMLDSA87andEd448() + throws Exception + { + // + // set up the keys + // + KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("ED448", "BC"); + + KeyPair ecKp = ecKpg.generateKeyPair(); + + PrivateKey ecPriv = ecKp.getPrivate(); + PublicKey ecPub = ecKp.getPublic(); + + KeyPairGenerator rmldsaKpg = KeyPairGenerator.getInstance("ML-DSA-87", "BC"); + + KeyPair mldsaKp = rmldsaKpg.generateKeyPair(); + + PrivateKey mldsaPriv = mldsaKp.getPrivate(); + PublicKey mldsaPub = mldsaKp.getPublic(); + + CompositePrivateKey mlecPriv = new CompositePrivateKey(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, mldsaPriv, ecPriv); + + StringWriter sWrt = new StringWriter(); + JcaPEMWriter pWrt = new JcaPEMWriter(sWrt); + + pWrt.writeObject(mlecPriv); + + pWrt.close(); + + CompositePublicKey mlecPub = new CompositePublicKey(mldsaPub, ecPub); + + pWrt = new JcaPEMWriter(sWrt); + + pWrt.writeObject(mlecPub); + + pWrt.close(); + + PEMParser pPrs = new PEMParser(new StringReader(sWrt.toString())); + + JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC"); + CompositePrivateKey prKey = (CompositePrivateKey)keyConverter.getPrivateKey((PrivateKeyInfo)pPrs.readObject()); + + CompositePublicKey puKey = (CompositePublicKey)keyConverter.getPublicKey((SubjectPublicKeyInfo)pPrs.readObject()); + } + private static void doOutput(String fileName, String contents) throws IOException { diff --git a/pkix/src/test/java/org/bouncycastle/openssl/test/ParserTest.java b/pkix/src/test/java/org/bouncycastle/openssl/test/ParserTest.java index 3e0b78f511..c330156b9a 100644 --- a/pkix/src/test/java/org/bouncycastle/openssl/test/ParserTest.java +++ b/pkix/src/test/java/org/bouncycastle/openssl/test/ParserTest.java @@ -34,6 +34,7 @@ import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.jcajce.interfaces.EdDSAPrivateKey; import org.bouncycastle.jcajce.interfaces.EdDSAPublicKey; @@ -164,6 +165,21 @@ public void performTest() fail("wrong algorithm name on private"); } + // + // Check for algorithm replacement + // + pair = new JcaPEMKeyConverter().setProvider("BC").setAlgorithmMapping(X9ObjectIdentifiers.id_ecPublicKey, "EC").getKeyPair(pemPair); + + if (!pair.getPublic().getAlgorithm().equals("EC")) + { + fail("wrong algorithm name on public got: " + pair.getPublic().getAlgorithm()); + } + + if (!pair.getPrivate().getAlgorithm().equals("EC")) + { + fail("wrong algorithm name on private"); + } + // // ECKey -- explicit parameters // @@ -301,7 +317,7 @@ public void performTest() { if (privInfo instanceof PrivateKeyInfo) { - privKey = (RSAPrivateCrtKey)converter.getPrivateKey(PrivateKeyInfo.getInstance(privInfo)); + privKey = (RSAPrivateCrtKey)converter.getPrivateKey((PrivateKeyInfo)privInfo); } else { diff --git a/pkix/src/test/java/org/bouncycastle/operator/test/AllTests.java b/pkix/src/test/java/org/bouncycastle/operator/test/AllTests.java index c50a9e614f..eb8d45b4f0 100644 --- a/pkix/src/test/java/org/bouncycastle/operator/test/AllTests.java +++ b/pkix/src/test/java/org/bouncycastle/operator/test/AllTests.java @@ -3,6 +3,7 @@ import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; +import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.spec.MGF1ParameterSpec; @@ -36,11 +37,25 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.AlgorithmNameFinder; import org.bouncycastle.operator.DefaultAlgorithmNameFinder; +import org.bouncycastle.operator.DefaultKemEncapsulationLengthProvider; import org.bouncycastle.operator.DefaultSignatureNameFinder; +import org.bouncycastle.operator.KemEncapsulationLengthProvider; import org.bouncycastle.operator.jcajce.JceAsymmetricKeyWrapper; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.ntru.NTRUKEMExtractor; +import org.bouncycastle.pqc.crypto.ntru.NTRUKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.ntru.NTRUKeyPairGenerator; +import org.bouncycastle.pqc.crypto.ntru.NTRUParameters; +import org.bouncycastle.pqc.crypto.ntru.NTRUPrivateKeyParameters; import org.bouncycastle.test.PrintTestResult; import org.bouncycastle.util.encoders.Hex; @@ -138,6 +153,36 @@ public void testAgainstKnownList() new Object[]{NISTObjectIdentifiers.id_dsa_with_sha3_512, "SHA3-512WITHDSA"}, new Object[]{BCObjectIdentifiers.falcon_512, "FALCON"}, new Object[]{BCObjectIdentifiers.falcon_1024, "FALCON"}, + new Object[]{NISTObjectIdentifiers.id_ml_dsa_44, "ML-DSA-44"}, + new Object[]{NISTObjectIdentifiers.id_ml_dsa_65, "ML-DSA-65"}, + new Object[]{NISTObjectIdentifiers.id_ml_dsa_87, "ML-DSA-87"}, + new Object[]{NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, "ML-DSA-44-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, "ML-DSA-65-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, "ML-DSA-87-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_sha2_128s, "SLH-DSA-SHA2-128S"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_sha2_128f, "SLH-DSA-SHA2-128F"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_sha2_192s, "SLH-DSA-SHA2-192S"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_sha2_192f, "SLH-DSA-SHA2-192F"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_sha2_256s, "SLH-DSA-SHA2-256S"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_sha2_256f, "SLH-DSA-SHA2-256F"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_shake_128s, "SLH-DSA-SHAKE-128S"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_shake_128f, "SLH-DSA-SHAKE-128F"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_shake_192s, "SLH-DSA-SHAKE-192S"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_shake_192f, "SLH-DSA-SHAKE-192F"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_shake_256s, "SLH-DSA-SHAKE-256S"}, + new Object[]{NISTObjectIdentifiers.id_slh_dsa_shake_256f, "SLH-DSA-SHAKE-256F"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, "SLH-DSA-SHA2-128S-WITH-SHA256"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, "SLH-DSA-SHA2-128F-WITH-SHA256"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, "SLH-DSA-SHA2-192S-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, "SLH-DSA-SHA2-192F-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, "SLH-DSA-SHA2-256S-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, "SLH-DSA-SHA2-256F-WITH-SHA512"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, "SLH-DSA-SHAKE-128S-WITH-SHAKE128"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, "SLH-DSA-SHAKE-128F-WITH-SHAKE128"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, "SLH-DSA-SHAKE-192S-WITH-SHAKE256"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, "SLH-DSA-SHAKE-192F-WITH-SHAKE256"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, "SLH-DSA-SHAKE-256S-WITH-SHAKE256"}, + new Object[]{NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, "SLH-DSA-SHAKE-256F-WITH-SHAKE256"}, new Object[]{BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, "SPHINCS+"}, new Object[]{BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, "SPHINCS+"}, new Object[]{BCObjectIdentifiers.sphincsPlus_shake_128s_r3, "SPHINCS+"}, @@ -175,6 +220,7 @@ public void testAgainstKnownList() new Object[]{BCObjectIdentifiers.sphincsPlus_haraka_256s_r3_simple, "SPHINCS+"}, new Object[]{BCObjectIdentifiers.sphincsPlus_haraka_256f_r3_simple, "SPHINCS+"}, new Object[]{GNUObjectIdentifiers.Tiger_192, "Tiger"}, + new Object[]{PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"}, new Object[]{PKCSObjectIdentifiers.RC2_CBC, "RC2/CBC"}, new Object[]{PKCSObjectIdentifiers.des_EDE3_CBC, "DESEDE-3KEY/CBC"}, @@ -231,7 +277,7 @@ public void testAgainstKnownList() // DefaultAlgorithmNameFinder nameFinder = new DefaultAlgorithmNameFinder(); assertEquals("default name finder has same number of entries as test case", - nameFinder.getOIDSet().size(), values.length); + values.length, nameFinder.getOIDSet().size()); ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)((Object[])value)[0]; String name = ((Object[])value)[1].toString(); @@ -422,4 +468,70 @@ private void checkAlgorithmId(KeyPair kp, String digest, ASN1ObjectIdentifier di Assert.assertEquals(PKCSObjectIdentifiers.id_pSpecified, oaepParams.getPSourceAlgorithm().getAlgorithm()); Assert.assertEquals(new DEROctetString(Hex.decode("beef")), oaepParams.getPSourceAlgorithm().getParameters()); } + + public void testDefaultKemEncapsulationLengthProvider() + { + KemEncapsulationLengthProvider lengthProvider = new DefaultKemEncapsulationLengthProvider(); + SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + + ASN1ObjectIdentifier[] mlKemOids = new ASN1ObjectIdentifier[] + { + NISTObjectIdentifiers.id_alg_ml_kem_512, + NISTObjectIdentifiers.id_alg_ml_kem_768, + NISTObjectIdentifiers.id_alg_ml_kem_1024 + }; + + MLKEMParameters[] mlKemParams = new MLKEMParameters[] + { + MLKEMParameters.ml_kem_512, + MLKEMParameters.ml_kem_768, + MLKEMParameters.ml_kem_1024 + }; + + for (int i = 0; i != mlKemOids.length; i++) + { + MLKEMKeyPairGenerator kpg = new MLKEMKeyPairGenerator(); + + kpg.init(new MLKEMKeyGenerationParameters(random, mlKemParams[i])); + + AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); + + MLKEMExtractor ext = new MLKEMExtractor((MLKEMPrivateKeyParameters)kp.getPrivate()); + + assertEquals(ext.getEncapsulationLength(), lengthProvider.getEncapsulationLength(new AlgorithmIdentifier(mlKemOids[i]))); + } + + ASN1ObjectIdentifier[] ntruOids = new ASN1ObjectIdentifier[] + { + BCObjectIdentifiers.ntruhps2048509, + BCObjectIdentifiers.ntruhps2048677, + BCObjectIdentifiers.ntruhps4096821, + BCObjectIdentifiers.ntruhps40961229, + BCObjectIdentifiers.ntruhrss701, + BCObjectIdentifiers.ntruhrss1373, + }; + + NTRUParameters[] ntruParams = new NTRUParameters[] + { + NTRUParameters.ntruhps2048509, + NTRUParameters.ntruhps2048677, + NTRUParameters.ntruhps4096821, + NTRUParameters.ntruhps40961229, + NTRUParameters.ntruhrss701, + NTRUParameters.ntruhrss1373 + }; + + for (int i = 0; i != ntruOids.length; i++) + { + NTRUKeyPairGenerator kpg = new NTRUKeyPairGenerator(); + + kpg.init(new NTRUKeyGenerationParameters(random, ntruParams[i])); + + AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); + + NTRUKEMExtractor ext = new NTRUKEMExtractor((NTRUPrivateKeyParameters)kp.getPrivate()); + + assertEquals(ext.getEncapsulationLength(), lengthProvider.getEncapsulationLength(new AlgorithmIdentifier(ntruOids[i]))); + } + } } \ No newline at end of file diff --git a/pkix/src/test/java/org/bouncycastle/pkcs/test/PBETest.java b/pkix/src/test/java/org/bouncycastle/pkcs/test/PBETest.java index e213c9f4d2..9c23affedf 100644 --- a/pkix/src/test/java/org/bouncycastle/pkcs/test/PBETest.java +++ b/pkix/src/test/java/org/bouncycastle/pkcs/test/PBETest.java @@ -3,9 +3,16 @@ import java.security.Security; import junit.framework.TestCase; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PBKDF2Params; +import org.bouncycastle.asn1.pkcs.PBMAC1Params; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.MacCalculator; +import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.pkcs.jcajce.JcePBMac1CalculatorBuilder; +import org.bouncycastle.pkcs.jcajce.JcePBMac1CalculatorProviderBuilder; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; @@ -29,4 +36,21 @@ public void testPBESHA256() assertEquals("55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc", Hex.toHexString((byte[])pbCalculator.getKey().getRepresentation())); } + + public void testPbmac1PrfPropagation() throws OperatorCreationException { + AlgorithmIdentifier prf = new AlgorithmIdentifier(NISTObjectIdentifiers.id_hmacWithSHA3_512, null);; + AlgorithmIdentifier protectionAlgorithm = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBMAC1, + new PBMAC1Params( + new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params("salt".getBytes(), 1234, 64, prf)), + new AlgorithmIdentifier(NISTObjectIdentifiers.id_hmacWithSHA3_512, null) + ) + ); + MacCalculator calculator = new JcePBMac1CalculatorProviderBuilder() + .setProvider(new BouncyCastleProvider()).build().get(protectionAlgorithm, "foobar123".toCharArray()); + AlgorithmIdentifier actualPrf = PBKDF2Params.getInstance( + PBMAC1Params.getInstance(calculator.getKey().getAlgorithmIdentifier().getParameters()).getKeyDerivationFunc().getParameters() + ).getPrf(); + assertTrue(prf.equals(actualPrf)); + } + } diff --git a/pkix/src/test/java/org/bouncycastle/pkcs/test/PKCS10Test.java b/pkix/src/test/java/org/bouncycastle/pkcs/test/PKCS10Test.java index 77768e0515..8a18411856 100644 --- a/pkix/src/test/java/org/bouncycastle/pkcs/test/PKCS10Test.java +++ b/pkix/src/test/java/org/bouncycastle/pkcs/test/PKCS10Test.java @@ -22,6 +22,7 @@ import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.operator.ContentSigner; @@ -34,7 +35,6 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; import org.bouncycastle.test.PrintTestResult; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; @@ -195,13 +195,13 @@ public void testAltRequestAttributes() p256Kpg.initialize(new ECNamedCurveGenParameterSpec("P-256")); KeyPair p256Kp = p256Kpg.generateKeyPair(); - KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("Dilithium", "BC"); - dilKpg.initialize(DilithiumParameterSpec.dilithium2); + KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + dilKpg.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpg.generateKeyPair(); JcaPKCS10CertificationRequestBuilder jcaPkcs10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Name("CN=Test"), p256Kp.getPublic()); - ContentSigner altSigner = new JcaContentSignerBuilder("Dilithium2").setProvider("BC").build(dilKp.getPrivate()); + ContentSigner altSigner = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(dilKp.getPrivate()); PKCS10CertificationRequest request = jcaPkcs10Builder.build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(p256Kp.getPrivate()), dilKp.getPublic(), altSigner); @@ -219,13 +219,13 @@ public void testDeltaRequestAttribute() p256Kpg.initialize(new ECNamedCurveGenParameterSpec("P-256")); KeyPair p256Kp = p256Kpg.generateKeyPair(); - KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("Dilithium", "BC"); - dilKpg.initialize(DilithiumParameterSpec.dilithium2); + KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + dilKpg.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpg.generateKeyPair(); PKCS10CertificationRequestBuilder pkcs10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Name("CN=Test"), p256Kp.getPublic()); - ContentSigner deltaSigner = new JcaContentSignerBuilder("Dilithium2").setProvider("BC").build(dilKp.getPrivate()); + ContentSigner deltaSigner = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(dilKp.getPrivate()); DeltaCertificateRequestAttributeValueBuilder deltaAttrBldr = new DeltaCertificateRequestAttributeValueBuilder( SubjectPublicKeyInfo.getInstance(dilKp.getPublic().getEncoded())); diff --git a/pkix/src/test/java/org/bouncycastle/pkcs/test/PQCPKCS10Test.java b/pkix/src/test/java/org/bouncycastle/pkcs/test/PQCPKCS10Test.java new file mode 100644 index 0000000000..fd4de9cbf5 --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/pkcs/test/PQCPKCS10Test.java @@ -0,0 +1,97 @@ +package org.bouncycastle.pkcs.test; + +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Security; +import java.util.Date; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.PrivateKeyStatement; +import org.bouncycastle.asn1.x509.X509AttributeIdentifiers; +import org.bouncycastle.cert.CertException; +import org.bouncycastle.cert.CertIOException; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.ContentVerifierProvider; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; +import org.bouncycastle.pkcs.PKCS10CertificationRequest; +import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; +import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; + +public class PQCPKCS10Test + extends TestCase +{ + public void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + public void testKEMPKCS10() + throws Exception + { + KeyPairGenerator dilKpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + dilKpGen.initialize(MLDSAParameterSpec.ml_dsa_65); + + KeyPair dilKp = dilKpGen.generateKeyPair(); + + X509CertificateHolder sigCert = makeV3Certificate("CN=ML-KEM Client", dilKp); + + KeyPairGenerator kemKpGen = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + kemKpGen.initialize(MLKEMParameterSpec.ml_kem_768); + + KeyPair kemKp = kemKpGen.generateKeyPair(); + + PKCS10CertificationRequestBuilder pkcs10Builder = new JcaPKCS10CertificationRequestBuilder( + new X500Name("CN=ML-KEM Client"), kemKp.getPublic()); + + pkcs10Builder.addAttribute(X509AttributeIdentifiers.id_at_privateKeyStatement, + new PrivateKeyStatement(sigCert.toASN1Structure())); + + PKCS10CertificationRequest request = pkcs10Builder.build( + new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(dilKp.getPrivate())); + + assertTrue(request.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(sigCert.getSubjectPublicKeyInfo()))); + } + + private static X509CertificateHolder makeV3Certificate(String _subDN, KeyPair issKP) + throws OperatorCreationException, CertException, CertIOException + { + PrivateKey issPriv = issKP.getPrivate(); + PublicKey issPub = issKP.getPublic(); + + X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( + new X500Name(_subDN), + BigInteger.valueOf(System.currentTimeMillis()), + new Date(System.currentTimeMillis() - 5000L), + new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), + new X500Name(_subDN), + issKP.getPublic()); + + certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); + + ContentSigner signer = new JcaContentSignerBuilder("ML-DSA").build(issPriv); + + X509CertificateHolder certHolder = certGen.build(signer); + + ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(issPub); + + assertTrue(certHolder.isSignatureValid(verifier)); + + return certHolder; + } +} diff --git a/pkix/src/test/java/org/bouncycastle/pkcs/test/PfxPduTest.java b/pkix/src/test/java/org/bouncycastle/pkcs/test/PfxPduTest.java index d3c4d37e33..4468002dd7 100644 --- a/pkix/src/test/java/org/bouncycastle/pkcs/test/PfxPduTest.java +++ b/pkix/src/test/java/org/bouncycastle/pkcs/test/PfxPduTest.java @@ -35,11 +35,14 @@ import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.asn1.pkcs.ContentInfo; +import org.bouncycastle.asn1.pkcs.PBKDF2Params; +import org.bouncycastle.asn1.pkcs.PBMAC1Params; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; @@ -71,6 +74,8 @@ import org.bouncycastle.pkcs.bc.BcPKCS12MacCalculatorBuilderProvider; import org.bouncycastle.pkcs.bc.BcPKCS12PBEInputDecryptorProviderBuilder; import org.bouncycastle.pkcs.bc.BcPKCS12PBEOutputEncryptorBuilder; +import org.bouncycastle.pkcs.bc.BcPKCS12PBMac1CalculatorBuilder; +import org.bouncycastle.pkcs.bc.BcPKCS12PBMac1CalculatorBuilderProvider; import org.bouncycastle.pkcs.jcajce.JcaPKCS12SafeBagBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS8EncryptedPrivateKeyInfoBuilder; import org.bouncycastle.pkcs.jcajce.JcePKCS12MacCalculatorBuilder; @@ -78,7 +83,11 @@ import org.bouncycastle.pkcs.jcajce.JcePKCSPBEInputDecryptorProviderBuilder; import org.bouncycastle.pkcs.jcajce.JcePKCSPBEOutputEncryptorBuilder; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Base64; +import org.junit.function.ThrowingRunnable; + +import static org.junit.Assert.assertThrows; public class PfxPduTest extends TestCase @@ -562,6 +571,361 @@ public class PfxPduTest "GhHLM2yiA0RxlCtlnNMXruHKEvFYgzI3lVQov4jU5MIL1XjH0zPGyu9t" + "/q8tpS4nbkRgGj8="); + // Valid PKCS #12 File with SHA-256 HMAC and PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a1 = Base64.decode( + "MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhvRzw4sC4xcwICCAACASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQITk9UIFVTRUQCAQE=\n"); + + // Valid PKCS #12 File with SHA-256 HMAC and SHA-512 PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a2 = Base64.decode("MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAi4j6UBBY2iOgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEFpHSS5zrk/9pkDo1JRbtE6AggPgtbMLGoFd5KLpVXMdcxLrT129L7/vCr0B\n" + + "0I2tnhPPA7aFtRjjuGbwooCMQwxw9qzuCX1eH4xK2LUw6Gbd2H47WimSOWJMaiUb\n" + + "wy4alIWELYufe74kXPmKPCyH92lN1hqu8s0EGhIl7nBhWbFzow1+qpIc9/lpujJo\n" + + "wodSY+pNBD8oBeoU1m6DgOjgc62apL7m0nwavDUqEt7HAqtTBxKxu/3lpb1q8nbl\n" + + "XLTqROax5feXErf+GQAqs24hUJIPg3O1eCMDVzH0h5pgZyRN9ZSIP0HC1i+d1lnb\n" + + "JwHyrAhZv8GMdAVKaXHETbq8zTpxT3UE/LmH1gyZGOG2B21D2dvNDKa712sHOS/t\n" + + "3XkFngHDLx+a9pVftt6p7Nh6jqI581tb7fyc7HBV9VUc/+xGgPgHZouaZw+I3PUz\n" + + "fjHboyLQer22ndBz+l1/S2GhhZ4xLXg4l0ozkgn7DX92S/UlbmcZam1apjGwkGY/\n" + + "7ktA8BarNW211mJF+Z+hci+BeDiM7eyEguLCYRdH+/UBiUuYjG1hi5Ki3+42pRZD\n" + + "FZkTHGOrcG6qE2KJDsENj+RkGiylG98v7flm4iWFVAB78AlAogT38Bod40evR7Ok\n" + + "c48sOIW05eCH/GLSO0MHKcttYUQNMqIDiG1TLzP1czFghhG97AxiTzYkKLx2cYfs\n" + + "pgg5PE9drq1fNzBZMUmC2bSwRhGRb5PDu6meD8uqvjxoIIZQAEV53xmD63umlUH1\n" + + "jhVXfcWSmhU/+vV/IWStZgQbwhF7DmH2q6S8itCkz7J7Byp5xcDiUOZ5Gpf9RJnk\n" + + "DTZoOYM5iA8kte6KCwA+jnmCgstI5EbRbnsNcjNvAT3q/X776VdmnehW0VeL+6k4\n" + + "z+GvQkr+D2sxPpldIb5hrb+1rcp9nOQgtpBnbXaT16Lc1HdTNe5kx4ScujXOWwfd\n" + + "Iy6bR6H0QFq2SLKAAC0qw4E8h1j3WPxll9e0FXNtoRKdsRuX3jzyqDBrQ6oGskkL\n" + + "wnyMtVjSX+3c9xbFc4vyJPFMPwb3Ng3syjUDrOpU5RxaMEAWt4josadWKEeyIC2F\n" + + "wrS1dzFn/5wv1g7E7xWq+nLq4zdppsyYOljzNUbhOEtJ2lhme3NJ45fxnxXmrPku\n" + + "gBda1lLf29inVuzuTjwtLjQwGk+usHJm9R/K0hTaSNRgepXnjY0cIgS+0gEY1/BW\n" + + "k3+Y4GE2JXds2cQToe5rCSYH3QG0QTyUAGvwX6hAlhrRRgUG3vxtYSixQ3UUuwzs\n" + + "eQW2SUFLl1611lJ7cQwFSPyr0sL0p81vdxWiigwjkfPtgljZ2QpmzR5rX2xiqItH\n" + + "Dy4E+iVigIYwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhDiwsh\n" + + "4wt3aAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEELNFnEpJT65wsXwd\n" + + "fZ1g56cEggTQRo04bP/fWfPPZrTEczq1qO1HHV86j76Sgxau2WQ9OQAG998HFtNq\n" + + "NxO8R66en6QFhqpWCI73tSJD+oA29qOsT+Xt2bR2z5+K7D4QoiXuLa3gXv62VkjB\n" + + "0DLCHAS7Mu+hkp5OKCpXCS7fo0OnAiQjM4EluAsiwwLrHu7z1E16UwpmlgKQnaC1\n" + + "S44fV9znS9TxofRTnuCq1lupdn2qQjSydOU6inQeKLBflKRiLrJHOobaFmjWwp1U\n" + + "OQAMuZrALhHyIbOFXMPYk3mmU/1UPuRGcbcV5v2Ut2UME+WYExXSCOYR3/R4UfVk\n" + + "IfEzeRPFs2slJMIDS2fmMyFkEEElBckhKO9IzhQV3koeKUBdM066ufyax/uIyXPm\n" + + "MiB9fAqbQQ4jkQTT80bKkBAP1Bvyg2L8BssstR5iCoZgWnfA9Uz4RI5GbRqbCz7H\n" + + "iSkuOIowEqOox3IWbXty5VdWBXNjZBHpbE0CyMLSH/4QdGVw8R0DiCAC0mmaMaZq\n" + + "32yrBR32E472N+2KaicvX31MwB/LkZN46c34TGanL5LJZx0DR6ITjdNgP8TlSSrp\n" + + "7y2mqi7VbKp/C/28Cj5r+m++Gk6EOUpLHsZ2d2hthrr7xqoPzUAEkkyYWedHJaoQ\n" + + "TkoIisZb0MGlXb9thjQ8Ee429ekfjv7CQfSDS6KTE/+mhuJ33mPz1ZcIacHjdHhE\n" + + "6rbrKhjSrLbgmrGa8i7ezd89T4EONu0wkG9KW0wM2cn5Gb12PF6rxjTfzypG7a50\n" + + "yc1IJ2Wrm0B7gGuYpVoCeIohr7IlxPYdeQGRO/SlzTd0xYaJVm9FzJaMNK0ZqnZo\n" + + "QMEPaeq8PC3kMjpa8eAiHXk9K3DWdOWYviGVCPVYIZK6Cpwe+EwfXs+2hZgZlYzc\n" + + "vpUWg60md1PD4UsyLQagaj37ubR6K4C4mzlhFx5NovV/C/KD+LgekMbjCtwEQeWy\n" + + "agev2l9KUEz73/BT4TgQFM5K2qZpVamwmsOmldPpekGPiUCu5YxYg/y4jUKvAqj1\n" + + "S9t4wUAScCJx8OvXUfgpmS2+mhFPBiFps0M4O3nWG91Q6mKMqbNHPUcFDn9P7cUh\n" + + "s1xu3NRLyJ+QIfVfba3YBTV8A6WBYEmL9lxf1uL1WS2Bx6+Crh0keyNUPo9cRjpx\n" + + "1oj/xkInoc2HQODEkvuK9DD7VrLr7sDhfmJvr1mUfJMQ5/THk7Z+E+NAuMdMtkM2\n" + + "yKXxghZAbBrQkU3mIW150i7PsjlUw0o0/LJvQwJIsh6yeJDHY8mby9mIdeP3LQAF\n" + + "clYKzNwmgwbdtmVAXmQxLuhmEpXfstIzkBrNJzChzb2onNSfa+r5L6XEHNHl7wCw\n" + + "TuuV/JWldNuYXLfVfuv3msfSjSWkv6aRtRWIvmOv0Qba2o05LlwFMd1PzKM5uN4D\n" + + "DYtsS9A6yQOXEsvUkWcLOJnCs8SkJRdXhJTxdmzeBqM1JttKwLbgGMbpjbxlg3ns\n" + + "N+Z+sEFox+2ZWOglgnBHj0mCZOiAC8wqUu+sxsLT4WndaPWKVqoRQChvDaZaNOaN\n" + + "qHciF9HPUcfZow+fH8TnSHneiQcDe6XcMhSaQ2MtpY8/jrgNKguZt22yH9gw/VpT\n" + + "3/QOB7FBgKFIEbvUaf3nVjFIlryIheg+LeiBd2isoMNNXaBwcg2YXukxJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAgUr2yP+/DBrgICCAACASAwDAYIKoZIhvcNAgsF\n" + + "ADAMBggqhkiG9w0CCQUABCA5zFL93jw8ItGlcbHKhqkNwbgpp6layuOuxSju4/Vd\n" + + "6QQITk9UIFVTRUQCAQE="); + + // Valid PKCS #12 File with SHA-512 HMAC and PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a3 = Base64.decode("MIIKrAIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAisrqL8obSBaQICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEECjXYYca0pwsgn1Imb9WqFGAggPgT7RcF5YzEJANZU9G3tSdpCHnyWatTlhm\n" + + "iCEcBGgwI5gz0+GoX+JCojgYY4g+KxeqznyCu+6GeD00T4Em7SWme9nzAfBFzng0\n" + + "3lYCSnahSEKfgHerbzAtq9kgXkclPVk0Liy92/buf0Mqotjjs/5o78AqP86Pwbj8\n" + + "xYNuXOU1ivO0JiW2c2HefKYvUvMYlOh99LCoZPLHPkaaZ4scAwDjFeTICU8oowVk\n" + + "LKvslrg1pHbfmXHMFJ4yqub37hRtj2CoJNy4+UA2hBYlBi9WnuAJIsjv0qS3kpLe\n" + + "4+J2DGe31GNG8pD01XD0l69OlailK1ykh4ap2u0KeD2z357+trCFbpWMMXQcSUCO\n" + + "OcVjxYqgv/l1++9huOHoPSt224x4wZfJ7cO2zbAAx/K2CPhdvi4CBaDHADsRq/c8\n" + + "SAi+LX5SCocGT51zL5KQD6pnr2ExaVum+U8a3nMPPMv9R2MfFUksYNGgFvS+lcZf\n" + + "R3qk/G9iXtSgray0mwRA8pWzoXl43vc9HJuuCU+ryOc/h36NChhQ9ltivUNaiUc2\n" + + "b9AAQSrZD8Z7KtxjbH3noS+gjDtimDB0Uh199zaCwQ95y463zdYsNCESm1OT979o\n" + + "Y+81BWFMFM/Hog5s7Ynhoi2E9+ZlyLK2UeKwvWjGzvcdPvxHR+5l/h6PyWROlpaZ\n" + + "zmzZBm+NKmbXtMD2AEa5+Q32ZqJQhijXZyIji3NS65y81j/a1ZrvU0lOVKA+MSPN\n" + + "KU27/eKZuF1LEL6qaazTUmpznLLdaVQy5aZ1qz5dyCziKcuHIclhh+RCblHU6XdE\n" + + "6pUTZSRQQiGUIkPUTnU9SFlZc7VwvxgeynLyXPCSzOKNWYGajy1LxDvv28uhMgNd\n" + + "WF51bNkl1QYl0fNunGO7YFt4wk+g7CQ/Yu2w4P7S3ZLMw0g4eYclcvyIMt4vxXfp\n" + + "VTKIPyzMqLr+0dp1eCPm8fIdaBZUhMUC/OVqLwgnPNY9cXCrn2R1cGKo5LtvtjbH\n" + + "2skz/D5DIOErfZSBJ8LE3De4j8MAjOeC8ia8LaM4PNfW/noQP1LBsZtTDTqEy01N\n" + + "Z5uliIocyQzlyWChErJv/Wxh+zBpbk1iXc2Owmh2GKjx0VSe7XbiqdoKkONUNUIE\n" + + "siseASiU/oXdJYUnBYVEUDJ1HPz7qnKiFhSgxNJZnoPfzbbx1hEzV+wxQqNnWIqQ\n" + + "U0s7Jt22wDBzPBHGao2tnGRLuBZWVePJGbsxThGKwrf3vYsNJTxme5KJiaxcPMwE\n" + + "r+ln2AqVOzzXHXgIxv/dvK0Qa7pH3AvGzcFjQChTRipgqiRrLor0//8580h+Ly2l\n" + + "IFo7bCuztmcwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAi1c7S5\n" + + "IEG77wICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEN6rzRtIdYxqOnY+\n" + + "aDS3AFYEggTQNdwUoZDXCryOFBUI/z71vfoyAxlnwJLRHNXQUlI7w0KkH22aNnSm\n" + + "xiaXHoCP1HgcmsYORS7p/ITi/9atCHqnGR4zHmePNhoMpNHFehdjlUUWgt004vUJ\n" + + "5ZwTdXweM+K4We6CfWA/tyvsyGNAsuunel+8243Zsv0mGLKpjA+ZyALt51s0knmX\n" + + "OD2DW49FckImUVnNC5LmvEIAmVC/ZNycryZQI+2EBkJKe+BC3834GexJnSwtUBg3\n" + + "Xg33ZV7X66kw8tK1Ws5zND5GQAJyIu47mnjZkIWQBY+XbWowrBZ8uXIQuxMZC0p8\n" + + "u62oIAtZaVQoVTR1LyR/7PISFW6ApwtbTn6uQxsb16qF8lEM0S1+x0AfJY6Zm11t\n" + + "yCqbb2tYZF+X34MoUkR/IYC/KCq/KJdpnd8Yqgfrwjg8dR2WGIxbp2GBHq6BK/DI\n" + + "ehOLMcLcsOuP0DEXppfcelMOGNIs+4h4KsjWiHVDMPsqLdozBdm6FLGcno3lY5FO\n" + + "+avVrlElAOB+9evgaBbD2lSrEMoOjAoD090tgXXwYBEnWnIpdk+56cf5IpshrLBA\n" + + "/+H13LBLes+X1o5dd0Mu+3abp5RtAv7zLPRRtXkDYJPzgNcTvJ2Wxw2C+zrAclzZ\n" + + "7IRdcLESUa4CsN01aEvQgOtkCNVjSCtkJGP0FstsWM4hP7lfSB7P2tDL+ugy6GvB\n" + + "X1sz9fMC7QMAFL98nDm/yqcnejG1BcQXZho8n0svSfbcVByGlPZGMuI9t25+0B2M\n" + + "TAx0f6zoD8+fFmhcVgS6MQPybGKFawckYl0zulsePqs+G4voIW17owGKsRiv06Jm\n" + + "ZSwd3KoGmjM49ADzuG9yrQ5PSa0nhVk1tybNape4HNYHrAmmN0ILlN+E0Bs/Edz4\n" + + "ntYZuoc/Z35tCgm79dV4/Vl6HUZ1JrLsLrEWCByVytwVFyf3/MwTWdf+Ac+XzBuC\n" + + "yEMqPlvnPWswdnaid35pxios79fPl1Hr0/Q6+DoA5GyYq8SFdP7EYLrGMGa5GJ+x\n" + + "5nS7z6U4UmZ2sXuKYHnuhB0zi6Y04a+fhT71x02eTeC7aPlEB319UqysujJVJnso\n" + + "bkcwOu/Jj0Is9YeFd693dB44xeZuYyvlwoD19lqcim0TSa2Tw7D1W/yu47dKrVP2\n" + + "VKxRqomuAQOpoZiuSfq1/7ysrV8U4hIlIU2vnrSVJ8EtPQKsoBW5l70dQGwXyxBk\n" + + "BUTHqfJ4LG/kPGRMOtUzgqFw2DjJtbym1q1MZgp2ycMon4vp7DeQLGs2XfEANB+Y\n" + + "nRwtjpevqAnIuK6K3Y02LY4FXTNQpC37Xb04bmdIQAcE0MaoP4/hY87aS82PQ68g\n" + + "3bI79uKo4we2g+WaEJlEzQ7147ZzV2wbDq89W69x1MWTfaDwlEtd4UaacYchAv7B\n" + + "TVaaVFiRAUywWaHGePpZG2WV1feH/zd+temxWR9qMFgBZySg1jipBPVciwl0LqlW\n" + + "s/raIBYmLmAaMMgM3759UkNVznDoFHrY4z2EADXp0RHHVzJS1x+yYvp/9I+AcW55\n" + + "oN0UP/3uQ6eyz/ix22sovQwhMJ8rmgR6CfyRPKmXu1RPK3puNv7mbFTfTXpYN2vX\n" + + "vhEZReXY8hJF/9o4G3UrJ1F0MgUHMCG86cw1z0bhPSaXVoufOnx/fRoxJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwgZ0wgY0wSQYJKoZIhvcN\n" + + "AQUOMDwwLAYJKoZIhvcNAQUMMB8ECFDaXOUaOcUPAgIIAAIBQDAMBggqhkiG9w0C\n" + + "CwUAMAwGCCqGSIb3DQILBQAEQHIAM8C9OAsHUCj9CmOJioqf7YwD4O/b3UiZ3Wqo\n" + + "F6OmQIRDc68SdkZJ6024l4nWlnhTE7a4lb2Tru4k3NOTa1oECE5PVCBVU0VEAgEB"); + + // Invalid PKCS #12 File with Incorrect Iteration Count + private static final byte[] pkcs12WithPBMac1PBKdf2_a4 = Base64.decode("MIIKiwIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfTBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhvRzw4sC4xcwICCAECASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQITk9UIFVTRUQCAggA"); + + // Invalid PKCS #12 File with Incorrect Salt + private static final byte[] pkcs12WithPBMac1PBKdf2_a5 = Base64.decode("MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhOT1QgVVNFRAICCAACASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQIb0c8OLAuMXMCAQE="); + + // Invalid PKCS #12 File with Missing Key Length + private static final byte[] pkcs12WithPBMac1PBKdf2_a6 = Base64.decode("MIIKiAIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwejBqMEYGCSqGSIb3DQEF\n" + + "DjA5MCkGCSqGSIb3DQEFDDAcBAhvRzw4sC4xcwICCAAwDAYIKoZIhvcNAgkFADAM\n" + + "BggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG3QQI\n" + + "b0c8OLAuMXMCAggA"); + /* * we generate the CA's certificate */ @@ -777,6 +1141,68 @@ public void testPfxPduMac() assertFalse(pfx.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), "not right".toCharArray())); } + public void testPfxPduMac1() + throws Exception + { + // + // set up the keys + // + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + PublicKey pubKey = fact.generatePublic(pubKeySpec); + + X509Certificate[] chain = createCertChain(fact, pubKey); + + PKCS12PfxPdu pfx = createPfxMac1(privKey, pubKey, chain); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), passwd)); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), "not right".toCharArray())); + + KeyStore pkcs12 = KeyStore.getInstance("PKCS12", "BC"); + + pkcs12.load(new ByteArrayInputStream(pfx.getEncoded()), passwd); + } + + public void testPfxPduPBMac1PBKdf2() + throws Exception + { + final char[] password = "1234".toCharArray(); + // valid test vectors + for (byte[] test_vector : new byte[][]{pkcs12WithPBMac1PBKdf2_a1, pkcs12WithPBMac1PBKdf2_a2, pkcs12WithPBMac1PBKdf2_a3}) + { + PKCS12PfxPdu pfx = new PKCS12PfxPdu(test_vector); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), password)); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), "not right".toCharArray())); + } + + // invalid test vectors + for (byte[] test_vector : new byte[][]{pkcs12WithPBMac1PBKdf2_a4, pkcs12WithPBMac1PBKdf2_a5}) + { + PKCS12PfxPdu pfx = new PKCS12PfxPdu(test_vector); + + assertTrue(pfx.hasMac()); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), password)); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), "not right".toCharArray())); + } + + // invalid test vector that throws exception + final PKCS12PfxPdu pfx = new PKCS12PfxPdu(pkcs12WithPBMac1PBKdf2_a6); + assertTrue(pfx.hasMac()); + PKCSException thrown = assertThrows(PKCSException.class, new ThrowingRunnable() + { + @Override + public void run() + throws Throwable + { + pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), password); + } + }); + assertTrue(thrown.getMessage().contains("Key length must be present when using PBMAC1.")); + } + public void testBcEncryptedPrivateKeyInfo() throws Exception { @@ -1352,4 +1778,47 @@ private PKCS12PfxPdu createPfx(PrivateKey privKey, PublicKey pubKey, X509Certifi return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwd); } + + private PKCS12PfxPdu createPfxMac1(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain) + throws NoSuchAlgorithmException, IOException, PKCSException + { + JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); + + PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]); + + taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Primary Certificate")); + + PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]); + + caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Intermediate Certificate")); + + PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]); + + eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); + eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); + + PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd)); + + keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); + keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); + + // + // construct the actual key store + // + PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder(); + + PKCS12SafeBag[] certs = new PKCS12SafeBag[3]; + + certs[0] = eeCertBagBuilder.build(); + certs[1] = caCertBagBuilder.build(); + certs[2] = taCertBagBuilder.build(); + + pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwd), certs); + + pfxPduBuilder.addData(keyBagBuilder.build()); + + return pfxPduBuilder.build(new BcPKCS12PBMac1CalculatorBuilder(new PBMAC1Params( + new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(Strings.toByteArray("saltsalt"), 1024, 256, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))), + new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA512))), passwd); + } } diff --git a/pkix/src/test/java/org/bouncycastle/pkix/test/AllTests.java b/pkix/src/test/java/org/bouncycastle/pkix/test/AllTests.java index d72390b78c..4955ee577e 100644 --- a/pkix/src/test/java/org/bouncycastle/pkix/test/AllTests.java +++ b/pkix/src/test/java/org/bouncycastle/pkix/test/AllTests.java @@ -22,6 +22,7 @@ public static Test suite() suite.addTestSuite(CheckerTest.class); suite.addTestSuite(RevocationTest.class); + suite.addTestSuite(CheckNameConstraintsTest.class); return new BCTestSetup(suite); } diff --git a/pkix/src/test/java/org/bouncycastle/pkix/test/CheckNameConstraintsTest.java b/pkix/src/test/java/org/bouncycastle/pkix/test/CheckNameConstraintsTest.java new file mode 100644 index 0000000000..e24392b6ca --- /dev/null +++ b/pkix/src/test/java/org/bouncycastle/pkix/test/CheckNameConstraintsTest.java @@ -0,0 +1,123 @@ +package org.bouncycastle.pkix.test; + +import java.security.Security; +import java.security.cert.CertPath; +import java.security.cert.CertPathBuilder; +import java.security.cert.CertPathValidator; +import java.security.cert.CertStore; +import java.security.cert.CertificateFactory; +import java.security.cert.CollectionCertStoreParameters; +import java.security.cert.PKIXBuilderParameters; +import java.security.cert.PKIXCertPathBuilderResult; +import java.security.cert.PKIXParameters; +import java.security.cert.TrustAnchor; +import java.security.cert.X509CertSelector; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pkix.jcajce.PKIXCertPathReviewer; +import org.bouncycastle.test.TestResourceFinder; + +public class CheckNameConstraintsTest + extends TestCase +{ + public void testPKIXCertPathReviewer() + throws Exception + { + Security.addProvider(new BouncyCastleProvider()); + + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + + X509Certificate root = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-root.crt")); + X509Certificate ca1 = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-ca1.crt")); + X509Certificate ca2 = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-ca2.crt")); + X509Certificate leaf = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-leaf.crt")); + + List certchain = new ArrayList(); + certchain.add(root); + certchain.add(ca1); + certchain.add(ca2); + certchain.add(leaf); + + CertPath cp = cf.generateCertPath(certchain); + + Set trust = new HashSet(); + trust.add(new TrustAnchor(root, null)); + PKIXParameters param = new PKIXParameters(trust); + + PKIXCertPathReviewer certPathReviewer = new PKIXCertPathReviewer(); + certPathReviewer.init(cp, param); + + assertFalse(certPathReviewer.isValidCertPath()); // hit + } + + public void testPKIXCertPathBuilder() + throws Exception + { + Security.addProvider(new BouncyCastleProvider()); + + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + X509Certificate rootCert = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-root.crt")); + X509Certificate endCert = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-ca1.crt")); + + // create CertStore to support path building + List list = new ArrayList(); + list.add(endCert); + + CollectionCertStoreParameters params = new CollectionCertStoreParameters(list); + CertStore store = CertStore.getInstance("Collection", params, "BC"); + + // build the path + CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); + X509CertSelector pathConstraints = new X509CertSelector(); + + pathConstraints.setCertificate(endCert); + + PKIXBuilderParameters buildParams = new PKIXBuilderParameters(Collections.singleton(new TrustAnchor(rootCert, null)), pathConstraints); + + buildParams.addCertStore(store); + buildParams.setDate(new Date(1744869361113L)); // 17th April 2025 + buildParams.setRevocationEnabled(false); + + PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(buildParams); + CertPath path = result.getCertPath(); + + if (path.getCertificates().size() != 1) + { + fail("wrong number of certs in testPKIXCertPathBuilder path"); + } + } + + public void testPKIXCertPathValidator() + throws Exception + { + Security.addProvider(new BouncyCastleProvider()); + + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + + X509Certificate rootCert = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-root.crt")); + X509Certificate endCert = (X509Certificate) cf.generateCertificate(TestResourceFinder.findTestResource("pkix", "mal-ca1.crt")); + + List list = new ArrayList(); + list.add(endCert); + + CertPath certPath = cf.generateCertPath(list); + + Set trust = new HashSet(); + trust.add(new TrustAnchor(rootCert, null)); + + CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC"); + PKIXParameters param = new PKIXParameters(trust); + param.setRevocationEnabled(false); + param.setDate(new Date(1744869361113L)); // 17th April 2025 + + cpv.validate(certPath, param); + } +} diff --git a/pkix/src/test/java/org/bouncycastle/tsp/test/ERSTest.java b/pkix/src/test/java/org/bouncycastle/tsp/test/ERSTest.java index 72d8d9f5b9..d703816833 100644 --- a/pkix/src/test/java/org/bouncycastle/tsp/test/ERSTest.java +++ b/pkix/src/test/java/org/bouncycastle/tsp/test/ERSTest.java @@ -1,12 +1,15 @@ package org.bouncycastle.tsp.test; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; +import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.security.KeyPair; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Security; import java.security.cert.X509Certificate; @@ -17,8 +20,8 @@ import java.util.HashSet; import java.util.List; -import junit.framework.Assert; import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -31,6 +34,7 @@ import org.bouncycastle.operator.DigestCalculator; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.tsp.TSPAlgorithms; @@ -106,7 +110,7 @@ public void testBasicBuild() TimeStampRequest tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("98fbf91c1aebdfec514d4a76532ec95f27ebcf4c8b6f7e2947afcbbfe7084cd4"), + assertTrue(Arrays.areEqual(Hex.decode("98fbf91c1aebdfec514d4a76532ec95f27ebcf4c8b6f7e2947afcbbfe7084cd4"), tspReq.getMessageImprintDigest())); String signDN = "O=Bouncy Castle, C=AU"; @@ -213,7 +217,7 @@ public void testBuildMultiGroups() TimeStampRequest tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("06836dfdec4b556e05535d5696b0e4add5cee7d765bcba1f4c1613ddb9176813"), + assertTrue(Arrays.areEqual(Hex.decode("06836dfdec4b556e05535d5696b0e4add5cee7d765bcba1f4c1613ddb9176813"), tspReq.getMessageImprintDigest())); String signDN = "O=Bouncy Castle, C=AU"; @@ -336,7 +340,7 @@ public void testBuildMulti() TimeStampRequest tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("b7efd5e742df672584e69b36ba5592748f841cc400ef989180aa2a69e43499e8"), + assertTrue(Arrays.areEqual(Hex.decode("b7efd5e742df672584e69b36ba5592748f841cc400ef989180aa2a69e43499e8"), tspReq.getMessageImprintDigest())); String signDN = "O=Bouncy Castle, C=AU"; @@ -514,7 +518,7 @@ public void testMonteMulti() } } } - Assert.assertEquals(atss.size(), count); + assertEquals(atss.size(), count); } private void checkAbsent(ERSEvidenceRecord ats, ERSData data) @@ -625,7 +629,7 @@ public void testBasicBuildEvidenceRecord() TimeStampRequest tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("98fbf91c1aebdfec514d4a76532ec95f27ebcf4c8b6f7e2947afcbbfe7084cd4"), + assertTrue(Arrays.areEqual(Hex.decode("98fbf91c1aebdfec514d4a76532ec95f27ebcf4c8b6f7e2947afcbbfe7084cd4"), tspReq.getMessageImprintDigest())); @@ -716,15 +720,15 @@ public void testBasicBuildEvidenceRecord() Collection recs = store.getMatches(new ERSEvidenceRecordSelector(h3Docs)); - Assert.assertEquals(1, recs.size()); + assertEquals(1, recs.size()); ERSEvidenceRecord r1 = (ERSEvidenceRecord)recs.iterator().next(); recs = store.getMatches(new ERSEvidenceRecordSelector(new ERSByteData(H3A_DATA))); - Assert.assertEquals(1, recs.size()); + assertEquals(1, recs.size()); ERSEvidenceRecord r2 = (ERSEvidenceRecord)recs.iterator().next(); - Assert.assertTrue(r2 == r1); + assertTrue(r2 == r1); } private void checkPresent(ERSEvidenceRecord ev, ERSData data) @@ -1099,7 +1103,7 @@ public void test4NodeBuild() TimeStampRequest tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("d82fea0eaff4b12925a201dff2332965953ca38c1eef6c9e31b55bbce4ce2984"), + assertTrue(Arrays.areEqual(Hex.decode("d82fea0eaff4b12925a201dff2332965953ca38c1eef6c9e31b55bbce4ce2984"), tspReq.getMessageImprintDigest())); ersGen = new ERSArchiveTimeStampGenerator(digestCalculator); @@ -1119,7 +1123,7 @@ public void test4NodeBuild() tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("d82fea0eaff4b12925a201dff2332965953ca38c1eef6c9e31b55bbce4ce2984"), + assertTrue(Arrays.areEqual(Hex.decode("d82fea0eaff4b12925a201dff2332965953ca38c1eef6c9e31b55bbce4ce2984"), tspReq.getMessageImprintDigest())); } @@ -1167,7 +1171,7 @@ public void testDirUtil() TimeStampRequest tspReq = ersGen.generateTimeStampRequest(tspReqGen); - Assert.assertTrue(Arrays.areEqual(Hex.decode("98fbf91c1aebdfec514d4a76532ec95f27ebcf4c8b6f7e2947afcbbfe7084cd4"), + assertTrue(Arrays.areEqual(Hex.decode("98fbf91c1aebdfec514d4a76532ec95f27ebcf4c8b6f7e2947afcbbfe7084cd4"), tspReq.getMessageImprintDigest())); deleteDirectory(rootDir); @@ -1439,19 +1443,16 @@ private void checkReducedHashTree(byte[] dataObjects, byte[][][] reducedHashTree private final ASN1ObjectIdentifier algorithm = NISTObjectIdentifiers.id_sha512; private final ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - @Override public AlgorithmIdentifier getAlgorithmIdentifier() { return new AlgorithmIdentifier(algorithm); } - @Override public OutputStream getOutputStream() { return bOut; } - - @Override + public byte[] getDigest() { final byte[] bytes = bOut.toByteArray(); @@ -1488,7 +1489,7 @@ private byte[] trimBytes(byte[] bytes) final TimeStampRequest timeStampRequest = ersArchiveTimeStampGenerator.generateTimeStampRequest(timeStampRequestGenerator); - //Assert.assertTrue(Arrays.areEqual(Hex.decode("b7efd5e742df672584e69b36ba5592748f841cc400ef989180aa2a69e43499e8"), + //assertTrue(Arrays.areEqual(Hex.decode("b7efd5e742df672584e69b36ba5592748f841cc400ef989180aa2a69e43499e8"), // tspReq.getMessageImprintDigest())); final String signDN = "O=Bouncy Castle, C=AU"; @@ -1530,7 +1531,6 @@ private byte[] trimBytes(byte[] bytes) final DigestCalculatorProvider digestCalculatorProvider = new DigestCalculatorProvider() { - @Override public DigestCalculator get(AlgorithmIdentifier digestAlgorithmIdentifier) throws OperatorCreationException { @@ -1571,4 +1571,79 @@ public DigestCalculator get(AlgorithmIdentifier digestAlgorithmIdentifier) } } + + public void testCompareStreamAndByteData () throws TSPException, ERSException, OperatorCreationException, IOException, + NoSuchAlgorithmException + { + // ER for the String "foo" using SHA-256 and a dummy cert/key. + String evidenceRecordBase64 = "MIIDCgIBATANMAsGCWCGSAFlAwQCATCCAvQwggLwMIIC7DCCAugGCSqGSI" + + "b3DQEHAqCCAtkwggLVAgEDMQ0wCwYJYIZIAWUDBAIDMG0GCyqGSIb3DQEJEAEEoF4EXDBaAgEBBgYEA" + + "I9nAQEwLzALBglghkgBZQMEAgEEICwmtGto/8aP+ZtFPB0wQTQTQi1wZIO/oPmKXohiZueuAgEBGA8y" + + "MDI0MTAwMjIzMDAzNloCCFO56J9TFmGGMYICUDCCAkwCAQEwBTAAAgEAMAsGCWCGSAFlAwQCA6CCAR4" + + "wGgYJKoZIhvcNAQkDMQ0GCyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yNDEwMDIyMzAwMzZaMC" + + "sGCSqGSIb3DQEJNDEeMBwwCwYJYIZIAWUDBAIDoQ0GCSqGSIb3DQEBDQUAME8GCSqGSIb3DQEJBDFCB" + + "EDPPkk9PN5EGrAvZyjv9wJR77tQCIwoA3xWwqESBGICShZxNjt6YU3LZor99ARJ4As+yiIjW/hTg5v3" + + "vqbTrfSIMGQGCyqGSIb3DQEJEAIvMVUwUzBRME8wCwYJYIZIAWUDBAIDBEAPvi2mNblzqqI91nWRM9s" + + "ocS7TJfpyQsx4ZcBVeGK1XjCW6BQ5KmrPFCc+IefB5FB/ZQsPwdyYv6umJzCYK0SzMA0GCSqGSIb3DQ" + + "EBDQUABIIBALWgWcjxzY5QEOlK92GNf9kjBflbO65dYkAKxrrgcwQ6Dz+ablUwsG01ILDUUnSL9wTQC" + + "OkYKb1oEFNrd9lbHWBOqlu5/lMjhZcWnYzbK3rzQRuoPwXYD/GWgiO0wLmF3FQ9xaum1Oui+Y075OS4" + + "7fXfLlSe2wMPlnoDb/IFAgHGBK/3zJ7w7n9OCa1U6qwTYCpw9MTXsOI/PbNw2h3cHTVgbY+HCTB4oJC" + + "GpY9bbEMuJboe4DkQx2Eqpq1pVaMKRxsjhrnbH8QlkUGtuGztqnZa5AoCth79x70Ch7WhdDcxG3wiFi" + + "29pw69obUCh3c61Q2WKl+MKW/tqq7EGYu5+jE="; + DigestCalculatorProvider digestProvider = new BcDigestCalculatorProvider(); + ERSEvidenceRecord ersEvidenceRecord = new ERSEvidenceRecord( + Base64.decode(evidenceRecordBase64), digestProvider); + + // Sanity check, make sure root hash of ER is what we expect. + byte[] sourceData = Strings.toUTF8ByteArray("foo"); + byte[] sourceSha256 = MessageDigest.getInstance("SHA-256").digest(sourceData); + assertTrue(Arrays.areEqual(sourceSha256, ersEvidenceRecord.getPrimaryRootHash())); + + + // Generate hash renewal request using ERSInputStreamData. + ERSData ersStreamData = new ERSInputStreamData(new ByteArrayInputStream(sourceData)); + TimeStampRequest streamDataReq = ersEvidenceRecord.generateHashRenewalRequest( + digestProvider.get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512)), + ersStreamData, + new TimeStampRequestGenerator(), + BigInteger.ZERO); + + + // Generate hash renewal request using ERSByteData to compare against. + ERSData ersByteData = new ERSByteData(sourceData); + TimeStampRequest byteDataReq = ersEvidenceRecord.generateHashRenewalRequest( + digestProvider.get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512)), + ersByteData, + new TimeStampRequestGenerator(), + BigInteger.ZERO); + + + // check ERSByteData and ERSInputStreamData produce same output + assertTrue(Arrays.areEqual(byteDataReq.getMessageImprintDigest(), + streamDataReq.getMessageImprintDigest())); + + + // Generate the digest we expect to see in the requests and compare. + byte[] expectedDigest = generateExpectedRequestDigest(sourceData, ersEvidenceRecord, + MessageDigest.getInstance("SHA-512")); + assertTrue(Arrays.areEqual(byteDataReq.getMessageImprintDigest(), expectedDigest)); + assertTrue(Arrays.areEqual(streamDataReq.getMessageImprintDigest(), expectedDigest)); + } + + /** Based on RFC 4998 section 5.2. */ + private static byte[] generateExpectedRequestDigest (byte[] sourceData, + ERSEvidenceRecord evidenceRecord, MessageDigest digest) throws IOException + { + byte[] atsci = evidenceRecord.toASN1Structure().getArchiveTimeStampSequence().getEncoded(ASN1Encoding.DER); + byte[] hi = digest.digest(sourceData); + byte[] hai = digest.digest(atsci); + byte[] hihai; + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + outputStream.write(hi); + outputStream.write(hai); + hihai = outputStream.toByteArray(); + + byte[] hiprime = digest.digest(hihai); + return hiprime; + } } diff --git a/pkix/src/test/java/org/bouncycastle/tsp/test/PQCTSPTest.java b/pkix/src/test/java/org/bouncycastle/tsp/test/PQCTSPTest.java index 0c0ae7155a..7b208598b9 100644 --- a/pkix/src/test/java/org/bouncycastle/tsp/test/PQCTSPTest.java +++ b/pkix/src/test/java/org/bouncycastle/tsp/test/PQCTSPTest.java @@ -131,7 +131,7 @@ public void testSPHINCSPlus() try { - KeyPairGenerator g = KeyPairGenerator.getInstance("SPHINCS+", BC); + KeyPairGenerator g = KeyPairGenerator.getInstance("SLH-DSA", BC); KeyPair p = g.generateKeyPair(); @@ -152,7 +152,7 @@ public void testSPHINCSPlus() // create the certificate - version 1 // - ContentSigner sigGen = new JcaContentSignerBuilder("SPHINCS+") + ContentSigner sigGen = new JcaContentSignerBuilder("SLH-DSA-SHA2-128F") .setProvider(BC).build(privKey); JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( new X500Name("CN=Test"), @@ -167,7 +167,7 @@ public void testSPHINCSPlus() X509Certificate cert = new JcaX509CertificateConverter() .setProvider("BC").getCertificate(certGen.build(sigGen)); - ContentSigner signer = new JcaContentSignerBuilder("SPHINCS+").setProvider(BC).build(privKey); + ContentSigner signer = new JcaContentSignerBuilder("SLH-DSA-SHA2-128F").setProvider(BC).build(privKey); TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/pkcs/test/PKCS10Test.java b/pkix/src/test/jdk1.3/org/bouncycastle/pkcs/test/PKCS10Test.java index 9a296fa37a..8a18411856 100644 --- a/pkix/src/test/jdk1.3/org/bouncycastle/pkcs/test/PKCS10Test.java +++ b/pkix/src/test/jdk1.3/org/bouncycastle/pkcs/test/PKCS10Test.java @@ -22,6 +22,7 @@ import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.operator.ContentSigner; @@ -34,7 +35,6 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; import org.bouncycastle.test.PrintTestResult; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; @@ -195,15 +195,15 @@ public void testAltRequestAttributes() p256Kpg.initialize(new ECNamedCurveGenParameterSpec("P-256")); KeyPair p256Kp = p256Kpg.generateKeyPair(); - KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("Dilithium", "BC"); - dilKpg.initialize(DilithiumParameterSpec.dilithium2); + KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + dilKpg.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpg.generateKeyPair(); JcaPKCS10CertificationRequestBuilder jcaPkcs10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Name("CN=Test"), p256Kp.getPublic()); - ContentSigner altSigner = new JcaContentSignerBuilder("Dilithium2").setProvider("BC").build(dilKp.getPrivate()); + ContentSigner altSigner = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(dilKp.getPrivate()); - PKCS10CertificationRequest request = jcaPkcs10Builder.build(((JcaContentSignerBuilder)new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC")).build(p256Kp.getPrivate()), dilKp.getPublic(), altSigner); + PKCS10CertificationRequest request = jcaPkcs10Builder.build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(p256Kp.getPrivate()), dilKp.getPublic(), altSigner); assertTrue(request.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(p256Kp.getPublic()))); @@ -219,13 +219,13 @@ public void testDeltaRequestAttribute() p256Kpg.initialize(new ECNamedCurveGenParameterSpec("P-256")); KeyPair p256Kp = p256Kpg.generateKeyPair(); - KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("Dilithium", "BC"); - dilKpg.initialize(DilithiumParameterSpec.dilithium2); + KeyPairGenerator dilKpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + dilKpg.initialize(MLDSAParameterSpec.ml_dsa_44); KeyPair dilKp = dilKpg.generateKeyPair(); PKCS10CertificationRequestBuilder pkcs10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Name("CN=Test"), p256Kp.getPublic()); - ContentSigner deltaSigner = new JcaContentSignerBuilder("Dilithium2").setProvider("BC").build(dilKp.getPrivate()); + ContentSigner deltaSigner = new JcaContentSignerBuilder("ML-DSA-44").setProvider("BC").build(dilKp.getPrivate()); DeltaCertificateRequestAttributeValueBuilder deltaAttrBldr = new DeltaCertificateRequestAttributeValueBuilder( SubjectPublicKeyInfo.getInstance(dilKp.getPublic().getEncoded())); diff --git a/pkix/src/test/jdk1.4/org/bouncycastle/cert/test/AllTests.java b/pkix/src/test/jdk1.4/org/bouncycastle/cert/test/AllTests.java new file mode 100644 index 0000000000..55c6c6c946 --- /dev/null +++ b/pkix/src/test/jdk1.4/org/bouncycastle/cert/test/AllTests.java @@ -0,0 +1,101 @@ +package org.bouncycastle.cert.test; + +import java.security.Security; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.PrintTestResult; +import org.bouncycastle.util.test.SimpleTestResult; + +public class AllTests + extends TestCase +{ + public void setUp() + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public void testSimpleTests() + { + org.bouncycastle.util.test.Test[] tests = new org.bouncycastle.util.test.Test[] + { + new AttrCertSelectorTest(), + new AttrCertTest(), + new CertPathLoopTest(), + new CertTest(), + new DANETest(), + new ExternalKeyTest(), + new GOST3410_2012CMSTest(), + new MLDSACredentialsTest(), + new PKCS10Test(), + new SLHDSACredentialsTest(), + new X509ExtensionUtilsTest(), + }; + + for (int i = 0; i != tests.length; i++) + { + SimpleTestResult result = (SimpleTestResult)tests[i].perform(); + + if (!result.isSuccessful()) + { + if (result.getException() != null) + { + result.getException().printStackTrace(); + } + fail(result.toString()); + } + } + } + + public static void main (String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("Cert Tests"); + + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + + suite.addTestSuite(AllTests.class); + suite.addTestSuite(BcAttrCertSelectorTest.class); + suite.addTestSuite(BcAttrCertSelectorTest.class); + suite.addTestSuite(BcAttrCertTest.class); + suite.addTestSuite(BcCertTest.class); + suite.addTestSuite(BcPKCS10Test.class); + suite.addTestSuite(PQCPKCS10Test.class); + suite.addTest(ConverterTest.suite()); + + return new BCTestSetup(suite); + } + + static class BCTestSetup + extends TestSetup + { + public BCTestSetup(Test test) + { + super(test); + } + + protected void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + protected void tearDown() + { + Security.removeProvider("BC"); + } + } + +} \ No newline at end of file diff --git a/pkix/src/test/jdk1.4/org/bouncycastle/cms/test/PQCSignedDataTest.java b/pkix/src/test/jdk1.4/org/bouncycastle/cms/test/PQCSignedDataTest.java new file mode 100644 index 0000000000..373810ff68 --- /dev/null +++ b/pkix/src/test/jdk1.4/org/bouncycastle/cms/test/PQCSignedDataTest.java @@ -0,0 +1,445 @@ +package org.bouncycastle.cms.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.KeyPair; +import java.security.MessageDigest; +import java.security.Security; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.cms.Attribute; +import org.bouncycastle.asn1.cms.AttributeTable; +import org.bouncycastle.asn1.cms.CMSAttributes; +import org.bouncycastle.asn1.cms.ContentInfo; +import org.bouncycastle.asn1.cms.SignerInfo; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaCertStore; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.CMSProcessableByteArray; +import org.bouncycastle.cms.CMSSignedData; +import org.bouncycastle.cms.CMSSignedDataGenerator; +import org.bouncycastle.cms.CMSTypedData; +import org.bouncycastle.cms.SignerId; +import org.bouncycastle.cms.SignerInformation; +import org.bouncycastle.cms.SignerInformationStore; +import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; +import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.DigestCalculatorProvider; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.util.Store; + +public class PQCSignedDataTest + extends TestCase +{ + private static final String BC = BouncyCastleProvider.PROVIDER_NAME; + private static final String BCPQC = BouncyCastlePQCProvider.PROVIDER_NAME; + + boolean DEBUG = true; + + private static String _origDN; + private static KeyPair _origKP; + private static X509Certificate _origCert; + + private static KeyPair _origFalconKP; + private static X509Certificate _origFalconCert; + private static KeyPair _origPicnicKP; + private static X509Certificate _origPicnicCert; + private static KeyPair _origMlDsaKP; + private static X509Certificate _origMlDsaCert; + private static KeyPair _origSlhDsaKP; + private static X509Certificate _origSlhDsaCert; + + private static String _signDN; + private static KeyPair _signKP; + private static X509Certificate _signCert; + private static KeyPair _signFalconKP; + private static X509Certificate _signFalconCert; + private static KeyPair _signPicnicKP; + private static X509Certificate _signPicnicCert; + private static KeyPair _signMlDsaKP; + private static X509Certificate _signMlDsaCert; + private static KeyPair _signSlhDsaKP; + private static X509Certificate _signSlhDsaCert; + + private static boolean _initialised = false; + + private static final Set noParams = new HashSet(); + + static + { + noParams.add(BCObjectIdentifiers.sphincs256_with_SHA512); + noParams.add(BCObjectIdentifiers.sphincs256_with_SHA3_512); + } + + public PQCSignedDataTest(String name) + { + super(name); + } + + public static void main(String args[]) + throws Exception + { + init(); + + junit.textui.TestRunner.run(PQCSignedDataTest.class); + } + + public static Test suite() + throws Exception + { + init(); + + return new CMSTestSetup(new TestSuite(PQCSignedDataTest.class)); + } + + public void setUp() + throws Exception + { + init(); + } + + private static void init() + throws Exception + { + if (!_initialised) + { + _initialised = true; + + if (Security.getProvider(BC) == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + if (Security.getProvider(BCPQC) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + + _origDN = "O=Bouncy Castle, C=AU"; + _origKP = PQCTestUtil.makeKeyPair(); + _origCert = PQCTestUtil.makeCertificate(_origKP, _origDN, _origKP, _origDN); + + _signDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; + _signKP = PQCTestUtil.makeKeyPair(); + _signCert = PQCTestUtil.makeCertificate(_signKP, _signDN, _origKP, _origDN); + + _origFalconKP = PQCTestUtil.makeFalconKeyPair(); + _origFalconCert = PQCTestUtil.makeCertificate(_origFalconKP, _origDN, _origFalconKP, _origDN); + + _signFalconKP = PQCTestUtil.makeFalconKeyPair(); + _signFalconCert = PQCTestUtil.makeCertificate(_signFalconKP, _signDN, _origFalconKP, _origDN); + + _origPicnicKP = PQCTestUtil.makePicnicKeyPair(); + _origPicnicCert = PQCTestUtil.makeCertificate(_origPicnicKP, _origDN, _origPicnicKP, _origDN); + + _signPicnicKP = PQCTestUtil.makePicnicKeyPair(); + _signPicnicCert = PQCTestUtil.makeCertificate(_signPicnicKP, _signDN, _origPicnicKP, _origDN); + + _origMlDsaKP = PQCTestUtil.makeMlDsaKeyPair(); + _origMlDsaCert = PQCTestUtil.makeCertificate(_origMlDsaKP, _origDN, _origMlDsaKP, _origDN); + + _signMlDsaKP = PQCTestUtil.makeMlDsaKeyPair(); + _signMlDsaCert = PQCTestUtil.makeCertificate(_signMlDsaKP, _signDN, _origMlDsaKP, _origDN); + + _origSlhDsaKP = PQCTestUtil.makeSlhDsaKeyPair(); + _origSlhDsaCert = PQCTestUtil.makeCertificate(_origSlhDsaKP, _origDN, _origSlhDsaKP, _origDN); + + _signSlhDsaKP = PQCTestUtil.makeSlhDsaKeyPair(); + _signSlhDsaCert = PQCTestUtil.makeCertificate(_signSlhDsaKP, _signDN, _origSlhDsaKP, _origDN); + } + } + + public void testSPHINCS256Encapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origCert); + certList.add(_signCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("SHA512withSPHINCS256").setProvider(BCPQC).build(_origKP.getPrivate()), _origCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); + ASN1InputStream aIn = new ASN1InputStream(bIn); + + s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + + certs = s.getCertificates(); + + SignerInformationStore signers = s.getSignerInfos(); + + Collection c = signers.getSigners(); + Iterator it = c.iterator(); + SignerId sid = null; + + while (it.hasNext()) + { + SignerInformation signer = (SignerInformation)it.next(); + Collection certCollection = certs.getMatches(signer.getSID()); + + Iterator certIt = certCollection.iterator(); + X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); + + assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))); + + // + // check content digest + // + + byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); + + AttributeTable table = signer.getSignedAttributes(); + Attribute hash = table.get(CMSAttributes.messageDigest); + + assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); + } + } + + public void testFalconEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origFalconCert); + certList.add(_signFalconCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("Falcon-512").setProvider(BCPQC).build(_origFalconKP.getPrivate()), _origFalconCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); + ASN1InputStream aIn = new ASN1InputStream(bIn); + + s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + + certs = s.getCertificates(); + + SignerInformationStore signers = s.getSignerInfos(); + + Collection c = signers.getSigners(); + Iterator it = c.iterator(); + + while (it.hasNext()) + { + SignerInformation signer = (SignerInformation)it.next(); + Collection certCollection = certs.getMatches(signer.getSID()); + + Iterator certIt = certCollection.iterator(); + X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); + + assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))); + + // + // check content digest + // + + byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); + + AttributeTable table = signer.getSignedAttributes(); + Attribute hash = table.get(CMSAttributes.messageDigest); + + assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); + } + } + + public void testPicnicEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origPicnicCert); + certList.add(_signPicnicCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("PICNIC").setProvider(BCPQC).build(_origPicnicKP.getPrivate()), _origPicnicCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testMLDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origMlDsaCert); + certList.add(_signMlDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("ML-DSA").setProvider(BC).build(_origMlDsaKP.getPrivate()), _origMlDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testHashMLDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origMlDsaCert); + certList.add(_signMlDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("HASH-ML-DSA").setProvider(BC).build(_origMlDsaKP.getPrivate()), _origMlDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testSLHDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origSlhDsaCert); + certList.add(_signSlhDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("SLH-DSA").setProvider(BC).build(_origSlhDsaKP.getPrivate()), _origSlhDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + public void testHashSLHDSAEncapsulated() + throws Exception + { + List certList = new ArrayList(); + CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); + + certList.add(_origSlhDsaCert); + certList.add(_signSlhDsaCert); + + Store certs = new JcaCertStore(certList); + + CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); + + DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); + + gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("HASH-SLH-DSA").setProvider(BC).build(_origSlhDsaKP.getPrivate()), _origSlhDsaCert)); + + gen.addCertificates(certs); + + CMSSignedData s = gen.generate(msg, true); + + checkSignature(s, gen); + } + + private void checkSignature(CMSSignedData s, CMSSignedDataGenerator gen) + throws IOException, CMSException, OperatorCreationException, CertificateException + { + Store certs; + ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); + ASN1InputStream aIn = new ASN1InputStream(bIn); + + s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + + certs = s.getCertificates(); + + SignerInformationStore signers = s.getSignerInfos(); + + Collection c = signers.getSigners(); + Iterator it = c.iterator(); + + + while (it.hasNext()) + { + SignerInformation signer = (SignerInformation)it.next(); + Collection certCollection = certs.getMatches(signer.getSID()); + + Iterator certIt = certCollection.iterator(); + X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); + + cert.getSubjectPublicKeyInfo(); + + assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))); + + // + // check content digest + // + + byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); + + AttributeTable table = signer.getSignedAttributes(); + Attribute hash = table.get(CMSAttributes.messageDigest); + + assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); + } + } +} diff --git a/pkix/src/test/jdk1.4/org/bouncycastle/cms/test/PQCTestUtil.java b/pkix/src/test/jdk1.4/org/bouncycastle/cms/test/PQCTestUtil.java new file mode 100644 index 0000000000..30547c4b04 --- /dev/null +++ b/pkix/src/test/jdk1.4/org/bouncycastle/cms/test/PQCTestUtil.java @@ -0,0 +1,132 @@ +package org.bouncycastle.cms.test; + +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Date; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jcajce.interfaces.MLDSAKey; +import org.bouncycastle.jcajce.interfaces.SLHDSAKey; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; +import org.bouncycastle.jce.X509KeyUsage; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.pqc.jcajce.interfaces.FalconKey; +import org.bouncycastle.pqc.jcajce.interfaces.PicnicKey; +import org.bouncycastle.pqc.jcajce.spec.FalconParameterSpec; +import org.bouncycastle.pqc.jcajce.spec.PicnicParameterSpec; +import org.bouncycastle.pqc.jcajce.spec.SPHINCS256KeyGenParameterSpec; +import org.bouncycastle.pqc.jcajce.spec.SPHINCSPlusParameterSpec; + +public class PQCTestUtil +{ + public static KeyPair makeKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("SPHINCS256", "BCPQC"); + + kpGen.initialize(new SPHINCS256KeyGenParameterSpec(), new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static KeyPair makeSphincsPlusKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("SPHINCSPlus", "BCPQC"); + + kpGen.initialize(SPHINCSPlusParameterSpec.sha2_128f_robust, new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static KeyPair makeFalconKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Falcon", "BCPQC"); + + kpGen.initialize(FalconParameterSpec.falcon_512, new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static KeyPair makePicnicKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Picnic", "BCPQC"); + //TODO: divide into two with cases with digest and with parametersets + kpGen.initialize(PicnicParameterSpec.picnicl1full, new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static KeyPair makeMlDsaKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ML-DSA", "BC"); + //TODO: divide into two with cases with digest and with parametersets + kpGen.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static KeyPair makeSlhDsaKeyPair() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + //TODO: divide into two with cases with digest and with parametersets + kpGen.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, new SecureRandom()); + + return kpGen.generateKeyPair(); + } + + public static X509Certificate makeCertificate(KeyPair subKP, String subDN, KeyPair issKP, String issDN) + throws Exception + { + // + // create base certificate - version 3 + // + ContentSigner sigGen; + PrivateKey issPriv = issKP.getPrivate(); + if (issPriv instanceof FalconKey) + { + sigGen = new JcaContentSignerBuilder(((FalconKey)issPriv).getParameterSpec().getName()).setProvider("BCPQC").build(issPriv); + } + else if (issPriv instanceof PicnicKey) + { +// sigGen = new JcaContentSignerBuilder(((PicnicKey)issPriv).getParameterSpec().getName()).setProvider("BCPQC").build(issPriv); + sigGen = new JcaContentSignerBuilder("PICNIC").setProvider("BCPQC").build(issPriv); + } + else if (issPriv instanceof MLDSAKey) + { + sigGen = new JcaContentSignerBuilder("ML-DSA").setProvider("BC").build(issPriv); + } + else if (issPriv instanceof SLHDSAKey) + { + sigGen = new JcaContentSignerBuilder("SLH-DSA").setProvider("BC").build(issPriv); + } + else + { + sigGen = new JcaContentSignerBuilder("SHA512withSPHINCS256").setProvider("BCPQC").build(issPriv); + } + + X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X500Name(issDN), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), new X500Name(subDN), subKP.getPublic()) + .addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, + new X509KeyUsage(X509KeyUsage.digitalSignature)) + .addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, + new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); + + return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); + } +} diff --git a/pkix/src/test/jdk1.4/org/bouncycastle/pkcs/test/PfxPduTest.java b/pkix/src/test/jdk1.4/org/bouncycastle/pkcs/test/PfxPduTest.java new file mode 100644 index 0000000000..fba6f10f43 --- /dev/null +++ b/pkix/src/test/jdk1.4/org/bouncycastle/pkcs/test/PfxPduTest.java @@ -0,0 +1,1744 @@ +package org.bouncycastle.pkcs.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.security.AlgorithmParameters; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Security; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.spec.KeySpec; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Date; + +import javax.crypto.Cipher; +import javax.crypto.EncryptedPrivateKeyInfo; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERBMPString; +import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.Attribute; +import org.bouncycastle.asn1.pkcs.ContentInfo; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.BCStyle; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v1CertificateBuilder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX500NameUtil; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; +import org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.crypto.engines.DESedeEngine; +import org.bouncycastle.crypto.engines.RC2Engine; +import org.bouncycastle.crypto.modes.CBCBlockCipher; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.InputDecryptorProvider; +import org.bouncycastle.operator.OutputEncryptor; +import org.bouncycastle.operator.bc.BcDefaultDigestProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.pkcs.PKCS12PfxPdu; +import org.bouncycastle.pkcs.PKCS12PfxPduBuilder; +import org.bouncycastle.pkcs.PKCS12SafeBag; +import org.bouncycastle.pkcs.PKCS12SafeBagBuilder; +import org.bouncycastle.pkcs.PKCS12SafeBagFactory; +import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; +import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfoBuilder; +import org.bouncycastle.pkcs.PKCSException; +import org.bouncycastle.pkcs.bc.BcPKCS12MacCalculatorBuilder; +import org.bouncycastle.pkcs.bc.BcPKCS12MacCalculatorBuilderProvider; +import org.bouncycastle.pkcs.bc.BcPKCS12PBMac1CalculatorBuilderProvider; +import org.bouncycastle.pkcs.bc.BcPKCS12PBEInputDecryptorProviderBuilder; +import org.bouncycastle.pkcs.bc.BcPKCS12PBEOutputEncryptorBuilder; +import org.bouncycastle.pkcs.jcajce.JcaPKCS12SafeBagBuilder; +import org.bouncycastle.pkcs.jcajce.JcaPKCS8EncryptedPrivateKeyInfoBuilder; +import org.bouncycastle.pkcs.jcajce.JcePKCS12MacCalculatorBuilder; +import org.bouncycastle.pkcs.jcajce.JcePKCS12MacCalculatorBuilderProvider; +import org.bouncycastle.pkcs.jcajce.JcePKCSPBEInputDecryptorProviderBuilder; +import org.bouncycastle.pkcs.jcajce.JcePKCSPBEOutputEncryptorBuilder; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Base64; + +public class PfxPduTest + extends TestCase +{ + private static final String BC = BouncyCastleProvider.PROVIDER_NAME; + private static final char[] passwd = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}; + + // + // personal keys + // + private static final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16)); + + private static final RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16), + new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), + new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), + new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), + new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), + new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), + new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); + + // + // intermediate keys. + // + private static final RSAPublicKeySpec intPubKeySpec = new RSAPublicKeySpec( + new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), + new BigInteger("ffff", 16)); + + + private static final RSAPrivateCrtKeySpec intPrivKeySpec = new RSAPrivateCrtKeySpec( + new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), + new BigInteger("ffff", 16), + new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16), + new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16), + new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16), + new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16), + new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16), + new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16)); + + // + // ca keys + // + private static final RSAPublicKeySpec caPubKeySpec = new RSAPublicKeySpec( + new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), + new BigInteger("11", 16)); + + private static final RSAPrivateCrtKeySpec caPrivKeySpec = new RSAPrivateCrtKeySpec( + new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), + new BigInteger("11", 16), + new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16), + new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16), + new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16), + new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16), + new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16), + new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16)); + + // + // pkcs-12 pfx-pdu + // + private String pkcs12Pass = "hello world"; + + private byte[] pkcs12 = Base64.decode( + "MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZI" + + "hvcNAQcBBAGgBAGABAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCAzQEAQQEAQEE" + + "ATAEAQQEAQMEA4IDMAQBBAQBAQQBBgQBBAQBAQQBCwQBBAQBCwQLKoZIhvcN" + + "AQwKAQIEAQQEAQEEAaAEAQQEAQMEA4ICpQQBBAQBAQQBMAQBBAQBAwQDggKh" + + "BAEEBAEBBAEwBAEEBAEBBAEbBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoq" + + "hkiG9w0BDAEDBAEEBAEPBA8wDQQIoagiwNZPJR4CAQEEAQQEAQEEAQQEAQQE" + + "AQMEA4ICgAQBBAQDggKABIICgEPG0XlhMFyrs4ZWDrvEzl51ICfXd6K2ql2l" + + "nnxhszUbigtSj6x49VEx4PfOB9fQFeidc5L5An+nKp646NBMIY0UwXGs8BLQ" + + "au59jtOs987+l7QYIvl6fdGUIuLPhVSnZZDyqD+HQjU/0/ccKFHRif4tlEQq" + + "aErvZbFeH0pg4ijf1HfgX6gBJGRKdO+msa4qKGnZdHCSLZehyyxvxAmURetg" + + "yhtEl7RmedTB+4TDs7atekqxkNlD9tfwDUX6sb0IH6qbEA6P/DlVMdaD54Cl" + + "QDxRzOfIIjklZhv5OMFWtPK0aYPcqyxzLpw1qRAyoTVXpidkj/hpIpgCVBP/" + + "k5s2+WdGbLgA/4/zSrF6feRCE5llzM2IGxiHVq4oPzzngl3R+Fi5VCPDMcuW" + + "NRuIOzJA+RNV2NPOE/P3knThDnwiImq+rfxmvZ1u6T06s20RmWK6cxp7fTEw" + + "lQ9BOsv+mmyV8dr6cYJq4IlRzHdFOyEUBDwfHThyribNKKobO50xh2f93xYj" + + "Rn5UMOQBJIe3b7OKZt5HOIMrJSZO02IZgvImi9yQWi96PnWa419D1cAsLWvM" + + "xiN0HqZMbDFfxVM2BZmsxiexLhkHWKwLqfQDzRjJfmVww8fnXpWZhFXKyut9" + + "gMGEyCNoba4RU3QI/wHKWYaK74qtJpsucuLWBH6UcsHsCry6VZkwRxWwC0lb" + + "/F3Bm5UKHax5n9JHJ2amQm9zW3WJ0S5stpPObfmg5ArhbPY+pVOsTqBRlop1" + + "bYJLD/X8Qbs468Bwzej0FhoEU59ZxFrbjLSBsMUYrVrwD83JE9kEazMLVchc" + + "uCB9WT1g0hxYb7VA0BhOrWhL8F5ZH72RMCYLPI0EAQQEAQEEATEEAQQEAQEE" + + "AXgEAQQEAQEEATAEAQQEAQEEAVEEAQQEAQEEAQYEAQQEAQEEAQkEAQQEAQkE" + + "CSqGSIb3DQEJFAQBBAQBAQQBMQQBBAQBAQQBRAQBBAQBAQQBHgQBBAQBAQQB" + + "QgQBBAQBQgRCAEQAYQB2AGkAZAAgAEcALgAgAEgAbwBvAGsAJwBzACAAVgBl" + + "AHIAaQBTAGkAZwBuACwAIABJAG4AYwAuACAASQBEBAEEBAEBBAEwBAEEBAEB" + + "BAEjBAEEBAEBBAEGBAEEBAEBBAEJBAEEBAEJBAkqhkiG9w0BCRUEAQQEAQEE" + + "ATEEAQQEAQEEARYEAQQEAQEEAQQEAQQEAQEEARQEAQQEARQEFKEcMJ798oZL" + + "FkH0OnpbUBnrTLgWBAIAAAQCAAAEAgAABAEwBAGABAEGBAEJBAkqhkiG9w0B" + + "BwYEAaAEAYAEATAEAYAEAQIEAQEEAQAEATAEAYAEAQYEAQkECSqGSIb3DQEH" + + "AQQBMAQBGwQBBgQBCgQKKoZIhvcNAQwBBgQPMA0ECEE7euvmxxwYAgEBBAGg" + + "BAGABAEEBAEIBAgQIWDGlBWxnwQBBAQBCAQI2WsMhavhSCcEAQQEAQgECPol" + + "uHJy9bm/BAEEBAEQBBCiRxtllKXkJS2anKD2q3FHBAEEBAEIBAjKy6BRFysf" + + "7gQBBAQDggMwBIIDMJWRGu2ZLZild3oz7UBdpBDUVMOA6eSoWiRIfVTo4++l" + + "RUBm8TpmmGrVkV32PEoLkoV+reqlyWCvqqSjRzi3epQiVwPQ6PV+ccLqxDhV" + + "pGWDRQ5UttDBC2+u4fUQVZi2Z1i1g2tsk6SzB3MKUCrjoWKvaDUUwXo5k9Vz" + + "qSLWCLTZCjs3RaY+jg3NbLZYtfMDdYovhCU2jMYV9adJ8MxxmJRz+zPWAJph" + + "LH8hhfkKG+wJOSszqk9BqGZUa/mnZyzeQSMTEFga1ZB/kt2e8SZFWrTZEBgJ" + + "oszsL5MObbwMDowNurnZsnS+Mf7xi01LeG0VT1fjd6rn9BzVwuMwhoqyoCNo" + + "ziUqSUyLEwnGTYYpvXLxzhNiYzW8546KdoEKDkEjhfYsc4XqSjm9NYy/BW/M" + + "qR+aL92j8hqnkrWkrWyvocUe3mWaiqt7/oOzNZiMTcV2dgjjh9HfnjSHjFGe" + + "CVhnEWzV7dQIVyc/qvNzOuND8X5IyJ28xb6a/i1vScwGuo/UDgPAaMjGw28f" + + "siOZBShzde0Kj82y8NilfYLHHeIGRW+N/grUFWhW25mAcBReXDd5JwOqM/eF" + + "y+4+zBzlO84ws88T1pkSifwtMldglN0APwr4hvUH0swfiqQOWtwyeM4t+bHd" + + "5buAlXOkSeF5rrLzZ2/Lx+JJmI2pJ/CQx3ej3bxPlx/BmarUGAxaI4le5go4" + + "KNfs4GV8U+dbEHQz+yDYL+ksYNs1eb+DjI2khbl28jhoeAFKBtu2gGOL5M9M" + + "CIP/JDOCHimu1YZRuOTAf6WISnG/0Ri3pYZsgQ0i4cXj+WfYwYVjhKX5AcDj" + + "UKnc4/Cxp+TbbgZqEKRcYVb2q0kOAxkeaNo3WCm+qvUYrwAmKp4nVB+/24rK" + + "khHiyYJQsETxtOEyvJkVxAS01djY4amuJ4jL0sYnXIhW3Ag93eavbzksGT7W" + + "Fg1ywpr1x1xpXWIIuVt1k4e+g9fy7Yx7rx0IK1qCSjNwU3QPWbaef1rp0Q/X" + + "P9IVXYkqo1g/T3SyXqrbZLO+sDjiG4IT3z3fJJqt81sRSVT0QN1ND8l93BG4" + + "QKzghYw8sZ4FwKPtLky1dDcVTgQBBAQBCAQIK/85VMKWDWYEAQQEAQgECGsO" + + "Q85CcFwPBAEEBAEIBAhaup6ot9XnQAQBBAQCgaAEgaCeCMadSm5fkLfhErYQ" + + "DgePZl/rrjP9FQ3VJZ13XrjTSjTRknAbXi0DEu2tvAbmCf0sdoVNuZIZ92W0" + + "iyaa2/A3RHA2RLPNQz5meTi1RE2N361yR0q181dC3ztkkJ8PLyd74nCtgPUX" + + "0JlsvLRrdSjPBpBQ14GiM8VjqeIY7EVFy3vte6IbPzodxaviuSc70iXM4Yko" + + "fQq6oaSjNBFRqkHrBAEEBAEIBAjlIvOf8SnfugQBBAQBCAQIutCF3Jovvl0E" + + "AQQEAQgECO7jxbucdp/3BAEEBAEIBAidxK3XDLj+BwQBBAQBCAQI3m/HMbd3" + + "TwwEAQQEA4ICOASCAjgtoCiMfTkjpCRuMhF5gNLRBiNv+xjg6GvZftR12qiJ" + + "dLeCERI5bvXbh9GD6U+DjTUfhEab/37TbiI7VOFzsI/R137sYy9Tbnu7qkSx" + + "u0bTvyXSSmio6sMRiWIcakmDbv+TDWR/xgtj7+7C6p+1jfUGXn/RjB3vlyjL" + + "Q9lFe5F84qkZjnADo66p9gor2a48fgGm/nkABIUeyzFWCiTp9v6FEzuBfeuP" + + "T9qoKSnCitaXRCru5qekF6L5LJHLNXLtIMSrbO0bS3hZK58FZAUVMaqawesJ" + + "e/sVfQip9x/aFQ6U3KlSpJkmZK4TAqp9jIfxBC8CclbuwmoXPMomiCH57ykr" + + "vkFHOGcxRcCxax5HySCwSyPDr8I4+6Kocty61i/1Xr4xJjb+3oyFStIpB24x" + + "+ALb0Mz6mUa1ls76o+iQv0VM2YFwnx+TC8KC1+O4cNOE/gKeh0ircenVX83h" + + "GNez8C5Ltg81g6p9HqZPc2pkwsneX2sJ4jMsjDhewV7TyyS3x3Uy3vTpZPek" + + "VdjYeVIcgAz8VLJOpsIjyHMB57AyT7Yj87hVVy//VODnE1T88tRXZb+D+fCg" + + "lj2weQ/bZtFzDX0ReiEQP6+yklGah59omeklIy9wctGV1o9GNZnGBSLvQ5NI" + + "61e9zmQTJD2iDjihvQA/6+edKswCjGRX6rMjRWXT5Jv436l75DVoUj09tgR9" + + "ytXSathCjQUL9MNXzUMtr7mgEUPETjM/kYBR7CNrsc+gWTWHYaSWuqKVBAEE" + + "BAEIBAh6slfZ6iqkqwQBBAQBCAQI9McJKl5a+UwEAQQEATgEOBelrmiYMay3" + + "q0OW2x2a8QQodYqdUs1TCUU4JhfFGFRy+g3yU1cP/9ZSI8gcI4skdPc31cFG" + + "grP7BAEEBAEIBAhzv/wSV+RBJQQBBAQBCAQI837ImVqqlr4EAQQEAQgECGeU" + + "gjULLnylBAEEBAEIBAjD3P4hlSBCvQQBBAQBCAQISP/qivIzf50EAQQEAQgE" + + "CKIDMX9PKxICBAEEBAOCBOgEggTocP5VVT1vWvpAV6koZupKN1btJ3C01dR6" + + "16g1zJ5FK5xL1PTdA0r6iAwVtgYdxQYnU8tht3bkNXdPJC1BdsC9oTkBg9Nr" + + "dqlF5cCzXWIezcR3ObjGLpXu49SAHvChH4emT5rytv81MYxZ7bGmlQfp8BNa" + + "0cMZz05A56LXw//WWDEzZcbKSk4tCsfMXBdGk/ngs7aILZ4FGM620PBPtD92" + + "pz2Ui/tUZqtQ0WKdLzwga1E/rl02a/x78/OdlVRNeaIYWJWLmLavX98w0PhY" + + "ha3Tbj/fqq+H3ua6Vv2Ff4VeXazkXpp4tTiqUxhc6aAGiRYckwZaP7OPSbos" + + "RKFlRLVofSGu1IVSKO+7faxV4IrVaAAzqRwLGkpJZLV7NkzkU1BwgvsAZAI4" + + "WClPDF228ygbhLwrSN2NK0s+5bKhTCNAR/LCUf3k7uip3ZSe18IwEkUMWiaZ" + + "ayktcTYn2ZjmfIfV7wIxHgWPkP1DeB+RMS7VZe9zEgJKOA16L+9SNBwJSSs9" + + "5Sb1+nmhquZmnAltsXMgwOrR12JLIgdfyyqGcNq997U0/KuHybqBVDVu0Fyr" + + "6O+q5oRmQZq6rju7h+Hb/ZUqRxRoTTSPjGD4Cu9vUqkoNVgwYOT+88FIMYun" + + "g9eChhio2kwPYwU/9BNGGzh+hAvAKcUpO016mGLImYin+FpQxodJXfpNCFpG" + + "4v4HhIwKh71OOfL6ocM/518dYwuU4Ds2/JrDhYYFsn+KprLftjrnTBnSsfYS" + + "t68b+Xr16qv9r6sseEkXbsaNbrGiZAhfHEVBOxQ4lchHrMp4zpduxG4crmpc" + + "+Jy4SadvS0uaJvADgI03DpsDYffUdriECUqAfOg/Hr7HHyr6Q9XMo1GfIarz" + + "eUHBgi1Ny0nDTWkdb7I3bIajG+Unr3KfK6dZz5Lb3g5NeclU5zintB1045Jr" + + "j9fvGGk0/2lG0n17QViBiOzGs2poTlhn7YxmiskwlkRKVafxPZNPxKILpN9s" + + "YaWGz93qER/pGMJarGJxu8sFi3+yt6FZ4pVPkvKE8JZMEPBBrmH41batS3sw" + + "sfnJ5CicAkwd8bluQpoc6qQd81HdNpS6u7djaRSDwPtYnZWu/8Hhj4DXisje" + + "FJBAjQdn2nK4MV7WKVwr+mNcVgOdc5IuOZbRLOfc3Sff6kYVuQFfcCGgAFpd" + + "nbprF/FnYXR/rghWE7fT1gfzSMNv+z5UjZ5Rtg1S/IQfUM/P7t0UqQ01/w58" + + "bTlMGihTxHiJ4Qf3o5GUzNmAyryLvID+nOFqxpr5es6kqSN4GPRHsmUIpB9t" + + "f9Nw952vhsXI9uVkhQap3JvmdAKJaIyDz6Qi7JBZvhxpghVIDh73BQTaAFP9" + + "5GUcPbYOYJzKaU5MeYEsorGoanSqPDeKDeZxjxJD4xFsqJCoutyssqIxnXUN" + + "Y3Uojbz26IJOhqIBLaUn6QVFX79buWYjJ5ZkDS7D8kq6DZeqZclt5711AO5U" + + "uz/eDSrx3d4iVHR+kSeopxFKsrK+KCH3CbBUMIFGX/GE9WPhDWCtjjNKEe8W" + + "PinQtxvv8MlqGXtv3v7ObJ2BmfIfLD0rh3EB5WuRNKL7Ssxaq14KZGEBvc7G" + + "Fx7jXLOW6ZV3SH+C3deJGlKM2kVhDdIVjjODvQzD8qw8a/ZKqDO5hGGKUTGD" + + "Psdd7O/k/Wfn+XdE+YuKIhcEAQQEAQgECJJCZNJdIshRBAEEBAEIBAiGGrlG" + + "HlKwrAQBBAQBCAQIkdvKinJYjJcEAQQEAUAEQBGiIgN/s1bvPQr+p1aQNh/X" + + "UQFmay6Vm5HIvPhoNrX86gmMjr6/sg28/WCRtSfyuYjwQkK91n7MwFLOBaU3" + + "RrsEAQQEAQgECLRqESFR50+zBAEEBAEIBAguqbAEWMTiPwQBBAQBGAQYKzUv" + + "EetQEAe3cXEGlSsY4a/MNTbzu1WbBAEEBAEIBAiVpOv1dOWZ1AQCAAAEAgAA" + + "BAIAAAQCAAAEAgAABAIAAAAAAAAAADA1MCEwCQYFKw4DAhoFAAQUvMkeVqe6" + + "D4UmMHGEQwcb8O7ZwhgEEGiX9DeqtRwQnVi+iY/6Re8AAA=="); + + private String sha256Pass = "D317F8D5191F2602C527F8E6E0E8855C4517EC9512F7A06A7A588ACF0B3A6325"; + + private byte[] sha256Pfx = Base64.decode( + "MIIFvwIBAzCCBXEGCSqGSIb3DQEHAaCCBWIEggVeMIIFWjCCBVYGCSqGSIb3" + + "DQEHAaCCBUcEggVDMIIFPzCCBTsGCyqGSIb3DQEMCgECoIIFKjCCBSYwUAYJ" + + "KoZIhvcNAQUNMEMwIgYJKoZIhvcNAQUMMBUEEFEZik5RaSrwXtrWCnaLzAQC" + + "AQEwHQYJYIZIAWUDBAEqBBBTqY5oFOjZxnBBtWchzf0TBIIE0Pcvwtwthm8d" + + "yR16f5yqtofxGzJ0aAbCF7JJ+XsL9QhNuqndTtnXits+E2WgNwwm24XyRhPA" + + "obAwqz+DvH+gdUbKoN/gCEp+/6xhlwMQZyjyqi5ePznwLQ/bJueqmXZDT+pO" + + "zTIeMXMF0YaSjcZZ4FJnZtBX7XQDEAPmialrknhcSZI5RoLjOzFv51FgYd9+" + + "nWdtWlRINS9LrGCVL+y8wwHp55tWEoCR2/o9YWFMYNrUkVUUzImHCN1fkbIH" + + "XQxPp5fUqP00kwYY4288JZrzHGWGmSVYm54ok5YRLpCs0yhB0ve//iH/fNNO" + + "esShfBTUcRCc086skxgoCVWBZERyVJHWkKl/Q4RVzYt70k2/Qfq/xBNwVCrw" + + "YiOB0TwSQJKpvRbtufPx2vODfAmhIKes08ZLJHsMJ+O3p99O2rWZslNY7nfx" + + "1vWXYLVkHg0q79ThgbP4p0qQQziIVZoF9ViisJTJWzZbfJLdaKPeHcduvXsR" + + "lRvfEpR6/lifcxvkloxjpYtM6JEjtvT1x442VRKJWZofkjCohpLSmEDt77FM" + + "ENvra7B9ojlY+0DkwNV34FlSRrwi/nVl2XhebI11DfQFEUN+krNoZ3U4n5Sb" + + "g0Heibg5mILPwVS5Zh2vEybXzFY6b1XPA7TlGQATm6xBaU+BNFiACp+7+6CZ" + + "PxofFKKlWq0+Apx43JDATerwlPBKxLqxxgo0xTJUtL8OKnt6oSFX4P6O6AgX" + + "D9Pz3dzdWW9ga65N2qEmqpeIsd6SB4eGRJ1Vf1ePDgdVBUD9DG/eWfpn8l1T" + + "neg7wsQOGDrX00uDfio/WrjRBOw37IfToqJ/j6y/Ybggg5tldvCNoxq/42rC" + + "RvP0GJH+LJAHgB9sOWbksR7tKizWeFEyHwrAQfYc8aIZocApObtsZp8O5nuI" + + "MNcSCc77WZfVacrJzssKki1YHPoZeTYb9q4DRm0F6Rk+bqyvd7vs2DyLN7jT" + + "bkWoSoyCw8PAOuc8Q/+X3jhs18RQGzsEpeTOHoYJWeTUxgPrPqDFNKNLhD+L" + + "7mvDM7EvB08tVfLTSMeVBY+RUW6eFCbdlHfqszvp9pFZPNxQHtgbAYplwK6J" + + "i24gCH2UMF+BNzdcN2Fw9vP3nao+mzjtY1HuYebDDNNxgBAEoUFS4jr1YLoa" + + "+li3A9T/NqSf+J5OwASsSsp0YttAJQ+VU19amwJ141U+04kVc2bUIvSxEyxu" + + "UzWfFs26J1FhKzacirtpNv21iH78NHWOgS3jlEZMirpCHtHDbwF0z3V0upJ7" + + "cZzMwHJPQIGP4Nk8ei20dEogc/D2ijXHGRKdRjstzi89YXs4iLWjy2lEqhlK" + + "IvmlbF/snra1He2En/TFYv7m1zMuEPtS/+DTcwzqoe10Lko+2bNlOikW58u/" + + "OdAlteo1IissecMjL6743ttt8SAwx9gpAn6XHaIfFL1jiGKUQPJ5Mx9RUzfB" + + "lsKzHLNWmrDCZtR4BC4A21aRUueDGgRbtiOCYLbVtoiTc2XWM5juahaWCNKm" + + "4+ENQNOPrB4rJUeWJquNOj9+Brhe6pWWfi4EYVBuWlbTQB7u3uP9lnYvQHSo" + + "nOjkhjwEhPZneaKctEqXx2LoYc8arY1LSSpaXORcOJc/LkgVCq3bBEDNCJrZ" + + "DBOUpcPXDj43MEUwMTANBglghkgBZQMEAgEFAAQgdWQUVEirOjgax8qJhjqC" + + "bArDHuZQQvCmtrjqyhWbI4MEENBoJ4T1+xY5fmdiwmoXPPM="); + + private String pkcs5Pass = "hello"; + + private byte[] pkcs5Aes128Pfx = Base64.decode( + "MIIFsQIBAzCCBXcGCSqGSIb3DQEHAaCCBWgEggVkMIIFYDCCAxcGCSqGSIb3" + + "DQEHBqCCAwgwggMEAgEAMIIC/QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYw" + + "DgQIBumPBl/jV0kCAggAgIIC0Dd2zn5WPPxgqdZg0a4zB10ErQnNlRUd1EOw" + + "kodoXH7Vt3/zVgssPDmuUJo6OlneBaYXjjjrqaDbmuc+1JTpB3GPsCAdDvAd" + + "m3IQR9oJJOqX0RYFKw4rFQ2xmzkybHiXWvt24lKr1A7MSfSWc+xO3xupNzQt" + + "z8dLGx0VJejJe8KSM+ST6JTXaHWcijPo/pADjyTWp2xwZaEfBDUOLgCPTlHY" + + "95cfqB0FlwfT+jGqrQjVXex9hL1MmANFwZ0bqxx+9yfdcDY8K/87NYZ4LJdA" + + "L7qAJg5Ziduhe+NMugzOMQijUGHX9g21kMmU96CUbUNyc0JWXyDJqwh0aAvV" + + "QVbLW9F+qzWPCMlV/5u30WNZ0gdVulCdQ9wIO1vt3oa3wUUdO1LCaEGyqO+h" + + "x5iPGH3f5WTeJK2BoOKtUXhZtfp7GvYYFcI8BeoTo5poT/uqLdZmaPgBXc5O" + + "kyRQCpvQJipNcwD+R8FPbTExUxTWnbxbx3f7n0v8vMFPqb26BrFzCN+JTFRw" + + "bN0dRaysOGgzMeBjk0TGpHHj5/g5DUvIxVjN6wY7HO+849g64a+Z/wHWB1vp" + + "fALen3hGVdYIgWXGWn3bBMXT5peWc1omPXJdoltpiFRGku3JFCBJEQ6LzqZD" + + "ApVqVgE6WbfTQXgsEE9+J5zJJx/yTGvFjxXNNUMSdo2zQtHJVj0karXHVLxu" + + "phGb8Eg23obEOZj6Y6cZviWeiEeBjinGh4M1RD4HuYnczDF3FWZbi9aRku9r" + + "a1VgUbftiXeqmRpIWtZhfB40IELadTbEMTOi4pQ2cPcjZRAKAZwnijTfXEA5" + + "XwBQYdPvORlP6PJJv2Ai6Zc2XrevvOYLnSXSU+2ZpVuTTaX7xcQFi4APexyc" + + "Csfhpcpmb2K8jek3XN0jnOti9rU6Rlab9U5bPMLuOqoISsQ/x2ho3M0uYZIh" + + "9nGPixL1lxKgNDXfh0sZ7u7/AzCCAkEGCSqGSIb3DQEHAaCCAjIEggIuMIIC" + + "KjCCAiYGCyqGSIb3DQEMCgECoIIBszCCAa8wSQYJKoZIhvcNAQUNMDwwGwYJ" + + "KoZIhvcNAQUMMA4ECDD2zGfoVExtAgIIADAdBglghkgBZQMEAQIEEFER8VTx" + + "Owq7+dXKJn8zEMwEggFgpsQbBZJ1/NCAv5G05MsoujT6jNmhUI5RyHlKVqBD" + + "odvw/wS13qmWqUA3gL0/sJz/uf9/DJ7ur5XbkW56Y5qlqXBc8xvZ22Mabfy4" + + "hBzBuL+A6gfEQZNuZPiev0w02fEuVAtceDgsnJfMaawK06PUjxTUP3n/Bczc" + + "rhYYaGHwTtX+N6C3Q0Zn/W3zoIsoSruN6jc9x2DCAc3cdv5zaXxvZv6GhQou" + + "kcibQhRnTqQVRRWsF2zX3ZgPLJrQcB4NPGoEecHceD8jB6JnKqgGUpWybrjK" + + "7Mwwl2wB8Ffd2XpTTw2beiNSZXhCp+IxqgggwK3L1RGWhRoQE3esAVlCDhkz" + + "sk/ngnpqaauE9NVcrZEY0x6++/MOJssQZZ8X+Ci/zJuyH1dpUQii3kuw4F/O" + + "8nHiHClR0IA/xrVM+h0NC1/o2jCjeKXPf67j2Wp95o40apldtqlHyTm3TM2O" + + "uXrT5ExzcjFgMCMGCSqGSIb3DQEJFTEWBBSpuRoBZ82LWCyE2mXmT5Gmk1xv" + + "+DA5BgkqhkiG9w0BCRQxLB4qAHQAZQBzAHQAQABiAG8AdQBuAGMAeQBjAGEA" + + "cwB0AGwAZQAuAG8AcgBnMDEwITAJBgUrDgMCGgUABBQRvdgo1LVPm68qJcVT" + + "gw8dRrSS4gQISYYYgNAwxl0CAggA"); + + private byte[] pkcs5Aes192Pfx = Base64.decode( + "MIIFsQIBAzCCBXcGCSqGSIb3DQEHAaCCBWgEggVkMIIFYDCCAxcGCSqGSIb3" + + "DQEHBqCCAwgwggMEAgEAMIIC/QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYw" + + "DgQImAP7SD16WkACAggAgIIC0MCS81oGaIY1yHwP6faAhe3eseR6gGMlezbx" + + "r/7jmVQ8xe2jsZwqRVp/WCx716/9RHab17UFy+e3efbCrCGUJGUU5OrADf0l" + + "6/S7v/C5hR5XeE12zukSe/c5mkGhPuM+for0daQpLP6zDQMNLENyp+mPVBsI" + + "7IqFihwWUow7lvZEwaUOmsu+m978BOqhMRykZ7MbEjq4lMumZNvp37WqPRrh" + + "eQ4tz7q47C+k5NkTjMz2s/2a9SZViW+FZWOvV0DXJj/BCpAARR0bQDpjqlQ8" + + "HoSjoVgP+p5Y1pnLBvI/pFecS4ZwM1TyAdFZbjFpkNe8DREO/Py+89kOJpZa" + + "aZoFKjxY5m7Z9ftJx615vih5d8D4t685tBJNAEiah9RFppNA41GpJc1winx1" + + "CuqQQqStOmmMD/uk1BEgaQ4R4lR88Bms69shK8Nk2U4egVYKdbrruulKY5M0" + + "dj5j2JChqYjE5dPxPyd1s0qYW9ABMeDT8l7gtiDTOfS4qZjVPWRW2vGbj80g" + + "HnBnd6SAC2DdWkY1QuDRVRABQO5NJPPqGhL2LclX1dE1FS0puXpl/oyxbAMU" + + "pCt+pnZZLPrMSZgZ6I3VWt+Dbg6jHtM4a+y3gsswL+uzdb4AnHqCcuFbnZDh" + + "2hz6IFsyw4LgUeIBJNBAqgag3VeJLL7bpKm58XSd/6hC369HXn91F1NAkBOO" + + "IZFZQPVgEufdryZck1/u0+zmyelAWG7Jq4SQF07C4v/dpgVH8U1OwR34+D0f" + + "0fPA3qdBLGL5cKNBxnKCx5+Gu/+dDR33aY176qaDZu7OmZkCJ3qkhOif7/Qi" + + "0s4NpG6ATLGD6TzSnmje3GwJze5KwOvMgAewWGScdqOE9KOh7iPC1kIDgwhE" + + "eBM+yciGGfinStyeSik6fLRi2JPnVNIALIh74DIfK3QJVVRNi9vuQ0j0Dm8C" + + "JSD/heWsebKIFrQSoeEAZCYPhzCCAkEGCSqGSIb3DQEHAaCCAjIEggIuMIIC" + + "KjCCAiYGCyqGSIb3DQEMCgECoIIBszCCAa8wSQYJKoZIhvcNAQUNMDwwGwYJ" + + "KoZIhvcNAQUMMA4ECBGQFSR+KZ2AAgIIADAdBglghkgBZQMEARYEEABRcxC7" + + "xWHsYaX2UsUZ5JoEggFgyrYAZowHdclsxaAeoY/Ch1F+NBb64bXdDOp56OWh" + + "HHu79vhLsjAOmbTYoMsmRZw8REen7ztBUv9h/f7WbfKs84FDI6LbM9EIaeun" + + "jrqaUdmSADQhakd7hJQhWAw4h/Df5KNhwsVJ1+i9RCtMzY1nFk1Pjg6yL/5E" + + "rWVvNRkconjrDbUwLPA+TfDlhOMapttER4k8kOY0WMc7iWHmowkh1JHUNbvC" + + "gEQvGwysXiFqoEcy/UbY7Wgke3h7HwoColAYorHhkV4/NBENmQbsiUdkxD/Z" + + "6KrgOuAvvluGUY79M6SusH11PfVBwyJX7Wt1HmllrykrsmJuF6UuN1BavUrR" + + "rr0Utm9T28iiqO6ky74V4XesmFdr7oObT2kLcGiFbWzXyVrWL3GM9N03CWXx" + + "b1M5hXACRlwKVp79qxeyw5k+ccixnjCumsSX8MMttKYwRJ1ML2YL0v8XdE0i" + + "LSkXsEoG5zFgMCMGCSqGSIb3DQEJFTEWBBSpuRoBZ82LWCyE2mXmT5Gmk1xv" + + "+DA5BgkqhkiG9w0BCRQxLB4qAHQAZQBzAHQAQABiAG8AdQBuAGMAeQBjAGEA" + + "cwB0AGwAZQAuAG8AcgBnMDEwITAJBgUrDgMCGgUABBQz1gLRjMDYVLIPGdsd" + + "4EPgRMGPtQQItR+KgKM/oRMCAggA"); + + private byte[] pkcs5Camellia128Pfx = Base64.decode( + "MIIFswIBAzCCBXkGCSqGSIb3DQEHAaCCBWoEggVmMIIFYjCCAxcGCSqGSIb3" + + "DQEHBqCCAwgwggMEAgEAMIIC/QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYw" + + "DgQIq+wFOOOtSokCAggAgIIC0IWDRpk4L/tSSMfwWx0mN3ecbaL+m2XZWvN9" + + "hK1K5PghAYquCs36l603cYSV9pypOkGC5rn1d2fyZCFhUMOObSC7V/mpkitr" + + "OfOYpaW7tU1JJecpONgIHlbd8N4fbBtH73E7vdmi6X/tg4Tl7yJf40fruYVq" + + "yzqfJCO2aGJIFv6JWsFivjCwehBa+6ppCHBnNcj4SsVlozj1y2B0Wl2TVi3r" + + "joBIsK2RQ+RMjM55k3pS57mV+jXtd29wb2q9utDKogvpBCboTk8dPMFcFGWz" + + "2D41onJoEJKizAEIgXiS7UvqHddhIL9O/rSZ68j2d2GcFi1Oxer1PyZoCI61" + + "CpZdk2QeNeVaVFTPJ26We6J34w2ivZwHOhn+iUZ7q0Sm9gcYa1QRG79LA/AC" + + "nE3Xxzl4nEjRRi5AKb6IOnMKBbr0povesS8tL323x91uPZc0jMctC6Q+vegX" + + "tIZ7dZPuNxhqRHqb62LSm11cpYQWibj16rRQ0ulOFSQGIr514PvfbIig6oo8" + + "niwHuefp/ey/Zvl/dAl+um2UkVdR9Mwn8vTM8oMF+ptJfpWyZEIrP785Rpu3" + + "oyBMyEYA2djX7JsFvoCxKxGCC5VK3C/9EFv9xUGmiV0zrTPcHb1P4sK1AJyI" + + "vhSY+Tgv+Fjq5KoPCa4ZXP+Y+vSzkttcP8u7x0wt9cblvgzdBy9Ee1xqCdJd" + + "F67U6vbQ6ErDrdVAwtRqc0TsPKG1XH5NFtxTwILyCeh8XzdYMIaHkEnTuITQ" + + "eeICaUJ2YPZrADLxXTNHI9e6dVcDvhjf/JfBXZfiiqFH8XmbCIMqyGSGTmQr" + + "8uwb8cquLMS78RbXSHLNcv+f/DmPOClNjmWgVAYxaDuw5lZBaU+YDyZaKEy2" + + "Mdjd+lR/g2LZhvAEfcM3V4bzr17s0GOSwJ5/5yzczPKZZ8auMwML+Bcmoggt" + + "EJgubVFHg/3l11xVe2djfg78CTCCAkMGCSqGSIb3DQEHAaCCAjQEggIwMIIC" + + "LDCCAigGCyqGSIb3DQEMCgECoIIBtTCCAbEwSwYJKoZIhvcNAQUNMD4wGwYJ" + + "KoZIhvcNAQUMMA4ECInc03N3q5vSAgIIADAfBgsqgwiMmks9AQEBAgQQR+Uo" + + "WVvmSL5AcwwRq6vtOQSCAWD0Ms1i2wHGaFi6qUWLqA5EnmYFwqwQQlfz5To+" + + "FwVEpHQHrqd0pehOt1J9vyDVYwfjU8DUOJDovCiBIzRsopyf0Qp5hcZnaTDw" + + "YJSNd3pIAYiEUAzfdtC7tQw2v0aLt5X/7zthEcoRtTe061dK8DhbV4fALWa9" + + "VF2E91L35+wq52DblvpJHBw28PHTbuhfJZsNshXKO7qU7uk+UR6V/Pwc7rsp" + + "x/TQ35fVfm7v53rapdHlMVyY4Bx/4fdEWV9aK1cV3qOfiBMByxt8WD0xBLoc" + + "Yy3qo3+k/N7q6t4hqjus3LPVrmCbpgAe5S5EkDgnjy7Mpz19tf7hhzL957p2" + + "ecWregvR9rQHoWZNOaxS2e2hdOiZUPSxIJ46nOJyCnoZQHG0CFVEwwJkGcWf" + + "Thjz38U203IRzuCPgsO1f8wjSXXMp4xJQtJW2TqMm+5/aaDtuXAsUGqQzGiH" + + "DQfUs4z/PCKyMWAwIwYJKoZIhvcNAQkVMRYEFKm5GgFnzYtYLITaZeZPkaaT" + + "XG/4MDkGCSqGSIb3DQEJFDEsHioAdABlAHMAdABAAGIAbwB1AG4AYwB5AGMA" + + "YQBzAHQAbABlAC4AbwByAGcwMTAhMAkGBSsOAwIaBQAEFHIzAiyzoVOmPvLE" + + "XCD2HHG5MC23BAhhHlFnklHZYgICCAA="); + + private byte[] pkcs5Camellia256Pfx = Base64.decode( + "MIIFswIBAzCCBXkGCSqGSIb3DQEHAaCCBWoEggVmMIIFYjCCAxcGCSqGSIb3" + + "DQEHBqCCAwgwggMEAgEAMIIC/QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYw" + + "DgQIq+wFOOOtSokCAggAgIIC0IWDRpk4L/tSSMfwWx0mN3ecbaL+m2XZWvN9" + + "hK1K5PghAYquCs36l603cYSV9pypOkGC5rn1d2fyZCFhUMOObSC7V/mpkitr" + + "OfOYpaW7tU1JJecpONgIHlbd8N4fbBtH73E7vdmi6X/tg4Tl7yJf40fruYVq" + + "yzqfJCO2aGJIFv6JWsFivjCwehBa+6ppCHBnNcj4SsVlozj1y2B0Wl2TVi3r" + + "joBIsK2RQ+RMjM55k3pS57mV+jXtd29wb2q9utDKogvpBCboTk8dPMFcFGWz" + + "2D41onJoEJKizAEIgXiS7UvqHddhIL9O/rSZ68j2d2GcFi1Oxer1PyZoCI61" + + "CpZdk2QeNeVaVFTPJ26We6J34w2ivZwHOhn+iUZ7q0Sm9gcYa1QRG79LA/AC" + + "nE3Xxzl4nEjRRi5AKb6IOnMKBbr0povesS8tL323x91uPZc0jMctC6Q+vegX" + + "tIZ7dZPuNxhqRHqb62LSm11cpYQWibj16rRQ0ulOFSQGIr514PvfbIig6oo8" + + "niwHuefp/ey/Zvl/dAl+um2UkVdR9Mwn8vTM8oMF+ptJfpWyZEIrP785Rpu3" + + "oyBMyEYA2djX7JsFvoCxKxGCC5VK3C/9EFv9xUGmiV0zrTPcHb1P4sK1AJyI" + + "vhSY+Tgv+Fjq5KoPCa4ZXP+Y+vSzkttcP8u7x0wt9cblvgzdBy9Ee1xqCdJd" + + "F67U6vbQ6ErDrdVAwtRqc0TsPKG1XH5NFtxTwILyCeh8XzdYMIaHkEnTuITQ" + + "eeICaUJ2YPZrADLxXTNHI9e6dVcDvhjf/JfBXZfiiqFH8XmbCIMqyGSGTmQr" + + "8uwb8cquLMS78RbXSHLNcv+f/DmPOClNjmWgVAYxaDuw5lZBaU+YDyZaKEy2" + + "Mdjd+lR/g2LZhvAEfcM3V4bzr17s0GOSwJ5/5yzczPKZZ8auMwML+Bcmoggt" + + "EJgubVFHg/3l11xVe2djfg78CTCCAkMGCSqGSIb3DQEHAaCCAjQEggIwMIIC" + + "LDCCAigGCyqGSIb3DQEMCgECoIIBtTCCAbEwSwYJKoZIhvcNAQUNMD4wGwYJ" + + "KoZIhvcNAQUMMA4ECInc03N3q5vSAgIIADAfBgsqgwiMmks9AQEBAgQQR+Uo" + + "WVvmSL5AcwwRq6vtOQSCAWD0Ms1i2wHGaFi6qUWLqA5EnmYFwqwQQlfz5To+" + + "FwVEpHQHrqd0pehOt1J9vyDVYwfjU8DUOJDovCiBIzRsopyf0Qp5hcZnaTDw" + + "YJSNd3pIAYiEUAzfdtC7tQw2v0aLt5X/7zthEcoRtTe061dK8DhbV4fALWa9" + + "VF2E91L35+wq52DblvpJHBw28PHTbuhfJZsNshXKO7qU7uk+UR6V/Pwc7rsp" + + "x/TQ35fVfm7v53rapdHlMVyY4Bx/4fdEWV9aK1cV3qOfiBMByxt8WD0xBLoc" + + "Yy3qo3+k/N7q6t4hqjus3LPVrmCbpgAe5S5EkDgnjy7Mpz19tf7hhzL957p2" + + "ecWregvR9rQHoWZNOaxS2e2hdOiZUPSxIJ46nOJyCnoZQHG0CFVEwwJkGcWf" + + "Thjz38U203IRzuCPgsO1f8wjSXXMp4xJQtJW2TqMm+5/aaDtuXAsUGqQzGiH" + + "DQfUs4z/PCKyMWAwIwYJKoZIhvcNAQkVMRYEFKm5GgFnzYtYLITaZeZPkaaT" + + "XG/4MDkGCSqGSIb3DQEJFDEsHioAdABlAHMAdABAAGIAbwB1AG4AYwB5AGMA" + + "YQBzAHQAbABlAC4AbwByAGcwMTAhMAkGBSsOAwIaBQAEFHIzAiyzoVOmPvLE" + + "XCD2HHG5MC23BAhhHlFnklHZYgICCAA="); + + private byte[] pkcs5Cast5Pfx = Base64.decode( + "MIIFqQIBAzCCBW8GCSqGSIb3DQEHAaCCBWAEggVcMIIFWDCCAxcGCSqGSIb3" + + "DQEHBqCCAwgwggMEAgEAMIIC/QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYw" + + "DgQIkiiANhrORysCAggAgIIC0GDKlVmlIcRXqb1XoCIhnHcKRm1Sa/bCJc7j" + + "ylp5Y8l2/ugimFeeM1yjZRke+KxTPXL0TO859j45NGUArL6hZipx8v6RzvH7" + + "WqyJx5wuDwufItgoJT2DE4UFGZEi/pP/RWALxNEZysVB5zod56vw3dZu/+rR" + + "gPIO7mOnWgqC2P1Pw4YLXOk4qNxaCCwIIp9aJlAdvCRfLBqPr8QjJFMGw5NQ" + + "gcHLG3QRW846wUtOxZj2+/Qy9GNAvo+PV6qIR/IS/A+QUwQ3+7SRojUWMUhV" + + "6N/L/+l2UyU551pA5oX8anPbKCU5bRa/MRIpfPvm+XJpEpbwhS164X7wBFIR" + + "RSdoj83wEWcR0WFTCXijCRdJcniO+h13kiaR3ltBD0dETjM7xu1XvkbAb3EV" + + "71PeRQC8kY6DPsJCI9DWDBCnJpVzO4q2atzYej4IAZNgF9PBAwA5isAzurVz" + + "xxxS4SF930CnrFLb/CxF/IBuz6RBh0lreRMfCP5g5sZUp686kShMSeAKNb7s" + + "xU2YshusTTShhK+2tK8Lf7z9O/P59P0yZOiFDStrDRUPo7IAfUD29+1EdWVQ" + + "3LGBtN/t/YOedKGVxd+YXZ4YKFRoNBR9GHsL31wrOm14mmWNib6nbd5+6Zcj" + + "j3xXLLXG7MT40KlmsmKDYCVeGhc7AfGU3b/HceX5u30RUWbgaC0ATiM/vJKX" + + "djvCpEiB5pPy2YtpSNAc0bV9GsHorL85WjJDWnMlm3yoy+Bfiu/doNzMEytL" + + "ycXq4LtaRl6EV8G4ak59lNJ7HdsABcsSa2fxEa595hbWYeYB1xgt0mHl+btx" + + "E5hrfyZmjN74YDbkPSIWsAFktcCHF2eGrwK/2NTewKHdsE6FSzc1pAYDgnxT" + + "aNnhxw/Nfb1XmwH0C3soolJuoTRKyMJxvMDVuCSB2WyoyEjq+BNQzUTkYYR6" + + "Hijzd9ljvX84XUlicSucbTHHVDCCAjkGCSqGSIb3DQEHAaCCAioEggImMIIC" + + "IjCCAh4GCyqGSIb3DQEMCgECoIIBqzCCAacwQQYJKoZIhvcNAQUNMDQwGwYJ" + + "KoZIhvcNAQUMMA4ECCDJh37hrS+SAgIIADAVBgkqhkiG9n0HQgoECOXn7rhs" + + "5ectBIIBYLiRI2Yb955K6WAeTBXOnb58hJxgsir3zsGCoIRWlGNhr5Ur0ebX" + + "AnXyD5ER8HTaArSO2EtZlVI8Ff6OIcYg5sKliYJEgbI7TPKcaImD92Um4Qim" + + "/8h4xkM3K4VQmT0H8zFM3Mm/86mnON+2UjVcFBrCxek9m06gMlkIrxbiSh8X" + + "YAYfHGTKTTX4HtvkZsQTKkcxSVzavyfVZFw1QtRXShvvJDY6TUGplyycWvu/" + + "+braWfuH1u2AGh30g1+SOx7vnJM78a0rZIwd3TP9rKczzqexDF/GwuGuZF+1" + + "bMe8xxC1ZdMZ1Mnh27TNoGMuU5VVsqhs5NP0XehuuV8rHdzDDxdx/2buiA4+" + + "8SrzW5LQAs6Z+U3pna3UsuH24tIPMm3OfDH7WSBU6+nvXub7d5XxA31OYHEk" + + "nAsuo6p6iuosnedTObA9bX+mTU4nR3oaa87ZDIPxbQVTHKberFlYhDzmmwAx" + + "YDAjBgkqhkiG9w0BCRUxFgQUqbkaAWfNi1gshNpl5k+RppNcb/gwOQYJKoZI" + + "hvcNAQkUMSweKgB0AGUAcwB0AEAAYgBvAHUAbgBjAHkAYwBhAHMAdABsAGUA" + + "LgBvAHIAZzAxMCEwCQYFKw4DAhoFAAQUc8hyg5aq/58lH3whwo66zJkWY28E" + + "CKHZUIQsQX9hAgIIAA=="); + + private byte[] pkcs5TripleDesPfx = Base64.decode( + "MIACAQMwgAYJKoZIhvcNAQcBoIAEggvtMIIL6TCCAi4GCSqGSIb3DQEHAaCCAh8EggIbMIICFzCCAhMGCyqGSIb3DQEMCgECoIIBtjCCAbIwTAYJKoZIhvcNAQUNMD8wJwYJKoZIhvcNAQUMMBoEFBUELlgR1kddObFK69drbrg+019yAgIEADAUBggqhkiG9w0DBwQIz2EcPBbGnIYEggFgtgCSaH8l0ab1y708ziQ6joMPh0+1Byh32lIx4NSPPrRTfdtuViyaneW9nrurvPgFgwVPD46aDdqJpdnvoijNTsrJJEII7HZNGY1EaSulG0fIKl/brwOhKbvFaivBn1ya7UlQJ0dMoWBtuso/bxQbtxCI0TCVR8u4X0v8LbY0wt60NfFAenjbLwKBBIM6XPFfxUiI/6SqZ1mvizQItX8PRdRQac6TXjzZMjpG0lOEf9X5sC5mhadXPEjnHl1Avz7Z8rh4eHfjgJ9tRQjQrZPsBJfkUSyChZT5SX6ygaFS8qyRXN2p1H3PybOs2WyTe8wnR6cNiwTQeNhCIHkrq53t+3ohCpbrUBDR6dk8j7N7JB99QFGw6MUxb4gPxVPUsKdnWEBk6SJHqILxiyA0OQ1DzG/WDMf3NJnIhTltgdSOXf5b0N2YF0nkVyJ/+M1ly8ZdPjNSeC51UpbJ71+oe3ZGSDFKMCMGCSqGSIb3DQEJFDEWHhQARQByAGkAYwAnAHMAIABLAGUAeTAjBgkqhkiG9w0BCRUxFgQU0GzsbTWDvFUSGwzLPv7XJqYWZGgwggmzBgkqhkiG9w0BBwagggmkMIIJoAIBADCCCZkGCSqGSIb3DQEHATAoBgoqhkiG9w0BDAEFMBoEFIA4figx3imGUQhb2JYHfaHeZyiIAgIEAICCCWACyck70bFrveGYPZKFEjlqO5avWuitzpA/cv+L4IX5W3LOKQPSpuwy62rKnIUkT8wj//yiP7vHab15KYUqoHPz1IKxy/5zOGNzUGCkBDlxRpcDwvqxtEZwQ1XNaaFPLT0uu+KgEJ1vIU7rSOgav6Sa6lOOPKoZrTJLZtrHZzzCUZxFaiHwRb4BkfEJ1UltFEMqlqyexwGLso2wqYElneGMq1aVSEnEaIhwpatulQRzls3IYpZYftotPPjxp/+i506+06GrWZQoAcNhuSS6SKVwtGntV6T9PgfIoehmGkhJzq2R/xBMBk62T5nph+CVrmrBafSGRVoWkDdC/3zhdivxX0oSX/J7NM2cW2Ub9+eMSMaT7NUTWbDD2MvPemLewzgfA0ON7GAajorarZiu/KvBRGHqLKFZGERsBmDWOnrJKt8FPNzpqfGwTxH5pTPeT/2XeleqigujInvuh0xpkRG+5JOp2lnXbq9BqpozoJr92QzWx4aCagBCS1BJUWl8FUAhSwMgYdGreD6q6QU16hJ/VHDyM8iCu2BpLDSyvDs//0pI8wNMq8pan6qUYDxfpgtg5qHzLfnl2if0opnqvJQTKMPeGKYuqiCscf0Bnhap3Gs1vFo9P9tx5RMDtopKfzvbyi03TQ8XNcVxi1l0jho5dHMZEFvI24RU+hUJJWXng/EtkgGfEPXdDfjFFu/Fn1E2G8Ni1QQrkGnPDpKcasl225RjmNz6L7LdF2MnZ/MqRq+Unvy46tKkIhRVTh2tlSEcQKulytHWpJJ2ZUKSDsMRILHsa/HOlCQAYIv4mzH9TqEmelbFP89XYQsC7ukw6wd2fnDyrT4c8p3Qwh35DJuvoKpVEre4ETbVNHSOY9R0GsiPReDZidTsHDOZIeIIxICSTZ9PC0CInn2qunLiZSHw4L+0F51ALLqg196rTHnbo8JrsfLDHLkcZk/Xg7QMxLTT1wPlSIFnDBKqjzRBNmGJ1+tNErcek9n8G2DkLIkO1s8Y0Wyn9g6v62EkNgH+LVcXe2sWahBOUMr++hvoN2w0NjEZ8ZS9ndJHWurV7Z2cI1RvHYw85iLVXeJIl3+tdZKB1hXfGoLWaOzDBLp0nHTEAeHpLjJxNTHIsBV2OHFlOYGwRTPY6aPvPAEMnXHw+ZFKggphQzNWBTEI4bLZCKFoFtR1iBMlg4dyN2Tx+21rY4msySsMdFZK/a0N8QBRs9ZYMmK8hnPNEY+lFzyJM6Obz9Lp2JwQW5aQ/FW1B+ol7ZabVRQUcmWvqUNM0YaMQmTsHq9jBnzTckq6fKZXGGZfo2IZ4tIVGNXaf3rXk6eJuml281b80SUbIXmGjqXiWvSjuUk8omdzUU0sU8nY9EfQFxA4+AfUiWF4UbYWASOAnsaVuciLgQy0bATiPL1XNFdJsrJGpdSyZ0ElMKgegHHxO2Tv17A/a35Aa6kdt8HGTcuR49UD3CLt54QYY+QKdWZolos5dYL1pg+KiNripXjlrBjWrEiOhB2HRtxfR+5R3XYvcJ/tlJfh3CmhSoIP/R4NDqhv9RXR60rTnoc4VRvGxjRasU4XvWFgpHGB6FrGf9RcPOOf4QWQOIebSZdTh0K+gy8Lo7/P/WyME9ja4/O3BaeHv9U3o3KppyF2C3SDic/sbiSxUY7njUvIZ6huP5h+EymqAZwthBXYo/hQOsrGADc8f+aufykFdy/K+cRPuzPcjwwo5fyYFUrWkihRfk4sg42Fo90pzGka8quBrM5bvaZ7Nnh7ulGIxnlGQclprldi0iGx1w2qOuV5YJGkmcPz2ibHaosBlvq3uV1msHNNTWkHvbeLGCBcYnmdTQ7xTAWsG37/5XwO7rhGyrIFMCPpKEYDyJl+iq4iSmyPvWpReH3aIfJ95+sd86KrGQfnkYJgGw/8JL1brQSlD7cez0GAty2EksG8GCDC5nj/p1wc6mYG6LUNMAKGlZOq3xQ0reZ1f1J5FVjWye9Szn3arAiZBjFMiZcftcSwwH5XNcqsdlVGfAeczrT4A6PyXqYTwDd67aIIYiPB/f8ECG+u374sIGzsjJBzRLL/5pQCj7GcE5AySH+TAV2wRD5UdN7Vf3zxqE+/wW8yl3/i7zFJsMZJAuAKWlNYAk2J9A6LfX2qFOiCMQpoTkCszG2zL5rph0u99bHtQYt6pplc4YcVJmeY8FyiBLhO3FQBbKURSupet2jhitky3hWlG1OS3YBMnuzRcL1YJZi7N/fMLowQYe5w9NODaDbHMHOc6x9/62F2pr1NoiDqRLhj29hOyxFCOXDpS1IaWHaHHs8h4/BdUimDr1cF7oqLawwmS3Y1aH+grE+48OwywvbJ/OxLhjDVA0fQPeqiMxuHcQDsSZYgZENdbKzfUeUTdOtY/FW7t7c6QTEpRI4at40m/hoT4B/oy98Us+ASnxfz0+Bdindt7vdnOJFe8TbvmRCCvAepCaa5WGG4fmPm6O0PNesAiZjysttoXlb/3cQM7mCnAEF2GmbGSnvkvwlVR6oUM5gR/LdspayNRYshLQC+nc1mIjp7wm3NbMb30OlGTCHYuq4+F0rSOIBx0ByLlq0WCcR9Eo0NW41irh8FM5Eiv0S2WdOsaQoEEn2YYPIGAcrBn2HURxfgV3cX7SQEg6GdMh269c7qmDLCggCMb9M2V8yuef9PQngUbHp0ZmMGHd6YahKXrT2vmtUpxNd+PJjYNXHs/riCPxcGnxfKg+qU7Lr+mp37DXD+O64AKWecc31Ij+hdYiO+cW233nvcpGiLDZWngLTxI4RWS84xqFSOqUH09lu0d5Y7GGM6tfOzQWTo5B0wEcXMqd2LWy0ajy1je+6q9Leshc5M1sck3+skcxejiV4kQSrtPCtns8ReKi4NZ7GPzS5RK+wMxf64VzmLIWBGeTpltPeSQJVbnN6Rs62idqm+SYYiCxFwwg/bhUXR7PJhftd13jy6FdtJN7NXcVd/m7dLp12yrm73wpGCVXJ0EHNlOp7rAf++BGWKb8UfXGv7v6WX0rzlt0Pq1NU/mBJ0Bwu7PYyhbxZTUIbqxP8Z4vZmj4tAqJiFJo6PFUpCLGR5l/mabZ3xLOk/dIp23Ulk4OlzbUy2bv69cBf7JZTij/y7D8enhzcLmgJYzqP/dmzt4ddXeTTFh0Q3F/siTakCqwHlhgf9xUobq4UbeVYS4DNg4p+TpVtGaeNzZfJghkWr12UAAAAAMD0wITAJBgUrDgMCGgUABBSWOQXmLtuxsApEZah7LamMw962GgQUGHv9dKsB8Rivt0MPrLszcABHJ+4CAgQAAAA="); + private byte[] gostPfx = Base64.decode( + "MIIHEgIBAzCCBssGCSqGSIb3DQEHAaCCBrwEgga4MIIGtDCCBYEGCSqGSIb3" + + "DQEHBqCCBXIwggVuAgEAMIIFZwYJKoZIhvcNAQcBMFUGCSqGSIb3DQEFDTBI" + + "MCcGCSqGSIb3DQEFDDAaBAi114+lRrpkXAICCAAwCgYGKoUDAgIKBQAwHQYG" + + "KoUDAgIVMBMECLEIQPMsz/ZZBgcqhQMCAh8BgIIFAbu13yJiW/BnSKYKbtv9" + + "tDJoTv6l9BVpCCI4tvpzJnMeLBJyVZU4JevcJNii+R1LilVuuB+xc8e7/P4G" + + "6TILWmnnispr9KPRAbYRfoCJOa59+TYJMur58wwDuYgMapQAFzsvpzyUWi62" + + "o3uQbbLKO9hQCeJW2L+K9cbg8k33MjXMLpnblKpqmZbHTmBJDFR3xGw7IEjD" + + "UNqruu7DlHY6jctiVJSii9UNEVetSo9AAzfROxRjROg38VsWxLyO9wEMBv/8" + + "H8ur+zOtmQPGqirNXmN+pa08OvZin9kh7CgswW03xIbfsdGGGLRAWtvCnEwJ" + + "mS2tEfH1SZcuVLpMomhq3FU/jsc12k+vq/jw4I2cmfDL41ieK72bwNj8xUXu" + + "JHeoFSPGX4z+nsJUrFbFG4VBuDs2Y0SCWLyYZvdjvJwYjfqtyi/RoFSZjGHF" + + "crstf9YNQ0vW0efCJ7pUBH44OrbnCx5ng2U5jFm1b3HBIKA2RX+Tlhv14MgT" + + "KSftPZ67eSmgdsyPuQAdMu6fEdBMpVKMNZNRV565690sqi+1jOmH94TUX8XU" + + "2pRQj6eGGLq6lgGnnDabcePUEPXW8zW2KYrDKYJ/1QZmVGldvlqnjZMNhIO+" + + "Afsqax/P8RBjMduGqdilGdRzbN8PdhVaN0Ys+WzFxiS9gtaA2yPzcQuedWDN" + + "T7sIrfIapgFYmmHRQ7ht4AKj+lmOyNadONYw+ww+8RzHB1d2Kk+iXeZCtvH0" + + "XFWJZtuoGKSt/gkI0E2vpDfMbLaczaRC7ityO0iJs25ozP4JhZRBVvOmpxc9" + + "YuIetbTnTf1TLJKXDgt1IwPZeugbofSeiNv117lx8VgtvMYFD4W+WQlB8HnO" + + "C8NOYjkMPElc6PCMB9gGm0cIu1fKLvY8ycLav93JJjdDuC0kgKLb2+8mC5+2" + + "DdMkcfgW6hy4c98xnJs8enCww3A4xkRbMU13zMq70liqmKHV2SSurg5hwUHM" + + "ZthT8p988ZBrnqW24lXfMBqTK4YtIBMeMnvKocYBXr96ig3GfahI1Aj2Bw2e" + + "bpZTVeayYUd+2xX8JJMdqna6Q61AL8/eUhJUETz5+fgQJtPjcKmdJfVHO6nB" + + "vOk1t/rjK17eiXLxHCyvfP+Tw8lSFOhcvr4eIeG8WfsWNRu2eKKosOU7uash" + + "QpnvQieqDeijuRxf+tbbJ5D86inwbJqdxra7wNuZXmiaB9gFDzNbNjhtL+6i" + + "gUyX/iQHKi9bNK+PH6pdH/gkwnG/juhdgqoNY6GRty/LUOPgXD+r5e/ST16R" + + "vnlwrlKp5FzRWBEkem+dhelj3rb+cxKEyvPe3TvIUFcmIlV1VCRQ1fBHtX18" + + "eC3a3GprH8c40z3S/kdyk7GlFQ27DRLka+iDN05b+MP5jlgvfqYBKxwLfeNu" + + "MpxWoCUvYWiQdMih86/l0H+0o5UB8SqRbpuvr6fY910JCk0hDaO1pgB3HlRz" + + "k1vb46pg25heXQm3JmO+ghxjOGliYBWjl8p7AfRS9cjS8ca+X02Mv9Viv7Ce" + + "3+Gz0MVwfK98viJ3CFxkaEBlM2LM0IeUQbkHG+YwYaTSfl4GYyrug4F0ZdrA" + + "KeY9/kIxa/OJxjcIMs2H+2mSpxmrb7ylmHZ2RB8ITiduRVtO091hn/J7N+eT" + + "h6BvLBKIFU+UFUdgjxoDNDk7ao++Mu9T3dQfceFBOYzW9vMQgX30yaPLSdan" + + "ZMAP0VtiNjCCASsGCSqGSIb3DQEHAaCCARwEggEYMIIBFDCCARAGCyqGSIb3" + + "DQEMCgECoIGyMIGvMFUGCSqGSIb3DQEFDTBIMCcGCSqGSIb3DQEFDDAaBAiQ" + + "Owewo16xzQICCAAwCgYGKoUDAgIKBQAwHQYGKoUDAgIVMBMECHSCNJJcQ2VI" + + "BgcqhQMCAh8BBFYCyRRpFtZgnsxeK7ZHT+aOyoVmzhtnLrqoBHgV4nJJW2/e" + + "UcJjc2Rlbzfd+3L/GWcRGF8Bgn+MjiaAqE64Rzaao9t2hc3myw1WrCfPnoEx" + + "VI7OPBM5FzFMMCMGCSqGSIb3DQEJFTEWBBTV7LvI27QWRmHD45X2WKXYs3ct" + + "AzAlBgkqhkiG9w0BCRQxGB4WAGMAcABfAGUAeABwAG8AcgB0AGUAZDA+MC4w" + + "CgYGKoUDAgIJBQAEIJbGZorQsNM63+xozwEI561cTFVCbyHAEEpkvF3eijT8" + + "BAgY5sDtkrVeBQICCAA="); + + private byte[] gostPfxFoo123 = Base64.decode( + "MIID6gIBAzCCA6MGCSqGSIb3DQEHAaCCA5QEggOQMIIDjDCCApQGCSqGSIb3" + + "DQEHBqCCAoUwggKBAgEAMIICegYJKoZIhvcNAQcBMFUGCSqGSIb3DQEFDTBI" + + "MCcGCSqGSIb3DQEFDDAaBAhIVrbUVNoQ2wICCAAwCgYGKoUDAgIKBQAwHQYG" + + "KoUDAgIVMBMECBLmAh+XCCYhBgcqhQMCAh8BgIICFP9hQLgDq5SORy2npOdo" + + "1bvoGl9Qdga1kV9s2c1/Y1kTGpuiYKfm5Il+PurzYdE5t/Wi2+SxoePm/AKA" + + "x1Ep5btK/002wnyRbUKdjgF1r7fMXRrd5Ioy8lYxB1v6qhHmzE5fz7FxY+iV" + + "Z70dSRS0JkTasI8MRsFLkJJfDb9twgoch8lYGFfYirHLcVy4xxA3JO9VSHm2" + + "8nuSWSnsmGN0ufPX14UpV2RFe3Rt0gZ0Jc8u2h2Mo0sIoVU6HVwdXzoe6LN7" + + "1NPZdRuhVtjxEvjDAvNJ8WHXQnBQMai2nVAj87uNr6OHLRs+foEccEY9WpPQ" + + "GPt4XbPt4MtmVctT2+Gsvf6Ws2UCx6hD4k8i28a6xS8lhTVam2g/2Z5cxtUV" + + "HxYt7j13HjuQVsuSNdgtrUnw3l43LnBxRZhlFz0r2zrvTB04ynenS+lGdVuG" + + "0TauIH+rdP1ubujw6lFdG9RNgUxWvS5IdwbFGX73a+ZrWiYJeERX11N/6r3g" + + "0EqVFNH9t/ROsdAtCCe2FycQoOSb+VxPU6I+SHjwe7Oa7R8Xxazh/eWTsV59" + + "QzPuLriUMbyYdQIf4xdclgcJoxFElopgl4orRfzH3XQsVbtTxN33lwjkE0j/" + + "686VtcO+b+dU7+BEB7O5yDcx1tupgre0ha/0KOlYfPvmbogGdDf0r6MOwrS7" + + "QFXxKlHfp8vn4mNwoy7pjrzjmjclkbkwgfEGCSqGSIb3DQEHAaCB4wSB4DCB" + + "3TCB2gYLKoZIhvcNAQwKAQKggaMwgaAwVQYJKoZIhvcNAQUNMEgwJwYJKoZI" + + "hvcNAQUMMBoECLD6Ld7TqurqAgIIADAKBgYqhQMCAgoFADAdBgYqhQMCAhUw" + + "EwQIoYXV7LETOEAGByqFAwICHwEERyBQK9LuYnOO0ELrge+a6JFeAVwPL85V" + + "ip2Kj/GfD3nzZR4tPzCwAt79RriKQklNqa3uCc9o0C9Zk5Qcj36SqiXxD1tz" + + "Ea63MSUwIwYJKoZIhvcNAQkVMRYEFKjg5gKM+i+vFhSwaga8YGaZ5thVMD4w" + + "LjAKBgYqhQMCAgkFAAQgIwD0CRCwva2Bjdlv5g970H2bCB1aafBNr/hxJLZE" + + "Ey4ECAW3VYXJzJpYAgIIAA=="); + + private byte[] desWithSha1 = Base64.decode( + "MIIBgTAbBgkqhkiG9w0BBQowDgQId6NZWs1Be5wCAgQABIIBYLineU3" + + "SS0NCA6Olpt9VciMD4gUHsaqqKZ7tZK83ig66ic4U/CwFEcc6sozkkk" + + "3tGp1PJ9XOofcRZhrAegUshROPtexMYlsarIlYvL+1dUzY2BZXVV34Z" + + "SBdko8+QI0G84neTh7lL0x/MoE+MV2LHNxjMSj1oDIp5DJ43LQ6oTxa" + + "IjMEH8UZSK9Lr/oWtBO4Gfm2OBIDfVLfdVGTX5D7a/dXgzunraVkHMm" + + "zHUqPoqw0HZewSYTCdU0qf0H695K81S1OcMEpV53oyCxw/chzIinzDC" + + "L+OjxUmFEKh7exfUKPeV4J6R5Wa1Ec0Xff+TWQ9yiwGnByGkd8eWCyf" + + "WsduibO7akY1/XiPziEUPTvs8guTdBm3l625AJOaHMn5PtDMuMSj2dM" + + "KpDnyOgNj5xADOJyetmZMcoC6dzNWs1zBZAQAmJ2soC114k03xhLaID" + + "NfNqx9WueoGaZ3qXbSUawlR8="); + + private byte[] desWithMD5 = Base64.decode( + "MIIBgTAbBgkqhkiG9w0BBQMwDgQIdKRvcJb9DdgCAgQABIIBYEZ0Bpqy" + + "l/LNlzo/EhcPnGcgwvLdkh3mTwFxb5wOhDS+/cz82XrtFNosyvGUPo7V" + + "CyJjg0C05prNOOug4n5EEIcr0B/6p7ZKw9JLEq/gkfTUhVXS7tFsIzjD" + + "giVGc9T59fcqr4NWFtFAHxKb24ZESYL4BponDxWql465+s4oFLjEWob1" + + "AOA268q5PpWP1Og2BS0mBPuh6x/QOXzyfxaNRcJewT0uh0fCgCS05A+2" + + "wI7mJgQk1kEWdHPBMv/LAHiXgULa1gS+aLto8fISoHObY0H/KTTJ7rhY" + + "Epkjjw1khc0wrMBlpbcVJvqvxeMeelp26vPjqRL+08gUhHdzsJ3SokCD" + + "j5Z0Mmh1haduOXAALcdO5st6ZBqkA8o886bTqBYYRIFGzZIhJzOhe8iD" + + "GhHLM2yiA0RxlCtlnNMXruHKEvFYgzI3lVQov4jU5MIL1XjH0zPGyu9t" + + "/q8tpS4nbkRgGj8="); + + // Valid PKCS #12 File with SHA-256 HMAC and PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a1 = Base64.decode( + "MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhvRzw4sC4xcwICCAACASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQITk9UIFVTRUQCAQE=\n"); + + // Valid PKCS #12 File with SHA-256 HMAC and SHA-512 PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a2 = Base64.decode("MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAi4j6UBBY2iOgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEFpHSS5zrk/9pkDo1JRbtE6AggPgtbMLGoFd5KLpVXMdcxLrT129L7/vCr0B\n" + + "0I2tnhPPA7aFtRjjuGbwooCMQwxw9qzuCX1eH4xK2LUw6Gbd2H47WimSOWJMaiUb\n" + + "wy4alIWELYufe74kXPmKPCyH92lN1hqu8s0EGhIl7nBhWbFzow1+qpIc9/lpujJo\n" + + "wodSY+pNBD8oBeoU1m6DgOjgc62apL7m0nwavDUqEt7HAqtTBxKxu/3lpb1q8nbl\n" + + "XLTqROax5feXErf+GQAqs24hUJIPg3O1eCMDVzH0h5pgZyRN9ZSIP0HC1i+d1lnb\n" + + "JwHyrAhZv8GMdAVKaXHETbq8zTpxT3UE/LmH1gyZGOG2B21D2dvNDKa712sHOS/t\n" + + "3XkFngHDLx+a9pVftt6p7Nh6jqI581tb7fyc7HBV9VUc/+xGgPgHZouaZw+I3PUz\n" + + "fjHboyLQer22ndBz+l1/S2GhhZ4xLXg4l0ozkgn7DX92S/UlbmcZam1apjGwkGY/\n" + + "7ktA8BarNW211mJF+Z+hci+BeDiM7eyEguLCYRdH+/UBiUuYjG1hi5Ki3+42pRZD\n" + + "FZkTHGOrcG6qE2KJDsENj+RkGiylG98v7flm4iWFVAB78AlAogT38Bod40evR7Ok\n" + + "c48sOIW05eCH/GLSO0MHKcttYUQNMqIDiG1TLzP1czFghhG97AxiTzYkKLx2cYfs\n" + + "pgg5PE9drq1fNzBZMUmC2bSwRhGRb5PDu6meD8uqvjxoIIZQAEV53xmD63umlUH1\n" + + "jhVXfcWSmhU/+vV/IWStZgQbwhF7DmH2q6S8itCkz7J7Byp5xcDiUOZ5Gpf9RJnk\n" + + "DTZoOYM5iA8kte6KCwA+jnmCgstI5EbRbnsNcjNvAT3q/X776VdmnehW0VeL+6k4\n" + + "z+GvQkr+D2sxPpldIb5hrb+1rcp9nOQgtpBnbXaT16Lc1HdTNe5kx4ScujXOWwfd\n" + + "Iy6bR6H0QFq2SLKAAC0qw4E8h1j3WPxll9e0FXNtoRKdsRuX3jzyqDBrQ6oGskkL\n" + + "wnyMtVjSX+3c9xbFc4vyJPFMPwb3Ng3syjUDrOpU5RxaMEAWt4josadWKEeyIC2F\n" + + "wrS1dzFn/5wv1g7E7xWq+nLq4zdppsyYOljzNUbhOEtJ2lhme3NJ45fxnxXmrPku\n" + + "gBda1lLf29inVuzuTjwtLjQwGk+usHJm9R/K0hTaSNRgepXnjY0cIgS+0gEY1/BW\n" + + "k3+Y4GE2JXds2cQToe5rCSYH3QG0QTyUAGvwX6hAlhrRRgUG3vxtYSixQ3UUuwzs\n" + + "eQW2SUFLl1611lJ7cQwFSPyr0sL0p81vdxWiigwjkfPtgljZ2QpmzR5rX2xiqItH\n" + + "Dy4E+iVigIYwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhDiwsh\n" + + "4wt3aAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEELNFnEpJT65wsXwd\n" + + "fZ1g56cEggTQRo04bP/fWfPPZrTEczq1qO1HHV86j76Sgxau2WQ9OQAG998HFtNq\n" + + "NxO8R66en6QFhqpWCI73tSJD+oA29qOsT+Xt2bR2z5+K7D4QoiXuLa3gXv62VkjB\n" + + "0DLCHAS7Mu+hkp5OKCpXCS7fo0OnAiQjM4EluAsiwwLrHu7z1E16UwpmlgKQnaC1\n" + + "S44fV9znS9TxofRTnuCq1lupdn2qQjSydOU6inQeKLBflKRiLrJHOobaFmjWwp1U\n" + + "OQAMuZrALhHyIbOFXMPYk3mmU/1UPuRGcbcV5v2Ut2UME+WYExXSCOYR3/R4UfVk\n" + + "IfEzeRPFs2slJMIDS2fmMyFkEEElBckhKO9IzhQV3koeKUBdM066ufyax/uIyXPm\n" + + "MiB9fAqbQQ4jkQTT80bKkBAP1Bvyg2L8BssstR5iCoZgWnfA9Uz4RI5GbRqbCz7H\n" + + "iSkuOIowEqOox3IWbXty5VdWBXNjZBHpbE0CyMLSH/4QdGVw8R0DiCAC0mmaMaZq\n" + + "32yrBR32E472N+2KaicvX31MwB/LkZN46c34TGanL5LJZx0DR6ITjdNgP8TlSSrp\n" + + "7y2mqi7VbKp/C/28Cj5r+m++Gk6EOUpLHsZ2d2hthrr7xqoPzUAEkkyYWedHJaoQ\n" + + "TkoIisZb0MGlXb9thjQ8Ee429ekfjv7CQfSDS6KTE/+mhuJ33mPz1ZcIacHjdHhE\n" + + "6rbrKhjSrLbgmrGa8i7ezd89T4EONu0wkG9KW0wM2cn5Gb12PF6rxjTfzypG7a50\n" + + "yc1IJ2Wrm0B7gGuYpVoCeIohr7IlxPYdeQGRO/SlzTd0xYaJVm9FzJaMNK0ZqnZo\n" + + "QMEPaeq8PC3kMjpa8eAiHXk9K3DWdOWYviGVCPVYIZK6Cpwe+EwfXs+2hZgZlYzc\n" + + "vpUWg60md1PD4UsyLQagaj37ubR6K4C4mzlhFx5NovV/C/KD+LgekMbjCtwEQeWy\n" + + "agev2l9KUEz73/BT4TgQFM5K2qZpVamwmsOmldPpekGPiUCu5YxYg/y4jUKvAqj1\n" + + "S9t4wUAScCJx8OvXUfgpmS2+mhFPBiFps0M4O3nWG91Q6mKMqbNHPUcFDn9P7cUh\n" + + "s1xu3NRLyJ+QIfVfba3YBTV8A6WBYEmL9lxf1uL1WS2Bx6+Crh0keyNUPo9cRjpx\n" + + "1oj/xkInoc2HQODEkvuK9DD7VrLr7sDhfmJvr1mUfJMQ5/THk7Z+E+NAuMdMtkM2\n" + + "yKXxghZAbBrQkU3mIW150i7PsjlUw0o0/LJvQwJIsh6yeJDHY8mby9mIdeP3LQAF\n" + + "clYKzNwmgwbdtmVAXmQxLuhmEpXfstIzkBrNJzChzb2onNSfa+r5L6XEHNHl7wCw\n" + + "TuuV/JWldNuYXLfVfuv3msfSjSWkv6aRtRWIvmOv0Qba2o05LlwFMd1PzKM5uN4D\n" + + "DYtsS9A6yQOXEsvUkWcLOJnCs8SkJRdXhJTxdmzeBqM1JttKwLbgGMbpjbxlg3ns\n" + + "N+Z+sEFox+2ZWOglgnBHj0mCZOiAC8wqUu+sxsLT4WndaPWKVqoRQChvDaZaNOaN\n" + + "qHciF9HPUcfZow+fH8TnSHneiQcDe6XcMhSaQ2MtpY8/jrgNKguZt22yH9gw/VpT\n" + + "3/QOB7FBgKFIEbvUaf3nVjFIlryIheg+LeiBd2isoMNNXaBwcg2YXukxJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAgUr2yP+/DBrgICCAACASAwDAYIKoZIhvcNAgsF\n" + + "ADAMBggqhkiG9w0CCQUABCA5zFL93jw8ItGlcbHKhqkNwbgpp6layuOuxSju4/Vd\n" + + "6QQITk9UIFVTRUQCAQE="); + + // Valid PKCS #12 File with SHA-512 HMAC and PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a3 = Base64.decode("MIIKrAIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAisrqL8obSBaQICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEECjXYYca0pwsgn1Imb9WqFGAggPgT7RcF5YzEJANZU9G3tSdpCHnyWatTlhm\n" + + "iCEcBGgwI5gz0+GoX+JCojgYY4g+KxeqznyCu+6GeD00T4Em7SWme9nzAfBFzng0\n" + + "3lYCSnahSEKfgHerbzAtq9kgXkclPVk0Liy92/buf0Mqotjjs/5o78AqP86Pwbj8\n" + + "xYNuXOU1ivO0JiW2c2HefKYvUvMYlOh99LCoZPLHPkaaZ4scAwDjFeTICU8oowVk\n" + + "LKvslrg1pHbfmXHMFJ4yqub37hRtj2CoJNy4+UA2hBYlBi9WnuAJIsjv0qS3kpLe\n" + + "4+J2DGe31GNG8pD01XD0l69OlailK1ykh4ap2u0KeD2z357+trCFbpWMMXQcSUCO\n" + + "OcVjxYqgv/l1++9huOHoPSt224x4wZfJ7cO2zbAAx/K2CPhdvi4CBaDHADsRq/c8\n" + + "SAi+LX5SCocGT51zL5KQD6pnr2ExaVum+U8a3nMPPMv9R2MfFUksYNGgFvS+lcZf\n" + + "R3qk/G9iXtSgray0mwRA8pWzoXl43vc9HJuuCU+ryOc/h36NChhQ9ltivUNaiUc2\n" + + "b9AAQSrZD8Z7KtxjbH3noS+gjDtimDB0Uh199zaCwQ95y463zdYsNCESm1OT979o\n" + + "Y+81BWFMFM/Hog5s7Ynhoi2E9+ZlyLK2UeKwvWjGzvcdPvxHR+5l/h6PyWROlpaZ\n" + + "zmzZBm+NKmbXtMD2AEa5+Q32ZqJQhijXZyIji3NS65y81j/a1ZrvU0lOVKA+MSPN\n" + + "KU27/eKZuF1LEL6qaazTUmpznLLdaVQy5aZ1qz5dyCziKcuHIclhh+RCblHU6XdE\n" + + "6pUTZSRQQiGUIkPUTnU9SFlZc7VwvxgeynLyXPCSzOKNWYGajy1LxDvv28uhMgNd\n" + + "WF51bNkl1QYl0fNunGO7YFt4wk+g7CQ/Yu2w4P7S3ZLMw0g4eYclcvyIMt4vxXfp\n" + + "VTKIPyzMqLr+0dp1eCPm8fIdaBZUhMUC/OVqLwgnPNY9cXCrn2R1cGKo5LtvtjbH\n" + + "2skz/D5DIOErfZSBJ8LE3De4j8MAjOeC8ia8LaM4PNfW/noQP1LBsZtTDTqEy01N\n" + + "Z5uliIocyQzlyWChErJv/Wxh+zBpbk1iXc2Owmh2GKjx0VSe7XbiqdoKkONUNUIE\n" + + "siseASiU/oXdJYUnBYVEUDJ1HPz7qnKiFhSgxNJZnoPfzbbx1hEzV+wxQqNnWIqQ\n" + + "U0s7Jt22wDBzPBHGao2tnGRLuBZWVePJGbsxThGKwrf3vYsNJTxme5KJiaxcPMwE\n" + + "r+ln2AqVOzzXHXgIxv/dvK0Qa7pH3AvGzcFjQChTRipgqiRrLor0//8580h+Ly2l\n" + + "IFo7bCuztmcwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAi1c7S5\n" + + "IEG77wICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEN6rzRtIdYxqOnY+\n" + + "aDS3AFYEggTQNdwUoZDXCryOFBUI/z71vfoyAxlnwJLRHNXQUlI7w0KkH22aNnSm\n" + + "xiaXHoCP1HgcmsYORS7p/ITi/9atCHqnGR4zHmePNhoMpNHFehdjlUUWgt004vUJ\n" + + "5ZwTdXweM+K4We6CfWA/tyvsyGNAsuunel+8243Zsv0mGLKpjA+ZyALt51s0knmX\n" + + "OD2DW49FckImUVnNC5LmvEIAmVC/ZNycryZQI+2EBkJKe+BC3834GexJnSwtUBg3\n" + + "Xg33ZV7X66kw8tK1Ws5zND5GQAJyIu47mnjZkIWQBY+XbWowrBZ8uXIQuxMZC0p8\n" + + "u62oIAtZaVQoVTR1LyR/7PISFW6ApwtbTn6uQxsb16qF8lEM0S1+x0AfJY6Zm11t\n" + + "yCqbb2tYZF+X34MoUkR/IYC/KCq/KJdpnd8Yqgfrwjg8dR2WGIxbp2GBHq6BK/DI\n" + + "ehOLMcLcsOuP0DEXppfcelMOGNIs+4h4KsjWiHVDMPsqLdozBdm6FLGcno3lY5FO\n" + + "+avVrlElAOB+9evgaBbD2lSrEMoOjAoD090tgXXwYBEnWnIpdk+56cf5IpshrLBA\n" + + "/+H13LBLes+X1o5dd0Mu+3abp5RtAv7zLPRRtXkDYJPzgNcTvJ2Wxw2C+zrAclzZ\n" + + "7IRdcLESUa4CsN01aEvQgOtkCNVjSCtkJGP0FstsWM4hP7lfSB7P2tDL+ugy6GvB\n" + + "X1sz9fMC7QMAFL98nDm/yqcnejG1BcQXZho8n0svSfbcVByGlPZGMuI9t25+0B2M\n" + + "TAx0f6zoD8+fFmhcVgS6MQPybGKFawckYl0zulsePqs+G4voIW17owGKsRiv06Jm\n" + + "ZSwd3KoGmjM49ADzuG9yrQ5PSa0nhVk1tybNape4HNYHrAmmN0ILlN+E0Bs/Edz4\n" + + "ntYZuoc/Z35tCgm79dV4/Vl6HUZ1JrLsLrEWCByVytwVFyf3/MwTWdf+Ac+XzBuC\n" + + "yEMqPlvnPWswdnaid35pxios79fPl1Hr0/Q6+DoA5GyYq8SFdP7EYLrGMGa5GJ+x\n" + + "5nS7z6U4UmZ2sXuKYHnuhB0zi6Y04a+fhT71x02eTeC7aPlEB319UqysujJVJnso\n" + + "bkcwOu/Jj0Is9YeFd693dB44xeZuYyvlwoD19lqcim0TSa2Tw7D1W/yu47dKrVP2\n" + + "VKxRqomuAQOpoZiuSfq1/7ysrV8U4hIlIU2vnrSVJ8EtPQKsoBW5l70dQGwXyxBk\n" + + "BUTHqfJ4LG/kPGRMOtUzgqFw2DjJtbym1q1MZgp2ycMon4vp7DeQLGs2XfEANB+Y\n" + + "nRwtjpevqAnIuK6K3Y02LY4FXTNQpC37Xb04bmdIQAcE0MaoP4/hY87aS82PQ68g\n" + + "3bI79uKo4we2g+WaEJlEzQ7147ZzV2wbDq89W69x1MWTfaDwlEtd4UaacYchAv7B\n" + + "TVaaVFiRAUywWaHGePpZG2WV1feH/zd+temxWR9qMFgBZySg1jipBPVciwl0LqlW\n" + + "s/raIBYmLmAaMMgM3759UkNVznDoFHrY4z2EADXp0RHHVzJS1x+yYvp/9I+AcW55\n" + + "oN0UP/3uQ6eyz/ix22sovQwhMJ8rmgR6CfyRPKmXu1RPK3puNv7mbFTfTXpYN2vX\n" + + "vhEZReXY8hJF/9o4G3UrJ1F0MgUHMCG86cw1z0bhPSaXVoufOnx/fRoxJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwgZ0wgY0wSQYJKoZIhvcN\n" + + "AQUOMDwwLAYJKoZIhvcNAQUMMB8ECFDaXOUaOcUPAgIIAAIBQDAMBggqhkiG9w0C\n" + + "CwUAMAwGCCqGSIb3DQILBQAEQHIAM8C9OAsHUCj9CmOJioqf7YwD4O/b3UiZ3Wqo\n" + + "F6OmQIRDc68SdkZJ6024l4nWlnhTE7a4lb2Tru4k3NOTa1oECE5PVCBVU0VEAgEB"); + + // Invalid PKCS #12 File with Incorrect Iteration Count + private static final byte[] pkcs12WithPBMac1PBKdf2_a4 = Base64.decode("MIIKiwIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfTBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhvRzw4sC4xcwICCAECASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQITk9UIFVTRUQCAggA"); + + // Invalid PKCS #12 File with Incorrect Salt + private static final byte[] pkcs12WithPBMac1PBKdf2_a5 = Base64.decode("MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhOT1QgVVNFRAICCAACASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQIb0c8OLAuMXMCAQE="); + + // Invalid PKCS #12 File with Missing Key Length + private static final byte[] pkcs12WithPBMac1PBKdf2_a6 = Base64.decode("MIIKiAIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwejBqMEYGCSqGSIb3DQEF\n" + + "DjA5MCkGCSqGSIb3DQEFDDAcBAhvRzw4sC4xcwICCAAwDAYIKoZIhvcNAgkFADAM\n" + + "BggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG3QQI\n" + + "b0c8OLAuMXMCAggA"); + + /* + * we generate the CA's certificate + */ + public static X509Certificate createMasterCert( + PublicKey pubKey, + PrivateKey privKey) + throws Exception + { + // + // signers name + // + String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate"; + + // + // subjects name - the same as we are self signed. + // + String subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate"; + + // + // create the certificate - version 1 + // + X509v1CertificateBuilder v1CertBuilder = new JcaX509v1CertificateBuilder( + new X500Name(issuer), + BigInteger.valueOf(1), + new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), + new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), + new X500Name(subject), + pubKey); + + X509CertificateHolder cert = v1CertBuilder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(privKey)); + + return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); + } + + /* + * we generate an intermediate certificate signed by our CA + */ + public static X509Certificate createIntermediateCert( + PublicKey pubKey, + PrivateKey caPrivKey, + X509Certificate caCert) + throws Exception + { + // + // subject name builder. + // + X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE); + + subjectBuilder.addRDN(BCStyle.C, "AU"); + subjectBuilder.addRDN(BCStyle.O, "The Legion of the Bouncy Castle"); + subjectBuilder.addRDN(BCStyle.OU, "Bouncy Intermediate Certificate"); + subjectBuilder.addRDN(BCStyle.EmailAddress, "feedback-crypto@bouncycastle.org"); + + // + // create the certificate - version 3 + // + X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder( + JcaX500NameUtil.getIssuer(caCert), + BigInteger.valueOf(2), + new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), + new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), + subjectBuilder.build(), + pubKey); + + + // + // extensions + // + JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); + + v3CertBuilder.addExtension( + Extension.subjectKeyIdentifier, + false, + utils.createSubjectKeyIdentifier(pubKey)); + + v3CertBuilder.addExtension( + Extension.authorityKeyIdentifier, + false, + utils.createAuthorityKeyIdentifier(caCert)); + + v3CertBuilder.addExtension( + Extension.basicConstraints, + true, + new BasicConstraints(0)); + + X509CertificateHolder cert = v3CertBuilder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(caPrivKey)); + + return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); + } + + /* + * we generate a certificate signed by our CA's intermediate certificate + */ + public static X509Certificate createCert( + PublicKey pubKey, + PrivateKey caPrivKey, + PublicKey caPubKey) + throws Exception + { + // + // signer name builder. + // + X500NameBuilder issuerBuilder = new X500NameBuilder(BCStyle.INSTANCE); + + issuerBuilder.addRDN(BCStyle.C, "AU"); + issuerBuilder.addRDN(BCStyle.O, "The Legion of the Bouncy Castle"); + issuerBuilder.addRDN(BCStyle.OU, "Bouncy Intermediate Certificate"); + issuerBuilder.addRDN(BCStyle.EmailAddress, "feedback-crypto@bouncycastle.org"); + + // + // subject name builder + // + X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE); + + subjectBuilder.addRDN(BCStyle.C, "AU"); + subjectBuilder.addRDN(BCStyle.O, "The Legion of the Bouncy Castle"); + subjectBuilder.addRDN(BCStyle.L, "Melbourne"); + subjectBuilder.addRDN(BCStyle.CN, "Eric H. Echidna"); + subjectBuilder.addRDN(BCStyle.EmailAddress, "feedback-crypto@bouncycastle.org"); + + // + // create the certificate - version 3 + // + X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder( + issuerBuilder.build(), + BigInteger.valueOf(3), + new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), + new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), + subjectBuilder.build(), + pubKey); + + + // + // add the extensions + // + JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); + + v3CertBuilder.addExtension( + Extension.subjectKeyIdentifier, + false, + utils.createSubjectKeyIdentifier(pubKey)); + + v3CertBuilder.addExtension( + Extension.authorityKeyIdentifier, + false, + utils.createAuthorityKeyIdentifier(caPubKey)); + + X509CertificateHolder cert = v3CertBuilder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(caPrivKey)); + + return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert); + } + + public void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + public void testPfxPdu() + throws Exception + { + // + // set up the keys + // + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + PublicKey pubKey = fact.generatePublic(pubKeySpec); + + X509Certificate[] chain = createCertChain(fact, pubKey); + + PKCS12PfxPdu pfx = createPfx(privKey, pubKey, chain); + + // + // now try reading our object + // + KeyStore store = KeyStore.getInstance("PKCS12", "BC"); + + store.load(new ByteArrayInputStream(pfx.toASN1Structure().getEncoded()), passwd); + + PrivateKey recPrivKey = (PrivateKey)store.getKey("Eric's Key", passwd); + + if (!privKey.equals(recPrivKey)) + { + fail("private key extraction failed"); + } + + Certificate[] certChain = store.getCertificateChain("Eric's Key"); + + for (int i = 0; i != certChain.length; i++) + { + if (!certChain[i].equals(chain[i])) + { + fail("certificate recovery failed"); + } + } + } + + public void testPfxPduMac() + throws Exception + { + // + // set up the keys + // + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + PublicKey pubKey = fact.generatePublic(pubKeySpec); + + X509Certificate[] chain = createCertChain(fact, pubKey); + + PKCS12PfxPdu pfx = createPfx(privKey, pubKey, chain); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), passwd)); + assertFalse(pfx.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), "not right".toCharArray())); + } + + public void testPfxPduPBMac1PBKdf2() + throws Exception + { + char[] password = "1234".toCharArray(); + // valid test vectors + byte test_vectors[][] = new byte[][]{pkcs12WithPBMac1PBKdf2_a1, pkcs12WithPBMac1PBKdf2_a2, pkcs12WithPBMac1PBKdf2_a3}; + for (int i = 0; i != test_vectors.length; i++) + { + byte[] test_vector = test_vectors[i]; + PKCS12PfxPdu pfx = new PKCS12PfxPdu(test_vector); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), password)); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), "not right".toCharArray())); + } + + // invalid test vectors + test_vectors = new byte[][]{pkcs12WithPBMac1PBKdf2_a4, pkcs12WithPBMac1PBKdf2_a5}; + for (int i = 0; i != test_vectors.length; i++) + { + byte[] test_vector = test_vectors[i]; + PKCS12PfxPdu pfx = new PKCS12PfxPdu(test_vector); + + assertTrue(pfx.hasMac()); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), password)); + assertFalse(pfx.isMacValid(new BcPKCS12PBMac1CalculatorBuilderProvider(), "not right".toCharArray())); + } + + // invalid test vector that throws exception + PKCS12PfxPdu pfx = new PKCS12PfxPdu(pkcs12WithPBMac1PBKdf2_a6); + assertTrue(pfx.hasMac()); + } + + public void testBcEncryptedPrivateKeyInfo() + throws Exception + { + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + + PKCS8EncryptedPrivateKeyInfoBuilder builder = new JcaPKCS8EncryptedPrivateKeyInfoBuilder(privKey); + + PKCS8EncryptedPrivateKeyInfo priv = builder.build(new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd)); + + PrivateKeyInfo info = priv.decryptPrivateKeyInfo(new BcPKCS12PBEInputDecryptorProviderBuilder().build(passwd)); + + assertTrue(Arrays.areEqual(info.getEncoded(), privKey.getEncoded())); + } + + public void testEncryptedPrivateKeyInfo() + throws Exception + { + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + + PKCS8EncryptedPrivateKeyInfoBuilder builder = new JcaPKCS8EncryptedPrivateKeyInfoBuilder(privKey); + + PKCS8EncryptedPrivateKeyInfo priv = builder.build(new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC).build(passwd)); + + PrivateKeyInfo info = priv.decryptPrivateKeyInfo(new JcePKCSPBEInputDecryptorProviderBuilder().build(passwd)); + + assertTrue(Arrays.areEqual(info.getEncoded(), privKey.getEncoded())); + } + + public void testEncryptedPrivateKeyInfoPKCS5() + throws Exception + { + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + + PKCS8EncryptedPrivateKeyInfoBuilder builder = new JcaPKCS8EncryptedPrivateKeyInfoBuilder(privKey); + + PKCS8EncryptedPrivateKeyInfo priv = builder.build(new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC).setProvider("BC").build(passwd)); + + PrivateKeyInfo info = priv.decryptPrivateKeyInfo(new JcePKCSPBEInputDecryptorProviderBuilder().setProvider("BC").build(passwd)); + + assertTrue(Arrays.areEqual(info.getEncoded(), privKey.getEncoded())); + } + + public void testEncryptedPrivateKeyInfoDESWithSHA1() + throws Exception + { + checkEncryptedPrivateKeyInfo("PKCS#5 Scheme 1".toCharArray(), desWithSha1); + } + + public void testEncryptedPrivateKeyInfoDESWithMD5() + throws Exception + { + checkEncryptedPrivateKeyInfo("PKCS#5 Scheme 1".toCharArray(), desWithMD5); + } + + private void checkEncryptedPrivateKeyInfo(char[] password, byte[] encodedEncPKInfo) + throws Exception + { + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + EncryptedPrivateKeyInfo encPKInfo = new EncryptedPrivateKeyInfo(encodedEncPKInfo); + AlgorithmParameters algParams = encPKInfo.getAlgParameters(); + + if (algParams == null) + { + return; // this PBE type is not supported on the JVM + } + + Cipher cipher = Cipher.getInstance(encPKInfo.getAlgName(), "BC"); + + PBEKeySpec pbeKeySpec = new PBEKeySpec(password); + + SecretKeyFactory skFac = SecretKeyFactory.getInstance(encPKInfo.getAlgName(), "BC"); + + Key pbeKey = skFac.generateSecret(pbeKeySpec); + + + cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams); + + KeySpec pkcs8KeySpec = encPKInfo.getKeySpec(cipher); + + RSAPrivateCrtKey rsaPriv = (RSAPrivateCrtKey)fact.generatePrivate(pkcs8KeySpec); + + assertEquals(privKey, rsaPriv); + } + + public void testKeyBag() + throws Exception + { + OutputEncryptor encOut = new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd); + InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder().build(passwd); + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey); + + keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); + + PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder(); + + builder.addEncryptedData(encOut, keyBagBuilder.build()); + + PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(), passwd); + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), passwd)); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.keyBag, bags[0].getType()); + + assertTrue(Arrays.areEqual(privKey.getEncoded(), ((PrivateKeyInfo)bags[0].getBagValue()).getEncoded())); + + Attribute[] attributes = bags[0].getAttributes(); + + assertEquals(1, attributes.length); + + assertEquals(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, attributes[0].getAttrType()); + + ASN1Encodable[] attrValues = attributes[0].getAttributeValues(); + + assertEquals(1, attrValues.length); + assertEquals(new DERBMPString("Eric's Key"), attrValues[0]); + } + else + { + fail("unknown bag encountered"); + } + } + } + + public void testSafeBagRecovery() + throws Exception + { + InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder().build(passwd); + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + PublicKey pubKey = fact.generatePublic(pubKeySpec); + + X509Certificate[] chain = createCertChain(fact, pubKey); + + PKCS12PfxPdu pfx = createPfx(privKey, pubKey, chain); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(3, bags.length); + assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + + for (int j = 0; j != bags.length; j++) + { + assertTrue(Arrays.areEqual(chain[j].getEncoded(), ((X509CertificateHolder)bags[j].getBagValue()).getEncoded())); + } + } + else + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + + assertTrue(Arrays.areEqual(info.getEncoded(), privKey.getEncoded())); + } + } + } + + public void testExceptions() + throws Exception + { + PKCS12SafeBagFactory dataFact; + + try + { + dataFact = new PKCS12SafeBagFactory(new ContentInfo(PKCSObjectIdentifiers.data, new DERSequence()), null); + } + catch (IllegalArgumentException e) + { + + } + + try + { + dataFact = new PKCS12SafeBagFactory(new ContentInfo(PKCSObjectIdentifiers.encryptedData, new DERSequence())); + } + catch (IllegalArgumentException e) + { + + } + } + + public void testBasicPKCS12() + throws Exception + { + InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() + .setProvider("BC").build(pkcs12Pass.toCharArray()); + PKCS12PfxPdu pfx = new PKCS12PfxPdu(pkcs12); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + // TODO: finish! +// assertEquals(3, bags.length); +// assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + } + else + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + } + } + } + + public void testSHA256withPKCS5() + throws Exception + { + InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() + .setProvider("BC").build(sha256Pass.toCharArray()); + PKCS12PfxPdu pfx = new PKCS12PfxPdu(sha256Pfx); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + // TODO: finish! +// assertEquals(3, bags.length); +// assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + } + else + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + } + } + } + + public void testCreateTripleDESAndSHA1() + throws Exception + { + testCipherAndDigest(PKCSObjectIdentifiers.des_EDE3_CBC, OIWObjectIdentifiers.idSHA1); + } + + public void testCreateAES256andSHA256() + throws Exception + { + testCipherAndDigest(NISTObjectIdentifiers.id_aes256_CBC, NISTObjectIdentifiers.id_sha256); + } + + private void testCipherAndDigest(ASN1ObjectIdentifier cipherOid, ASN1ObjectIdentifier digestOid) + throws Exception + { + OutputEncryptor encOut = new JcePKCSPBEOutputEncryptorBuilder(cipherOid).setProvider("BC").build(passwd); + + KeyFactory fact = KeyFactory.getInstance("RSA", BC); + PrivateKey privKey = fact.generatePrivate(privKeySpec); + PublicKey pubKey = fact.generatePublic(pubKeySpec); + + X509Certificate[] chain = createCertChain(fact, pubKey); + + PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]); + + taCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Bouncy Primary Certificate")); + + PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]); + + caCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Bouncy Intermediate Certificate")); + + JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); + PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]); + + eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key")); + SubjectKeyIdentifier pubKeyId = extUtils.createSubjectKeyIdentifier(chain[0].getPublicKey()); + eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); + + PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, encOut); + + keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key")); + keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); + + PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder(); + + builder.addData(keyBagBuilder.build()); + + builder.addEncryptedData(new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC).setProvider("BC").build(passwd), new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build(), taCertBagBuilder.build() }); + + PKCS12PfxPdu pfx = builder.build(new JcePKCS12MacCalculatorBuilder(digestOid), passwd); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new JcePKCS12MacCalculatorBuilderProvider().setProvider("BC"), passwd)); + + InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() + .setProvider("BC").build(passwd); + + pfx = new PKCS12PfxPdu(pfx.toASN1Structure().getEncoded()); + + ContentInfo[] infos = pfx.getContentInfos(); + boolean encDataFound = false; + boolean pkcs8Found = false; + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + encDataFound = true; + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(3, bags.length); + assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + } + else + { + pkcs8Found = true; + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + } + } + + assertTrue(encDataFound); + assertTrue(pkcs8Found); + + KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); + + ks.load(new ByteArrayInputStream(pfx.getEncoded(ASN1Encoding.DL)), passwd); + + assertTrue(ks.containsAlias("Eric's Key")); + } + + public void testPKCS5() + throws Exception + { + doPKCS5Test(pkcs5Aes128Pfx); + doPKCS5Test(pkcs5Aes192Pfx); + doPKCS5Test(pkcs5Camellia128Pfx); + doPKCS5Test(pkcs5Camellia256Pfx); + doPKCS5Test(pkcs5Cast5Pfx); + doPKCS5Test(pkcs5TripleDesPfx); + } + + private void doPKCS5Test(byte[] keyStore) + throws Exception + { + InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() + .setProvider("BC").build(pkcs5Pass.toCharArray()); + PKCS12PfxPdu pfx = new PKCS12PfxPdu(keyStore); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + // TODO: finish! +// assertEquals(3, bags.length); +// assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + } + else + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + } + } + + // BC key store check + KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); + + ks.load(new ByteArrayInputStream(pfx.getEncoded(ASN1Encoding.DL)), pkcs5Pass.toCharArray()); + } + + public void testGOST1() + throws Exception + { + char[] password = "1".toCharArray(); + + InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() + .setProvider("BC").build(password); + PKCS12PfxPdu pfx = new PKCS12PfxPdu(gostPfx); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new JcePKCS12MacCalculatorBuilderProvider().setProvider("BC"), password)); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + // TODO: finish! +// assertEquals(3, bags.length); +// assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + } + else + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + assertEquals(CryptoProObjectIdentifiers.gostR3410_2001, info.getPrivateKeyAlgorithm().getAlgorithm()); + } + } + } + + public void testGOST2() + throws Exception + { + char[] password = "foo123".toCharArray(); + + InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() + .setProvider("BC").build(password); + PKCS12PfxPdu pfx = new PKCS12PfxPdu(gostPfxFoo123); + + assertTrue(pfx.hasMac()); + assertTrue(pfx.isMacValid(new JcePKCS12MacCalculatorBuilderProvider().setProvider("BC"), password)); + + ContentInfo[] infos = pfx.getContentInfos(); + + for (int i = 0; i != infos.length; i++) + { + if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + // TODO: finish! +// assertEquals(3, bags.length); +// assertEquals(PKCSObjectIdentifiers.certBag, bags[0].getType()); + } + else + { + PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); + + PKCS12SafeBag[] bags = dataFact.getSafeBags(); + + assertEquals(1, bags.length); + assertEquals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag, bags[0].getType()); + + PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo)bags[0].getBagValue(); + PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + assertEquals(CryptoProObjectIdentifiers.gostR3410_2001, info.getPrivateKeyAlgorithm().getAlgorithm()); + } + } + } + + private X509Certificate[] createCertChain(KeyFactory fact, PublicKey pubKey) + throws Exception + { + PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec); + PublicKey caPubKey = fact.generatePublic(caPubKeySpec); + PrivateKey intPrivKey = fact.generatePrivate(intPrivKeySpec); + PublicKey intPubKey = fact.generatePublic(intPubKeySpec); + + X509Certificate[] chain = new X509Certificate[3]; + + chain[2] = createMasterCert(caPubKey, caPrivKey); + chain[1] = createIntermediateCert(intPubKey, caPrivKey, chain[2]); + chain[0] = createCert(pubKey, intPrivKey, intPubKey); + return chain; + } + + private PKCS12PfxPdu createPfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain) + throws NoSuchAlgorithmException, IOException, PKCSException + { + JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); + + PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]); + + taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Primary Certificate")); + + PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]); + + caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Intermediate Certificate")); + + PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]); + + eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); + eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); + + PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd)); + + keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); + keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); + + // + // construct the actual key store + // + PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder(); + + PKCS12SafeBag[] certs = new PKCS12SafeBag[3]; + + certs[0] = eeCertBagBuilder.build(); + certs[1] = caCertBagBuilder.build(); + certs[2] = taCertBagBuilder.build(); + + pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwd), certs); + + pfxPduBuilder.addData(keyBagBuilder.build()); + + return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwd); + } +} diff --git a/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_dual_sig_ee.pem b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_dual_sig_ee.pem new file mode 100644 index 0000000000..ab76e64c59 --- /dev/null +++ b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_dual_sig_ee.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICYTCCAcOgAwIBAgIUVcVNficoipRs4c6JBiF731VtDLAwCgYIKoZIzj0EAwQw +gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi +bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg +UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X +DTI0MTAxNzIzMzcyM1oXDTM0MTAxNTIzMzcyM1owLzELMAkGA1UEBhMCWFgxDzAN +BgNVBAoMBkhhbmFrbzEPMA0GA1UECwwGWWFtYWRhMFkwEwYHKoZIzj0CAQYIKoZI +zj0DAQcDQgAEbg5mK9aDw+9pIASgzCANcYRugXSfaWtTH3Kg6th/m8hybPvXHsFG +Enm4Zu3a+S/5RPmIw78UoBMpIqR+Tfno16NgMF4wDAYDVR0TAQH/BAIwADAOBgNV +HQ8BAf8EBAMCB4AwHQYDVR0OBBYEFKjGwfjydnErtBzOVMiLz5lP9Jq/MB8GA1Ud +IwQYMBaAFOuj0ItR/hLczCFmh4UPmMdnc4g0MAoGCCqGSM49BAMEA4GLADCBhwJB +O3d8oj0thpSmSI85xLuvA97w/QKRhdGXwPtzO7VceH3seMiORoCLPKO8Gfd1liRL +tznhz7IbmVbS64WbxQe4QawCQgFeT1babH2MEBLT+NGXIKA0azitP11LA/rynYoD +bindtP08txIa8w9O2MhG1706nrLc+z+PstQqXgQQ5ha/fn97PA== +-----END CERTIFICATE----- diff --git a/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_dual_xch_ee.pem b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_dual_xch_ee.pem new file mode 100644 index 0000000000..b68dfca97a --- /dev/null +++ b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_dual_xch_ee.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIIDzTCCAy6gAwIBAgIUczxcVsNa7M9uSs598vuGatGLDuIwCgYIKoZIzj0EAwQw +gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi +bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg +UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X +DTI0MTAxNzIzMzcyM1oXDTM0MTAxNTIzMzcyM1owLzELMAkGA1UEBhMCWFgxDzAN +BgNVBAoMBkhhbmFrbzEPMA0GA1UECwwGWWFtYWRhMHYwEAYHKoZIzj0CAQYFK4EE +ACIDYgAE+qm8IaZ5hVFufLvTuniWWnQoa9d0YCyNiOmQ2OrrcukSy0FgozyJq7hc +g8o2pJ5uRRLVysU1gHNfxL+TvwRRr6eWUJE8v0dCUccuCFPAVbxwf7Hjcp5NSsFn +J2lIrvzgo4IBrDCCAagwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCAwgwHQYD +VR0OBBYEFAHprr1J3zZ7gG1ksEzN8BHM7tCzMB8GA1UdIwQYMBaAFOuj0ItR/hLc +zCFmh4UPmMdnc4g0MIIBRgYKYIZIAYb6a1AGAQSCATYwggEyAhRVxU1+JyiKlGzh +zokGIXvfVW0MsDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABG4OZivWg8PvaSAE +oMwgDXGEboF0n2lrUx9yoOrYf5vIcmz71x7BRhJ5uGbt2vkv+UT5iMO/FKATKSKk +fk356NekMTAvMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQUqMbB+PJ2cSu0HM5U +yIvPmU/0mr8DgYsAMIGHAkE7d3yiPS2GlKZIjznEu68D3vD9ApGF0ZfA+3M7tVx4 +fex4yI5GgIs8o7wZ93WWJEu3OeHPshuZVtLrhZvFB7hBrAJCAV5PVtpsfYwQEtP4 +0ZcgoDRrOK0/XUsD+vKdigNuKd20/Ty3EhrzD07YyEbXvTqestz7P4+y1CpeBBDm +Fr9+f3s8MAoGCCqGSM49BAMEA4GMADCBiAJCAXrIaCetU/F7+TDkYBjEaHRZEujy +DL2Ic08Eu+iDBRvzuYjxulQKCJaRFrcbegcW8D8MTkrJW8b0j9PkIXuLB51wAkIB +0/4Tx4hhUQ6SCBNx70mG2kOeHpgZB62K3b3PtypOJtUWTZS5XgBhljUUTmdsaQtA +wi1V+cwAnegmu168l43lQz0= +-----END CERTIFICATE----- diff --git a/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_ee.pem b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_ee.pem new file mode 100644 index 0000000000..a45f369e4b --- /dev/null +++ b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_ee.pem @@ -0,0 +1,133 @@ +-----BEGIN CERTIFICATE----- +MIIYhDCCF+agAwIBAgIUQFy9NSVq9ZXG6QZyo14DJ/bew58wCgYIKoZIzj0EAwQw +gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi +bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg +UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X +DTI0MTAxNzIzMzcyM1oXDTM0MTAxNTIzMzcyM1owLzELMAkGA1UEBhMCWFgxDzAN +BgNVBAoMBkhhbmFrbzEPMA0GA1UECwwGWWFtYWRhMIGbMBAGByqGSM49AgEGBSuB +BAAjA4GGAAQAFfoXF6AZPOkYTpb8vA2q+ZAtkE399B9BBz+q0A91vSeBvZbfat5V +hqVLtT+nEguQhlYhXf6CmCvFUERmQc8zfW4BaH1ZSd+kpuR5fJj6ibDbstHU3le4 +Vq2qHR+aXvmccEtYVZ5BX3KE+gY/ezpY/BBXrd8vJuV72SPdsrNzjCz5z8OjghY+ +MIIWOjAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQUB4Ts +5OVjMVy4x3jV/GEY8FPDjK0wHwYDVR0jBBgwFoAU66PQi1H+EtzMIWaHhQ+Yx2dz +iDQwghXYBgpghkgBhvprUAYBBIIVyDCCFcQCFEGRvI0Kc1g44vXzdeADjLKBvPUi +oA0wCwYJYIZIAWUDBAMSoYGPMIGMMQswCQYDVQQGEwJYWDE1MDMGA1UECgwsUm95 +YWwgSW5zdGl0dXRlIG9mIFB1YmxpYyBLZXkgSW5mcmFzdHJ1Y3R1cmUxKzApBgNV +BAsMIlBvc3QtSGVmZmFsdW1wIFJlc2VhcmNoIERlcGFydG1lbnQxGTAXBgNVBAMM +EE1MLURTQSBSb290IC0gRzEwggeyMAsGCWCGSAFlAwQDEgOCB6EAh3C60Iowi3gH +MtKvoDgZ1gHulpK4i8rX/+KOI9lKjMr4BUqYKeM80jQ9odCo1B3pTpG+79xQVpZa +kl2VCdhDEw4cdp+JZ21lwVhO8EBwMVFPExk4F3Tz94+J2y0XqVx4TSGbeJzaaqPV +EsJV/+KjBGr1BUUMFGl4ZAKwe5+47EAK9TZWNgsgW0MIx9G0q42s8WHh0LTymbi7 +zTcUEh8HcHDJPfxcH53AjXTlOdjlnzUcyzxobot+cah/62AEiPUaAuPQsko9l1Lk +5B6frofqTE7tpNBn3eMjXV2R4cPJo/Kj1wFrchdD5BMg+MD19mDu9aT7BIMC3MZe +mWaynMRnbwfMkqDFpPKE1mISbDv2Ia0bqzHUNMUSc26Xaer2rcXdD7TM4kZfS1SL +4QhnbD6chyfw9Z9ggPiSU2J4glEL1detpi2MwWwKtSiQ5Sc0ksaX35U6ULTl+5zO +wQd8WeXaS+7AUlTS25mDzQRXd+goSX2QZC/e2a2yh2HsCIDP8PAG/J6ClnuMasGw +o+4v93/GKfGjJ85HqSeK/ybbQna/bi4dwabtSRPmflmk1YDFov4IP9J9oI3NQx/J +EMSgHWpSxGsdGOgNGHLTACbqLCqLhWCjiJyMU5bQo7Ump9U1nzaZoIQkKbsTAE2F +rTKA+PJtDxl3OkDzNnCKW2IijN68+msyuDTMdv4fLIBCKCsFPHpLRZInBKwZJ8a2 +qm0G0a6R64/A/65KoVoByDkKsJbP0QtpZmaLW+r9G6yrvOSBgorDYBcA1l6y6gh8 +SS/RhSgmBFtXog4l4pm2DwkiqGEqz9GOUgMMA08UocHWTvfUlGJYM/INFqLc5xM3 +xJ+6ef37+dlNd86+HXVx1uzEOCDJHhlVwYKNhoKiGGeb3IrOkzVxQ44tVmjfIn6R +mlvFyAIKuJvRxPN53wFFI2j4AhyCaut8dcgFdKdoAfnQAuoE0i1vMcJXBn2XAlFm +ifCVYw6AtghqVkEVlOK0VwEcNeiCC3TzwqPLLNkgedGZfiVTcJSVsAN6Q1KjPhAW +AaUSCMPYgHKVzSOu9eKRiesiqEjr44D7ATWi3VP3kzHHlRmPakUAV9U7woOpNHbs +IyEhrua9n/D5LoYbL2a0QLtcs2BW6pGfXLlIafW95QZLrz1uUvSzb8MuLdFuk3Mo +h/ugHWvmcyoLloIGhf789/qdEldmSMe/PwM3ruHsoKMj/yTW28wvnkJU6y8FoOaD +hLP83MICvLc0jockJXvgG6Y5eEfQ+69Or20Gvneb+fmnYDxYhIqLhcZ9EjDAFsgK +O83Xk8lWa20AXUX6vbkpbimRCRQK8NLc+NHxVYLnKwmNY9av2LPuXxyCm15YEWOl +Zs+rXa3zj8fa2ptidCGHICHR3rKEiyPfCIMAFhs5VGva3SZWFOjFVXzOl8q/CODa +oJwPXVPe8hiEIfnswNKBsg6+mZcv0wD252QmrCAmGhIhz5uBj23TL/wHoucrVfvD +hjQWPiiXNRSVYf9abgxU/C2VfQFJSWH9SDTQIShzY2vq7T/Nnb76+3w+oo+f7a40 +Z+B2vSJJ37wqQQmVnQxQHrDMgRGzeS2OHoQMcZrrwOwzc9IeP+pa4qQcdrzIuAbK +HcZfGWS49OMSdOLAizOwKxkOKmixmNndQBbXqOjH7oflIzsX+muGqhp+pX0ZjH5A ++SgPc3IogUV7giY5ABzn4q2Z7yyMewTrQB2VRANdM3EZBLGK3fQ/OrSrPqSfulwC +Lc97vLuByBfTrpJOhnLzM9AL8U6NascJ0W9fcyLKtBj9+iGKhq0MgRgK/IsA1J7S +Eczyfk2sf39jIbPzSvD8RrbVcqO2p5wkzpL2H/BuD2Wqdw301hefg/eSdcO/cSHu +mLUU9ZyRfQuWAFsZQ5+OXkSaIMStJZOScluoQuY0NHib5bwni5TX3G8TZ0tcmMFg +rhmNmv+xUYNhhKYOEL/SAIbonl33KR6URa1R0eQMnhTsGff7wHfMX7ggynZ20886 +NWHLA30whGHPiLcn8QHJFdPvRaJvrF03rEGUPMKXkoV3/vX0QoA10Y4VD6EwdDiI +OrIiBDSYBB1ZteGn5kG16c4YZTbenYJ6QBjB7D6FrkG5SjNzDlSL1GBe/rxbyuEY +rfM6ImIrl+GPP4p/aFx/tAmPrgIj6gxeXrUMaRXOiphtHWHdWdhnHpq6I61t0Kmc +bFnMZ2AQICJxbVSCd0uVwvtdJA8xftakRiC5Miy5c3jbOmcPsTiCk3cj3U+cuXFi +uiNMkkIxpUineagyZVYhYnn2QlerFdJC2Lfw5DHekIA0nt8byScNsZujwPvIuKee +vA/0byH6QpizT0lUBW/ZioI3780b5VZn0BRBNG7cY94s9EpjfbuaTDv2xW7AGVGg +OUy8VOnX0Xf9GlDiXOUnXAUJZjIFNmd4D7fyGQccbXl4V9xf1xlIL8JYlHSgpMuV +aSMlgwQEbHQrPNzpdmXaNfmFo/63FLgs8CL5XvaY2QyjoWnGdF6BUL2BFVFw+7nN +TEqIT30XfEDJsqcDQPNLFK9vph1M6Bc2mqMpw0d3lMvK1BIKKD6cDVqb20HQdDl7 +UejWY7ZdzoH7n8FLvQGiMw3JFbwcNW+kYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgGGMB0GA1UdDgQWBBRJdGxRQiHln7uR5KM1S+MBTZCQjjAfBgNV +HSMEGDAWgBSbB7SkdcS8kV014MmhwWLid1XWPwOCDO4AYK+Hb9SGbGLVRl2UkgRK +x4TQHl3mXSPXT6k/kMDPMrb1P4J0cI1PEfu7ZBLMpUjs+WG65+8i0bKLQ/a/h0WB +3V+9ZYnhDxJIYRXr9HPgpfw9XjFGzl7r9prf33daciIR98KNOaJs/sSSIeSEabLH +bGbinXXX1uNXKbtT3haT2ISkvztEdEP3ddOD/NhhTYhUUxWw5pKQBdEYDJmSMa0z +8Gsd9y9LlqFDVjwe8MJogay/y/CFpQmmuwkifJnX/JOMzoTGhYYMXKUSI5cooQz+ +XlDrvP6y2+M70t5WclTDisUJsu7FLtF1BgVnY+6zPR2puaNh27rgi/1uNtjsOqgA +G6aBGeOu7fp1uwBeas6P3hCsibZzQyJmKFVEIoigePTBRSWV9uc0K1cHYDHi+Mlc +MsigyT1H6EWOWhykXRx1STEISZnWdN4M/r7i40Au656xPYdWKoksSYUWuCXUyH5K ++tDTQCtyyJ+zfVJyLFy8uNG26chwTiyr2SeSjtNOBkq5hqO72H/7rGUtufxKAJYY +PWkA3VWMgymz1rg8SaBTw7GuNIDTNuLMWo4C1fTyi+ypi5IJIIHSOhwbfSWYzlPO +XnMpRaQ2FK5CIG/koj1TVbUXwdv24Gvam7VDnQUWdhVFbCRrTDrWX6vI4hXiOG+s +ZXvhjETPkrtXrcccEMjkxjADagU8yLSzKt+0JMb7YcaLaiFfg3jFVDc2pmqUQfyk +TD/8nywSpyF0bp9m8EVUR4f6Eh2yQNh4ofuSRJVB9mnv91QVEUK97Zkm7WU458B8 +sAiRuQicmToTA/Nub1zAGmUvfcsFwNqoGcg1ly3um1+mX2Do664vSrKNOpo7qM8F +wUgE0YHLR6CCbYPWH7cnz2+75Mj6fo9WFwecEFPmnO3Yzxx8/OvjX5jDpY3GW0f/ +C77rqiioabuejNjTsFMW4YQZtEtsSZ2Q4rQhUxJM1vREh/sTxN+RPfxiy4we5gSZ +scfL0qB8wn7paY/cbWEzJKtvlEukvnWIjt16NLLHcBIMTfnUdubeulmB1p5k1NKK +IQsOPS0AxWL/+BNs2wFQa4JBNuDlh8nQR7cIUIGOhqFwK2FWCuH414Q1vc02d4FT +HiPw5iIm8k/cZDlOeKO0OanwrvyVNDdb1naC9lrxRWkmcyokPoBtsfFUF5bYmsrh +CZFSHgo2jrVNsXo6OtJz934ZEZOGDYjhRrjHCl3HUgFhUfh4aVDrjaG8atQSpbBh +M+ZAbVI8r7ldccgaCABE823dSlizruB9phhf4rMKKkjWg31u9l5Hg8WSvHIp2xng +/MzOaUV1NIyJsMppi30kDpgOKc5Gn0wxhvAZFvG0x41KmMJ08UtG51+eftZErZZK +jyDxJ+xSIQ3pNfZFBAE7JPTDqAYAEaOJFX5OhE3nSxirPVh61c9RmihWA3GJ5P1d +sX13VYsWnW9QGrntgh6y3FiVjFmBqHl0YOXaSLr4sUkXP+JiK4dXnq/eCacajOi3 +FauHU0rlGBY4HSIznFI9yItyrZjF+b58D+Zda1RoeXhjWOTjio8NZQkIkg3pctcT +hbFdZ22OSzChiwZMZZ8LRzkvPSxgh7kQONRkyEOJtQseh/BxTf+tSSzRffkcgNXN +VkW3K+CQUB5zVNvL5XLIPqyyueOCWgqYUU39GywznT//Jp6d++S4hZKjdlAFf/kH +B2o5w8m9hYD+/EAgnI2Dwgw2zIvIvexsiunNAVxODZDhwEQQWceaO7qoWrjEbg/M +lp94C33genksjWx0AtOGjSKNVtPMigrcoSRi9DD7v6rlhGnetQP7gLtHFJTFqbHK +rCirlmpqQC1cCCCFRcEmIOcvzPp4NDx7Q4hoJvPlbXYz3ZKnSyPI5GBb74ucB19N +dUenK9DIA57PWlwSuElSjvyheKgaVpZdrGOS9d/xjMRHff6/3tffNI/0Gkx3eXXV +fjFOsyGNNjV8xXFkyFiIn7Nxm4AQxVzaKRaPagV9ykLe/+d4XSZ00+I89r4GaLrs +jKmMDjsz9XIuKL/FX0xaASa8j/Yoa0WM3UCaJeTFMJTFj55qBJmXT3HyXxBDAet7 +WmxQDh9ciYWLp0sVYQvTsY+dCT8W6kNQGeC/C3JRVeoVDFaKG+JgLvbYmlqp6YB3 +D3WXGrGwViRTYOqPzWPBpGsluO4cjW5Nuipn6j1yyFlIlQjJGHELU+b8vDFo9+CQ +r6L1IHaxi2CUXMUAAhM0YuyVDmU3VkOFxmHBpriYqc6LSw19Z4EkEaEdTuiTZXDg +uOmLK8lKtBMh93IAkHIHyUPWe8ZyC51Kzdb2ntwQWUo7JXwj6PtneSG0byZKKbhm +TNB9I6ISrc20I3GTqIYHWKLQqa8x746YFj+FPR/rx4jeEc0K/716kHZ1DXTLLziW +KaNplCOkLpBv+bdQafiHt3qV/NiojSZ2K5Pclh3F/m5lYx1dsiZ35Hq+bfC/75Mf +npdpiatkZPy7cBS7aJFZMqW/398ei5W+0AZFCSPp51fZVDzzY/ltdRBM2gF8xbOV +IMuReia4eeI5WdP6aGZI1HUrxyNXa9PkhQvzn1KFFAXEcP37B3lY/z6Nbrl9xTKO +04Cx8b+eq/+3OnAtTHTq0arHvRIS0KUvZSJvZA0Rmzi9wRDmiW2PpvBI0ev0FE4g +dEvjvOAFsxkrjwRhWfg3Qi6PxMhiGay6VPGjESWJfHyMzILcBJ5opShuEVSMYziZ +lJvhNarEqtdHXEIHTvh85/RrNwrRu1uqPhc3iQIdPiyYLlBrza2/35g0iI3HkTkO +Ti4jV9Eas8v+IdEqDglsVrTcpQHvCV0ov85c5ujark84dyz9FzwUqmUaIgtgVEGD +bMUIUeZmdbBOSW+xKhQmD3+yQAake+zeDDwbX1Z6kEWJTb2LC4333fVESuT6jjqj +uBLoRzEZczu6p6h4aGT9NlVIoKDAuwxkJOOgyAcWPFQ5wEWwMxsbE7/+tgIQD2rC +ENxN6jPYyBch2hVyne/EEuiGoA3oxA8B0gLqgWEoooNCEEYmztRPGSRIQTUYdZ4e +/lqdOAbMKD8b6soC8qtxkJLH5hYqOewlsNLU42eZK73nxGtg0CypRacEKfa4tj1q +P/RViSg3VDvswMF9/fbL15pBoqb6lZfCKBqJET4Y4TAa9TRa1yPC3u1ia5khE2p6 +ZV2WQyoDgP3AiH8dZ9uDyGWSrSabU8gWBtrBcc2UvPmj4P5LF7rtr6RWuWTf2bkc +ZaaX+vtDGoq5RaxqvJBaRO5y9wZ+aiep9VR/DmIK25A06/lUB0YMKk7dKKQirTye +EpIxyzXdHFAjNUKuwqljoXhmWe8RXAbhKpZxVKJwSVyfegg6CcwKnQLi10fFXdOj +/WOvDPenfXytJrQnZuprbyq6+7KTsF1rvlZbVs55RFuyGcy/eTWVyynUfTFh0uy+ +v6HcSceqF3V6TICrvS1pcJQlvPOACowKIiCjs4H9oYjfQ+8QhzPW7mNf7qU4aGnL +/o6XngOdMcT+j/NAelI91CJK62elll5lFvPXdlLEZKH89Lr9fOJzuEa0jfLGLpfI +QL6AmhS/ZrqwwSim0w+zktSEDUhLXcdBhqJvG73wMOwpUJR/XMufWPnFo5+42CiK +zhHKzFN+zf+E8SRVUbDKZarvNpQai/xTUT9eNo1arfV04tRL7ZCrT82gQH3ivKFY +9hSX/omu9bcWG3BQgCI1HWIMXDqWAB2FAEYPNEELyTMpKis1Y0N1ehdcJ7uAhgF8 +emm+qrXaRDXXOT/XfHQSGnMllODwrakQ0/CPTSmde+KZALq/Bd5zJ0KS/JheTQ8j +ZzwuMOmcOrKlAlWRHfFjevbVcXSAWeHjJQLQL7OOuzk9Zr8L/tMF/BDK4mu5lw8S +KKNPy11w/uVqRqnl0PW2YbPanUXrummptMKKnjoLIcMJu/pBu2ePsMI4xgaREh5v +QxgLl/+D/sawyK/WFOjFEsurYrjv/7FSg+PQtXAwz3+M/QOvLbLX70Dqpczn2gBb +FvgfI8pBKWnmT+PqJaxxFfVGm6HvUuULJIJK+Mmu5/Dhge0sbp0JL+3WA1PQ3N8w +B5NXkNTQFzAGWna2TtwAfVOLnJpRd8W+fahjzw9ivboYMmTMoXaNoCVTHCyAOH5f +fUkWAe784VC91E78fAU4yI+QSfmo+lxrgDvQnEvZTXPhPUyF53mZbY4WKX8uIHtZ +SOMKeRknZxEEagF8/yPDA5RiDP7KKQVEFEt8GMQGQWodrWQ+AGxe3VgcXdjma+Iq +zJ7As+J2rUKtOgzjG5E03WEx/fL1ppgOhn1wU7cGSWuPO70DNRMdvkUSzt/MGjP7 +zL/cjhyZ8I3DStaRX4PjG7EAI0ZWd6HO4gUYMjU+VVx0m81haqDD/LW/8PcLPEma +owAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgSFxsgMAoGCCqGSM49BAMEA4GLADCB +hwJCAP1Y2r26fxhSYmL7pjEF7aP9V4ZzoVfpDf75VxKTW6vCvz/CozYhzn6mZka5 +18GBRgmXC4Ye88toLOhdxjT319/lAkEVyxpodYAljpbkwVjT4a7b4yioPJvR6S44 +6dU955tbns3PFbzhOU8usFhyXsKRDH7MBzt+ew9EnPEel7ud4+F23A== +-----END CERTIFICATE----- diff --git a/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_root.pem b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_root.pem new file mode 100644 index 0000000000..59c7580cdd --- /dev/null +++ b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ec_dsa_root.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDBDCCAmagAwIBAgIUDCQO4j68JeS6tggSujZ2W/+5RMAwCgYIKoZIzj0EAwQw +gYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVi +bGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAg +UmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMB4X +DTI0MTAxNzIzMzcyM1oXDTM0MTAxNTIzMzcyM1owgYsxCzAJBgNVBAYTAlhYMTUw +MwYDVQQKDCxSb3lhbCBJbnN0aXR1dGUgb2YgUHVibGljIEtleSBJbmZyYXN0cnVj +dHVyZTErMCkGA1UECwwiUG9zdC1IZWZmYWx1bXAgUmVzZWFyY2ggRGVwYXJ0bWVu +dDEYMBYGA1UEAwwPRUNEU0EgUm9vdCAtIEcxMIGbMBAGByqGSM49AgEGBSuBBAAj +A4GGAAQBAFYGp79DhDUnJ+euhbWIqRMPC/YJyMcXp5xEF96cQji2rOckvcqQkhqE +K2upXcSLaclIkS16REFZgT0q3vO2m1wAhXxeKePsML2EiCMQIEArXsEwCDGu+qdx +mN2lHUQNuiisrkigRdXILHaAXdfTtAvpopsAchnm+vUbHNavcxVRjK2jYzBhMA8G +A1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTro9CLUf4S +3MwhZoeFD5jHZ3OINDAfBgNVHSMEGDAWgBTro9CLUf4S3MwhZoeFD5jHZ3OINDAK +BggqhkjOPQQDBAOBiwAwgYcCQUnnSxI6X5NPGGetpBUkEh3HIDTrW24dPtx74wmW +ANwrejsbS0SvbipnQJPQXjTv8aXDlDAMiPKHado5qCJXMvU3AkIAmDbRmevtaNUQ +0k6e97CWc8tTPE7gXo5iqFD0NU9v20HV3z7voEU8fYD65A1Ay3VQ76nC8W8T4T1a +fvRCLit6wo0= +-----END CERTIFICATE----- diff --git a/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ml_dsa_ee.pem b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ml_dsa_ee.pem new file mode 100644 index 0000000000..d9dedc75cf --- /dev/null +++ b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ml_dsa_ee.pem @@ -0,0 +1,121 @@ +-----BEGIN CERTIFICATE----- +MIIWJjCCCSOgAwIBAgIUQZG8jQpzWDji9fN14AOMsoG89SIwCwYJYIZIAWUDBAMS +MIGMMQswCQYDVQQGEwJYWDE1MDMGA1UECgwsUm95YWwgSW5zdGl0dXRlIG9mIFB1 +YmxpYyBLZXkgSW5mcmFzdHJ1Y3R1cmUxKzApBgNVBAsMIlBvc3QtSGVmZmFsdW1w +IFJlc2VhcmNoIERlcGFydG1lbnQxGTAXBgNVBAMMEE1MLURTQSBSb290IC0gRzEw +HhcNMjQxMDE3MjMzNzIzWhcNMzQxMDE1MjMzNzIzWjAvMQswCQYDVQQGEwJYWDEP +MA0GA1UECgwGSGFuYWtvMQ8wDQYDVQQLDAZZYW1hZGEwggeyMAsGCWCGSAFlAwQD +EgOCB6EAh3C60Iowi3gHMtKvoDgZ1gHulpK4i8rX/+KOI9lKjMr4BUqYKeM80jQ9 +odCo1B3pTpG+79xQVpZakl2VCdhDEw4cdp+JZ21lwVhO8EBwMVFPExk4F3Tz94+J +2y0XqVx4TSGbeJzaaqPVEsJV/+KjBGr1BUUMFGl4ZAKwe5+47EAK9TZWNgsgW0MI +x9G0q42s8WHh0LTymbi7zTcUEh8HcHDJPfxcH53AjXTlOdjlnzUcyzxobot+cah/ +62AEiPUaAuPQsko9l1Lk5B6frofqTE7tpNBn3eMjXV2R4cPJo/Kj1wFrchdD5BMg ++MD19mDu9aT7BIMC3MZemWaynMRnbwfMkqDFpPKE1mISbDv2Ia0bqzHUNMUSc26X +aer2rcXdD7TM4kZfS1SL4QhnbD6chyfw9Z9ggPiSU2J4glEL1detpi2MwWwKtSiQ +5Sc0ksaX35U6ULTl+5zOwQd8WeXaS+7AUlTS25mDzQRXd+goSX2QZC/e2a2yh2Hs +CIDP8PAG/J6ClnuMasGwo+4v93/GKfGjJ85HqSeK/ybbQna/bi4dwabtSRPmflmk +1YDFov4IP9J9oI3NQx/JEMSgHWpSxGsdGOgNGHLTACbqLCqLhWCjiJyMU5bQo7Um +p9U1nzaZoIQkKbsTAE2FrTKA+PJtDxl3OkDzNnCKW2IijN68+msyuDTMdv4fLIBC +KCsFPHpLRZInBKwZJ8a2qm0G0a6R64/A/65KoVoByDkKsJbP0QtpZmaLW+r9G6yr +vOSBgorDYBcA1l6y6gh8SS/RhSgmBFtXog4l4pm2DwkiqGEqz9GOUgMMA08UocHW +TvfUlGJYM/INFqLc5xM3xJ+6ef37+dlNd86+HXVx1uzEOCDJHhlVwYKNhoKiGGeb +3IrOkzVxQ44tVmjfIn6RmlvFyAIKuJvRxPN53wFFI2j4AhyCaut8dcgFdKdoAfnQ +AuoE0i1vMcJXBn2XAlFmifCVYw6AtghqVkEVlOK0VwEcNeiCC3TzwqPLLNkgedGZ +fiVTcJSVsAN6Q1KjPhAWAaUSCMPYgHKVzSOu9eKRiesiqEjr44D7ATWi3VP3kzHH +lRmPakUAV9U7woOpNHbsIyEhrua9n/D5LoYbL2a0QLtcs2BW6pGfXLlIafW95QZL +rz1uUvSzb8MuLdFuk3Moh/ugHWvmcyoLloIGhf789/qdEldmSMe/PwM3ruHsoKMj +/yTW28wvnkJU6y8FoOaDhLP83MICvLc0jockJXvgG6Y5eEfQ+69Or20Gvneb+fmn +YDxYhIqLhcZ9EjDAFsgKO83Xk8lWa20AXUX6vbkpbimRCRQK8NLc+NHxVYLnKwmN +Y9av2LPuXxyCm15YEWOlZs+rXa3zj8fa2ptidCGHICHR3rKEiyPfCIMAFhs5VGva +3SZWFOjFVXzOl8q/CODaoJwPXVPe8hiEIfnswNKBsg6+mZcv0wD252QmrCAmGhIh +z5uBj23TL/wHoucrVfvDhjQWPiiXNRSVYf9abgxU/C2VfQFJSWH9SDTQIShzY2vq +7T/Nnb76+3w+oo+f7a40Z+B2vSJJ37wqQQmVnQxQHrDMgRGzeS2OHoQMcZrrwOwz +c9IeP+pa4qQcdrzIuAbKHcZfGWS49OMSdOLAizOwKxkOKmixmNndQBbXqOjH7ofl +IzsX+muGqhp+pX0ZjH5A+SgPc3IogUV7giY5ABzn4q2Z7yyMewTrQB2VRANdM3EZ +BLGK3fQ/OrSrPqSfulwCLc97vLuByBfTrpJOhnLzM9AL8U6NascJ0W9fcyLKtBj9 ++iGKhq0MgRgK/IsA1J7SEczyfk2sf39jIbPzSvD8RrbVcqO2p5wkzpL2H/BuD2Wq +dw301hefg/eSdcO/cSHumLUU9ZyRfQuWAFsZQ5+OXkSaIMStJZOScluoQuY0NHib +5bwni5TX3G8TZ0tcmMFgrhmNmv+xUYNhhKYOEL/SAIbonl33KR6URa1R0eQMnhTs +Gff7wHfMX7ggynZ20886NWHLA30whGHPiLcn8QHJFdPvRaJvrF03rEGUPMKXkoV3 +/vX0QoA10Y4VD6EwdDiIOrIiBDSYBB1ZteGn5kG16c4YZTbenYJ6QBjB7D6FrkG5 +SjNzDlSL1GBe/rxbyuEYrfM6ImIrl+GPP4p/aFx/tAmPrgIj6gxeXrUMaRXOipht +HWHdWdhnHpq6I61t0KmcbFnMZ2AQICJxbVSCd0uVwvtdJA8xftakRiC5Miy5c3jb +OmcPsTiCk3cj3U+cuXFiuiNMkkIxpUineagyZVYhYnn2QlerFdJC2Lfw5DHekIA0 +nt8byScNsZujwPvIuKeevA/0byH6QpizT0lUBW/ZioI3780b5VZn0BRBNG7cY94s +9EpjfbuaTDv2xW7AGVGgOUy8VOnX0Xf9GlDiXOUnXAUJZjIFNmd4D7fyGQccbXl4 +V9xf1xlIL8JYlHSgpMuVaSMlgwQEbHQrPNzpdmXaNfmFo/63FLgs8CL5XvaY2Qyj +oWnGdF6BUL2BFVFw+7nNTEqIT30XfEDJsqcDQPNLFK9vph1M6Bc2mqMpw0d3lMvK +1BIKKD6cDVqb20HQdDl7UejWY7ZdzoH7n8FLvQGiMw3JFbwcNW+jYzBhMA8GA1Ud +EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBRJdGxRQiHln7uR +5KM1S+MBTZCQjjAfBgNVHSMEGDAWgBSbB7SkdcS8kV014MmhwWLid1XWPzALBglg +hkgBZQMEAxIDggzuAGCvh2/Uhmxi1UZdlJIESseE0B5d5l0j10+pP5DAzzK29T+C +dHCNTxH7u2QSzKVI7PlhuufvItGyi0P2v4dFgd1fvWWJ4Q8SSGEV6/Rz4KX8PV4x +Rs5e6/aa3993WnIiEffCjTmibP7EkiHkhGmyx2xm4p1119bjVym7U94Wk9iEpL87 +RHRD93XTg/zYYU2IVFMVsOaSkAXRGAyZkjGtM/BrHfcvS5ahQ1Y8HvDCaIGsv8vw +haUJprsJInyZ1/yTjM6ExoWGDFylEiOXKKEM/l5Q67z+stvjO9LeVnJUw4rFCbLu +xS7RdQYFZ2Pusz0dqbmjYdu64Iv9bjbY7DqoABumgRnjru36dbsAXmrOj94QrIm2 +c0MiZihVRCKIoHj0wUUllfbnNCtXB2Ax4vjJXDLIoMk9R+hFjlocpF0cdUkxCEmZ +1nTeDP6+4uNALuuesT2HViqJLEmFFrgl1Mh+SvrQ00Arcsifs31ScixcvLjRtunI +cE4sq9knko7TTgZKuYaju9h/+6xlLbn8SgCWGD1pAN1VjIMps9a4PEmgU8OxrjSA +0zbizFqOAtX08ovsqYuSCSCB0jocG30lmM5Tzl5zKUWkNhSuQiBv5KI9U1W1F8Hb +9uBr2pu1Q50FFnYVRWwka0w61l+ryOIV4jhvrGV74YxEz5K7V63HHBDI5MYwA2oF +PMi0syrftCTG+2HGi2ohX4N4xVQ3NqZqlEH8pEw//J8sEqchdG6fZvBFVEeH+hId +skDYeKH7kkSVQfZp7/dUFRFCve2ZJu1lOOfAfLAIkbkInJk6EwPzbm9cwBplL33L +BcDaqBnINZct7ptfpl9g6OuuL0qyjTqaO6jPBcFIBNGBy0eggm2D1h+3J89vu+TI ++n6PVhcHnBBT5pzt2M8cfPzr41+Yw6WNxltH/wu+66ooqGm7nozY07BTFuGEGbRL +bEmdkOK0IVMSTNb0RIf7E8TfkT38YsuMHuYEmbHHy9KgfMJ+6WmP3G1hMySrb5RL +pL51iI7dejSyx3ASDE351Hbm3rpZgdaeZNTSiiELDj0tAMVi//gTbNsBUGuCQTbg +5YfJ0Ee3CFCBjoahcCthVgrh+NeENb3NNneBUx4j8OYiJvJP3GQ5TnijtDmp8K78 +lTQ3W9Z2gvZa8UVpJnMqJD6AbbHxVBeW2JrK4QmRUh4KNo61TbF6OjrSc/d+GRGT +hg2I4Ua4xwpdx1IBYVH4eGlQ642hvGrUEqWwYTPmQG1SPK+5XXHIGggARPNt3UpY +s67gfaYYX+KzCipI1oN9bvZeR4PFkrxyKdsZ4PzMzmlFdTSMibDKaYt9JA6YDinO +Rp9MMYbwGRbxtMeNSpjCdPFLRudfnn7WRK2WSo8g8SfsUiEN6TX2RQQBOyT0w6gG +ABGjiRV+ToRN50sYqz1YetXPUZooVgNxieT9XbF9d1WLFp1vUBq57YIestxYlYxZ +gah5dGDl2ki6+LFJFz/iYiuHV56v3gmnGozotxWrh1NK5RgWOB0iM5xSPciLcq2Y +xfm+fA/mXWtUaHl4Y1jk44qPDWUJCJIN6XLXE4WxXWdtjkswoYsGTGWfC0c5Lz0s +YIe5EDjUZMhDibULHofwcU3/rUks0X35HIDVzVZFtyvgkFAec1Tby+VyyD6ssrnj +gloKmFFN/RssM50//yaenfvkuIWSo3ZQBX/5BwdqOcPJvYWA/vxAIJyNg8IMNsyL +yL3sbIrpzQFcTg2Q4cBEEFnHmju6qFq4xG4PzJafeAt94Hp5LI1sdALTho0ijVbT +zIoK3KEkYvQw+7+q5YRp3rUD+4C7RxSUxamxyqwoq5ZqakAtXAgghUXBJiDnL8z6 +eDQ8e0OIaCbz5W12M92Sp0sjyORgW++LnAdfTXVHpyvQyAOez1pcErhJUo78oXio +GlaWXaxjkvXf8YzER33+v97X3zSP9BpMd3l11X4xTrMhjTY1fMVxZMhYiJ+zcZuA +EMVc2ikWj2oFfcpC3v/neF0mdNPiPPa+Bmi67IypjA47M/VyLii/xV9MWgEmvI/2 +KGtFjN1AmiXkxTCUxY+eagSZl09x8l8QQwHre1psUA4fXImFi6dLFWEL07GPnQk/ +FupDUBngvwtyUVXqFQxWihviYC722JpaqemAdw91lxqxsFYkU2Dqj81jwaRrJbju +HI1uTboqZ+o9cshZSJUIyRhxC1Pm/LwxaPfgkK+i9SB2sYtglFzFAAITNGLslQ5l +N1ZDhcZhwaa4mKnOi0sNfWeBJBGhHU7ok2Vw4LjpiyvJSrQTIfdyAJByB8lD1nvG +cgudSs3W9p7cEFlKOyV8I+j7Z3khtG8mSim4ZkzQfSOiEq3NtCNxk6iGB1ii0Kmv +Me+OmBY/hT0f68eI3hHNCv+9epB2dQ10yy84limjaZQjpC6Qb/m3UGn4h7d6lfzY +qI0mdiuT3JYdxf5uZWMdXbImd+R6vm3wv++TH56XaYmrZGT8u3AUu2iRWTKlv9/f +HouVvtAGRQkj6edX2VQ882P5bXUQTNoBfMWzlSDLkXomuHniOVnT+mhmSNR1K8cj +V2vT5IUL859ShRQFxHD9+wd5WP8+jW65fcUyjtOAsfG/nqv/tzpwLUx06tGqx70S +EtClL2Uib2QNEZs4vcEQ5oltj6bwSNHr9BROIHRL47zgBbMZK48EYVn4N0Iuj8TI +YhmsulTxoxEliXx8jMyC3ASeaKUobhFUjGM4mZSb4TWqxKrXR1xCB074fOf0azcK +0btbqj4XN4kCHT4smC5Qa82tv9+YNIiNx5E5Dk4uI1fRGrPL/iHRKg4JbFa03KUB +7wldKL/OXObo2q5POHcs/Rc8FKplGiILYFRBg2zFCFHmZnWwTklvsSoUJg9/skAG +pHvs3gw8G19WepBFiU29iwuN9931RErk+o46o7gS6EcxGXM7uqeoeGhk/TZVSKCg +wLsMZCTjoMgHFjxUOcBFsDMbGxO//rYCEA9qwhDcTeoz2MgXIdoVcp3vxBLohqAN +6MQPAdIC6oFhKKKDQhBGJs7UTxkkSEE1GHWeHv5anTgGzCg/G+rKAvKrcZCSx+YW +KjnsJbDS1ONnmSu958RrYNAsqUWnBCn2uLY9aj/0VYkoN1Q77MDBff32y9eaQaKm ++pWXwigaiRE+GOEwGvU0Wtcjwt7tYmuZIRNqemVdlkMqA4D9wIh/HWfbg8hlkq0m +m1PIFgbawXHNlLz5o+D+Sxe67a+kVrlk39m5HGWml/r7QxqKuUWsaryQWkTucvcG +fmonqfVUfw5iCtuQNOv5VAdGDCpO3SikIq08nhKSMcs13RxQIzVCrsKpY6F4Zlnv +EVwG4SqWcVSicElcn3oIOgnMCp0C4tdHxV3To/1jrwz3p318rSa0J2bqa28quvuy +k7Bda75WW1bOeURbshnMv3k1lcsp1H0xYdLsvr+h3EnHqhd1ekyAq70taXCUJbzz +gAqMCiIgo7OB/aGI30PvEIcz1u5jX+6lOGhpy/6Ol54DnTHE/o/zQHpSPdQiSutn +pZZeZRbz13ZSxGSh/PS6/Xzic7hGtI3yxi6XyEC+gJoUv2a6sMEoptMPs5LUhA1I +S13HQYaibxu98DDsKVCUf1zLn1j5xaOfuNgois4RysxTfs3/hPEkVVGwymWq7zaU +Gov8U1E/XjaNWq31dOLUS+2Qq0/NoEB94ryhWPYUl/6JrvW3FhtwUIAiNR1iDFw6 +lgAdhQBGDzRBC8kzKSorNWNDdXoXXCe7gIYBfHppvqq12kQ11zk/13x0EhpzJZTg +8K2pENPwj00pnXvimQC6vwXecydCkvyYXk0PI2c8LjDpnDqypQJVkR3xY3r21XF0 +gFnh4yUC0C+zjrs5PWa/C/7TBfwQyuJruZcPEiijT8tdcP7lakap5dD1tmGz2p1F +67ppqbTCip46CyHDCbv6Qbtnj7DCOMYGkRIeb0MYC5f/g/7GsMiv1hToxRLLq2K4 +7/+xUoPj0LVwMM9/jP0Dry2y1+9A6qXM59oAWxb4HyPKQSlp5k/j6iWscRX1Rpuh +71LlCySCSvjJrufw4YHtLG6dCS/t1gNT0NzfMAeTV5DU0BcwBlp2tk7cAH1Ti5ya +UXfFvn2oY88PYr26GDJkzKF2jaAlUxwsgDh+X31JFgHu/OFQvdRO/HwFOMiPkEn5 +qPpca4A70JxL2U1z4T1Mhed5mW2OFil/LiB7WUjjCnkZJ2cRBGoBfP8jwwOUYgz+ +yikFRBRLfBjEBkFqHa1kPgBsXt1YHF3Y5mviKsyewLPidq1CrToM4xuRNN1hMf3y +9aaYDoZ9cFO3Bklrjzu9AzUTHb5FEs7fzBoz+8y/3I4cmfCNw0rWkV+D4xuxACNG +VnehzuIFGDI1PlVcdJvNYWqgw/y1v/D3CzxJmqMAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAIEhcbIA== +-----END CERTIFICATE----- diff --git a/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ml_dsa_root.pem b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ml_dsa_root.pem new file mode 100644 index 0000000000..78853d00d4 --- /dev/null +++ b/pkix/src/test/resources/org/bouncycastle/cert/test/delta/ml_dsa_root.pem @@ -0,0 +1,136 @@ +-----BEGIN CERTIFICATE----- +MIIZCDCCDAWgAwIBAgIUFWd6hCxGhDNL+S1OL3UY7w+psbQwCwYJYIZIAWUDBAMS +MIGMMQswCQYDVQQGEwJYWDE1MDMGA1UECgwsUm95YWwgSW5zdGl0dXRlIG9mIFB1 +YmxpYyBLZXkgSW5mcmFzdHJ1Y3R1cmUxKzApBgNVBAsMIlBvc3QtSGVmZmFsdW1w +IFJlc2VhcmNoIERlcGFydG1lbnQxGTAXBgNVBAMMEE1MLURTQSBSb290IC0gRzEw +HhcNMjQxMDE3MjMzNzIzWhcNMzQxMDE1MjMzNzIzWjAvMQswCQYDVQQGEwJYWDEP +MA0GA1UECgwGSGFuYWtvMQ8wDQYDVQQLDAZZYW1hZGEwggeyMAsGCWCGSAFlAwQD +EgOCB6EA/a6iHTzCfanvaHi8GU+U+oX5nDkvkSj/c/eGnGt0f70YDjvXoNmwXSxI +pFHz7mLnmJ09lEI2O1OGLgUFjAYdubQRMlvjj0OzZjD4gJhs/c6G8B2loKtd6aOW +t4KPPVpmmvXaOFwFeU3NVq+JYZh8Uk7dCQ6PNC6FqIirE+5X8EqoG1SvOe8jYDt+ +KVu7Q9VKSNMEwZYoa9lE/JDlQ+CTr3LsC4XbpHGFzxlbXBz2hPv9Rq+K5JGKZ8Xe +WiEvJ0gwU9BuEJ1zwA/mKO/gmYcxFwVT24aaoW4nDwZ4eyUmDxdH6y1PK7Anwbbm +Izis+50FisFbSCv+FCg+M4Bwa+VFLcnG2RB31dwR6Qx7WOyMhYEXycQIPwD1GRLO +zJopFVAoeWFIUec28gSLPG/a6WtZthVf3AwNlEU9q5GVMyNXi4wikwr3oMW0JHea +Muv1dN+QEHPKFUP/pVdrux+39EdUP2Ydh0m4xB4cPTYD3b0PEtNvlwWvprP1S6yE +GbbFNCqXKoPiGLeTgEiKIzDr9b0DxFMQhjzHBEKxnTbpFpYTuFuUApUAnmm6DzUj +o1V1RdsIqG5B1ZEGaJxHkBZle7Xr6ALw9Pr8ypmaUNnjq9E4ZxoqBWhuWQLsomB3 +gLXrXcTTZGo/Yr603KZacjL0fitoplczRu91crEqLV4d7s1jNZKKRC+0p2cYDcIn +ktjgf8ypkgElWo+GdgoMmUdqtzpORIbq3pWV3AJfL9PU8tB6KTCN86Rxb/syTG7Y +53TLW67qyY6xY/BGvdxtdjw7zNkkOhO6AUywFn8xi5+B9S3n11ICSXrn6Rpu+Qgt +z1GKl53ltc97Gv19eFn48u7uPwkqtHVyvRqCzEMBygZKcy2Weaij3gsXW+JWYxtP +zJgrn9fA3zGia9CWPe/+W0xGuIm0nXf4H85rrJ8Iwgh7lwlQeoWaXFIzxtj5YSks +ksZGy0YcW1QfmUGpeu5j6qLBuLfNyKgNpRxMbqC50UQh0hSJkOr9mwEPEL7A0LJG +SlRnqNo7gCmhxTRKyaNR3luLZbIJfj4j3ltlPCDCRBrIFXkTbAiE8tfillgWqnCK +phdQHtzLRvFPaFpCDMhXuAyjLXW/6JhERClap5dJFjYVH0YWvWffcRPChusVSSLh +lTGxD5QYe8S0EkECJ1ajlUCyRf1kOPejJSh/gsW0DLvYW3vIypDJhnDcD40CPqqz +B5YduFeFGkYLnJs6LA1JyosJGkblcUA5O+eqz7AIdK02GPLL5eDAeQ/HCXgIa8AN +nXa3eErpAv7V6TCIdUpUdAMzTSf1E5x30uas4PBbF85MZWTP5xH2eGHmaNvi2UQd +Zg3FVfWa4hv99IIlBPqDykd60RHKrWSXwB16R0zzzLy8vcIDPMrC9M2rOGkJF2w1 +KZ6u86/PGUVvwESxz+7jpxkMFdsgQ79ffhJYxjJNBY0EEe9C3vz4+vIDm0PW7YhR +BZ11pWYH+4v8WzhT1HmGIfq6QQYh9Pz9uHsNc9Pl5kTQu1jTgdSeqFbshUNWuvGo +LeGhoIC6fn5cYKJhKEslFl4fcJr5eQfVzwhXncZkloHgrrFYprv35Odqo/2AAPu6 ++ILsegIY+D809nrQWBsZLNs7gopYi68xHc/yA6vOFGu7hLk/6qeV8ZNr89aGQU3Q +WBLmFRCZ+c4325uNmr2uhZntOK2ELVDosHkMkxynQPKDXheUGhU2lP/3bT+aGsug +l+0eXYYrxR3qnc5fM8u9ntJUGDTV9z/CzcBovHdMJfR16gbs4Qi5tsrwp1Teu8cI +SKh1zgdlxXKk/F7D0q3xiMcS8RC4fp3wstOVzgaQNrJEgAcN3tNsblu1JYKoSwoe +Rg94FAvULY8PLlkntNvjWAqAQXr1UW/diWX20wSUG9qFCmyo/TFpUbXIUER1kwi4 +j/Ll5tLfziGWWsnAehE8heeZSkeKwa63ZBjUAZzQ2Ycohd3I+yzf3sbL6q4v4qtT +tpRSJh4f25YJEg4DPYCUxpS1ZQyhZ7yG77ylKgw2+pA1Kv3wArO/3pWff+NZoP9O +LKDrOmNY2ythYRxjfvwerjAl93vcnqm/t84XY1PNWk4uvf5M3ZqBF4skeMAtTdsD +y1ROQuAMBvnuXdg58cBDe6RSInoJyn8sZYILyveHt9bK4E9O3icOfCMaCweeJ30x +SDOrW9bdB7jA3WHqzSrg1NqJJGUwCQTYdmbACzOsiDaduUZAB4BaD666bzcSUjHf +QEN5/930H4wFNyRBAcrjlyJ0s3SCDG+8RX0EVN8QFt+A+0VFPpkTeIqsOzHaSwjs +WhALemYVCFpuqCc9ILDh7LmGNPkAUFpVjCGOWiNTxP1jhiQWp/gR7fF3Y/8tpFF0 +/Le6X7p4VysXETscgXtopK/eT4eRo08wI2bkR7V8E9eiV+djFJw9uiHxmYH2HN2X +xVNWRGnpZRUiHzHIm0mQwmaamkaz+v8D8zNa2EC8PNcE1UAjqiKEcxOm3pBcFozT +BnDx5gJ0zcOP29+DZWKDNNHwr+ldHK51ttXeBn44LVC7CsG8CcN+/hMK0oGs7ivE +eC4YVfpeimX5k4ZfG0BfQAEVSUkgQL5d0VyW3Ceiunzc4wbYHTOjggNDMIIDPzAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUmwe0pHXE +vJFdNeDJocFi4ndV1j8wHwYDVR0jBBgwFoAUmwe0pHXEvJFdNeDJocFi4ndV1j8w +ggLaBgpghkgBhvprUAYBBIICyjCCAsYCFAwkDuI+vCXkurYIEro2dlv/uUTAoAww +CgYIKoZIzj0EAwShgY4wgYsxCzAJBgNVBAYTAlhYMTUwMwYDVQQKDCxSb3lhbCBJ +bnN0aXR1dGUgb2YgUHVibGljIEtleSBJbmZyYXN0cnVjdHVyZTErMCkGA1UECwwi +UG9zdC1IZWZmYWx1bXAgUmVzZWFyY2ggRGVwYXJ0bWVudDEYMBYGA1UEAwwPRUNE +U0EgUm9vdCAtIEcxo4GOMIGLMQswCQYDVQQGEwJYWDE1MDMGA1UECgwsUm95YWwg +SW5zdGl0dXRlIG9mIFB1YmxpYyBLZXkgSW5mcmFzdHJ1Y3R1cmUxKzApBgNVBAsM +IlBvc3QtSGVmZmFsdW1wIFJlc2VhcmNoIERlcGFydG1lbnQxGDAWBgNVBAMMD0VD +RFNBIFJvb3QgLSBHMTCBmzAQBgcqhkjOPQIBBgUrgQQAIwOBhgAEAQBWBqe/Q4Q1 +JyfnroW1iKkTDwv2CcjHF6ecRBfenEI4tqznJL3KkJIahCtrqV3Ei2nJSJEtekRB +WYE9Kt7ztptcAIV8Xinj7DC9hIgjECBAK17BMAgxrvqncZjdpR1EDboorK5IoEXV +yCx2gF3X07QL6aKbAHIZ5vr1GxzWr3MVUYytpFIwUDAOBgNVHQ8BAf8EBAMCAQYw +HQYDVR0OBBYEFOuj0ItR/hLczCFmh4UPmMdnc4g0MB8GA1UdIwQYMBaAFOuj0ItR +/hLczCFmh4UPmMdnc4g0A4GLADCBhwJBSedLEjpfk08YZ62kFSQSHccgNOtbbh0+ +3HvjCZYA3Ct6OxtLRK9uKmdAk9BeNO/xpcOUMAyI8odp2jmoIlcy9TcCQgCYNtGZ +6+1o1RDSTp73sJZzy1M8TuBejmKoUPQ1T2/bQdXfPu+gRTx9gPrkDUDLdVDvqcLx +bxPhPVp+9EIuK3rCjTALBglghkgBZQMEAxIDggzuAKKWJqZR+Ce+zJlGjCzLJWmx +/c3mxMug0vo1NtheVQ4Id3Lnhv5yimxnGXCdtkCcRyQGef6ku2gpf6AeSTBaA9sa +C3d8sB1HLTlPnwBXTWJ0xgp0kGVqCfwrbeRdCsoFrRoz1V2ETBecFehgQFHYLWtO +Q/VZrXPpwUxjIJRpSdxIw3SCsADjT/cQI9CQl5riMFOsZedRRPxSpw6lAGo557Ul +IgsxXA90mZQvRONY3mh8YkDT5uxQV0xRlyLLcZ3dxkzKgZrndz9F1yPrDGA0ixdk +F+3u4mxt8BJYZyRA2UeLEPG0OAIORmCeNuuixnFytGkctTd83GHeAszUtSanOyIU +JSomB/9G/omW3TU8uI8zWFuW+Fac8kpcNIECMujWUpB4RlxTWC/eTqrSiH7leE41 +aCaZC8Hd1jwTEK2xvPC8KCI/apk71rnmX4KFOCgG8FirIw/Usv6mnqt2G65nNlde +7gWS8XoMFJDtYWDUpkgwRwLHvBNvKK/WikRDG3pSI8E1UyU1MU5R1JQnQRgzjazR +5lWhsMLrYoC+wi+XKNkFjeKVbgoiVoAD3ZKGnkJvIEueilGEWTYoTiobKBHzDjI3 +b9x0GuBU0Z/MiRsycsDJUrl8hK8kpgBAS7ENTaowGdE9KhiqzY4xX83vgjy0bDL4 +X9+2CXuQtFR5QotYapjA1HJUM5UuB5ix7i32dbZfnrJOZqcgocWuFRkShsAAu/wH +wFeeiJodlAlFVh3onDgh76316MewB/VLpM3G4EctzI9i5xqJzKXjlKWXP9ZjW/Sd +50R42fe6AaUqN4DaNbwOQaBs48auupU+EK6NytQl9rCeCJ4gicnM1no4QQbcwecZ +VvrrCs8egd3hawzMuCRhKeNzaYVeqnWhsRWdLxJANa07ANQqgXLhSx7vDBLiIQLA +UNqNYndYjEG3jirFxITUtHcz4ekZC7hpGkbl5qabQvrlk6lJ7yfuNuoO5jcCKY/C +BbOluVgjOeYeBfqJ9u9MwMcTUs26DkpW9h5YXIXATBj9dI3Tzp6fb9qtg9zBTHap +JKwmbUbgbPJSabtFMwh5XUpIpsJ+Mujek4uQ2GNaA6YfitHeDP91DM9ZUVFM7/5/ +0BysQZLfD3SDO2Q/TnCug4XlCy0Z8ChnCBRGldqU1cMKPszXviLauBoM6aiLx7Lf +feuMxZVWJ1xC3crrP4OXpEO7IkIsDeKoVBBdkhV9RuD394h7jSCljMEVCYKCRUWV +mvffcmJNxfIfTgeLboHiAu0vDjE6s9vrcUASTDTgXuooy3rQ4q4fkWvV+cLPCZH9 +sRZQvGcziMWrubTPa3WuVG9FHmejYcTsRTIxl1IlU8IjgW5hzwdmiZKI9cnCPqxy +a+uSk7K/by9rG4msxklsijdQ8CRg3V4mgNW5FTa6hXpfabmYWEZetYzJ7CISueCH +RtevtYz5HTARC5KB2CcYMV3Cz1AaIxd29lZpWJFd8sWLN50P/1KBanqeFfqXgIuW +RVE26I1IyMrrxzPUN6F+C7AWEEFGI5rue3M2EdIAAP3Sv6paLut9cESLS8zQBz8J +nL+RXsvL3ctYW5XbcuDIFJaIAENJArveEI4u4Oyvxyz0bp5JmS8tpRTWUoRWBt9B +hAp4axTi2eUWn6XHCBTG5DIyi4i+Tz8yt+zkBLdCh/b/UgxVtH6O5jcrOc9j0kb7 +IJGacW71sE/sM0xCLFvqo2pEaKrt2dF+3/sK9TsT8TCisrEC4iCeSWt/I6Jb1RIc +TjBIt+yP/0u+B/pZVs9sUQpNkgkUmxAgJsuhH9PkIV+26vijDppKSgod4CrlCrkE +gvUe55DhUTx7bi2TNNUwQNRY8KeGsJMEOap6TIV0MdEnvRqpnVpWlYWSIpC4lJFH +uEPkkfumLKphH+ZrComFg/8Ys0ApNiGpAIIDngUkOvUggT51vyk5EnzJs7n6XQoI +cnJ+nax/+bLC9UHo6llqmggUXOUnRupclyJUo99uafwyoCw/8y43OI4s7CffQZ9U +JJLOT5WvoFXLqZlLl99CmQRZ/+0CEObOxsf5zmt2YbKKLVh1xZCyOyglODG5fU1O +a+droWi/K/Y8EN2TFYC9278AC9TVFhY7QoMhn1eG3Lc5cNfL5G5aPcbIybJUJ1XT +17wHKrExmRG8/itNHB7Yh4uetwumgls+vWL/QpCepU3kTMc4yXMnuYkmqmA4vW/B +vy4CCSarPjUCoF7hyfPSEv2fI1iTleJl5lDNsII8uz2zW2kNGK9RVKNPkMAW5EqR +nVGdt6TzpNlRtBo8ZZbV6g00+ZRKrW0iXfYRv6jT0+02/BjCA4sr+KwwTS70oU0s +MIsgfLFRWUP2swV3oUsGrxL+r8OckzqTmRzMMk0MCiIm6Tg2DSBhiMF9Sn8cajIW +PVpBZoPlmPz3S0LqMH4KFRHqx8HIcRUKdRSItOn7h7kZEl4dkrY6HehbZd/s0h4Z +EIUotKN/Ls8NbS+NqxvKkiu/udt+tGjWzlauHR1I8b4uyJMoE1A+pJS5A5AdXPsr +q0Nj3cHhvZCSdbsFH4pWd7m90EWc4e54EX6NHnFUlvypjmQ5rXAIdNn3uMQ9hD9F +BQjDa9p5KI8bTvQBojS1fuOKR2wTqjCFVAjnnTgQ1xvDtIdBDPpfFwB/fIvh2wRi +tnu/9bs4suGX7yXWIAg+KopJUL5AjF8QUyOPzDVAVHQk+rRjg2rcb4b72dR56o8F +Y8GvdTAJGKApxFFKXk+YRYXUBczoaV6XG3J4+pieHv10P/wNrua2nKotTNgQ3X3e +Lg8BYMejeUAFyaLSn/taMsCwDAQfEIExx8wCB3ySp7oa0l70V2IjXReTijM8M2Yf +osYQ6KX01GyP01BGPiLj4Z2CeAr7y7QH5qkWBIQNOPEOMpC/3lKfWgF0GUrW1qzD +lxRSRcqYrmvWpT3tZYftGt1WqpFHi6N4R09KaLrEEgF57CYfKrQJisBKehm63v5A +2Pbc9mRsbCz1KSP0dtKSaXhaMBSbs/AflAOEniA45ZozFQHIp2VIgvYVxe0kV+i4 +0UOGBb4eckx8jfXr9zG1MyLCmc3tBEDZIIicJSaqGA4lRpKQoGbHOxGEEgvWi46e +pRUpsCh7xP9k4bwrAGiFUOsq+NneS0DL5/iosSwjVlrF1CKjpG6zvTNgtSgQ0WL0 +5/1f/gH9KJDyzVukKsl8xfK/EQw7q9zNxlw3DdqX0Gh74+AwLpUCMIen4+XgKxTD +9qLphL/gsWtncpaK2buRmQii2++Px8+8XbrReAENjLfuEH4m1Pnqo/tVtGpt2JOv +KrtM7Abj9ZRcxVthhy+K6cZwC9qcFSeuswcU81bqpJ4pmEcgCbd+DnqMBBMJsJHs +wKrhY4VaOpKt15lWQzqaHV2+S9uVmhS48aIUw4GWhfuwWLVwTACEtUvqPR8eK1n/ +MLP0tmLlc2igdIQ0+Rj+27GJOm4sWx58kEnOlO1E5AlaMmoclJuVtwn7LSjdLY6/ +HVBYST10of4OwXTk6reKpZnfzwI4Jb1Ml6MKyujGrBHfFpF0ezY8gGnhUif+GeCa +A5qySvwYq7dHpbhBsWFZXf5coK5xCUX7MblWY1kzDXqKr0dTiSHL0AxKD5DORpal +poSnF1auJcqwyoPDvtJxG/k2pWZD6206v6o/Ed2VItKgzeRQBznFCLhAbKSZKSjQ +VDT8HpX1xoakWvXrmE5g0/2UVQu39MuHkoXV3MwG45N/03fyUsR+MAAvyjfOqlmb +8UFQYGdAeA/P5+60DRCtC/v/9jlWj+uDDbyUD5rYlO9kLKlxmKgdH2LHerJ63Y4a +0P4PvBNYiPevrvN9WO5f0Z5N/fMwz88gm8Q2TVt3kJqHPj9SFI1e/KVOCZQlNTLh +ewnrNZZAjP9yQGbxnIgeiftnSmBM/30VxCgDv1+hE1FeG2jm4URgsiIu53rX6Ac7 +HUl48/QWIXHMUQxSWXeXxGKI+SaVFRrM+5DCjWxW4bM190Joj21R7dBRfCbmdLrI +y6uhLJqKtZ+imkZnGpd33lWBJp9wuOVSEJWiS2Jwj4sgdrywD1mSPkyG2oXZOLUL +A3e8SFVGQaI7aFwG7wiRibgnuLz1omU/n46f02Gjj/0kSkqlhWIT7rqKkRYimMhE +6PTVRRLDmFK6OhK2WSCDIXGkQxv/pD5TOL0bjchj/FF9sQhDhG7W8IPOLMrtRsmK +PHfQ4l6+SUMo+tVNfo87m6uQismTwSu6nt4X+CNFvb5bY9Apltg5HAkTInJ41ed+ +Shu2siOaLEbfQ3rjeeyTwuCnn8NPOe3VBLfhEvznBR+wCQA7W6/UiUoJCZgZwQkP +pGbnhaBP+YJF9ypE/mS0RGhti6UGKS9QWXaH9h4hVlt3krr4IiVYgpGetb/vCA5d +fYAjMD9K/AAAAAAAAAAAAAAAAAAAAAUNFR4jKA== +-----END CERTIFICATE----- diff --git a/pkix/src/test/resources/org/bouncycastle/cms/test/bc1639test.p7m b/pkix/src/test/resources/org/bouncycastle/cms/test/bc1639test.p7m new file mode 100644 index 0000000000..02f0cf9b79 Binary files /dev/null and b/pkix/src/test/resources/org/bouncycastle/cms/test/bc1639test.p7m differ diff --git a/prov/build.gradle b/prov/build.gradle index d9c620fd01..c0b531d054 100644 --- a/prov/build.gradle +++ b/prov/build.gradle @@ -3,16 +3,18 @@ plugins { } dependencies { - implementation project(':core') testImplementation files('../libs/unboundid-ldapsdk-6.0.8.jar') } -jar.archiveBaseName = "bcprov-$vmrange" +evaluationDependsOn(":core") sourceSets { main { java { - srcDirs '../core/src/main/java' + srcDirs "${project(":core").projectDir}/src/main/java" + } + resources { + srcDirs "${project(":core").projectDir}/src/main/resources" } } @@ -40,6 +42,7 @@ sourceSets { } dependencies { + java9Implementation files([sourceSets.main.output.classesDirs]) { builtBy compileJava } @@ -66,53 +69,35 @@ dependencies { } } + compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + options.release = 8; } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + options.release = 9 options.sourcepath = files(['../core/src/main/java', 'src/main/java', 'src/main/jdk1.9']) } compileJava11Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 11 - targetCompatibility = 11 + options.release = 11 options.sourcepath = files(['src/main/java', 'src/main/jdk1.11']) } compileJava15Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 15 - targetCompatibility = 15 + options.release = 15 options.sourcepath = files(['src/main/java', 'src/main/jdk1.15']) } compileJava21Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(21) - } - sourceCompatibility = 21 - targetCompatibility = 21 + options.release = 21 options.sourcepath = files(['src/main/java', 'src/main/jdk21']) } task sourcesJar(type: Jar) { - archiveBaseName = jar.archiveBaseName + archiveBaseName="bcprov" + archiveAppendix="${vmrange}" archiveClassifier = 'sources' from sourceSets.main.allSource exclude("**/*.so") @@ -131,6 +116,9 @@ task sourcesJar(type: Jar) { } jar { + jar.archiveBaseName="bcprov" + jar.archiveAppendix="${vmrange}" + from sourceSets.main.output into('META-INF/versions/9') { from sourceSets.java9.output @@ -144,17 +132,21 @@ jar { into('META-INF/versions/21') { from sourceSets.java21.output } + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bcprov') manifest.attributes('Bundle-SymbolicName': 'bcprov') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': '!org.bouncycastle.internal.*,org.bouncycastle.*') + manifest.attributes('Export-Package': "!org.bouncycastle.internal.*,org.bouncycastle.*;version=${v}") manifest.attributes('Import-Package': 'java.*;resolution:=optional,javax.*;resolution:=optional') + manifest.attributes('Bundle-Version': "${v}") + } task javadocJar(type: Jar, dependsOn: javadoc) { - archiveBaseName = jar.archiveBaseName + archiveBaseName="bcprov" + archiveAppendix="${vmrange}" archiveClassifier = 'javadoc' from javadoc.destinationDir } @@ -172,15 +164,15 @@ sourceSets { java { compileClasspath += main.output + test.output runtimeClasspath += test.output - srcDir(files("src/test/jdk1.11", "src/test/java")) + srcDir(files("src/test/jdk1.11")) } } - test17 { + test15 { java { compileClasspath += main.output + test.output runtimeClasspath += test.output - srcDir(files("src/test/jdk1.11","src/test/jdk1.15", "src/test/java")) + srcDir(files("src/test/jdk1.15")) } } @@ -188,20 +180,20 @@ sourceSets { java { compileClasspath += main.output + test.output runtimeClasspath += test.output - srcDir(files("src/test/jdk1.11","src/test/jdk1.15","src/test/jdk21", "src/test/java")) + srcDir(files("src/test/jdk21")) } } } dependencies { test11Implementation group: 'junit', name: 'junit', version: '4.13.2' - test17Implementation group: 'junit', name: 'junit', version: '4.13.2' + test15Implementation group: 'junit', name: 'junit', version: '4.13.2' test21Implementation group: 'junit', name: 'junit', version: '4.13.2' test11Implementation files('../libs/unboundid-ldapsdk-6.0.8.jar') - test17Implementation files('../libs/unboundid-ldapsdk-6.0.8.jar') + test15Implementation files('../libs/unboundid-ldapsdk-6.0.8.jar') test21Implementation files('../libs/unboundid-ldapsdk-6.0.8.jar') test11Implementation(project(":core")) - test17Implementation(project(":core")) + test15Implementation(project(":core")) test21Implementation(project(":core")) } @@ -209,39 +201,73 @@ dependencies { compileTest11Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 11 - targetCompatibility = 11 + options.release = 11 options.sourcepath = files(['src/test/java', 'src/test/jdk1.11']) } -compileTest17Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 17 - targetCompatibility = 17 +compileTest15Java { + options.release = 15 options.sourcepath = files(['src/test/java', 'src/test/jdk1.15']) } compileTest21Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(21) - } - sourceCompatibility = 21 - targetCompatibility = 21 + options.release = 21 options.sourcepath = files(['src/test/java', 'src/test/jdk21']) } +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcprov-$vmrange" + from components.java + + artifact(javadocJar) + artifact(sourcesJar) + } + + } +} + + test { - jvmArgs = ['-Dtest.java.version.prefix=1.8'] + jvmArgs = ['-Dtest.java.version.prefix=any'] } -task test11(type: Test) { +task test8(type: Test) { + onlyIf {System.getenv("BC_JDK8") != null} + dependsOn(jar) + + testClassesDirs = sourceSets.test.output.classesDirs + classpath = sourceSets.test.runtimeClasspath + files(jar.archiveFile) + + forkEvery = 1; + maxParallelForks = 8; + systemProperty 'bc.test.data.home', bcTestDataHome + maxHeapSize = "1536m" + testLogging.showStandardStreams = false + + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(8) + } + + jvmArgs = ['-Dtest.java.version.prefix=1.8'] + + + finalizedBy jacocoTestReport + + filter { + includeTestsMatching "AllTest*" + if (project.hasProperty('excludeTests')) { + excludeTestsMatching "${excludeTests}" + } + } +} + +task test11(type: Test) { + onlyIf {System.getenv("BC_JDK11") != null} dependsOn(jar) testClassesDirs = sourceSets.test11.output.classesDirs @@ -252,13 +278,13 @@ task test11(type: Test) { systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(11) } - jvmArgs = ['-Dtest.java.version.prefix=11.'] + jvmArgs = ['-Dtest.java.version.prefix=11'] finalizedBy jacocoTestReport @@ -271,27 +297,27 @@ task test11(type: Test) { } } -task test17(type: Test) { +task test15(type: Test) { // This is testing the 1.15 code base - + onlyIf {System.getenv("BC_JDK17") != null} dependsOn jar - testClassesDirs = sourceSets.test17.output.classesDirs - classpath = sourceSets.test17.runtimeClasspath + files(jar.archiveFile) + testClassesDirs = sourceSets.test15.output.classesDirs + classpath = sourceSets.test15.runtimeClasspath + files(jar.archiveFile) forkEvery = 1; maxParallelForks = 8; systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(17) } - jvmArgs = ['-Dtest.java.version.prefix=17.'] + jvmArgs = ['-Dtest.java.version.prefix=17'] finalizedBy jacocoTestReport @@ -307,7 +333,7 @@ task test17(type: Test) { task test21(type: Test) { // This is testing the 21 code base - + onlyIf {System.getenv("BC_JDK21") != null} dependsOn jar testClassesDirs = sourceSets.test21.output.classesDirs @@ -318,7 +344,7 @@ task test21(type: Test) { systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) @@ -336,3 +362,27 @@ task test21(type: Test) { } } } + +if (System.getenv("BC_JDK8") != null) { + System.out.println("${project.name}: Adding test8 as dependency for test task because BC_JDK8 is defined") + test.dependsOn("test8") +} + +if (System.getenv("BC_JDK11") != null) { + System.out.println("${project.name}: Adding test11 as dependency for test task because BC_JDK11 is defined") + test.dependsOn("test11") +} + +if (System.getenv("BC_JDK17") != null) { + System.out.println("${project.name}: Adding test15 as dependency for test task because BC_JDK17 is defined") + test.dependsOn("test15") +} + +if (System.getenv("BC_JDK21") != null) { + System.out.println("${project.name}: Adding test21 as dependency for test task because BC_JDK21 is defined") + test.dependsOn("test21") +} + + + + diff --git a/prov/src/main/ext-jdk1.9/module-info.java b/prov/src/main/ext-jdk1.9/module-info.java index 87c7f33c1d..b4f0ba7462 100644 --- a/prov/src/main/ext-jdk1.9/module-info.java +++ b/prov/src/main/ext-jdk1.9/module-info.java @@ -8,6 +8,9 @@ opens org.bouncycastle.jcajce.provider.asymmetric.edec to java.base; opens org.bouncycastle.pqc.jcajce.provider.lms to java.base; + opens org.bouncycastle.jcajce.provider.asymmetric.mldsa to java.base; + opens org.bouncycastle.jcajce.provider.asymmetric.mlkem to java.base; + opens org.bouncycastle.jcajce.provider.asymmetric.slhdsa to java.base; exports org.bouncycastle; exports org.bouncycastle.asn1; @@ -110,20 +113,22 @@ exports org.bouncycastle.pqc.crypto.bike; exports org.bouncycastle.pqc.crypto.cmce; exports org.bouncycastle.pqc.crypto.crystals.dilithium; - exports org.bouncycastle.pqc.crypto.crystals.kyber; + exports org.bouncycastle.pqc.crypto.mldsa; + exports org.bouncycastle.pqc.crypto.mlkem; exports org.bouncycastle.pqc.crypto.falcon; exports org.bouncycastle.pqc.crypto.frodo; - exports org.bouncycastle.pqc.crypto.gemss; + exports org.bouncycastle.pqc.legacy.crypto.gemss; exports org.bouncycastle.pqc.crypto.hqc; exports org.bouncycastle.pqc.crypto.lms; + exports org.bouncycastle.pqc.crypto.mayo; exports org.bouncycastle.pqc.crypto.newhope; exports org.bouncycastle.pqc.crypto.ntru; exports org.bouncycastle.pqc.crypto.ntruprime; exports org.bouncycastle.pqc.crypto.picnic; - exports org.bouncycastle.pqc.crypto.rainbow; exports org.bouncycastle.pqc.crypto.saber; exports org.bouncycastle.pqc.crypto.sphincs; exports org.bouncycastle.pqc.crypto.sphincsplus; + exports org.bouncycastle.pqc.crypto.snova; exports org.bouncycastle.pqc.crypto.util; exports org.bouncycastle.pqc.crypto.xmss; exports org.bouncycastle.pqc.math.ntru; diff --git a/prov/src/main/java/org/bouncycastle/jcajce/CompositePrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/CompositePrivateKey.java index e0831e7b59..4abe0d3a4a 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/CompositePrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/CompositePrivateKey.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.security.PrivateKey; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -14,9 +13,10 @@ import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; -import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeSignaturesConstants; +import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeIndex; import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.KeyFactorySpi; import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Exceptions; /** @@ -75,7 +75,7 @@ public CompositePrivateKey(PrivateKeyInfo keyInfo) ASN1ObjectIdentifier keyInfoIdentifier = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); try { - if (!Arrays.asList(CompositeSignaturesConstants.supportedIdentifiers).contains(keyInfoIdentifier)) + if (!CompositeIndex.isAlgorithmSupported(keyInfoIdentifier)) { throw new IllegalStateException("Unable to create CompositePrivateKey from PrivateKeyInfo"); } @@ -108,7 +108,7 @@ public List getPrivateKeys() public String getAlgorithm() { - return CompositeSignaturesConstants.ASN1IdentifierAlgorithmNameMap.get(this.algorithmIdentifier).getId(); + return CompositeIndex.getAlgorithmName(this.algorithmIdentifier); } public ASN1ObjectIdentifier getAlgorithmIdentifier() @@ -132,18 +132,40 @@ public byte[] getEncoded() { ASN1EncodableVector v = new ASN1EncodableVector(); - for (int i = 0; i < keys.size(); i++) + if (algorithmIdentifier.equals(MiscObjectIdentifiers.id_composite_key)) { - v.add(PrivateKeyInfo.getInstance(keys.get(i).getEncoded())); - } + for (int i = 0; i < keys.size(); i++) + { + PrivateKeyInfo info = PrivateKeyInfo.getInstance(keys.get(i).getEncoded()); + v.add(info); + } - try - { - return new PrivateKeyInfo(new AlgorithmIdentifier(this.algorithmIdentifier), new DERSequence(v)).getEncoded(ASN1Encoding.DER); + try + { + return new PrivateKeyInfo(new AlgorithmIdentifier(this.algorithmIdentifier), new DERSequence(v)).getEncoded(ASN1Encoding.DER); + } + catch (IOException e) + { + throw new IllegalStateException("unable to encode composite private key: " + e.getMessage()); + } } - catch (IOException e) + else { - throw new IllegalStateException("unable to encode composite private key: " + e.getMessage()); + byte[] keyEncoding = null; + for (int i = 0; i < keys.size(); i++) + { + PrivateKeyInfo info = PrivateKeyInfo.getInstance(keys.get(i).getEncoded()); + keyEncoding = Arrays.concatenate(keyEncoding, info.getPrivateKey().getOctets()); + } + + try + { + return new PrivateKeyInfo(new AlgorithmIdentifier(this.algorithmIdentifier), keyEncoding).getEncoded(ASN1Encoding.DER); + } + catch (IOException e) + { + throw new IllegalStateException("unable to encode composite private key: " + e.getMessage()); + } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/CompositePublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/CompositePublicKey.java index 1bc8a6e634..39e4564fa0 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/CompositePublicKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/CompositePublicKey.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.security.PublicKey; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -14,7 +13,7 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; -import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeSignaturesConstants; +import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeIndex; import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.KeyFactorySpi; import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; @@ -75,7 +74,7 @@ public CompositePublicKey(SubjectPublicKeyInfo keyInfo) try { //Check if the public key algorithm specified in SubjectPublicKeyInfo is one of the supported composite signatures. - if (!Arrays.asList(CompositeSignaturesConstants.supportedIdentifiers).contains(keyInfoIdentifier)) + if (!CompositeIndex.isAlgorithmSupported(keyInfoIdentifier)) { throw new IllegalStateException("unable to create CompositePublicKey from SubjectPublicKeyInfo"); } @@ -108,7 +107,7 @@ public List getPublicKeys() public String getAlgorithm() { - return CompositeSignaturesConstants.ASN1IdentifierAlgorithmNameMap.get(this.algorithmIdentifier).getId(); + return CompositeIndex.getAlgorithmName(this.algorithmIdentifier); } public ASN1ObjectIdentifier getAlgorithmIdentifier() diff --git a/prov/src/main/java/org/bouncycastle/jcajce/MLDSAProxyPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/MLDSAProxyPrivateKey.java new file mode 100644 index 0000000000..9074b56723 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/MLDSAProxyPrivateKey.java @@ -0,0 +1,73 @@ +package org.bouncycastle.jcajce; + +import java.security.PublicKey; + +import org.bouncycastle.jcajce.interfaces.MLDSAPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLDSAPublicKey; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; + +/** + * An ML-DSA private key wrapper which acts as a proxy to allow an ML-DSA public key + * to be passed in for external-mu calculation. + */ +public class MLDSAProxyPrivateKey + implements MLDSAPrivateKey +{ + private final MLDSAPublicKey publicKey; + + public MLDSAProxyPrivateKey(PublicKey publicKey) + { + if (!(publicKey instanceof MLDSAPublicKey)) + { + throw new IllegalArgumentException("public key must be an ML-DSA public key"); + } + this.publicKey = (MLDSAPublicKey)publicKey; + } + + public MLDSAPublicKey getPublicKey() + { + return publicKey; + } + + @Override + public String getAlgorithm() + { + return publicKey.getAlgorithm(); + } + + @Override + public String getFormat() + { + return null; + } + + @Override + public byte[] getEncoded() + { + return new byte[0]; + } + + @Override + public MLDSAParameterSpec getParameterSpec() + { + return publicKey.getParameterSpec(); + } + + @Override + public byte[] getPrivateData() + { + return new byte[0]; + } + + @Override + public byte[] getSeed() + { + return new byte[0]; + } + + @Override + public MLDSAPrivateKey getPrivateKey(boolean preferSeedOnly) + { + return null; + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/PKCS12StoreParameter.java b/prov/src/main/java/org/bouncycastle/jcajce/PKCS12StoreParameter.java index b53eca5aad..2541e65e0a 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/PKCS12StoreParameter.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/PKCS12StoreParameter.java @@ -17,6 +17,7 @@ public class PKCS12StoreParameter private final OutputStream out; private final ProtectionParameter protectionParameter; private final boolean forDEREncoding; + private final boolean overwriteFriendlyName; public PKCS12StoreParameter(OutputStream out, char[] password) { @@ -25,19 +26,29 @@ public PKCS12StoreParameter(OutputStream out, char[] password) public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter) { - this(out, protectionParameter, false); + this(out, protectionParameter, false, true); } public PKCS12StoreParameter(OutputStream out, char[] password, boolean forDEREncoding) { - this(out, new KeyStore.PasswordProtection(password), forDEREncoding); + this(out, new KeyStore.PasswordProtection(password), forDEREncoding, true); } - public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter, boolean forDEREncoding) + { + this(out, protectionParameter, forDEREncoding, true); + } + + public PKCS12StoreParameter(OutputStream out, char[] password, boolean forDEREncoding, boolean overwriteFriendlyName) + { + this(out, new KeyStore.PasswordProtection(password), forDEREncoding, overwriteFriendlyName); + } + + public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter, boolean forDEREncoding, boolean overwriteFriendlyName) { this.out = out; this.protectionParameter = protectionParameter; this.forDEREncoding = forDEREncoding; + this.overwriteFriendlyName = overwriteFriendlyName; } public OutputStream getOutputStream() @@ -59,4 +70,15 @@ public boolean isForDEREncoding() { return forDEREncoding; } + + /** + * Return whether the KeyStore used with this parameter should overwrite friendlyName + * when friendlyName is not present or does not equal the same name as alias + * + * @return true (default) to overwrite friendlyName, false otherwise, + */ + public boolean isOverwriteFriendlyName() + { + return overwriteFriendlyName; + } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/PKIXCRLStoreSelector.java b/prov/src/main/java/org/bouncycastle/jcajce/PKIXCRLStoreSelector.java index e7dbcce0f8..b82b7ca616 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/PKIXCRLStoreSelector.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/PKIXCRLStoreSelector.java @@ -185,45 +185,44 @@ public boolean match(CRL obj) } X509CRL crl = (X509CRL)obj; - ASN1Integer dci = null; - try + + // TODO[pkix] Do we always need to parse the Delta CRL Indicator extension? { - byte[] bytes = crl - .getExtensionValue(Extension.deltaCRLIndicator.getId()); - if (bytes != null) + ASN1Integer baseCRLNumber = null; + try { - dci = ASN1Integer.getInstance(ASN1OctetString.getInstance(bytes).getOctets()); + byte[] dci = crl.getExtensionValue(Extension.deltaCRLIndicator.getId()); + if (dci != null) + { + baseCRLNumber = ASN1Integer.getInstance(ASN1OctetString.getInstance(dci).getOctets()); + } } - } - catch (Exception e) - { - return false; - } - if (isDeltaCRLIndicatorEnabled()) - { - if (dci == null) + catch (Exception e) { return false; } - } - if (isCompleteCRLEnabled()) - { - if (dci != null) + + if (baseCRLNumber == null) { - return false; + if (isDeltaCRLIndicatorEnabled()) + { + return false; + } } - } - if (dci != null) - { - - if (maxBaseCRLNumber != null) + else { - if (dci.getPositiveValue().compareTo(maxBaseCRLNumber) == 1) + if (isCompleteCRLEnabled()) + { + return false; + } + + if (maxBaseCRLNumber != null && baseCRLNumber.getPositiveValue().compareTo(maxBaseCRLNumber) == 1) { return false; } } } + if (issuingDistributionPointEnabled) { byte[] idp = crl diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAKey.java new file mode 100644 index 0000000000..fe77659b2d --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAKey.java @@ -0,0 +1,16 @@ +package org.bouncycastle.jcajce.interfaces; + +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; + +import java.security.Key; + +public interface MLDSAKey + extends Key +{ + /** + * Return the parameters for this key. + * + * @return a MLDSAParameterSpec + */ + MLDSAParameterSpec getParameterSpec(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAPrivateKey.java new file mode 100644 index 0000000000..1f4224e461 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAPrivateKey.java @@ -0,0 +1,36 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.PrivateKey; + +public interface MLDSAPrivateKey + extends PrivateKey, MLDSAKey +{ + /** + * Return the public key corresponding to this private key. + * + * @return a ML-DSA Public Key + */ + MLDSAPublicKey getPublicKey(); + + /** + * Return the long form private data for the ML-DSA private key. + * + * @return long form private data for private key. + */ + byte[] getPrivateData(); + + /** + * Return the seed the private key was generated from (if available). + * + * @return the seed for the private key, null if not available. + */ + byte[] getSeed(); + + /** + * Return a privateKey which will encode as seed-only or as an expanded-key. + * + * @param preferSeedOnly if true, return a privateKey which will encode to seed-only if possible. + * @return a new MLDSAPrivateKey which encodes to either seed-only or expanded-key. + */ + MLDSAPrivateKey getPrivateKey(boolean preferSeedOnly); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAPublicKey.java new file mode 100644 index 0000000000..7b6593af15 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLDSAPublicKey.java @@ -0,0 +1,14 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.PublicKey; + +public interface MLDSAPublicKey + extends PublicKey, MLDSAKey +{ + /** + * Return the raw encoded data representing the public key: rho || t1. + * + * @return the concatenation of rho and t1. + */ + byte[] getPublicData(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMKey.java new file mode 100644 index 0000000000..5cfbafaba8 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMKey.java @@ -0,0 +1,16 @@ +package org.bouncycastle.jcajce.interfaces; + +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; + +import java.security.Key; + +public interface MLKEMKey + extends Key +{ + /** + * Return the parameters for this key. + * + * @return a MLKEMParameterSpec + */ + MLKEMParameterSpec getParameterSpec(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMPrivateKey.java new file mode 100644 index 0000000000..38ecf2bf06 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMPrivateKey.java @@ -0,0 +1,36 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.PrivateKey; + +public interface MLKEMPrivateKey + extends PrivateKey, MLKEMKey +{ + /** + * Return the public key corresponding to this private key. + * + * @return a ML-KEM Public Key + */ + MLKEMPublicKey getPublicKey(); + + /** + * Return the long form private data for the ML-KEM private key. + * + * @return long form private data for private key. + */ + byte[] getPrivateData(); + + /** + * Return the seed the private key was generated from (if available). + * + * @return the seed for the private key, null if not available. + */ + byte[] getSeed(); + + /** + * Return a privateKey which will encode as seed-only or as an expanded-key. + * + * @param preferSeedOnly if true, return a privateKey which will encode to seed-only if possible. + * @return a new MLKEMPrivateKey which encodes to either seed-only or expanded-key. + */ + MLKEMPrivateKey getPrivateKey(boolean preferSeedOnly); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMPublicKey.java new file mode 100644 index 0000000000..1554370d2a --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/MLKEMPublicKey.java @@ -0,0 +1,14 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.PublicKey; + +public interface MLKEMPublicKey + extends PublicKey, MLKEMKey +{ + /** + * Return the raw encoded data representing the public key: t || rho. + * + * @return the concatenation of t and rho. + */ + byte[] getPublicData(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAKey.java new file mode 100644 index 0000000000..aa2da41eaa --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAKey.java @@ -0,0 +1,16 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.Key; + +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; + +public interface SLHDSAKey + extends Key +{ + /** + * Return the parameters for this key. + * + * @return a SLHDSAParameterSpec + */ + SLHDSAParameterSpec getParameterSpec(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAPrivateKey.java new file mode 100644 index 0000000000..9fe8069967 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAPrivateKey.java @@ -0,0 +1,14 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.PrivateKey; + +public interface SLHDSAPrivateKey + extends PrivateKey, SLHDSAKey +{ + /** + * Return the public key corresponding to this private key. + * + * @return a SLH-DSA Public Key + */ + SLHDSAPublicKey getPublicKey(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAPublicKey.java new file mode 100644 index 0000000000..cb31a97339 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/interfaces/SLHDSAPublicKey.java @@ -0,0 +1,14 @@ +package org.bouncycastle.jcajce.interfaces; + +import java.security.PublicKey; + +public interface SLHDSAPublicKey + extends PublicKey, SLHDSAKey +{ + /** + * Return the raw encoded data representing the public key: seed || root. + * + * @return the concatenation of the seed and root values. + */ + byte[] getPublicData(); +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/COMPOSITE.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/COMPOSITE.java index b77e4a47db..c31ac8ce25 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/COMPOSITE.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/COMPOSITE.java @@ -8,16 +8,16 @@ import java.util.HashMap; import java.util.Map; -import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; -import org.bouncycastle.jcajce.CompositePrivateKey; -import org.bouncycastle.jcajce.CompositePublicKey; +import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.KeyFactorySpi; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; +import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; +import org.bouncycastle.jce.provider.BouncyCastleProvider; public class COMPOSITE { @@ -71,50 +71,6 @@ public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) } } - private static class CompositeKeyInfoConverter - implements AsymmetricKeyInfoConverter - { - private final ConfigurableProvider provider; - - public CompositeKeyInfoConverter(ConfigurableProvider provider) - { - this.provider = provider; - } - - public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) - throws IOException - { - ASN1Sequence keySeq = ASN1Sequence.getInstance(keyInfo.parsePrivateKey()); - PrivateKey[] privKeys = new PrivateKey[keySeq.size()]; - - for (int i = 0; i != keySeq.size(); i++) - { - PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(keySeq.getObjectAt(i)); - - privKeys[i] = provider.getKeyInfoConverter( - privInfo.getPrivateKeyAlgorithm().getAlgorithm()).generatePrivate(privInfo); - } - - return new CompositePrivateKey(privKeys); - } - - public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) - throws IOException - { - ASN1Sequence keySeq = ASN1Sequence.getInstance(keyInfo.getPublicKeyData().getBytes()); - PublicKey[] pubKeys = new PublicKey[keySeq.size()]; - - for (int i = 0; i != keySeq.size(); i++) - { - SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(keySeq.getObjectAt(i)); - - pubKeys[i] = provider.getKeyInfoConverter((pubInfo.getAlgorithm().getAlgorithm())).generatePublic(pubInfo); - } - - return new CompositePublicKey(pubKeys); - } - } - public static class Mappings extends AsymmetricAlgorithmProvider { @@ -130,7 +86,7 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("KeyFactory." + MiscObjectIdentifiers.id_composite_key, PREFIX + "$KeyFactory"); provider.addAlgorithm("KeyFactory.OID." + MiscObjectIdentifiers.id_composite_key, PREFIX + "$KeyFactory"); - baseConverter = new CompositeKeyInfoConverter(provider); + baseConverter = new KeyFactorySpi(new ProviderJcaJceHelper((BouncyCastleProvider)provider)); provider.addKeyInfoConverter(MiscObjectIdentifiers.id_alg_composite, baseConverter); provider.addKeyInfoConverter(MiscObjectIdentifiers.id_composite_key, baseConverter); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CONTEXT.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CONTEXT.java new file mode 100644 index 0000000000..033dad0f6f --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CONTEXT.java @@ -0,0 +1,100 @@ +package org.bouncycastle.jcajce.provider.asymmetric; + +import java.io.IOException; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.InvalidParameterSpecException; + +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.jcajce.spec.ContextParameterSpec; + +public class CONTEXT +{ + private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".CONTEXT$"; + + public static class ContextAlgorithmParametersSpi + extends java.security.AlgorithmParametersSpi + { + private ContextParameterSpec contextParameterSpec; + + protected boolean isASN1FormatString(String format) + { + return format == null || format.equals("ASN.1"); + } + + protected AlgorithmParameterSpec engineGetParameterSpec( + Class paramSpec) + throws InvalidParameterSpecException + { + if (paramSpec == null) + { + throw new NullPointerException("argument to getParameterSpec must not be null"); + } + if (paramSpec != ContextParameterSpec.class) + { + throw new IllegalArgumentException("argument to getParameterSpec must be ContextParameterSpec.class"); + } + + return contextParameterSpec; + } + + @Override + protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec) + throws InvalidParameterSpecException + { + if (!(algorithmParameterSpec instanceof ContextParameterSpec)) + { + throw new IllegalArgumentException("argument to engineInit must be a ContextParameterSpec"); + } + + this.contextParameterSpec = (ContextParameterSpec)algorithmParameterSpec; + } + + @Override + protected void engineInit(byte[] bytes) + throws IOException + { + throw new IllegalStateException("not implemented"); + } + + @Override + protected void engineInit(byte[] bytes, String s) + throws IOException + { + throw new IllegalStateException("not implemented"); + } + + @Override + protected byte[] engineGetEncoded() + throws IOException + { + throw new IllegalStateException("not implemented"); + } + + @Override + protected byte[] engineGetEncoded(String s) + throws IOException + { + throw new IllegalStateException("not implemented"); + } + + @Override + protected String engineToString() + { + return "ContextParameterSpec"; + } + } + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("AlgorithmParameters.CONTEXT", PREFIX + "ContextAlgorithmParametersSpi"); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CompositeSignatures.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CompositeSignatures.java index 11c24acf3f..d804b196bf 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CompositeSignatures.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/CompositeSignatures.java @@ -4,7 +4,7 @@ import java.util.Map; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeSignaturesConstants; +import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeIndex; import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.KeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; @@ -33,17 +33,19 @@ public Mappings() public void configure(ConfigurableProvider provider) { - for (ASN1ObjectIdentifier oid : CompositeSignaturesConstants.supportedIdentifiers) + for (ASN1ObjectIdentifier oid : CompositeIndex.getSupportedIdentifiers()) { - CompositeSignaturesConstants.CompositeName algName = CompositeSignaturesConstants.ASN1IdentifierAlgorithmNameMap.get(oid); - provider.addAlgorithm("KeyFactory." + algName.getId(), PREFIX + "KeyFactorySpi"); //Key factory is the same for all composite signatures. - provider.addAlgorithm("Alg.Alias.KeyFactory", oid, algName.getId()); + String algorithmName = CompositeIndex.getAlgorithmName(oid); + String className = algorithmName.replace('-', '_'); - provider.addAlgorithm("KeyPairGenerator." + algName.getId(), PREFIX + "KeyPairGeneratorSpi$" + algName); - provider.addAlgorithm("Alg.Alias.KeyPairGenerator", oid, algName.getId()); + provider.addAlgorithm("Alg.Alias.KeyFactory", oid, "COMPOSITE"); + provider.addAlgorithm("Alg.Alias.KeyFactory." + algorithmName, "COMPOSITE"); + + provider.addAlgorithm("KeyPairGenerator." + algorithmName, PREFIX + "KeyPairGeneratorSpi$" + className); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator", oid, algorithmName); - provider.addAlgorithm("Signature." + algName.getId(), PREFIX + "SignatureSpi$" + algName); - provider.addAlgorithm("Alg.Alias.Signature", oid, algName.getId()); + provider.addAlgorithm("Signature." + algorithmName, PREFIX + "SignatureSpi$" + className); + provider.addAlgorithm("Alg.Alias.Signature", oid, algorithmName); provider.addKeyInfoConverter(oid, new KeyFactorySpi()); } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/MLDSA.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/MLDSA.java new file mode 100644 index 0000000000..79540890da --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/MLDSA.java @@ -0,0 +1,78 @@ +package org.bouncycastle.jcajce.provider.asymmetric; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.jcajce.provider.asymmetric.mldsa.MLDSAKeyFactorySpi; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; + +public class MLDSA +{ + private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".mldsa."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.ML-DSA", PREFIX + "MLDSAKeyFactorySpi$Pure"); + provider.addAlgorithm("KeyPairGenerator.ML-DSA", PREFIX + "MLDSAKeyPairGeneratorSpi$Pure"); + provider.addAlgorithm("Alg.Alias.KeyFactory.MLDSA", "ML-DSA"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.MLDSA", "ML-DSA"); + provider.addAlgorithm("KeyFactory.HASH-ML-DSA", PREFIX + "MLDSAKeyFactorySpi$Hash"); + provider.addAlgorithm("KeyPairGenerator.HASH-ML-DSA", PREFIX + "MLDSAKeyPairGeneratorSpi$Hash"); + provider.addAlgorithm("Alg.Alias.KeyFactory.SHA512WITHMLDSA", "HASH-ML-DSA"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.SHA512WITHMLDSA", "HASH-ML-DSA"); + + addKeyFactoryAlgorithm(provider, "ML-DSA-44", PREFIX + "MLDSAKeyFactorySpi$MLDSA44", NISTObjectIdentifiers.id_ml_dsa_44, new MLDSAKeyFactorySpi.MLDSA44()); + addKeyFactoryAlgorithm(provider, "ML-DSA-65", PREFIX + "MLDSAKeyFactorySpi$MLDSA65", NISTObjectIdentifiers.id_ml_dsa_65, new MLDSAKeyFactorySpi.MLDSA65()); + addKeyFactoryAlgorithm(provider, "ML-DSA-87", PREFIX + "MLDSAKeyFactorySpi$MLDSA87", NISTObjectIdentifiers.id_ml_dsa_87, new MLDSAKeyFactorySpi.MLDSA87()); + addKeyFactoryAlgorithm(provider, "ML-DSA-44-WITH-SHA512", PREFIX + "MLDSAKeyFactorySpi$HashMLDSA44", NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, new MLDSAKeyFactorySpi.HashMLDSA44()); + addKeyFactoryAlgorithm(provider, "ML-DSA-65-WITH-SHA512", PREFIX + "MLDSAKeyFactorySpi$HashMLDSA65", NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, new MLDSAKeyFactorySpi.HashMLDSA65()); + addKeyFactoryAlgorithm(provider, "ML-DSA-87-WITH-SHA512", PREFIX + "MLDSAKeyFactorySpi$HashMLDSA87", NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, new MLDSAKeyFactorySpi.HashMLDSA87()); + + addKeyPairGeneratorAlgorithm(provider, "ML-DSA-44", PREFIX + "MLDSAKeyPairGeneratorSpi$MLDSA44", NISTObjectIdentifiers.id_ml_dsa_44); + addKeyPairGeneratorAlgorithm(provider, "ML-DSA-65", PREFIX + "MLDSAKeyPairGeneratorSpi$MLDSA65", NISTObjectIdentifiers.id_ml_dsa_65); + addKeyPairGeneratorAlgorithm(provider, "ML-DSA-87", PREFIX + "MLDSAKeyPairGeneratorSpi$MLDSA87", NISTObjectIdentifiers.id_ml_dsa_87); + addKeyPairGeneratorAlgorithm(provider, "ML-DSA-44-WITH-SHA512", PREFIX + "MLDSAKeyPairGeneratorSpi$MLDSA44withSHA512", NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + addKeyPairGeneratorAlgorithm(provider, "ML-DSA-65-WITH-SHA512", PREFIX + "MLDSAKeyPairGeneratorSpi$MLDSA65withSHA512", NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + addKeyPairGeneratorAlgorithm(provider, "ML-DSA-87-WITH-SHA512", PREFIX + "MLDSAKeyPairGeneratorSpi$MLDSA87withSHA512", NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + + addSignatureAlgorithm(provider, "ML-DSA", PREFIX + "SignatureSpi$MLDSA", (ASN1ObjectIdentifier)null); + addSignatureAlgorithm(provider, "ML-DSA-44", PREFIX + "SignatureSpi$MLDSA44", NISTObjectIdentifiers.id_ml_dsa_44); + addSignatureAlgorithm(provider, "ML-DSA-65", PREFIX + "SignatureSpi$MLDSA65", NISTObjectIdentifiers.id_ml_dsa_65); + addSignatureAlgorithm(provider, "ML-DSA-87", PREFIX + "SignatureSpi$MLDSA87", NISTObjectIdentifiers.id_ml_dsa_87); + provider.addAlgorithm("Alg.Alias.Signature.MLDSA", "ML-DSA"); + + addSignatureAlgorithm(provider, "ML-DSA-CALCULATE-MU", PREFIX + "SignatureSpi$MLDSACalcMu", (ASN1ObjectIdentifier)null); + provider.addAlgorithm("Alg.Alias.Signature.MLDSA-CALCULATE-MU", "ML-DSA-CALCULATE-MU"); + + addSignatureAlgorithm(provider, "ML-DSA-EXTERNAL-MU", PREFIX + "SignatureSpi$MLDSAExtMu", (ASN1ObjectIdentifier)null); + provider.addAlgorithm("Alg.Alias.Signature.MLDSA-EXTERNAL-MU", "ML-DSA-EXTERNAL-MU"); + + addSignatureAlgorithm(provider, "HASH-ML-DSA", PREFIX + "HashSignatureSpi$MLDSA", (ASN1ObjectIdentifier)null); + addSignatureAlgorithm(provider, "ML-DSA-44-WITH-SHA512", PREFIX + "HashSignatureSpi$MLDSA44", NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + addSignatureAlgorithm(provider, "ML-DSA-65-WITH-SHA512", PREFIX + "HashSignatureSpi$MLDSA65", NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + addSignatureAlgorithm(provider, "ML-DSA-87-WITH-SHA512", PREFIX + "HashSignatureSpi$MLDSA87", NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + + provider.addAlgorithm("Alg.Alias.Signature.SHA512WITHMLDSA", "HASH-ML-DSA"); + provider.addAlgorithm("Alg.Alias.Signature.SHA512WITHMLDSA44", "ML-DSA-44-WITH-SHA512"); + provider.addAlgorithm("Alg.Alias.Signature.SHA512WITHMLDSA65", "ML-DSA-65-WITH-SHA512"); + provider.addAlgorithm("Alg.Alias.Signature.SHA512WITHMLDSA87", "ML-DSA-87-WITH-SHA512"); + + AsymmetricKeyInfoConverter keyFact = new MLDSAKeyFactorySpi.Hash(); + + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_ml_dsa_44, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_ml_dsa_65, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_ml_dsa_87, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, keyFact); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/MLKEM.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/MLKEM.java new file mode 100644 index 0000000000..4fc74ce683 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/MLKEM.java @@ -0,0 +1,56 @@ +package org.bouncycastle.jcajce.provider.asymmetric; + +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.MLKEMKeyFactorySpi; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; + +public class MLKEM +{ + private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".mlkem."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.ML-KEM", PREFIX + "MLKEMKeyFactorySpi"); + provider.addAlgorithm("Alg.Alias.KeyFactory.MLKEM", "ML-KEM"); + + addKeyFactoryAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMKeyFactorySpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512, new MLKEMKeyFactorySpi.MLKEM512()); + addKeyFactoryAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMKeyFactorySpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768, new MLKEMKeyFactorySpi.MLKEM768()); + addKeyFactoryAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMKeyFactorySpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024, new MLKEMKeyFactorySpi.MLKEM1024()); + + provider.addAlgorithm("KeyPairGenerator.ML-KEM", PREFIX + "MLKEMKeyPairGeneratorSpi"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.MLKEM", "ML-KEM"); + + addKeyPairGeneratorAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMKeyPairGeneratorSpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addKeyPairGeneratorAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMKeyPairGeneratorSpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addKeyPairGeneratorAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMKeyPairGeneratorSpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + + provider.addAlgorithm("KeyGenerator.ML-KEM", PREFIX + "MLKEMKeyGeneratorSpi"); + + addKeyGeneratorAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMKeyGeneratorSpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addKeyGeneratorAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMKeyGeneratorSpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addKeyGeneratorAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMKeyGeneratorSpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + + AsymmetricKeyInfoConverter keyFact = new MLKEMKeyFactorySpi(); + + provider.addAlgorithm("Cipher.ML-KEM", PREFIX + "MLKEMCipherSpi$Base"); + provider.addAlgorithm("Alg.Alias.Cipher.MLKEM", "ML-KEM"); + + addCipherAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMCipherSpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addCipherAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMCipherSpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addCipherAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMCipherSpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_512, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_768, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_1024, keyFact); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/NoSig.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/NoSig.java new file mode 100644 index 0000000000..abf599f26a --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/NoSig.java @@ -0,0 +1,90 @@ +package org.bouncycastle.jcajce.provider.asymmetric; + +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.SignatureSpi; + +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; + +public class NoSig +{ + private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric.NoSig$"; + + public static class SigSpi + extends SignatureSpi + { + @Override + protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException + { + throw new InvalidKeyException("attempt to pass public key to NoSig"); + } + + @Override + protected void engineInitSign(PrivateKey privateKey) + throws InvalidKeyException + { + throw new InvalidKeyException("attempt to pass private key to NoSig"); + } + + @Override + protected void engineUpdate(byte b) + throws SignatureException + { + + } + + @Override + protected void engineUpdate(byte[] bytes, int i, int i1) + throws SignatureException + { + + } + + @Override + protected byte[] engineSign() + throws SignatureException + { + return new byte[0]; + } + + @Override + protected boolean engineVerify(byte[] bytes) + throws SignatureException + { + return false; + } + + @Override + protected void engineSetParameter(String s, Object o) + throws InvalidParameterException + { + + } + + @Override + protected Object engineGetParameter(String s) + throws InvalidParameterException + { + return null; + } + } + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("Signature." + X509ObjectIdentifiers.id_alg_noSignature, PREFIX + "SigSpi"); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SLHDSA.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SLHDSA.java new file mode 100644 index 0000000000..6a05ffddf7 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SLHDSA.java @@ -0,0 +1,178 @@ +package org.bouncycastle.jcajce.provider.asymmetric; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.jcajce.provider.asymmetric.slhdsa.SLHDSAKeyFactorySpi; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; + +public class SLHDSA +{ + private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".slhdsa."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.SLH-DSA", PREFIX + "SLHDSAKeyFactorySpi$Pure"); + provider.addAlgorithm("KeyPairGenerator.SLH-DSA", PREFIX + "SLHDSAKeyPairGeneratorSpi$Pure"); + provider.addAlgorithm("KeyFactory.HASH-SLH-DSA", PREFIX + "SLHDSAKeyFactorySpi$Hash"); + provider.addAlgorithm("KeyPairGenerator.HASH-SLH-DSA", PREFIX + "SLHDSAKeyPairGeneratorSpi$Hash"); + + AsymmetricKeyInfoConverter keyFact = new SLHDSAKeyFactorySpi.Hash(); + + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-128S", PREFIX + "SLHDSAKeyFactorySpi$Sha2_128s", NISTObjectIdentifiers.id_slh_dsa_sha2_128s, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-128F", PREFIX + "SLHDSAKeyFactorySpi$Sha2_128f", NISTObjectIdentifiers.id_slh_dsa_sha2_128f, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-192S", PREFIX + "SLHDSAKeyFactorySpi$Sha2_192s", NISTObjectIdentifiers.id_slh_dsa_sha2_192s, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-192F", PREFIX + "SLHDSAKeyFactorySpi$Sha2_192f", NISTObjectIdentifiers.id_slh_dsa_sha2_192f, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-256S", PREFIX + "SLHDSAKeyFactorySpi$Sha2_256s", NISTObjectIdentifiers.id_slh_dsa_sha2_256s, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-256F", PREFIX + "SLHDSAKeyFactorySpi$Sha2_256f", NISTObjectIdentifiers.id_slh_dsa_sha2_256f, keyFact); + + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-128S", PREFIX + "SLHDSAKeyFactorySpi$Shake_128s", NISTObjectIdentifiers.id_slh_dsa_shake_128s, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-128F", PREFIX + "SLHDSAKeyFactorySpi$Shake_128f", NISTObjectIdentifiers.id_slh_dsa_shake_128f, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-192S", PREFIX + "SLHDSAKeyFactorySpi$Shake_192s", NISTObjectIdentifiers.id_slh_dsa_shake_192s, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-192F", PREFIX + "SLHDSAKeyFactorySpi$Shake_192f", NISTObjectIdentifiers.id_slh_dsa_shake_192f, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-256S", PREFIX + "SLHDSAKeyFactorySpi$Shake_256s", NISTObjectIdentifiers.id_slh_dsa_shake_256s, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-256F", PREFIX + "SLHDSAKeyFactorySpi$Shake_256f", NISTObjectIdentifiers.id_slh_dsa_shake_256f, keyFact); + + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-128S-WITH-SHA256", PREFIX + "SLHDSAKeyFactorySpi$HashSha2_128s", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-128F-WITH-SHA256", PREFIX + "SLHDSAKeyFactorySpi$HashSha2_128f", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-192S-WITH-SHA512", PREFIX + "SLHDSAKeyFactorySpi$HashSha2_192s", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-192F-WITH-SHA512", PREFIX + "SLHDSAKeyFactorySpi$HashSha2_192f", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-256S-WITH-SHA512", PREFIX + "SLHDSAKeyFactorySpi$HashSha2_256s", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHA2-256F-WITH-SHA512", PREFIX + "SLHDSAKeyFactorySpi$HashSha2_256f", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, keyFact); + + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-128S-WITH-SHAKE128", PREFIX + "SLHDSAKeyFactorySpi$HashShake_128s", NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-128F-WITH-SHAKE128", PREFIX + "SLHDSAKeyFactorySpi$HashShake_128f", NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-192S-WITH-SHAKE256", PREFIX + "SLHDSAKeyFactorySpi$HashShake_192s", NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-192F-WITH-SHAKE256", PREFIX + "SLHDSAKeyFactorySpi$HashShake_192f", NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-256S-WITH-SHAKE256", PREFIX + "SLHDSAKeyFactorySpi$HashShake_256s", NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, keyFact); + addKeyFactoryAlgorithm(provider, "SLH-DSA-SHAKE-256F-WITH-SHAKE256", PREFIX + "SLHDSAKeyFactorySpi$HashShake_256f", NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, keyFact); + + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-128S", PREFIX + "SLHDSAKeyPairGeneratorSpi$Sha2_128s", NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-128F", PREFIX + "SLHDSAKeyPairGeneratorSpi$Sha2_128f", NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-192S", PREFIX + "SLHDSAKeyPairGeneratorSpi$Sha2_192s", NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-192F", PREFIX + "SLHDSAKeyPairGeneratorSpi$Sha2_192f", NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-256S", PREFIX + "SLHDSAKeyPairGeneratorSpi$Sha2_256s", NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-256F", PREFIX + "SLHDSAKeyPairGeneratorSpi$Sha2_256f", NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-128S", PREFIX + "SLHDSAKeyPairGeneratorSpi$Shake_128s", NISTObjectIdentifiers.id_slh_dsa_shake_128s); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-128F", PREFIX + "SLHDSAKeyPairGeneratorSpi$Shake_128f", NISTObjectIdentifiers.id_slh_dsa_shake_128f); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-192S", PREFIX + "SLHDSAKeyPairGeneratorSpi$Shake_192s", NISTObjectIdentifiers.id_slh_dsa_shake_192s); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-192F", PREFIX + "SLHDSAKeyPairGeneratorSpi$Shake_192f", NISTObjectIdentifiers.id_slh_dsa_shake_192f); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-256S", PREFIX + "SLHDSAKeyPairGeneratorSpi$Shake_256s", NISTObjectIdentifiers.id_slh_dsa_shake_256s); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-256F", PREFIX + "SLHDSAKeyPairGeneratorSpi$Shake_256f", NISTObjectIdentifiers.id_slh_dsa_shake_256f); + + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-128S-WITH-SHA256", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashSha2_128s", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-128F-WITH-SHA256", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashSha2_128f", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-192S-WITH-SHA512", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashSha2_192s", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-192F-WITH-SHA512", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashSha2_192f", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-256S-WITH-SHA512", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashSha2_256s", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHA2-256F-WITH-SHA512", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashSha2_256f", NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-128S-WITH-SHAKE128", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashShake_128s", NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-128F-WITH-SHAKE128", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashShake_128f", NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-192S-WITH-SHAKE256", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashShake_192s", NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-192F-WITH-SHAKE256", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashShake_192f", NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-256S-WITH-SHAKE256", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashShake_256s", NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + addKeyPairGeneratorAlgorithm(provider, "SLH-DSA-SHAKE-256F-WITH-SHAKE256", PREFIX + "SLHDSAKeyPairGeneratorSpi$HashShake_256f", NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + + String[] algNames = new String[] + { + "SLH-DSA-SHA2-128S", + "SLH-DSA-SHA2-128F", + "SLH-DSA-SHA2-192S", + "SLH-DSA-SHA2-192F", + "SLH-DSA-SHA2-256S", + "SLH-DSA-SHA2-256F", + "SLH-DSA-SHAKE-128S", + "SLH-DSA-SHAKE-128F", + "SLH-DSA-SHAKE-192S", + "SLH-DSA-SHAKE-192F", + "SLH-DSA-SHAKE-256S", + "SLH-DSA-SHAKE-256F" + }; + + String[] hashAlgNames = new String[] + { + "SLH-DSA-SHA2-128S-WITH-SHA256", + "SLH-DSA-SHA2-128F-WITH-SHA256", + "SLH-DSA-SHA2-192S-WITH-SHA512", + "SLH-DSA-SHA2-192F-WITH-SHA512", + "SLH-DSA-SHA2-256S-WITH-SHA512", + "SLH-DSA-SHA2-256F-WITH-SHA512", + "SLH-DSA-SHAKE-128S-WITH-SHAKE128", + "SLH-DSA-SHAKE-128F-WITH-SHAKE128", + "SLH-DSA-SHAKE-192S-WITH-SHAKE256", + "SLH-DSA-SHAKE-192F-WITH-SHAKE256", + "SLH-DSA-SHAKE-256S-WITH-SHAKE256", + "SLH-DSA-SHAKE-256F-WITH-SHAKE256" + }; + + addSignatureAlgorithm(provider, "SLH-DSA", PREFIX + "SignatureSpi$Direct", (ASN1ObjectIdentifier)null); + provider.addAlgorithm("Alg.Alias.Signature.SLHDSA", "SLH-DSA"); + addSignatureAlgorithm(provider, "HASH-SLH-DSA", PREFIX + "HashSignatureSpi$Direct", (ASN1ObjectIdentifier)null); + provider.addAlgorithm("Alg.Alias.Signature.HASHWITHSLHDSA", "HASH-SLH-DSA"); + + for (int i = 0; i != algNames.length; i++) + { + provider.addAlgorithm("Alg.Alias.Signature." + algNames[i], "SLH-DSA"); + } + + for (int i = 0; i != hashAlgNames.length; i++) + { + provider.addAlgorithm("Alg.Alias.Signature." + hashAlgNames[i], "HASH-SLH-DSA"); + } + + ASN1ObjectIdentifier[] nistOids = new ASN1ObjectIdentifier[] + { + NISTObjectIdentifiers.id_slh_dsa_sha2_128s, + NISTObjectIdentifiers.id_slh_dsa_sha2_128f, + NISTObjectIdentifiers.id_slh_dsa_sha2_192s, + NISTObjectIdentifiers.id_slh_dsa_sha2_192f, + NISTObjectIdentifiers.id_slh_dsa_sha2_256s, + NISTObjectIdentifiers.id_slh_dsa_sha2_256f, + NISTObjectIdentifiers.id_slh_dsa_shake_128s, + NISTObjectIdentifiers.id_slh_dsa_shake_128f, + NISTObjectIdentifiers.id_slh_dsa_shake_192s, + NISTObjectIdentifiers.id_slh_dsa_shake_192f, + NISTObjectIdentifiers.id_slh_dsa_shake_256s, + NISTObjectIdentifiers.id_slh_dsa_shake_256f + }; + + for (int i = 0; i != nistOids.length; i++) + { + provider.addAlgorithm("Alg.Alias.Signature." + nistOids[i], "SLH-DSA"); + provider.addAlgorithm("Alg.Alias.Signature.OID." + nistOids[i], "SLH-DSA"); + } + + nistOids = new ASN1ObjectIdentifier[] + { + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256 + }; + + for (int i = 0; i != nistOids.length; i++) + { + provider.addAlgorithm("Alg.Alias.Signature." + nistOids[i], "HASH-SLH-DSA"); + provider.addAlgorithm("Alg.Alias.Signature.OID." + nistOids[i], "HASH-SLH-DSA"); + } + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SPHINCSPlus.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SPHINCSPlus.java index 480184981d..2f2c071bbd 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SPHINCSPlus.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/SPHINCSPlus.java @@ -75,8 +75,7 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("Alg.Alias.Signature.SPHINCS+", "SPHINCSPLUS"); AsymmetricKeyInfoConverter keyFact = new SPHINCSPlusKeyFactorySpi(); - -// registerOid(provider, BCObjectIdentifiers.sphincsPlus, "SPHINCSPLUS", keyFact); + registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, "SPHINCSPLUS", keyFact); registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, "SPHINCSPLUS", keyFact); registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus_shake_128s_r3, "SPHINCSPLUS", keyFact); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/CompositeIndex.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/CompositeIndex.java new file mode 100644 index 0000000000..00f117cfa8 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/CompositeIndex.java @@ -0,0 +1,150 @@ +package org.bouncycastle.jcajce.provider.asymmetric.compositesignatures; + +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.RSAKeyGenParameterSpec; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; + +public class CompositeIndex +{ + private static Map pairings = new HashMap(); + private static Map kpgInitSpecs = new HashMap(); + private static Map algorithmNames = new HashMap(); + + static + { + pairings.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256, new String[] { "ML-DSA-44", "SHA256withRSAandMGF1"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256, new String[] { "ML-DSA-44", "SHA256withRSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, new String[] { "ML-DSA-44", "Ed25519"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, new String[] { "ML-DSA-44", "SHA256withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256, new String[] { "ML-DSA-65", "SHA256withRSAandMGF1"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256, new String[] { "ML-DSA-65", "SHA256withRSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384, new String[] { "ML-DSA-65", "SHA384withRSAandMGF1"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384, new String[] { "ML-DSA-65", "SHA384withRSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384, new String[] { "ML-DSA-65", "SHA384withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256, new String[] { "ML-DSA-65", "SHA256withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512, new String[] { "ML-DSA-65", "Ed25519"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384, new String[] { "ML-DSA-87", "SHA384withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384, new String[] { "ML-DSA-87", "SHA384withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, new String[] { "ML-DSA-87", "Ed448"}); + + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256, new String[] { "ML-DSA-44", "SHA256withRSAandMGF1"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256, new String[] { "ML-DSA-44", "SHA256withRSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512, new String[] { "ML-DSA-44", "Ed25519"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256, new String[] { "ML-DSA-44", "SHA256withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512, new String[] { "ML-DSA-65", "SHA256withRSAandMGF1"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512, new String[] { "ML-DSA-65", "SHA256withRSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512, new String[] { "ML-DSA-65", "SHA384withRSAandMGF1"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512, new String[] { "ML-DSA-65", "SHA384withRSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512, new String[] { "ML-DSA-65", "SHA384withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512, new String[] { "ML-DSA-65", "SHA256withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512, new String[] { "ML-DSA-65", "Ed25519"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512, new String[] { "ML-DSA-87", "SHA384withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512, new String[] { "ML-DSA-87", "SHA384withECDSA"}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512, new String[] { "ML-DSA-87", "Ed448"}); + + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, new AlgorithmParameterSpec[] { null, null}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("P-256")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(4096, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(4096, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("P-384")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("brainpoolP256r1")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512, new AlgorithmParameterSpec[] { null, null}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("P-384")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("brainpoolP384r1")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, new AlgorithmParameterSpec[] { null, null}); + + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512, new AlgorithmParameterSpec[] { null, null}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("P-256")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(4096, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512, new AlgorithmParameterSpec[] { null, new RSAKeyGenParameterSpec(4096, RSAKeyGenParameterSpec.F4)}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("P-384")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("brainpoolP256r1")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512, new AlgorithmParameterSpec[] { null, null}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("P-384")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512, new AlgorithmParameterSpec[] { null, new ECNamedCurveGenParameterSpec("brainpoolP384r1")}); + kpgInitSpecs.put(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512, new AlgorithmParameterSpec[] { null, null}); + + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256, "MLDSA44-RSA2048-PSS-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256, "MLDSA44-RSA2048-PKCS15-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, "MLDSA44-Ed25519-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, "MLDSA44-ECDSA-P256-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256, "MLDSA65-RSA3072-PSS-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256, "MLDSA65-RSA3072-PKCS15-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384, "MLDSA65-RSA4096-PSS-SHA384"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384, "MLDSA65-RSA4096-PKCS15-SHA384"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384, "MLDSA65-ECDSA-P384-SHA384"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256, "MLDSA65-ECDSA-brainpoolP256r1-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512, "MLDSA65-Ed25519-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384, "MLDSA87-ECDSA-P384-SHA384"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384, "MLDSA87-ECDSA-brainpoolP384r1-SHA384"); + algorithmNames.put(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, "MLDSA87-Ed448-SHA512"); + + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256, "HashMLDSA44-RSA2048-PSS-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256, "HashMLDSA44-RSA2048-PKCS15-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512, "HashMLDSA44-Ed25519-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256, "HashMLDSA44-ECDSA-P256-SHA256"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512, "HashMLDSA65-RSA3072-PSS-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512, "HashMLDSA65-RSA3072-PKCS15-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512, "HashMLDSA65-RSA4096-PSS-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512, "HashMLDSA65-RSA4096-PKCS15-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512, "HashMLDSA65-ECDSA-P384-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512, "HashMLDSA65-ECDSA-brainpoolP256r1-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512, "HashMLDSA65-Ed25519-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512, "HashMLDSA87-ECDSA-P384-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512, "HashMLDSA87-ECDSA-brainpoolP384r1-SHA512"); + algorithmNames.put(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512, "HashMLDSA87-Ed448-SHA512"); + } + + public static boolean isAlgorithmSupported(ASN1ObjectIdentifier algorithm) + { + return pairings.containsKey(algorithm); + } + + public static Set getSupportedIdentifiers() + { + return pairings.keySet(); + } + + public static String getAlgorithmName(ASN1ObjectIdentifier algorithm) + { + return algorithmNames.get(algorithm); + } + + static String[] getPairing(ASN1ObjectIdentifier algorithm) + { + return pairings.get(algorithm); + } + + static AlgorithmParameterSpec[] getKeyPairSpecs(ASN1ObjectIdentifier algorithm) + { + return kpgInitSpecs.get(algorithm); + } + + static String getBaseName(String name) + { + if (name.indexOf("RSA") >= 0) + { + return "RSA"; + } + if (name.indexOf("ECDSA") >= 0) + { + return "EC"; + } + + return name; + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/CompositeSignaturesConstants.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/CompositeSignaturesConstants.java deleted file mode 100644 index e4b1c94b02..0000000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/CompositeSignaturesConstants.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.compositesignatures; - -import java.util.HashMap; -import java.util.Map.Entry; - -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; - - -/** - * Helper class containing constants/mappings for composite signatures. - */ -public abstract class CompositeSignaturesConstants -{ - - /** - * An array of supported identifiers of composite signature schemes. - */ - public static final ASN1ObjectIdentifier[] supportedIdentifiers = { - MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256, - MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256, - MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, - MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, - MiscObjectIdentifiers.id_MLDSA44_ECDSA_brainpoolP256r1_SHA256, - MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA512, - MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA512, - MiscObjectIdentifiers.id_MLDSA65_ECDSA_P256_SHA512, - MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA512, - MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512, - MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA512, - MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA512, - MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, - MiscObjectIdentifiers.id_Falcon512_ECDSA_P256_SHA256, - MiscObjectIdentifiers.id_Falcon512_ECDSA_brainpoolP256r1_SHA256, - MiscObjectIdentifiers.id_Falcon512_Ed25519_SHA512, - }; - - /** - * Enum of supported composited signature schemes. Each one corresponds to a value from supportedIdentifiers. - */ - public enum CompositeName - { - MLDSA44_RSA2048_PSS_SHA256("MLDSA44-RSA2048-PSS-SHA256"), - MLDSA44_RSA2048_PKCS15_SHA256("MLDSA44-RSA2048-PKCS15-SHA256"), - MLDSA44_Ed25519_SHA512("MLDSA44-Ed25519-SHA512"), - MLDSA44_ECDSA_P256_SHA256("MLDSA44-ECDSA-P256-SHA256"), - MLDSA44_ECDSA_brainpoolP256r1_SHA256("MLDSA44-ECDSA-brainpoolP256r1-SHA256"), - MLDSA65_RSA3072_PSS_SHA512("MLDSA65-RSA3072-PSS-SHA512"), - MLDSA65_RSA3072_PKCS15_SHA512("MLDSA65-RSA3072-PKCS15-SHA512"), - MLDSA65_ECDSA_brainpoolP256r1_SHA512("MLDSA65-ECDSA-brainpoolP256r1-SHA512"), - MLDSA65_ECDSA_P256_SHA512("MLDSA65-ECDSA-P256-SHA512"), - MLDSA65_Ed25519_SHA512("MLDSA65-Ed25519-SHA512"), - MLDSA87_ECDSA_P384_SHA512("MLDSA87-ECDSA-P384-SHA512"), - MLDSA87_ECDSA_brainpoolP384r1_SHA512("MLDSA87-ECDSA-brainpoolP384r1-SHA512"), - MLDSA87_Ed448_SHA512("MLDSA87-Ed448-SHA512"), - Falcon512_ECDSA_P256_SHA256("Falcon512-ECDSA-P256-SHA256"), - Falcon512_ECDSA_brainpoolP256r1_SHA256("Falcon512-ECDSA-brainpoolP256r1-SHA256"), - Falcon512_Ed25519_SHA512("Falcon512-Ed25519-SHA512"); - - private final String id; - - private CompositeName(String id) - { - this.id = id; - } - - public String getId() - { - return id; - } - } - - /** - * Map from CompositeName enum to ASN1 identifier. - */ - public static final HashMap compositeNameASN1IdentifierMap; - - static - { - compositeNameASN1IdentifierMap = new HashMap(); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA44_RSA2048_PSS_SHA256, MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA44_RSA2048_PKCS15_SHA256, MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA44_ECDSA_P256_SHA256, MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA44_ECDSA_brainpoolP256r1_SHA256, MiscObjectIdentifiers.id_MLDSA44_ECDSA_brainpoolP256r1_SHA256); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA44_Ed25519_SHA512, MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA65_RSA3072_PSS_SHA512, MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA65_RSA3072_PKCS15_SHA512, MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA65_ECDSA_P256_SHA512, MiscObjectIdentifiers.id_MLDSA65_ECDSA_P256_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA65_ECDSA_brainpoolP256r1_SHA512, MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA65_Ed25519_SHA512, MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA87_ECDSA_P384_SHA512, MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA87_ECDSA_brainpoolP384r1_SHA512, MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.MLDSA87_Ed448_SHA512, MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512); - compositeNameASN1IdentifierMap.put(CompositeName.Falcon512_ECDSA_P256_SHA256, MiscObjectIdentifiers.id_Falcon512_ECDSA_P256_SHA256); - compositeNameASN1IdentifierMap.put(CompositeName.Falcon512_ECDSA_brainpoolP256r1_SHA256, MiscObjectIdentifiers.id_Falcon512_ECDSA_brainpoolP256r1_SHA256); - compositeNameASN1IdentifierMap.put(CompositeName.Falcon512_Ed25519_SHA512, MiscObjectIdentifiers.id_Falcon512_Ed25519_SHA512); - } - - /** - * Reverse map of compositeNameASN1IdentifierMap. - */ - public static final HashMap ASN1IdentifierCompositeNameMap; - - static - { - ASN1IdentifierCompositeNameMap = new HashMap(); - for (Entry entry : compositeNameASN1IdentifierMap.entrySet()) - { - ASN1IdentifierCompositeNameMap.put(entry.getValue(), entry.getKey()); - } - } - - /** - * Map from ASN1 identifier to a readable string used as the composite signature name for the JCA/JCE API. - */ - public static final HashMap ASN1IdentifierAlgorithmNameMap; - - static - { - ASN1IdentifierAlgorithmNameMap = new HashMap(); - for (ASN1ObjectIdentifier oid : supportedIdentifiers) - { - CompositeName algName = ASN1IdentifierCompositeNameMap.get(oid); //Get enum so we can get name() value. - ASN1IdentifierAlgorithmNameMap.put(oid, algName); - } - } - - private CompositeSignaturesConstants() - { - - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyFactorySpi.java index 8f1976fa67..8379a8f293 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyFactorySpi.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyFactorySpi.java @@ -9,32 +9,45 @@ import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.bouncycastle.asn1.ASN1BitString; +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.sec.SECObjectIdentifiers; +import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; +import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X962Parameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.sec.SECObjectIdentifiers; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; +import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.jcajce.CompositePrivateKey; import org.bouncycastle.jcajce.CompositePublicKey; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.jcajce.util.JcaJceHelper; +import org.bouncycastle.math.ec.rfc8032.Ed25519; +import org.bouncycastle.math.ec.rfc8032.Ed448; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Exceptions; /** @@ -42,24 +55,108 @@ */ public class KeyFactorySpi extends BaseKeyFactorySpi + implements AsymmetricKeyInfoConverter { //Specific algorithm identifiers of all component signature algorithms for SubjectPublicKeyInfo. These do not need to be all initialized here but makes the code more readable IMHO. - private static final AlgorithmIdentifier dilithium2Identifier = new AlgorithmIdentifier(BCObjectIdentifiers.dilithium2); - private static final AlgorithmIdentifier dilithium3Identifier = new AlgorithmIdentifier(BCObjectIdentifiers.dilithium3); - private static final AlgorithmIdentifier dilithium5Identifier = new AlgorithmIdentifier(BCObjectIdentifiers.dilithium5); + private static final AlgorithmIdentifier mlDsa44 = new AlgorithmIdentifier(NISTObjectIdentifiers.id_ml_dsa_44); + private static final AlgorithmIdentifier mlDsa65 = new AlgorithmIdentifier(NISTObjectIdentifiers.id_ml_dsa_65); + private static final AlgorithmIdentifier mlDsa87 = new AlgorithmIdentifier(NISTObjectIdentifiers.id_ml_dsa_87); private static final AlgorithmIdentifier falcon512Identifier = new AlgorithmIdentifier(BCObjectIdentifiers.falcon_512); - private static final AlgorithmIdentifier ed25519Identifier = new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519); - private static final AlgorithmIdentifier ecdsaP256Identifier = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(SECObjectIdentifiers.secp256r1)); - private static final AlgorithmIdentifier ecdsaBrainpoolP256r1Identifier = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(TeleTrusTObjectIdentifiers.brainpoolP256r1)); - private static final AlgorithmIdentifier rsaIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption); - private static final AlgorithmIdentifier ed448Identifier = new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448); - private static final AlgorithmIdentifier ecdsaP384Identifier = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(SECObjectIdentifiers.secp384r1)); - private static final AlgorithmIdentifier ecdsaBrainpoolP384r1Identifier = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(TeleTrusTObjectIdentifiers.brainpoolP384r1)); + private static final AlgorithmIdentifier ed25519 = new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519); + private static final AlgorithmIdentifier ecDsaP256 = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(SECObjectIdentifiers.secp256r1)); + private static final AlgorithmIdentifier ecDsaBrainpoolP256r1 = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(TeleTrusTObjectIdentifiers.brainpoolP256r1)); + private static final AlgorithmIdentifier rsa = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption); + private static final AlgorithmIdentifier ed448 = new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448); + private static final AlgorithmIdentifier ecDsaP384 = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(SECObjectIdentifiers.secp384r1)); + private static final AlgorithmIdentifier ecDsaBrainpoolP384r1 = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, new X962Parameters(TeleTrusTObjectIdentifiers.brainpoolP384r1)); + + private static Map pairings = new HashMap(); + private static Map componentKeySizes = new HashMap(); + + static + { + pairings.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256, new AlgorithmIdentifier[]{mlDsa44, rsa}); + pairings.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256, new AlgorithmIdentifier[]{mlDsa44, rsa}); + pairings.put(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, new AlgorithmIdentifier[]{mlDsa44, ed25519}); + pairings.put(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, new AlgorithmIdentifier[]{mlDsa44, ecDsaP256}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384, new AlgorithmIdentifier[]{mlDsa65, ecDsaP384}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256, new AlgorithmIdentifier[]{mlDsa65, ecDsaBrainpoolP256r1}); + pairings.put(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512, new AlgorithmIdentifier[]{mlDsa65, ed25519}); + pairings.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384, new AlgorithmIdentifier[]{mlDsa87, ecDsaP384}); + pairings.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384, new AlgorithmIdentifier[]{mlDsa87, ecDsaBrainpoolP384r1}); + pairings.put(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, new AlgorithmIdentifier[]{mlDsa87, ed448}); + + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256, new AlgorithmIdentifier[]{mlDsa44, rsa}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256, new AlgorithmIdentifier[]{mlDsa44, rsa}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512, new AlgorithmIdentifier[]{mlDsa44, ed25519}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256, new AlgorithmIdentifier[]{mlDsa44, ecDsaP256}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512, new AlgorithmIdentifier[]{mlDsa65, rsa}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512, new AlgorithmIdentifier[]{mlDsa65, ecDsaP384}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512, new AlgorithmIdentifier[]{mlDsa65, ecDsaBrainpoolP256r1}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512, new AlgorithmIdentifier[]{mlDsa65, ed25519}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512, new AlgorithmIdentifier[]{mlDsa87, ecDsaP384}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512, new AlgorithmIdentifier[]{mlDsa87, ecDsaBrainpoolP384r1}); + pairings.put(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512, new AlgorithmIdentifier[] { mlDsa87, ed448}); + + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256, new int[]{1328, 268}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256, new int[]{1312, 284}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512, new int[]{1312, Ed25519.PUBLIC_KEY_SIZE}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256, new int[]{1312, 76}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256, new int[]{1952, 256}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256, new int[]{1952, 256}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384, new int[]{1952, 542}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384, new int[]{1952, 542}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384, new int[]{1952, 87}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256, new int[]{1952, 76}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512, new int[]{1952, Ed25519.PUBLIC_KEY_SIZE}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384, new int[]{2592, 87}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384, new int[]{2592, 87}); + componentKeySizes.put(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512, new int[]{2592, Ed448.PUBLIC_KEY_SIZE}); + + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256, new int[]{1328, 268}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256, new int[]{1312, 284}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512, new int[]{1312, Ed25519.PUBLIC_KEY_SIZE}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256, new int[]{1312, 76}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512, new int[]{1952, 256}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512, new int[]{1952, 256}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512, new int[]{1952, 542}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512, new int[]{1952, 542}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512, new int[]{1952, 87}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512, new int[]{1952, 76}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512, new int[]{1952, Ed25519.PUBLIC_KEY_SIZE}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512, new int[]{2592, 87}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512, new int[]{2592, 87}); + componentKeySizes.put(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512, new int[] { 2592, Ed448.PUBLIC_KEY_SIZE}); + } + + private JcaJceHelper helper; + + public KeyFactorySpi() + { + this(null); + } + + public KeyFactorySpi(JcaJceHelper helper) + { + this.helper = helper; + } protected Key engineTranslateKey(Key key) throws InvalidKeyException { + if (helper == null) + { + helper = new BCJcaJceHelper(); + } + try { if (key instanceof PrivateKey) @@ -91,19 +188,93 @@ else if (key instanceof PublicKey) public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) throws IOException { - ASN1Sequence seq = DERSequence.getInstance(keyInfo.parsePrivateKey()); + if (helper == null) + { + helper = new BCJcaJceHelper(); + } + ASN1ObjectIdentifier keyIdentifier = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); + if (MiscObjectIdentifiers.id_alg_composite.equals(keyIdentifier) + || MiscObjectIdentifiers.id_composite_key.equals(keyIdentifier)) + { + ASN1Sequence seq = DERSequence.getInstance(keyInfo.parsePrivateKey()); + + PrivateKey[] privKeys = new PrivateKey[seq.size()]; + + for (int i = 0; i != seq.size(); i++) + { + ASN1Sequence kSeq = ASN1Sequence.getInstance(seq.getObjectAt(i)); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kSeq); + + try + { + privKeys[i] = helper.createKeyFactory( + privInfo.getPrivateKeyAlgorithm().getAlgorithm().getId()).generatePrivate(new PKCS8EncodedKeySpec(privInfo.getEncoded())); + } + catch (Exception e) + { + throw new IOException("cannot decode generic composite: " + e.getMessage(), e); + } + } + + return new CompositePrivateKey(privKeys); + } try { + ASN1Sequence seq; + // TODO: backwards compatibility code - should be deleted after 1.84. + try + { + ASN1Encodable obj = keyInfo.parsePrivateKey(); + if (obj instanceof ASN1OctetString) + { + seq = DERSequence.getInstance(ASN1OctetString.getInstance(obj).getOctets()); + } + else + { + seq = DERSequence.getInstance(obj); + } + } + catch (Exception e) + { + // new raw encoding - we capitalise on the fact initial key is first 32 bytes. + ASN1EncodableVector v = new ASN1EncodableVector(); + byte[] data = keyInfo.getPrivateKey().getOctets(); + + v.add(new DEROctetString(Arrays.copyOfRange(data, 0, 32))); + v.add(new DEROctetString(Arrays.copyOfRange(data, 32, data.length))); + + seq = new DERSequence(v); + } + List factories = getKeyFactoriesFromIdentifier(keyIdentifier); //Get key factories for each component algorithm. PrivateKey[] privateKeys = new PrivateKey[seq.size()]; + AlgorithmIdentifier[] algIds = pairings.get(keyIdentifier); for (int i = 0; i < seq.size(); i++) { - // We assume each component is of type OneAsymmetricKey (PrivateKeyInfo) as defined by the draft RFC - // and use the component key factory to decode the component key from PrivateKeyInfo. - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(PrivateKeyInfo.getInstance(seq.getObjectAt(i)).getEncoded()); - privateKeys[i] = factories.get(i).generatePrivate(keySpec); + if (seq.getObjectAt(i) instanceof ASN1OctetString) + { + ASN1EncodableVector v = new ASN1EncodableVector(3); + + v.add(keyInfo.getVersion()); + v.add(algIds[i]); + v.add(seq.getObjectAt(i)); + + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec( + PrivateKeyInfo.getInstance(new DERSequence(v)).getEncoded()); + privateKeys[i] = factories.get(i).generatePrivate(keySpec); + } + else + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(seq.getObjectAt(i)); + + // We assume each component is of type OneAsymmetricKey (PrivateKeyInfo) as defined by the draft RFC + // and use the component key factory to decode the component key from PrivateKeyInfo. + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(PrivateKeyInfo.getInstance(keySeq).getEncoded()); + privateKeys[i] = factories.get(i).generatePrivate(keySpec); + } } return new CompositePrivateKey(keyIdentifier, privateKeys); } @@ -126,32 +297,80 @@ public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) throws IOException { - ASN1Sequence seq = DERSequence.getInstance(keyInfo.getPublicKeyData().getBytes()); + if (helper == null) + { + helper = new BCJcaJceHelper(); + } + ASN1ObjectIdentifier keyIdentifier = keyInfo.getAlgorithm().getAlgorithm(); + + ASN1Sequence seq = null; + byte[][] componentKeys = new byte[2][]; + + try + { + seq = DERSequence.getInstance(keyInfo.getPublicKeyData().getBytes()); + } + catch (Exception e) + { + componentKeys = split(keyIdentifier, keyInfo.getPublicKeyData()); + } + + if (MiscObjectIdentifiers.id_alg_composite.equals(keyIdentifier) + || MiscObjectIdentifiers.id_composite_key.equals(keyIdentifier)) + { + ASN1Sequence keySeq = ASN1Sequence.getInstance(keyInfo.getPublicKeyData().getBytes()); + PublicKey[] pubKeys = new PublicKey[keySeq.size()]; + + for (int i = 0; i != keySeq.size(); i++) + { + SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(keySeq.getObjectAt(i)); + + try + { + pubKeys[i] = helper.createKeyFactory((pubInfo.getAlgorithm().getAlgorithm().getId())).generatePublic(new X509EncodedKeySpec(pubInfo.getEncoded())); + } + catch (Exception e) + { + throw new IOException("cannot decode generic composite: " + e.getMessage(), e); + } + } + + return new CompositePublicKey(pubKeys); + } try { + int numKeys = (seq == null) ? componentKeys.length : seq.size(); + List factories = getKeyFactoriesFromIdentifier(keyIdentifier); - ASN1BitString[] componentBitStrings = new ASN1BitString[seq.size()]; - for (int i = 0; i < seq.size(); i++) + ASN1BitString[] componentBitStrings = new ASN1BitString[numKeys]; + for (int i = 0; i < numKeys; i++) { // Check if component is OCTET STRING. If yes, convert it to BIT STRING. // This check should not be necessary since the draft RFC specifies components as BIT STRING encoded, // but currently the example public keys are OCTET STRING. So we leave it for interoperability. - if (seq.getObjectAt(i) instanceof DEROctetString) + if (seq != null) { - componentBitStrings[i] = new DERBitString(((DEROctetString)seq.getObjectAt(i)).getOctets()); + if (seq.getObjectAt(i) instanceof DEROctetString) + { + componentBitStrings[i] = new DERBitString(((DEROctetString)seq.getObjectAt(i)).getOctets()); + } + else + { + componentBitStrings[i] = (DERBitString)seq.getObjectAt(i); + } } else { - componentBitStrings[i] = (DERBitString)seq.getObjectAt(i); + componentBitStrings[i] = new DERBitString(componentKeys[i]); } } // We need to get X509EncodedKeySpec to use key factories to produce component public keys. X509EncodedKeySpec[] x509EncodedKeySpecs = getKeysSpecs(keyIdentifier, componentBitStrings); - PublicKey[] publicKeys = new PublicKey[seq.size()]; - for (int i = 0; i < seq.size(); i++) + PublicKey[] publicKeys = new PublicKey[numKeys]; + for (int i = 0; i < numKeys; i++) { publicKeys[i] = factories.get(i).generatePublic(x509EncodedKeySpecs[i]); } @@ -164,6 +383,15 @@ public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) } } + byte[][] split(ASN1ObjectIdentifier algorithm, ASN1BitString publicKeyData) + { + int[] sizes = componentKeySizes.get(algorithm); + byte[] keyData = publicKeyData.getOctets(); + byte[][] components = new byte[][] { new byte[sizes[0]], new byte[sizes[1]] }; + + return components; + } + /** * A helper method that returns a list of KeyFactory objects based on the composite signature OID. * @@ -178,48 +406,14 @@ private List getKeyFactoriesFromIdentifier(ASN1ObjectIdentifier algo List factories = new ArrayList(); List algorithmNames = new ArrayList(); - switch (CompositeSignaturesConstants.ASN1IdentifierCompositeNameMap.get(algorithmIdentifier)) + String[] pairings = CompositeIndex.getPairing(algorithmIdentifier); + if (pairings == null) { - case MLDSA44_Ed25519_SHA512: - case MLDSA65_Ed25519_SHA512: - algorithmNames.add("Dilithium"); - algorithmNames.add("Ed25519"); - break; - case MLDSA87_Ed448_SHA512: - algorithmNames.add("Dilithium"); - algorithmNames.add("Ed448"); - break; - case MLDSA44_RSA2048_PSS_SHA256: - case MLDSA44_RSA2048_PKCS15_SHA256: - case MLDSA65_RSA3072_PSS_SHA512: - case MLDSA65_RSA3072_PKCS15_SHA512: - algorithmNames.add("Dilithium"); - algorithmNames.add("RSA"); - break; - case MLDSA44_ECDSA_P256_SHA256: - case MLDSA44_ECDSA_brainpoolP256r1_SHA256: - case MLDSA65_ECDSA_P256_SHA512: - case MLDSA65_ECDSA_brainpoolP256r1_SHA512: - case MLDSA87_ECDSA_P384_SHA512: - case MLDSA87_ECDSA_brainpoolP384r1_SHA512: - algorithmNames.add("Dilithium"); - algorithmNames.add("ECDSA"); - break; - case Falcon512_Ed25519_SHA512: - algorithmNames.add("Falcon"); - algorithmNames.add("Ed25519"); - break; - case Falcon512_ECDSA_P256_SHA256: - case Falcon512_ECDSA_brainpoolP256r1_SHA256: - algorithmNames.add("Falcon"); - algorithmNames.add("ECDSA"); - break; - default: - throw new IllegalArgumentException("Cannot create KeyFactories. Unsupported algorithm identifier."); + throw new NoSuchAlgorithmException("Cannot create KeyFactories. Unsupported algorithm identifier."); } - factories.add(KeyFactory.getInstance(algorithmNames.get(0), "BC")); - factories.add(KeyFactory.getInstance(algorithmNames.get(1), "BC")); + factories.add(helper.createKeyFactory(CompositeIndex.getBaseName(pairings[0]))); + factories.add(helper.createKeyFactory(CompositeIndex.getBaseName(pairings[1]))); return Collections.unmodifiableList(factories); } @@ -239,70 +433,16 @@ private X509EncodedKeySpec[] getKeysSpecs(ASN1ObjectIdentifier algorithmIdentifi X509EncodedKeySpec[] specs = new X509EncodedKeySpec[subjectPublicKeys.length]; SubjectPublicKeyInfo[] keyInfos = new SubjectPublicKeyInfo[subjectPublicKeys.length]; - switch (CompositeSignaturesConstants.ASN1IdentifierCompositeNameMap.get(algorithmIdentifier)) + AlgorithmIdentifier[] algIds = pairings.get(algorithmIdentifier); + + if (algIds == null) { - case MLDSA44_Ed25519_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium2Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ed25519Identifier, subjectPublicKeys[1]); - break; - case MLDSA44_ECDSA_P256_SHA256: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium2Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaP256Identifier, subjectPublicKeys[1]); - break; - case MLDSA44_ECDSA_brainpoolP256r1_SHA256: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium2Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaBrainpoolP256r1Identifier, subjectPublicKeys[1]); - break; - case MLDSA44_RSA2048_PSS_SHA256: - case MLDSA44_RSA2048_PKCS15_SHA256: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium2Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(rsaIdentifier, subjectPublicKeys[1]); - break; - case MLDSA65_Ed25519_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium3Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ed25519Identifier, subjectPublicKeys[1]); - break; - case MLDSA65_ECDSA_P256_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium3Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaP256Identifier, subjectPublicKeys[1]); - break; - case MLDSA65_ECDSA_brainpoolP256r1_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium3Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaBrainpoolP256r1Identifier, subjectPublicKeys[1]); - break; - case MLDSA65_RSA3072_PSS_SHA512: - case MLDSA65_RSA3072_PKCS15_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium3Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(rsaIdentifier, subjectPublicKeys[1]); - break; - case MLDSA87_Ed448_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium5Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ed448Identifier, subjectPublicKeys[1]); - break; - case MLDSA87_ECDSA_P384_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium5Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaP384Identifier, subjectPublicKeys[1]); - break; - case MLDSA87_ECDSA_brainpoolP384r1_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(dilithium5Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaBrainpoolP384r1Identifier, subjectPublicKeys[1]); - break; - case Falcon512_Ed25519_SHA512: - keyInfos[0] = new SubjectPublicKeyInfo(falcon512Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ed25519Identifier, subjectPublicKeys[1]); - break; - case Falcon512_ECDSA_P256_SHA256: - keyInfos[0] = new SubjectPublicKeyInfo(falcon512Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaP256Identifier, subjectPublicKeys[1]); - break; - case Falcon512_ECDSA_brainpoolP256r1_SHA256: - keyInfos[0] = new SubjectPublicKeyInfo(falcon512Identifier, subjectPublicKeys[0]); - keyInfos[1] = new SubjectPublicKeyInfo(ecdsaBrainpoolP256r1Identifier, subjectPublicKeys[1]); - break; - default: - throw new IllegalArgumentException("Cannot create key specs. Unsupported algorithm identifier."); + throw new IOException("Cannot create key specs. Unsupported algorithm identifier."); } + keyInfos[0] = new SubjectPublicKeyInfo(algIds[0], subjectPublicKeys[0]); + keyInfos[1] = new SubjectPublicKeyInfo(algIds[1], subjectPublicKeys[1]); + specs[0] = new X509EncodedKeySpec(keyInfos[0].getEncoded()); specs[1] = new X509EncodedKeySpec(keyInfos[1].getEncoded()); return specs; diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyPairGeneratorSpi.java index f74da56a5a..2fdaad28f3 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyPairGeneratorSpi.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/KeyPairGeneratorSpi.java @@ -1,25 +1,17 @@ package org.bouncycastle.jcajce.provider.asymmetric.compositesignatures; -import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.ECGenParameterSpec; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.jcajce.CompositePrivateKey; import org.bouncycastle.jcajce.CompositePublicKey; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; -import org.bouncycastle.pqc.jcajce.spec.FalconParameterSpec; /** @@ -28,138 +20,38 @@ public class KeyPairGeneratorSpi extends java.security.KeyPairGeneratorSpi { - //Enum value of the selected composite signature algorithm. - private final CompositeSignaturesConstants.CompositeName algorithmIdentifier; - //ASN1 OI value of the selected composite signature algorithm. - private final ASN1ObjectIdentifier algorithmIdentifierASN1; - - //List of KeyPairGenerators. Each entry corresponds to a component signature from the composite definition. - private List generators; + private final ASN1ObjectIdentifier algorithm; + private final KeyPairGenerator[] generators; private SecureRandom secureRandom; private boolean parametersInitialized = false; - KeyPairGeneratorSpi(CompositeSignaturesConstants.CompositeName algorithmIdentifier) + KeyPairGeneratorSpi(ASN1ObjectIdentifier algorithm) { - this.algorithmIdentifier = algorithmIdentifier; - this.algorithmIdentifierASN1 = CompositeSignaturesConstants.compositeNameASN1IdentifierMap.get(this.algorithmIdentifier); - } + this.algorithm = algorithm; - /** - * Creates a list of KeyPairGenerators based on the selected composite algorithm (algorithmIdentifier). - * Each component generator is initialized with parameters according to the specification https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html. - * Called after initialize() method or right before keypair generation in case initialize() was not called by the user. - */ - private void initializeParameters() - { + String[] algorithms = CompositeIndex.getPairing(algorithm); + AlgorithmParameterSpec[] initSpecs = CompositeIndex.getKeyPairSpecs(algorithm); - if (this.secureRandom == null) + this.generators = new KeyPairGenerator[algorithms.length]; + for (int i = 0; i != algorithms.length; i++) { - this.secureRandom = new SecureRandom(); - } + try + { + this.generators[i] = KeyPairGenerator.getInstance(CompositeIndex.getBaseName(algorithms[i]), "BC"); - List generators = new ArrayList(); - try - { - switch (this.algorithmIdentifier) + + AlgorithmParameterSpec initSpec = initSpecs[i]; + if (initSpec != null) + { + this.generators[i].initialize(initSpec); + } + } + catch (Exception e) { - case MLDSA44_Ed25519_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("Ed25519", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium2, this.secureRandom); - generators.get(1).initialize(256, this.secureRandom); - break; - case MLDSA65_Ed25519_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("Ed25519", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium3, this.secureRandom); - generators.get(1).initialize(256, this.secureRandom); - break; - case MLDSA87_Ed448_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("Ed448", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium5, this.secureRandom); - generators.get(1).initialize(448, this.secureRandom); - break; - case MLDSA44_RSA2048_PSS_SHA256: - case MLDSA44_RSA2048_PKCS15_SHA256: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("RSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium2, this.secureRandom); - generators.get(1).initialize(2048, this.secureRandom); - break; - case MLDSA65_RSA3072_PSS_SHA512: - case MLDSA65_RSA3072_PKCS15_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("RSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium3, this.secureRandom); - generators.get(1).initialize(3072, this.secureRandom); - break; - case MLDSA44_ECDSA_P256_SHA256: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium2, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("P-256"), this.secureRandom); - break; - case MLDSA44_ECDSA_brainpoolP256r1_SHA256: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium2, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("brainpoolP256r1"), this.secureRandom); - break; - case MLDSA65_ECDSA_P256_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium3, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("P-256"), this.secureRandom); - break; - case MLDSA65_ECDSA_brainpoolP256r1_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium3, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("brainpoolP256r1"), this.secureRandom); - break; - case MLDSA87_ECDSA_P384_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium5, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("P-384"), this.secureRandom); - break; - case MLDSA87_ECDSA_brainpoolP384r1_SHA512: - generators.add(KeyPairGenerator.getInstance("Dilithium", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(DilithiumParameterSpec.dilithium5, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("brainpoolP384r1"), this.secureRandom); - break; - case Falcon512_ECDSA_P256_SHA256: - generators.add(KeyPairGenerator.getInstance("Falcon", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(FalconParameterSpec.falcon_512, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("P-256"), this.secureRandom); - break; - case Falcon512_ECDSA_brainpoolP256r1_SHA256: - generators.add(KeyPairGenerator.getInstance("Falcon", "BC")); - generators.add(KeyPairGenerator.getInstance("ECDSA", "BC")); - generators.get(0).initialize(FalconParameterSpec.falcon_512, this.secureRandom); - generators.get(1).initialize(new ECGenParameterSpec("brainpoolP256r1"), this.secureRandom); - break; - case Falcon512_Ed25519_SHA512: - generators.add(KeyPairGenerator.getInstance("Falcon", "BC")); - generators.add(KeyPairGenerator.getInstance("Ed25519", "BC")); - generators.get(0).initialize(FalconParameterSpec.falcon_512, this.secureRandom); - generators.get(1).initialize(256, this.secureRandom); - break; - default: - throw new IllegalStateException("Generators not correctly initialized. Unsupported composite algorithm."); + throw new IllegalStateException("unable to create base generator: " + e.getMessage()); } } - catch (GeneralSecurityException e) - { - throw new RuntimeException(e); - } - - this.generators = Collections.unmodifiableList(generators); - this.parametersInitialized = true; } /** @@ -192,17 +84,19 @@ public void initialize(AlgorithmParameterSpec paramSpec, SecureRandom secureRand throw new IllegalArgumentException("Use initialize only for custom SecureRandom. AlgorithmParameterSpec must be null because it is determined by algorithm name."); } - this.secureRandom = secureRandom; - initializeParameters(); + AlgorithmParameterSpec[] initSpecs = CompositeIndex.getKeyPairSpecs(algorithm); + for (int i = 0; i != initSpecs.length; i++) + { + AlgorithmParameterSpec initSpec = initSpecs[i]; + if (initSpec != null) + { + this.generators[i].initialize(initSpec, secureRandom); + } + } } public KeyPair generateKeyPair() { - if (!this.parametersInitialized) - { - this.initializeParameters(); - } - return getCompositeKeyPair(); } @@ -214,79 +108,142 @@ public KeyPair generateKeyPair() */ private KeyPair getCompositeKeyPair() { - PublicKey[] publicKeys = new PublicKey[generators.size()]; - PrivateKey[] privateKeys = new PrivateKey[generators.size()]; - for (int i = 0; i < generators.size(); i++) + PublicKey[] publicKeys = new PublicKey[generators.length]; + PrivateKey[] privateKeys = new PrivateKey[generators.length]; + for (int i = 0; i < generators.length; i++) { - KeyPair keyPair = generators.get(i).generateKeyPair(); + KeyPair keyPair = generators[i].generateKeyPair(); publicKeys[i] = keyPair.getPublic(); privateKeys[i] = keyPair.getPrivate(); } - CompositePublicKey compositePublicKey = new CompositePublicKey(this.algorithmIdentifierASN1, publicKeys); - CompositePrivateKey compositePrivateKey = new CompositePrivateKey(this.algorithmIdentifierASN1, privateKeys); + CompositePublicKey compositePublicKey = new CompositePublicKey(this.algorithm, publicKeys); + CompositePrivateKey compositePrivateKey = new CompositePrivateKey(this.algorithm, privateKeys); return new KeyPair(compositePublicKey, compositePrivateKey); } + + public static final class HashMLDSA44_ECDSA_P256_SHA256 + extends KeyPairGeneratorSpi + { + public HashMLDSA44_ECDSA_P256_SHA256() + { + super(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256); + } + } - public static final class MLDSA44_Ed25519_SHA512 + public static final class HashMLDSA44_Ed25519_SHA512 extends KeyPairGeneratorSpi { - public MLDSA44_Ed25519_SHA512() + public HashMLDSA44_Ed25519_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_Ed25519_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512); } } - public static final class MLDSA65_Ed25519_SHA512 + public static final class HashMLDSA44_RSA2048_PKCS15_SHA256 extends KeyPairGeneratorSpi { - public MLDSA65_Ed25519_SHA512() + public HashMLDSA44_RSA2048_PKCS15_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_Ed25519_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256); } } - public static final class MLDSA87_Ed448_SHA512 + public static final class HashMLDSA44_RSA2048_PSS_SHA256 extends KeyPairGeneratorSpi { - public MLDSA87_Ed448_SHA512() + public HashMLDSA44_RSA2048_PSS_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA87_Ed448_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256); } } - public static final class MLDSA44_RSA2048_PSS_SHA256 + public static final class HashMLDSA65_ECDSA_brainpoolP256r1_SHA512 extends KeyPairGeneratorSpi { - public MLDSA44_RSA2048_PSS_SHA256() + public HashMLDSA65_ECDSA_brainpoolP256r1_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_RSA2048_PSS_SHA256); + super(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512); } } - public static final class MLDSA44_RSA2048_PKCS15_SHA256 + public static final class HashMLDSA65_ECDSA_P384_SHA512 extends KeyPairGeneratorSpi { - public MLDSA44_RSA2048_PKCS15_SHA256() + public HashMLDSA65_ECDSA_P384_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512); + } + } + + public static final class HashMLDSA65_Ed25519_SHA512 + extends KeyPairGeneratorSpi + { + public HashMLDSA65_Ed25519_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512); + } + } + + public static final class HashMLDSA65_RSA3072_PKCS15_SHA512 + extends KeyPairGeneratorSpi + { + public HashMLDSA65_RSA3072_PKCS15_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512); + } + } + + public static final class HashMLDSA65_RSA3072_PSS_SHA512 + extends KeyPairGeneratorSpi + { + public HashMLDSA65_RSA3072_PSS_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512); + } + } + + public static final class HashMLDSA65_RSA4096_PKCS15_SHA512 + extends KeyPairGeneratorSpi + { + public HashMLDSA65_RSA4096_PKCS15_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_RSA2048_PKCS15_SHA256); + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512); } } - public static final class MLDSA65_RSA3072_PSS_SHA512 + public static final class HashMLDSA65_RSA4096_PSS_SHA512 extends KeyPairGeneratorSpi { - public MLDSA65_RSA3072_PSS_SHA512() + public HashMLDSA65_RSA4096_PSS_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_RSA3072_PSS_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512); } } - public static final class MLDSA65_RSA3072_PKCS15_SHA512 + public static final class HashMLDSA87_ECDSA_brainpoolP384r1_SHA512 extends KeyPairGeneratorSpi { - public MLDSA65_RSA3072_PKCS15_SHA512() + public HashMLDSA87_ECDSA_brainpoolP384r1_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_RSA3072_PKCS15_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512); + } + } + + public static final class HashMLDSA87_ECDSA_P384_SHA512 + extends KeyPairGeneratorSpi + { + public HashMLDSA87_ECDSA_P384_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512); + } + } + + public static final class HashMLDSA87_Ed448_SHA512 + extends KeyPairGeneratorSpi + { + public HashMLDSA87_Ed448_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512); } } @@ -295,81 +252,124 @@ public static final class MLDSA44_ECDSA_P256_SHA256 { public MLDSA44_ECDSA_P256_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_ECDSA_P256_SHA256); + super(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); + } + } + + public static final class MLDSA44_Ed25519_SHA512 + extends KeyPairGeneratorSpi + { + public MLDSA44_Ed25519_SHA512() + { + super(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512); + } + } + + public static final class MLDSA44_RSA2048_PKCS15_SHA256 + extends KeyPairGeneratorSpi + { + public MLDSA44_RSA2048_PKCS15_SHA256() + { + super(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256); } } - public static final class MLDSA44_ECDSA_brainpoolP256r1_SHA256 + public static final class MLDSA44_RSA2048_PSS_SHA256 extends KeyPairGeneratorSpi { - public MLDSA44_ECDSA_brainpoolP256r1_SHA256() + public MLDSA44_RSA2048_PSS_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_ECDSA_brainpoolP256r1_SHA256); + super(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256); } } - public static final class MLDSA65_ECDSA_P256_SHA512 + public static final class MLDSA65_ECDSA_brainpoolP256r1_SHA256 extends KeyPairGeneratorSpi { - public MLDSA65_ECDSA_P256_SHA512() + public MLDSA65_ECDSA_brainpoolP256r1_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_ECDSA_P256_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256); } } - public static final class MLDSA65_ECDSA_brainpoolP256r1_SHA512 + public static final class MLDSA65_ECDSA_P384_SHA384 extends KeyPairGeneratorSpi { - public MLDSA65_ECDSA_brainpoolP256r1_SHA512() + public MLDSA65_ECDSA_P384_SHA384() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_ECDSA_brainpoolP256r1_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384); } } - public static final class MLDSA87_ECDSA_P384_SHA512 + public static final class MLDSA65_Ed25519_SHA512 extends KeyPairGeneratorSpi { - public MLDSA87_ECDSA_P384_SHA512() + public MLDSA65_Ed25519_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA87_ECDSA_P384_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512); } } - public static final class MLDSA87_ECDSA_brainpoolP384r1_SHA512 + public static final class MLDSA65_RSA3072_PKCS15_SHA256 extends KeyPairGeneratorSpi { - public MLDSA87_ECDSA_brainpoolP384r1_SHA512() + public MLDSA65_RSA3072_PKCS15_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA87_ECDSA_brainpoolP384r1_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256); } } - public static final class Falcon512_Ed25519_SHA512 + public static final class MLDSA65_RSA3072_PSS_SHA256 extends KeyPairGeneratorSpi { - public Falcon512_Ed25519_SHA512() + public MLDSA65_RSA3072_PSS_SHA256() { - super(CompositeSignaturesConstants.CompositeName.Falcon512_Ed25519_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256); } } - public static final class Falcon512_ECDSA_P256_SHA256 + public static final class MLDSA65_RSA4096_PKCS15_SHA384 extends KeyPairGeneratorSpi { - public Falcon512_ECDSA_P256_SHA256() + public MLDSA65_RSA4096_PKCS15_SHA384() { - super(CompositeSignaturesConstants.CompositeName.Falcon512_ECDSA_P256_SHA256); + super(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384); } } - public static final class Falcon512_ECDSA_brainpoolP256r1_SHA256 + public static final class MLDSA65_RSA4096_PSS_SHA384 extends KeyPairGeneratorSpi { - public Falcon512_ECDSA_brainpoolP256r1_SHA256() + public MLDSA65_RSA4096_PSS_SHA384() { - super(CompositeSignaturesConstants.CompositeName.Falcon512_ECDSA_brainpoolP256r1_SHA256); + super(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384); } } + public static final class MLDSA87_ECDSA_brainpoolP384r1_SHA384 + extends KeyPairGeneratorSpi + { + public MLDSA87_ECDSA_brainpoolP384r1_SHA384() + { + super(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384); + } + } + public static final class MLDSA87_ECDSA_P384_SHA384 + extends KeyPairGeneratorSpi + { + public MLDSA87_ECDSA_P384_SHA384() + { + super(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384); + } + } + + public static final class MLDSA87_Ed448_SHA512 + extends KeyPairGeneratorSpi + { + public MLDSA87_Ed448_SHA512() + { + super(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512); + } + } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/SignatureSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/SignatureSpi.java index 29d0680c7c..6fa7c0fd0c 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/SignatureSpi.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/compositesignatures/SignatureSpi.java @@ -3,17 +3,18 @@ import java.io.IOException; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.InvalidParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; +import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; -import java.util.ArrayList; -import java.util.Collections; +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.bouncycastle.asn1.ASN1BitString; import org.bouncycastle.asn1.ASN1EncodableVector; @@ -22,10 +23,16 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.util.DigestFactory; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.jcajce.CompositePrivateKey; import org.bouncycastle.jcajce.CompositePublicKey; +import org.bouncycastle.jcajce.spec.ContextParameterSpec; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.util.Exceptions; /** @@ -34,125 +41,117 @@ public class SignatureSpi extends java.security.SignatureSpi { - //Enum value of the selected composite signature algorithm. - private final CompositeSignaturesConstants.CompositeName algorithmIdentifier; - //ASN1 OI value of the selected composite signature algorithm. - private final ASN1ObjectIdentifier algorithmIdentifierASN1; + private static final Map canonicalNames = new HashMap(); - //List of Signatures. Each entry corresponds to a component signature from the composite definition. - private final List componentSignatures; + private static final String ML_DSA_44 = "ML-DSA-44"; + private static final String ML_DSA_65 = "ML-DSA-65"; + private static final String ML_DSA_87 = "ML-DSA-87"; - //Hash function that is used to pre-hash the input message before it is fed into the component Signature. - //Each composite signature has a specific hash function https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html - private final Digest digest; - private byte[] OIDBytes; + private Key compositeKey; + static + { + canonicalNames.put("MLDSA44", ML_DSA_44); + canonicalNames.put("MLDSA65", ML_DSA_65); + canonicalNames.put("MLDSA87", ML_DSA_87); + canonicalNames.put(NISTObjectIdentifiers.id_ml_dsa_44.getId(), ML_DSA_44); + canonicalNames.put(NISTObjectIdentifiers.id_ml_dsa_65.getId(), ML_DSA_65); + canonicalNames.put(NISTObjectIdentifiers.id_ml_dsa_87.getId(), ML_DSA_87); + } - SignatureSpi(CompositeSignaturesConstants.CompositeName algorithmIdentifier) + //List of Signatures. Each entry corresponds to a component signature from the composite definition. + private final ASN1ObjectIdentifier algorithm; + private final Signature[] componentSignatures; + private final byte[] domain; + private final Digest preHashDigest; + private final byte[] hashOID; + private final JcaJceHelper helper = new BCJcaJceHelper(); + + private ContextParameterSpec contextSpec; + private AlgorithmParameters engineParams = null; + + private boolean unprimed = true; + + SignatureSpi(ASN1ObjectIdentifier algorithm) { - this.algorithmIdentifier = algorithmIdentifier; - this.algorithmIdentifierASN1 = CompositeSignaturesConstants.compositeNameASN1IdentifierMap.get(this.algorithmIdentifier); - List componentSignatures = new ArrayList(); - try + this(algorithm, null, null); + } + + SignatureSpi(ASN1ObjectIdentifier algorithm, Digest preHashDigest, ASN1ObjectIdentifier preHashOid) + { + this.algorithm = algorithm; + this.preHashDigest = preHashDigest; + + String[] algs = CompositeIndex.getPairing(algorithm); + + if (preHashDigest != null) { - switch (this.algorithmIdentifier) + try { - case MLDSA44_Ed25519_SHA512: - case MLDSA65_Ed25519_SHA512: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("Ed25519", "BC")); - this.digest = DigestFactory.createSHA512(); - break; - case MLDSA87_Ed448_SHA512: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("Ed448", "BC")); - this.digest = DigestFactory.createSHA512(); - break; - case MLDSA44_RSA2048_PSS_SHA256: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("SHA256withRSA/PSS", "BC")); //PSS with SHA-256 as digest algo and MGF. - this.digest = DigestFactory.createSHA256(); - break; - case MLDSA65_RSA3072_PSS_SHA512: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("SHA512withRSA/PSS", "BC")); //PSS with SHA-512 as digest algo and MGF. - this.digest = DigestFactory.createSHA512(); - break; - case MLDSA44_RSA2048_PKCS15_SHA256: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("SHA256withRSA", "BC")); //PKCS15 - this.digest = DigestFactory.createSHA256(); - break; - case MLDSA65_RSA3072_PKCS15_SHA512: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("SHA512withRSA", "BC")); //PKCS15 - this.digest = DigestFactory.createSHA512(); - break; - case MLDSA44_ECDSA_P256_SHA256: - case MLDSA44_ECDSA_brainpoolP256r1_SHA256: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("SHA256withECDSA", "BC")); - this.digest = DigestFactory.createSHA256(); - break; - case MLDSA65_ECDSA_P256_SHA512: - case MLDSA65_ECDSA_brainpoolP256r1_SHA512: - case MLDSA87_ECDSA_P384_SHA512: - case MLDSA87_ECDSA_brainpoolP384r1_SHA512: - componentSignatures.add(Signature.getInstance("Dilithium", "BC")); - componentSignatures.add(Signature.getInstance("SHA512withECDSA", "BC")); - this.digest = DigestFactory.createSHA512(); - break; - case Falcon512_ECDSA_P256_SHA256: - case Falcon512_ECDSA_brainpoolP256r1_SHA256: - componentSignatures.add(Signature.getInstance("Falcon", "BC")); - componentSignatures.add(Signature.getInstance("SHA256withECDSA", "BC")); - this.digest = DigestFactory.createSHA256(); - break; - case Falcon512_Ed25519_SHA512: - componentSignatures.add(Signature.getInstance("Falcon", "BC")); - componentSignatures.add(Signature.getInstance("Ed25519", "BC")); - this.digest = DigestFactory.createSHA512(); - break; - default: - throw new IllegalArgumentException("unknown composite algorithm"); + this.hashOID = preHashOid.getEncoded(); + } + catch (IOException e) + { // if this happens, we're in real trouble! + throw new IllegalStateException("unable to encode domain value"); } - - //get bytes of composite signature algorithm OID in DER - //these bytes are used a prefix to the message digest https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html#name-composite-sign - OIDBytes = this.algorithmIdentifierASN1.getEncoded(ASN1Encoding.DER); } - catch (GeneralSecurityException e) + else { - throw Exceptions.illegalStateException(e.getMessage(), e); + hashOID = null; + } + + try + { + this.domain = algorithm.getEncoded(); } catch (IOException e) + { // if this happens, we're in real trouble! + throw new IllegalStateException("unable to encode domain value"); + } + + this.componentSignatures = new Signature[algs.length]; + try + { + for (int i = 0; i != componentSignatures.length; i++) + { + componentSignatures[i] = Signature.getInstance(algs[i], "BC"); + } + } + catch (GeneralSecurityException e) { throw Exceptions.illegalStateException(e.getMessage(), e); } - this.componentSignatures = Collections.unmodifiableList(componentSignatures); } protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { - if (!(publicKey instanceof CompositePublicKey)) { throw new InvalidKeyException("Public key is not composite."); } - CompositePublicKey compositePublicKey = (CompositePublicKey)publicKey; + this.compositeKey = publicKey; - if (!compositePublicKey.getAlgorithmIdentifier().equals(this.algorithmIdentifierASN1)) + CompositePublicKey compositePublicKey = (CompositePublicKey)this.compositeKey; + if (!compositePublicKey.getAlgorithmIdentifier().equals(this.algorithm)) { throw new InvalidKeyException("Provided composite public key cannot be used with the composite signature algorithm."); } - //for each component signature run initVerify with the corresponding public key. - for (int i = 0; i < this.componentSignatures.size(); i++) + sigInitVerify(); + } + + private void sigInitVerify() + throws InvalidKeyException + { + CompositePublicKey compositePublicKey = (CompositePublicKey)this.compositeKey; + for (int i = 0; i < this.componentSignatures.length; i++) { - this.componentSignatures.get(i).initVerify(compositePublicKey.getPublicKeys().get(i)); + this.componentSignatures[i].initVerify(compositePublicKey.getPublicKeys().get(i)); } + + this.unprimed = true; } protected void engineInitSign(PrivateKey privateKey) @@ -163,31 +162,108 @@ protected void engineInitSign(PrivateKey privateKey) throw new InvalidKeyException("Private key is not composite."); } + this.compositeKey = privateKey; + CompositePrivateKey compositePrivateKey = (CompositePrivateKey)privateKey; - - if (!compositePrivateKey.getAlgorithmIdentifier().equals(this.algorithmIdentifierASN1)) + if (!compositePrivateKey.getAlgorithmIdentifier().equals(this.algorithm)) { throw new InvalidKeyException("Provided composite private key cannot be used with the composite signature algorithm."); } + sigInitSign(); + } + + private void sigInitSign() + throws InvalidKeyException + { + CompositePrivateKey compositePrivateKey = (CompositePrivateKey)this.compositeKey; //for each component signature run initVerify with the corresponding private key. - for (int i = 0; i < this.componentSignatures.size(); i++) + for (int i = 0; i < this.componentSignatures.length; i++) { - this.componentSignatures.get(i).initSign(compositePrivateKey.getPrivateKeys().get(i)); + this.componentSignatures[i].initSign(compositePrivateKey.getPrivateKeys().get(i)); } + this.unprimed = true; } + private void baseSigInit() + throws SignatureException + { + try + { + componentSignatures[0].setParameter(new ContextParameterSpec(domain)); + } + catch (InvalidAlgorithmParameterException e) + { + throw new IllegalStateException("unable to set context on ML-DSA"); + } + + if (preHashDigest == null) + { + for (int i = 0; i < this.componentSignatures.length; i++) + { + Signature componentSig = this.componentSignatures[i]; + componentSig.update(domain); + if (contextSpec == null) + { + componentSig.update((byte)0); + } + else + { + byte[] ctx = contextSpec.getContext(); + + componentSig.update((byte)ctx.length); + componentSig.update(ctx); + } + } + } + + this.unprimed = false; + } protected void engineUpdate(byte b) throws SignatureException { - digest.update(b); + if (unprimed) + { + baseSigInit(); + } + + if (preHashDigest != null) + { + preHashDigest.update(b); + } + else + { + for (int i = 0; i < this.componentSignatures.length; i++) + { + Signature componentSig = this.componentSignatures[i]; + + componentSig.update(b); + } + } } protected void engineUpdate(byte[] bytes, int off, int len) throws SignatureException { - digest.update(bytes, off, len); + if (unprimed) + { + baseSigInit(); + } + + if (preHashDigest != null) + { + preHashDigest.update(bytes, off, len); + } + else + { + for (int i = 0; i < this.componentSignatures.length; i++) + { + Signature componentSig = this.componentSignatures[i]; + + componentSig.update(bytes, off, len); + } + } } /** @@ -200,18 +276,17 @@ protected void engineUpdate(byte[] bytes, int off, int len) protected byte[] engineSign() throws SignatureException { + if (preHashDigest != null) + { + processPreHashedMessage(); + } + ASN1EncodableVector signatureSequence = new ASN1EncodableVector(); try { - //calculate message digest (pre-hashing of the message) - byte[] digestResult = new byte[digest.getDigestSize()]; - digest.doFinal(digestResult, 0); - - for (int i = 0; i < this.componentSignatures.size(); i++) + for (int i = 0; i < this.componentSignatures.length; i++) { - this.componentSignatures.get(i).update(this.OIDBytes); - this.componentSignatures.get(i).update(digestResult); //in total, "OID || digest(message)" is the message fed into each component signature - byte[] signatureValue = this.componentSignatures.get(i).sign(); + byte[] signatureValue = this.componentSignatures[i].sign(); signatureSequence.add(new DERBitString(signatureValue)); } @@ -221,7 +296,33 @@ protected byte[] engineSign() { throw new SignatureException(e.getMessage()); } + } + + private void processPreHashedMessage() + throws SignatureException + { + byte[] dig = new byte[preHashDigest.getDigestSize()]; + + preHashDigest.doFinal(dig, 0); + + for (int i = 0; i < this.componentSignatures.length; i++) + { + Signature componentSig = this.componentSignatures[i]; + componentSig.update(domain, 0, domain.length); + if (contextSpec == null) + { + componentSig.update((byte)0); + } + else + { + byte[] ctx = contextSpec.getContext(); + componentSig.update((byte)ctx.length); + componentSig.update(ctx); + } + componentSig.update(hashOID, 0, hashOID.length); + componentSig.update(dig, 0, dig.length); + } } /** @@ -236,28 +337,29 @@ protected byte[] engineSign() protected boolean engineVerify(byte[] signature) throws SignatureException { - ASN1Sequence signatureSequence = DERSequence.getInstance(signature); //Check if the decoded sequence of component signatures has the expected size. - if (signatureSequence.size() != this.componentSignatures.size()) + if (signatureSequence.size() != this.componentSignatures.length) { return false; } - //calculate message digest (pre-hashing of the message) - byte[] digestResult = new byte[digest.getDigestSize()]; - digest.doFinal(digestResult, 0); - + if (preHashDigest != null) + { + if (preHashDigest != null) + { + processPreHashedMessage(); + } + } + // Currently all signatures try to verify even if, e.g., the first is invalid. // If each component verify() is constant time, then this is also, otherwise it does not make sense to iterate over all if one of them already fails. // However, it is important that we do not provide specific error messages, e.g., "only the 2nd component failed to verify". boolean fail = false; - for (int i = 0; i < this.componentSignatures.size(); i++) + for (int i = 0; i < this.componentSignatures.length; i++) { - this.componentSignatures.get(i).update(this.OIDBytes); - this.componentSignatures.get(i).update(digestResult); //in total, "OID || digest(message)" is the message fed into each component signature - if (!this.componentSignatures.get(i).verify(ASN1BitString.getInstance(signatureSequence.getObjectAt(i)).getOctets())) + if (!this.componentSignatures[i].verify(ASN1BitString.getInstance(signatureSequence.getObjectAt(i)).getOctets())) { fail = true; } @@ -266,6 +368,65 @@ protected boolean engineVerify(byte[] signature) return !fail; } + protected void engineSetParameter(AlgorithmParameterSpec algorithmParameterSpec) + throws InvalidAlgorithmParameterException + { + if (!unprimed) + { + throw new InvalidAlgorithmParameterException("attempt to set parameter after update"); + } + + if (algorithmParameterSpec instanceof ContextParameterSpec) + { + contextSpec = (ContextParameterSpec)algorithmParameterSpec; + try + { + if (compositeKey instanceof PublicKey) + { + sigInitVerify(); + } + else + { + sigInitSign(); + } + } + catch (InvalidKeyException e) + { + throw new InvalidAlgorithmParameterException("keys invalid on reset: " + e.getMessage(), e); + } + } + else + { + throw new InvalidAlgorithmParameterException("unknown parameterSpec passed to composite signature"); + } + } + + private void setSigParameter(Signature targetSig, String targetSigName, List names, List specs) + throws InvalidAlgorithmParameterException + { + for (int i = 0; i != names.size(); i++) + { + String canonicalName = getCanonicalName(names.get(i)); + + if (names.get(i).equals(targetSigName)) + { + targetSig.setParameter(specs.get(i)); + } + } + } + + private String getCanonicalName(String baseName) + { + String name = canonicalNames.get(baseName); + + if (name != null) + { + return name; + } + + return baseName; + } + protected void engineSetParameter(String s, Object o) throws InvalidParameterException { @@ -278,152 +439,276 @@ protected Object engineGetParameter(String s) throw new UnsupportedOperationException("engineGetParameter unsupported"); } - protected AlgorithmParameters engineGetParameters() + protected final AlgorithmParameters engineGetParameters() { - return null; + if (engineParams == null) + { + if (contextSpec != null) + { + try + { + engineParams = helper.createAlgorithmParameters("CONTEXT"); + engineParams.init(contextSpec); + } + catch (Exception e) + { + throw Exceptions.illegalStateException(e.toString(), e); + } + } + } + + return engineParams; } - public final static class MLDSA44_Ed25519_SHA512 + public static final class HashMLDSA44_ECDSA_P256_SHA256 extends SignatureSpi { - public MLDSA44_Ed25519_SHA512() + public HashMLDSA44_ECDSA_P256_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_Ed25519_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA44_ECDSA_P256_SHA256, new SHA256Digest(), NISTObjectIdentifiers.id_sha256); } } - public final static class MLDSA65_Ed25519_SHA512 + public static final class HashMLDSA44_Ed25519_SHA512 extends SignatureSpi { - public MLDSA65_Ed25519_SHA512() + public HashMLDSA44_Ed25519_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_Ed25519_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA44_Ed25519_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); } } - public final static class MLDSA87_Ed448_SHA512 + public static final class HashMLDSA44_RSA2048_PKCS15_SHA256 extends SignatureSpi { - public MLDSA87_Ed448_SHA512() + public HashMLDSA44_RSA2048_PKCS15_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA87_Ed448_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PKCS15_SHA256, new SHA256Digest(), NISTObjectIdentifiers.id_sha256); } } - public final static class MLDSA44_RSA2048_PSS_SHA256 + public static final class HashMLDSA44_RSA2048_PSS_SHA256 extends SignatureSpi { - public MLDSA44_RSA2048_PSS_SHA256() + public HashMLDSA44_RSA2048_PSS_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_RSA2048_PSS_SHA256); + super(MiscObjectIdentifiers.id_HashMLDSA44_RSA2048_PSS_SHA256, new SHA256Digest(), NISTObjectIdentifiers.id_sha256); } } - public final static class MLDSA44_RSA2048_PKCS15_SHA256 + public static final class HashMLDSA65_ECDSA_brainpoolP256r1_SHA512 extends SignatureSpi { - public MLDSA44_RSA2048_PKCS15_SHA256() + public HashMLDSA65_ECDSA_brainpoolP256r1_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class HashMLDSA65_ECDSA_P384_SHA512 + extends SignatureSpi + { + public HashMLDSA65_ECDSA_P384_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_ECDSA_P384_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class HashMLDSA65_Ed25519_SHA512 + extends SignatureSpi + { + public HashMLDSA65_Ed25519_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_Ed25519_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class HashMLDSA65_RSA3072_PKCS15_SHA512 + extends SignatureSpi + { + public HashMLDSA65_RSA3072_PKCS15_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PKCS15_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class HashMLDSA65_RSA3072_PSS_SHA512 + extends SignatureSpi + { + public HashMLDSA65_RSA3072_PSS_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_RSA2048_PKCS15_SHA256); + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA3072_PSS_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); } } - public final static class MLDSA65_RSA3072_PSS_SHA512 + public static final class HashMLDSA65_RSA4096_PKCS15_SHA512 extends SignatureSpi { - public MLDSA65_RSA3072_PSS_SHA512() + public HashMLDSA65_RSA4096_PKCS15_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_RSA3072_PSS_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PKCS15_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); } } - public final static class MLDSA65_RSA3072_PKCS15_SHA512 + public static final class HashMLDSA65_RSA4096_PSS_SHA512 extends SignatureSpi { - public MLDSA65_RSA3072_PKCS15_SHA512() + public HashMLDSA65_RSA4096_PSS_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_RSA3072_PKCS15_SHA512); + super(MiscObjectIdentifiers.id_HashMLDSA65_RSA4096_PSS_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); } } - public final static class MLDSA44_ECDSA_P256_SHA256 + public static final class HashMLDSA87_ECDSA_brainpoolP384r1_SHA512 + extends SignatureSpi + { + public HashMLDSA87_ECDSA_brainpoolP384r1_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class HashMLDSA87_ECDSA_P384_SHA512 + extends SignatureSpi + { + public HashMLDSA87_ECDSA_P384_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA87_ECDSA_P384_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class HashMLDSA87_Ed448_SHA512 + extends SignatureSpi + { + public HashMLDSA87_Ed448_SHA512() + { + super(MiscObjectIdentifiers.id_HashMLDSA87_Ed448_SHA512, new SHA512Digest(), NISTObjectIdentifiers.id_sha512); + } + } + + public static final class MLDSA44_ECDSA_P256_SHA256 extends SignatureSpi { public MLDSA44_ECDSA_P256_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_ECDSA_P256_SHA256); + super(MiscObjectIdentifiers.id_MLDSA44_ECDSA_P256_SHA256); + } + } + + public static final class MLDSA44_Ed25519_SHA512 + extends SignatureSpi + { + public MLDSA44_Ed25519_SHA512() + { + super(MiscObjectIdentifiers.id_MLDSA44_Ed25519_SHA512); + } + } + + public static final class MLDSA44_RSA2048_PKCS15_SHA256 + extends SignatureSpi + { + public MLDSA44_RSA2048_PKCS15_SHA256() + { + super(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PKCS15_SHA256); + } + } + + public static final class MLDSA44_RSA2048_PSS_SHA256 + extends SignatureSpi + { + public MLDSA44_RSA2048_PSS_SHA256() + { + super(MiscObjectIdentifiers.id_MLDSA44_RSA2048_PSS_SHA256); + } + } + + public static final class MLDSA65_ECDSA_brainpoolP256r1_SHA256 + extends SignatureSpi + { + public MLDSA65_ECDSA_brainpoolP256r1_SHA256() + { + super(MiscObjectIdentifiers.id_MLDSA65_ECDSA_brainpoolP256r1_SHA256); } } - public final static class MLDSA44_ECDSA_brainpoolP256r1_SHA256 + public static final class MLDSA65_ECDSA_P384_SHA384 extends SignatureSpi { - public MLDSA44_ECDSA_brainpoolP256r1_SHA256() + public MLDSA65_ECDSA_P384_SHA384() { - super(CompositeSignaturesConstants.CompositeName.MLDSA44_ECDSA_brainpoolP256r1_SHA256); + super(MiscObjectIdentifiers.id_MLDSA65_ECDSA_P384_SHA384); } } - public final static class MLDSA65_ECDSA_P256_SHA512 + public static final class MLDSA65_Ed25519_SHA512 extends SignatureSpi { - public MLDSA65_ECDSA_P256_SHA512() + public MLDSA65_Ed25519_SHA512() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_ECDSA_P256_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_Ed25519_SHA512); } } - public final static class MLDSA65_ECDSA_brainpoolP256r1_SHA512 + public static final class MLDSA65_RSA3072_PKCS15_SHA256 extends SignatureSpi { - public MLDSA65_ECDSA_brainpoolP256r1_SHA512() + public MLDSA65_RSA3072_PKCS15_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA65_ECDSA_brainpoolP256r1_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PKCS15_SHA256); } } - public final static class MLDSA87_ECDSA_P384_SHA512 + public static final class MLDSA65_RSA3072_PSS_SHA256 extends SignatureSpi { - public MLDSA87_ECDSA_P384_SHA512() + public MLDSA65_RSA3072_PSS_SHA256() { - super(CompositeSignaturesConstants.CompositeName.MLDSA87_ECDSA_P384_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_RSA3072_PSS_SHA256); } } - public final static class MLDSA87_ECDSA_brainpoolP384r1_SHA512 + public static final class MLDSA65_RSA4096_PKCS15_SHA384 extends SignatureSpi { - public MLDSA87_ECDSA_brainpoolP384r1_SHA512() + public MLDSA65_RSA4096_PKCS15_SHA384() { - super(CompositeSignaturesConstants.CompositeName.MLDSA87_ECDSA_brainpoolP384r1_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PKCS15_SHA384); } } - public final static class Falcon512_Ed25519_SHA512 + public static final class MLDSA65_RSA4096_PSS_SHA384 extends SignatureSpi { - public Falcon512_Ed25519_SHA512() + public MLDSA65_RSA4096_PSS_SHA384() { - super(CompositeSignaturesConstants.CompositeName.Falcon512_Ed25519_SHA512); + super(MiscObjectIdentifiers.id_MLDSA65_RSA4096_PSS_SHA384); } } - public final static class Falcon512_ECDSA_P256_SHA256 + public static final class MLDSA87_ECDSA_brainpoolP384r1_SHA384 extends SignatureSpi { - public Falcon512_ECDSA_P256_SHA256() + public MLDSA87_ECDSA_brainpoolP384r1_SHA384() { - super(CompositeSignaturesConstants.CompositeName.Falcon512_ECDSA_P256_SHA256); + super(MiscObjectIdentifiers.id_MLDSA87_ECDSA_brainpoolP384r1_SHA384); } } - public final static class Falcon512_ECDSA_brainpoolP256r1_SHA256 + public static final class MLDSA87_ECDSA_P384_SHA384 extends SignatureSpi { - public Falcon512_ECDSA_brainpoolP256r1_SHA256() + public MLDSA87_ECDSA_P384_SHA384() + { + super(MiscObjectIdentifiers.id_MLDSA87_ECDSA_P384_SHA384); + } + } + + public static final class MLDSA87_Ed448_SHA512 + extends SignatureSpi + { + public MLDSA87_Ed448_SHA512() { - super(CompositeSignaturesConstants.CompositeName.Falcon512_ECDSA_brainpoolP256r1_SHA256); + super(MiscObjectIdentifiers.id_MLDSA87_Ed448_SHA512); } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dh/BCDHPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dh/BCDHPrivateKey.java index f8b4bf5c60..670c96ae68 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dh/BCDHPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dh/BCDHPrivateKey.java @@ -243,6 +243,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dsa/BCDSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dsa/BCDSAPrivateKey.java index d19c90ed0e..b0634bf036 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dsa/BCDSAPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dsa/BCDSAPrivateKey.java @@ -145,6 +145,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dstu/BCDSTU4145PrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dstu/BCDSTU4145PrivateKey.java index f4c6817462..be5fd04a2f 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dstu/BCDSTU4145PrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dstu/BCDSTU4145PrivateKey.java @@ -447,6 +447,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java index 76c426c176..e7bc2b6eb4 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java @@ -385,6 +385,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java index 4b8c8e824c..9168773998 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java @@ -29,7 +29,7 @@ public class GMSignatureSpi private final SM2Signer signer; - GMSignatureSpi(SM2Signer signer) + protected GMSignatureSpi(SM2Signer signer) { this.signer = signer; } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java index 086b5acd22..25be087fe2 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java @@ -459,6 +459,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost12/BCECGOST3410_2012PrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost12/BCECGOST3410_2012PrivateKey.java index 64e44d96da..adbfe19a5c 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost12/BCECGOST3410_2012PrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/ecgost12/BCECGOST3410_2012PrivateKey.java @@ -480,6 +480,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/elgamal/BCElGamalPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/elgamal/BCElGamalPrivateKey.java index 8c6a9627a8..2c177db824 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/elgamal/BCElGamalPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/elgamal/BCElGamalPrivateKey.java @@ -194,4 +194,14 @@ public Enumeration getBagAttributeKeys() { return attrCarrier.getBagAttributeKeys(); } + + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/gost/BCGOST3410PrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/gost/BCGOST3410PrivateKey.java index 2fc4dba0b4..946549e461 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/gost/BCGOST3410PrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/gost/BCGOST3410PrivateKey.java @@ -234,6 +234,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/BCMLDSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/BCMLDSAPrivateKey.java new file mode 100644 index 0000000000..04a61ceeb4 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/BCMLDSAPrivateKey.java @@ -0,0 +1,194 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.bouncycastle.asn1.ASN1Set; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLDSAPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLDSAPublicKey; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.jcajce.provider.util.KeyUtil; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Fingerprint; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class BCMLDSAPrivateKey + implements MLDSAPrivateKey +{ + private static final long serialVersionUID = 1L; + + private transient MLDSAPrivateKeyParameters params; + private transient String algorithm; + private transient byte[] encoding; + private transient ASN1Set attributes; + + public BCMLDSAPrivateKey( + MLDSAPrivateKeyParameters params) + { + this.params = params; + this.algorithm = Strings.toUpperCase(MLDSAParameterSpec.fromName(params.getParameters().getName()).getName()); + } + + public BCMLDSAPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(PrivateKeyInfo keyInfo) + throws IOException + { + this.encoding = keyInfo.getEncoded(); + init((MLDSAPrivateKeyParameters)PrivateKeyFactory.createKey(keyInfo), keyInfo.getAttributes()); + } + + private void init(MLDSAPrivateKeyParameters params, ASN1Set attributes) + { + this.attributes = attributes; + this.params = params; + algorithm = Strings.toUpperCase(MLDSAParameterSpec.fromName(params.getParameters().getName()).getName()); + } + + /** + * Compare this ML-DSA private key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCMLDSAPrivateKey) + { + BCMLDSAPrivateKey otherKey = (BCMLDSAPrivateKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm + */ + public final String getAlgorithm() + { + return algorithm; + } + + public MLDSAPrivateKey getPrivateKey(boolean preferSeedOnly) + { + if (preferSeedOnly) + { + byte[] seed = params.getSeed(); + if (seed != null) + { + return new BCMLDSAPrivateKey(this.params.getParametersWithFormat(MLDSAPrivateKeyParameters.SEED_ONLY)); + } + } + + return new BCMLDSAPrivateKey(this.params.getParametersWithFormat(MLDSAPrivateKeyParameters.EXPANDED_KEY)); + } + + public byte[] getEncoded() + { + if (encoding == null) + { + encoding = KeyUtil.getEncodedPrivateKeyInfo(params, attributes); + } + + return Arrays.clone(encoding); + } + + public MLDSAPublicKey getPublicKey() + { + MLDSAPublicKeyParameters publicKeyParameters = params.getPublicKeyParameters(); + if (publicKeyParameters == null) + { + return null; + } + return new BCMLDSAPublicKey(publicKeyParameters); + } + + @Override + public byte[] getPrivateData() + { + return params.getEncoded(); + } + + @Override + public byte[] getSeed() + { + return params.getSeed(); + } + + public MLDSAParameterSpec getParameterSpec() + { + return MLDSAParameterSpec.fromName(params.getParameters().getName()); + } + + public String getFormat() + { + return "PKCS#8"; + } + + public String toString() + { + StringBuilder buf = new StringBuilder(); + String nl = Strings.lineSeparator(); + byte[] keyBytes = params.getPublicKey(); + + // -DM Hex.toHexString + buf.append(getAlgorithm()) + .append(" ") + .append("Private Key").append(" [") + .append(new Fingerprint(keyBytes).toString()) + .append("]") + .append(nl) + .append(" public data: ") + .append(Hex.toHexString(keyBytes)) + .append(nl); + + return buf.toString(); + } + + MLDSAPrivateKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(PrivateKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/BCMLDSAPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/BCMLDSAPublicKey.java new file mode 100644 index 0000000000..8a88864d35 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/BCMLDSAPublicKey.java @@ -0,0 +1,155 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLDSAPublicKey; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Fingerprint; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class BCMLDSAPublicKey + implements MLDSAPublicKey +{ + private static final long serialVersionUID = 1L; + + private transient MLDSAPublicKeyParameters params; + private transient String algorithm; + + public BCMLDSAPublicKey( + MLDSAPublicKeyParameters params) + { + this.params = params; + this.algorithm = Strings.toUpperCase(MLDSAParameterSpec.fromName(params.getParameters().getName()).getName()); + } + + public BCMLDSAPublicKey(SubjectPublicKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(SubjectPublicKeyInfo keyInfo) + throws IOException + { + this.params = (MLDSAPublicKeyParameters)PublicKeyFactory.createKey(keyInfo); + this.algorithm = Strings.toUpperCase(MLDSAParameterSpec.fromName(params.getParameters().getName()).getName()); + } + + /** + * Compare this ML-DSA public key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCMLDSAPublicKey) + { + BCMLDSAPublicKey otherKey = (BCMLDSAPublicKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "ML-DSA" followed by the parameter type. + */ + public final String getAlgorithm() + { + return algorithm; + } + + public byte[] getPublicData() + { + return params.getEncoded(); + } + + public byte[] getEncoded() + { + try + { + SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(params); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public String getFormat() + { + return "X.509"; + } + + public MLDSAParameterSpec getParameterSpec() + { + return MLDSAParameterSpec.fromName(params.getParameters().getName()); + } + + public String toString() + { + StringBuilder buf = new StringBuilder(); + String nl = Strings.lineSeparator(); + byte[] keyBytes = params.getEncoded(); + + // -DM Hex.toHexString + buf.append(getAlgorithm()) + .append(" ") + .append("Public Key").append(" [") + .append(new Fingerprint(keyBytes).toString()) + .append("]") + .append(nl) + .append(" public data: ") + .append(Hex.toHexString(keyBytes)) + .append(nl); + + return buf.toString(); + } + + MLDSAPublicKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(SubjectPublicKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/HashSignatureSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/HashSignatureSpi.java new file mode 100644 index 0000000000..05d138a52e --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/HashSignatureSpi.java @@ -0,0 +1,162 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.SignatureException; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.jcajce.provider.asymmetric.util.BaseDeterministicOrRandomSignature; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.pqc.crypto.mldsa.HashMLDSASigner; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; + +public class HashSignatureSpi + extends BaseDeterministicOrRandomSignature +{ + private HashMLDSASigner signer; + private MLDSAParameters parameters; + + protected HashSignatureSpi(HashMLDSASigner signer) + { + super("HashMLDSA"); + + this.signer = signer; + this.parameters = null; + } + + protected HashSignatureSpi(HashMLDSASigner signer, MLDSAParameters parameters) + { + super(MLDSAParameterSpec.fromName(parameters.getName()).getName()); + + this.signer = signer; + this.parameters = parameters; + } + + @Override + protected void verifyInit(PublicKey publicKey) + throws InvalidKeyException + { + if (publicKey instanceof BCMLDSAPublicKey) + { + BCMLDSAPublicKey key = (BCMLDSAPublicKey)publicKey; + + this.keyParams = key.getKeyParams(); + + if (parameters != null) + { + String canonicalAlg = MLDSAParameterSpec.fromName(parameters.getName()).getName(); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + } + else + { + throw new InvalidKeyException("unknown public key passed to ML-DSA"); + } + } + + protected void signInit(PrivateKey privateKey, SecureRandom random) + throws InvalidKeyException + { + this.appRandom = random; + if (privateKey instanceof BCMLDSAPrivateKey) + { + BCMLDSAPrivateKey key = (BCMLDSAPrivateKey)privateKey; + + this.keyParams = key.getKeyParams(); + + if (parameters != null) + { + String canonicalAlg = MLDSAParameterSpec.fromName(parameters.getName()).getName(); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + } + else + { + throw new InvalidKeyException("unknown private key passed to ML-DSA"); + } + } + + @Override + protected void updateEngine(byte b) + throws SignatureException + { + signer.update(b); + } + + @Override + protected void updateEngine(byte[] buf, int off, int len) + throws SignatureException + { + signer.update(buf, off, len); + } + + protected byte[] engineSign() + throws SignatureException + { + try + { + return signer.generateSignature(); + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + return signer.verifySignature(sigBytes); + } + + @Override + protected void reInitialize(boolean forSigning, CipherParameters params) + { + signer.init(forSigning, params); + } + + public static class MLDSA + extends HashSignatureSpi + { + public MLDSA() + { + super(new HashMLDSASigner()); + } + } + public static class MLDSA44 + extends HashSignatureSpi + { + public MLDSA44() + { + super(new HashMLDSASigner(), MLDSAParameters.ml_dsa_44_with_sha512); + } + } + + public static class MLDSA65 + extends HashSignatureSpi + { + public MLDSA65() + { + super(new HashMLDSASigner(), MLDSAParameters.ml_dsa_65_with_sha512); + } + } + + public static class MLDSA87 + extends HashSignatureSpi + { + public MLDSA87() + throws NoSuchAlgorithmException + { + super(new HashMLDSASigner(), MLDSAParameters.ml_dsa_87_with_sha512); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/MLDSAKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/MLDSAKeyFactorySpi.java new file mode 100644 index 0000000000..9256293d6e --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/MLDSAKeyFactorySpi.java @@ -0,0 +1,286 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.spec.MLDSAPrivateKeySpec; +import org.bouncycastle.jcajce.spec.MLDSAPublicKeySpec; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; +import org.bouncycastle.util.Arrays; + +public class MLDSAKeyFactorySpi + extends BaseKeyFactorySpi +{ + private static final Set pureKeyOids = new HashSet(); + private static final Set hashKeyOids = new HashSet(); + + static + { + pureKeyOids.add(NISTObjectIdentifiers.id_ml_dsa_44); + pureKeyOids.add(NISTObjectIdentifiers.id_ml_dsa_65); + pureKeyOids.add(NISTObjectIdentifiers.id_ml_dsa_87); + + hashKeyOids.add(NISTObjectIdentifiers.id_ml_dsa_44); + hashKeyOids.add(NISTObjectIdentifiers.id_ml_dsa_65); + hashKeyOids.add(NISTObjectIdentifiers.id_ml_dsa_87); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + } + + private final boolean isHashOnly; + + public MLDSAKeyFactorySpi(Set keyOids) + { + super(keyOids); + + this.isHashOnly = false; + } + + public MLDSAKeyFactorySpi(ASN1ObjectIdentifier keyOid) + { + super(keyOid); + + this.isHashOnly = (keyOid.equals(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512) + || keyOid.equals(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512) + || keyOid.equals(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512)); + } + + public final KeySpec engineGetKeySpec(Key key, Class keySpec) + throws InvalidKeySpecException + { + if (key instanceof BCMLDSAPrivateKey) + { + if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new PKCS8EncodedKeySpec(key.getEncoded()); + } + if (MLDSAPrivateKeySpec.class.isAssignableFrom(keySpec)) + { + BCMLDSAPrivateKey mldsaKey = (BCMLDSAPrivateKey)key; + byte[] seed = mldsaKey.getSeed(); + if (seed != null) + { + return new MLDSAPrivateKeySpec(mldsaKey.getParameterSpec(), seed); + } + return new MLDSAPrivateKeySpec(mldsaKey.getParameterSpec(), mldsaKey.getPrivateData(), mldsaKey.getPublicKey().getPublicData()); + } + if (MLDSAPublicKeySpec.class.isAssignableFrom(keySpec)) + { + BCMLDSAPrivateKey mldsaKey = (BCMLDSAPrivateKey)key; + return new MLDSAPublicKeySpec(mldsaKey.getParameterSpec(), mldsaKey.getPublicKey().getPublicData()); + } + } + else if (key instanceof BCMLDSAPublicKey) + { + if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new X509EncodedKeySpec(key.getEncoded()); + } + if (MLDSAPublicKeySpec.class.isAssignableFrom(keySpec)) + { + BCMLDSAPublicKey mldsaKey = (BCMLDSAPublicKey)key; + return new MLDSAPublicKeySpec(mldsaKey.getParameterSpec(), mldsaKey.getPublicData()); + } + } + else + { + throw new InvalidKeySpecException("unsupported key type: " + + key.getClass() + "."); + } + + throw new InvalidKeySpecException("unknown key specification: " + + keySpec + "."); + } + + public final Key engineTranslateKey(Key key) + throws InvalidKeyException + { + if (key instanceof BCMLDSAPrivateKey || key instanceof BCMLDSAPublicKey) + { + return key; + } + + throw new InvalidKeyException("unsupported key type"); + } + + public PrivateKey engineGeneratePrivate( + KeySpec keySpec) + throws InvalidKeySpecException + { + if (keySpec instanceof MLDSAPrivateKeySpec) + { + MLDSAPrivateKeySpec spec = (MLDSAPrivateKeySpec)keySpec; + MLDSAPrivateKeyParameters params; + MLDSAParameters mldsaParameters = Utils.getParameters(spec.getParameterSpec().getName()); + if (spec.isSeed()) + { + params = new MLDSAPrivateKeyParameters( + mldsaParameters, spec.getSeed()); + } + else + { + params = new MLDSAPrivateKeyParameters( + mldsaParameters, spec.getPrivateData(), null); + byte[] publicData = spec.getPublicData(); + if (publicData != null) + { + if (!Arrays.constantTimeAreEqual(publicData, params.getPublicKey())) + { + throw new InvalidKeySpecException("public key data does not match private key data"); + } + } + } + + return new BCMLDSAPrivateKey(params); + } + + return super.engineGeneratePrivate(keySpec); + } + + public PublicKey engineGeneratePublic( + KeySpec keySpec) + throws InvalidKeySpecException + { + if (keySpec instanceof MLDSAPublicKeySpec) + { + MLDSAPublicKeySpec spec = (MLDSAPublicKeySpec)keySpec; + + return new BCMLDSAPublicKey(new MLDSAPublicKeyParameters( + Utils.getParameters(spec.getParameterSpec().getName()), + spec.getPublicData())); + } + + return super.engineGeneratePublic(keySpec); + } + + public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) + throws IOException + { + BCMLDSAPrivateKey key = new BCMLDSAPrivateKey(keyInfo); + + if (!isHashOnly || (key.getAlgorithm().indexOf("WITH") > 0)) + { + return key; + } + + // keyfactory for hash-only, convert key to hash-only. + MLDSAPrivateKeyParameters kParams = key.getKeyParams(); + MLDSAParameters mldsaParameters = null; + if (kParams.getParameters().equals(MLDSAParameters.ml_dsa_44)) + { + mldsaParameters = MLDSAParameters.ml_dsa_44_with_sha512; + } + else if (kParams.getParameters().equals(MLDSAParameters.ml_dsa_65)) + { + mldsaParameters = MLDSAParameters.ml_dsa_65_with_sha512; + } + else if (kParams.getParameters().equals(MLDSAParameters.ml_dsa_87)) + { + mldsaParameters = MLDSAParameters.ml_dsa_87_with_sha512; + } + else + { + throw new IllegalStateException("unknown ML-DSA parameters"); + } + + MLDSAPrivateKeyParameters hkParams = new MLDSAPrivateKeyParameters( + mldsaParameters, kParams.getRho(), kParams.getK(), kParams.getTr(), kParams.getS1(), kParams.getS2(), kParams.getT0(), kParams.getT1(), kParams.getSeed()); + + return new BCMLDSAPrivateKey(hkParams); + } + + public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) + throws IOException + { + return new BCMLDSAPublicKey(keyInfo); + } + + public static class Pure + extends MLDSAKeyFactorySpi + { + public Pure() + { + super(pureKeyOids); + } + } + + public static class MLDSA44 + extends MLDSAKeyFactorySpi + { + public MLDSA44() + { + super(NISTObjectIdentifiers.id_ml_dsa_44); + } + } + + public static class MLDSA65 + extends MLDSAKeyFactorySpi + { + public MLDSA65() + { + super(NISTObjectIdentifiers.id_ml_dsa_65); + } + } + + public static class MLDSA87 + extends MLDSAKeyFactorySpi + { + public MLDSA87() + { + super(NISTObjectIdentifiers.id_ml_dsa_87); + } + } + + public static class Hash + extends MLDSAKeyFactorySpi + { + public Hash() + { + super(hashKeyOids); + } + } + + public static class HashMLDSA44 + extends MLDSAKeyFactorySpi + { + public HashMLDSA44() + { + super(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512); + } + } + + public static class HashMLDSA65 + extends MLDSAKeyFactorySpi + { + public HashMLDSA65() + { + super(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512); + } + } + + public static class HashMLDSA87 + extends MLDSAKeyFactorySpi + { + public HashMLDSA87() + { + super(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/MLDSAKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/MLDSAKeyPairGeneratorSpi.java new file mode 100644 index 0000000000..ce58857e60 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/MLDSAKeyPairGeneratorSpi.java @@ -0,0 +1,218 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; +import org.bouncycastle.util.Strings; + +public class MLDSAKeyPairGeneratorSpi + extends java.security.KeyPairGenerator +{ + private final MLDSAParameters mldsaParameters; + MLDSAKeyGenerationParameters param; + MLDSAKeyPairGenerator engine = new MLDSAKeyPairGenerator(); + + SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + boolean initialised = false; + + public MLDSAKeyPairGeneratorSpi(String name) + { + super(name); + this.mldsaParameters = null; + } + + protected MLDSAKeyPairGeneratorSpi(MLDSAParameterSpec paramSpec) + { + super(Strings.toUpperCase(paramSpec.getName())); + this.mldsaParameters = Utils.getParameters(paramSpec.getName()); + + if (param == null) + { + param = new MLDSAKeyGenerationParameters(random, mldsaParameters); + } + + engine.init(param); + initialised = true; + } + + public void initialize( + int strength, + SecureRandom random) + { + throw new IllegalArgumentException("use AlgorithmParameterSpec"); + } + + public void initialize( + AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException + { + try + { + initialize(params, new BCJcaJceHelper().createSecureRandom("DEFAULT")); + } + catch (NoSuchAlgorithmException e) + { + throw new IllegalStateException("unable to find DEFAULT DRBG"); + } + } + + public void initialize( + AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + String name = getNameFromParams(params); + + if (name != null) + { + MLDSAParameters mldsaParams = Utils.getParameters(name); + if (mldsaParams == null) + { + throw new InvalidAlgorithmParameterException("unknown parameter set name: " + name); + } + param = new MLDSAKeyGenerationParameters(random, mldsaParams); + + if (mldsaParameters != null && !mldsaParams.getName().equals(mldsaParameters.getName())) + { + throw new InvalidAlgorithmParameterException("key pair generator locked to " + MLDSAParameterSpec.fromName(mldsaParameters.getName()).getName()); + } + engine.init(param); + initialised = true; + } + else + { + throw new InvalidAlgorithmParameterException("invalid ParameterSpec: " + params); + } + } + + + public KeyPair generateKeyPair() + { + if (!initialised) + { + if (this.getAlgorithm().startsWith("HASH")) + { + param = new MLDSAKeyGenerationParameters(random, MLDSAParameters.ml_dsa_87_with_sha512); + } + else + { + param = new MLDSAKeyGenerationParameters(random, MLDSAParameters.ml_dsa_87); + } + + engine.init(param); + initialised = true; + } + + AsymmetricCipherKeyPair pair = engine.generateKeyPair(); + MLDSAPublicKeyParameters pub = (MLDSAPublicKeyParameters)pair.getPublic(); + MLDSAPrivateKeyParameters priv = (MLDSAPrivateKeyParameters)pair.getPrivate(); + + return new KeyPair(new BCMLDSAPublicKey(pub), new BCMLDSAPrivateKey(priv)); + } + + private static String getNameFromParams(AlgorithmParameterSpec paramSpec) + { + if (paramSpec instanceof MLDSAParameterSpec) + { + MLDSAParameterSpec params = (MLDSAParameterSpec)paramSpec; + return params.getName(); + } + else + { + return Strings.toUpperCase(SpecUtil.getNameFrom(paramSpec)); + } + } + + public static class Pure + extends MLDSAKeyPairGeneratorSpi + { + public Pure() + throws NoSuchAlgorithmException + { + super("ML-DSA"); + } + } + + public static class MLDSA44 + extends MLDSAKeyPairGeneratorSpi + { + public MLDSA44() + throws NoSuchAlgorithmException + { + super(MLDSAParameterSpec.ml_dsa_44); + } + } + + public static class MLDSA65 + extends MLDSAKeyPairGeneratorSpi + { + public MLDSA65() + throws NoSuchAlgorithmException + { + super(MLDSAParameterSpec.ml_dsa_65); + } + } + + public static class MLDSA87 + extends MLDSAKeyPairGeneratorSpi + { + public MLDSA87() + throws NoSuchAlgorithmException + { + super(MLDSAParameterSpec.ml_dsa_87); + } + } + + public static class Hash + extends MLDSAKeyPairGeneratorSpi + { + public Hash() + throws NoSuchAlgorithmException + { + super("HASH-ML-DSA"); + } + } + + public static class MLDSA44withSHA512 + extends MLDSAKeyPairGeneratorSpi + { + public MLDSA44withSHA512() + throws NoSuchAlgorithmException + { + super(MLDSAParameterSpec.ml_dsa_44_with_sha512); + } + } + + public static class MLDSA65withSHA512 + extends MLDSAKeyPairGeneratorSpi + { + public MLDSA65withSHA512() + throws NoSuchAlgorithmException + { + super(MLDSAParameterSpec.ml_dsa_65_with_sha512); + } + } + + public static class MLDSA87withSHA512 + extends MLDSAKeyPairGeneratorSpi + { + public MLDSA87withSHA512() + throws NoSuchAlgorithmException + { + super(MLDSAParameterSpec.ml_dsa_87_with_sha512); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/SignatureSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/SignatureSpi.java new file mode 100644 index 0000000000..9d7433c117 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/SignatureSpi.java @@ -0,0 +1,277 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.SignatureException; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.jcajce.MLDSAProxyPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLDSAPublicKey; +import org.bouncycastle.jcajce.provider.asymmetric.util.BaseDeterministicOrRandomSignature; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSASigner; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; + +public class SignatureSpi + extends BaseDeterministicOrRandomSignature +{ + protected MLDSASigner signer; + protected MLDSAParameters parameters; + + protected SignatureSpi(MLDSASigner signer) + { + super("MLDSA"); + + this.signer = signer; + this.parameters = null; + } + + protected SignatureSpi(MLDSASigner signer, MLDSAParameters parameters) + { + super(MLDSAParameterSpec.fromName(parameters.getName()).getName()); + + this.signer = signer; + this.parameters = parameters; + } + + protected void verifyInit(PublicKey publicKey) + throws InvalidKeyException + { + if (publicKey instanceof BCMLDSAPublicKey) + { + BCMLDSAPublicKey key = (BCMLDSAPublicKey)publicKey; + + this.keyParams = key.getKeyParams(); + + if (parameters != null) + { + String canonicalAlg = MLDSAParameterSpec.fromName(parameters.getName()).getName(); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + } + else + { + throw new InvalidKeyException("unknown public key passed to ML-DSA"); + } + } + + protected void signInit(PrivateKey privateKey, SecureRandom random) + throws InvalidKeyException + { + this.appRandom = random; + if (privateKey instanceof BCMLDSAPrivateKey) + { + BCMLDSAPrivateKey key = (BCMLDSAPrivateKey)privateKey; + + this.keyParams = key.getKeyParams(); + + if (parameters != null) + { + String canonicalAlg = MLDSAParameterSpec.fromName(parameters.getName()).getName(); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + } + else if (privateKey instanceof MLDSAProxyPrivateKey && this instanceof MLDSACalcMu) + { + MLDSAProxyPrivateKey pKey = (MLDSAProxyPrivateKey)privateKey; + MLDSAPublicKey key = pKey.getPublicKey(); + + try + { + this.keyParams = PublicKeyFactory.createKey(key.getEncoded()); + } + catch (IOException e) + { + throw new InvalidKeyException(e.getMessage()); + } + + if (parameters != null) + { + String canonicalAlg = MLDSAParameterSpec.fromName(parameters.getName()).getName(); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + } + else + { + throw new InvalidKeyException("unknown private key passed to ML-DSA"); + } + } + + protected void updateEngine(byte b) + throws SignatureException + { + signer.update(b); + } + + protected void updateEngine(byte[] b, int off, int len) + throws SignatureException + { + signer.update(b, off, len); + } + + protected byte[] engineSign() + throws SignatureException + { + try + { + return signer.generateSignature(); + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + return signer.verifySignature(sigBytes); + } + + protected void reInitialize(boolean forSigning, CipherParameters params) + { + signer.init(forSigning, params); + } + + public static class MLDSA + extends SignatureSpi + { + public MLDSA() + { + super(new MLDSASigner()); + } + } + + public static class MLDSA44 + extends SignatureSpi + { + public MLDSA44() + { + super(new MLDSASigner(), MLDSAParameters.ml_dsa_44); + } + } + + public static class MLDSA65 + extends SignatureSpi + { + public MLDSA65() + { + super(new MLDSASigner(), MLDSAParameters.ml_dsa_65); + } + } + + public static class MLDSA87 + extends SignatureSpi + { + public MLDSA87() + throws NoSuchAlgorithmException + { + super(new MLDSASigner(), MLDSAParameters.ml_dsa_87); + } + } + + public static class MLDSAExtMu + extends SignatureSpi + { + private ByteArrayOutputStream bOut = new ByteArrayOutputStream(64); + + public MLDSAExtMu() + { + super(new MLDSASigner()); + } + + protected void updateEngine(byte b) + throws SignatureException + { + bOut.write(b); + } + + protected void updateEngine(byte[] b, int off, int len) + throws SignatureException + { + bOut.write(b, off, len); + } + + protected byte[] engineSign() + throws SignatureException + { + try + { + byte[] mu = bOut.toByteArray(); + + bOut.reset(); + + return signer.generateMuSignature(mu); + } + catch (DataLengthException e) + { + throw new SignatureException(e.getMessage()); + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + byte[] mu = bOut.toByteArray(); + + bOut.reset(); + + try + { + return signer.verifyMuSignature(mu, sigBytes); + } + catch (DataLengthException e) + { + throw new SignatureException(e.getMessage()); + } + } + } + + public static class MLDSACalcMu + extends SignatureSpi + { + public MLDSACalcMu() + { + super(new MLDSASigner()); + } + + protected byte[] engineSign() + throws SignatureException + { + try + { + return signer.generateMu(); + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + return signer.verifyMu(sigBytes); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/Utils.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/Utils.java new file mode 100644 index 0000000000..02cf7f4a8a --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mldsa/Utils.java @@ -0,0 +1,27 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mldsa; + +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; + +class Utils +{ + private static Map parameters = new HashMap(); + + static + { + parameters.put(MLDSAParameterSpec.ml_dsa_44.getName(), MLDSAParameters.ml_dsa_44); + parameters.put(MLDSAParameterSpec.ml_dsa_65.getName(), MLDSAParameters.ml_dsa_65); + parameters.put(MLDSAParameterSpec.ml_dsa_87.getName(), MLDSAParameters.ml_dsa_87); + parameters.put(MLDSAParameterSpec.ml_dsa_44_with_sha512.getName(), MLDSAParameters.ml_dsa_44_with_sha512); + parameters.put(MLDSAParameterSpec.ml_dsa_65_with_sha512.getName(), MLDSAParameters.ml_dsa_65_with_sha512); + parameters.put(MLDSAParameterSpec.ml_dsa_87_with_sha512.getName(), MLDSAParameters.ml_dsa_87_with_sha512); + } + + static MLDSAParameters getParameters(String paramName) + { + return (MLDSAParameters)parameters.get(paramName); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/BCMLKEMPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/BCMLKEMPrivateKey.java new file mode 100644 index 0000000000..3937b4a1e0 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/BCMLKEMPrivateKey.java @@ -0,0 +1,193 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.bouncycastle.asn1.ASN1Set; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLKEMPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLKEMPublicKey; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Fingerprint; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class BCMLKEMPrivateKey + implements MLKEMPrivateKey +{ + private static final long serialVersionUID = 1L; + + private transient MLKEMPrivateKeyParameters params; + private transient String algorithm; + private transient ASN1Set attributes; + private transient byte[] priorEncoding; + + public BCMLKEMPrivateKey( + MLKEMPrivateKeyParameters params) + { + this.params = params; + this.algorithm = Strings.toUpperCase(params.getParameters().getName()); + } + + public BCMLKEMPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(PrivateKeyInfo keyInfo) + throws IOException + { + this.attributes = keyInfo.getAttributes(); + this.priorEncoding = keyInfo.getEncoded(); + this.params = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey(keyInfo); + this.algorithm = Strings.toUpperCase(MLKEMParameterSpec.fromName(params.getParameters().getName()).getName()); + } + + /** + * Compare this ML-KEM private key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCMLKEMPrivateKey) + { + BCMLKEMPrivateKey otherKey = (BCMLKEMPrivateKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "ML-KEM" + */ + public final String getAlgorithm() + { + return algorithm; + } + + public byte[] getEncoded() + { + try + { + if (priorEncoding != null) + { + return priorEncoding; + } + PrivateKeyInfo pki = PrivateKeyInfoFactory.createPrivateKeyInfo(params, attributes); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public MLKEMPublicKey getPublicKey() + { + return new BCMLKEMPublicKey(params.getPublicKeyParameters()); + } + + @Override + public byte[] getPrivateData() + { + return params.getEncoded(); + } + + @Override + public byte[] getSeed() + { + return params.getSeed(); + } + + @Override + public MLKEMPrivateKey getPrivateKey(boolean preferSeedOnly) + { + if (preferSeedOnly) + { + byte[] seed = params.getSeed(); + if (seed != null) + { + return new BCMLKEMPrivateKey(this.params.getParametersWithFormat(MLDSAPrivateKeyParameters.SEED_ONLY)); + } + } + + return new BCMLKEMPrivateKey(this.params.getParametersWithFormat(MLDSAPrivateKeyParameters.EXPANDED_KEY)); + } + + public MLKEMParameterSpec getParameterSpec() + { + return MLKEMParameterSpec.fromName(params.getParameters().getName()); + } + + public String getFormat() + { + return "PKCS#8"; + } + + public String toString() + { + StringBuilder buf = new StringBuilder(); + String nl = Strings.lineSeparator(); + byte[] keyBytes = params.getPublicKey(); + + // -DM Hex.toHexString + buf.append(getAlgorithm()) + .append(" ") + .append("Private Key").append(" [") + .append(new Fingerprint(keyBytes).toString()) + .append("]") + .append(nl) + .append(" public data: ") + .append(Hex.toHexString(keyBytes)) + .append(nl); + + return buf.toString(); + } + + MLKEMPrivateKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(PrivateKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/BCMLKEMPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/BCMLKEMPublicKey.java new file mode 100644 index 0000000000..97f877301b --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/BCMLKEMPublicKey.java @@ -0,0 +1,160 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLKEMPublicKey; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Fingerprint; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class BCMLKEMPublicKey + implements MLKEMPublicKey +{ + private static final long serialVersionUID = 1L; + + private transient MLKEMPublicKeyParameters params; + + private transient String algorithm; + + public BCMLKEMPublicKey( + MLKEMPublicKeyParameters params) + { + init(params); + } + + public BCMLKEMPublicKey(SubjectPublicKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(SubjectPublicKeyInfo keyInfo) + throws IOException + { + this.params = (MLKEMPublicKeyParameters)PublicKeyFactory.createKey(keyInfo); + this.algorithm = Strings.toUpperCase(MLKEMParameterSpec.fromName(params.getParameters().getName()).getName()); + } + + private void init(MLKEMPublicKeyParameters params) + { + this.params = params; + this.algorithm = Strings.toUpperCase(MLKEMParameterSpec.fromName(params.getParameters().getName()).getName()); + } + /** + * Compare this ML-KEM public key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCMLKEMPublicKey) + { + BCMLKEMPublicKey otherKey = (BCMLKEMPublicKey)o; + + return Arrays.areEqual(this.getEncoded(), otherKey.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(getEncoded()); + } + + /** + * @return name of the algorithm - "ML-KEM" followed by the parameter type. + */ + public final String getAlgorithm() + { + return algorithm; + } + + public byte[] getPublicData() + { + return params.getEncoded(); + } + + public byte[] getEncoded() + { + try + { + SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(params); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public String getFormat() + { + return "X.509"; + } + + public MLKEMParameterSpec getParameterSpec() + { + return MLKEMParameterSpec.fromName(params.getParameters().getName()); + } + + public String toString() + { + StringBuilder buf = new StringBuilder(); + String nl = Strings.lineSeparator(); + byte[] keyBytes = params.getEncoded(); + + // -DM Hex.toHexString + buf.append(getAlgorithm()) + .append(" ") + .append("Public Key").append(" [") + .append(new Fingerprint(keyBytes).toString()) + .append("]") + .append(nl) + .append(" public data: ") + .append(Hex.toHexString(keyBytes)) + .append(nl); + + return buf.toString(); + } + + MLKEMPublicKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(SubjectPublicKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMCipherSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMCipherSpi.java new file mode 100644 index 0000000000..036248b738 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMCipherSpi.java @@ -0,0 +1,364 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.CipherSpi; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.SecretKeySpec; +import javax.security.auth.DestroyFailedException; + +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.crypto.Wrapper; +import org.bouncycastle.jcajce.spec.KEMParameterSpec; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.jcajce.provider.util.WrapUtil; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Exceptions; + +class MLKEMCipherSpi + extends CipherSpi +{ + private final String algorithmName; + private MLKEMGenerator kemGen; + private KTSParameterSpec kemParameterSpec; + private BCMLKEMPublicKey wrapKey; + private BCMLKEMPrivateKey unwrapKey; + + private AlgorithmParameters engineParams; + private MLKEMParameters mlkemParamters; + + MLKEMCipherSpi(String algorithmName) + { + this.algorithmName = algorithmName; + this.mlkemParamters = null; + } + + MLKEMCipherSpi(MLKEMParameters kyberParameters) + { + this.mlkemParamters = kyberParameters; + this.algorithmName = kyberParameters.getName(); + } + + @Override + protected void engineSetMode(String mode) + throws NoSuchAlgorithmException + { + throw new NoSuchAlgorithmException("Cannot support mode " + mode); + } + + @Override + protected void engineSetPadding(String padding) + throws NoSuchPaddingException + { + throw new NoSuchPaddingException("Padding " + padding + " unknown"); + } + + protected int engineGetKeySize( + Key key) + { + return 2048; // TODO + //throw new IllegalArgumentException("not an valid key!"); + } + + @Override + protected int engineGetBlockSize() + { + return 0; + } + + @Override + protected int engineGetOutputSize(int i) + { + return -1; // can't use with update/doFinal + } + + @Override + protected byte[] engineGetIV() + { + return null; + } + + @Override + protected AlgorithmParameters engineGetParameters() + { + if (engineParams == null) + { + try + { + engineParams = AlgorithmParameters.getInstance(algorithmName, "BCPQC"); + + engineParams.init(kemParameterSpec); + } + catch (Exception e) + { + throw Exceptions.illegalStateException(e.toString(), e); + } + } + + return engineParams; + } + + @Override + protected void engineInit(int opmode, Key key, SecureRandom random) + throws InvalidKeyException + { + try + { + engineInit(opmode, key, (AlgorithmParameterSpec)null, random); + } + catch (InvalidAlgorithmParameterException e) + { + throw Exceptions.illegalArgumentException(e.getMessage(), e); + } + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec paramSpec, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException + { + if (paramSpec == null) + { + // TODO: default should probably use shake. + kemParameterSpec = new KEMParameterSpec("AES-KWP"); + } + else + { + if (!(paramSpec instanceof KTSParameterSpec)) + { + throw new InvalidAlgorithmParameterException(algorithmName + " can only accept KTSParameterSpec"); + } + + kemParameterSpec = (KTSParameterSpec)paramSpec; + } + + if (opmode == Cipher.WRAP_MODE) + { + if (key instanceof BCMLKEMPublicKey) + { + wrapKey = (BCMLKEMPublicKey)key; + kemGen = new MLKEMGenerator(CryptoServicesRegistrar.getSecureRandom(random)); + } + else + { + throw new InvalidKeyException("Only a " + algorithmName + " public key can be used for wrapping"); + } + } + else if (opmode == Cipher.UNWRAP_MODE) + { + if (key instanceof BCMLKEMPrivateKey) + { + unwrapKey = (BCMLKEMPrivateKey)key; + } + else + { + throw new InvalidKeyException("Only a " + algorithmName + " private key can be used for unwrapping"); + } + } + else + { + throw new InvalidParameterException("Cipher only valid for wrapping/unwrapping"); + } + + if (mlkemParamters != null) + { + String canonicalAlgName = MLKEMParameterSpec.fromName(mlkemParamters.getName()).getName(); + if (!canonicalAlgName.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("cipher locked to " + canonicalAlgName); + } + } + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameters algorithmParameters, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException + { + AlgorithmParameterSpec paramSpec = null; + + if (algorithmParameters != null) + { + try + { + paramSpec = algorithmParameters.getParameterSpec(KEMParameterSpec.class); + } + catch (Exception e) + { + throw new InvalidAlgorithmParameterException("can't handle parameter " + algorithmParameters.toString()); + } + } + + engineInit(opmode, key, paramSpec, random); + } + + @Override + protected byte[] engineUpdate(byte[] bytes, int i, int i1) + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + @Override + protected int engineUpdate(byte[] bytes, int i, int i1, byte[] bytes1, int i2) + throws ShortBufferException + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + @Override + protected byte[] engineDoFinal(byte[] bytes, int i, int i1) + throws IllegalBlockSizeException, BadPaddingException + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + @Override + protected int engineDoFinal(byte[] bytes, int i, int i1, byte[] bytes1, int i2) + throws ShortBufferException, IllegalBlockSizeException, BadPaddingException + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + protected byte[] engineWrap( + Key key) + throws IllegalBlockSizeException, InvalidKeyException + { + byte[] encoded = key.getEncoded(); + if (encoded == null) + { + throw new InvalidKeyException("Cannot wrap key, null encoding."); + } + + SecretWithEncapsulation secEnc = null; + try + { + secEnc = kemGen.generateEncapsulated(wrapKey.getKeyParams()); + + Wrapper kWrap = WrapUtil.getKeyWrapper(kemParameterSpec, secEnc.getSecret()); + + byte[] encapsulation = secEnc.getEncapsulation(); + + byte[] keyToWrap = key.getEncoded(); + + byte[] rv = Arrays.concatenate(encapsulation, kWrap.wrap(keyToWrap, 0, keyToWrap.length)); + + Arrays.clear(keyToWrap); + + return rv; + } + catch (IllegalArgumentException e) + { + throw new IllegalBlockSizeException("unable to generate KTS secret: " + e.getMessage()); + } + finally + { + try + { + if (secEnc != null) + { + secEnc.destroy(); + } + } + catch (DestroyFailedException e) + { + throw new IllegalBlockSizeException("unable to destroy interim values: " + e.getMessage()); + } + } + } + + protected Key engineUnwrap( + byte[] wrappedKey, + String wrappedKeyAlgorithm, + int wrappedKeyType) + throws InvalidKeyException, NoSuchAlgorithmException + { + // TODO: add support for other types. + if (wrappedKeyType != Cipher.SECRET_KEY) + { + throw new InvalidKeyException("only SECRET_KEY supported"); + } + byte[] secret = null; + try + { + MLKEMExtractor kemExt = new MLKEMExtractor(unwrapKey.getKeyParams()); + + secret = kemExt.extractSecret(Arrays.copyOfRange(wrappedKey, 0, kemExt.getEncapsulationLength())); + + Wrapper kWrap = WrapUtil.getKeyUnwrapper(kemParameterSpec, secret); + + byte[] keyEncBytes = Arrays.copyOfRange(wrappedKey, kemExt.getEncapsulationLength(), wrappedKey.length); + + SecretKey rv = new SecretKeySpec(kWrap.unwrap(keyEncBytes, 0, keyEncBytes.length), wrappedKeyAlgorithm); + + return rv; + } + catch (IllegalArgumentException e) + { + throw new NoSuchAlgorithmException("unable to extract KTS secret: " + e.getMessage()); + } + catch (InvalidCipherTextException e) + { + throw new InvalidKeyException("unable to extract KTS secret: " + e.getMessage()); + } + finally + { + if (secret != null) + { + Arrays.clear(secret); + } + } + } + + public static class Base + extends MLKEMCipherSpi + { + public Base() + throws NoSuchAlgorithmException + { + super("MLKEM"); + } + } + + public static class MLKEM512 + extends MLKEMCipherSpi + { + public MLKEM512() + { + super(MLKEMParameters.ml_kem_512); + } + } + + public static class MLKEM768 + extends MLKEMCipherSpi + { + public MLKEM768() + { + super(MLKEMParameters.ml_kem_768); + } + } + + public static class MLKEM1024 + extends MLKEMCipherSpi + { + public MLKEM1024() + { + super(MLKEMParameters.ml_kem_1024); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyFactorySpi.java new file mode 100644 index 0000000000..68abf2ba1a --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyFactorySpi.java @@ -0,0 +1,196 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.spec.MLKEMPrivateKeySpec; +import org.bouncycastle.jcajce.spec.MLKEMPublicKeySpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; +import org.bouncycastle.util.Arrays; + +public class MLKEMKeyFactorySpi + extends BaseKeyFactorySpi +{ + private static final Set keyOids = new HashSet(); + + static + { + keyOids.add(NISTObjectIdentifiers.id_alg_ml_kem_512); + keyOids.add(NISTObjectIdentifiers.id_alg_ml_kem_768); + keyOids.add(NISTObjectIdentifiers.id_alg_ml_kem_1024); + } + + public MLKEMKeyFactorySpi() + { + super(keyOids); + } + + public MLKEMKeyFactorySpi(ASN1ObjectIdentifier keyOid) + { + super(keyOid); + } + + + public final KeySpec engineGetKeySpec(Key key, Class keySpec) + throws InvalidKeySpecException + { + if (key instanceof BCMLKEMPrivateKey) + { + if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new PKCS8EncodedKeySpec(key.getEncoded()); + } + if (MLKEMPrivateKeySpec.class.isAssignableFrom(keySpec)) + { + BCMLKEMPrivateKey mlkemKey = (BCMLKEMPrivateKey)key; + byte[] seed = mlkemKey.getSeed(); + if (seed != null) + { + return new MLKEMPrivateKeySpec(mlkemKey.getParameterSpec(), seed); + } + return new MLKEMPrivateKeySpec(mlkemKey.getParameterSpec(), mlkemKey.getPrivateData(), mlkemKey.getPublicKey().getPublicData()); + } + if (MLKEMPublicKeySpec.class.isAssignableFrom(keySpec)) + { + BCMLKEMPrivateKey mlkemKey = (BCMLKEMPrivateKey)key; + return new MLKEMPublicKeySpec(mlkemKey.getParameterSpec(), mlkemKey.getPublicKey().getPublicData()); + } + } + else if (key instanceof BCMLKEMPublicKey) + { + if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new X509EncodedKeySpec(key.getEncoded()); + } + if (MLKEMPublicKeySpec.class.isAssignableFrom(keySpec)) + { + BCMLKEMPublicKey mlkemKey = (BCMLKEMPublicKey)key; + return new MLKEMPublicKeySpec(mlkemKey.getParameterSpec(), mlkemKey.getPublicData()); + } + } + else + { + throw new InvalidKeySpecException("Unsupported key type: " + + key.getClass() + "."); + } + + throw new InvalidKeySpecException("unknown key specification: " + + keySpec + "."); + } + + public final Key engineTranslateKey(Key key) + throws InvalidKeyException + { + if (key instanceof BCMLKEMPrivateKey || key instanceof BCMLKEMPublicKey) + { + return key; + } + + throw new InvalidKeyException("unsupported key type"); + } + + public PrivateKey engineGeneratePrivate( + KeySpec keySpec) + throws InvalidKeySpecException + { + if (keySpec instanceof MLKEMPrivateKeySpec) + { + MLKEMPrivateKeySpec spec = (MLKEMPrivateKeySpec)keySpec; + MLKEMPrivateKeyParameters params; + MLKEMParameters mlkemParameters = Utils.getParameters(spec.getParameterSpec().getName()); + if (spec.isSeed()) + { + params = new MLKEMPrivateKeyParameters( + mlkemParameters, spec.getSeed()); + } + else + { + params = new MLKEMPrivateKeyParameters(mlkemParameters, spec.getPrivateData()); + byte[] publicKeyData = spec.getPublicData(); + if (publicKeyData != null) + { + if (!Arrays.constantTimeAreEqual(publicKeyData, params.getPublicKey())) + { + throw new InvalidKeySpecException("public key data does not match private key data"); + } + } + } + + return new BCMLKEMPrivateKey(params); + } + + return super.engineGeneratePrivate(keySpec); + } + + public PublicKey engineGeneratePublic( + KeySpec keySpec) + throws InvalidKeySpecException + { + if (keySpec instanceof MLKEMPublicKeySpec) + { + MLKEMPublicKeySpec spec = (MLKEMPublicKeySpec)keySpec; + + return new BCMLKEMPublicKey(new MLKEMPublicKeyParameters( + Utils.getParameters(spec.getParameterSpec().getName()), + spec.getPublicData())); + } + + return super.engineGeneratePublic(keySpec); + } + + public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) + throws IOException + { + return new BCMLKEMPrivateKey(keyInfo); + } + + public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) + throws IOException + { + return new BCMLKEMPublicKey(keyInfo); + } + + public static class MLKEM512 + extends MLKEMKeyFactorySpi + { + public MLKEM512() + { + super(NISTObjectIdentifiers.id_alg_ml_kem_512); + } + } + + public static class MLKEM768 + extends MLKEMKeyFactorySpi + { + public MLKEM768() + { + super(NISTObjectIdentifiers.id_alg_ml_kem_768); + } + } + + public static class MLKEM1024 + extends MLKEMKeyFactorySpi + { + public MLKEM1024() + { + super(NISTObjectIdentifiers.id_alg_ml_kem_1024); + } + } + +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyGeneratorSpi.java new file mode 100644 index 0000000000..eb3a50c1ca --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyGeneratorSpi.java @@ -0,0 +1,160 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.security.InvalidAlgorithmParameterException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.KeyGeneratorSpi; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import javax.security.auth.DestroyFailedException; + +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; +import org.bouncycastle.jcajce.spec.KEMExtractSpec; +import org.bouncycastle.jcajce.spec.KEMGenerateSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; +import org.bouncycastle.util.Arrays; + +public class MLKEMKeyGeneratorSpi + extends KeyGeneratorSpi +{ + private KEMGenerateSpec genSpec; + private SecureRandom random; + private KEMExtractSpec extSpec; + private MLKEMParameters kyberParameters; + + public MLKEMKeyGeneratorSpi() + { + this(null); + } + + protected MLKEMKeyGeneratorSpi(MLKEMParameters kyberParameters) + { + this.kyberParameters = kyberParameters; + } + + protected void engineInit(SecureRandom secureRandom) + { + throw new UnsupportedOperationException("Operation not supported"); + } + + protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec, SecureRandom secureRandom) + throws InvalidAlgorithmParameterException + { + this.random = secureRandom; + if (algorithmParameterSpec instanceof KEMGenerateSpec) + { + this.genSpec = (KEMGenerateSpec)algorithmParameterSpec; + this.extSpec = null; + if (kyberParameters != null) + { + String canonicalAlgName = MLKEMParameterSpec.fromName(kyberParameters.getName()).getName(); + if (!canonicalAlgName.equals(genSpec.getPublicKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } + } + else if (algorithmParameterSpec instanceof KEMExtractSpec) + { + this.genSpec = null; + this.extSpec = (KEMExtractSpec)algorithmParameterSpec; + if (kyberParameters != null) + { + String canonicalAlgName = MLKEMParameterSpec.fromName(kyberParameters.getName()).getName(); + if (!canonicalAlgName.equals(extSpec.getPrivateKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } + } + else + { + throw new InvalidAlgorithmParameterException("unknown spec"); + } + } + + protected void engineInit(int i, SecureRandom secureRandom) + { + throw new UnsupportedOperationException("Operation not supported"); + } + + protected SecretKey engineGenerateKey() + { + if (genSpec != null) + { + BCMLKEMPublicKey pubKey = (BCMLKEMPublicKey)genSpec.getPublicKey(); + MLKEMGenerator kemGen = new MLKEMGenerator(random); + + SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(pubKey.getKeyParams()); + + byte[] sharedSecret = secEnc.getSecret(); + + byte[] secret = KdfUtil.makeKeyBytes(genSpec, sharedSecret); + + Arrays.clear(sharedSecret); + + SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secret, genSpec.getKeyAlgorithmName()), secEnc.getEncapsulation()); + + try + { + secEnc.destroy(); + } + catch (DestroyFailedException e) + { + throw new IllegalStateException("key cleanup failed"); + } + + return rv; + } + else + { + BCMLKEMPrivateKey privKey = (BCMLKEMPrivateKey)extSpec.getPrivateKey(); + MLKEMExtractor kemExt = new MLKEMExtractor(privKey.getKeyParams()); + + byte[] encapsulation = extSpec.getEncapsulation(); + byte[] sharedSecret = kemExt.extractSecret(encapsulation); + byte[] secret = KdfUtil.makeKeyBytes(extSpec, sharedSecret); + + Arrays.clear(sharedSecret); + + SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secret, extSpec.getKeyAlgorithmName()), encapsulation); + + Arrays.clear(secret); + + return rv; + } + } + + public static class MLKEM512 + extends MLKEMKeyGeneratorSpi + { + public MLKEM512() + { + super(MLKEMParameters.ml_kem_512); + } + } + + public static class MLKEM768 + extends MLKEMKeyGeneratorSpi + { + public MLKEM768() + { + super(MLKEMParameters.ml_kem_768); + } + } + + public static class MLKEM1024 + extends MLKEMKeyGeneratorSpi + { + public MLKEM1024() + { + super(MLKEMParameters.ml_kem_1024); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyPairGeneratorSpi.java new file mode 100644 index 0000000000..facce8a400 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyPairGeneratorSpi.java @@ -0,0 +1,158 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; +import org.bouncycastle.util.Strings; + +public class MLKEMKeyPairGeneratorSpi + extends java.security.KeyPairGenerator +{ + MLKEMKeyGenerationParameters param; + MLKEMKeyPairGenerator engine = new MLKEMKeyPairGenerator(); + + SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + boolean initialised = false; + private MLKEMParameters mlkemParameters; + + public MLKEMKeyPairGeneratorSpi() + { + super("ML-KEM"); + } + + protected MLKEMKeyPairGeneratorSpi(MLKEMParameterSpec paramSpec) + { + super(Strings.toUpperCase(paramSpec.getName())); + this.mlkemParameters = Utils.getParameters(paramSpec.getName()); + + if (param == null) + { + param = new MLKEMKeyGenerationParameters(random, mlkemParameters); + } + + engine.init(param); + initialised = true; + } + + public void initialize( + int strength, + SecureRandom random) + { + throw new IllegalArgumentException("use AlgorithmParameterSpec"); + } + + public void initialize( + AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException + { + try + { + initialize(params, new BCJcaJceHelper().createSecureRandom("DEFAULT")); + } + catch (NoSuchAlgorithmException e) + { + throw new IllegalStateException("unable to find DEFAULT DRBG"); + } + } + + public void initialize( + AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + String name = getNameFromParams(params); + + if (name != null) + { + MLKEMParameters mlkemParams = Utils.getParameters(name); + if (mlkemParams == null) + { + throw new InvalidAlgorithmParameterException("unknown parameter set name: " + name); + } + + if (mlkemParameters != null && !mlkemParams.getName().equals(mlkemParameters.getName())) + { + throw new InvalidAlgorithmParameterException("key pair generator locked to " + getAlgorithm()); + } + + param = new MLKEMKeyGenerationParameters(random, (MLKEMParameters)mlkemParams); + + engine.init(param); + initialised = true; + } + else + { + throw new InvalidAlgorithmParameterException("invalid ParameterSpec: " + params); + } + } + + public KeyPair generateKeyPair() + { + if (!initialised) + { + param = new MLKEMKeyGenerationParameters(random, MLKEMParameters.ml_kem_768); + + engine.init(param); + initialised = true; + } + + AsymmetricCipherKeyPair pair = engine.generateKeyPair(); + MLKEMPublicKeyParameters pub = (MLKEMPublicKeyParameters)pair.getPublic(); + MLKEMPrivateKeyParameters priv = (MLKEMPrivateKeyParameters)pair.getPrivate(); + + return new KeyPair(new BCMLKEMPublicKey(pub), new BCMLKEMPrivateKey(priv)); + } + + private static String getNameFromParams(AlgorithmParameterSpec paramSpec) + { + if (paramSpec instanceof MLKEMParameterSpec) + { + MLKEMParameterSpec params = (MLKEMParameterSpec)paramSpec; + return params.getName(); + } + else + { + return Strings.toUpperCase(SpecUtil.getNameFrom(paramSpec)); + } + } + + public static class MLKEM512 + extends MLKEMKeyPairGeneratorSpi + { + public MLKEM512() + { + super(MLKEMParameterSpec.ml_kem_512); + } + } + + public static class MLKEM768 + extends MLKEMKeyPairGeneratorSpi + { + public MLKEM768() + { + super(MLKEMParameterSpec.ml_kem_768); + } + } + + public static class MLKEM1024 + extends MLKEMKeyPairGeneratorSpi + { + public MLKEM1024() + { + super(MLKEMParameterSpec.ml_kem_1024); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/Utils.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/Utils.java new file mode 100644 index 0000000000..12f94c8b75 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/mlkem/Utils.java @@ -0,0 +1,24 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; + +class Utils +{ + private static Map parameters = new HashMap(); + + static + { + parameters.put(MLKEMParameterSpec.ml_kem_512.getName(), MLKEMParameters.ml_kem_512); + parameters.put(MLKEMParameterSpec.ml_kem_768.getName(), MLKEMParameters.ml_kem_768); + parameters.put(MLKEMParameterSpec.ml_kem_1024.getName(), MLKEMParameters.ml_kem_1024); + } + + static MLKEMParameters getParameters(String name) + { + return (MLKEMParameters)parameters.get(name); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPrivateKey.java index f92a430ad4..215945d3eb 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPrivateKey.java @@ -154,6 +154,15 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/BCSLHDSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/BCSLHDSAPrivateKey.java new file mode 100644 index 0000000000..a0cc8ca28e --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/BCSLHDSAPrivateKey.java @@ -0,0 +1,158 @@ +package org.bouncycastle.jcajce.provider.asymmetric.slhdsa; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.bouncycastle.asn1.ASN1Set; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.jcajce.interfaces.SLHDSAPrivateKey; +import org.bouncycastle.jcajce.interfaces.SLHDSAPublicKey; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Fingerprint; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class BCSLHDSAPrivateKey + implements SLHDSAPrivateKey +{ + private static final long serialVersionUID = 1L; + + private transient SLHDSAPrivateKeyParameters params; + private transient ASN1Set attributes; + + public BCSLHDSAPrivateKey( + SLHDSAPrivateKeyParameters params) + { + this.params = params; + } + + public BCSLHDSAPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(PrivateKeyInfo keyInfo) + throws IOException + { + this.attributes = keyInfo.getAttributes(); + this.params = (SLHDSAPrivateKeyParameters)PrivateKeyFactory.createKey(keyInfo); + } + + /** + * Compare this SPHINCS-256 private key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCSLHDSAPrivateKey) + { + BCSLHDSAPrivateKey otherKey = (BCSLHDSAPrivateKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "SLH-DSA..." + */ + public final String getAlgorithm() + { + return "SLH-DSA" + "-" + Strings.toUpperCase(params.getParameters().getName()); + } + + public byte[] getEncoded() + { + + try + { + PrivateKeyInfo pki = PrivateKeyInfoFactory.createPrivateKeyInfo(params, attributes); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public SLHDSAPublicKey getPublicKey() + { + return new BCSLHDSAPublicKey(new SLHDSAPublicKeyParameters(params.getParameters(), params.getPublicKey())); + } + + public SLHDSAParameterSpec getParameterSpec() + { + return SLHDSAParameterSpec.fromName(params.getParameters().getName()); + } + + public String getFormat() + { + return "PKCS#8"; + } + + public String toString() + { + StringBuilder buf = new StringBuilder(); + String nl = Strings.lineSeparator(); + byte[] keyBytes = params.getPublicKey(); + + // -DM Hex.toHexString + buf.append(getAlgorithm()) + .append(" ") + .append("Private Key").append(" [") + .append(new Fingerprint(keyBytes).toString()) + .append("]") + .append(nl) + .append(" public data: ") + .append(Hex.toHexString(keyBytes)) + .append(nl); + + return buf.toString(); + } + + SLHDSAPrivateKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(PrivateKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/BCSLHDSAPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/BCSLHDSAPublicKey.java new file mode 100644 index 0000000000..59ee6d8b86 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/BCSLHDSAPublicKey.java @@ -0,0 +1,152 @@ +package org.bouncycastle.jcajce.provider.asymmetric.slhdsa; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.SLHDSAPublicKey; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Fingerprint; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; + +public class BCSLHDSAPublicKey + implements SLHDSAPublicKey +{ + private static final long serialVersionUID = 1L; + + private transient SLHDSAPublicKeyParameters params; + + public BCSLHDSAPublicKey( + SLHDSAPublicKeyParameters params) + { + this.params = params; + } + + public BCSLHDSAPublicKey(SubjectPublicKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(SubjectPublicKeyInfo keyInfo) + throws IOException + { + this.params = (SLHDSAPublicKeyParameters)PublicKeyFactory.createKey(keyInfo); + } + + /** + * Compare this SPHINCS-256 public key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCSLHDSAPublicKey) + { + BCSLHDSAPublicKey otherKey = (BCSLHDSAPublicKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "SLH-DSA" followed by the parameter type. + */ + public final String getAlgorithm() + { + return "SLH-DSA" + "-" + Strings.toUpperCase(params.getParameters().getName()); + } + + public byte[] getPublicData() + { + return params.getEncoded(); + } + + public byte[] getEncoded() + { + try + { + SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(params); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public String getFormat() + { + return "X.509"; + } + + public SLHDSAParameterSpec getParameterSpec() + { + return SLHDSAParameterSpec.fromName(params.getParameters().getName()); + } + + public String toString() + { + StringBuilder buf = new StringBuilder(); + String nl = Strings.lineSeparator(); + byte[] keyBytes = params.getEncoded(); + + // -DM Hex.toHexString + buf.append(getAlgorithm()) + .append(" ") + .append("Public Key").append(" [") + .append(new Fingerprint(keyBytes).toString()) + .append("]") + .append(nl) + .append(" public data: ") + .append(Hex.toHexString(keyBytes)) + .append(nl); + + return buf.toString(); + } + + SLHDSAPublicKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(SubjectPublicKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/HashSignatureSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/HashSignatureSpi.java new file mode 100644 index 0000000000..0e6b42c197 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/HashSignatureSpi.java @@ -0,0 +1,129 @@ +package org.bouncycastle.jcajce.provider.asymmetric.slhdsa; + +import java.security.InvalidKeyException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.SignatureException; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.jcajce.provider.asymmetric.util.BaseDeterministicOrRandomSignature; +import org.bouncycastle.pqc.crypto.slhdsa.HashSLHDSASigner; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; + +public class HashSignatureSpi + extends BaseDeterministicOrRandomSignature + { + private final HashSLHDSASigner signer; + + protected HashSignatureSpi(HashSLHDSASigner signer) + { + super("HASH-SLH-DSA"); + + this.signer = signer; + } + + protected void verifyInit(PublicKey publicKey) + throws InvalidKeyException + { + if (publicKey instanceof BCSLHDSAPublicKey) + { + BCSLHDSAPublicKey key = (BCSLHDSAPublicKey)publicKey; + + this.keyParams = key.getKeyParams(); + } + else + { + throw new InvalidKeyException("unknown public key passed to SLH-DSA"); + } + } + + protected void signInit(PrivateKey privateKey, SecureRandom random) + throws InvalidKeyException + { + this.appRandom = random; + if (privateKey instanceof BCSLHDSAPrivateKey) + { + BCSLHDSAPrivateKey key = (BCSLHDSAPrivateKey)privateKey; + + this.keyParams = key.getKeyParams(); + } + else + { + throw new InvalidKeyException("unknown private key passed to SLH-DSA"); + } + } + + protected void updateEngine(byte b) + throws SignatureException + { + signer.update(b); + } + + protected void updateEngine(byte[] buf, int off, int len) + throws SignatureException + { + signer.update(buf, off, len); + } + + protected byte[] engineSign() + throws SignatureException + { + CipherParameters param = keyParams; + + if (!(param instanceof SLHDSAPrivateKeyParameters)) + { + throw new SignatureException("engine initialized for verification"); + } + + try + { + byte[] sig = signer.generateSignature(); + + return sig; + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + finally + { + this.isInitState = true; + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + CipherParameters param = keyParams; + + if (!(param instanceof SLHDSAPublicKeyParameters)) + { + throw new SignatureException("engine initialized for signing"); + } + + try + { + return signer.verifySignature(sigBytes); + } + finally + { + this.isInitState = true; + } + } + + protected void reInitialize(boolean forSigning, CipherParameters params) + { + signer.init(forSigning, params); + } + + static public class Direct + extends HashSignatureSpi + { + public Direct() + { + super(new HashSLHDSASigner()); + } + } + } \ No newline at end of file diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SLHDSAKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SLHDSAKeyFactorySpi.java new file mode 100644 index 0000000000..088b359a16 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SLHDSAKeyFactorySpi.java @@ -0,0 +1,364 @@ +package org.bouncycastle.jcajce.provider.asymmetric.slhdsa; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; + +public class SLHDSAKeyFactorySpi + extends BaseKeyFactorySpi +{ + private static final Set pureKeyOids = new HashSet(); + private static final Set hashKeyOids = new HashSet(); + static + { + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_128f); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_128s); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_192f); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_192s); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_256f); + pureKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_256s); + + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_128f); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_128s); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_192f); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_192s); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_256f); + hashKeyOids.add(NISTObjectIdentifiers.id_slh_dsa_shake_256s); + + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + hashKeyOids.add(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + } + + public SLHDSAKeyFactorySpi(Set keyOids) + { + super(keyOids); + } + + public SLHDSAKeyFactorySpi(ASN1ObjectIdentifier keyOid) + { + super(keyOid); + } + + public final KeySpec engineGetKeySpec(Key key, Class keySpec) + throws InvalidKeySpecException + { + if (key instanceof BCSLHDSAPrivateKey) + { + if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new PKCS8EncodedKeySpec(key.getEncoded()); + } + } + else if (key instanceof BCSLHDSAPublicKey) + { + if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new X509EncodedKeySpec(key.getEncoded()); + } + } + else + { + throw new InvalidKeySpecException("Unsupported key type: " + + key.getClass() + "."); + } + + throw new InvalidKeySpecException("Unknown key specification: " + + keySpec + "."); + } + + public final Key engineTranslateKey(Key key) + throws InvalidKeyException + { + if (key instanceof BCSLHDSAPrivateKey || key instanceof BCSLHDSAPublicKey) + { + return key; + } + + throw new InvalidKeyException("Unsupported key type"); + } + + public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) + throws IOException + { + return new BCSLHDSAPrivateKey(keyInfo); + } + + public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) + throws IOException + { + return new BCSLHDSAPublicKey(keyInfo); + } + + public static class Pure + extends SLHDSAKeyFactorySpi + { + public Pure() + { + super(pureKeyOids); + } + } + + public static class Sha2_128f + extends SLHDSAKeyFactorySpi + { + public Sha2_128f() + { + super(NISTObjectIdentifiers.id_slh_dsa_sha2_128f); + } + } + + public static class Sha2_128s + extends SLHDSAKeyFactorySpi + { + public Sha2_128s() + { + super(NISTObjectIdentifiers.id_slh_dsa_sha2_128s); + } + } + + public static class Sha2_192f + extends SLHDSAKeyFactorySpi + { + public Sha2_192f() + { + super(NISTObjectIdentifiers.id_slh_dsa_sha2_192f); + } + } + + public static class Sha2_192s + extends SLHDSAKeyFactorySpi + { + public Sha2_192s() + { + super(NISTObjectIdentifiers.id_slh_dsa_sha2_192s); + } + } + + public static class Sha2_256f + extends SLHDSAKeyFactorySpi + { + public Sha2_256f() + { + super(NISTObjectIdentifiers.id_slh_dsa_sha2_256f); + } + } + + public static class Sha2_256s + extends SLHDSAKeyFactorySpi + { + public Sha2_256s() + { + super(NISTObjectIdentifiers.id_slh_dsa_sha2_256s); + } + } + + public static class Shake_128f + extends SLHDSAKeyFactorySpi + { + public Shake_128f() + { + super(NISTObjectIdentifiers.id_slh_dsa_shake_128f); + } + } + + public static class Shake_128s + extends SLHDSAKeyFactorySpi + { + public Shake_128s() + { + super(NISTObjectIdentifiers.id_slh_dsa_shake_128s); + } + } + + public static class Shake_192f + extends SLHDSAKeyFactorySpi + { + public Shake_192f() + { + super(NISTObjectIdentifiers.id_slh_dsa_shake_192f); + } + } + + public static class Shake_192s + extends SLHDSAKeyFactorySpi + { + public Shake_192s() + { + super(NISTObjectIdentifiers.id_slh_dsa_shake_192s); + } + } + + public static class Shake_256f + extends SLHDSAKeyFactorySpi + { + public Shake_256f() + { + super(NISTObjectIdentifiers.id_slh_dsa_shake_256f); + } + } + + public static class Shake_256s + extends SLHDSAKeyFactorySpi + { + public Shake_256s() + { + super(NISTObjectIdentifiers.id_slh_dsa_shake_256s); + } + } + + public static class Hash + extends SLHDSAKeyFactorySpi + { + public Hash() + { + super(hashKeyOids); + } + } + + public static class HashSha2_128f + extends SLHDSAKeyFactorySpi + { + public HashSha2_128f() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256); + } + } + + public static class HashSha2_128s + extends SLHDSAKeyFactorySpi + { + public HashSha2_128s() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256); + } + } + + public static class HashSha2_192f + extends SLHDSAKeyFactorySpi + { + public HashSha2_192f() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512); + } + } + + public static class HashSha2_192s + extends SLHDSAKeyFactorySpi + { + public HashSha2_192s() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512); + } + } + + public static class HashSha2_256f + extends SLHDSAKeyFactorySpi + { + public HashSha2_256f() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512); + } + } + + public static class HashSha2_256s + extends SLHDSAKeyFactorySpi + { + public HashSha2_256s() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512); + } + } + + public static class HashShake_128f + extends SLHDSAKeyFactorySpi + { + public HashShake_128f() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128); + } + } + + public static class HashShake_128s + extends SLHDSAKeyFactorySpi + { + public HashShake_128s() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128); + } + } + + public static class HashShake_192f + extends SLHDSAKeyFactorySpi + { + public HashShake_192f() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256); + } + } + + public static class HashShake_192s + extends SLHDSAKeyFactorySpi + { + public HashShake_192s() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256); + } + } + + public static class HashShake_256f + extends SLHDSAKeyFactorySpi + { + public HashShake_256f() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256); + } + } + + public static class HashShake_256s + extends SLHDSAKeyFactorySpi + { + public HashShake_256s() + { + super(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SLHDSAKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SLHDSAKeyPairGeneratorSpi.java new file mode 100644 index 0000000000..338de9791c --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SLHDSAKeyPairGeneratorSpi.java @@ -0,0 +1,383 @@ +package org.bouncycastle.jcajce.provider.asymmetric.slhdsa; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAKeyPairGenerator; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; +import org.bouncycastle.util.Strings; + +public class SLHDSAKeyPairGeneratorSpi + extends java.security.KeyPairGenerator +{ + private static Map parameters = new HashMap(); + + static + { + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_128f.getName(), SLHDSAParameters.sha2_128f); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_128s.getName(), SLHDSAParameters.sha2_128s); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_192f.getName(), SLHDSAParameters.sha2_192f); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_192s.getName(), SLHDSAParameters.sha2_192s); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_256f.getName(), SLHDSAParameters.sha2_256f); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_256s.getName(), SLHDSAParameters.sha2_256s); + + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_128f.getName(), SLHDSAParameters.shake_128f); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_128s.getName(), SLHDSAParameters.shake_128s); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_192f.getName(), SLHDSAParameters.shake_192f); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_192s.getName(), SLHDSAParameters.shake_192s); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_256f.getName(), SLHDSAParameters.shake_256f); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_256s.getName(), SLHDSAParameters.shake_256s); + + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_128f_with_sha256.getName(), SLHDSAParameters.sha2_128f_with_sha256); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_128s_with_sha256.getName(), SLHDSAParameters.sha2_128s_with_sha256); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_192f_with_sha512.getName(), SLHDSAParameters.sha2_192f_with_sha512); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_192s_with_sha512.getName(), SLHDSAParameters.sha2_192s_with_sha512); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_256f_with_sha512.getName(), SLHDSAParameters.sha2_256f_with_sha512); + parameters.put(SLHDSAParameterSpec.slh_dsa_sha2_256s_with_sha512.getName(), SLHDSAParameters.sha2_256s_with_sha512); + + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_128f_with_shake128.getName(), SLHDSAParameters.shake_128f_with_shake128); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_128s_with_shake128.getName(), SLHDSAParameters.shake_128s_with_shake128); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_192f_with_shake256.getName(), SLHDSAParameters.shake_192f_with_shake256); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_192s_with_shake256.getName(), SLHDSAParameters.shake_192s_with_shake256); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_256f_with_shake256.getName(), SLHDSAParameters.shake_256f_with_shake256); + parameters.put(SLHDSAParameterSpec.slh_dsa_shake_256s_with_shake256.getName(), SLHDSAParameters.shake_256s_with_shake256); + } + + SLHDSAKeyGenerationParameters param; + SLHDSAKeyPairGenerator engine = new SLHDSAKeyPairGenerator(); + + SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + boolean initialised = false; + + public SLHDSAKeyPairGeneratorSpi(String name) + { + super(name); + } + + protected SLHDSAKeyPairGeneratorSpi(SLHDSAParameterSpec paramSpec) + { + super("SLH-DSA" + "-" + Strings.toUpperCase(paramSpec.getName())); + + param = new SLHDSAKeyGenerationParameters(random, (SLHDSAParameters)parameters.get(paramSpec.getName())); + + engine.init(param); + initialised = true; + } + + public void initialize( + int strength, + SecureRandom random) + { + throw new IllegalArgumentException("use AlgorithmParameterSpec"); + } + + public void initialize( + AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + String name = getNameFromParams(params); + + if (name != null) + { + SLHDSAParameters parameters = (SLHDSAParameters)SLHDSAKeyPairGeneratorSpi.parameters.get(name); + if (parameters == null) + { + throw new InvalidAlgorithmParameterException("unknown parameter set name: " + name); + } + param = new SLHDSAKeyGenerationParameters(random, parameters); + + engine.init(param); + initialised = true; + } + else + { + throw new InvalidAlgorithmParameterException("invalid ParameterSpec: " + params); + } + } + + public KeyPair generateKeyPair() + { + if (!initialised) + { + if (this.getAlgorithm().startsWith("HASH")) + { + param = new SLHDSAKeyGenerationParameters(random, SLHDSAParameters.sha2_128f_with_sha256); + } + else + { + param = new SLHDSAKeyGenerationParameters(random, SLHDSAParameters.sha2_128f); + } + + engine.init(param); + initialised = true; + } + + AsymmetricCipherKeyPair pair = engine.generateKeyPair(); + SLHDSAPublicKeyParameters pub = (SLHDSAPublicKeyParameters)pair.getPublic(); + SLHDSAPrivateKeyParameters priv = (SLHDSAPrivateKeyParameters)pair.getPrivate(); + + return new KeyPair(new BCSLHDSAPublicKey(pub), new BCSLHDSAPrivateKey(priv)); + } + + private static String getNameFromParams(AlgorithmParameterSpec paramSpec) + { + if (paramSpec instanceof SLHDSAParameterSpec) + { + SLHDSAParameterSpec params = (SLHDSAParameterSpec)paramSpec; + return params.getName(); + } + else + { + return Strings.toUpperCase(SpecUtil.getNameFrom(paramSpec)); + } + } + + public static class Pure + extends SLHDSAKeyPairGeneratorSpi + { + public Pure() + throws NoSuchAlgorithmException + { + super("SLH-DSA"); + } + } + + public static class Sha2_128s + extends SLHDSAKeyPairGeneratorSpi + { + public Sha2_128s() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_128s); + } + } + + public static class Sha2_128f + extends SLHDSAKeyPairGeneratorSpi + { + public Sha2_128f() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_128f); + } + } + + public static class Sha2_192s + extends SLHDSAKeyPairGeneratorSpi + { + public Sha2_192s() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_192s); + } + } + + public static class Sha2_192f + extends SLHDSAKeyPairGeneratorSpi + { + public Sha2_192f() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_192f); + } + } + + public static class Sha2_256s + extends SLHDSAKeyPairGeneratorSpi + { + public Sha2_256s() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_256s); + } + } + + public static class Sha2_256f + extends SLHDSAKeyPairGeneratorSpi + { + public Sha2_256f() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_256f); + } + } + + public static class Shake_128s + extends SLHDSAKeyPairGeneratorSpi + { + public Shake_128s() + { + super(SLHDSAParameterSpec.slh_dsa_shake_128s); + } + } + + public static class Shake_128f + extends SLHDSAKeyPairGeneratorSpi + { + public Shake_128f() + { + super(SLHDSAParameterSpec.slh_dsa_shake_128f); + } + } + + public static class Shake_192s + extends SLHDSAKeyPairGeneratorSpi + { + public Shake_192s() + { + super(SLHDSAParameterSpec.slh_dsa_shake_192s); + } + } + + public static class Shake_192f + extends SLHDSAKeyPairGeneratorSpi + { + public Shake_192f() + { + super(SLHDSAParameterSpec.slh_dsa_shake_192f); + } + } + + public static class Shake_256s + extends SLHDSAKeyPairGeneratorSpi + { + public Shake_256s() + { + super(SLHDSAParameterSpec.slh_dsa_shake_256s); + } + } + + public static class Hash + extends SLHDSAKeyPairGeneratorSpi + { + public Hash() + throws NoSuchAlgorithmException + { + super("HASH-SLH-DSA"); + } + } + + public static class Shake_256f + extends SLHDSAKeyPairGeneratorSpi + { + public Shake_256f() + { + super(SLHDSAParameterSpec.slh_dsa_shake_256f); + } + } + + public static class HashSha2_128s + extends SLHDSAKeyPairGeneratorSpi + { + public HashSha2_128s() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_128s_with_sha256); + } + } + + public static class HashSha2_128f + extends SLHDSAKeyPairGeneratorSpi + { + public HashSha2_128f() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_128f_with_sha256); + } + } + + public static class HashSha2_192s + extends SLHDSAKeyPairGeneratorSpi + { + public HashSha2_192s() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_192s_with_sha512); + } + } + + public static class HashSha2_192f + extends SLHDSAKeyPairGeneratorSpi + { + public HashSha2_192f() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_192f_with_sha512); + } + } + + public static class HashSha2_256s + extends SLHDSAKeyPairGeneratorSpi + { + public HashSha2_256s() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_256s_with_sha512); + } + } + + public static class HashSha2_256f + extends SLHDSAKeyPairGeneratorSpi + { + public HashSha2_256f() + { + super(SLHDSAParameterSpec.slh_dsa_sha2_256f_with_sha512); + } + } + + public static class HashShake_128s + extends SLHDSAKeyPairGeneratorSpi + { + public HashShake_128s() + { + super(SLHDSAParameterSpec.slh_dsa_shake_128s_with_shake128); + } + } + + public static class HashShake_128f + extends SLHDSAKeyPairGeneratorSpi + { + public HashShake_128f() + { + super(SLHDSAParameterSpec.slh_dsa_shake_128f_with_shake128); + } + } + + public static class HashShake_192s + extends SLHDSAKeyPairGeneratorSpi + { + public HashShake_192s() + { + super(SLHDSAParameterSpec.slh_dsa_shake_192s_with_shake256); + } + } + + public static class HashShake_192f + extends SLHDSAKeyPairGeneratorSpi + { + public HashShake_192f() + { + super(SLHDSAParameterSpec.slh_dsa_shake_192f_with_shake256); + } + } + + public static class HashShake_256s + extends SLHDSAKeyPairGeneratorSpi + { + public HashShake_256s() + { + super(SLHDSAParameterSpec.slh_dsa_shake_256s_with_shake256); + } + } + + public static class HashShake_256f + extends SLHDSAKeyPairGeneratorSpi + { + public HashShake_256f() + { + super(SLHDSAParameterSpec.slh_dsa_shake_256f_with_shake256); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SignatureSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SignatureSpi.java new file mode 100644 index 0000000000..2a8ea4a538 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/slhdsa/SignatureSpi.java @@ -0,0 +1,135 @@ +package org.bouncycastle.jcajce.provider.asymmetric.slhdsa; + +import java.io.ByteArrayOutputStream; +import java.security.InvalidKeyException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.SignatureException; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.jcajce.provider.asymmetric.util.BaseDeterministicOrRandomSignature; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSASigner; + +public class SignatureSpi + extends BaseDeterministicOrRandomSignature +{ + private final ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + private final SLHDSASigner signer; + + protected SignatureSpi(SLHDSASigner signer) + { + super("SLH-DSA"); + + this.signer = signer; + } + + protected void verifyInit(PublicKey publicKey) + throws InvalidKeyException + { + if (publicKey instanceof BCSLHDSAPublicKey) + { + BCSLHDSAPublicKey key = (BCSLHDSAPublicKey)publicKey; + + this.keyParams = key.getKeyParams(); + } + else + { + throw new InvalidKeyException("unknown public key passed to SLH-DSA"); + } + } + + protected void signInit(PrivateKey privateKey, SecureRandom random) + throws InvalidKeyException + { + this.appRandom = random; + if (privateKey instanceof BCSLHDSAPrivateKey) + { + BCSLHDSAPrivateKey key = (BCSLHDSAPrivateKey)privateKey; + + this.keyParams = key.getKeyParams(); + } + else + { + throw new InvalidKeyException("unknown private key passed to SLH-DSA"); + } + } + + protected void updateEngine(byte b) + throws SignatureException + { + bOut.write(b); + } + + protected void updateEngine(byte[] buf, int off, int len) + throws SignatureException + { + bOut.write(buf, off, len); + } + + protected byte[] engineSign() + throws SignatureException + { + CipherParameters param = keyParams; + + if (!(param instanceof SLHDSAPrivateKeyParameters)) + { + throw new SignatureException("engine initialized for verification"); + } + + try + { + byte[] sig = signer.generateSignature(bOut.toByteArray()); + + return sig; + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + finally + { + this.isInitState = true; + bOut.reset(); + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + CipherParameters param = keyParams; + + if (!(param instanceof SLHDSAPublicKeyParameters)) + { + throw new SignatureException("engine initialized for signing"); + } + + try + { + return signer.verifySignature(bOut.toByteArray(), sigBytes); + } + finally + { + this.isInitState = true; + bOut.reset(); + } + } + + protected void reInitialize(boolean forSigning, CipherParameters params) + { + signer.init(forSigning, params); + + bOut.reset(); + } + + static public class Direct + extends SignatureSpi + { + public Direct() + { + super(new SLHDSASigner()); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/BaseDeterministicOrRandomSignature.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/BaseDeterministicOrRandomSignature.java new file mode 100644 index 0000000000..cc3178676b --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/BaseDeterministicOrRandomSignature.java @@ -0,0 +1,200 @@ +package org.bouncycastle.jcajce.provider.asymmetric.util; + +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.PrivateKey; +import java.security.ProviderException; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.ParametersWithContext; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.jcajce.spec.ContextParameterSpec; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.jcajce.util.JcaJceHelper; +import org.bouncycastle.util.Exceptions; + +public abstract class BaseDeterministicOrRandomSignature + extends Signature +{ + private final JcaJceHelper helper = new BCJcaJceHelper(); + private final AlgorithmParameterSpec originalSpec; + + protected AlgorithmParameters engineParams; + protected ContextParameterSpec paramSpec; + + protected AsymmetricKeyParameter keyParams; + protected boolean isInitState = true; + + protected BaseDeterministicOrRandomSignature(String name) + { + super(name); + this.originalSpec = ContextParameterSpec.EMPTY_CONTEXT_SPEC; + } + + final protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException + { + verifyInit(publicKey); + paramSpec = ContextParameterSpec.EMPTY_CONTEXT_SPEC; + isInitState = true; + reInit(); + } + + protected abstract void verifyInit(PublicKey publicKey) throws InvalidKeyException; + + final protected void engineInitSign( + PrivateKey privateKey) + throws InvalidKeyException + { + signInit(privateKey, null); + paramSpec = ContextParameterSpec.EMPTY_CONTEXT_SPEC; + isInitState = true; + reInit(); + } + + final protected void engineInitSign( + PrivateKey privateKey, + SecureRandom random) + throws InvalidKeyException + { + signInit(privateKey, random); + paramSpec = ContextParameterSpec.EMPTY_CONTEXT_SPEC; + isInitState = true; + reInit(); + } + + protected abstract void signInit(PrivateKey privateKey, SecureRandom random) + throws InvalidKeyException; + + final protected void engineUpdate( + byte b) + throws SignatureException + { + isInitState = false; + updateEngine(b); + } + + protected abstract void updateEngine(byte b) throws SignatureException; + + final protected void engineUpdate( + byte[] b, + int off, + int len) + throws SignatureException + { + isInitState = false; + updateEngine(b, off, len); + } + + protected abstract void updateEngine(byte[] buf, int off, int len) throws SignatureException; + + protected void engineSetParameter( + AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException + { + if (params == null) + { + if (originalSpec != null) + { + params = originalSpec; + } + else + { + return; + } + } + + if (!isInitState) + { + throw new ProviderException("cannot call setParameter in the middle of update"); + } + + if (params instanceof ContextParameterSpec) + { + this.paramSpec = (ContextParameterSpec)params; + reInit(); + } + else + { + throw new InvalidAlgorithmParameterException("unknown AlgorithmParameterSpec in signature"); + } + } + + private void reInit() + { + CipherParameters param = keyParams; + + if (keyParams.isPrivate()) + { + if (appRandom != null) + { + param = new ParametersWithRandom(param, appRandom); + } + + if (paramSpec != null) + { + param = new ParametersWithContext(param, paramSpec.getContext()); + } + + reInitialize(true, param); + } + else + { + if (paramSpec != null) + { + param = new ParametersWithContext(param, paramSpec.getContext()); + } + + reInitialize(false, param); + } + } + + protected abstract void reInitialize(boolean forSigning, CipherParameters params); + + protected final AlgorithmParameters engineGetParameters() + { + if (engineParams == null) + { + if (paramSpec != null && paramSpec != ContextParameterSpec.EMPTY_CONTEXT_SPEC) + { + try + { + engineParams = helper.createAlgorithmParameters("CONTEXT"); + engineParams.init(paramSpec); + } + catch (Exception e) + { + throw Exceptions.illegalStateException(e.toString(), e); + } + } + } + + return engineParams; + } + + /** + * @deprecated replaced with engineSetParameter(java.security.spec.AlgorithmParameterSpec) + */ + protected final void engineSetParameter( + String param, + Object value) + { + throw new UnsupportedOperationException("SetParameter unsupported"); + } + + /** + * @deprecated replaced with engineGetParameters() + */ + protected final Object engineGetParameter( + String param) + { + throw new UnsupportedOperationException("GetParameter unsupported"); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/ECUtil.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/ECUtil.java index c1c93b88d4..742fa14a50 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/ECUtil.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/ECUtil.java @@ -314,7 +314,14 @@ public static int getOrderBitLength(ProviderConfiguration configuration, BigInte public static ASN1ObjectIdentifier getNamedCurveOid( String curveName) { - if (null == curveName || curveName.length() < 1) + if (null == curveName) + { + return null; + } + + curveName = curveName.trim(); + + if (curveName.length() == 0) { return null; } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PKCS12BagAttributeCarrierImpl.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PKCS12BagAttributeCarrierImpl.java index 3273bd9397..dfd4e5b5b4 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PKCS12BagAttributeCarrierImpl.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/PKCS12BagAttributeCarrierImpl.java @@ -12,6 +12,8 @@ import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OutputStream; +import org.bouncycastle.asn1.DERBMPString; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; public class PKCS12BagAttributeCarrierImpl @@ -57,6 +59,19 @@ public Enumeration getBagAttributeKeys() return pkcs12Ordering.elements(); } + public boolean hasFriendlyName() + { + ASN1Encodable friendlyNameAttr = getBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName); + return friendlyNameAttr != null; + } + + public void setFriendlyName(String friendlyName) + { + ASN1Encodable customFriendlyName = new DERBMPString(friendlyName); + this.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, customFriendlyName); + } + + int size() { return pkcs12Ordering.size(); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java index e7e3a76a1c..e7c20daf1b 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java @@ -15,6 +15,7 @@ import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.CRLReason; @@ -78,9 +79,9 @@ protected X509CRLEntryObject( */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); + Extensions extensions = c.getExtensions(); - return extns != null && !extns.isEmpty(); + return extensions != null && extensions.hasAnyCriticalExtensions(); } private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) @@ -90,15 +91,15 @@ private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCert return null; } - Extension ext = getExtension(Extension.certificateIssuer); - if (ext == null) + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), Extension.certificateIssuer); + if (extValue == null) { return previousCertificateIssuer; } try { - GeneralName[] names = GeneralNames.getInstance(ext.getParsedValue()).getNames(); + GeneralName[] names = GeneralNames.getInstance(extValue.getOctets()).getNames(); for (int i = 0; i < names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) @@ -166,35 +167,9 @@ public Set getNonCriticalExtensionOIDs() return getExtensionOIDs(false); } - private Extension getExtension(ASN1ObjectIdentifier oid) - { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - return exts.getExtension(oid); - } - - return null; - } - public byte[] getExtensionValue(String oid) { - Extension ext = getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("Exception encoding: " + e.toString()); - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } /** diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java index f113cbe2e4..e2de3fb4fc 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java @@ -83,30 +83,41 @@ abstract class X509CRLImpl this.isIndirect = isIndirect; } - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) + if (getVersion() == 2) { - return false; - } + Extensions extensions = c.getExtensions(); + if (extensions != null) + { + Enumeration e = extensions.oids(); + while (e.hasMoreElements()) + { + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - extns.remove(Extension.issuingDistributionPoint.getId()); - extns.remove(Extension.deltaCRLIndicator.getId()); + if (Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid)) + { + continue; + } + + Extension ext = extensions.getExtension(oid); + if (ext.isCritical()) + { + return true; + } + } + } + } - return !extns.isEmpty(); + return false; } private Set getExtensionOIDs(boolean critical) { if (this.getVersion() == 2) { - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -143,19 +154,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - try - { - return extValue.getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public void verify(PublicKey key) @@ -540,7 +539,7 @@ public String toString() X509SignatureUtil.prettyPrintSignature(this.getSignature(), buf, nl); - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -698,28 +697,10 @@ public boolean isRevoked(Certificate cert) return false; } - protected static byte[] getExtensionOctets(CertificateList c, String oid) + static byte[] getExtensionOctets(CertificateList c, ASN1ObjectIdentifier oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - return extValue.getOctets(); - } - return null; - } + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); - protected static ASN1OctetString getExtensionValue(CertificateList c, String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - if (null != exts) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (null != ext) - { - return ext.getExtnValue(); - } - } - return null; + return extValue == null ? null : extValue.getOctets(); } } - diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java index 8e4efe27f1..752e7fef6e 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java @@ -144,7 +144,7 @@ private static boolean isIndirectCRL(CertificateList c) throws CRLException { try { - byte[] extOctets = getExtensionOctets(c, Extension.issuingDistributionPoint.getId()); + byte[] extOctets = getExtensionOctets(c, Extension.issuingDistributionPoint); if (null == extOctets) { return false; diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java index f5c935334e..71e4832042 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java @@ -39,7 +39,6 @@ import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.DEROctetString; @@ -78,6 +77,7 @@ abstract class X509CertificateImpl protected boolean[] keyUsage; protected String sigAlgName; protected byte[] sigAlgParams; + X509CertificateImpl(JcaJceHelper bcHelper, org.bouncycastle.asn1.x509.Certificate c, BasicConstraints basicConstraints, boolean[] keyUsage, String sigAlgName, byte[] sigAlgParams) { @@ -271,10 +271,10 @@ public boolean[] getKeyUsage() return Arrays.clone(keyUsage); } - public List getExtendedKeyUsage() + public List getExtendedKeyUsage() throws CertificateParsingException { - byte[] extOctets = getExtensionOctets(c, "2.5.29.37"); + byte[] extOctets = getExtensionOctets(c, Extension.extendedKeyUsage); if (null == extOctets) { return null; @@ -282,7 +282,7 @@ public List getExtendedKeyUsage() try { - ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(extOctets)); + ASN1Sequence seq = ASN1Sequence.getInstance(extOctets); List list = new ArrayList(); for (int i = 0; i != seq.size(); i++) @@ -316,13 +316,13 @@ public int getBasicConstraints() public Collection getSubjectAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(c, Extension.subjectAlternativeName.getId()); + return getAlternativeNames(c, Extension.subjectAlternativeName); } public Collection getIssuerAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(c, Extension.issuerAlternativeName.getId()); + return getAlternativeNames(c, Extension.issuerAlternativeName); } public Set getCriticalExtensionOIDs() @@ -330,7 +330,7 @@ public Set getCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -356,20 +356,7 @@ public Set getCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - try - { - return extValue.getEncoded(); - } - catch (Exception e) - { - throw Exceptions.illegalStateException("error parsing " + e.getMessage(), e); - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public Set getNonCriticalExtensionOIDs() @@ -377,7 +364,7 @@ public Set getNonCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -403,35 +390,32 @@ public Set getNonCriticalExtensionOIDs() public boolean hasUnsupportedCriticalExtension() { - if (this.getVersion() == 3) + if (getVersion() == 3) { - Extensions extensions = c.getTBSCertificate().getExtensions(); - + Extensions extensions = c.getExtensions(); if (extensions != null) { - Enumeration e = extensions.oids(); - + Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - if (oid.equals(Extension.keyUsage) - || oid.equals(Extension.certificatePolicies) - || oid.equals(Extension.policyMappings) - || oid.equals(Extension.inhibitAnyPolicy) - || oid.equals(Extension.cRLDistributionPoints) - || oid.equals(Extension.issuingDistributionPoint) - || oid.equals(Extension.deltaCRLIndicator) - || oid.equals(Extension.policyConstraints) - || oid.equals(Extension.basicConstraints) - || oid.equals(Extension.subjectAlternativeName) - || oid.equals(Extension.nameConstraints)) + if (Extension.keyUsage.equals(oid) || + Extension.certificatePolicies.equals(oid) || + Extension.policyMappings.equals(oid) || + Extension.inhibitAnyPolicy.equals(oid) || + Extension.cRLDistributionPoints.equals(oid) || + Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid) || + Extension.policyConstraints.equals(oid) || + Extension.basicConstraints.equals(oid) || + Extension.subjectAlternativeName.equals(oid) || + Extension.nameConstraints.equals(oid)) { continue; } - Extension ext = extensions.getExtension(oid); - + Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { return true; @@ -471,7 +455,7 @@ public String toString() X509SignatureUtil.prettyPrintSignature(this.getSignature(), buf, nl); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -778,7 +762,7 @@ private void checkSignature(PublicKey key, Signature signature, ASN1Encodable si } } - private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, String oid) + private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) throws CertificateParsingException { byte[] extOctets = getExtensionOctets(c, oid); @@ -844,27 +828,10 @@ private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certifi } } - protected static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, String oid) + static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - return extValue.getOctets(); - } - return null; - } + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); - protected static ASN1OctetString getExtensionValue(org.bouncycastle.asn1.x509.Certificate c, String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - if (null != exts) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (null != ext) - { - return ext.getExtnValue(); - } - } - return null; + return extValue == null ? null : extValue.getOctets(); } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java index 9a1c8e11f0..9e86a463b1 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java @@ -15,8 +15,8 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; @@ -248,6 +248,15 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } private X509CertificateInternal getInternalCertificate() { synchronized (cacheLock) @@ -288,13 +297,13 @@ private static BasicConstraints createBasicConstraints(org.bouncycastle.asn1.x50 { try { - byte[] extOctets = getExtensionOctets(c, "2.5.29.19"); + byte[] extOctets = getExtensionOctets(c, Extension.basicConstraints); if (null == extOctets) { return null; } - return BasicConstraints.getInstance(ASN1Primitive.fromByteArray(extOctets)); + return BasicConstraints.getInstance(extOctets); } catch (Exception e) { @@ -306,13 +315,13 @@ private static boolean[] createKeyUsage(org.bouncycastle.asn1.x509.Certificate c { try { - byte[] extOctets = getExtensionOctets(c, "2.5.29.15"); + byte[] extOctets = getExtensionOctets(c, Extension.keyUsage); if (null == extOctets) { return null; } - ASN1BitString bits = ASN1BitString.getInstance(ASN1Primitive.fromByteArray(extOctets)); + ASN1BitString bits = ASN1BitString.getInstance(extOctets); byte[] bytes = bits.getBytes(); int length = (bytes.length * 8) - bits.getPadBits(); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java index dbf2d9ff93..86641be60b 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java @@ -15,17 +15,19 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.jcajce.util.MessageDigestUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Exceptions; import org.bouncycastle.util.Objects; import org.bouncycastle.util.Properties; import org.bouncycastle.util.encoders.Hex; @@ -60,6 +62,30 @@ static boolean areEquivalentAlgorithms(AlgorithmIdentifier id1, AlgorithmIdentif return Objects.areEqual(id1.getParameters(), id2.getParameters()); } + static byte[] getExtensionValue(Extensions extensions, String oid) + { + if (oid != null) + { + ASN1ObjectIdentifier asn1Oid = ASN1ObjectIdentifier.tryFromID(oid); + if (asn1Oid != null) + { + ASN1OctetString extValue = Extensions.getExtensionValue(extensions, asn1Oid); + if (null != extValue) + { + try + { + return extValue.getEncoded(); + } + catch (Exception e) + { + throw Exceptions.illegalStateException("error parsing " + e.getMessage(), e); + } + } + } + } + return null; + } + private static boolean isAbsentOrEmptyParameters(ASN1Encodable parameters) { return parameters == null || DERNull.INSTANCE.equals(parameters); @@ -116,9 +142,9 @@ static String getSignatureName(AlgorithmIdentifier sigAlgId) } if (X9ObjectIdentifiers.ecdsa_with_SHA2.equals(sigAlgOid)) { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); + AlgorithmIdentifier ecDsaParams = AlgorithmIdentifier.getInstance(params); - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; + return getDigestAlgName(ecDsaParams.getAlgorithm()) + "withECDSA"; } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/config/PKCS12StoreParameter.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/config/PKCS12StoreParameter.java index 7d0b203f79..05c8d752dd 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/config/PKCS12StoreParameter.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/config/PKCS12StoreParameter.java @@ -24,6 +24,10 @@ public PKCS12StoreParameter(OutputStream out, char[] password, boolean forDEREnc { super(out, new KeyStore.PasswordProtection(password), forDEREncoding); } + public PKCS12StoreParameter(OutputStream out, char[] password, boolean forDEREncoding, boolean overwriteFriendlyName) + { + super(out, new KeyStore.PasswordProtection(password), forDEREncoding, overwriteFriendlyName); + } public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter, boolean forDEREncoding) { diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA1.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA1.java index 3aee85f1db..81a65d2968 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA1.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA1.java @@ -9,6 +9,7 @@ import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseSecretKeyFactory; import org.bouncycastle.jcajce.provider.symmetric.util.PBESecretKeyFactory; public class SHA1 @@ -78,7 +79,16 @@ public static class PBEWithMacKeyFactory { public PBEWithMacKeyFactory() { - super("PBEwithHmacSHA", null, false, PKCS12, SHA1, 160, 0); + super("PBEwithHmacSHA1", null, false, PKCS12, SHA1, 160, 0); + } + } + + static public class KeyFactory + extends BaseSecretKeyFactory + { + public KeyFactory() + { + super("HmacSHA1", null); } } @@ -109,6 +119,8 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("Alg.Alias.Mac." + OIWObjectIdentifiers.idSHA1, "PBEWITHHMACSHA"); provider.addAlgorithm("SecretKeyFactory.PBEWITHHMACSHA1", PREFIX + "$PBEWithMacKeyFactory"); + provider.addAlgorithm("SecretKeyFactory.HMACSHA1", PREFIX + "$KeyFactory"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA1, "HMACSHA1"); } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA224.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA224.java index ac83fc231c..c35020a067 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA224.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA224.java @@ -8,6 +8,7 @@ import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseSecretKeyFactory; public class SHA224 { @@ -44,6 +45,15 @@ public HashMac() } } + static public class KeyFactory + extends BaseSecretKeyFactory + { + public KeyFactory() + { + super("HmacSHA224", null); + } + } + public static class KeyGenerator extends BaseKeyGenerator { @@ -73,6 +83,8 @@ public void configure(ConfigurableProvider provider) addHMACAlgorithm(provider, "SHA224", PREFIX + "$HashMac", PREFIX + "$KeyGenerator"); addHMACAlias(provider, "SHA224", PKCSObjectIdentifiers.id_hmacWithSHA224); + provider.addAlgorithm("SecretKeyFactory.HMACSHA224", PREFIX + "$KeyFactory"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA224, "HMACSHA224"); } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA256.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA256.java index 77e4a14983..20f6670f04 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA256.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA256.java @@ -8,6 +8,7 @@ import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseSecretKeyFactory; import org.bouncycastle.jcajce.provider.symmetric.util.PBESecretKeyFactory; public class SHA256 @@ -57,6 +58,15 @@ public PBEWithMacKeyFactory() } } + static public class KeyFactory + extends BaseSecretKeyFactory + { + public KeyFactory() + { + super("HmacSHA256", null); + } + } + /** * HMACSHA256 */ @@ -93,6 +103,9 @@ public void configure(ConfigurableProvider provider) addHMACAlgorithm(provider, "SHA256", PREFIX + "$HashMac", PREFIX + "$KeyGenerator"); addHMACAlias(provider, "SHA256", PKCSObjectIdentifiers.id_hmacWithSHA256); addHMACAlias(provider, "SHA256", NISTObjectIdentifiers.id_sha256); + + provider.addAlgorithm("SecretKeyFactory.HMACSHA256", PREFIX + "$KeyFactory"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA256, "HMACSHA256"); } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA3.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA3.java index ac140dc434..591d94f006 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA3.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA3.java @@ -1,5 +1,6 @@ package org.bouncycastle.jcajce.provider.digest; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.crypto.CipherKeyGenerator; import org.bouncycastle.crypto.digests.ParallelHash; @@ -11,6 +12,7 @@ import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseSecretKeyFactory; public class SHA3 { @@ -104,6 +106,78 @@ public HashMacSHA3(int size) } } + static public class KeyFactorySHA3 + extends BaseSecretKeyFactory + { + public KeyFactorySHA3(int size, ASN1ObjectIdentifier algOid) + { + super("HmacSHA3-" + size, algOid); + } + } + + static public class KeyFactory224 + extends KeyFactorySHA3 + { + public KeyFactory224() + { + super(224, NISTObjectIdentifiers.id_hmacWithSHA3_224); + } + } + + static public class KeyFactory256 + extends KeyFactorySHA3 + { + public KeyFactory256() + { + super(256, NISTObjectIdentifiers.id_hmacWithSHA3_256); + } + } + + static public class KeyFactory384 + extends KeyFactorySHA3 + { + public KeyFactory384() + { + super(384, NISTObjectIdentifiers.id_hmacWithSHA3_384); + } + } + + static public class KeyFactory512 + extends KeyFactorySHA3 + { + public KeyFactory512() + { + super(512, NISTObjectIdentifiers.id_hmacWithSHA3_512); + } + } + + static public class KeyFactoryKMAC + extends BaseSecretKeyFactory + { + public KeyFactoryKMAC(int size, ASN1ObjectIdentifier algOid) + { + super("KMAC" + size, algOid); + } + } + + static public class KeyFactoryKMAC128 + extends KeyFactoryKMAC + { + public KeyFactoryKMAC128() + { + super(128, NISTObjectIdentifiers.id_KmacWithSHAKE128); + } + } + + static public class KeyFactoryKMAC256 + extends KeyFactoryKMAC + { + public KeyFactoryKMAC256() + { + super(256, NISTObjectIdentifiers.id_KmacWithSHAKE256); + } + } + public static class KeyGeneratorSHA3 extends BaseKeyGenerator { @@ -321,18 +395,31 @@ public void configure(ConfigurableProvider provider) addHMACAlgorithm(provider, "SHA3-224", PREFIX + "$HashMac224", PREFIX + "$KeyGenerator224"); addHMACAlias(provider, "SHA3-224", NISTObjectIdentifiers.id_hmacWithSHA3_224); + provider.addAlgorithm("SecretKeyFactory.HMACSHA3-224", PREFIX + "$KeyFactory224"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + NISTObjectIdentifiers.id_hmacWithSHA3_224, "HMACSHA3-224"); addHMACAlgorithm(provider, "SHA3-256", PREFIX + "$HashMac256", PREFIX + "$KeyGenerator256"); addHMACAlias(provider, "SHA3-256", NISTObjectIdentifiers.id_hmacWithSHA3_256); + provider.addAlgorithm("SecretKeyFactory.HMACSHA3-256", PREFIX + "$KeyFactory256"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + NISTObjectIdentifiers.id_hmacWithSHA3_256, "HMACSHA3-256"); addHMACAlgorithm(provider, "SHA3-384", PREFIX + "$HashMac384", PREFIX + "$KeyGenerator384"); addHMACAlias(provider, "SHA3-384", NISTObjectIdentifiers.id_hmacWithSHA3_384); + provider.addAlgorithm("SecretKeyFactory.HMACSHA3-384", PREFIX + "$KeyFactory384"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + NISTObjectIdentifiers.id_hmacWithSHA3_384, "HMACSHA3-384"); addHMACAlgorithm(provider, "SHA3-512", PREFIX + "$HashMac512", PREFIX + "$KeyGenerator512"); addHMACAlias(provider, "SHA3-512", NISTObjectIdentifiers.id_hmacWithSHA3_512); + provider.addAlgorithm("SecretKeyFactory.HMACSHA3-512", PREFIX + "$KeyFactory512"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + NISTObjectIdentifiers.id_hmacWithSHA3_512, "HMACSHA3-512"); addKMACAlgorithm(provider, "128", PREFIX + "$KMac128", PREFIX + "$KeyGenerator256"); + provider.addAlgorithm("SecretKeyFactory.KMAC128", PREFIX + "$KeyFactoryKMAC128"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + NISTObjectIdentifiers.id_Kmac128, "KMAC128"); + addKMACAlgorithm(provider, "256", PREFIX + "$KMac256", PREFIX + "$KeyGenerator512"); + provider.addAlgorithm("SecretKeyFactory.KMAC256", PREFIX + "$KeyFactoryKMAC256"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + NISTObjectIdentifiers.id_Kmac256, "KMAC256"); provider.addAlgorithm("MessageDigest.TUPLEHASH256-512", PREFIX + "$DigestTupleHash256_512"); provider.addAlgorithm("MessageDigest.TUPLEHASH128-256", PREFIX + "$DigestTupleHash128_256"); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA384.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA384.java index 75b04ebf1b..7173c62a22 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA384.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA384.java @@ -9,6 +9,7 @@ import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseSecretKeyFactory; public class SHA384 { @@ -45,6 +46,15 @@ public HashMac() } } + static public class KeyFactory + extends BaseSecretKeyFactory + { + public KeyFactory() + { + super("HmacSHA384", null); + } + } + /** * HMACSHA384 */ @@ -86,6 +96,9 @@ public void configure(ConfigurableProvider provider) addHMACAlgorithm(provider, "SHA384", PREFIX + "$HashMac", PREFIX + "$KeyGenerator"); addHMACAlias(provider, "SHA384", PKCSObjectIdentifiers.id_hmacWithSHA384); + + provider.addAlgorithm("SecretKeyFactory.HMACSHA384", PREFIX + "$KeyFactory"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA384, "HMACSHA384"); } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA512.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA512.java index b43b5ca1a4..ad39fc7cca 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA512.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/digest/SHA512.java @@ -10,6 +10,7 @@ import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseSecretKeyFactory; public class SHA512 { @@ -101,6 +102,33 @@ public HashMacT256() } } + static public class KeyFactory + extends BaseSecretKeyFactory + { + public KeyFactory() + { + super("HmacSHA512", null); + } + } + + static public class KeyFactory224 + extends BaseSecretKeyFactory + { + public KeyFactory224() + { + super("HmacSHA512/224", null); + } + } + + static public class KeyFactory256 + extends BaseSecretKeyFactory + { + public KeyFactory256() + { + super("HmacSHA512/256", null); + } + } + /** * SHA-512 HMac */ @@ -181,6 +209,17 @@ public void configure(ConfigurableProvider provider) addHMACAlgorithm(provider, "SHA512/224", PREFIX + "$HashMacT224", PREFIX + "$KeyGeneratorT224"); addHMACAlgorithm(provider, "SHA512/256", PREFIX + "$HashMacT256", PREFIX + "$KeyGeneratorT256"); + + provider.addAlgorithm("SecretKeyFactory.HMACSHA512", PREFIX + "$KeyFactory"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA512, "HMACSHA512"); + + provider.addAlgorithm("SecretKeyFactory.HMACSHA512/224", PREFIX + "$KeyFactory224"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.HMACSHA512(224)", "HMACSHA512/224"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA512_224, "HMACSHA512/224"); + + provider.addAlgorithm("SecretKeyFactory.HMACSHA512/256", PREFIX + "$KeyFactory256"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.HMACSHA512(256)", "HMACSHA512/256"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory." + PKCSObjectIdentifiers.id_hmacWithSHA512_256, "HMACSHA512/256"); } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/drbg/DRBG.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/drbg/DRBG.java index 2aaf14a44c..437de65ff3 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/drbg/DRBG.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/drbg/DRBG.java @@ -223,7 +223,8 @@ public EntropySource get(int bitsRequired) // unfortunately new SecureRandom() can cause a regress and it's the only reliable way of getting access // to the JVM's seed generator. - private static EntropySourceProvider createInitialEntropySource() + + private static EntropySourceProvider createCoreEntropySourceProvider() { boolean hasGetInstanceStrong = AccessController.doPrivileged(new PrivilegedAction() { @@ -254,20 +255,25 @@ public SecureRandom run() } catch (Exception e) { - return new CoreSecureRandom(findSource()); + return null; } } }); + if (strong == null) + { + return createInitialEntropySource(); + } + return new IncrementalEntropySourceProvider(strong, true); } else { - return new IncrementalEntropySourceProvider(new CoreSecureRandom(findSource()), true); + return createInitialEntropySource(); } } - private static EntropySourceProvider createCoreEntropySourceProvider() + private static EntropySourceProvider createInitialEntropySource() { String source = AccessController.doPrivileged(new PrivilegedAction() { @@ -279,7 +285,7 @@ public String run() if (source == null) { - return createInitialEntropySource(); + return new IncrementalEntropySourceProvider(new CoreSecureRandom(findSource()), true); } else { @@ -289,7 +295,7 @@ public String run() } catch (Exception e) { - return createInitialEntropySource(); + return new IncrementalEntropySourceProvider(new CoreSecureRandom(findSource()), true); } } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/bcfks/BcFKSKeyStoreSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/bcfks/BcFKSKeyStoreSpi.java index 007d53ab64..3a30a5549b 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/bcfks/BcFKSKeyStoreSpi.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/bcfks/BcFKSKeyStoreSpi.java @@ -118,6 +118,16 @@ class BcFKSKeyStoreSpi oidMap.put("HMACSHA256", PKCSObjectIdentifiers.id_hmacWithSHA256); oidMap.put("HMACSHA384", PKCSObjectIdentifiers.id_hmacWithSHA384); oidMap.put("HMACSHA512", PKCSObjectIdentifiers.id_hmacWithSHA512); + oidMap.put("HMACSHA512/224", PKCSObjectIdentifiers.id_hmacWithSHA512_224); + oidMap.put("HMACSHA512/256", PKCSObjectIdentifiers.id_hmacWithSHA512_256); + oidMap.put("HMACSHA512(224)", PKCSObjectIdentifiers.id_hmacWithSHA512_224); + oidMap.put("HMACSHA512(256)", PKCSObjectIdentifiers.id_hmacWithSHA512_256); + oidMap.put("HMACSHA3-224", NISTObjectIdentifiers.id_hmacWithSHA3_224); + oidMap.put("HMACSHA3-256", NISTObjectIdentifiers.id_hmacWithSHA3_256); + oidMap.put("HMACSHA3-384", NISTObjectIdentifiers.id_hmacWithSHA3_384); + oidMap.put("HMACSHA3-512", NISTObjectIdentifiers.id_hmacWithSHA3_512); + oidMap.put("KMAC128", NISTObjectIdentifiers.id_Kmac128); + oidMap.put("KMAC256", NISTObjectIdentifiers.id_Kmac256); oidMap.put("SEED", KISAObjectIdentifiers.id_seedCBC); oidMap.put("CAMELLIA.128", NTTObjectIdentifiers.id_camellia128_cbc); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java index 488b434e85..219efb6d8d 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java @@ -76,6 +76,7 @@ import org.bouncycastle.asn1.pkcs.KeyDerivationFunc; import org.bouncycastle.asn1.pkcs.MacData; import org.bouncycastle.asn1.pkcs.PBES2Parameters; +import org.bouncycastle.asn1.pkcs.PBMAC1Params; import org.bouncycastle.asn1.pkcs.PBKDF2Params; import org.bouncycastle.asn1.pkcs.PKCS12PBEParams; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; @@ -93,8 +94,14 @@ import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.TBSCertificate; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; +import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.PBEParametersGenerator; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; +import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.util.DigestFactory; import org.bouncycastle.internal.asn1.cms.GCMParameters; import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; @@ -1264,45 +1271,49 @@ private void processKeyBag(SafeBag b) // // set the attributes on the key // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; String alias = null; ASN1OctetString localId = null; - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) + if (privKey instanceof PKCS12BagAttributeCarrier) { - ASN1Sequence sq = ASN1Sequence.getInstance(e.nextElement()); - ASN1ObjectIdentifier aOid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0)); - ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1)); - ASN1Primitive attr = null; + PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - if (attrSet.size() > 0) + Enumeration e = b.getBagAttributes().getObjects(); + while (e.hasMoreElements()) { - attr = (ASN1Primitive)attrSet.getObjectAt(0); + ASN1Sequence sq = ASN1Sequence.getInstance(e.nextElement()); + ASN1ObjectIdentifier aOid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0)); + ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1)); + ASN1Primitive attr = null; - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) + if (attrSet.size() > 0) { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) + attr = (ASN1Primitive)attrSet.getObjectAt(0); + + ASN1Encodable existing = bagAttr.getBagAttribute(aOid); + if (existing != null) { - throw new IOException( - "attempt to add existing attribute with different value"); + // OK, but the value has to be the same + if (!existing.toASN1Primitive().equals(attr)) + { + throw new IOException( + "attempt to add existing attribute with different value"); + } + } + else + { + bagAttr.setBagAttribute(aOid, attr); } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((ASN1BMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; + if (aOid.equals(pkcs_9_at_friendlyName)) + { + alias = ((ASN1BMPString)attr).getString(); + keys.put(alias, privKey); + } + else if (aOid.equals(pkcs_9_at_localKeyId)) + { + localId = (ASN1OctetString)attr; + } } } } @@ -1389,7 +1400,8 @@ public void engineStore(LoadStoreParameter param) else { bcParam = new PKCS12StoreParameter(((JDKPKCS12StoreParameter)param).getOutputStream(), - param.getProtectionParameter(), ((JDKPKCS12StoreParameter)param).isUseDEREncoding()); + param.getProtectionParameter(), ((JDKPKCS12StoreParameter)param).isUseDEREncoding(), + ((JDKPKCS12StoreParameter)param).isOverwriteFriendlyName()); } char[] password; @@ -1408,18 +1420,106 @@ else if (protParam instanceof KeyStore.PasswordProtection) "No support for protection parameter of type " + protParam.getClass().getName()); } - doStore(bcParam.getOutputStream(), password, bcParam.isForDEREncoding()); + doStore(bcParam.getOutputStream(), password, bcParam.isForDEREncoding(), bcParam.isOverwriteFriendlyName()); } public void engineStore(OutputStream stream, char[] password) throws IOException { - doStore(stream, password, false); + doStore(stream, password, false, true); } - private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) + private void syncFriendlyName() + { + // TODO:delete comment + // Since we cannot add any function to the KeyStore Api we will run code when saving the store + // to sync the friendlyNames with Alias depending on the storeParameter + /** + * @Override + * public void setFriendlyName(String alias, String newFriendlyName, char[] password) throws UnrecoverableKeyException, NoSuchAlgorithmException + * { + * if (alias.equals(newFriendlyName)) + * { + * return; + * } + * + * if (engineIsKeyEntry(alias)) + * { + * ((PKCS12BagAttributeCarrier)engineGetKey(alias, password)).setFriendlyName(newFriendlyName); + * keyCerts.put(newFriendlyName, keyCerts.get(alias)); + * keyCerts.remove(alias); + * } + * else + * { + * certs.put(newFriendlyName, certs.get(alias)); + * certs.remove(alias); + * } + * ((PKCS12BagAttributeCarrier)engineGetCertificate(alias)).setFriendlyName(newFriendlyName); + * + * } + */ + Enumeration cs = keys.keys(); + + while (cs.hasMoreElements()) + { + String keyId = (String) cs.nextElement(); + PrivateKey key = (PrivateKey)keys.get(keyId); + + if (key instanceof PKCS12BagAttributeCarrier) + { + ASN1Encodable friendlyName = ((PKCS12BagAttributeCarrier)key).getBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName); + if (friendlyName != null && !keyId.equals(friendlyName.toString())) + { + keys.put(friendlyName.toString(), key); + keys.remove(keyId); + } + } + } + + cs = certs.keys(); + + while (cs.hasMoreElements()) + { + String certId = (String) cs.nextElement(); + Certificate cert = (Certificate)certs.get(certId); + + if (cert instanceof PKCS12BagAttributeCarrier) + { + ASN1Encodable friendlyName = ((PKCS12BagAttributeCarrier)cert).getBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName); + if (friendlyName != null && !certId.equals(friendlyName.toString())) + { + certs.put(friendlyName.toString(), cert); + certs.remove(certId); + } + } + } + cs = keyCerts.keys(); + + while (cs.hasMoreElements()) + { + String certId = (String) cs.nextElement(); + Certificate cert = (Certificate)keyCerts.get(certId); + + if (cert instanceof PKCS12BagAttributeCarrier) + { + ASN1Encodable friendlyName = ((PKCS12BagAttributeCarrier)cert).getBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName); + if (friendlyName != null && !certId.equals(friendlyName.toString())) + { + keyCerts.put(friendlyName.toString(), cert); + keyCerts.remove(certId); + } + } + } + } + + private void doStore(OutputStream stream, char[] password, boolean useDEREncoding, boolean overwriteFriendlyName) throws IOException { + if (!overwriteFriendlyName) + { + syncFriendlyName(); + } + if (keys.size() == 0) { if (password == null) @@ -1435,7 +1535,7 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin String certId = (String)cs.nextElement(); Certificate cert = (Certificate)certs.get(certId); - SafeBag sBag = createSafeBag(certId, cert); + SafeBag sBag = createSafeBag(certId, cert, overwriteFriendlyName); certSeq.add(sBag); } @@ -1516,9 +1616,12 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin // make sure we are using the local alias on store // ASN1BMPString nm = (ASN1BMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) + if (overwriteFriendlyName) { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); + if (nm == null || !nm.getString().equals(name)) + { + bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); + } } // @@ -1617,9 +1720,12 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin // make sure we are using the local alias on store // ASN1BMPString nm = (ASN1BMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) + if (overwriteFriendlyName) { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); + if (nm == null || !nm.getString().equals(name)) + { + bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); + } } // @@ -1686,7 +1792,7 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin continue; } - SafeBag sBag = createSafeBag(certId, cert); + SafeBag sBag = createSafeBag(certId, cert, overwriteFriendlyName); certSeq.add(sBag); @@ -1749,7 +1855,6 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin } } - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); certSeq.add(sBag); @@ -1815,7 +1920,7 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin pfx.encodeTo(stream, useDEREncoding ? ASN1Encoding.DER : ASN1Encoding.BER); } - private SafeBag createSafeBag(String certId, Certificate cert) + private SafeBag createSafeBag(String certId, Certificate cert, boolean overwriteFriendlyName) throws CertificateEncodingException { CertBag cBag = new CertBag( @@ -1831,11 +1936,14 @@ private SafeBag createSafeBag(String certId, Certificate cert) // make sure we are using the local alias on store // ASN1BMPString nm = (ASN1BMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(certId)) + if (overwriteFriendlyName) { - if (certId != null) + if (nm == null || !nm.getString().equals(certId)) { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId)); + if (certId != null) + { + bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId)); + } } } @@ -1854,6 +1962,11 @@ private SafeBag createSafeBag(String certId, Certificate cert) continue; } + if (oid.equals(MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage)) + { + continue; + } + ASN1EncodableVector fSeq = new ASN1EncodableVector(); fSeq.add(oid); @@ -1878,36 +1991,21 @@ private SafeBag createSafeBag(String certId, Certificate cert) if (cert instanceof X509Certificate) { TBSCertificate tbsCert = TBSCertificate.getInstance(((X509Certificate)cert).getTBSCertificate()); - Extensions exts = tbsCert.getExtensions(); - if (exts != null) - { - Extension extUsage = exts.getExtension(Extension.extendedKeyUsage); - if (extUsage != null) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - // oracle trusted key usage OID. - fSeq.add(MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage); - fSeq.add(new DERSet(ExtendedKeyUsage.getInstance(extUsage.getParsedValue()).getUsages())); - fName.add(new DERSequence(fSeq)); - } - else - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); + ASN1OctetString eku = Extensions.getExtensionValue(tbsCert.getExtensions(), + Extension.extendedKeyUsage); - fSeq.add(MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage); - fSeq.add(new DERSet(KeyPurposeId.anyExtendedKeyUsage)); - fName.add(new DERSequence(fSeq)); - } + DERSet attrValue; + if (eku != null) + { + attrValue = new DERSet(ExtendedKeyUsage.getInstance(eku.getOctets()).getUsages()); } else { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage); - fSeq.add(new DERSet(KeyPurposeId.anyExtendedKeyUsage)); - fName.add(new DERSequence(fSeq)); + attrValue = new DERSet(KeyPurposeId.anyExtendedKeyUsage); } + + fName.add(new DERSequence(MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage, attrValue)); } return new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); @@ -1950,6 +2048,39 @@ private byte[] calculatePbeMac( byte[] data) throws Exception { + if (PKCSObjectIdentifiers.id_PBMAC1.equals(oid)) + { + PBMAC1Params pbmac1Params = PBMAC1Params.getInstance(macAlgorithm.getParameters()); + if (pbmac1Params == null) + { + throw new IOException("If the DigestAlgorithmIdentifier is id-PBMAC1, then the parameters field must contain valid PBMAC1-params parameters."); + } + if (PKCSObjectIdentifiers.id_PBKDF2.equals(pbmac1Params.getKeyDerivationFunc().getAlgorithm())) + { + PBKDF2Params pbkdf2Params = PBKDF2Params.getInstance(pbmac1Params.getKeyDerivationFunc().getParameters()); + if (pbkdf2Params.getKeyLength() == null) + { + throw new IOException("Key length must be present when using PBMAC1."); + } + final HMac hMac = new HMac(getPrf(pbmac1Params.getMessageAuthScheme().getAlgorithm())); + + PBEParametersGenerator generator = new PKCS5S2ParametersGenerator(getPrf(pbkdf2Params.getPrf().getAlgorithm())); + + generator.init( + Strings.toUTF8ByteArray(password), + pbkdf2Params.getSalt(), + BigIntegers.intValueExact(pbkdf2Params.getIterationCount())); + + CipherParameters key = generator.generateDerivedParameters(BigIntegers.intValueExact(pbkdf2Params.getKeyLength()) * 8); + + hMac.init(key); + hMac.update(data, 0, data.length); + byte[] res = new byte[hMac.getMacSize()]; + hMac.doFinal(res, 0); + return res; + } + } + PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); Mac mac = helper.createMac(oid.getId()); @@ -1959,6 +2090,22 @@ private byte[] calculatePbeMac( return mac.doFinal(); } + private static Digest getPrf(ASN1ObjectIdentifier prfId) + { + if (PKCSObjectIdentifiers.id_hmacWithSHA256.equals(prfId)) + { + return new SHA256Digest(); + } + else if (PKCSObjectIdentifiers.id_hmacWithSHA512.equals(prfId)) + { + return new SHA512Digest(); + } + else + { + throw new IllegalArgumentException("unknown prf id " + prfId); + } + } + public static class BCPKCS12KeyStore extends AdaptingKeyStoreSpi { @@ -2051,7 +2198,7 @@ public void put(String key, Object value) public Enumeration keys() { - return orig.keys(); + return new Hashtable(orig).keys(); } public Object remove(String alias) diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/AES.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/AES.java index 87facc5cdc..1f83faab72 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/AES.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/AES.java @@ -29,6 +29,7 @@ import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; import org.bouncycastle.crypto.macs.CMac; import org.bouncycastle.crypto.macs.GMac; +import org.bouncycastle.crypto.modes.AEADBlockCipher; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.modes.CCMBlockCipher; import org.bouncycastle.crypto.modes.CCMModeCipher; @@ -80,6 +81,51 @@ public BlockCipher get() } } + public static class ECB128 + extends BaseBlockCipher + { + public ECB128() + { + super(128, new BlockCipherProvider() + { + public BlockCipher get() + { + return AESEngine.newInstance(); + } + }); + } + } + + public static class ECB192 + extends BaseBlockCipher + { + public ECB192() + { + super(192, new BlockCipherProvider() + { + public BlockCipher get() + { + return AESEngine.newInstance(); + } + }); + } + } + + public static class ECB256 + extends BaseBlockCipher + { + public ECB256() + { + super(256, new BlockCipherProvider() + { + public BlockCipher get() + { + return AESEngine.newInstance(); + } + }); + } + } + public static class CBC extends BaseBlockCipher { @@ -89,6 +135,33 @@ public CBC() } } + public static class CBC128 + extends BaseBlockCipher + { + public CBC128() + { + super(128, CBCBlockCipher.newInstance(AESEngine.newInstance()), 128); + } + } + + public static class CBC192 + extends BaseBlockCipher + { + public CBC192() + { + super(192, CBCBlockCipher.newInstance(AESEngine.newInstance()), 128); + } + } + + public static class CBC256 + extends BaseBlockCipher + { + public CBC256() + { + super(192, CBCBlockCipher.newInstance(AESEngine.newInstance()), 128); + } + } + static public class CFB extends BaseBlockCipher { @@ -97,7 +170,34 @@ public CFB() super(new DefaultBufferedBlockCipher(CFBBlockCipher.newInstance(AESEngine.newInstance(), 128)), 128); } } - + + public static class CFB128 + extends BaseBlockCipher + { + public CFB128() + { + super(128, new DefaultBufferedBlockCipher(CFBBlockCipher.newInstance(AESEngine.newInstance(), 128)), 128); + } + } + + public static class CFB192 + extends BaseBlockCipher + { + public CFB192() + { + super(192, new DefaultBufferedBlockCipher(CFBBlockCipher.newInstance(AESEngine.newInstance(), 128)), 128); + } + } + + public static class CFB256 + extends BaseBlockCipher + { + public CFB256() + { + super(256, new DefaultBufferedBlockCipher(CFBBlockCipher.newInstance(AESEngine.newInstance(), 128)), 128); + } + } + static public class OFB extends BaseBlockCipher { @@ -106,7 +206,35 @@ public OFB() super(new DefaultBufferedBlockCipher(new OFBBlockCipher(AESEngine.newInstance(), 128)), 128); } } - + + public static class OFB128 + extends BaseBlockCipher + { + public OFB128() + { + super(128, new DefaultBufferedBlockCipher(new OFBBlockCipher(AESEngine.newInstance(), 128)), 128); + } + } + + public static class OFB192 + extends BaseBlockCipher + { + public OFB192() + { + super(192, new DefaultBufferedBlockCipher(new OFBBlockCipher(AESEngine.newInstance(), 128)), 128); + } + } + + public static class OFB256 + extends BaseBlockCipher + { + public OFB256() + { + super(256, new DefaultBufferedBlockCipher(new OFBBlockCipher(AESEngine.newInstance(), 128)), 128); + } + } + + static public class GCM extends BaseBlockCipher { @@ -116,6 +244,33 @@ public GCM() } } + static public class GCM128 + extends BaseBlockCipher + { + public GCM128() + { + super(128, (AEADBlockCipher)GCMBlockCipher.newInstance(AESEngine.newInstance())); + } + } + + static public class GCM192 + extends BaseBlockCipher + { + public GCM192() + { + super(192, (AEADBlockCipher)GCMBlockCipher.newInstance(AESEngine.newInstance())); + } + } + + static public class GCM256 + extends BaseBlockCipher + { + public GCM256() + { + super(256, (AEADBlockCipher)GCMBlockCipher.newInstance(AESEngine.newInstance())); + } + } + static public class CCM extends BaseBlockCipher { @@ -125,6 +280,33 @@ public CCM() } } + static public class CCM128 + extends BaseBlockCipher + { + public CCM128() + { + super(128, (AEADBlockCipher)CCMBlockCipher.newInstance(AESEngine.newInstance()), false, 12); + } + } + + static public class CCM192 + extends BaseBlockCipher + { + public CCM192() + { + super(192, (AEADBlockCipher)CCMBlockCipher.newInstance(AESEngine.newInstance()), false, 12); + } + } + + static public class CCM256 + extends BaseBlockCipher + { + public CCM256() + { + super(256, (AEADBlockCipher)CCMBlockCipher.newInstance(AESEngine.newInstance()), false, 12); + } + } + public static class AESCMAC extends BaseMac { @@ -143,68 +325,95 @@ public AESGMAC() } } - public static class AESCCMMAC - extends BaseMac + static class CCMMac + implements Mac { - public AESCCMMAC() + private final CCMModeCipher ccm = CCMBlockCipher.newInstance(AESEngine.newInstance()); + + private int macLength = 8; + + public void init(CipherParameters params) + throws IllegalArgumentException { - super(new CCMMac()); + ccm.init(true, params); + + this.macLength = ccm.getMac().length; } - private static class CCMMac - implements Mac + public String getAlgorithmName() { - private final CCMModeCipher ccm = CCMBlockCipher.newInstance(AESEngine.newInstance()); + return ccm.getAlgorithmName() + "Mac"; + } - private int macLength = 8; + public int getMacSize() + { + return macLength; + } - public void init(CipherParameters params) - throws IllegalArgumentException - { - ccm.init(true, params); + public void update(byte in) + throws IllegalStateException + { + ccm.processAADByte(in); + } - this.macLength = ccm.getMac().length; - } + public void update(byte[] in, int inOff, int len) + throws DataLengthException, IllegalStateException + { + ccm.processAADBytes(in, inOff, len); + } - public String getAlgorithmName() + public int doFinal(byte[] out, int outOff) + throws DataLengthException, IllegalStateException + { + try { - return ccm.getAlgorithmName() + "Mac"; + return ccm.doFinal(out, 0); } - - public int getMacSize() + catch (InvalidCipherTextException e) { - return macLength; + throw new IllegalStateException("exception on doFinal(): " + e.toString()); } + } - public void update(byte in) - throws IllegalStateException - { - ccm.processAADByte(in); - } + public void reset() + { + ccm.reset(); + } + } - public void update(byte[] in, int inOff, int len) - throws DataLengthException, IllegalStateException - { - ccm.processAADBytes(in, inOff, len); - } + public static class AESCCMMAC + extends BaseMac + { + public AESCCMMAC() + { + super(new CCMMac()); + } + } - public int doFinal(byte[] out, int outOff) - throws DataLengthException, IllegalStateException - { - try - { - return ccm.doFinal(out, 0); - } - catch (InvalidCipherTextException e) - { - throw new IllegalStateException("exception on doFinal(): " + e.toString()); - } - } + public static class AESCCMMAC128 + extends BaseMac + { + public AESCCMMAC128() + { + super(128, new CCMMac()); + } + } - public void reset() - { - ccm.reset(); - } + public static class AESCCMMAC192 + extends BaseMac + { + public AESCCMMAC192() + { + super(192, new CCMMac()); + } + } + + public static class AESCCMMAC256 + extends BaseMac + { + public AESCCMMAC256() + { + super(256, new CCMMac()); } } @@ -244,6 +453,33 @@ public Wrap() } } + static public class Wrap128 + extends BaseWrapCipher + { + public Wrap128() + { + super(new AESWrapEngine()); + } + } + + static public class Wrap192 + extends BaseWrapCipher + { + public Wrap192() + { + super(new AESWrapEngine()); + } + } + + static public class Wrap256 + extends BaseWrapCipher + { + public Wrap256() + { + super(new AESWrapEngine()); + } + } + public static class WrapPad extends BaseWrapCipher { @@ -253,6 +489,33 @@ public WrapPad() } } + public static class WrapPad128 + extends BaseWrapCipher + { + public WrapPad128() + { + super(new AESWrapPadEngine()); + } + } + + public static class WrapPad192 + extends BaseWrapCipher + { + public WrapPad192() + { + super(new AESWrapPadEngine()); + } + } + + public static class WrapPad256 + extends BaseWrapCipher + { + public WrapPad256() + { + super(new AESWrapPadEngine()); + } + } + public static class RFC3211Wrap extends BaseWrapCipher { @@ -838,31 +1101,31 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES256, "AES"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$ECB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$ECB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$ECB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$OFB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$OFB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$OFB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$CFB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$CFB"); - provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$CFB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$ECB128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$ECB192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$ECB256"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$CBC128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$CBC192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$CBC256"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$OFB128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$OFB192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$OFB256"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$CFB128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$CFB192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$CFB256"); provider.addAttributes("Cipher.AESWRAP", generalAesAttributes); provider.addAlgorithm("Cipher.AESWRAP", PREFIX + "$Wrap"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_wrap, "AESWRAP"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_wrap, "AESWRAP"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_wrap, "AESWRAP"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_wrap, PREFIX + "$Wrap128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_wrap, PREFIX + "$Wrap192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_wrap, PREFIX + "$Wrap256"); provider.addAlgorithm("Alg.Alias.Cipher.AESKW", "AESWRAP"); provider.addAttributes("Cipher.AESWRAPPAD", generalAesAttributes); provider.addAlgorithm("Cipher.AESWRAPPAD", PREFIX + "$WrapPad"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_wrap_pad, "AESWRAPPAD"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_wrap_pad, "AESWRAPPAD"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_wrap_pad, "AESWRAPPAD"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_wrap_pad, PREFIX + "$WrapPad128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_wrap_pad, PREFIX + "$WrapPad192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_wrap_pad, PREFIX + "$WrapPad256"); provider.addAlgorithm("Alg.Alias.Cipher.AESKWP", "AESWRAPPAD"); provider.addAlgorithm("Cipher.AESRFC3211WRAP", PREFIX + "$RFC3211Wrap"); @@ -875,9 +1138,9 @@ public void configure(ConfigurableProvider provider) provider.addAttributes("Cipher.CCM", generalAesAttributes); provider.addAlgorithm("Cipher.CCM", PREFIX + "$CCM"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_CCM, "CCM"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_CCM, "CCM"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_CCM, "CCM"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CCM, PREFIX + "$CCM128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CCM, PREFIX + "$CCM192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CCM, PREFIX + "$CCM256"); provider.addAlgorithm("AlgorithmParameterGenerator.GCM", PREFIX + "$AlgParamGenGCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); @@ -886,9 +1149,9 @@ public void configure(ConfigurableProvider provider) provider.addAttributes("Cipher.GCM", generalAesAttributes); provider.addAlgorithm("Cipher.GCM", PREFIX + "$GCM"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_GCM, "GCM"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_GCM, "GCM"); - provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_GCM, "GCM"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_GCM, PREFIX + "$GCM128"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_GCM, PREFIX + "$GCM192"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_GCM, PREFIX + "$GCM256"); provider.addAlgorithm("KeyGenerator.AES", PREFIX + "$KeyGen"); provider.addAlgorithm("KeyGenerator." + wrongAES128, PREFIX + "$KeyGen128"); @@ -924,9 +1187,9 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("Mac.AESCMAC", PREFIX + "$AESCMAC"); provider.addAlgorithm("Mac.AESCCMMAC", PREFIX + "$AESCCMMAC"); - provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes128_CCM.getId(), "AESCCMMAC"); - provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes192_CCM.getId(), "AESCCMMAC"); - provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes256_CCM.getId(), "AESCCMMAC"); + provider.addAlgorithm("Mac." + NISTObjectIdentifiers.id_aes128_CCM.getId(), PREFIX + "$AESCCMMAC128"); + provider.addAlgorithm("Mac." + NISTObjectIdentifiers.id_aes192_CCM.getId(), PREFIX + "$AESCCMMAC192"); + provider.addAlgorithm("Mac." + NISTObjectIdentifiers.id_aes256_CCM.getId(), PREFIX + "$AESCCMMAC256"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Camellia.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Camellia.java index 6d82f21a2c..d4bab38db6 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Camellia.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Camellia.java @@ -58,6 +58,33 @@ public CBC() } } + public static class CBC128 + extends BaseBlockCipher + { + public CBC128() + { + super(128, new CBCBlockCipher(new CamelliaEngine()), 128); + } + } + + public static class CBC192 + extends BaseBlockCipher + { + public CBC192() + { + super(192, new CBCBlockCipher(new CamelliaEngine()), 128); + } + } + + public static class CBC256 + extends BaseBlockCipher + { + public CBC256() + { + super(256, new CBCBlockCipher(new CamelliaEngine()), 128); + } + } + public static class Wrap extends BaseWrapCipher { @@ -67,6 +94,33 @@ public Wrap() } } + public static class Wrap128 + extends BaseWrapCipher + { + public Wrap128() + { + super(128, new CamelliaWrapEngine()); + } + } + + public static class Wrap192 + extends BaseWrapCipher + { + public Wrap192() + { + super(192, new CamelliaWrapEngine()); + } + } + + public static class Wrap256 + extends BaseWrapCipher + { + public Wrap256() + { + super(256, new CamelliaWrapEngine()); + } + } + public static class RFC3211Wrap extends BaseWrapCipher { @@ -223,15 +277,15 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator", NTTObjectIdentifiers.id_camellia256_cbc, "CAMELLIA"); provider.addAlgorithm("Cipher.CAMELLIA", PREFIX + "$ECB"); - provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia128_cbc, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia192_cbc, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia256_cbc, PREFIX + "$CBC"); + provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia128_cbc, PREFIX + "$CBC128"); + provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia192_cbc, PREFIX + "$CBC192"); + provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia256_cbc, PREFIX + "$CBC256"); provider.addAlgorithm("Cipher.CAMELLIARFC3211WRAP", PREFIX + "$RFC3211Wrap"); provider.addAlgorithm("Cipher.CAMELLIAWRAP", PREFIX + "$Wrap"); - provider.addAlgorithm("Alg.Alias.Cipher", NTTObjectIdentifiers.id_camellia128_wrap, "CAMELLIAWRAP"); - provider.addAlgorithm("Alg.Alias.Cipher", NTTObjectIdentifiers.id_camellia192_wrap, "CAMELLIAWRAP"); - provider.addAlgorithm("Alg.Alias.Cipher", NTTObjectIdentifiers.id_camellia256_wrap, "CAMELLIAWRAP"); + provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia128_wrap, PREFIX + "$Wrap128"); + provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia192_wrap, PREFIX + "$Wrap192"); + provider.addAlgorithm("Cipher", NTTObjectIdentifiers.id_camellia256_wrap, PREFIX + "$Wrap256"); provider.addAlgorithm("SecretKeyFactory.CAMELLIA", PREFIX + "$KeyFactory"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", NTTObjectIdentifiers.id_camellia128_cbc, "CAMELLIA"); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/SEED.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/SEED.java index d0ef6116c7..c1b6bf9d4b 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/SEED.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/SEED.java @@ -39,7 +39,7 @@ public static class ECB { public ECB() { - super(new BlockCipherProvider() + super(128, new BlockCipherProvider() { public BlockCipher get() { @@ -54,7 +54,7 @@ public static class CBC { public CBC() { - super(new CBCBlockCipher(new SEEDEngine()), 128); + super(128, new CBCBlockCipher(new SEEDEngine()), 128); } } @@ -63,7 +63,7 @@ public static class Wrap { public Wrap() { - super(new SEEDWrapEngine()); + super(128, new SEEDWrapEngine()); } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Serpent.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Serpent.java index 4d1351c71b..a493aba7b6 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Serpent.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/Serpent.java @@ -40,6 +40,51 @@ public BlockCipher get() } } + public static class ECB128 + extends BaseBlockCipher + { + public ECB128() + { + super(128, new BlockCipherProvider() + { + public BlockCipher get() + { + return new SerpentEngine(); + } + }); + } + } + + public static class ECB192 + extends BaseBlockCipher + { + public ECB192() + { + super(192, new BlockCipherProvider() + { + public BlockCipher get() + { + return new SerpentEngine(); + } + }); + } + } + + public static class ECB256 + extends BaseBlockCipher + { + public ECB256() + { + super(256, new BlockCipherProvider() + { + public BlockCipher get() + { + return new SerpentEngine(); + } + }); + } + } + public static class TECB extends BaseBlockCipher { @@ -64,6 +109,33 @@ public CBC() } } + public static class CBC128 + extends BaseBlockCipher + { + public CBC128() + { + super(128, new CBCBlockCipher(new SerpentEngine()), 128); + } + } + + public static class CBC192 + extends BaseBlockCipher + { + public CBC192() + { + super(192, new CBCBlockCipher(new SerpentEngine()), 128); + } + } + + public static class CBC256 + extends BaseBlockCipher + { + public CBC256() + { + super(256, new CBCBlockCipher(new SerpentEngine()), 128); + } + } + public static class CFB extends BaseBlockCipher { @@ -73,6 +145,33 @@ public CFB() } } + public static class CFB128 + extends BaseBlockCipher + { + public CFB128() + { + super(128, new BufferedBlockCipher(new CFBBlockCipher(new SerpentEngine(), 128)), 128); + } + } + + public static class CFB192 + extends BaseBlockCipher + { + public CFB192() + { + super(192, new BufferedBlockCipher(new CFBBlockCipher(new SerpentEngine(), 128)), 128); + } + } + + public static class CFB256 + extends BaseBlockCipher + { + public CFB256() + { + super(256, new BufferedBlockCipher(new CFBBlockCipher(new SerpentEngine(), 128)), 128); + } + } + public static class OFB extends BaseBlockCipher { @@ -82,6 +181,33 @@ public OFB() } } + public static class OFB128 + extends BaseBlockCipher + { + public OFB128() + { + super(128, new BufferedBlockCipher(new OFBBlockCipher(new SerpentEngine(), 128)), 128); + } + } + + public static class OFB192 + extends BaseBlockCipher + { + public OFB192() + { + super(192, new BufferedBlockCipher(new OFBBlockCipher(new SerpentEngine(), 128)), 128); + } + } + + public static class OFB256 + extends BaseBlockCipher + { + public OFB256() + { + super(256, new BufferedBlockCipher(new OFBBlockCipher(new SerpentEngine(), 128)), 128); + } + } + public static class KeyGen extends BaseKeyGenerator { @@ -174,21 +300,21 @@ public void configure(ConfigurableProvider provider) provider.addAlgorithm("KeyGenerator.Tnepres", PREFIX + "$TKeyGen"); provider.addAlgorithm("AlgorithmParameters.Tnepres", PREFIX + "$TAlgParams"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_ECB, PREFIX + "$ECB"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_ECB, PREFIX + "$ECB"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_ECB, PREFIX + "$ECB"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_ECB, PREFIX + "$ECB128"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_ECB, PREFIX + "$ECB192"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_ECB, PREFIX + "$ECB256"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_CBC, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_CBC, PREFIX + "$CBC"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_CBC, PREFIX + "$CBC"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_CBC, PREFIX + "$CBC128"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_CBC, PREFIX + "$CBC192"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_CBC, PREFIX + "$CBC256"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_CFB, PREFIX + "$CFB"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_CFB, PREFIX + "$CFB"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_CFB, PREFIX + "$CFB"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_CFB, PREFIX + "$CFB128"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_CFB, PREFIX + "$CFB192"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_CFB, PREFIX + "$CFB256"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_OFB, PREFIX + "$OFB"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_OFB, PREFIX + "$OFB"); - provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_OFB, PREFIX + "$OFB"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_128_OFB, PREFIX + "$OFB128"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_192_OFB, PREFIX + "$OFB192"); + provider.addAlgorithm("Cipher", GNUObjectIdentifiers.Serpent_256_OFB, PREFIX + "$OFB256"); addGMacAlgorithm(provider, "SERPENT", PREFIX + "$SerpentGMAC", PREFIX + "$KeyGen"); addGMacAlgorithm(provider, "TNEPRES", PREFIX + "$TSerpentGMAC", PREFIX + "$TKeyGen"); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java index b7dbc2f203..a026b2188f 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java @@ -75,6 +75,8 @@ import org.bouncycastle.internal.asn1.cms.GCMParameters; import org.bouncycastle.jcajce.PBKDF1Key; import org.bouncycastle.jcajce.PBKDF1KeyWithParameters; +import org.bouncycastle.jcajce.PBKDF2Key; +import org.bouncycastle.jcajce.PBKDF2KeyWithParameters; import org.bouncycastle.jcajce.PKCS12Key; import org.bouncycastle.jcajce.PKCS12KeyWithParameters; import org.bouncycastle.jcajce.spec.AEADParameterSpec; @@ -156,9 +158,28 @@ protected BaseBlockCipher( cipher = new BufferedGenericBlockCipher(provider.get()); } + protected BaseBlockCipher( + int keySizeInBits, + BlockCipherProvider provider) + { + baseEngine = provider.get(); + engineProvider = provider; + this.keySizeInBits = keySizeInBits; + + cipher = new BufferedGenericBlockCipher(provider.get()); + } + protected BaseBlockCipher( AEADBlockCipher engine) { + this(0, engine); + } + + protected BaseBlockCipher( + int keySizeInBits, + AEADBlockCipher engine) + { + this.keySizeInBits = keySizeInBits; this.baseEngine = engine.getUnderlyingCipher(); if (engine.getAlgorithmName().indexOf("GCM") >= 0) { @@ -187,6 +208,16 @@ protected BaseBlockCipher( boolean fixedIv, int ivLength) { + this(0, engine, fixedIv, ivLength); + } + + protected BaseBlockCipher( + int keySizeInBits, + AEADBlockCipher engine, + boolean fixedIv, + int ivLength) + { + this.keySizeInBits = keySizeInBits; this.baseEngine = engine.getUnderlyingCipher(); this.fixedIv = fixedIv; this.ivLength = ivLength; @@ -200,6 +231,19 @@ protected BaseBlockCipher( this(engine, true, ivLength); } + protected BaseBlockCipher( + int keySizeInBits, + org.bouncycastle.crypto.BlockCipher engine, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + baseEngine = engine; + + this.fixedIv = true; + this.cipher = new BufferedGenericBlockCipher(engine); + this.ivLength = ivLength / 8; + } + protected BaseBlockCipher( org.bouncycastle.crypto.BlockCipher engine, boolean fixedIv, @@ -219,6 +263,19 @@ protected BaseBlockCipher( this(engine, true, ivLength); } + protected BaseBlockCipher( + int keySizeInBits, + BufferedBlockCipher engine, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + baseEngine = engine.getUnderlyingCipher(); + + this.cipher = new BufferedGenericBlockCipher(engine); + this.fixedIv = true; + this.ivLength = ivLength / 8; + } + protected BaseBlockCipher( BufferedBlockCipher engine, boolean fixedIv, @@ -391,7 +448,7 @@ else if (modeName.startsWith("PGPCFB")) { throw new NoSuchAlgorithmException("no mode support for " + modeName); } - + ivLength = baseEngine.getBlockSize(); cipher = new BufferedGenericBlockCipher( new PGPCFBBlockCipher(baseEngine, inlineIV)); @@ -577,7 +634,7 @@ else if (paddingName.equals("TBCPADDING")) protected void engineInit( int opmode, Key key, - final AlgorithmParameterSpec params, + final AlgorithmParameterSpec paramSpec, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { @@ -599,7 +656,7 @@ protected void engineInit( // // for RC5-64 we must have some default parameters // - if (params == null && (baseEngine != null && baseEngine.getAlgorithmName().startsWith("RC5-64"))) + if (paramSpec == null && (baseEngine != null && baseEngine.getAlgorithmName().startsWith("RC5-64"))) { throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in."); } @@ -619,9 +676,9 @@ protected void engineInit( throw new InvalidKeyException("PKCS12 requires a SecretKey/PBEKey"); } - if (params instanceof PBEParameterSpec) + if (paramSpec instanceof PBEParameterSpec) { - pbeSpec = (PBEParameterSpec)params; + pbeSpec = (PBEParameterSpec)paramSpec; } if (k instanceof PBEKey && pbeSpec == null) @@ -670,9 +727,9 @@ else if (key instanceof PBKDF1Key) { PBKDF1Key k = (PBKDF1Key)key; - if (params instanceof PBEParameterSpec) + if (paramSpec instanceof PBEParameterSpec) { - pbeSpec = (PBEParameterSpec)params; + pbeSpec = (PBEParameterSpec)paramSpec; } if (k instanceof PBKDF1KeyWithParameters && pbeSpec == null) { @@ -685,6 +742,25 @@ else if (key instanceof PBKDF1Key) ivParam = (ParametersWithIV)param; } } + else if (key instanceof PBKDF2Key) + { + PBKDF2Key k = (PBKDF2Key)key; + + if (paramSpec instanceof PBEParameterSpec) + { + pbeSpec = (PBEParameterSpec)paramSpec; + } + if (k instanceof PBKDF2KeyWithParameters && pbeSpec == null) + { + pbeSpec = new PBEParameterSpec(((PBKDF2KeyWithParameters)k).getSalt(), ((PBKDF2KeyWithParameters)k).getIterationCount()); + } + + param = PBE.Util.makePBEParameters(k.getEncoded(), PKCS5S2, PBE.SHA512, keySizeInBits, 0, pbeSpec, cipher.getAlgorithmName()); + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } else if (key instanceof BCPBEKey) { BCPBEKey k = (BCPBEKey)key; @@ -700,12 +776,12 @@ else if (key instanceof BCPBEKey) if (k.getParam() != null) { - param = adjustParameters(params, k.getParam()); + param = adjustParameters(paramSpec, k.getParam()); } - else if (params instanceof PBEParameterSpec) + else if (paramSpec instanceof PBEParameterSpec) { - pbeSpec = (PBEParameterSpec)params; - param = PBE.Util.makePBEParameters(k, params, cipher.getUnderlyingCipher().getAlgorithmName()); + pbeSpec = (PBEParameterSpec)paramSpec; + param = PBE.Util.makePBEParameters(k, paramSpec, cipher.getUnderlyingCipher().getAlgorithmName()); } else { @@ -720,7 +796,7 @@ else if (params instanceof PBEParameterSpec) else if (key instanceof PBEKey) { PBEKey k = (PBEKey)key; - pbeSpec = (PBEParameterSpec)params; + pbeSpec = (PBEParameterSpec)paramSpec; if (k instanceof PKCS12KeyWithParameters && pbeSpec == null) { pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount()); @@ -745,6 +821,18 @@ else if (!(key instanceof RepeatedSecretKeySpec)) param = null; } + AlgorithmParameterSpec params = paramSpec; + if (paramSpec instanceof PBEParameterSpec) + { + params = ((PBEParameterSpec)paramSpec).getParameterSpec(); + // If params.getIv() returns an empty byte array, ivParam will be assigned an IV generated by PBE.Util.makePBEParameters + // according to RFC 7292. This behavior is intended for Jasypt users who choose to use NoIvGenerator. + if (params instanceof IvParameterSpec && ((IvParameterSpec)params).getIV().length == 0) + { + params = paramSpec; + } + } + if (params instanceof AEADParameterSpec) { if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseMac.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseMac.java index 8918d0d0a5..f650eaa29b 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseMac.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseMac.java @@ -42,6 +42,14 @@ protected BaseMac( this.macEngine = macEngine; } + protected BaseMac( + int keySize, + Mac macEngine) + { + this.keySize = keySize; + this.macEngine = macEngine; + } + protected BaseMac( Mac macEngine, int scheme, diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseWrapCipher.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseWrapCipher.java index 080566fd16..6297f667da 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseWrapCipher.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseWrapCipher.java @@ -87,9 +87,26 @@ protected BaseWrapCipher( } protected BaseWrapCipher( + int keySizeInBits, + Wrapper wrapEngine) + { + this(keySizeInBits, wrapEngine, 0); + } + + protected BaseWrapCipher( + Wrapper wrapEngine, + int ivSize) + { + this.wrapEngine = wrapEngine; + this.ivSize = ivSize; + } + + protected BaseWrapCipher( + int keySizeInBits, Wrapper wrapEngine, int ivSize) { + this.pbeKeySize = keySizeInBits; this.wrapEngine = wrapEngine; this.ivSize = ivSize; } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/util/AsymmetricAlgorithmProvider.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/util/AsymmetricAlgorithmProvider.java index 4d912ac871..88810d9acc 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/util/AsymmetricAlgorithmProvider.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/util/AsymmetricAlgorithmProvider.java @@ -15,8 +15,11 @@ protected void addSignatureAlgorithm( ASN1ObjectIdentifier oid) { provider.addAlgorithm("Signature." + algorithm, className); - provider.addAlgorithm("Alg.Alias.Signature." + oid, algorithm); - provider.addAlgorithm("Alg.Alias.Signature.OID." + oid, algorithm); + if (oid != null) + { + provider.addAlgorithm("Alg.Alias.Signature." + oid, algorithm); + provider.addAlgorithm("Alg.Alias.Signature.OID." + oid, algorithm); + } } protected void addSignatureAlias( diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/util/SecretKeyUtil.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/util/SecretKeyUtil.java index 686d6b8461..42c601a4bb 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/util/SecretKeyUtil.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/util/SecretKeyUtil.java @@ -9,13 +9,16 @@ import org.bouncycastle.internal.asn1.ntt.NTTObjectIdentifiers; import org.bouncycastle.util.Integers; +/** + * @deprecated class appears to be no longer in use, maybe getting imported by others though. + */ public class SecretKeyUtil { - private static Map keySizes = new HashMap(); + private static Map keySizes = new HashMap(); static { - keySizes.put(PKCSObjectIdentifiers.des_EDE3_CBC.getId(), Integers.valueOf(192)); + keySizes.put(PKCSObjectIdentifiers.des_EDE3_CBC, Integers.valueOf(192)); keySizes.put(NISTObjectIdentifiers.id_aes128_CBC, Integers.valueOf(128)); keySizes.put(NISTObjectIdentifiers.id_aes192_CBC, Integers.valueOf(192)); diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/ContextParameterSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/ContextParameterSpec.java new file mode 100644 index 0000000000..a8d0a750b3 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/ContextParameterSpec.java @@ -0,0 +1,23 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.AlgorithmParameterSpec; + +import org.bouncycastle.util.Arrays; + +public class ContextParameterSpec + implements AlgorithmParameterSpec +{ + public static ContextParameterSpec EMPTY_CONTEXT_SPEC = new ContextParameterSpec(new byte[0]); + + private final byte[] context; + + public ContextParameterSpec(byte[] context) + { + this.context = Arrays.clone(context); + } + + public byte[] getContext() + { + return Arrays.clone(context); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMExtractSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMExtractSpec.java index 6ece51ef28..309dc10074 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMExtractSpec.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMExtractSpec.java @@ -3,15 +3,109 @@ import java.security.PrivateKey; import java.security.spec.AlgorithmParameterSpec; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.util.Arrays; public class KEMExtractSpec + extends KEMKDFSpec implements AlgorithmParameterSpec { + private static final byte[] EMPTY_OTHER_INFO = new byte[0]; + private static AlgorithmIdentifier DefKdf = new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)); + + /** + * Builder class for creating a KEMExtractSpec. + */ + public static final class Builder + { + private final PrivateKey privateKey; + private final byte[] encapsulation; + private final String algorithmName; + private final int keySizeInBits; + + private AlgorithmIdentifier kdfAlgorithm; + private byte[] otherInfo; + + /** + * Basic builder. + * + * @param privateKey the private key to use for the secret extraction. + * @param encapsulation the encapsulation to process. + * @param keyAlgorithmName the algorithm name for the secret key we want to generate. + * @param keySizeInBits the size of the wrapping key we want to produce in bits. + */ + public Builder(PrivateKey privateKey, byte[] encapsulation, String keyAlgorithmName, int keySizeInBits) + { + this.privateKey = privateKey; + this.encapsulation = Arrays.clone(encapsulation); + this.algorithmName = keyAlgorithmName; + this.keySizeInBits = keySizeInBits; + this.kdfAlgorithm = new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)); + this.otherInfo = EMPTY_OTHER_INFO; + } + + /** + * Use the shared secret directly for key wrap generation. + * + * @return the current Builder instance. + */ + public Builder withNoKdf() + { + this.kdfAlgorithm = null; + + return this; + } + + /** + * Set the KDF algorithm and digest algorithm for wrap key generation. The default KDF is X9.44 KDF-3, also + * known as the NIST concatenation KDF. + * + * @param kdfAlgorithm the KDF algorithm to apply. + * @return the current Builder instance. + */ + public Builder withKdfAlgorithm(AlgorithmIdentifier kdfAlgorithm) + { + this.kdfAlgorithm = kdfAlgorithm; + + return this; + } + + /** + * Set the OtherInfo to use with the KDF. The default OtherInfo is a zero length byte[]. + * + * @param otherInfo the other info to use. + * @return the current Builder instance. + */ + public Builder withOtherInfo(byte[] otherInfo) + { + this.otherInfo = (otherInfo == null) ? EMPTY_OTHER_INFO : Arrays.clone(otherInfo); + + return this; + } + + /** + * Build the new parameter spec. + * + * @return a new parameter spec configured according to the builder state. + */ + public KEMExtractSpec build() + { + return new KEMExtractSpec(privateKey, encapsulation, algorithmName, keySizeInBits, kdfAlgorithm, otherInfo); + } + } + private final PrivateKey privateKey; private final byte[] encapsulation; - private final String keyAlgorithmName; - private final int keySizeInBits; + + private KEMExtractSpec(PrivateKey privateKey, byte[] encapsulation, String keyAlgorithmName, int keySizeInBits, AlgorithmIdentifier kdfAlgorithm, byte[] otherInfo) + { + super(kdfAlgorithm, otherInfo, keyAlgorithmName, keySizeInBits); + + this.privateKey = privateKey; + this.encapsulation = Arrays.clone(encapsulation); + } public KEMExtractSpec(PrivateKey privateKey, byte[] encapsulation, String keyAlgorithmName) { @@ -20,10 +114,7 @@ public KEMExtractSpec(PrivateKey privateKey, byte[] encapsulation, String keyAlg public KEMExtractSpec(PrivateKey privateKey, byte[] encapsulation, String keyAlgorithmName, int keySizeInBits) { - this.privateKey = privateKey; - this.encapsulation = Arrays.clone(encapsulation); - this.keyAlgorithmName = keyAlgorithmName; - this.keySizeInBits = keySizeInBits; + this(privateKey, encapsulation, keyAlgorithmName, keySizeInBits, DefKdf, EMPTY_OTHER_INFO); } public byte[] getEncapsulation() @@ -35,14 +126,4 @@ public PrivateKey getPrivateKey() { return privateKey; } - - public String getKeyAlgorithmName() - { - return keyAlgorithmName; - } - - public int getKeySize() - { - return keySizeInBits; - } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMGenerateSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMGenerateSpec.java index a5ea3f0e54..dcbf231412 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMGenerateSpec.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMGenerateSpec.java @@ -3,37 +3,117 @@ import java.security.PublicKey; import java.security.spec.AlgorithmParameterSpec; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.util.Arrays; + public class KEMGenerateSpec + extends KEMKDFSpec implements AlgorithmParameterSpec { - private final PublicKey publicKey; - private final String keyAlgorithmName; - private final int keySizeInBits; + private static final byte[] EMPTY_OTHER_INFO = new byte[0]; + private static AlgorithmIdentifier DefKdf = new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)); - public KEMGenerateSpec(PublicKey publicKey, String keyAlgorithmName) + /** + * Builder class for creating a KEMGenerateSpec. + */ + public static final class Builder { - this(publicKey, keyAlgorithmName, 256); + private final PublicKey publicKey; + private final String algorithmName; + private final int keySizeInBits; + + private AlgorithmIdentifier kdfAlgorithm; + private byte[] otherInfo; + + /** + * Basic builder. + * + * @param publicKey the public key to use for encapsulation/secret generation. + * @param keyAlgorithmName the algorithm name for the secret key we want to generate. + * @param keySizeInBits the size of the wrapping key we want to produce in bits. + */ + public Builder(PublicKey publicKey, String keyAlgorithmName, int keySizeInBits) + { + this.publicKey = publicKey; + this.algorithmName = keyAlgorithmName; + this.keySizeInBits = keySizeInBits; + this.kdfAlgorithm = new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)); + this.otherInfo = EMPTY_OTHER_INFO; + } + + /** + * Use the shared secret directly for key wrap generation. + * + * @return the current Builder instance. + */ + public Builder withNoKdf() + { + this.kdfAlgorithm = null; + + return this; + } + + /** + * Set the KDF algorithm and digest algorithm for wrap key generation. The default KDF is X9.44 KDF-3, also + * known as the NIST concatenation KDF. + * + * @param kdfAlgorithm the KDF algorithm to apply. + * @return the current Builder instance. + */ + public Builder withKdfAlgorithm(AlgorithmIdentifier kdfAlgorithm) + { + this.kdfAlgorithm = kdfAlgorithm; + + return this; + } + + /** + * Set the OtherInfo to use with the KDF. The default OtherInfo is a zero length byte[]. + * + * @param otherInfo the other info to use. + * @return the current Builder instance. + */ + public Builder withOtherInfo(byte[] otherInfo) + { + this.otherInfo = (otherInfo == null) ? EMPTY_OTHER_INFO : Arrays.clone(otherInfo); + + return this; + } + + /** + * Build the new parameter spec. + * + * @return a new parameter spec configured according to the builder state. + */ + public KEMGenerateSpec build() + { + return new KEMGenerateSpec(publicKey, algorithmName, keySizeInBits, kdfAlgorithm, otherInfo); + } } - public KEMGenerateSpec(PublicKey publicKey, String keyAlgorithmName, int keySizeInBits) + private final PublicKey publicKey; + + private KEMGenerateSpec(PublicKey publicKey, String keyAlgorithmName, int keySizeInBits, AlgorithmIdentifier kdfAlgorithm, byte[] otherInfo) { + super(kdfAlgorithm, otherInfo, keyAlgorithmName, keySizeInBits); + this.publicKey = publicKey; - this.keyAlgorithmName = keyAlgorithmName; - this.keySizeInBits = keySizeInBits; } - public PublicKey getPublicKey() + public KEMGenerateSpec(PublicKey publicKey, String keyAlgorithmName) { - return publicKey; + this(publicKey, keyAlgorithmName, 256, DefKdf, EMPTY_OTHER_INFO); } - public String getKeyAlgorithmName() + public KEMGenerateSpec(PublicKey publicKey, String keyAlgorithmName, int keySizeInBits) { - return keyAlgorithmName; + this(publicKey, keyAlgorithmName, keySizeInBits, DefKdf, EMPTY_OTHER_INFO); } - public int getKeySize() + public PublicKey getPublicKey() { - return keySizeInBits; + return publicKey; } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMKDFSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMKDFSpec.java new file mode 100644 index 0000000000..df6936df85 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/KEMKDFSpec.java @@ -0,0 +1,40 @@ +package org.bouncycastle.jcajce.spec; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.util.Arrays; + +public class KEMKDFSpec +{ + private final String keyAlgorithmName; + private final int keySizeInBits; + private final AlgorithmIdentifier kdfAlgorithm; + private final byte[] otherInfo; + + protected KEMKDFSpec(AlgorithmIdentifier kdfAlgorithm, byte[] otherInfo, String keyAlgorithmName, int keySizeInBits) + { + this.keyAlgorithmName = keyAlgorithmName; + this.keySizeInBits = keySizeInBits; + this.kdfAlgorithm = kdfAlgorithm; + this.otherInfo = otherInfo; + } + + public String getKeyAlgorithmName() + { + return keyAlgorithmName; + } + + public int getKeySize() + { + return keySizeInBits; + } + + public AlgorithmIdentifier getKdfAlgorithm() + { + return kdfAlgorithm; + } + + public byte[] getOtherInfo() + { + return Arrays.clone(otherInfo); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/KTSParameterSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/KTSParameterSpec.java index 4e3fbd73fa..f51b6e90b0 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/spec/KTSParameterSpec.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/KTSParameterSpec.java @@ -11,13 +11,10 @@ * Parameter spec for doing KTS based wrapping via the Cipher API. */ public class KTSParameterSpec + extends KEMKDFSpec implements AlgorithmParameterSpec { - private final String wrappingKeyAlgorithm; - private final int keySizeInBits; private final AlgorithmParameterSpec parameterSpec; - private final AlgorithmIdentifier kdfAlgorithm; - private byte[] otherInfo; /** * Builder class for creating a KTSParameterSpec. @@ -91,6 +88,11 @@ public Builder withNoKdf() */ public Builder withKdfAlgorithm(AlgorithmIdentifier kdfAlgorithm) { + if (kdfAlgorithm == null) + { + throw new NullPointerException("kdfAlgorithm cannot be null"); + } + this.kdfAlgorithm = kdfAlgorithm; return this; @@ -111,31 +113,9 @@ protected KTSParameterSpec( String wrappingKeyAlgorithm, int keySizeInBits, AlgorithmParameterSpec parameterSpec, AlgorithmIdentifier kdfAlgorithm, byte[] otherInfo) { - this.wrappingKeyAlgorithm = wrappingKeyAlgorithm; - this.keySizeInBits = keySizeInBits; - this.parameterSpec = parameterSpec; - this.kdfAlgorithm = kdfAlgorithm; - this.otherInfo = otherInfo; - } + super(kdfAlgorithm, otherInfo, wrappingKeyAlgorithm, keySizeInBits); - /** - * Return the name of the algorithm for the wrapping key this key spec should use. - * - * @return the key algorithm. - */ - public String getKeyAlgorithmName() - { - return wrappingKeyAlgorithm; - } - - /** - * Return the size of the key (in bits) for the wrapping key this key spec should use. - * - * @return length in bits of the key to be calculated. - */ - public int getKeySize() - { - return keySizeInBits; + this.parameterSpec = parameterSpec; } /** @@ -147,24 +127,4 @@ public AlgorithmParameterSpec getParameterSpec() { return parameterSpec; } - - /** - * Return the AlgorithmIdentifier for the KDF to do key derivation after extracting the secret. - * - * @return the AlgorithmIdentifier for the SecretKeyFactory's KDF. - */ - public AlgorithmIdentifier getKdfAlgorithm() - { - return kdfAlgorithm; - } - - /** - * Return the otherInfo data for initialising the KDF. - * - * @return the otherInfo data. - */ - public byte[] getOtherInfo() - { - return Arrays.clone(otherInfo); - } } diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAParameterSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAParameterSpec.java new file mode 100644 index 0000000000..0f77ed0dff --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAParameterSpec.java @@ -0,0 +1,63 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.util.Strings; + +/** + * AlgorithmSpec for ML-DSA + */ +public class MLDSAParameterSpec + implements AlgorithmParameterSpec +{ + public static final MLDSAParameterSpec ml_dsa_44 = new MLDSAParameterSpec("ML-DSA-44"); + public static final MLDSAParameterSpec ml_dsa_65 = new MLDSAParameterSpec("ML-DSA-65"); + public static final MLDSAParameterSpec ml_dsa_87 = new MLDSAParameterSpec("ML-DSA-87"); + + public static final MLDSAParameterSpec ml_dsa_44_with_sha512 = new MLDSAParameterSpec("ML-DSA-44-WITH-SHA512"); + public static final MLDSAParameterSpec ml_dsa_65_with_sha512 = new MLDSAParameterSpec("ML-DSA-65-WITH-SHA512"); + public static final MLDSAParameterSpec ml_dsa_87_with_sha512 = new MLDSAParameterSpec("ML-DSA-87-WITH-SHA512"); + + private static Map parameters = new HashMap(); + + static + { + parameters.put("ml-dsa-44", MLDSAParameterSpec.ml_dsa_44); + parameters.put("ml-dsa-65", MLDSAParameterSpec.ml_dsa_65); + parameters.put("ml-dsa-87", MLDSAParameterSpec.ml_dsa_87); + parameters.put("ml-dsa-44-with-sha512", MLDSAParameterSpec.ml_dsa_44_with_sha512); + parameters.put("ml-dsa-65-with-sha512", MLDSAParameterSpec.ml_dsa_65_with_sha512); + parameters.put("ml-dsa-87-with-sha512", MLDSAParameterSpec.ml_dsa_87_with_sha512); + } + + private final String name; + + private MLDSAParameterSpec(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public static MLDSAParameterSpec fromName(String name) + { + if (name == null) + { + throw new NullPointerException("name cannot be null"); + } + + MLDSAParameterSpec parameterSpec = (MLDSAParameterSpec)parameters.get(Strings.toLowerCase(name)); + + if (parameterSpec == null) + { + throw new IllegalArgumentException("unknown parameter name: " + name); + } + + return parameterSpec; + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAPrivateKeySpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAPrivateKeySpec.java new file mode 100644 index 0000000000..3c1ab04e8c --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAPrivateKeySpec.java @@ -0,0 +1,85 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.KeySpec; + +import org.bouncycastle.util.Arrays; + +/** + * PrivateKeySpec for ML-DSA. + */ +public class MLDSAPrivateKeySpec + implements KeySpec +{ + private final byte[] data; + private final byte[] publicData; + private final MLDSAParameterSpec params; + private final boolean isSeed; + + public MLDSAPrivateKeySpec(MLDSAParameterSpec params, byte[] seed) + { + if (seed.length != 32) + { + throw new IllegalArgumentException("incorrect length for seed"); + } + + this.isSeed = true; + this.params = params; + this.data = Arrays.clone(seed); + this.publicData = null; + } + + /** + * Create a KeySpec using the long form private and public data. + * + * @param params the parameter set to use with the encodings. + * @param privateData the long form private key. + * @param publicData the long form public key - may be null. + */ + public MLDSAPrivateKeySpec(MLDSAParameterSpec params, byte[] privateData, byte[] publicData) + { + this.isSeed = false; + this.params = params; + this.data = Arrays.clone(privateData); + this.publicData = Arrays.clone(publicData); + } + + public boolean isSeed() + { + return isSeed; + } + + public MLDSAParameterSpec getParameterSpec() + { + return params; + } + + public byte[] getSeed() + { + if (isSeed()) + { + return Arrays.clone(data); + } + + throw new IllegalStateException("KeySpec represents long form"); + } + + public byte[] getPrivateData() + { + if (!isSeed()) + { + return Arrays.clone(data); + } + + throw new IllegalStateException("KeySpec represents seed"); + } + + public byte[] getPublicData() + { + if (!isSeed()) + { + return Arrays.clone(publicData); + } + + throw new IllegalStateException("KeySpec represents long form"); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAPublicKeySpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAPublicKeySpec.java new file mode 100644 index 0000000000..8ead8f13a4 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLDSAPublicKeySpec.java @@ -0,0 +1,37 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.KeySpec; + +import org.bouncycastle.util.Arrays; + +/** + * PublicKeySpec for ML-DSA. + */ +public class MLDSAPublicKeySpec + implements KeySpec +{ + private final MLDSAParameterSpec params; + private final byte[] publicData; + + /** + * Base constructor. + * + * @param params the parameters to use with the passed in encoding. + * @param publicData the long form encoding of the public key. + */ + public MLDSAPublicKeySpec(MLDSAParameterSpec params, byte[] publicData) + { + this.params = params; + this.publicData = Arrays.clone(publicData); + } + + public MLDSAParameterSpec getParameterSpec() + { + return params; + } + + public byte[] getPublicData() + { + return Arrays.clone(publicData); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMParameterSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMParameterSpec.java new file mode 100644 index 0000000000..ce5043a4fa --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMParameterSpec.java @@ -0,0 +1,60 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.util.Strings; + +/** + * AlgorithmSpec for ML-KEM + */ +public class MLKEMParameterSpec + implements AlgorithmParameterSpec +{ + public static final MLKEMParameterSpec ml_kem_512 = new MLKEMParameterSpec("ML-KEM-512"); + public static final MLKEMParameterSpec ml_kem_768 = new MLKEMParameterSpec("ML-KEM-768"); + public static final MLKEMParameterSpec ml_kem_1024 = new MLKEMParameterSpec("ML-KEM-1024"); + + private static Map parameters = new HashMap(); + + static + { + parameters.put("ml-kem-512", MLKEMParameterSpec.ml_kem_512); + parameters.put("ml-kem-768", MLKEMParameterSpec.ml_kem_768); + parameters.put("ml-kem-1024", MLKEMParameterSpec.ml_kem_1024); + + parameters.put("kyber512", MLKEMParameterSpec.ml_kem_512); + parameters.put("kyber768", MLKEMParameterSpec.ml_kem_768); + parameters.put("kyber1024", MLKEMParameterSpec.ml_kem_1024); + } + + private final String name; + + private MLKEMParameterSpec(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public static MLKEMParameterSpec fromName(String name) + { + if (name == null) + { + throw new NullPointerException("name cannot be null"); + } + + MLKEMParameterSpec parameterSpec = (MLKEMParameterSpec)parameters.get(Strings.toLowerCase(name)); + + if (parameterSpec == null) + { + throw new IllegalArgumentException("unknown parameter name: " + name); + } + + return parameterSpec; + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMPrivateKeySpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMPrivateKeySpec.java new file mode 100644 index 0000000000..33ed26468b --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMPrivateKeySpec.java @@ -0,0 +1,85 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.KeySpec; + +import org.bouncycastle.util.Arrays; + +/** + * PrivateKeySpec for ML-DSA. + */ +public class MLKEMPrivateKeySpec + implements KeySpec +{ + private final byte[] data; + private final byte[] publicData; + private final MLKEMParameterSpec params; + private final boolean isSeed; + + public MLKEMPrivateKeySpec(MLKEMParameterSpec params, byte[] seed) + { + if (seed.length != 64) + { + throw new IllegalArgumentException("incorrect length for seed"); + } + + this.isSeed = true; + this.params = params; + this.data = Arrays.clone(seed); + this.publicData = null; + } + + /** + * Create a KeySpec using the long form private and public data. + * + * @param params the parameter set to use with the encodings. + * @param privateData the long form private key. + * @param publicData the long form public key - may be null. + */ + public MLKEMPrivateKeySpec(MLKEMParameterSpec params, byte[] privateData, byte[] publicData) + { + this.isSeed = false; + this.params = params; + this.data = Arrays.clone(privateData); + this.publicData = Arrays.clone(publicData); + } + + public boolean isSeed() + { + return isSeed; + } + + public MLKEMParameterSpec getParameterSpec() + { + return params; + } + + public byte[] getSeed() + { + if (isSeed()) + { + return Arrays.clone(data); + } + + throw new IllegalStateException("KeySpec represents long form"); + } + + public byte[] getPrivateData() + { + if (!isSeed()) + { + return Arrays.clone(data); + } + + throw new IllegalStateException("KeySpec represents seed"); + } + + public byte[] getPublicData() + { + if (!isSeed()) + { + return Arrays.clone(publicData); + } + + throw new IllegalStateException("KeySpec represents long form"); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMPublicKeySpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMPublicKeySpec.java new file mode 100644 index 0000000000..f3f4148636 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/MLKEMPublicKeySpec.java @@ -0,0 +1,37 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.KeySpec; + +import org.bouncycastle.util.Arrays; + +/** + * PublicKeySpec for ML-DSA. + */ +public class MLKEMPublicKeySpec + implements KeySpec +{ + private final MLKEMParameterSpec params; + private final byte[] publicData; + + /** + * Base constructor. + * + * @param params the parameters to use with the passed in encoding. + * @param publicData the long form encoding of the public key. + */ + public MLKEMPublicKeySpec(MLKEMParameterSpec params, byte[] publicData) + { + this.params = params; + this.publicData = Arrays.clone(publicData); + } + + public MLKEMParameterSpec getParameterSpec() + { + return params; + } + + public byte[] getPublicData() + { + return Arrays.clone(publicData); + } +} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/spec/SLHDSAParameterSpec.java b/prov/src/main/java/org/bouncycastle/jcajce/spec/SLHDSAParameterSpec.java new file mode 100644 index 0000000000..1710dd20bb --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jcajce/spec/SLHDSAParameterSpec.java @@ -0,0 +1,145 @@ +package org.bouncycastle.jcajce.spec; + +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.util.Strings; + +/** + * AlgorithmSpec for SLH-DSA + */ +public class SLHDSAParameterSpec + implements AlgorithmParameterSpec +{ + public static final SLHDSAParameterSpec slh_dsa_sha2_128f = new SLHDSAParameterSpec("SLH-DSA-SHA2-128F"); + public static final SLHDSAParameterSpec slh_dsa_sha2_128s = new SLHDSAParameterSpec("SLH-DSA-SHA2-128S"); + + public static final SLHDSAParameterSpec slh_dsa_sha2_192f = new SLHDSAParameterSpec("SLH-DSA-SHA2-192F"); + public static final SLHDSAParameterSpec slh_dsa_sha2_192s = new SLHDSAParameterSpec("SLH-DSA-SHA2-192S"); + + public static final SLHDSAParameterSpec slh_dsa_sha2_256f = new SLHDSAParameterSpec("SLH-DSA-SHA2-256F"); + public static final SLHDSAParameterSpec slh_dsa_sha2_256s = new SLHDSAParameterSpec("SLH-DSA-SHA2-256S"); + + // SHAKE-256. + + public static final SLHDSAParameterSpec slh_dsa_shake_128f = new SLHDSAParameterSpec("SLH-DSA-SHAKE-128F"); + public static final SLHDSAParameterSpec slh_dsa_shake_128s = new SLHDSAParameterSpec("SLH-DSA-SHAKE-128S"); + + public static final SLHDSAParameterSpec slh_dsa_shake_192f = new SLHDSAParameterSpec("SLH-DSA-SHAKE-192F"); + public static final SLHDSAParameterSpec slh_dsa_shake_192s = new SLHDSAParameterSpec("SLH-DSA-SHAKE-192S"); + + public static final SLHDSAParameterSpec slh_dsa_shake_256f = new SLHDSAParameterSpec("SLH-DSA-SHAKE-256F"); + public static final SLHDSAParameterSpec slh_dsa_shake_256s = new SLHDSAParameterSpec("SLH-DSA-SHAKE-256S"); + + // PREHASH + public static final SLHDSAParameterSpec slh_dsa_sha2_128f_with_sha256 = new SLHDSAParameterSpec("SLH-DSA-SHA2-128F-WITH-SHA256"); + public static final SLHDSAParameterSpec slh_dsa_sha2_128s_with_sha256 = new SLHDSAParameterSpec("SLH-DSA-SHA2-128S-WITH-SHA256"); + + public static final SLHDSAParameterSpec slh_dsa_sha2_192f_with_sha512 = new SLHDSAParameterSpec("SLH-DSA-SHA2-192F-WITH-SHA512"); + public static final SLHDSAParameterSpec slh_dsa_sha2_192s_with_sha512 = new SLHDSAParameterSpec("SLH-DSA-SHA2-192S-WITH-SHA512"); + + public static final SLHDSAParameterSpec slh_dsa_sha2_256f_with_sha512 = new SLHDSAParameterSpec("SLH-DSA-SHA2-256F-WITH-SHA512"); + public static final SLHDSAParameterSpec slh_dsa_sha2_256s_with_sha512 = new SLHDSAParameterSpec("SLH-DSA-SHA2-256S-WITH-SHA512"); + + // SHAKE-256. + + public static final SLHDSAParameterSpec slh_dsa_shake_128f_with_shake128 = new SLHDSAParameterSpec("SLH-DSA-SHAKE-128F-WITH-SHAKE128"); + public static final SLHDSAParameterSpec slh_dsa_shake_128s_with_shake128 = new SLHDSAParameterSpec("SLH-DSA-SHAKE-128S-WITH-SHAKE128"); + + public static final SLHDSAParameterSpec slh_dsa_shake_192f_with_shake256 = new SLHDSAParameterSpec("SLH-DSA-SHAKE-192F-WITH-SHAKE256"); + public static final SLHDSAParameterSpec slh_dsa_shake_192s_with_shake256 = new SLHDSAParameterSpec("SLH-DSA-SHAKE-192S-WITH-SHAKE256"); + + public static final SLHDSAParameterSpec slh_dsa_shake_256f_with_shake256 = new SLHDSAParameterSpec("SLH-DSA-SHAKE-256F-WITH-SHAKE256"); + public static final SLHDSAParameterSpec slh_dsa_shake_256s_with_shake256 = new SLHDSAParameterSpec("SLH-DSA-SHAKE-256S-WITH-SHAKE256"); + + private static Map parameters = new HashMap(); + + static + { + parameters.put("slh-dsa-sha2-128f", SLHDSAParameterSpec.slh_dsa_sha2_128f); + parameters.put("slh-dsa-sha2-128s", SLHDSAParameterSpec.slh_dsa_sha2_128s); + parameters.put("slh-dsa-sha2-192f", SLHDSAParameterSpec.slh_dsa_sha2_192f); + parameters.put("slh-dsa-sha2-192s", SLHDSAParameterSpec.slh_dsa_sha2_192s); + parameters.put("slh-dsa-sha2-256f", SLHDSAParameterSpec.slh_dsa_sha2_256f); + parameters.put("slh-dsa-sha2-256s", SLHDSAParameterSpec.slh_dsa_sha2_256s); + + parameters.put("sha2-128f", SLHDSAParameterSpec.slh_dsa_sha2_128f); + parameters.put("sha2-128s", SLHDSAParameterSpec.slh_dsa_sha2_128s); + parameters.put("sha2-192f", SLHDSAParameterSpec.slh_dsa_sha2_192f); + parameters.put("sha2-192s", SLHDSAParameterSpec.slh_dsa_sha2_192s); + parameters.put("sha2-256f", SLHDSAParameterSpec.slh_dsa_sha2_256f); + parameters.put("sha2-256s", SLHDSAParameterSpec.slh_dsa_sha2_256s); + + parameters.put("slh-dsa-shake-128f", SLHDSAParameterSpec.slh_dsa_shake_128f); + parameters.put("slh-dsa-shake-128s", SLHDSAParameterSpec.slh_dsa_shake_128s); + parameters.put("slh-dsa-shake-192f", SLHDSAParameterSpec.slh_dsa_shake_192f); + parameters.put("slh-dsa-shake-192s", SLHDSAParameterSpec.slh_dsa_shake_192s); + parameters.put("slh-dsa-shake-256f", SLHDSAParameterSpec.slh_dsa_shake_256f); + parameters.put("slh-dsa-shake-256s", SLHDSAParameterSpec.slh_dsa_shake_256s); + + parameters.put("shake-128f", SLHDSAParameterSpec.slh_dsa_shake_128f); + parameters.put("shake-128s", SLHDSAParameterSpec.slh_dsa_shake_128s); + parameters.put("shake-192f", SLHDSAParameterSpec.slh_dsa_shake_192f); + parameters.put("shake-192s", SLHDSAParameterSpec.slh_dsa_shake_192s); + parameters.put("shake-256f", SLHDSAParameterSpec.slh_dsa_shake_256f); + parameters.put("shake-256s", SLHDSAParameterSpec.slh_dsa_shake_256s); + + parameters.put("slh-dsa-sha2-128f-with-sha256", SLHDSAParameterSpec.slh_dsa_sha2_128f_with_sha256); + parameters.put("slh-dsa-sha2-128s-with-sha256", SLHDSAParameterSpec.slh_dsa_sha2_128s_with_sha256); + parameters.put("slh-dsa-sha2-192f-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_192f_with_sha512); + parameters.put("slh-dsa-sha2-192s-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_192s_with_sha512); + parameters.put("slh-dsa-sha2-256f-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_256f_with_sha512); + parameters.put("slh-dsa-sha2-256s-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_256s_with_sha512); + + parameters.put("sha2-128f-with-sha256", SLHDSAParameterSpec.slh_dsa_sha2_128f_with_sha256); + parameters.put("sha2-128s-with-sha256", SLHDSAParameterSpec.slh_dsa_sha2_128s_with_sha256); + parameters.put("sha2-192f-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_192f_with_sha512); + parameters.put("sha2-192s-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_192s_with_sha512); + parameters.put("sha2-256f-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_256f_with_sha512); + parameters.put("sha2-256s-with-sha512", SLHDSAParameterSpec.slh_dsa_sha2_256s_with_sha512); + + parameters.put("slh-dsa-shake-128f-with-shake128", SLHDSAParameterSpec.slh_dsa_shake_128f_with_shake128); + parameters.put("slh-dsa-shake-128s-with-shake128", SLHDSAParameterSpec.slh_dsa_shake_128s_with_shake128); + parameters.put("slh-dsa-shake-192f-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_192f_with_shake256); + parameters.put("slh-dsa-shake-192s-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_192s_with_shake256); + parameters.put("slh-dsa-shake-256f-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_256f_with_shake256); + parameters.put("slh-dsa-shake-256s-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_256s_with_shake256); + + parameters.put("shake-128f-with-shake128", SLHDSAParameterSpec.slh_dsa_shake_128f_with_shake128); + parameters.put("shake-128s-with-shake128", SLHDSAParameterSpec.slh_dsa_shake_128s_with_shake128); + parameters.put("shake-192f-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_192f_with_shake256); + parameters.put("shake-192s-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_192s_with_shake256); + parameters.put("shake-256f-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_256f_with_shake256); + parameters.put("shake-256s-with-shake256", SLHDSAParameterSpec.slh_dsa_shake_256s_with_shake256); + } + + private final String name; + + private SLHDSAParameterSpec(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public static SLHDSAParameterSpec fromName(String name) + { + if (name == null) + { + throw new NullPointerException("name cannot be null"); + } + + SLHDSAParameterSpec parameterSpec = (SLHDSAParameterSpec)parameters.get(Strings.toLowerCase(name)); + + if (parameterSpec == null) + { + throw new IllegalArgumentException("unknown parameter name: " + name); + } + + return parameterSpec; + } +} diff --git a/prov/src/main/java/org/bouncycastle/jce/interfaces/ElGamalPublicKey.java b/prov/src/main/java/org/bouncycastle/jce/interfaces/ElGamalPublicKey.java index 1f75987056..b0c86abe8a 100644 --- a/prov/src/main/java/org/bouncycastle/jce/interfaces/ElGamalPublicKey.java +++ b/prov/src/main/java/org/bouncycastle/jce/interfaces/ElGamalPublicKey.java @@ -4,6 +4,9 @@ import javax.crypto.interfaces.DHPublicKey; +/** + * @deprecated just use DHPublicKey. + */ public interface ElGamalPublicKey extends ElGamalKey, DHPublicKey { diff --git a/prov/src/main/java/org/bouncycastle/jce/interfaces/PKCS12BagAttributeCarrier.java b/prov/src/main/java/org/bouncycastle/jce/interfaces/PKCS12BagAttributeCarrier.java index b8ebee74d7..0dd3aa2c27 100644 --- a/prov/src/main/java/org/bouncycastle/jce/interfaces/PKCS12BagAttributeCarrier.java +++ b/prov/src/main/java/org/bouncycastle/jce/interfaces/PKCS12BagAttributeCarrier.java @@ -1,3 +1,4 @@ + package org.bouncycastle.jce.interfaces; import java.util.Enumeration; @@ -18,4 +19,8 @@ ASN1Encodable getBagAttribute( ASN1ObjectIdentifier oid); Enumeration getBagAttributeKeys(); + + boolean hasFriendlyName(); + + void setFriendlyName(String friendlyName); } diff --git a/prov/src/main/java/org/bouncycastle/jce/interfaces/package-info.java b/prov/src/main/java/org/bouncycastle/jce/interfaces/package-info.java new file mode 100644 index 0000000000..8260364d84 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jce/interfaces/package-info.java @@ -0,0 +1,4 @@ +/** + * Interfaces for supporting Elliptic Curve Keys, El Gamal, and PKCS12 attributes. + */ +package org.bouncycastle.jce.interfaces; diff --git a/prov/src/main/java/org/bouncycastle/jce/package-info.java b/prov/src/main/java/org/bouncycastle/jce/package-info.java new file mode 100644 index 0000000000..31042cd8a3 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jce/package-info.java @@ -0,0 +1,9 @@ +/** + * Utility classes for use with the JCE. + *

      + * The classes in this package support the generation of certificates and PKCS10 signing requests. + *

      + * Note: the PKCS7 class is deprecated, for a fuller version of CMS see the cms package distributed + * with the BC mail API. + */ +package org.bouncycastle.jce; diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java b/prov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java index 0098ec2d55..15d26740d6 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java @@ -15,6 +15,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; @@ -23,6 +24,7 @@ import org.bouncycastle.crypto.CryptoServicePurpose; import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.internal.asn1.isara.IsaraObjectIdentifiers; +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.MLKEMKeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.config.ProviderConfiguration; import org.bouncycastle.jcajce.provider.symmetric.util.ClassUtil; @@ -36,9 +38,11 @@ import org.bouncycastle.pqc.jcajce.provider.hqc.HQCKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.kyber.KyberKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.lms.LMSKeyFactorySpi; +import org.bouncycastle.pqc.jcajce.provider.mayo.MayoKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.newhope.NHKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.ntru.NTRUKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.picnic.PicnicKeyFactorySpi; +import org.bouncycastle.pqc.jcajce.provider.snova.SnovaKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.sphincs.Sphincs256KeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.sphincsplus.SPHINCSPlusKeyFactorySpi; import org.bouncycastle.pqc.jcajce.provider.xmss.XMSSKeyFactorySpi; @@ -74,7 +78,7 @@ public final class BouncyCastleProvider extends Provider { private static final Logger LOG = Logger.getLogger(BouncyCastleProvider.class.getName()); - private static String info = "BouncyCastle Security Provider v1.78.1"; + private static String info = "BouncyCastle Security Provider v1.81"; public static final String PROVIDER_NAME = "BC"; @@ -90,29 +94,29 @@ public final class BouncyCastleProvider extends Provider private static final String SYMMETRIC_PACKAGE = "org.bouncycastle.jcajce.provider.symmetric."; private static final String[] SYMMETRIC_GENERIC = - { - "PBEPBKDF1", "PBEPBKDF2", "PBEPKCS12", "TLSKDF", "SCRYPT" - }; + { + "PBEPBKDF1", "PBEPBKDF2", "PBEPKCS12", "TLSKDF", "SCRYPT" + }; private static final String[] SYMMETRIC_MACS = - { - "SipHash", "SipHash128", "Poly1305" - }; + { + "SipHash", "SipHash128", "Poly1305" + }; private static final CryptoServiceProperties[] SYMMETRIC_CIPHERS = - { - // TODO: these numbers need a bit more work, we cap at 256 bits. - service("AES", 256), service("ARC4", 20), service("ARIA", 256), service("Blowfish", 128), service("Camellia", 256), - service("CAST5", 128), service("CAST6", 256), service("ChaCha", 128), service("DES", 56), service("DESede", 112), - service("GOST28147", 128), service("Grainv1", 128), service("Grain128", 128), service("HC128", 128), service("HC256", 256), - service("IDEA", 128), service("Noekeon", 128), service("RC2", 128), service("RC5", 128), service("RC6", 256), - service("Rijndael", 256), service("Salsa20", 128), service("SEED", 128), service("Serpent", 256), service("Shacal2", 128), - service("Skipjack", 80), service("SM4", 128), service("TEA", 128), service("Twofish", 256), service("Threefish", 128), - service("VMPC", 128), service("VMPCKSA3", 128), service("XTEA", 128), service("XSalsa20", 128), service("OpenSSLPBKDF", 128), - service("DSTU7624", 256), service("GOST3412_2015", 256), service("Zuc", 128) - }; - - /* + { + // TODO: these numbers need a bit more work, we cap at 256 bits. + service("AES", 256), service("ARC4", 20), service("ARIA", 256), service("Blowfish", 128), service("Camellia", 256), + service("CAST5", 128), service("CAST6", 256), service("ChaCha", 128), service("DES", 56), service("DESede", 112), + service("GOST28147", 128), service("Grainv1", 128), service("Grain128", 128), service("HC128", 128), service("HC256", 256), + service("IDEA", 128), service("Noekeon", 128), service("RC2", 128), service("RC5", 128), service("RC6", 256), + service("Rijndael", 256), service("Salsa20", 128), service("SEED", 128), service("Serpent", 256), service("Shacal2", 128), + service("Skipjack", 80), service("SM4", 128), service("TEA", 128), service("Twofish", 256), service("Threefish", 128), + service("VMPC", 128), service("VMPCKSA3", 128), service("XTEA", 128), service("XSalsa20", 128), service("OpenSSLPBKDF", 128), + service("DSTU7624", 256), service("GOST3412_2015", 256), service("Zuc", 128) + }; + + /* * Configurable asymmetric ciphers */ private static final String ASYMMETRIC_PACKAGE = "org.bouncycastle.jcajce.provider.asymmetric."; @@ -120,43 +124,44 @@ public final class BouncyCastleProvider extends Provider // this one is required for GNU class path - it needs to be loaded first as the // later ones configure it. private static final String[] ASYMMETRIC_GENERIC = - { - "X509", "IES", "COMPOSITE", "EXTERNAL", "CompositeSignatures" - }; + { + "X509", "IES", "COMPOSITE", "EXTERNAL", "CompositeSignatures", "NoSig" + }; private static final String[] ASYMMETRIC_CIPHERS = - { - "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145", "GM", "EdEC", "LMS", "SPHINCSPlus", "Dilithium", "Falcon", "NTRU" - }; + { + "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145", "GM", "EdEC", "LMS", "SPHINCSPlus", + "Dilithium", "Falcon", "NTRU", "CONTEXT", "SLHDSA", "MLDSA", "MLKEM" + }; /* * Configurable digests */ private static final String DIGEST_PACKAGE = "org.bouncycastle.jcajce.provider.digest."; private static final String[] DIGESTS = - { - "GOST3411", "Keccak", "MD2", "MD4", "MD5", "SHA1", "RIPEMD128", "RIPEMD160", "RIPEMD256", "RIPEMD320", "SHA224", - "SHA256", "SHA384", "SHA512", "SHA3", "Skein", "SM3", "Tiger", "Whirlpool", "Blake2b", "Blake2s", "DSTU7564", - "Haraka", "Blake3" - }; + { + "GOST3411", "Keccak", "MD2", "MD4", "MD5", "SHA1", "RIPEMD128", "RIPEMD160", "RIPEMD256", "RIPEMD320", "SHA224", + "SHA256", "SHA384", "SHA512", "SHA3", "Skein", "SM3", "Tiger", "Whirlpool", "Blake2b", "Blake2s", "DSTU7564", + "Haraka", "Blake3" + }; /* * Configurable keystores */ private static final String KEYSTORE_PACKAGE = "org.bouncycastle.jcajce.provider.keystore."; private static final String[] KEYSTORES = - { - "BC", "BCFKS", "PKCS12" - }; + { + "BC", "BCFKS", "PKCS12" + }; /* * Configurable secure random */ private static final String SECURE_RANDOM_PACKAGE = "org.bouncycastle.jcajce.provider.drbg."; private static final String[] SECURE_RANDOMS = - { - "DRBG" - }; + { + "DRBG" + }; private Map serviceMap = new ConcurrentHashMap(); @@ -167,7 +172,7 @@ public final class BouncyCastleProvider extends Provider */ public BouncyCastleProvider() { - super(PROVIDER_NAME, 1.7801, info); + super(PROVIDER_NAME, 1.81, info); AccessController.doPrivileged(new PrivilegedAction() { @@ -274,7 +279,8 @@ public final Service getService(final String type, final String algorithm) public Service run() { Service service = BouncyCastleProvider.super.getService(type, algorithm); - if (service == null) + // from Java21 services started to return with null class names... + if (service == null || service.getClassName() == null) { return null; } @@ -347,6 +353,7 @@ private void loadServiceClass(String packageName, String serviceName) private void loadPQCKeys() { addKeyInfoConverter(BCObjectIdentifiers.sphincsPlus, new SPHINCSPlusKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, new SPHINCSPlusKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, new SPHINCSPlusKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.sphincsPlus_shake_128s_r3, new SPHINCSPlusKeyFactorySpi()); @@ -402,15 +409,17 @@ private void loadPQCKeys() addKeyInfoConverter(BCObjectIdentifiers.picnic_key, new PicnicKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.falcon_512, new FalconKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.falcon_1024, new FalconKeyFactorySpi()); + + addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_512, new MLKEMKeyFactorySpi()); + addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_768, new MLKEMKeyFactorySpi()); + addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_1024, new MLKEMKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.dilithium2, new DilithiumKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.dilithium3, new DilithiumKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.dilithium5, new DilithiumKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.dilithium2_aes, new DilithiumKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.dilithium3_aes, new DilithiumKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.dilithium5_aes, new DilithiumKeyFactorySpi()); - addKeyInfoConverter(BCObjectIdentifiers.kyber512, new KyberKeyFactorySpi()); - addKeyInfoConverter(BCObjectIdentifiers.kyber768, new KyberKeyFactorySpi()); - addKeyInfoConverter(BCObjectIdentifiers.kyber1024, new KyberKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.mceliece348864_r3, new CMCEKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.mceliece460896_r3, new CMCEKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.mceliece6688128_r3, new CMCEKeyFactorySpi()); @@ -422,7 +431,8 @@ private void loadPQCKeys() addKeyInfoConverter(BCObjectIdentifiers.hqc128, new HQCKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.hqc192, new HQCKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.hqc256, new HQCKeyFactorySpi()); - addKeyInfoConverter(BCObjectIdentifiers.kyber1024, new KyberKeyFactorySpi()); + + addKeyInfoConverter(BCObjectIdentifiers.kyber512_aes, new KyberKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.kyber768_aes, new KyberKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.kyber1024_aes, new KyberKeyFactorySpi()); @@ -430,6 +440,52 @@ private void loadPQCKeys() addKeyInfoConverter(BCObjectIdentifiers.ntruhps2048677, new NTRUKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.ntruhps4096821, new NTRUKeyFactorySpi()); addKeyInfoConverter(BCObjectIdentifiers.ntruhrss701, new NTRUKeyFactorySpi()); + + addKeyInfoConverter(BCObjectIdentifiers.mayo1, new MayoKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.mayo2, new MayoKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.mayo3, new MayoKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.mayo5, new MayoKeyFactorySpi()); + + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_4_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_4_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_4_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_4_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_5_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_5_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_5_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_24_5_5_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_25_8_3_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_25_8_3_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_25_8_3_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_25_8_3_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_8_4_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_8_4_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_8_4_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_8_4_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_17_2_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_17_2_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_17_2_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_37_17_2_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_49_11_3_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_49_11_3_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_49_11_3_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_49_11_3_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_56_25_2_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_56_25_2_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_56_25_2_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_56_25_2_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_60_10_4_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_60_10_4_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_60_10_4_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_60_10_4_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_66_15_3_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_66_15_3_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_66_15_3_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_66_15_3_shake_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_75_33_2_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_75_33_2_esk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_75_33_2_shake_ssk, new SnovaKeyFactorySpi()); + addKeyInfoConverter(BCObjectIdentifiers.snova_75_33_2_shake_esk, new SnovaKeyFactorySpi()); } public void setParameter(String parameterName, Object parameter) @@ -473,7 +529,7 @@ public void addAlgorithm(String type, ASN1ObjectIdentifier oid, String className addAttributes(type + "." + oid, attributes); addAttributes(type + ".OID." + oid, attributes); } - + public void addKeyInfoConverter(ASN1ObjectIdentifier oid, AsymmetricKeyInfoConverter keyInfoConverter) { synchronized (keyInfoConverters) diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java b/prov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java index efb6ff6053..951e12be40 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java @@ -52,7 +52,6 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.RFC4519Style; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -64,7 +63,6 @@ import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.PolicyInformation; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.internal.asn1.isismtt.ISISMTTObjectIdentifiers; import org.bouncycastle.jcajce.PKIXCRLStore; @@ -413,34 +411,65 @@ protected static final Set getQualifierSet(ASN1Sequence qualifiers) return pq; } - protected static PKIXPolicyNode removePolicyNode( - PKIXPolicyNode validPolicyTree, - List[] policyNodes, - PKIXPolicyNode _node) + static PKIXPolicyNode removeChildlessPolicyNodes(PKIXPolicyNode validPolicyTree, List[] policyNodes, int depthLimit) { - PKIXPolicyNode _parent = (PKIXPolicyNode)_node.getParent(); - if (validPolicyTree == null) { return null; } - if (_parent == null) + int i = depthLimit; + while (--i >= 0) { - for (int j = 0; j < policyNodes.length; j++) + List nodes_i = policyNodes[i]; + + int j = nodes_i.size(); + while (--j >= 0) { - policyNodes[j] = new ArrayList(); + PKIXPolicyNode node_j = (PKIXPolicyNode)nodes_i.get(j); + + if (node_j.hasChildren()) + { + continue; + } + + nodes_i.remove(j); + + PKIXPolicyNode parent = (PKIXPolicyNode)node_j.getParent(); + if (parent == null) + { + return null; + } + + parent.removeChild(node_j); } + } + return validPolicyTree; + } + + static PKIXPolicyNode removePolicyNode(PKIXPolicyNode validPolicyTree, List[] policyNodes, PKIXPolicyNode node) + { + if (validPolicyTree == null) + { return null; } - else + + PKIXPolicyNode parent = (PKIXPolicyNode)node.getParent(); + if (parent == null) { - _parent.removeChild(_node); - removePolicyNodeRecurse(policyNodes, _node); + for (int j = 0; j < policyNodes.length; j++) + { + policyNodes[j].clear(); + } - return validPolicyTree; + return null; } + + parent.removeChild(node); + removePolicyNodeRecurse(policyNodes, node); + + return validPolicyTree; } private static void removePolicyNodeRecurse( @@ -496,160 +525,21 @@ protected static boolean processCertD1i( return false; } - protected static void processCertD1ii( - int index, - List[] policyNodes, - ASN1ObjectIdentifier _poid, - Set _pq) + static void processCertD1ii(int index, List[] policyNodes, ASN1ObjectIdentifier _poid, Set _pq) { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) + PKIXPolicyNode anyPolicyNode = findValidPolicy(policyNodes[index - 1].iterator(), ANY_POLICY); + if (anyPolicyNode != null) { - PKIXPolicyNode _node = (PKIXPolicyNode)policyNodeVec.get(j); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Set _childExpectedPolicies = new HashSet(); - _childExpectedPolicies.add(_poid.getId()); - - PKIXPolicyNode _child = new PKIXPolicyNode(new ArrayList(), - index, - _childExpectedPolicies, - _node, - _pq, - _poid.getId(), - false); - _node.addChild(_child); - policyNodes[index].add(_child); - return; - } - } - } - - protected static void prepareNextCertB1( - int i, - List[] policyNodes, - String id_p, - Map m_idp, - X509Certificate cert - ) - throws AnnotatedException, CertPathValidatorException - { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; - } - } - - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = null; - try - { - policies = DERSequence.getInstance(getExtensionValue(cert, CERTIFICATE_POLICIES)); - } - catch (Exception e) - { - throw new AnnotatedException("Certificate policies cannot be decoded.", e); - } - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = null; - - try - { - pinfo = PolicyInformation.getInstance(e.nextElement()); - } - catch (Exception ex) - { - throw new AnnotatedException("Policy information cannot be decoded.", ex); - } - if (ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - try - { - pq = getQualifierSet(pinfo.getPolicyQualifiers()); - } - catch (CertPathValidatorException ex) - { - throw new ExtCertPathValidatorException( - "Policy qualifier info set could not be built.", ex); - } - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains(CERTIFICATE_POLICIES); - } + String policy = _poid.getId(); - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode( - new ArrayList(), i, - (Set)m_idp.get(id_p), - p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } - } + Set _childExpectedPolicies = new HashSet(); + _childExpectedPolicies.add(policy); - protected static PKIXPolicyNode prepareNextCertB2( - int i, - List[] policyNodes, - String id_p, - PKIXPolicyNode validPolicyTree) - { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node2); - if (validPolicyTree == null) - { - break; - } - } - } - } - } + PKIXPolicyNode _child = new PKIXPolicyNode(new ArrayList(), index, _childExpectedPolicies, anyPolicyNode, + _pq, policy, false); + anyPolicyNode.addChild(_child); + policyNodes[index].add(_child); } - return validPolicyTree; } protected static boolean isAnyPolicy( @@ -981,10 +871,7 @@ else if (!PrincipalUtils.getEncodedIssuerPrincipal(cert).equals(PrincipalUtils.g ASN1Enumerated reasonCode = null; if (crl_entry.hasExtensions()) { - if (crl_entry.hasUnsupportedCriticalExtension()) - { - throw new AnnotatedException("CRL entry has unsupported critical extensions."); - } + checkCRLEntryCriticalExtensions(crl_entry, "CRL entry has unsupported critical extensions."); try { @@ -1079,13 +966,16 @@ protected static Set getDeltaCRLs(Date validityDate, // 5.2.4 (c) selBuilder.setMaxBaseCRLNumber(completeCRLNumber); + // NOTE: Does not restrict to critical DCI extension, so we filter non-critical ones later + selBuilder.setDeltaCRLIndicatorEnabled(true); + PKIXCRLStoreSelector deltaSelect = selBuilder.build(); // find delta CRLs - Set temp = PKIXCRLUtil.findCRLs(deltaSelect, validityDate, certStores, pkixCrlStores); + Set deltaCRLs = getDeltaCRLs(PKIXCRLUtil.findCRLs(deltaSelect, validityDate, certStores, pkixCrlStores)); // if the named CRL store is empty, and we're told to check with CRLDP - if (temp.isEmpty() && Properties.isOverrideSet("org.bouncycastle.x509.enableCRLDP")) + if (deltaCRLs.isEmpty() && Properties.isOverrideSet("org.bouncycastle.x509.enableCRLDP")) { CertificateFactory certFact; try @@ -1109,7 +999,7 @@ protected static Set getDeltaCRLs(Date validityDate, for (int j = 0; j < genNames.length; j++) { - GeneralName name = genNames[i]; + GeneralName name = genNames[j]; if (name.getTagNo() == GeneralName.uniformResourceIdentifier) { try @@ -1118,8 +1008,9 @@ protected static Set getDeltaCRLs(Date validityDate, new URI(((ASN1String)name.getName()).getString())); if (store != null) { - temp = PKIXCRLUtil.findCRLs(deltaSelect, validityDate, Collections.EMPTY_LIST, - Collections.singletonList(store)); + deltaCRLs = getDeltaCRLs( + PKIXCRLUtil.findCRLs(deltaSelect, validityDate, Collections.EMPTY_LIST, + Collections.singletonList(store))); } break; } @@ -1132,10 +1023,15 @@ protected static Set getDeltaCRLs(Date validityDate, } } } - + + return deltaCRLs; + } + + private static Set getDeltaCRLs(Set crls) + { Set result = new HashSet(); - for (Iterator it = temp.iterator(); it.hasNext(); ) + for (Iterator it = crls.iterator(); it.hasNext(); ) { X509CRL crl = (X509CRL)it.next(); @@ -1150,14 +1046,7 @@ protected static Set getDeltaCRLs(Date validityDate, private static boolean isDeltaCRL(X509CRL crl) { - Set critical = crl.getCriticalExtensionOIDs(); - - if (critical == null) - { - return false; - } - - return critical.contains(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); + return hasCriticalExtension(crl, Extension.deltaCRLIndicator.getId()); } /** @@ -1415,4 +1304,67 @@ static void checkCRLsNotEmpty(PKIXCertRevocationCheckerParameters params, Set cr } } } + + static void checkCRLCriticalExtensions(X509CRL crl, String exceptionMessage) + throws AnnotatedException + { + Set criticalExtensions = crl.getCriticalExtensionOIDs(); + if (criticalExtensions != null) + { + int count = criticalExtensions.size(); + if (count > 0) + { + if (criticalExtensions.contains(Extension.issuingDistributionPoint.getId())) + { + --count; + } + if (criticalExtensions.contains(Extension.deltaCRLIndicator.getId())) + { + --count; + } + + if (count > 0) + { + throw new AnnotatedException(exceptionMessage); + } + } + } + } + + static void checkCRLEntryCriticalExtensions(X509CRLEntry crlEntry, String exceptionMessage) + throws AnnotatedException + { + if (crlEntry.hasUnsupportedCriticalExtension()) + { + throw new AnnotatedException(exceptionMessage); + } + } + + static PKIXPolicyNode findValidPolicy(Iterator policyNodes, String policy) + { + while (policyNodes.hasNext()) + { + PKIXPolicyNode node = (PKIXPolicyNode)policyNodes.next(); + if (policy.equals(node.getValidPolicy())) + { + return node; + } + } + return null; + } + + static boolean hasCriticalExtension(X509Certificate cert, String extensionOID) + { + return hasCriticalExtension(cert.getCriticalExtensionOIDs(), extensionOID); + } + + static boolean hasCriticalExtension(X509CRL crl, String extensionOID) + { + return hasCriticalExtension(crl.getCriticalExtensionOIDs(), extensionOID); + } + + private static boolean hasCriticalExtension(Set criticalExtensionOIDs, String extensionOID) + { + return criticalExtensionOIDs != null && criticalExtensionOIDs.contains(extensionOID); + } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/CrlCache.java b/prov/src/main/java/org/bouncycastle/jce/provider/CrlCache.java index ca30e10119..34a7542640 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/CrlCache.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/CrlCache.java @@ -4,8 +4,8 @@ import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; -import java.net.HttpURLConnection; import java.net.URI; +import java.net.URLConnection; import java.security.cert.CRL; import java.security.cert.CRLException; import java.security.cert.CertificateFactory; @@ -54,7 +54,7 @@ static synchronized PKIXCRLStore getCrl(CertificateFactory certFact, Date validD if (crlStore != null) { boolean isExpired = false; - for (Iterator it = crlStore.getMatches(null).iterator(); it.hasNext();) + for (Iterator it = crlStore.getMatches(null).iterator(); it.hasNext(); ) { X509CRL crl = (X509CRL)it.next(); @@ -125,11 +125,12 @@ private static Collection getCrlsFromLDAP(CertificateFactory certFact, URI distr private static Collection getCrls(CertificateFactory certFact, URI distributionPoint) throws IOException, CRLException { - HttpURLConnection crlCon = (HttpURLConnection)distributionPoint.toURL().openConnection(); - crlCon.setConnectTimeout(DEFAULT_TIMEOUT); - crlCon.setReadTimeout(DEFAULT_TIMEOUT); + URLConnection urlConnection = distributionPoint.toURL().openConnection(); - InputStream crlIn = crlCon.getInputStream(); + urlConnection.setConnectTimeout(DEFAULT_TIMEOUT); + urlConnection.setReadTimeout(DEFAULT_TIMEOUT); + + InputStream crlIn = urlConnection.getInputStream(); Collection crls = certFact.generateCRLs(crlIn); diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java b/prov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java index 32e3043f41..f3f0bbda14 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java @@ -184,4 +184,13 @@ public Enumeration getBagAttributeKeys() { return attrCarrier.getBagAttributeKeys(); } + + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java b/prov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java index 3f33cdb116..222d656e87 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java @@ -382,6 +382,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java b/prov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java index 64a1228d0f..7001c1468e 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java @@ -162,4 +162,14 @@ public Enumeration getBagAttributeKeys() { return attrCarrier.getBagAttributeKeys(); } + + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/JCERSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jce/provider/JCERSAPrivateKey.java index 7529b4143e..24428e7cf0 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/JCERSAPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/JCERSAPrivateKey.java @@ -121,6 +121,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java b/prov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java index 3bd6d307b0..ff028de8f8 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java @@ -153,6 +153,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/JDKPKCS12StoreParameter.java b/prov/src/main/java/org/bouncycastle/jce/provider/JDKPKCS12StoreParameter.java index 7e8340aa54..b30fde254e 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/JDKPKCS12StoreParameter.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/JDKPKCS12StoreParameter.java @@ -13,6 +13,7 @@ public class JDKPKCS12StoreParameter implements LoadStoreParameter private OutputStream outputStream; private ProtectionParameter protectionParameter; private boolean useDEREncoding; + private boolean overwriteFriendlyName; public OutputStream getOutputStream() { @@ -28,6 +29,10 @@ public boolean isUseDEREncoding() { return useDEREncoding; } + public boolean isOverwriteFriendlyName() + { + return overwriteFriendlyName; + } public void setOutputStream(OutputStream outputStream) { @@ -48,4 +53,8 @@ public void setUseDEREncoding(boolean useDEREncoding) { this.useDEREncoding = useDEREncoding; } + public void setOverwriteFriendlyName(boolean overwriteFriendlyName) + { + this.overwriteFriendlyName = overwriteFriendlyName; + } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/OcspCache.java b/prov/src/main/java/org/bouncycastle/jce/provider/OcspCache.java index 06817817d9..6f1805fd3c 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/OcspCache.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/OcspCache.java @@ -13,6 +13,7 @@ import java.security.cert.X509Certificate; import java.text.ParseException; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -23,6 +24,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.ocsp.BasicOCSPResponse; import org.bouncycastle.asn1.ocsp.CertID; @@ -38,6 +40,7 @@ import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.jcajce.PKIXCertRevocationCheckerParameters; import org.bouncycastle.jcajce.util.JcaJceHelper; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.io.Streams; class OcspCache @@ -70,36 +73,14 @@ static OCSPResponse getOcspResponse( BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance( ASN1OctetString.getInstance(response.getResponseBytes().getResponse()).getOctets()); - ResponseData responseData = ResponseData.getInstance(basicResp.getTbsResponseData()); - - ASN1Sequence s = responseData.getResponses(); - - for (int i = 0; i != s.size(); i++) + boolean matchFound = isCertIDFoundAndCurrent(basicResp, parameters.getValidDate(), certID); + if (matchFound) { - SingleResponse resp = SingleResponse.getInstance(s.getObjectAt(i)); - - if (certID.equals(resp.getCertID())) - { - ASN1GeneralizedTime nextUp = resp.getNextUpdate(); - try - { - if (nextUp != null && parameters.getValidDate().after(nextUp.getDate())) - { - responseMap.remove(certID); - response = null; - } - } - catch (ParseException e) - { - // this should never happen, but... - responseMap.remove(certID); - response = null; - } - } + return response; } - if (response != null) + else { - return response; + responseMap.remove(certID); } } } @@ -129,15 +110,16 @@ static OCSPResponse getOcspResponse( for (int i = 0; i != exts.size(); i++) { Extension ext = (Extension)exts.get(i); - byte[] value = ext.getValue(); - if (OCSPObjectIdentifiers.id_pkix_ocsp_nonce.getId().equals(ext.getId())) + ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(ext.getId()); + ASN1OctetString value = new DEROctetString(ext.getValue()); + + if (OCSPObjectIdentifiers.id_pkix_ocsp_nonce.equals(oid)) { - nonce = value; + nonce = Arrays.clone(value.getOctets()); } - requestExtensions.add(new org.bouncycastle.asn1.x509.Extension( - new ASN1ObjectIdentifier(ext.getId()), ext.isCritical(), value)); + requestExtensions.add(new org.bouncycastle.asn1.x509.Extension(oid, ext.isCritical(), value)); } // TODO: configure originator @@ -190,7 +172,8 @@ static OCSPResponse getOcspResponse( { BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(respBytes.getResponse().getOctets()); - validated = ProvOcspRevocationChecker.validatedOcspResponse(basicResp, parameters, nonce, responderCert, helper); + validated = ProvOcspRevocationChecker.validatedOcspResponse(basicResp, parameters, nonce, responderCert, helper) + && isCertIDFoundAndCurrent(basicResp, parameters.getValidDate(), certID); } if (!validated) @@ -231,4 +214,36 @@ static OCSPResponse getOcspResponse( e, parameters.getCertPath(), parameters.getIndex()); } } + + private static boolean isCertIDFoundAndCurrent(BasicOCSPResponse basicResp, Date validDate, CertID certID) + { + ResponseData responseData = ResponseData.getInstance(basicResp.getTbsResponseData()); + ASN1Sequence s = responseData.getResponses(); + + for (int i = 0; i != s.size(); i++) + { + SingleResponse resp = SingleResponse.getInstance(s.getObjectAt(i)); + + if (certID.equals(resp.getCertID())) + { + ASN1GeneralizedTime nextUp = resp.getNextUpdate(); + try + { + if (nextUp != null && validDate.after(nextUp.getDate())) + { + return false; + } + } + catch (ParseException e) + { + // this should never happen, but... + return false; + } + + return true; + } + } + + return false; + } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java b/prov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java index d89e920dff..d54aa2d25b 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java @@ -53,37 +53,37 @@ public Iterator getChildren() { return children.iterator(); } - + public int getDepth() { return depth; } - + public Set getExpectedPolicies() { return expectedPolicies; } - + public PolicyNode getParent() { return parent; } - + public Set getPolicyQualifiers() { return policyQualifiers; } - + public String getValidPolicy() { return validPolicy; } - + public boolean hasChildren() { return !children.isEmpty(); } - + public boolean isCritical() { return critical; @@ -98,7 +98,12 @@ public void setCritical(boolean _critical) { critical = _critical; } - + + public void setExpectedPolicies(Set expectedPolicies) + { + this.expectedPolicies = expectedPolicies; + } + public void setParent(PKIXPolicyNode _parent) { parent = _parent; @@ -125,49 +130,39 @@ public String toString(String _indent) _buf.append("}\n"); return _buf.toString(); } - + + // TODO[api] Maybe remove this, the 'clone' loses its parent public Object clone() { return copy(); } - + public PKIXPolicyNode copy() { - Set _expectedPolicies = new HashSet(); + Set _expectedPolicies = new HashSet(); Iterator _iter = expectedPolicies.iterator(); while (_iter.hasNext()) { - _expectedPolicies.add(new String((String)_iter.next())); + _expectedPolicies.add(_iter.next()); } - - Set _policyQualifiers = new HashSet(); + + Set _policyQualifiers = new HashSet(); _iter = policyQualifiers.iterator(); while (_iter.hasNext()) { - _policyQualifiers.add(new String((String)_iter.next())); + _policyQualifiers.add(_iter.next()); } - - PKIXPolicyNode _node = new PKIXPolicyNode(new ArrayList(), - depth, - _expectedPolicies, - null, - _policyQualifiers, - new String(validPolicy), - critical); - + + PKIXPolicyNode copy = new PKIXPolicyNode(new ArrayList(), depth, _expectedPolicies, null, _policyQualifiers, + validPolicy, critical); + _iter = children.iterator(); while (_iter.hasNext()) { - PKIXPolicyNode _child = ((PKIXPolicyNode)_iter.next()).copy(); - _child.setParent(_node); - _node.addChild(_child); + PKIXPolicyNode child = (PKIXPolicyNode)_iter.next(); + copy.addChild(child.copy()); } - - return _node; - } - public void setExpectedPolicies(Set expectedPolicies) - { - this.expectedPolicies = expectedPolicies; + return copy; } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/ProvOcspRevocationChecker.java b/prov/src/main/java/org/bouncycastle/jce/provider/ProvOcspRevocationChecker.java index 1d697023f0..234e967276 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/ProvOcspRevocationChecker.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/ProvOcspRevocationChecker.java @@ -279,7 +279,7 @@ public void check(Certificate certificate) { throw new ExtCertPathValidatorException("OCSP response expired"); } - if (certID == null || !certID.getHashAlgorithm().equals(resp.getCertID().getHashAlgorithm())) + if (certID == null || !isEqualAlgId(certID.getHashAlgorithm(), resp.getCertID().getHashAlgorithm())) { org.bouncycastle.asn1.x509.Certificate issuer = extractCert(); @@ -340,6 +340,41 @@ public void check(Certificate certificate) } } + private static boolean isEqualAlgId(AlgorithmIdentifier a, AlgorithmIdentifier b) + { + if (a == b || a.equals(b)) + { + return true; + } + + if (a.getAlgorithm().equals(b.getAlgorithm())) + { + ASN1Encodable aParam = a.getParameters(); + ASN1Encodable bParam = b.getParameters(); + + if (aParam == bParam) + { + return true; + } + + if (aParam == null) + { + return DERNull.INSTANCE.equals(bParam); + } + else + { + if (DERNull.INSTANCE.equals(aParam) && bParam == null) + { + return true; + } + + return aParam.equals(bParam); + } + } + + return false; + } + static URI getOcspResponderURI(X509Certificate cert) { byte[] extValue = cert.getExtensionValue(org.bouncycastle.asn1.x509.Extension.authorityInfoAccess.getId()); diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java b/prov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java index 5df9eed861..09c146283c 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java @@ -61,6 +61,7 @@ import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Properties; class RFC3280CertPathUtilities { @@ -556,15 +557,30 @@ protected static Set processCRLF( { X509Certificate signCert = (X509Certificate)validCerts.get(i); boolean[] keyUsage = signCert.getKeyUsage(); - - if (keyUsage != null && (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN])) + + if (keyUsage == null) { - lastException = new AnnotatedException( - "Issuer certificate key usage extension does not permit CRL signing."); + if (Properties.isOverrideSet("org.bouncycastle.x509.allow_ca_without_crl_sign", true)) + { + checkKeys.add(validKeys.get(i)); + } + else + { + lastException = new AnnotatedException( + "No key usage extension on CRL issuer certificate."); + } } else { - checkKeys.add(validKeys.get(i)); + if (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN]) + { + lastException = new AnnotatedException( + "Issuer certificate key usage extension does not permit CRL signing."); + } + else + { + checkKeys.add(validKeys.get(i)); + } } } @@ -792,176 +808,148 @@ protected static PKIXPolicyNode prepareCertB( int i = n - index; // (b) // - ASN1Sequence pm = null; + ASN1Sequence mappings; try { - pm = ASN1Sequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.POLICY_MAPPINGS)); + mappings = ASN1Sequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, POLICY_MAPPINGS)); } catch (AnnotatedException ex) { throw new ExtCertPathValidatorException("Policy mappings extension could not be decoded.", ex, certPath, index); } - PKIXPolicyNode _validPolicyTree = validPolicyTree; - if (pm != null) + + if (mappings != null) { - ASN1Sequence mappings = (ASN1Sequence)pm; - Map m_idp = new HashMap(); - Set s_idp = new HashSet(); + HashMap m_idp = new HashMap(); for (int j = 0; j < mappings.size(); j++) { ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); String id_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(0)).getId(); String sd_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(1)).getId(); - Set tmp; - if (!m_idp.containsKey(id_p)) + HashSet tmp = (HashSet)m_idp.get(id_p); + if (tmp == null) { tmp = new HashSet(); - tmp.add(sd_p); m_idp.put(id_p, tmp); - s_idp.add(id_p); - } - else - { - tmp = (Set)m_idp.get(id_p); - tmp.add(sd_p); } + + tmp.add(sd_p); } - Iterator it_idp = s_idp.iterator(); + Iterator it_idp = m_idp.entrySet().iterator(); while (it_idp.hasNext()) { - String id_p = (String)it_idp.next(); + Map.Entry e_idp = (Map.Entry)it_idp.next(); + + String id_p = (String)e_idp.getKey(); + HashSet expectedPolicies = (HashSet)e_idp.getValue(); // - // (1) + // (2) // - if (policyMapping > 0) + if (policyMapping <= 0) { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) + List nodes_i = policyNodes[i]; + + int j = nodes_i.size(); + while (--j >= 0) { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) + PKIXPolicyNode node_j = (PKIXPolicyNode)nodes_i.get(j); + if (node_j.getValidPolicy().equals(id_p)) { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; + PKIXPolicyNode p_node = (PKIXPolicyNode)node_j.getParent(); + p_node.removeChild(node_j); + nodes_i.remove(j); } } - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (RFC3280CertPathUtilities.ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = null; - try - { - policies = (ASN1Sequence)CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - } - catch (AnnotatedException e) - { - throw new ExtCertPathValidatorException( - "Certificate policies extension could not be decoded.", e, certPath, index); - } - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = null; - try - { - pinfo = PolicyInformation.getInstance(e.nextElement()); - } - catch (Exception ex) - { - throw new CertPathValidatorException( - "Policy information could not be decoded.", ex, certPath, index); - } - if (RFC3280CertPathUtilities.ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - try - { - pq = CertPathValidatorUtilities - .getQualifierSet(pinfo.getPolicyQualifiers()); - } - catch (CertPathValidatorException ex) - { - - throw new ExtCertPathValidatorException( - "Policy qualifier info set could not be decoded.", ex, certPath, - index); - } - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains( - RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - } + validPolicyTree = CertPathValidatorUtilities.removeChildlessPolicyNodes(validPolicyTree, + policyNodes, i); - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (RFC3280CertPathUtilities.ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode(new ArrayList(), i, (Set)m_idp - .get(id_p), p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } + continue; + } + + // + // (1) + // +// assert policyMapping > 0; + + PKIXPolicyNode validPolicyNode = CertPathValidatorUtilities.findValidPolicy( + policyNodes[i].iterator(), id_p); + + if (validPolicyNode != null) + { + validPolicyNode.setExpectedPolicies(expectedPolicies); + continue; + } + + PKIXPolicyNode anyPolicyNode = CertPathValidatorUtilities.findValidPolicy( + policyNodes[i].iterator(), ANY_POLICY); + + if (anyPolicyNode == null) + { + continue; + } - // - // (2) - // + ASN1Sequence policies; + try + { + policies = ASN1Sequence.getInstance( + CertPathValidatorUtilities.getExtensionValue(cert, CERTIFICATE_POLICIES)); } - else if (policyMapping <= 0) + catch (AnnotatedException e) + { + throw new ExtCertPathValidatorException( + "Certificate policies extension could not be decoded.", e, certPath, index); + } + + Set pq = null; + + Enumeration e = policies.getObjects(); + while (e.hasMoreElements()) { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) + PolicyInformation policyInformation; + try + { + policyInformation = PolicyInformation.getInstance(e.nextElement()); + } + catch (Exception ex) { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) + throw new CertPathValidatorException("Policy information could not be decoded.", ex, certPath, + index); + } + + if (ANY_POLICY.equals(policyInformation.getPolicyIdentifier().getId())) + { + try { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - _validPolicyTree = CertPathValidatorUtilities.removePolicyNode( - _validPolicyTree, policyNodes, node2); - if (_validPolicyTree == null) - { - break; - } - } - } - } + pq = CertPathValidatorUtilities.getQualifierSet(policyInformation.getPolicyQualifiers()); } + catch (CertPathValidatorException ex) + { + throw new ExtCertPathValidatorException("Policy qualifier info set could not be decoded.", + ex, certPath, index); + } + break; } } + + boolean critical = CertPathValidatorUtilities.hasCriticalExtension(cert, CERTIFICATE_POLICIES); + + PKIXPolicyNode p_node = (PKIXPolicyNode)anyPolicyNode.getParent(); + if (ANY_POLICY.equals(p_node.getValidPolicy())) + { + PKIXPolicyNode c_node = new PKIXPolicyNode(new ArrayList(), i, expectedPolicies, p_node, pq, id_p, + critical); + p_node.addChild(c_node); + policyNodes[i].add(c_node); + } } } - return _validPolicyTree; + return validPolicyTree; } protected static void prepareNextCertA( @@ -1144,6 +1132,11 @@ protected static void processCertBC( } if (altName != null) { + /* + * NOTE: PKIXCertPathReviewer limits the number of alternative names, to avoid a denial-of-service + * attack. That does not appear to be an issue for validation, so no limit is applied. + */ + GeneralName[] genNames = null; try { @@ -1301,20 +1294,10 @@ else if (_tmp instanceof ASN1ObjectIdentifier) continue; } - boolean _found = false; - Iterator _childrenIter = _node.getChildren(); - - while (_childrenIter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_childrenIter.next(); - - if (_policy.equals(_child.getValidPolicy())) - { - _found = true; - } - } + PKIXPolicyNode validPolicyChild = CertPathValidatorUtilities.findValidPolicy( + _node.getChildren(), _policy); - if (!_found) + if (validPolicyChild == null) { Set _newChildExpectedPolicies = new HashSet(); _newChildExpectedPolicies.add(_policy); @@ -1331,46 +1314,24 @@ else if (_tmp instanceof ASN1ObjectIdentifier) } } - PKIXPolicyNode _validPolicyTree = validPolicyTree; // // (d) (3) // - for (int j = (i - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - _validPolicyTree = CertPathValidatorUtilities.removePolicyNode(_validPolicyTree, policyNodes, - node); - if (_validPolicyTree == null) - { - break; - } - } - } - } + validPolicyTree = CertPathValidatorUtilities.removeChildlessPolicyNodes(validPolicyTree, policyNodes, i); // // d (4) // - Set criticalExtensionOids = cert.getCriticalExtensionOIDs(); - - if (criticalExtensionOids != null) + if (CertPathValidatorUtilities.hasCriticalExtension(cert, CERTIFICATE_POLICIES)) { - boolean critical = criticalExtensionOids.contains(RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - List nodes = policyNodes[i]; for (int j = 0; j < nodes.size(); j++) { PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(j); - node.setCritical(critical); + node.setCritical(true); } } - return _validPolicyTree; + return validPolicyTree; } return null; } @@ -1779,32 +1740,13 @@ private static void checkCRL( // update reasons mask reasonMask.addReasons(interimReasonsMask); - Set criticalExtensions = crl.getCriticalExtensionOIDs(); - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - criticalExtensions.remove(Extension.issuingDistributionPoint.getId()); - criticalExtensions.remove(Extension.deltaCRLIndicator.getId()); - - if (!criticalExtensions.isEmpty()) - { - throw new AnnotatedException("CRL contains unsupported critical extensions."); - } - } + CertPathValidatorUtilities.checkCRLCriticalExtensions(crl, + "CRL contains unsupported critical extensions."); if (deltaCRL != null) { - criticalExtensions = deltaCRL.getCriticalExtensionOIDs(); - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - criticalExtensions.remove(Extension.issuingDistributionPoint.getId()); - criticalExtensions.remove(Extension.deltaCRLIndicator.getId()); - if (!criticalExtensions.isEmpty()) - { - throw new AnnotatedException("Delta CRL contains unsupported critical extension."); - } - } + CertPathValidatorUtilities.checkCRLCriticalExtensions(deltaCRL, + "Delta CRL contains unsupported critical extensions."); } validCrlFound = true; @@ -2371,8 +2313,7 @@ protected static PKIXPolicyNode wrapupCertG( } intersection = null; } - else if (CertPathValidatorUtilities.isAnyPolicy(userInitialPolicySet)) // (g) - // (ii) + else if (CertPathValidatorUtilities.isAnyPolicy(userInitialPolicySet)) // (g) (ii) { if (paramsPKIX.isExplicitPolicyRequired()) { @@ -2381,60 +2322,45 @@ else if (CertPathValidatorUtilities.isAnyPolicy(userInitialPolicySet)) // (g) throw new ExtCertPathValidatorException("Explicit policy requested but none available.", null, certPath, index); } - else + + Set _validPolicyNodeSet = new HashSet(); + + for (int j = 0; j < policyNodes.length; j++) { - Set _validPolicyNodeSet = new HashSet(); + List _nodeDepth = policyNodes[j]; - for (int j = 0; j < policyNodes.length; j++) + for (int k = 0; k < _nodeDepth.size(); k++) { - List _nodeDepth = policyNodes[j]; + PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - for (int k = 0; k < _nodeDepth.size(); k++) + if (ANY_POLICY.equals(_node.getValidPolicy())) { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (RFC3280CertPathUtilities.ANY_POLICY.equals(_node.getValidPolicy())) + Iterator _iter = _node.getChildren(); + while (_iter.hasNext()) { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - _validPolicyNodeSet.add(_iter.next()); - } + _validPolicyNodeSet.add(_iter.next()); } + + // TODO[pkix] break if there can only be one ANY_POLICY node at this depth? (use findValidPolicy) } } + } - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); + Iterator _vpnsIter = _validPolicyNodeSet.iterator(); + while (_vpnsIter.hasNext()) + { + PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); + String _validPolicy = _node.getValidPolicy(); - if (!acceptablePolicies.contains(_validPolicy)) - { - // validPolicyTree = - // removePolicyNode(validPolicyTree, policyNodes, - // _node); - } - } - if (validPolicyTree != null) + if (!acceptablePolicies.contains(_validPolicy)) { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = CertPathValidatorUtilities.removePolicyNode(validPolicyTree, - policyNodes, node); - } - } - } + // TODO? + // validPolicyTree = CertPathValidatorUtilities.removePolicyNode(validPolicyTree, policyNodes, + // _node); } } + + validPolicyTree = CertPathValidatorUtilities.removeChildlessPolicyNodes(validPolicyTree, policyNodes, n); } intersection = validPolicyTree; @@ -2464,17 +2390,19 @@ else if (CertPathValidatorUtilities.isAnyPolicy(userInitialPolicySet)) // (g) { PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - if (RFC3280CertPathUtilities.ANY_POLICY.equals(_node.getValidPolicy())) + if (ANY_POLICY.equals(_node.getValidPolicy())) { Iterator _iter = _node.getChildren(); while (_iter.hasNext()) { PKIXPolicyNode _c_node = (PKIXPolicyNode)_iter.next(); - if (!RFC3280CertPathUtilities.ANY_POLICY.equals(_c_node.getValidPolicy())) + if (!ANY_POLICY.equals(_c_node.getValidPolicy())) { _validPolicyNodeSet.add(_c_node); } } + + // TODO[pkix] break if there can only be one ANY_POLICY node at this depth? (use findValidPolicy) } } } @@ -2497,27 +2425,10 @@ else if (CertPathValidatorUtilities.isAnyPolicy(userInitialPolicySet)) // (g) // // (g) (iii) 4 // - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = CertPathValidatorUtilities.removePolicyNode(validPolicyTree, policyNodes, - node); - } - } - } - } + validPolicyTree = CertPathValidatorUtilities.removeChildlessPolicyNodes(validPolicyTree, policyNodes, n); intersection = validPolicyTree; } return intersection; } - } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLEntryObject.java b/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLEntryObject.java index bbfacab4cb..a253aeaedd 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLEntryObject.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLEntryObject.java @@ -15,6 +15,7 @@ import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.CRLReason; @@ -77,9 +78,9 @@ public X509CRLEntryObject( */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); + Extensions extensions = c.getExtensions(); - return extns != null && !extns.isEmpty(); + return extensions != null && extensions.hasAnyCriticalExtensions(); } private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) @@ -89,15 +90,15 @@ private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCert return null; } - Extension ext = getExtension(Extension.certificateIssuer); - if (ext == null) + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), Extension.certificateIssuer); + if (extValue == null) { return previousCertificateIssuer; } try { - GeneralName[] names = GeneralNames.getInstance(ext.getParsedValue()).getNames(); + GeneralName[] names = GeneralNames.getInstance(extValue.getOctets()).getNames(); for (int i = 0; i < names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) @@ -165,35 +166,9 @@ public Set getNonCriticalExtensionOIDs() return getExtensionOIDs(false); } - private Extension getExtension(ASN1ObjectIdentifier oid) - { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - return exts.getExtension(oid); - } - - return null; - } - public byte[] getExtensionValue(String oid) { - Extension ext = getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } /** diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java b/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java index 5b32a13225..44e102edde 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java @@ -41,7 +41,9 @@ import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.IssuingDistributionPoint; import org.bouncycastle.asn1.x509.TBSCertList; +import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.jce.X509Principal; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; @@ -108,30 +110,41 @@ public X509CRLObject( } } - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) + if (getVersion() == 2) { - return false; - } + Extensions extensions = c.getExtensions(); + if (extensions != null) + { + Enumeration e = extensions.oids(); + while (e.hasMoreElements()) + { + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); + if (Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid)) + { + continue; + } - return !extns.isEmpty(); + Extension ext = extensions.getExtension(oid); + if (ext.isCritical()) + { + return true; + } + } + } + } + + return false; } private Set getExtensionOIDs(boolean critical) { if (this.getVersion() == 2) { - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -168,26 +181,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public byte[] getEncoded() @@ -304,14 +298,11 @@ public Date getThisUpdate() public Date getNextUpdate() { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } + Time nextUpdate = c.getNextUpdate(); - return null; + return null == nextUpdate ? null : nextUpdate.getDate(); } - + private Set loadCRLEntries() { Set entrySet = new HashSet(); @@ -407,16 +398,7 @@ public String getSigAlgOID() public byte[] getSigAlgParams() { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; + return Arrays.clone(sigAlgParams); } /** @@ -458,7 +440,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/X509CertificateObject.java b/prov/src/main/java/org/bouncycastle/jce/provider/X509CertificateObject.java index 6d6994abea..90ca8d730a 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/X509CertificateObject.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/X509CertificateObject.java @@ -38,6 +38,7 @@ import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1String; @@ -87,7 +88,7 @@ public X509CertificateObject( try { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); + byte[] bytes = getExtensionOctets(c, Extension.basicConstraints); if (bytes != null) { @@ -101,7 +102,7 @@ public X509CertificateObject( try { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); + byte[] bytes = getExtensionOctets(c, Extension.keyUsage); if (bytes != null) { ASN1BitString bits = ASN1BitString.getInstance(ASN1Primitive.fromByteArray(bytes)); @@ -333,32 +334,29 @@ public boolean[] getKeyUsage() public List getExtendedKeyUsage() throws CertificateParsingException { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); + byte[] extOctets = getExtensionOctets(c, Extension.extendedKeyUsage); + if (null == extOctets) + { + return null; + } - if (bytes != null) + try { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); + ASN1Sequence seq = ASN1Sequence.getInstance(extOctets); - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) + List list = new ArrayList(); + for (int i = 0; i != seq.size(); i++) { - throw new CertificateParsingException("error processing extended key usage extension"); + list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); } + return Collections.unmodifiableList(list); + } + catch (Exception e) + { + throw new CertificateParsingException("error processing extended key usage extension"); } - - return null; } - + public int getBasicConstraints() { if (basicConstraints == null || !basicConstraints.isCA()) @@ -378,13 +376,13 @@ public int getBasicConstraints() public Collection getSubjectAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); + return getAlternativeNames(c, Extension.subjectAlternativeName); } public Collection getIssuerAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); + return getAlternativeNames(c, Extension.issuerAlternativeName); } public Set getCriticalExtensionOIDs() @@ -392,7 +390,7 @@ public Set getCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -416,44 +414,9 @@ public Set getCriticalExtensionOIDs() return null; } - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - public byte[] getExtensionValue(String oid) { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public Set getNonCriticalExtensionOIDs() @@ -461,7 +424,7 @@ public Set getNonCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -487,36 +450,32 @@ public Set getNonCriticalExtensionOIDs() public boolean hasUnsupportedCriticalExtension() { - if (this.getVersion() == 3) + if (getVersion() == 3) { - Extensions extensions = c.getTBSCertificate().getExtensions(); - + Extensions extensions = c.getExtensions(); if (extensions != null) { - Enumeration e = extensions.oids(); - + Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) + + if (Extension.keyUsage.equals(oid) || + Extension.certificatePolicies.equals(oid) || + Extension.policyMappings.equals(oid) || + Extension.inhibitAnyPolicy.equals(oid) || + Extension.cRLDistributionPoints.equals(oid) || + Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid) || + Extension.policyConstraints.equals(oid) || + Extension.basicConstraints.equals(oid) || + Extension.subjectAlternativeName.equals(oid) || + Extension.nameConstraints.equals(oid)) { continue; } - Extension ext = extensions.getExtension(oid); - + Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { return true; @@ -628,6 +587,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public String toString() { StringBuffer buf = new StringBuffer(); @@ -657,7 +626,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -842,17 +811,18 @@ private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) return id1.getParameters().equals(id2.getParameters()); } - private static Collection getAlternativeNames(byte[] extVal) + private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) throws CertificateParsingException { - if (extVal == null) + byte[] extOctets = getExtensionOctets(c, oid); + if (extOctets == null) { return null; } try { Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); + Enumeration it = ASN1Sequence.getInstance(extOctets).getObjects(); while (it.hasMoreElements()) { GeneralName genName = GeneralName.getInstance(it.nextElement()); @@ -906,4 +876,11 @@ private static Collection getAlternativeNames(byte[] extVal) throw new CertificateParsingException(e.getMessage()); } } + + private static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) + { + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); + + return extValue == null ? null : extValue.getOctets(); + } } diff --git a/prov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java b/prov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java index 8f57457418..572eba6122 100644 --- a/prov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java +++ b/prov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java @@ -10,9 +10,8 @@ import java.security.spec.PSSParameterSpec; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; @@ -20,22 +19,49 @@ import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; class X509SignatureUtil { - private static final ASN1Null derNull = DERNull.INSTANCE; - - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) + static byte[] getExtensionValue(Extensions extensions, String oid) + { + if (oid != null) + { + ASN1ObjectIdentifier asn1Oid = ASN1ObjectIdentifier.tryFromID(oid); + if (asn1Oid != null) + { + ASN1OctetString extValue = Extensions.getExtensionValue(extensions, asn1Oid); + if (null != extValue) + { + try + { + return extValue.getEncoded(); + } + catch (Exception e) + { + throw new IllegalStateException("error parsing " + e.toString()); + } + } + } + } + return null; + } + + private static boolean isAbsentOrEmptyParameters(ASN1Encodable parameters) + { + return parameters == null || DERNull.INSTANCE.equals(parameters); + } + + static void setSignatureParameters(Signature signature, ASN1Encodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { - if (params != null && !derNull.equals(params)) + if (!isAbsentOrEmptyParameters(params)) { - AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider()); - + String sigAlgName = signature.getAlgorithm(); + AlgorithmParameters sigParams = AlgorithmParameters.getInstance(sigAlgName, signature.getProvider()); + try { sigParams.init(params.toASN1Primitive().getEncoded()); @@ -44,8 +70,8 @@ static void setSignatureParameters( { throw new SignatureException("IOException decoding parameters: " + e.getMessage()); } - - if (signature.getAlgorithm().endsWith("MGF1")) + + if (sigAlgName.endsWith("MGF1")) { try { @@ -58,31 +84,31 @@ static void setSignatureParameters( } } } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) + + static String getSignatureName(AlgorithmIdentifier sigAlgId) { + ASN1ObjectIdentifier sigAlgOid = sigAlgId.getAlgorithm(); ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) + + if (!isAbsentOrEmptyParameters(params)) { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) + if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgOid)) { RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - + return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) + if (X9ObjectIdentifiers.ecdsa_with_SHA2.equals(sigAlgOid)) { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName(ASN1ObjectIdentifier.getInstance(ecDsaParams.getObjectAt(0))) + "withECDSA"; + AlgorithmIdentifier ecDsaParams = AlgorithmIdentifier.getInstance(params); + + return getDigestAlgName(ecDsaParams.getAlgorithm()) + "withECDSA"; } } - return sigAlgId.getAlgorithm().getId(); + return sigAlgOid.getId(); } - + /** * Return the digest algorithm using one of the standard JCA string * representations rather the the algorithm identifier (if possible). diff --git a/prov/src/main/java/org/bouncycastle/jce/spec/package-info.java b/prov/src/main/java/org/bouncycastle/jce/spec/package-info.java new file mode 100644 index 0000000000..71202ae648 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/jce/spec/package-info.java @@ -0,0 +1,4 @@ +/** + * Parameter specifications for supporting El Gamal, and Elliptic Curve. + */ +package org.bouncycastle.jce.spec; diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/MayoKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/MayoKey.java new file mode 100644 index 0000000000..efe8e2fb9d --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/MayoKey.java @@ -0,0 +1,16 @@ +package org.bouncycastle.pqc.jcajce.interfaces; + +import java.security.Key; + +import org.bouncycastle.pqc.jcajce.spec.MayoParameterSpec; + +public interface MayoKey + extends Key +{ + /** + * Return the parameters for this key. + * + * @return a MayoParameterSpec + */ + MayoParameterSpec getParameterSpec(); +} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/QTESLAKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/QTESLAKey.java deleted file mode 100644 index c6fc80f917..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/QTESLAKey.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bouncycastle.pqc.jcajce.interfaces; - -import org.bouncycastle.pqc.jcajce.spec.QTESLAParameterSpec; - -/** - * Base interface for a qTESLA key. - */ -public interface QTESLAKey -{ - /** - * Return the parameters for this key - in this case the security category. - * - * @return a QTESLAParameterSpec - */ - QTESLAParameterSpec getParams(); -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowKey.java deleted file mode 100644 index 827b2f4ddd..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowKey.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bouncycastle.pqc.jcajce.interfaces; - -import java.security.Key; - -import org.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; - -public interface RainbowKey - extends Key -{ - /** - * Return the parameters for this key. - * - * @return a RainbowParameterSpec - */ - RainbowParameterSpec getParameterSpec(); -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowPrivateKey.java deleted file mode 100644 index a60f912d5d..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowPrivateKey.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bouncycastle.pqc.jcajce.interfaces; - -import java.security.PrivateKey; - -public interface RainbowPrivateKey - extends PrivateKey, RainbowKey -{ - /** - * Return the public key corresponding to this private key. - * - * @return a Rainbow Public Key - */ - RainbowPublicKey getPublicKey(); -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowPublicKey.java deleted file mode 100644 index 61dcce91a9..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/RainbowPublicKey.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bouncycastle.pqc.jcajce.interfaces; - -import java.security.PublicKey; - -public interface RainbowPublicKey - extends PublicKey, RainbowKey -{ - -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/SnovaKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/SnovaKey.java new file mode 100644 index 0000000000..0615e1acc7 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/interfaces/SnovaKey.java @@ -0,0 +1,16 @@ +package org.bouncycastle.pqc.jcajce.interfaces; + +import java.security.Key; + +import org.bouncycastle.pqc.jcajce.spec.SnovaParameterSpec; + +public interface SnovaKey + extends Key +{ + /** + * Return the parameters for this key. + * + * @return a SnovaParameterSpec + */ + SnovaParameterSpec getParameterSpec(); +} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/BouncyCastlePQCProvider.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/BouncyCastlePQCProvider.java index 999464e50a..17fe0229d5 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/BouncyCastlePQCProvider.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/BouncyCastlePQCProvider.java @@ -22,7 +22,7 @@ public class BouncyCastlePQCProvider extends Provider implements ConfigurableProvider { - private static String info = "BouncyCastle Post-Quantum Security Provider v1.78.1"; + private static String info = "BouncyCastle Post-Quantum Security Provider v1.81"; public static String PROVIDER_NAME = "BCPQC"; @@ -32,15 +32,16 @@ public class BouncyCastlePQCProvider private static final Map keyInfoConverters = new HashMap(); /* - * Configurable symmetric ciphers - */ + * Configurable symmetric ciphers + */ private static final String ALGORITHM_PACKAGE = "org.bouncycastle.pqc.jcajce.provider."; private static final String[] ALGORITHMS = { //"Rainbow", "McEliece", "SPHINCS", "LMS", "NH", "XMSS", "SPHINCSPlus", "CMCE", "Frodo", "SABER", "Picnic", "NTRU", "Falcon", "Kyber", - "Dilithium", "NTRUPrime", "BIKE", "HQC", "Rainbow" + "Dilithium", "NTRUPrime", "BIKE", "HQC", "Rainbow", + "Mayo", "Snova" }; /** @@ -50,7 +51,7 @@ public class BouncyCastlePQCProvider */ public BouncyCastlePQCProvider() { - super(PROVIDER_NAME, 1.7801, info); + super(PROVIDER_NAME, 1.81, info); AccessController.doPrivileged(new PrivilegedAction() { @@ -117,7 +118,7 @@ public void addAlgorithm(String key, String value, Map attribute addAttributes(key, attributes); } - public void addAlgorithm(String type, ASN1ObjectIdentifier oid, String className) + public void addAlgorithm(String type, ASN1ObjectIdentifier oid, String className) { if (!containsKey(type + "." + className)) { @@ -150,7 +151,7 @@ public AsymmetricKeyInfoConverter getKeyInfoConverter(ASN1ObjectIdentifier oid) public void addAttributes(String key, Map attributeMap) { - for (Iterator it = attributeMap.keySet().iterator(); it.hasNext();) + for (Iterator it = attributeMap.keySet().iterator(); it.hasNext(); ) { String attributeName = (String)it.next(); String attributeKey = key + " " + attributeName; diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Falcon.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Falcon.java index 0af7244a1a..c8e56d21ee 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Falcon.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Falcon.java @@ -3,7 +3,6 @@ import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; import org.bouncycastle.pqc.jcajce.provider.falcon.FalconKeyFactorySpi; public class Falcon diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/HQC.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/HQC.java index 6492ad122a..882e9a2ee2 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/HQC.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/HQC.java @@ -20,13 +20,26 @@ public Mappings() public void configure(ConfigurableProvider provider) { provider.addAlgorithm("KeyFactory.HQC", PREFIX + "HQCKeyFactorySpi"); + provider.addAlgorithm("Alg.Alias.KeyFactory.HQC", "HQC"); + addKeyFactoryAlgorithm(provider, "HQC128", PREFIX + "HQCKeyFactorySpi$HQC128", BCObjectIdentifiers.hqc128, new HQCKeyFactorySpi.HQC128()); + addKeyFactoryAlgorithm(provider, "HQC192", PREFIX + "HQCKeyFactorySpi$HQC192", BCObjectIdentifiers.hqc192, new HQCKeyFactorySpi.HQC192()); + addKeyFactoryAlgorithm(provider, "HQC256", PREFIX + "HQCKeyFactorySpi$HQC256", BCObjectIdentifiers.hqc256, new HQCKeyFactorySpi.HQC256()); + provider.addAlgorithm("KeyPairGenerator.HQC", PREFIX + "HQCKeyPairGeneratorSpi"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.HQC", "HQC"); + addKeyPairGeneratorAlgorithm(provider, "HQC128", PREFIX + "HQCKeyPairGeneratorSpi$HQC128", BCObjectIdentifiers.hqc128); + addKeyPairGeneratorAlgorithm(provider, "HQC192", PREFIX + "HQCKeyPairGeneratorSpi$HQC192", BCObjectIdentifiers.hqc192); + addKeyPairGeneratorAlgorithm(provider, "HQC256", PREFIX + "HQCKeyPairGeneratorSpi$HQC256", BCObjectIdentifiers.hqc256); provider.addAlgorithm("KeyGenerator.HQC", PREFIX + "HQCKeyGeneratorSpi"); + addKeyGeneratorAlgorithm(provider, "HQC128", PREFIX + "HQCKeyGeneratorSpi$HQC128", BCObjectIdentifiers.hqc128); + addKeyGeneratorAlgorithm(provider, "HQC192", PREFIX + "HQCKeyGeneratorSpi$HQC192", BCObjectIdentifiers.hqc192); + addKeyGeneratorAlgorithm(provider, "HQC256", PREFIX + "HQCKeyGeneratorSpi$HQC256", BCObjectIdentifiers.hqc256); AsymmetricKeyInfoConverter keyFact = new HQCKeyFactorySpi(); provider.addAlgorithm("Cipher.HQC", PREFIX + "HQCCipherSpi$Base"); + provider.addAlgorithm("Alg.Alias.Cipher.HQC", "HQC"); provider.addAlgorithm("Alg.Alias.Cipher." + BCObjectIdentifiers.pqc_kem_hqc, "HQC"); addCipherAlgorithm(provider, "HQC128", PREFIX + "HQCCipherSpi$HQC128", BCObjectIdentifiers.hqc128); @@ -34,6 +47,10 @@ public void configure(ConfigurableProvider provider) addCipherAlgorithm(provider, "HQC256", PREFIX + "HQCCipherSpi$HQC256", BCObjectIdentifiers.hqc256); registerOid(provider, BCObjectIdentifiers.pqc_kem_hqc, "HQC", keyFact); + provider.addKeyInfoConverter(BCObjectIdentifiers.hqc128, keyFact); + provider.addKeyInfoConverter(BCObjectIdentifiers.hqc192, keyFact); + provider.addKeyInfoConverter(BCObjectIdentifiers.hqc256, keyFact); } } } + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Kyber.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Kyber.java index 24988c4657..d959f51b34 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Kyber.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Kyber.java @@ -1,6 +1,7 @@ package org.bouncycastle.pqc.jcajce.provider; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; @@ -21,31 +22,43 @@ public void configure(ConfigurableProvider provider) { provider.addAlgorithm("KeyFactory.KYBER", PREFIX + "KyberKeyFactorySpi"); - addKeyFactoryAlgorithm(provider, "KYBER512", PREFIX + "KyberKeyFactorySpi$Kyber512", BCObjectIdentifiers.kyber512, new KyberKeyFactorySpi.Kyber512()); - addKeyFactoryAlgorithm(provider, "KYBER768", PREFIX + "KyberKeyFactorySpi$Kyber768", BCObjectIdentifiers.kyber768, new KyberKeyFactorySpi.Kyber768()); - addKeyFactoryAlgorithm(provider, "KYBER1024", PREFIX + "KyberKeyFactorySpi$Kyber1024", BCObjectIdentifiers.kyber1024, new KyberKeyFactorySpi.Kyber1024()); + addKeyFactoryAlgorithm(provider, "ML-KEM-512", PREFIX + "KyberKeyFactorySpi$Kyber512", NISTObjectIdentifiers.id_alg_ml_kem_512, new KyberKeyFactorySpi.Kyber512()); + addKeyFactoryAlgorithm(provider, "ML-KEM-768", PREFIX + "KyberKeyFactorySpi$Kyber768", NISTObjectIdentifiers.id_alg_ml_kem_768, new KyberKeyFactorySpi.Kyber768()); + addKeyFactoryAlgorithm(provider, "ML-KEM-1024", PREFIX + "KyberKeyFactorySpi$Kyber1024", NISTObjectIdentifiers.id_alg_ml_kem_1024, new KyberKeyFactorySpi.Kyber1024()); + provider.addAlgorithm("Alg.Alias.KeyFactory.KYBER512", "ML-KEM-512"); + provider.addAlgorithm("Alg.Alias.KeyFactory.KYBER768", "ML-KEM-768"); + provider.addAlgorithm("Alg.Alias.KeyFactory.KYBER1024", "ML-KEM-1024"); - provider.addAlgorithm("KeyPairGenerator.KYBER", PREFIX + "KyberKeyPairGeneratorSpi"); - - addKeyPairGeneratorAlgorithm(provider, "KYBER512", PREFIX + "KyberKeyPairGeneratorSpi$Kyber512", BCObjectIdentifiers.kyber512); - addKeyPairGeneratorAlgorithm(provider, "KYBER768", PREFIX + "KyberKeyPairGeneratorSpi$Kyber768", BCObjectIdentifiers.kyber768); - addKeyPairGeneratorAlgorithm(provider, "KYBER1024", PREFIX + "KyberKeyPairGeneratorSpi$Kyber1024", BCObjectIdentifiers.kyber1024); + provider.addAlgorithm("KeyPairGenerator.ML-KEM", PREFIX + "KyberKeyPairGeneratorSpi"); + provider.addAlgorithm("KeyPairGenerator.ML-KEM-512", PREFIX + "KyberKeyPairGeneratorSpi$Kyber512"); + provider.addAlgorithm("KeyPairGenerator.ML-KEM-768", PREFIX + "KyberKeyPairGeneratorSpi$Kyber768"); + provider.addAlgorithm("KeyPairGenerator.ML-KEM-1024", PREFIX + "KyberKeyPairGeneratorSpi$Kyber1024"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.KYBER", "ML-KEM"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.KYBER512", "ML-KEM-512"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.KYBER768", "ML-KEM-768"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.KYBER1024", "ML-KEM-1024"); provider.addAlgorithm("KeyGenerator.KYBER", PREFIX + "KyberKeyGeneratorSpi"); - addKeyGeneratorAlgorithm(provider, "KYBER512", PREFIX + "KyberKeyGeneratorSpi$Kyber512", BCObjectIdentifiers.kyber512); - addKeyGeneratorAlgorithm(provider, "KYBER768", PREFIX + "KyberKeyGeneratorSpi$Kyber768", BCObjectIdentifiers.kyber768); - addKeyGeneratorAlgorithm(provider, "KYBER1024", PREFIX + "KyberKeyGeneratorSpi$Kyber1024", BCObjectIdentifiers.kyber1024); + addKeyGeneratorAlgorithm(provider, "ML-KEM-512", PREFIX + "KyberKeyGeneratorSpi$Kyber512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addKeyGeneratorAlgorithm(provider, "ML-KEM-768", PREFIX + "KyberKeyGeneratorSpi$Kyber768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addKeyGeneratorAlgorithm(provider, "ML-KEM-1024", PREFIX + "KyberKeyGeneratorSpi$Kyber1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + provider.addAlgorithm("Alg.Alias.KeyGenerator.KYBER512", "ML-KEM-512"); + provider.addAlgorithm("Alg.Alias.KeyGenerator.KYBER768", "ML-KEM-768"); + provider.addAlgorithm("Alg.Alias.KeyGenerator.KYBER1024", "ML-KEM-1024"); AsymmetricKeyInfoConverter keyFact = new KyberKeyFactorySpi(); provider.addAlgorithm("Cipher.KYBER", PREFIX + "KyberCipherSpi$Base"); provider.addAlgorithm("Alg.Alias.Cipher." + BCObjectIdentifiers.pqc_kem_kyber, "KYBER"); - addCipherAlgorithm(provider, "KYBER512", PREFIX + "KyberCipherSpi$Kyber512", BCObjectIdentifiers.kyber512); - addCipherAlgorithm(provider, "KYBER768", PREFIX + "KyberCipherSpi$Kyber768", BCObjectIdentifiers.kyber768); - addCipherAlgorithm(provider, "KYBER1024", PREFIX + "KyberCipherSpi$Kyber1024", BCObjectIdentifiers.kyber1024); - + addCipherAlgorithm(provider, "ML-KEM-512", PREFIX + "KyberCipherSpi$Kyber512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addCipherAlgorithm(provider, "ML-KEM-768", PREFIX + "KyberCipherSpi$Kyber768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addCipherAlgorithm(provider, "ML-KEM-1024", PREFIX + "KyberCipherSpi$Kyber1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + provider.addAlgorithm("Alg.Alias.Cipher.KYBER512", "ML-KEM-512"); + provider.addAlgorithm("Alg.Alias.Cipher.KYBER768", "ML-KEM-768"); + provider.addAlgorithm("Alg.Alias.Cipher.KYBER1024", "ML-KEM-1024"); + registerOid(provider, BCObjectIdentifiers.pqc_kem_kyber, "KYBER", keyFact); } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Mayo.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Mayo.java new file mode 100644 index 0000000000..ae8669d748 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Mayo.java @@ -0,0 +1,44 @@ +package org.bouncycastle.pqc.jcajce.provider; + +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.pqc.jcajce.provider.mayo.MayoKeyFactorySpi; + +public class Mayo +{ + private static final String PREFIX = "org.bouncycastle.pqc.jcajce.provider.mayo."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.Mayo", PREFIX + "MayoKeyFactorySpi"); + + addKeyFactoryAlgorithm(provider, "MAYO_1", PREFIX + "MayoKeyFactorySpi$Mayo1", BCObjectIdentifiers.mayo1, new MayoKeyFactorySpi.Mayo1()); + addKeyFactoryAlgorithm(provider, "MAYO_2", PREFIX + "MayoKeyFactorySpi$Mayo2", BCObjectIdentifiers.mayo2, new MayoKeyFactorySpi.Mayo2()); + addKeyFactoryAlgorithm(provider, "MAYO_3", PREFIX + "MayoKeyFactorySpi$Mayo3", BCObjectIdentifiers.mayo3, new MayoKeyFactorySpi.Mayo3()); + addKeyFactoryAlgorithm(provider, "MAYO_5", PREFIX + "MayoKeyFactorySpi$Mayo5", BCObjectIdentifiers.mayo5, new MayoKeyFactorySpi.Mayo5()); + + provider.addAlgorithm("KeyPairGenerator.Mayo", PREFIX + "MayoKeyPairGeneratorSpi"); + + addKeyPairGeneratorAlgorithm(provider, "MAYO_1", PREFIX + "MayoKeyPairGeneratorSpi$Mayo1", BCObjectIdentifiers.mayo1); + addKeyPairGeneratorAlgorithm(provider, "MAYO_2", PREFIX + "MayoKeyPairGeneratorSpi$Mayo2", BCObjectIdentifiers.mayo2); + addKeyPairGeneratorAlgorithm(provider, "MAYO_3", PREFIX + "MayoKeyPairGeneratorSpi$Mayo3", BCObjectIdentifiers.mayo3); + addKeyPairGeneratorAlgorithm(provider, "MAYO_5", PREFIX + "MayoKeyPairGeneratorSpi$Mayo5", BCObjectIdentifiers.mayo5); + + addSignatureAlgorithm(provider, "Mayo", PREFIX + "SignatureSpi$Base", BCObjectIdentifiers.mayo); + + addSignatureAlgorithm(provider, "MAYO_1", PREFIX + "SignatureSpi$Mayo1", BCObjectIdentifiers.mayo1); + addSignatureAlgorithm(provider, "MAYO_2", PREFIX + "SignatureSpi$Mayo2", BCObjectIdentifiers.mayo2); + addSignatureAlgorithm(provider, "MAYO_3", PREFIX + "SignatureSpi$Mayo3", BCObjectIdentifiers.mayo3); + addSignatureAlgorithm(provider, "MAYO_5", PREFIX + "SignatureSpi$Mayo5", BCObjectIdentifiers.mayo5); + } + } +} + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Rainbow.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Rainbow.java deleted file mode 100644 index 7c1fcf8012..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Rainbow.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider; - -import org.bouncycastle.asn1.bc.BCObjectIdentifiers; -import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; -import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; -import org.bouncycastle.pqc.jcajce.provider.rainbow.RainbowKeyFactorySpi; - -public class Rainbow -{ - private static final String PREFIX = "org.bouncycastle.pqc.jcajce.provider" + ".rainbow."; - - public static class Mappings - extends AsymmetricAlgorithmProvider - { - public Mappings() - { - } - - public void configure(ConfigurableProvider provider) - { - provider.addAlgorithm("KeyFactory.RAINBOW", PREFIX + "RainbowKeyFactorySpi"); - provider.addAlgorithm("KeyPairGenerator.RAINBOW", PREFIX + "RainbowKeyPairGeneratorSpi"); - - addKeyPairGeneratorAlgorithm(provider, "RAINBOW-III-CLASSIC", PREFIX + "RainbowKeyPairGeneratorSpi$RainbowIIIclassic", BCObjectIdentifiers.rainbow_III_classic); - addKeyPairGeneratorAlgorithm(provider, "RAINBOW-III-CIRCUMZENITHAL", PREFIX + "RainbowKeyPairGeneratorSpi$RainbowIIIcircum", BCObjectIdentifiers.rainbow_III_circumzenithal); - addKeyPairGeneratorAlgorithm(provider, "RAINBOW-III-COMPRESSED", PREFIX + "RainbowKeyPairGeneratorSpi$RainbowIIIcomp", BCObjectIdentifiers.rainbow_III_compressed); - addKeyPairGeneratorAlgorithm(provider, "RAINBOW-V-CLASSIC", PREFIX + "RainbowKeyPairGeneratorSpi$RainbowVclassic", BCObjectIdentifiers.rainbow_V_classic); - addKeyPairGeneratorAlgorithm(provider, "RAINBOW-V-CIRCUMZENITHAL", PREFIX + "RainbowKeyPairGeneratorSpi$RainbowVcircum", BCObjectIdentifiers.rainbow_V_circumzenithal); - addKeyPairGeneratorAlgorithm(provider, "RAINBOW-V-COMPRESSED", PREFIX + "RainbowKeyPairGeneratorSpi$RainbowVcomp", BCObjectIdentifiers.rainbow_V_compressed); - - addSignatureAlgorithm(provider, "RAINBOW", PREFIX + "SignatureSpi$Base", BCObjectIdentifiers.rainbow); - - addSignatureAlgorithm(provider, "RAINBOW-III-CLASSIC", PREFIX + "SignatureSpi$RainbowIIIclassic", BCObjectIdentifiers.rainbow_III_classic); - addSignatureAlgorithm(provider, "RAINBOW-III-CIRCUMZENITHAL", PREFIX + "SignatureSpi$RainbowIIIcircum", BCObjectIdentifiers.rainbow_III_circumzenithal); - addSignatureAlgorithm(provider, "RAINBOW-III-COMPRESSED", PREFIX + "SignatureSpi$RainbowIIIcomp", BCObjectIdentifiers.rainbow_III_compressed); - addSignatureAlgorithm(provider, "RAINBOW-V-CLASSIC", PREFIX + "SignatureSpi$RainbowVclassic", BCObjectIdentifiers.rainbow_V_classic); - addSignatureAlgorithm(provider, "RAINBOW-V-CIRCUMZENITHAL", PREFIX + "SignatureSpi$RainbowVcircum", BCObjectIdentifiers.rainbow_V_circumzenithal); - addSignatureAlgorithm(provider, "RAINBOW-v-COMPRESSED", PREFIX + "SignatureSpi$RainbowVcomp", BCObjectIdentifiers.rainbow_V_compressed); - - AsymmetricKeyInfoConverter keyFact = new RainbowKeyFactorySpi(); - - registerKeyFactoryOid(provider, BCObjectIdentifiers.rainbow_III_classic, "RAINBOW", keyFact); - registerKeyFactoryOid(provider, BCObjectIdentifiers.rainbow_III_circumzenithal, "RAINBOW", keyFact); - registerKeyFactoryOid(provider, BCObjectIdentifiers.rainbow_III_compressed, "RAINBOW", keyFact); - registerKeyFactoryOid(provider, BCObjectIdentifiers.rainbow_V_classic, "RAINBOW", keyFact); - registerKeyFactoryOid(provider, BCObjectIdentifiers.rainbow_V_circumzenithal, "RAINBOW", keyFact); - registerKeyFactoryOid(provider, BCObjectIdentifiers.rainbow_V_compressed, "RAINBOW", keyFact); - } - } -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/SPHINCSPlus.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/SPHINCSPlus.java index 90e8f91e5a..8ef9b9e45e 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/SPHINCSPlus.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/SPHINCSPlus.java @@ -40,7 +40,6 @@ public void configure(ConfigurableProvider provider) addSignatureAlgorithm(provider, "SPHINCSPLUS", PREFIX + "SignatureSpi$Direct", BCObjectIdentifiers.sphincsPlus); - addSignatureAlias(provider, "SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus_sha2_128s_r3); addSignatureAlias(provider, "SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus_sha2_128f_r3); addSignatureAlias(provider, "SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus_shake_128s_r3); addSignatureAlias(provider, "SPHINCSPLUS", BCObjectIdentifiers.sphincsPlus_shake_128f_r3); @@ -82,6 +81,7 @@ public void configure(ConfigurableProvider provider) AsymmetricKeyInfoConverter keyFact = new SPHINCSPlusKeyFactorySpi(); registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus, "SPHINCSPLUS", keyFact); + registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus_sha2_128s_r3, "SPHINCSPLUS", keyFact); registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus_sha2_128f_r3, "SPHINCSPLUS", keyFact); registerKeyFactoryOid(provider, BCObjectIdentifiers.sphincsPlus_shake_128s_r3, "SPHINCSPLUS", keyFact); diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Snova.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Snova.java new file mode 100644 index 0000000000..4ad9ea91e8 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/Snova.java @@ -0,0 +1,164 @@ +package org.bouncycastle.pqc.jcajce.provider; + +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.pqc.jcajce.provider.snova.SnovaKeyFactorySpi; + +public class Snova +{ + private static final String PREFIX = "org.bouncycastle.pqc.jcajce.provider.snova."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.Snova", PREFIX + "SnovaKeyFactorySpi"); + + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_4_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_4_SSK", BCObjectIdentifiers.snova_24_5_4_ssk, new SnovaKeyFactorySpi.SNOVA_24_5_4_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_4_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_4_ESK", BCObjectIdentifiers.snova_24_5_4_esk, new SnovaKeyFactorySpi.SNOVA_24_5_4_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_4_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_4_SHAKE_SSK", BCObjectIdentifiers.snova_24_5_4_shake_ssk, new SnovaKeyFactorySpi.SNOVA_24_5_4_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_4_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_4_SHAKE_ESK", BCObjectIdentifiers.snova_24_5_4_shake_esk, new SnovaKeyFactorySpi.SNOVA_24_5_4_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_5_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_5_SSK", BCObjectIdentifiers.snova_24_5_5_ssk, new SnovaKeyFactorySpi.SNOVA_24_5_5_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_5_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_5_ESK", BCObjectIdentifiers.snova_24_5_5_esk, new SnovaKeyFactorySpi.SNOVA_24_5_5_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_5_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_5_SHAKE_SSK", BCObjectIdentifiers.snova_24_5_5_shake_ssk, new SnovaKeyFactorySpi.SNOVA_24_5_5_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_24_5_5_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_24_5_5_SHAKE_ESK", BCObjectIdentifiers.snova_24_5_5_shake_esk, new SnovaKeyFactorySpi.SNOVA_24_5_5_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_25_8_3_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_25_8_3_SSK", BCObjectIdentifiers.snova_25_8_3_ssk, new SnovaKeyFactorySpi.SNOVA_25_8_3_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_25_8_3_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_25_8_3_ESK", BCObjectIdentifiers.snova_25_8_3_esk, new SnovaKeyFactorySpi.SNOVA_25_8_3_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_25_8_3_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_25_8_3_SHAKE_SSK", BCObjectIdentifiers.snova_25_8_3_shake_ssk, new SnovaKeyFactorySpi.SNOVA_25_8_3_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_25_8_3_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_25_8_3_SHAKE_ESK", BCObjectIdentifiers.snova_25_8_3_shake_esk, new SnovaKeyFactorySpi.SNOVA_25_8_3_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_29_6_5_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_29_6_5_SSK", BCObjectIdentifiers.snova_29_6_5_ssk, new SnovaKeyFactorySpi.SNOVA_29_6_5_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_29_6_5_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_29_6_5_ESK", BCObjectIdentifiers.snova_29_6_5_esk, new SnovaKeyFactorySpi.SNOVA_29_6_5_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_29_6_5_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_29_6_5_SHAKE_SSK", BCObjectIdentifiers.snova_29_6_5_shake_ssk, new SnovaKeyFactorySpi.SNOVA_29_6_5_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_29_6_5_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_29_6_5_SHAKE_ESK", BCObjectIdentifiers.snova_29_6_5_shake_esk, new SnovaKeyFactorySpi.SNOVA_29_6_5_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_8_4_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_8_4_SSK", BCObjectIdentifiers.snova_37_8_4_ssk, new SnovaKeyFactorySpi.SNOVA_37_8_4_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_8_4_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_8_4_ESK", BCObjectIdentifiers.snova_37_8_4_esk, new SnovaKeyFactorySpi.SNOVA_37_8_4_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_8_4_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_8_4_SHAKE_SSK", BCObjectIdentifiers.snova_37_8_4_shake_ssk, new SnovaKeyFactorySpi.SNOVA_37_8_4_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_8_4_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_8_4_SHAKE_ESK", BCObjectIdentifiers.snova_37_8_4_shake_esk, new SnovaKeyFactorySpi.SNOVA_37_8_4_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_17_2_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_17_2_SSK", BCObjectIdentifiers.snova_37_17_2_ssk, new SnovaKeyFactorySpi.SNOVA_37_17_2_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_17_2_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_17_2_ESK", BCObjectIdentifiers.snova_37_17_2_esk, new SnovaKeyFactorySpi.SNOVA_37_17_2_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_17_2_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_17_2_SHAKE_SSK", BCObjectIdentifiers.snova_37_17_2_shake_ssk, new SnovaKeyFactorySpi.SNOVA_37_17_2_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_37_17_2_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_37_17_2_SHAKE_ESK", BCObjectIdentifiers.snova_37_17_2_shake_esk, new SnovaKeyFactorySpi.SNOVA_37_17_2_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_49_11_3_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_49_11_3_SSK", BCObjectIdentifiers.snova_49_11_3_ssk, new SnovaKeyFactorySpi.SNOVA_49_11_3_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_49_11_3_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_49_11_3_ESK", BCObjectIdentifiers.snova_49_11_3_esk, new SnovaKeyFactorySpi.SNOVA_49_11_3_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_49_11_3_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_49_11_3_SHAKE_SSK", BCObjectIdentifiers.snova_49_11_3_shake_ssk, new SnovaKeyFactorySpi.SNOVA_49_11_3_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_49_11_3_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_49_11_3_SHAKE_ESK", BCObjectIdentifiers.snova_49_11_3_shake_esk, new SnovaKeyFactorySpi.SNOVA_49_11_3_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_56_25_2_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_56_25_2_SSK", BCObjectIdentifiers.snova_56_25_2_ssk, new SnovaKeyFactorySpi.SNOVA_56_25_2_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_56_25_2_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_56_25_2_ESK", BCObjectIdentifiers.snova_56_25_2_esk, new SnovaKeyFactorySpi.SNOVA_56_25_2_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_56_25_2_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_56_25_2_SHAKE_SSK", BCObjectIdentifiers.snova_56_25_2_shake_ssk, new SnovaKeyFactorySpi.SNOVA_56_25_2_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_56_25_2_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_56_25_2_SHAKE_ESK", BCObjectIdentifiers.snova_56_25_2_shake_esk, new SnovaKeyFactorySpi.SNOVA_56_25_2_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_60_10_4_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_60_10_4_SSK", BCObjectIdentifiers.snova_60_10_4_ssk, new SnovaKeyFactorySpi.SNOVA_60_10_4_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_60_10_4_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_60_10_4_ESK", BCObjectIdentifiers.snova_60_10_4_esk, new SnovaKeyFactorySpi.SNOVA_60_10_4_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_60_10_4_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_60_10_4_SHAKE_SSK", BCObjectIdentifiers.snova_60_10_4_shake_ssk, new SnovaKeyFactorySpi.SNOVA_60_10_4_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_60_10_4_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_60_10_4_SHAKE_ESK", BCObjectIdentifiers.snova_60_10_4_shake_esk, new SnovaKeyFactorySpi.SNOVA_60_10_4_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_66_15_3_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_66_15_3_SSK", BCObjectIdentifiers.snova_66_15_3_ssk, new SnovaKeyFactorySpi.SNOVA_66_15_3_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_66_15_3_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_66_15_3_ESK", BCObjectIdentifiers.snova_66_15_3_esk, new SnovaKeyFactorySpi.SNOVA_66_15_3_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_66_15_3_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_66_15_3_SHAKE_SSK", BCObjectIdentifiers.snova_66_15_3_shake_ssk, new SnovaKeyFactorySpi.SNOVA_66_15_3_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_66_15_3_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_66_15_3_SHAKE_ESK", BCObjectIdentifiers.snova_66_15_3_shake_esk, new SnovaKeyFactorySpi.SNOVA_66_15_3_SHAKE_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_75_33_2_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_75_33_2_SSK", BCObjectIdentifiers.snova_75_33_2_ssk, new SnovaKeyFactorySpi.SNOVA_75_33_2_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_75_33_2_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_75_33_2_ESK", BCObjectIdentifiers.snova_75_33_2_esk, new SnovaKeyFactorySpi.SNOVA_75_33_2_ESK()); + addKeyFactoryAlgorithm(provider, "SNOVA_75_33_2_SHAKE_SSK", PREFIX + "SnovaKeyFactorySpi$SNOVA_75_33_2_SHAKE_SSK", BCObjectIdentifiers.snova_75_33_2_shake_ssk, new SnovaKeyFactorySpi.SNOVA_75_33_2_SHAKE_SSK()); + addKeyFactoryAlgorithm(provider, "SNOVA_75_33_2_SHAKE_ESK", PREFIX + "SnovaKeyFactorySpi$SNOVA_75_33_2_SHAKE_ESK", BCObjectIdentifiers.snova_75_33_2_shake_esk, new SnovaKeyFactorySpi.SNOVA_75_33_2_SHAKE_ESK()); + + + provider.addAlgorithm("KeyPairGenerator.Snova", PREFIX + "SnovaKeyPairGeneratorSpi"); + + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_4_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_4_SSK", BCObjectIdentifiers.snova_24_5_4_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_4_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_4_ESK", BCObjectIdentifiers.snova_24_5_4_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_4_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_4_SHAKE_SSK", BCObjectIdentifiers.snova_24_5_4_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_4_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_4_SHAKE_ESK", BCObjectIdentifiers.snova_24_5_4_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_5_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_5_SSK", BCObjectIdentifiers.snova_24_5_5_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_5_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_5_ESK", BCObjectIdentifiers.snova_24_5_5_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_5_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_5_SHAKE_SSK", BCObjectIdentifiers.snova_24_5_5_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_24_5_5_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_24_5_5_SHAKE_ESK", BCObjectIdentifiers.snova_24_5_5_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_25_8_3_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_25_8_3_SSK", BCObjectIdentifiers.snova_25_8_3_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_25_8_3_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_25_8_3_ESK", BCObjectIdentifiers.snova_25_8_3_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_25_8_3_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_25_8_3_SHAKE_SSK", BCObjectIdentifiers.snova_25_8_3_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_25_8_3_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_25_8_3_SHAKE_ESK", BCObjectIdentifiers.snova_25_8_3_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_29_6_5_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_29_6_5_SSK", BCObjectIdentifiers.snova_29_6_5_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_29_6_5_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_29_6_5_ESK", BCObjectIdentifiers.snova_29_6_5_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_29_6_5_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_29_6_5_SHAKE_SSK", BCObjectIdentifiers.snova_29_6_5_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_29_6_5_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_29_6_5_SHAKE_ESK", BCObjectIdentifiers.snova_29_6_5_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_8_4_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_8_4_SSK", BCObjectIdentifiers.snova_37_8_4_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_8_4_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_8_4_ESK", BCObjectIdentifiers.snova_37_8_4_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_8_4_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_8_4_SHAKE_SSK", BCObjectIdentifiers.snova_37_8_4_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_8_4_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_8_4_SHAKE_ESK", BCObjectIdentifiers.snova_37_8_4_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_17_2_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_17_2_SSK", BCObjectIdentifiers.snova_37_17_2_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_17_2_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_17_2_ESK", BCObjectIdentifiers.snova_37_17_2_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_17_2_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_17_2_SHAKE_SSK", BCObjectIdentifiers.snova_37_17_2_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_37_17_2_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_37_17_2_SHAKE_ESK", BCObjectIdentifiers.snova_37_17_2_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_49_11_3_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_49_11_3_SSK", BCObjectIdentifiers.snova_49_11_3_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_49_11_3_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_49_11_3_ESK", BCObjectIdentifiers.snova_49_11_3_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_49_11_3_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_49_11_3_SHAKE_SSK", BCObjectIdentifiers.snova_49_11_3_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_49_11_3_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_49_11_3_SHAKE_ESK", BCObjectIdentifiers.snova_49_11_3_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_56_25_2_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_56_25_2_SSK", BCObjectIdentifiers.snova_56_25_2_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_56_25_2_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_56_25_2_ESK", BCObjectIdentifiers.snova_56_25_2_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_56_25_2_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_56_25_2_SHAKE_SSK", BCObjectIdentifiers.snova_56_25_2_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_56_25_2_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_56_25_2_SHAKE_ESK", BCObjectIdentifiers.snova_56_25_2_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_60_10_4_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_60_10_4_SSK", BCObjectIdentifiers.snova_60_10_4_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_60_10_4_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_60_10_4_ESK", BCObjectIdentifiers.snova_60_10_4_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_60_10_4_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_60_10_4_SHAKE_SSK", BCObjectIdentifiers.snova_60_10_4_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_60_10_4_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_60_10_4_SHAKE_ESK", BCObjectIdentifiers.snova_60_10_4_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_66_15_3_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_66_15_3_SSK", BCObjectIdentifiers.snova_66_15_3_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_66_15_3_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_66_15_3_ESK", BCObjectIdentifiers.snova_66_15_3_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_66_15_3_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_66_15_3_SHAKE_SSK", BCObjectIdentifiers.snova_66_15_3_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_66_15_3_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_66_15_3_SHAKE_ESK", BCObjectIdentifiers.snova_66_15_3_shake_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_75_33_2_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_75_33_2_SSK", BCObjectIdentifiers.snova_75_33_2_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_75_33_2_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_75_33_2_ESK", BCObjectIdentifiers.snova_75_33_2_esk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_75_33_2_SHAKE_SSK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_75_33_2_SHAKE_SSK", BCObjectIdentifiers.snova_75_33_2_shake_ssk); + addKeyPairGeneratorAlgorithm(provider, "SNOVA_75_33_2_SHAKE_ESK", PREFIX + "SnovaKeyPairGeneratorSpi$SNOVA_75_33_2_SHAKE_ESK", BCObjectIdentifiers.snova_75_33_2_shake_esk); + + addSignatureAlgorithm(provider, "Snova", PREFIX + "SignatureSpi$Base", BCObjectIdentifiers.snova); + + addSignatureAlgorithm(provider, "SNOVA_24_5_4_SSK", PREFIX + "SignatureSpi$SNOVA_24_5_4_SSK", BCObjectIdentifiers.snova_24_5_4_ssk); + addSignatureAlgorithm(provider, "SNOVA_24_5_4_ESK", PREFIX + "SignatureSpi$SNOVA_24_5_4_ESK", BCObjectIdentifiers.snova_24_5_4_esk); + addSignatureAlgorithm(provider, "SNOVA_24_5_4_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_24_5_4_SHAKE_SSK", BCObjectIdentifiers.snova_24_5_4_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_24_5_4_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_24_5_4_SHAKE_ESK", BCObjectIdentifiers.snova_24_5_4_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_24_5_5_SSK", PREFIX + "SignatureSpi$SNOVA_24_5_5_SSK", BCObjectIdentifiers.snova_24_5_5_ssk); + addSignatureAlgorithm(provider, "SNOVA_24_5_5_ESK", PREFIX + "SignatureSpi$SNOVA_24_5_5_ESK", BCObjectIdentifiers.snova_24_5_5_esk); + addSignatureAlgorithm(provider, "SNOVA_24_5_5_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_24_5_5_SHAKE_SSK", BCObjectIdentifiers.snova_24_5_5_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_24_5_5_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_24_5_5_SHAKE_ESK", BCObjectIdentifiers.snova_24_5_5_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_25_8_3_SSK", PREFIX + "SignatureSpi$SNOVA_25_8_3_SSK", BCObjectIdentifiers.snova_25_8_3_ssk); + addSignatureAlgorithm(provider, "SNOVA_25_8_3_ESK", PREFIX + "SignatureSpi$SNOVA_25_8_3_ESK", BCObjectIdentifiers.snova_25_8_3_esk); + addSignatureAlgorithm(provider, "SNOVA_25_8_3_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_25_8_3_SHAKE_SSK", BCObjectIdentifiers.snova_25_8_3_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_25_8_3_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_25_8_3_SHAKE_ESK", BCObjectIdentifiers.snova_25_8_3_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_29_6_5_SSK", PREFIX + "SignatureSpi$SNOVA_29_6_5_SSK", BCObjectIdentifiers.snova_29_6_5_ssk); + addSignatureAlgorithm(provider, "SNOVA_29_6_5_ESK", PREFIX + "SignatureSpi$SNOVA_29_6_5_ESK", BCObjectIdentifiers.snova_29_6_5_esk); + addSignatureAlgorithm(provider, "SNOVA_29_6_5_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_29_6_5_SHAKE_SSK", BCObjectIdentifiers.snova_29_6_5_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_29_6_5_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_29_6_5_SHAKE_ESK", BCObjectIdentifiers.snova_29_6_5_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_37_8_4_SSK", PREFIX + "SignatureSpi$SNOVA_37_8_4_SSK", BCObjectIdentifiers.snova_37_8_4_ssk); + addSignatureAlgorithm(provider, "SNOVA_37_8_4_ESK", PREFIX + "SignatureSpi$SNOVA_37_8_4_ESK", BCObjectIdentifiers.snova_37_8_4_esk); + addSignatureAlgorithm(provider, "SNOVA_37_8_4_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_37_8_4_SHAKE_SSK", BCObjectIdentifiers.snova_37_8_4_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_37_8_4_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_37_8_4_SHAKE_ESK", BCObjectIdentifiers.snova_37_8_4_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_37_17_2_SSK", PREFIX + "SignatureSpi$SNOVA_37_17_2_SSK", BCObjectIdentifiers.snova_37_17_2_ssk); + addSignatureAlgorithm(provider, "SNOVA_37_17_2_ESK", PREFIX + "SignatureSpi$SNOVA_37_17_2_ESK", BCObjectIdentifiers.snova_37_17_2_esk); + addSignatureAlgorithm(provider, "SNOVA_37_17_2_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_37_17_2_SHAKE_SSK", BCObjectIdentifiers.snova_37_17_2_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_37_17_2_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_37_17_2_SHAKE_ESK", BCObjectIdentifiers.snova_37_17_2_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_49_11_3_SSK", PREFIX + "SignatureSpi$SNOVA_49_11_3_SSK", BCObjectIdentifiers.snova_49_11_3_ssk); + addSignatureAlgorithm(provider, "SNOVA_49_11_3_ESK", PREFIX + "SignatureSpi$SNOVA_49_11_3_ESK", BCObjectIdentifiers.snova_49_11_3_esk); + addSignatureAlgorithm(provider, "SNOVA_49_11_3_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_49_11_3_SHAKE_SSK", BCObjectIdentifiers.snova_49_11_3_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_49_11_3_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_49_11_3_SHAKE_ESK", BCObjectIdentifiers.snova_49_11_3_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_56_25_2_SSK", PREFIX + "SignatureSpi$SNOVA_56_25_2_SSK", BCObjectIdentifiers.snova_56_25_2_ssk); + addSignatureAlgorithm(provider, "SNOVA_56_25_2_ESK", PREFIX + "SignatureSpi$SNOVA_56_25_2_ESK", BCObjectIdentifiers.snova_56_25_2_esk); + addSignatureAlgorithm(provider, "SNOVA_56_25_2_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_56_25_2_SHAKE_SSK", BCObjectIdentifiers.snova_56_25_2_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_56_25_2_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_56_25_2_SHAKE_ESK", BCObjectIdentifiers.snova_56_25_2_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_60_10_4_SSK", PREFIX + "SignatureSpi$SNOVA_60_10_4_SSK", BCObjectIdentifiers.snova_60_10_4_ssk); + addSignatureAlgorithm(provider, "SNOVA_60_10_4_ESK", PREFIX + "SignatureSpi$SNOVA_60_10_4_ESK", BCObjectIdentifiers.snova_60_10_4_esk); + addSignatureAlgorithm(provider, "SNOVA_60_10_4_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_60_10_4_SHAKE_SSK", BCObjectIdentifiers.snova_60_10_4_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_60_10_4_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_60_10_4_SHAKE_ESK", BCObjectIdentifiers.snova_60_10_4_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_66_15_3_SSK", PREFIX + "SignatureSpi$SNOVA_66_15_3_SSK", BCObjectIdentifiers.snova_66_15_3_ssk); + addSignatureAlgorithm(provider, "SNOVA_66_15_3_ESK", PREFIX + "SignatureSpi$SNOVA_66_15_3_ESK", BCObjectIdentifiers.snova_66_15_3_esk); + addSignatureAlgorithm(provider, "SNOVA_66_15_3_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_66_15_3_SHAKE_SSK", BCObjectIdentifiers.snova_66_15_3_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_66_15_3_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_66_15_3_SHAKE_ESK", BCObjectIdentifiers.snova_66_15_3_shake_esk); + addSignatureAlgorithm(provider, "SNOVA_75_33_2_SSK", PREFIX + "SignatureSpi$SNOVA_75_33_2_SSK", BCObjectIdentifiers.snova_75_33_2_ssk); + addSignatureAlgorithm(provider, "SNOVA_75_33_2_ESK", PREFIX + "SignatureSpi$SNOVA_75_33_2_ESK", BCObjectIdentifiers.snova_75_33_2_esk); + addSignatureAlgorithm(provider, "SNOVA_75_33_2_SHAKE_SSK", PREFIX + "SignatureSpi$SNOVA_75_33_2_SHAKE_SSK", BCObjectIdentifiers.snova_75_33_2_shake_ssk); + addSignatureAlgorithm(provider, "SNOVA_75_33_2_SHAKE_ESK", PREFIX + "SignatureSpi$SNOVA_75_33_2_SHAKE_ESK", BCObjectIdentifiers.snova_75_33_2_shake_esk); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPrivateKey.java index e810a83003..a5868d94ce 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPrivateKey.java @@ -43,7 +43,7 @@ private void init(PrivateKeyInfo keyInfo) } /** - * Compare this SPHINCS-256 private key with another object. + * Compare this CMCE private key with another object. * * @param o the other object * @return the result of the comparison diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPublicKey.java index 386b92a975..0d17b3793d 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPublicKey.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/cmce/BCCMCEPublicKey.java @@ -40,7 +40,7 @@ private void init(SubjectPublicKeyInfo keyInfo) } /** - * Compare this SPHINCS-256 public key with another object. + * Compare this CMCE public key with another object. * * @param o the other object * @return the result of the comparison diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/dilithium/DilithiumKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/dilithium/DilithiumKeyFactorySpi.java index 8b0a3402a9..1ed163c146 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/dilithium/DilithiumKeyFactorySpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/dilithium/DilithiumKeyFactorySpi.java @@ -3,8 +3,6 @@ import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; -import java.security.KeyFactorySpi; -import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; @@ -15,12 +13,9 @@ import java.util.Set; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; -import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; public class DilithiumKeyFactorySpi diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/falcon/FalconKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/falcon/FalconKeyFactorySpi.java index d4f36890a5..58adc178c5 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/falcon/FalconKeyFactorySpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/falcon/FalconKeyFactorySpi.java @@ -17,7 +17,6 @@ import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; public class FalconKeyFactorySpi diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/frodo/FrodoCipherSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/frodo/FrodoCipherSpi.java index f7f65a30a8..2520da5150 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/frodo/FrodoCipherSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/frodo/FrodoCipherSpi.java @@ -27,9 +27,6 @@ import org.bouncycastle.jcajce.spec.KEMParameterSpec; import org.bouncycastle.pqc.crypto.frodo.FrodoKEMExtractor; import org.bouncycastle.pqc.crypto.frodo.FrodoKEMGenerator; -import org.bouncycastle.pqc.crypto.hqc.HQCKEMGenerator; -import org.bouncycastle.pqc.jcajce.provider.hqc.BCHQCPrivateKey; -import org.bouncycastle.pqc.jcajce.provider.hqc.BCHQCPublicKey; import org.bouncycastle.pqc.jcajce.provider.util.WrapUtil; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Exceptions; diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCCipherSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCCipherSpi.java index 2281b93db1..8e51066d8b 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCCipherSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCCipherSpi.java @@ -251,7 +251,7 @@ protected byte[] engineWrap( Wrapper kWrap = WrapUtil.getWrapper(kemParameterSpec.getKeyAlgorithmName()); - KeyParameter keyParameter = new KeyParameter(secEnc.getSecret()); + KeyParameter keyParameter = new KeyParameter(WrapUtil.trimSecret(kemParameterSpec.getKeyAlgorithmName(), secEnc.getSecret())); kWrap.init(true, keyParameter); @@ -296,7 +296,7 @@ protected Key engineUnwrap( Wrapper kWrap = WrapUtil.getWrapper(kemParameterSpec.getKeyAlgorithmName()); - KeyParameter keyParameter = new KeyParameter(secret); + KeyParameter keyParameter = new KeyParameter(WrapUtil.trimSecret(kemParameterSpec.getKeyAlgorithmName(), secret)); Arrays.clear(secret); diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyFactorySpi.java index e3b08b6ada..4a36a31c10 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyFactorySpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyFactorySpi.java @@ -3,23 +3,44 @@ import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; -import java.security.KeyFactorySpi; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; +import java.util.HashSet; +import java.util.Set; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; +import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; public class HQCKeyFactorySpi - extends KeyFactorySpi - implements AsymmetricKeyInfoConverter + extends BaseKeyFactorySpi { + private static final Set keyOids = new HashSet(); + + static + { + keyOids.add(BCObjectIdentifiers.hqc128); + keyOids.add(BCObjectIdentifiers.hqc192); + keyOids.add(BCObjectIdentifiers.hqc256); + } + + public HQCKeyFactorySpi() + { + super(keyOids); + } + + public HQCKeyFactorySpi(ASN1ObjectIdentifier keyOids) + { + super(keyOids); + } + public PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException { @@ -113,4 +134,31 @@ public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) { return new BCHQCPublicKey(keyInfo); } + + public static class HQC128 + extends HQCKeyFactorySpi + { + public HQC128() + { + super(BCObjectIdentifiers.hqc128); + } + } + + public static class HQC192 + extends HQCKeyFactorySpi + { + public HQC192() + { + super(BCObjectIdentifiers.hqc192); + } + } + + public static class HQC256 + extends HQCKeyFactorySpi + { + public HQC256() + { + super(BCObjectIdentifiers.hqc256); + } + } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyGeneratorSpi.java index 87619dd57b..cd0d6e51b7 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyGeneratorSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyGeneratorSpi.java @@ -15,14 +15,27 @@ import org.bouncycastle.jcajce.spec.KEMGenerateSpec; import org.bouncycastle.pqc.crypto.hqc.HQCKEMExtractor; import org.bouncycastle.pqc.crypto.hqc.HQCKEMGenerator; +import org.bouncycastle.pqc.crypto.hqc.HQCParameters; +import org.bouncycastle.pqc.jcajce.spec.HQCParameterSpec; import org.bouncycastle.util.Arrays; public class HQCKeyGeneratorSpi - extends KeyGeneratorSpi + extends KeyGeneratorSpi { private KEMGenerateSpec genSpec; private SecureRandom random; private KEMExtractSpec extSpec; + private HQCParameters hqcParameters; + + public HQCKeyGeneratorSpi() + { + this(null); + } + + public HQCKeyGeneratorSpi(HQCParameters hqcParameters) + { + this.hqcParameters = hqcParameters; + } protected void engineInit(SecureRandom secureRandom) { @@ -30,18 +43,34 @@ protected void engineInit(SecureRandom secureRandom) } protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec, SecureRandom secureRandom) - throws InvalidAlgorithmParameterException + throws InvalidAlgorithmParameterException { this.random = secureRandom; if (algorithmParameterSpec instanceof KEMGenerateSpec) { this.genSpec = (KEMGenerateSpec)algorithmParameterSpec; this.extSpec = null; + if (hqcParameters != null) + { + String canonicalAlgName = HQCParameterSpec.fromName(hqcParameters.getName()).getName(); + if (!canonicalAlgName.equals(genSpec.getPublicKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } } else if (algorithmParameterSpec instanceof KEMExtractSpec) { this.genSpec = null; this.extSpec = (KEMExtractSpec)algorithmParameterSpec; + if (hqcParameters != null) + { + String canonicalAlgName = HQCParameterSpec.fromName(hqcParameters.getName()).getName(); + if (!canonicalAlgName.equals(extSpec.getPrivateKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } } else { @@ -91,4 +120,31 @@ protected SecretKey engineGenerateKey() return rv; } } + + public static class HQC128 + extends HQCKeyGeneratorSpi + { + public HQC128() + { + super(HQCParameters.hqc128); + } + } + + public static class HQC192 + extends HQCKeyGeneratorSpi + { + public HQC192() + { + super(HQCParameters.hqc192); + } + } + + public static class HQC256 + extends HQCKeyGeneratorSpi + { + public HQC256() + { + super(HQCParameters.hqc256); + } + } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyPairGeneratorSpi.java index 989f22714d..2f6624890e 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyPairGeneratorSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKeyPairGeneratorSpi.java @@ -2,6 +2,7 @@ import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.util.HashMap; @@ -19,7 +20,7 @@ import org.bouncycastle.util.Strings; public class HQCKeyPairGeneratorSpi - extends java.security.KeyPairGenerator + extends java.security.KeyPairGenerator { private static Map parameters = new HashMap(); @@ -45,17 +46,22 @@ public HQCKeyPairGeneratorSpi() super("HQC"); } + protected HQCKeyPairGeneratorSpi(HQCParameterSpec paramSpec) + { + super(Strings.toUpperCase(paramSpec.getName())); + } + public void initialize( - int strength, - SecureRandom random) + int strength, + SecureRandom random) { throw new IllegalArgumentException("use AlgorithmParameterSpec"); } public void initialize( - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidAlgorithmParameterException + AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException { String name = getNameFromParams(params); @@ -101,4 +107,34 @@ public KeyPair generateKeyPair() return new KeyPair(new BCHQCPublicKey(pub), new BCHQCPrivateKey(priv)); } + + public static class HQC128 + extends HQCKeyPairGeneratorSpi + { + public HQC128() + throws NoSuchAlgorithmException + { + super(HQCParameterSpec.hqc128); + } + } + + public static class HQC192 + extends HQCKeyPairGeneratorSpi + { + public HQC192() + throws NoSuchAlgorithmException + { + super(HQCParameterSpec.hqc192); + } + } + + public static class HQC256 + extends HQCKeyPairGeneratorSpi + { + public HQC256() + throws NoSuchAlgorithmException + { + super(HQCParameterSpec.hqc256); + } + } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPrivateKey.java index bd62a5a839..3441f5d716 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPrivateKey.java @@ -4,16 +4,13 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; import org.bouncycastle.pqc.jcajce.interfaces.KyberPrivateKey; import org.bouncycastle.pqc.jcajce.interfaces.KyberPublicKey; -import org.bouncycastle.pqc.jcajce.provider.util.KeyUtil; import org.bouncycastle.pqc.jcajce.spec.KyberParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; @@ -23,12 +20,12 @@ public class BCKyberPrivateKey { private static final long serialVersionUID = 1L; - private transient KyberPrivateKeyParameters params; + private transient MLKEMPrivateKeyParameters params; private transient String algorithm; private transient ASN1Set attributes; public BCKyberPrivateKey( - KyberPrivateKeyParameters params) + MLKEMPrivateKeyParameters params) { this.params = params; this.algorithm = Strings.toUpperCase(params.getParameters().getName()); @@ -44,7 +41,7 @@ private void init(PrivateKeyInfo keyInfo) throws IOException { this.attributes = keyInfo.getAttributes();; - this.params = (KyberPrivateKeyParameters)PrivateKeyFactory.createKey(keyInfo); + this.params = (MLKEMPrivateKeyParameters)PrivateKeyFactory.createKey(keyInfo); this.algorithm = Strings.toUpperCase(params.getParameters().getName()); } @@ -113,7 +110,7 @@ public String getFormat() return "PKCS#8"; } - KyberPrivateKeyParameters getKeyParams() + MLKEMPrivateKeyParameters getKeyParams() { return params; } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPublicKey.java index 48f52af386..0a481cd213 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPublicKey.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/BCKyberPublicKey.java @@ -5,9 +5,8 @@ import java.io.ObjectOutputStream; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; -import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; import org.bouncycastle.pqc.jcajce.interfaces.KyberPublicKey; import org.bouncycastle.pqc.jcajce.provider.util.KeyUtil; import org.bouncycastle.pqc.jcajce.spec.KyberParameterSpec; @@ -19,12 +18,12 @@ public class BCKyberPublicKey { private static final long serialVersionUID = 1L; - private transient KyberPublicKeyParameters params; + private transient MLKEMPublicKeyParameters params; private transient String algorithm; private transient byte[] encoding; public BCKyberPublicKey( - KyberPublicKeyParameters params) + MLKEMPublicKeyParameters params) { init(params); } @@ -38,10 +37,10 @@ public BCKyberPublicKey(SubjectPublicKeyInfo keyInfo) private void init(SubjectPublicKeyInfo keyInfo) throws IOException { - init((KyberPublicKeyParameters)PublicKeyFactory.createKey(keyInfo)); + init((MLKEMPublicKeyParameters)PublicKeyFactory.createKey(keyInfo)); } - private void init(KyberPublicKeyParameters params) + private void init(MLKEMPublicKeyParameters params) { this.params = params; this.algorithm = Strings.toUpperCase(params.getParameters().getName()); @@ -103,7 +102,7 @@ public KyberParameterSpec getParameterSpec() return KyberParameterSpec.fromName(params.getParameters().getName()); } - KyberPublicKeyParameters getKeyParams() + MLKEMPublicKeyParameters getKeyParams() { return params; } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java index f3ea88ff92..3712391a38 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java @@ -25,9 +25,9 @@ import org.bouncycastle.crypto.Wrapper; import org.bouncycastle.jcajce.spec.KEMParameterSpec; import org.bouncycastle.jcajce.spec.KTSParameterSpec; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.pqc.jcajce.provider.util.WrapUtil; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Exceptions; @@ -37,13 +37,13 @@ class KyberCipherSpi extends CipherSpi { private final String algorithmName; - private KyberKEMGenerator kemGen; + private MLKEMGenerator kemGen; private KTSParameterSpec kemParameterSpec; private BCKyberPublicKey wrapKey; private BCKyberPrivateKey unwrapKey; private AlgorithmParameters engineParams; - private KyberParameters kyberParameters; + private MLKEMParameters kyberParameters; KyberCipherSpi(String algorithmName) { @@ -51,7 +51,7 @@ class KyberCipherSpi this.kyberParameters = null; } - KyberCipherSpi(KyberParameters kyberParameters) + KyberCipherSpi(MLKEMParameters kyberParameters) { this.kyberParameters = kyberParameters; this.algorithmName = Strings.toUpperCase(kyberParameters.getName()); @@ -154,7 +154,7 @@ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec paramSpec, if (key instanceof BCKyberPublicKey) { wrapKey = (BCKyberPublicKey)key; - kemGen = new KyberKEMGenerator(CryptoServicesRegistrar.getSecureRandom(random)); + kemGen = new MLKEMGenerator(CryptoServicesRegistrar.getSecureRandom(random)); } else { @@ -296,7 +296,7 @@ protected Key engineUnwrap( byte[] secret = null; try { - KyberKEMExtractor kemExt = new KyberKEMExtractor(unwrapKey.getKeyParams()); + MLKEMExtractor kemExt = new MLKEMExtractor(unwrapKey.getKeyParams()); secret = kemExt.extractSecret(Arrays.copyOfRange(wrappedKey, 0, kemExt.getEncapsulationLength())); @@ -340,7 +340,7 @@ public static class Kyber512 { public Kyber512() { - super(KyberParameters.kyber512); + super(MLKEMParameters.ml_kem_512); } } @@ -349,7 +349,7 @@ public static class Kyber768 { public Kyber768() { - super(KyberParameters.kyber768); + super(MLKEMParameters.ml_kem_768); } } @@ -358,7 +358,7 @@ public static class Kyber1024 { public Kyber1024() { - super(KyberParameters.kyber1024); + super(MLKEMParameters.ml_kem_1024); } } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyFactorySpi.java index 387ae576ed..c39d3cb0b6 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyFactorySpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyFactorySpi.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; -import java.security.KeyFactorySpi; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; @@ -14,12 +13,10 @@ import java.util.Set; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; public class KyberKeyFactorySpi @@ -29,9 +26,9 @@ public class KyberKeyFactorySpi static { - keyOids.add(BCObjectIdentifiers.kyber512); - keyOids.add(BCObjectIdentifiers.kyber768); - keyOids.add(BCObjectIdentifiers.kyber1024); + keyOids.add(NISTObjectIdentifiers.id_alg_ml_kem_512); + keyOids.add(NISTObjectIdentifiers.id_alg_ml_kem_768); + keyOids.add(NISTObjectIdentifiers.id_alg_ml_kem_1024); keyOids.add(BCObjectIdentifiers.kyber512_aes); keyOids.add(BCObjectIdentifiers.kyber768_aes); keyOids.add(BCObjectIdentifiers.kyber1024_aes); @@ -102,7 +99,7 @@ public static class Kyber512 { public Kyber512() { - super(BCObjectIdentifiers.kyber512); + super(NISTObjectIdentifiers.id_alg_ml_kem_512); } } @@ -111,7 +108,7 @@ public static class Kyber768 { public Kyber768() { - super(BCObjectIdentifiers.kyber768); + super(NISTObjectIdentifiers.id_alg_ml_kem_768); } } @@ -120,7 +117,7 @@ public static class Kyber1024 { public Kyber1024() { - super(BCObjectIdentifiers.kyber1024); + super(NISTObjectIdentifiers.id_alg_ml_kem_1024); } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java index 2d2a22dc04..4e73a4cd9d 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java @@ -13,9 +13,9 @@ import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; import org.bouncycastle.jcajce.spec.KEMExtractSpec; import org.bouncycastle.jcajce.spec.KEMGenerateSpec; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; @@ -25,14 +25,14 @@ public class KyberKeyGeneratorSpi private KEMGenerateSpec genSpec; private SecureRandom random; private KEMExtractSpec extSpec; - private KyberParameters kyberParameters; + private MLKEMParameters kyberParameters; public KyberKeyGeneratorSpi() { this(null); } - protected KyberKeyGeneratorSpi(KyberParameters kyberParameters) + protected KyberKeyGeneratorSpi(MLKEMParameters kyberParameters) { this.kyberParameters = kyberParameters; } @@ -88,7 +88,7 @@ protected SecretKey engineGenerateKey() if (genSpec != null) { BCKyberPublicKey pubKey = (BCKyberPublicKey)genSpec.getPublicKey(); - KyberKEMGenerator kemGen = new KyberKEMGenerator(random); + MLKEMGenerator kemGen = new MLKEMGenerator(random); SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(pubKey.getKeyParams()); @@ -113,7 +113,7 @@ protected SecretKey engineGenerateKey() else { BCKyberPrivateKey privKey = (BCKyberPrivateKey)extSpec.getPrivateKey(); - KyberKEMExtractor kemExt = new KyberKEMExtractor(privKey.getKeyParams()); + MLKEMExtractor kemExt = new MLKEMExtractor(privKey.getKeyParams()); byte[] encapsulation = extSpec.getEncapsulation(); byte[] sharedSecret = kemExt.extractSecret(encapsulation); @@ -134,7 +134,7 @@ public static class Kyber512 { public Kyber512() { - super(KyberParameters.kyber512); + super(MLKEMParameters.ml_kem_512); } } @@ -143,7 +143,7 @@ public static class Kyber768 { public Kyber768() { - super(KyberParameters.kyber768); + super(MLKEMParameters.ml_kem_768); } } @@ -152,7 +152,7 @@ public static class Kyber1024 { public Kyber1024() { - super(KyberParameters.kyber1024); + super(MLKEMParameters.ml_kem_1024); } } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyPairGeneratorSpi.java index ddcc574f45..0c72535fd7 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyPairGeneratorSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyPairGeneratorSpi.java @@ -9,11 +9,11 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyPairGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; import org.bouncycastle.pqc.jcajce.spec.KyberParameterSpec; import org.bouncycastle.util.Strings; @@ -25,17 +25,17 @@ public class KyberKeyPairGeneratorSpi static { - parameters.put(KyberParameterSpec.kyber512.getName(), KyberParameters.kyber512); - parameters.put(KyberParameterSpec.kyber768.getName(), KyberParameters.kyber768); - parameters.put(KyberParameterSpec.kyber1024.getName(), KyberParameters.kyber1024); + parameters.put(KyberParameterSpec.kyber512.getName(), MLKEMParameters.ml_kem_512); + parameters.put(KyberParameterSpec.kyber768.getName(), MLKEMParameters.ml_kem_768); + parameters.put(KyberParameterSpec.kyber1024.getName(), MLKEMParameters.ml_kem_1024); } - KyberKeyGenerationParameters param; - KyberKeyPairGenerator engine = new KyberKeyPairGenerator(); + MLKEMKeyGenerationParameters param; + MLKEMKeyPairGenerator engine = new MLKEMKeyPairGenerator(); SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); boolean initialised = false; - private KyberParameters kyberParameters; + private MLKEMParameters kyberParameters; public KyberKeyPairGeneratorSpi() { @@ -43,7 +43,7 @@ public KyberKeyPairGeneratorSpi() this.kyberParameters = null; } - protected KyberKeyPairGeneratorSpi(KyberParameters kyberParameters) + protected KyberKeyPairGeneratorSpi(MLKEMParameters kyberParameters) { super(Strings.toUpperCase(kyberParameters.getName())); this.kyberParameters = kyberParameters; @@ -65,9 +65,9 @@ public void initialize( if (name != null && parameters.containsKey(name)) { - KyberParameters kyberParams = (KyberParameters)parameters.get(name); + MLKEMParameters kyberParams = (MLKEMParameters)parameters.get(name); - param = new KyberKeyGenerationParameters(random, kyberParams); + param = new MLKEMKeyGenerationParameters(random, kyberParams); if (kyberParameters != null && !kyberParams.getName().equals(kyberParameters.getName())) { @@ -102,11 +102,11 @@ public KeyPair generateKeyPair() { if (kyberParameters != null) { - param = new KyberKeyGenerationParameters(random, kyberParameters); + param = new MLKEMKeyGenerationParameters(random, kyberParameters); } else { - param = new KyberKeyGenerationParameters(random, KyberParameters.kyber1024); + param = new MLKEMKeyGenerationParameters(random, MLKEMParameters.ml_kem_1024); } engine.init(param); @@ -114,8 +114,8 @@ public KeyPair generateKeyPair() } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - KyberPublicKeyParameters pub = (KyberPublicKeyParameters)pair.getPublic(); - KyberPrivateKeyParameters priv = (KyberPrivateKeyParameters)pair.getPrivate(); + MLKEMPublicKeyParameters pub = (MLKEMPublicKeyParameters)pair.getPublic(); + MLKEMPrivateKeyParameters priv = (MLKEMPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new BCKyberPublicKey(pub), new BCKyberPrivateKey(priv)); } @@ -125,7 +125,7 @@ public static class Kyber512 { public Kyber512() { - super(KyberParameters.kyber512); + super(MLKEMParameters.ml_kem_512); } } @@ -134,7 +134,7 @@ public static class Kyber768 { public Kyber768() { - super(KyberParameters.kyber768); + super(MLKEMParameters.ml_kem_768); } } @@ -143,7 +143,7 @@ public static class Kyber1024 { public Kyber1024() { - super(KyberParameters.kyber1024); + super(MLKEMParameters.ml_kem_1024); } } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPrivateKey.java index c0df9f8315..ae82e09dca 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPrivateKey.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPrivateKey.java @@ -27,7 +27,7 @@ public class BCLMSPrivateKey public BCLMSPrivateKey( LMSKeyParameters keyParams) { - this.keyParams = keyParams; + this.keyParams = (keyParams instanceof HSSPrivateKeyParameters) ? (HSSPrivateKeyParameters)keyParams : new HSSPrivateKeyParameters((LMSPrivateKeyParameters)keyParams, ((LMSPrivateKeyParameters)keyParams).getIndex(), ((LMSPrivateKeyParameters)keyParams).getIndex() + ((LMSPrivateKeyParameters)keyParams).getUsagesRemaining()); } public BCLMSPrivateKey(PrivateKeyInfo keyInfo) diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPublicKey.java index 4b018d78b0..cb2b61623f 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPublicKey.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/lms/BCLMSPublicKey.java @@ -26,7 +26,7 @@ public class BCLMSPublicKey public BCLMSPublicKey( LMSKeyParameters keyParams) { - this.keyParams = keyParams; + this.keyParams = (keyParams instanceof HSSPublicKeyParameters) ? keyParams : new HSSPublicKeyParameters(1, (LMSPublicKeyParameters)keyParams); } public BCLMSPublicKey(SubjectPublicKeyInfo keyInfo) diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/BCMayoPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/BCMayoPrivateKey.java new file mode 100644 index 0000000000..043fee5635 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/BCMayoPrivateKey.java @@ -0,0 +1,131 @@ +package org.bouncycastle.pqc.jcajce.provider.mayo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.PrivateKey; + +import org.bouncycastle.asn1.ASN1Set; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.pqc.crypto.mayo.MayoPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.pqc.jcajce.interfaces.MayoKey; +import org.bouncycastle.pqc.jcajce.spec.MayoParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +public class BCMayoPrivateKey + implements PrivateKey, MayoKey +{ + private static final long serialVersionUID = 1L; + + private transient MayoPrivateKeyParameters params; + private transient ASN1Set attributes; + + public BCMayoPrivateKey( + MayoPrivateKeyParameters params) + { + this.params = params; + } + + public BCMayoPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(PrivateKeyInfo keyInfo) + throws IOException + { + this.attributes = keyInfo.getAttributes(); + this.params = (MayoPrivateKeyParameters) PrivateKeyFactory.createKey(keyInfo); + } + + /** + * Compare this private key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCMayoPrivateKey) + { + BCMayoPrivateKey otherKey = (BCMayoPrivateKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "Mayo[1|2|3|5]" + */ + public final String getAlgorithm() + { + return Strings.toUpperCase(params.getParameters().getName()); + } + + public byte[] getEncoded() + { + + try + { + PrivateKeyInfo pki = PrivateKeyInfoFactory.createPrivateKeyInfo(params, attributes); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public MayoParameterSpec getParameterSpec() + { + return MayoParameterSpec.fromName(params.getParameters().getName()); + } + + public String getFormat() + { + return "PKCS#8"; + } + + MayoPrivateKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(PrivateKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/BCMayoPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/BCMayoPublicKey.java new file mode 100644 index 0000000000..5d53ecc839 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/BCMayoPublicKey.java @@ -0,0 +1,127 @@ +package org.bouncycastle.pqc.jcajce.provider.mayo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.PublicKey; + +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.pqc.crypto.mayo.MayoPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.pqc.jcajce.interfaces.MayoKey; +import org.bouncycastle.pqc.jcajce.spec.MayoParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +public class BCMayoPublicKey + implements PublicKey, MayoKey +{ + private static final long serialVersionUID = 1L; + + private transient MayoPublicKeyParameters params; + + public BCMayoPublicKey( + MayoPublicKeyParameters params) + { + this.params = params; + } + + public BCMayoPublicKey(SubjectPublicKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(SubjectPublicKeyInfo keyInfo) + throws IOException + { + this.params = (MayoPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); + } + + /** + * Compare this BIKE public key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCMayoPublicKey) + { + BCMayoPublicKey otherKey = (BCMayoPublicKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "Mayo[1|2|3|5]" + */ + public final String getAlgorithm() + { + return Strings.toUpperCase(params.getParameters().getName()); + } + + public byte[] getEncoded() + { + try + { + SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(params); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public String getFormat() + { + return "X.509"; + } + + public MayoParameterSpec getParameterSpec() + { + return MayoParameterSpec.fromName(params.getParameters().getName()); + } + + MayoPublicKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(SubjectPublicKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/MayoKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/MayoKeyFactorySpi.java new file mode 100644 index 0000000000..f27d25e86d --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/MayoKeyFactorySpi.java @@ -0,0 +1,130 @@ +package org.bouncycastle.pqc.jcajce.provider.mayo; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; + +public class MayoKeyFactorySpi + extends BaseKeyFactorySpi +{ + private static final Set keyOids = new HashSet(); + + static + { + keyOids.add(BCObjectIdentifiers.mayo1); + keyOids.add(BCObjectIdentifiers.mayo2); + keyOids.add(BCObjectIdentifiers.mayo3); + keyOids.add(BCObjectIdentifiers.mayo5); + } + + public MayoKeyFactorySpi() + { + super(keyOids); + } + + public MayoKeyFactorySpi(ASN1ObjectIdentifier keyOid) + { + super(keyOid); + } + + public final KeySpec engineGetKeySpec(Key key, Class keySpec) + throws InvalidKeySpecException + { + if (key instanceof BCMayoPrivateKey) + { + if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new PKCS8EncodedKeySpec(key.getEncoded()); + } + } + else if (key instanceof BCMayoPublicKey) + { + if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new X509EncodedKeySpec(key.getEncoded()); + } + } + else + { + throw new InvalidKeySpecException("Unsupported key type: " + + key.getClass() + "."); + } + + throw new InvalidKeySpecException("Unknown key specification: " + + keySpec + "."); + } + + public final Key engineTranslateKey(Key key) + throws InvalidKeyException + { + if (key instanceof BCMayoPrivateKey || key instanceof BCMayoPublicKey) + { + return key; + } + + throw new InvalidKeyException("Unsupported key type"); + } + + public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) + throws IOException + { + return new BCMayoPrivateKey(keyInfo); + } + + public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) + throws IOException + { + return new BCMayoPublicKey(keyInfo); + } + + public static class Mayo1 + extends MayoKeyFactorySpi + { + public Mayo1() + { + super(BCObjectIdentifiers.mayo1); + } + } + + public static class Mayo2 + extends MayoKeyFactorySpi + { + public Mayo2() + { + super(BCObjectIdentifiers.mayo2); + } + } + + public static class Mayo3 + extends MayoKeyFactorySpi + { + public Mayo3() + { + super(BCObjectIdentifiers.mayo3); + } + } + + public static class Mayo5 + extends MayoKeyFactorySpi + { + public Mayo5() + { + super(BCObjectIdentifiers.mayo5); + } + } +} + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/MayoKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/MayoKeyPairGeneratorSpi.java new file mode 100644 index 0000000000..892730e20d --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/MayoKeyPairGeneratorSpi.java @@ -0,0 +1,148 @@ +package org.bouncycastle.pqc.jcajce.provider.mayo; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.pqc.crypto.mayo.MayoKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; +import org.bouncycastle.pqc.jcajce.spec.MayoParameterSpec; +import org.bouncycastle.util.Strings; + +public class MayoKeyPairGeneratorSpi + extends java.security.KeyPairGenerator +{ + private static Map parameters = new HashMap(); + + static + { + parameters.put("MAYO_1", MayoParameters.mayo1); + parameters.put("MAYO_2", MayoParameters.mayo2); + parameters.put("MAYO_3", MayoParameters.mayo3); + parameters.put("MAYO_5", MayoParameters.mayo5); + parameters.put(MayoParameterSpec.mayo1.getName(), MayoParameters.mayo1); + parameters.put(MayoParameterSpec.mayo2.getName(), MayoParameters.mayo2); + parameters.put(MayoParameterSpec.mayo3.getName(), MayoParameters.mayo3); + parameters.put(MayoParameterSpec.mayo5.getName(), MayoParameters.mayo5); + } + + MayoKeyGenerationParameters param; + private MayoParameters mayoParameters; + MayoKeyPairGenerator engine = new MayoKeyPairGenerator(); + + SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + boolean initialised = false; + + public MayoKeyPairGeneratorSpi() + { + super("Mayo"); + } + + protected MayoKeyPairGeneratorSpi(MayoParameters mayoParameters) + { + super(mayoParameters.getName()); + this.mayoParameters = mayoParameters; + } + + public void initialize( + int strength, + SecureRandom random) + { + throw new IllegalArgumentException("use AlgorithmParameterSpec"); + } + + public void initialize( + AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + String name = getNameFromParams(params); + + if (name != null) + { + param = new MayoKeyGenerationParameters(random, (MayoParameters)parameters.get(name)); + + engine.init(param); + initialised = true; + } + else + { + throw new InvalidAlgorithmParameterException("invalid ParameterSpec: " + params); + } + } + + private static String getNameFromParams(AlgorithmParameterSpec paramSpec) + { + if (paramSpec instanceof MayoParameterSpec) + { + MayoParameterSpec MayoParams = (MayoParameterSpec)paramSpec; + return MayoParams.getName(); + } + else + { + return Strings.toLowerCase(SpecUtil.getNameFrom(paramSpec)); + } + } + + public KeyPair generateKeyPair() + { + if (!initialised) + { + param = new MayoKeyGenerationParameters(random, MayoParameters.mayo1); + + engine.init(param); + initialised = true; + } + + AsymmetricCipherKeyPair pair = engine.generateKeyPair(); + MayoPublicKeyParameters pub = (MayoPublicKeyParameters)pair.getPublic(); + MayoPrivateKeyParameters priv = (MayoPrivateKeyParameters)pair.getPrivate(); + + return new KeyPair(new BCMayoPublicKey(pub), new BCMayoPrivateKey(priv)); + } + + public static class Mayo1 + extends MayoKeyPairGeneratorSpi + { + public Mayo1() + { + super(MayoParameters.mayo1); + } + } + + public static class Mayo2 + extends MayoKeyPairGeneratorSpi + { + public Mayo2() + { + super(MayoParameters.mayo2); + } + } + + public static class Mayo3 + extends MayoKeyPairGeneratorSpi + { + public Mayo3() + { + super(MayoParameters.mayo3); + } + } + + public static class Mayo5 + extends MayoKeyPairGeneratorSpi + { + public Mayo5() + { + super(MayoParameters.mayo5); + } + } +} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/SignatureSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/SignatureSpi.java similarity index 65% rename from prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/SignatureSpi.java rename to prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/SignatureSpi.java index 14213bb3ac..0a1075657e 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/SignatureSpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/mayo/SignatureSpi.java @@ -1,4 +1,4 @@ -package org.bouncycastle.pqc.jcajce.provider.rainbow; +package org.bouncycastle.pqc.jcajce.provider.mayo; import java.io.ByteArrayOutputStream; import java.security.InvalidKeyException; @@ -11,28 +11,28 @@ import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.pqc.crypto.rainbow.RainbowParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowSigner; +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.pqc.crypto.mayo.MayoSigner; import org.bouncycastle.util.Strings; public class SignatureSpi extends java.security.Signature { - private ByteArrayOutputStream bOut; - private RainbowSigner signer; + private final ByteArrayOutputStream bOut; + private final MayoSigner signer; private SecureRandom random; - private RainbowParameters parameters; + private final MayoParameters parameters; - protected SignatureSpi(RainbowSigner signer) + protected SignatureSpi(MayoSigner signer) { - super("RAINBOW"); - + super("Mayo"); + this.bOut = new ByteArrayOutputStream(); this.signer = signer; this.parameters = null; } - protected SignatureSpi(RainbowSigner signer, RainbowParameters parameters) + protected SignatureSpi(MayoSigner signer, MayoParameters parameters) { super(Strings.toUpperCase(parameters.getName())); this.parameters = parameters; @@ -44,19 +44,19 @@ protected SignatureSpi(RainbowSigner signer, RainbowParameters parameters) protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { - if (!(publicKey instanceof BCRainbowPublicKey)) + if (!(publicKey instanceof BCMayoPublicKey)) { try { - publicKey = new BCRainbowPublicKey(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); + publicKey = new BCMayoPublicKey(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); } catch (Exception e) { - throw new InvalidKeyException("unknown public key passed to Rainbow: " + e.getMessage(), e); + throw new InvalidKeyException("unknown public key passed to Mayo: " + e.getMessage()); } } - BCRainbowPublicKey key = (BCRainbowPublicKey)publicKey; + BCMayoPublicKey key = (BCMayoPublicKey)publicKey; if (parameters != null) { @@ -80,9 +80,9 @@ protected void engineInitSign(PrivateKey privateKey, SecureRandom random) protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { - if (privateKey instanceof BCRainbowPrivateKey) + if (privateKey instanceof BCMayoPrivateKey) { - BCRainbowPrivateKey key = (BCRainbowPrivateKey)privateKey; + BCMayoPrivateKey key = (BCMayoPrivateKey)privateKey; CipherParameters param = key.getKeyParams(); if (parameters != null) @@ -105,18 +105,18 @@ protected void engineInitSign(PrivateKey privateKey) } else { - throw new InvalidKeyException("unknown private key passed to Rainbow"); + throw new InvalidKeyException("unknown private key passed to Mayo"); } } protected void engineUpdate(byte b) - throws SignatureException + throws SignatureException { bOut.write(b); } protected void engineUpdate(byte[] b, int off, int len) - throws SignatureException + throws SignatureException { bOut.write(b, off, len); } @@ -171,65 +171,48 @@ protected Object engineGetParameter(String param) } public static class Base - extends SignatureSpi + extends org.bouncycastle.pqc.jcajce.provider.mayo.SignatureSpi { public Base() { - super(new RainbowSigner()); - } - } - - public static class RainbowIIIclassic - extends SignatureSpi - { - public RainbowIIIclassic() - { - super(new RainbowSigner(), RainbowParameters.rainbowIIIclassic); + super(new MayoSigner()); } } - public static class RainbowIIIcircum - extends SignatureSpi + public static class Mayo1 + extends org.bouncycastle.pqc.jcajce.provider.mayo.SignatureSpi { - public RainbowIIIcircum() + public Mayo1() { - super(new RainbowSigner(), RainbowParameters.rainbowIIIcircumzenithal); + super(new MayoSigner(), MayoParameters.mayo1); } } - public static class RainbowIIIcomp - extends SignatureSpi + public static class Mayo2 + extends org.bouncycastle.pqc.jcajce.provider.mayo.SignatureSpi { - public RainbowIIIcomp() + public Mayo2() { - super(new RainbowSigner(), RainbowParameters.rainbowIIIcompressed); + super(new MayoSigner(), MayoParameters.mayo2); } } - public static class RainbowVclassic - extends SignatureSpi + public static class Mayo3 + extends org.bouncycastle.pqc.jcajce.provider.mayo.SignatureSpi { - public RainbowVclassic() + public Mayo3() { - super(new RainbowSigner(), RainbowParameters.rainbowVclassic); + super(new MayoSigner(), MayoParameters.mayo3); } } - public static class RainbowVcircum - extends SignatureSpi + public static class Mayo5 + extends org.bouncycastle.pqc.jcajce.provider.mayo.SignatureSpi { - public RainbowVcircum() + public Mayo5() { - super(new RainbowSigner(), RainbowParameters.rainbowVcircumzenithal); - } - } - - public static class RainbowVcomp - extends SignatureSpi - { - public RainbowVcomp() - { - super(new RainbowSigner(), RainbowParameters.rainbowVcompressed); + super(new MayoSigner(), MayoParameters.mayo5); } } } + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPrivateKey.java deleted file mode 100644 index e1e1e53f8b..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPrivateKey.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider.rainbow; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; -import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; -import org.bouncycastle.pqc.jcajce.interfaces.RainbowPrivateKey; -import org.bouncycastle.pqc.jcajce.interfaces.RainbowPublicKey; -import org.bouncycastle.pqc.jcajce.provider.util.KeyUtil; -import org.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Hex; - -public class BCRainbowPrivateKey - implements RainbowPrivateKey -{ - private static final long serialVersionUID = 1L; - - private transient RainbowPrivateKeyParameters params; - private transient String algorithm; - private transient byte[] encoding; - private transient ASN1Set attributes; - - public BCRainbowPrivateKey( - RainbowPrivateKeyParameters params) - { - init(params, null); - } - - public BCRainbowPrivateKey(PrivateKeyInfo keyInfo) - throws IOException - { - init(keyInfo); - } - - private void init(PrivateKeyInfo keyInfo) - throws IOException - { - init((RainbowPrivateKeyParameters) PrivateKeyFactory.createKey(keyInfo), keyInfo.getAttributes()); - } - - private void init(RainbowPrivateKeyParameters params, ASN1Set attributes) - { - this.attributes = attributes; - this.params = params; - this.algorithm = Strings.toUpperCase(params.getParameters().getName()); - } - - /** - * Compare this Rainbow private key with another object. - * - * @param o the other object - * @return the result of the comparison - */ - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - - if (o instanceof BCRainbowPrivateKey) - { - BCRainbowPrivateKey otherKey = (BCRainbowPrivateKey)o; - - return Arrays.areEqual(getEncoded(), otherKey.getEncoded()); - } - - return false; - } - - public int hashCode() - { - return Arrays.hashCode(getEncoded()); - } - - /** - * @return name of the algorithm - */ - public final String getAlgorithm() - { - return algorithm; - } - - public byte[] getEncoded() - { - if (encoding == null) - { - encoding = KeyUtil.getEncodedPrivateKeyInfo(params, attributes); - } - - return Arrays.clone(encoding); - } - - public RainbowParameterSpec getParameterSpec() - { - return RainbowParameterSpec.fromName(params.getParameters().getName()); - } - - public String getFormat() - { - return "PKCS#8"; - } - - public RainbowPublicKey getPublicKey() - { - return new BCRainbowPublicKey(new RainbowPublicKeyParameters(params.getParameters(), params.getPublicKey())); - } - - RainbowPrivateKeyParameters getKeyParams() - { - return params; - } - - private void readObject( - ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - byte[] enc = (byte[])in.readObject(); - - init(PrivateKeyInfo.getInstance(enc)); - } - - private void writeObject( - ObjectOutputStream out) - throws IOException - { - out.defaultWriteObject(); - - out.writeObject(this.getEncoded()); - } -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPublicKey.java deleted file mode 100644 index a8f0c63bfe..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/BCRainbowPublicKey.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider.rainbow; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; -import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; -import org.bouncycastle.pqc.jcajce.interfaces.RainbowPublicKey; -import org.bouncycastle.pqc.jcajce.provider.util.KeyUtil; -import org.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Hex; - -public class BCRainbowPublicKey - implements RainbowPublicKey -{ - private static final long serialVersionUID = 1L; - - private transient RainbowPublicKeyParameters params; - private transient String algorithm; - private transient byte[] encoding; - - public BCRainbowPublicKey( - RainbowPublicKeyParameters params) - { - init(params); - } - - public BCRainbowPublicKey(SubjectPublicKeyInfo keyInfo) - throws IOException - { - init(keyInfo); - } - - private void init(SubjectPublicKeyInfo keyInfo) - throws IOException - { - init((RainbowPublicKeyParameters) PublicKeyFactory.createKey(keyInfo)); - } - - private void init(RainbowPublicKeyParameters params) - { - this.params = params; - this.algorithm = Strings.toUpperCase(params.getParameters().getName()); - } - - /** - * Compare this Rainbow public key with another object. - * - * @param o the other object - * @return the result of the comparison - */ - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - - if (o instanceof BCRainbowPublicKey) - { - BCRainbowPublicKey otherKey = (BCRainbowPublicKey)o; - - return Arrays.areEqual(getEncoded(), otherKey.getEncoded()); - } - - return false; - } - - public int hashCode() - { - return Arrays.hashCode(getEncoded()); - } - - /** - * @return name of the algorithm - */ - public final String getAlgorithm() - { - return algorithm; - } - - public byte[] getEncoded() - { - if (encoding == null) - { - encoding = KeyUtil.getEncodedSubjectPublicKeyInfo(params); - } - - return Arrays.clone(encoding); - } - - public String getFormat() - { - return "X.509"; - } - - public RainbowParameterSpec getParameterSpec() - { - return RainbowParameterSpec.fromName(params.getParameters().getName()); - } - - RainbowPublicKeyParameters getKeyParams() - { - return params; - } - - private void readObject( - ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - byte[] enc = (byte[])in.readObject(); - - init(SubjectPublicKeyInfo.getInstance(enc)); - } - - private void writeObject( - ObjectOutputStream out) - throws IOException - { - out.defaultWriteObject(); - - out.writeObject(this.getEncoded()); - } -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyFactorySpi.java deleted file mode 100644 index 5c3c142a19..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyFactorySpi.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider.rainbow; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactorySpi; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; - -public class RainbowKeyFactorySpi - extends KeyFactorySpi - implements AsymmetricKeyInfoConverter -{ - public PrivateKey engineGeneratePrivate(KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof PKCS8EncodedKeySpec) - { - // get the DER-encoded Key according to PKCS#8 from the spec - byte[] encKey = ((PKCS8EncodedKeySpec)keySpec).getEncoded(); - - try - { - return generatePrivate(PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(encKey))); - } - catch (Exception e) - { - throw new InvalidKeySpecException(e.toString()); - } - } - - throw new InvalidKeySpecException("Unsupported key specification: " - + keySpec.getClass() + "."); - } - - public PublicKey engineGeneratePublic(KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof X509EncodedKeySpec) - { - // get the DER-encoded Key according to X.509 from the spec - byte[] encKey = ((X509EncodedKeySpec)keySpec).getEncoded(); - - // decode the SubjectPublicKeyInfo data structure to the pki object - try - { - return generatePublic(SubjectPublicKeyInfo.getInstance(encKey)); - } - catch (Exception e) - { - throw new InvalidKeySpecException(e.toString(), e); - } - } - - throw new InvalidKeySpecException("Unknown key specification: " + keySpec + "."); - } - - public final KeySpec engineGetKeySpec(Key key, Class keySpec) - throws InvalidKeySpecException - { - if (key instanceof BCRainbowPrivateKey) - { - if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) - { - return new PKCS8EncodedKeySpec(key.getEncoded()); - } - } - else if (key instanceof BCRainbowPublicKey) - { - if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) - { - return new X509EncodedKeySpec(key.getEncoded()); - } - } - else - { - throw new InvalidKeySpecException("Unsupported key type: " - + key.getClass() + "."); - } - - throw new InvalidKeySpecException("Unknown key specification: " - + keySpec + "."); - } - - public final Key engineTranslateKey(Key key) - throws InvalidKeyException - { - if (key instanceof BCRainbowPrivateKey || key instanceof BCRainbowPublicKey) - { - return key; - } - - throw new InvalidKeyException("Unsupported key type"); - } - - public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) - throws IOException - { - return new BCRainbowPrivateKey(keyInfo); - } - - public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) - throws IOException - { - return new BCRainbowPublicKey(keyInfo); - } -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyPairGeneratorSpi.java deleted file mode 100644 index 0bafb9af47..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/rainbow/RainbowKeyPairGeneratorSpi.java +++ /dev/null @@ -1,180 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider.rainbow; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; -import java.util.HashMap; -import java.util.Map; - -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.CryptoServicesRegistrar; -import org.bouncycastle.pqc.crypto.rainbow.RainbowKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowKeyPairGenerator; -import org.bouncycastle.pqc.crypto.rainbow.RainbowParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowPublicKeyParameters; -import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; -import org.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; -import org.bouncycastle.util.Strings; - -public class RainbowKeyPairGeneratorSpi - extends java.security.KeyPairGenerator -{ - private static Map parameters = new HashMap(); - - static - { - parameters.put(RainbowParameterSpec.rainbowIIIclassic.getName(), RainbowParameters.rainbowIIIclassic); - parameters.put(RainbowParameterSpec.rainbowIIIcircumzenithal.getName(), RainbowParameters.rainbowIIIcircumzenithal); - parameters.put(RainbowParameterSpec.rainbowIIIcompressed.getName(), RainbowParameters.rainbowIIIcompressed); - parameters.put(RainbowParameterSpec.rainbowVclassic.getName(), RainbowParameters.rainbowVclassic); - parameters.put(RainbowParameterSpec.rainbowVcircumzenithal.getName(), RainbowParameters.rainbowVcircumzenithal); - parameters.put(RainbowParameterSpec.rainbowVcompressed.getName(), RainbowParameters.rainbowVcompressed); - } - - private final RainbowParameters rainbowParameters; - - RainbowKeyGenerationParameters param; - RainbowKeyPairGenerator engine = new RainbowKeyPairGenerator(); - - SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); - boolean initialised = false; - - public RainbowKeyPairGeneratorSpi() - { - super("RAINBOW"); - this.rainbowParameters = null; - } - - protected RainbowKeyPairGeneratorSpi(RainbowParameters rainbowParameters) - { - super(rainbowParameters.getName()); - this.rainbowParameters = rainbowParameters; - } - - public void initialize( - int strength, - SecureRandom random) - { - throw new IllegalArgumentException("use AlgorithmParameterSpec"); - } - - public void initialize( - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidAlgorithmParameterException - { - String name = getNameFromParams(params); - - if (name != null && parameters.containsKey(name)) - { - RainbowParameters rainbowParams = (RainbowParameters)parameters.get(name); - - param = new RainbowKeyGenerationParameters(random, rainbowParams); - - if (rainbowParameters != null && !rainbowParams.getName().equals(rainbowParameters.getName())) - { - throw new InvalidAlgorithmParameterException("key pair generator locked to " + Strings.toUpperCase(rainbowParameters.getName())); - } - - engine.init(param); - initialised = true; - } - else - { - throw new InvalidAlgorithmParameterException("invalid ParameterSpec: " + params); - } - } - - private static String getNameFromParams(AlgorithmParameterSpec paramSpec) - { - if (paramSpec instanceof RainbowParameterSpec) - { - RainbowParameterSpec rainbowParams = (RainbowParameterSpec)paramSpec; - return rainbowParams.getName(); - } - else - { - return Strings.toLowerCase(SpecUtil.getNameFrom(paramSpec)); - } - } - - public KeyPair generateKeyPair() - { - if (!initialised) - { - if (rainbowParameters != null) - { - param = new RainbowKeyGenerationParameters(random, rainbowParameters); - } - else - { - param = new RainbowKeyGenerationParameters(random, RainbowParameters.rainbowIIIclassic); - } - - engine.init(param); - initialised = true; - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - RainbowPublicKeyParameters pub = (RainbowPublicKeyParameters)pair.getPublic(); - RainbowPrivateKeyParameters priv = (RainbowPrivateKeyParameters)pair.getPrivate(); - - return new KeyPair(new BCRainbowPublicKey(pub), new BCRainbowPrivateKey(priv)); - } - - public static class RainbowIIIclassic - extends RainbowKeyPairGeneratorSpi - { - public RainbowIIIclassic() - { - super(RainbowParameters.rainbowIIIclassic); - } - } - - public static class RainbowIIIcircum - extends RainbowKeyPairGeneratorSpi - { - public RainbowIIIcircum() - { - super(RainbowParameters.rainbowIIIcircumzenithal); - } - } - - public static class RainbowIIIcomp - extends RainbowKeyPairGeneratorSpi - { - public RainbowIIIcomp() - { - super(RainbowParameters.rainbowIIIcompressed); - } - } - - public static class RainbowVclassic - extends RainbowKeyPairGeneratorSpi - { - public RainbowVclassic() - { - super(RainbowParameters.rainbowVclassic); - } - } - - public static class RainbowVcircum - extends RainbowKeyPairGeneratorSpi - { - public RainbowVcircum() - { - super(RainbowParameters.rainbowVcircumzenithal); - } - } - - public static class RainbowVcomp - extends RainbowKeyPairGeneratorSpi - { - public RainbowVcomp() - { - super(RainbowParameters.rainbowVcompressed); - } - } -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/BCSnovaPrivateKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/BCSnovaPrivateKey.java new file mode 100644 index 0000000000..34f47b2df0 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/BCSnovaPrivateKey.java @@ -0,0 +1,132 @@ +package org.bouncycastle.pqc.jcajce.provider.snova; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.PrivateKey; + +import org.bouncycastle.asn1.ASN1Set; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.pqc.crypto.snova.SnovaPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory; +import org.bouncycastle.pqc.crypto.util.PrivateKeyInfoFactory; +import org.bouncycastle.pqc.jcajce.interfaces.SnovaKey; +import org.bouncycastle.pqc.jcajce.spec.SnovaParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +public class BCSnovaPrivateKey + implements PrivateKey, SnovaKey +{ + private static final long serialVersionUID = 1L; + + private transient SnovaPrivateKeyParameters params; + private transient ASN1Set attributes; + + public BCSnovaPrivateKey( + SnovaPrivateKeyParameters params) + { + this.params = params; + } + + public BCSnovaPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(PrivateKeyInfo keyInfo) + throws IOException + { + this.attributes = keyInfo.getAttributes(); + this.params = (SnovaPrivateKeyParameters) PrivateKeyFactory.createKey(keyInfo); + } + + /** + * Compare this private key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCSnovaPrivateKey) + { + BCSnovaPrivateKey otherKey = (BCSnovaPrivateKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "Snova_[v]_[o]_[l]" + */ + public final String getAlgorithm() + { + return Strings.toUpperCase(params.getParameters().getName()); + } + + public byte[] getEncoded() + { + + try + { + PrivateKeyInfo pki = PrivateKeyInfoFactory.createPrivateKeyInfo(params, attributes); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public SnovaParameterSpec getParameterSpec() + { + return SnovaParameterSpec.fromName(params.getParameters().getName()); + } + + public String getFormat() + { + return "PKCS#8"; + } + + SnovaPrivateKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(PrivateKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} + + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/BCSnovaPublicKey.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/BCSnovaPublicKey.java new file mode 100644 index 0000000000..3c6ec6b946 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/BCSnovaPublicKey.java @@ -0,0 +1,128 @@ +package org.bouncycastle.pqc.jcajce.provider.snova; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.PublicKey; + +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.pqc.crypto.snova.SnovaPublicKeyParameters; +import org.bouncycastle.pqc.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.pqc.jcajce.interfaces.SnovaKey; +import org.bouncycastle.pqc.jcajce.spec.SnovaParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +public class BCSnovaPublicKey + implements PublicKey, SnovaKey +{ + private static final long serialVersionUID = 1L; + + private transient SnovaPublicKeyParameters params; + + public BCSnovaPublicKey( + SnovaPublicKeyParameters params) + { + this.params = params; + } + + public BCSnovaPublicKey(SubjectPublicKeyInfo keyInfo) + throws IOException + { + init(keyInfo); + } + + private void init(SubjectPublicKeyInfo keyInfo) + throws IOException + { + this.params = (SnovaPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); + } + + /** + * Compare this BIKE public key with another object. + * + * @param o the other object + * @return the result of the comparison + */ + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCSnovaPublicKey) + { + BCSnovaPublicKey otherKey = (BCSnovaPublicKey)o; + + return Arrays.areEqual(params.getEncoded(), otherKey.params.getEncoded()); + } + + return false; + } + + public int hashCode() + { + return Arrays.hashCode(params.getEncoded()); + } + + /** + * @return name of the algorithm - "Snova_[v]_[o]_[l]" + */ + public final String getAlgorithm() + { + return Strings.toUpperCase(params.getParameters().getName()); + } + + public byte[] getEncoded() + { + try + { + SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(params); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public String getFormat() + { + return "X.509"; + } + + public SnovaParameterSpec getParameterSpec() + { + return SnovaParameterSpec.fromName(params.getParameters().getName()); + } + + SnovaPublicKeyParameters getKeyParams() + { + return params; + } + + private void readObject( + ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + byte[] enc = (byte[])in.readObject(); + + init(SubjectPublicKeyInfo.getInstance(enc)); + } + + private void writeObject( + ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + out.writeObject(this.getEncoded()); + } +} + + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SignatureSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SignatureSpi.java new file mode 100644 index 0000000000..e544734348 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SignatureSpi.java @@ -0,0 +1,578 @@ +package org.bouncycastle.pqc.jcajce.provider.snova; + +import java.io.ByteArrayOutputStream; +import java.security.InvalidKeyException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; + +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaSigner; +import org.bouncycastle.util.Strings; + +public class SignatureSpi + extends java.security.Signature +{ + private final ByteArrayOutputStream bOut; + private final SnovaSigner signer; + private SecureRandom random; + private final SnovaParameters parameters; + + protected SignatureSpi(SnovaSigner signer) + { + super("Snova"); + + this.bOut = new ByteArrayOutputStream(); + this.signer = signer; + this.parameters = null; + } + + protected SignatureSpi(SnovaSigner signer, SnovaParameters parameters) + { + super(Strings.toUpperCase(parameters.getName())); + this.parameters = parameters; + + this.bOut = new ByteArrayOutputStream(); + this.signer = signer; + } + + protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException + { + if (!(publicKey instanceof BCSnovaPublicKey)) + { + try + { + publicKey = new BCSnovaPublicKey(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); + } + catch (Exception e) + { + throw new InvalidKeyException("unknown public key passed to Snova: " + e.getMessage()); + } + } + + BCSnovaPublicKey key = (BCSnovaPublicKey)publicKey; + + if (parameters != null) + { + String canonicalAlg = Strings.toUpperCase(parameters.getName()); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + + signer.init(false, key.getKeyParams()); + } + + protected void engineInitSign(PrivateKey privateKey, SecureRandom random) + throws InvalidKeyException + { + this.random = random; + engineInitSign(privateKey); + } + + protected void engineInitSign(PrivateKey privateKey) + throws InvalidKeyException + { + if (privateKey instanceof BCSnovaPrivateKey) + { + BCSnovaPrivateKey key = (BCSnovaPrivateKey)privateKey; + CipherParameters param = key.getKeyParams(); + + if (parameters != null) + { + String canonicalAlg = Strings.toUpperCase(parameters.getName()); + if (!canonicalAlg.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("signature configured for " + canonicalAlg); + } + } + + if (random != null) + { + signer.init(true, new ParametersWithRandom(param, random)); + } + else + { + signer.init(true, param); + } + } + else + { + throw new InvalidKeyException("unknown private key passed to Snova"); + } + } + + protected void engineUpdate(byte b) + throws SignatureException + { + bOut.write(b); + } + + protected void engineUpdate(byte[] b, int off, int len) + throws SignatureException + { + bOut.write(b, off, len); + } + + protected byte[] engineSign() + throws SignatureException + { + try + { + byte[] message = bOut.toByteArray(); + + bOut.reset(); + + return signer.generateSignature(message); + } + catch (Exception e) + { + throw new SignatureException(e.toString()); + } + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException + { + byte[] message = bOut.toByteArray(); + + bOut.reset(); + + return signer.verifySignature(message, sigBytes); + } + + protected void engineSetParameter(AlgorithmParameterSpec params) + { + // TODO + throw new UnsupportedOperationException("engineSetParameter unsupported"); + } + + /** + * @deprecated replaced with #engineSetParameter(java.security.spec.AlgorithmParameterSpec) + */ + protected void engineSetParameter(String param, Object value) + { + throw new UnsupportedOperationException("engineSetParameter unsupported"); + } + + /** + * @deprecated + */ + protected Object engineGetParameter(String param) + { + throw new UnsupportedOperationException("engineSetParameter unsupported"); + } + + public static class Base + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public Base() + { + super(new SnovaSigner()); + } + } + + public static class SNOVA_24_5_4_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_4_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_4_SSK); + } + } + + public static class SNOVA_24_5_4_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_4_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_4_ESK); + } + } + + public static class SNOVA_24_5_4_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_4_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_4_SHAKE_ESK); + } + } + + public static class SNOVA_24_5_4_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_4_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_4_SHAKE_SSK); + } + } + + public static class SNOVA_24_5_5_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_5_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_5_SSK); + } + } + + public static class SNOVA_24_5_5_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_5_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_5_ESK); + } + } + + public static class SNOVA_24_5_5_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_5_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_5_SHAKE_ESK); + } + } + + public static class SNOVA_24_5_5_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_24_5_5_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_24_5_5_SHAKE_SSK); + } + } + + public static class SNOVA_25_8_3_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_25_8_3_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_25_8_3_SSK); + } + } + + public static class SNOVA_25_8_3_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_25_8_3_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_25_8_3_ESK); + } + } + + public static class SNOVA_25_8_3_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_25_8_3_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_25_8_3_SHAKE_ESK); + } + } + + public static class SNOVA_25_8_3_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_25_8_3_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_25_8_3_SHAKE_SSK); + } + } + + public static class SNOVA_29_6_5_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_29_6_5_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_29_6_5_SSK); + } + } + + public static class SNOVA_29_6_5_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_29_6_5_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_29_6_5_ESK); + } + } + + public static class SNOVA_29_6_5_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_29_6_5_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_29_6_5_SHAKE_ESK); + } + } + + public static class SNOVA_29_6_5_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_29_6_5_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_29_6_5_SHAKE_SSK); + } + } + + public static class SNOVA_37_8_4_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_8_4_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_8_4_SSK); + } + } + + public static class SNOVA_37_8_4_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_8_4_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_8_4_ESK); + } + } + + public static class SNOVA_37_8_4_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_8_4_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_8_4_SHAKE_ESK); + } + } + + public static class SNOVA_37_8_4_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_8_4_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_8_4_SHAKE_SSK); + } + } + + public static class SNOVA_37_17_2_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_17_2_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_17_2_SSK); + } + } + + public static class SNOVA_37_17_2_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_17_2_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_17_2_ESK); + } + } + + public static class SNOVA_37_17_2_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_17_2_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_17_2_SHAKE_ESK); + } + } + + public static class SNOVA_37_17_2_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_37_17_2_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_37_17_2_SHAKE_SSK); + } + } + + public static class SNOVA_49_11_3_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_49_11_3_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_49_11_3_SSK); + } + } + + public static class SNOVA_49_11_3_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_49_11_3_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_49_11_3_ESK); + } + } + + public static class SNOVA_49_11_3_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_49_11_3_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_49_11_3_SHAKE_ESK); + } + } + + public static class SNOVA_49_11_3_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_49_11_3_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_49_11_3_SHAKE_SSK); + } + } + + public static class SNOVA_56_25_2_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_56_25_2_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_56_25_2_SSK); + } + } + + public static class SNOVA_56_25_2_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_56_25_2_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_56_25_2_ESK); + } + } + + public static class SNOVA_56_25_2_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_56_25_2_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_56_25_2_SHAKE_ESK); + } + } + + public static class SNOVA_56_25_2_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_56_25_2_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_56_25_2_SHAKE_SSK); + } + } + + public static class SNOVA_60_10_4_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_60_10_4_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_60_10_4_SSK); + } + } + + public static class SNOVA_60_10_4_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_60_10_4_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_60_10_4_ESK); + } + } + + public static class SNOVA_60_10_4_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_60_10_4_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_60_10_4_SHAKE_ESK); + } + } + + public static class SNOVA_60_10_4_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_60_10_4_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_60_10_4_SHAKE_SSK); + } + } + + public static class SNOVA_66_15_3_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_66_15_3_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_66_15_3_SSK); + } + } + + public static class SNOVA_66_15_3_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_66_15_3_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_66_15_3_ESK); + } + } + + public static class SNOVA_66_15_3_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_66_15_3_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_66_15_3_SHAKE_ESK); + } + } + + public static class SNOVA_66_15_3_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_66_15_3_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_66_15_3_SHAKE_SSK); + } + } + + public static class SNOVA_75_33_2_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_75_33_2_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_75_33_2_SSK); + } + } + + public static class SNOVA_75_33_2_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_75_33_2_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_75_33_2_ESK); + } + } + + public static class SNOVA_75_33_2_SHAKE_ESK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_75_33_2_SHAKE_ESK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_75_33_2_SHAKE_ESK); + } + } + + public static class SNOVA_75_33_2_SHAKE_SSK + extends org.bouncycastle.pqc.jcajce.provider.snova.SignatureSpi + { + public SNOVA_75_33_2_SHAKE_SSK() + { + super(new SnovaSigner(), SnovaParameters.SNOVA_75_33_2_SHAKE_SSK); + } + } +} + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SnovaKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SnovaKeyFactorySpi.java new file mode 100644 index 0000000000..060696c0f5 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SnovaKeyFactorySpi.java @@ -0,0 +1,531 @@ +package org.bouncycastle.pqc.jcajce.provider.snova; + +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashSet; +import java.util.Set; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.pqc.jcajce.provider.util.BaseKeyFactorySpi; + +public class SnovaKeyFactorySpi + extends BaseKeyFactorySpi +{ + private static final Set keyOids = new HashSet(); + + static + { + keyOids.add(BCObjectIdentifiers.snova_24_5_4_ssk); + keyOids.add(BCObjectIdentifiers.snova_24_5_4_esk); + keyOids.add(BCObjectIdentifiers.snova_24_5_4_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_24_5_4_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_24_5_5_ssk); + keyOids.add(BCObjectIdentifiers.snova_24_5_5_esk); + keyOids.add(BCObjectIdentifiers.snova_24_5_5_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_24_5_5_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_25_8_3_ssk); + keyOids.add(BCObjectIdentifiers.snova_25_8_3_esk); + keyOids.add(BCObjectIdentifiers.snova_25_8_3_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_25_8_3_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_29_6_5_ssk); + keyOids.add(BCObjectIdentifiers.snova_29_6_5_esk); + keyOids.add(BCObjectIdentifiers.snova_29_6_5_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_29_6_5_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_37_8_4_ssk); + keyOids.add(BCObjectIdentifiers.snova_37_8_4_esk); + keyOids.add(BCObjectIdentifiers.snova_37_8_4_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_37_8_4_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_37_17_2_ssk); + keyOids.add(BCObjectIdentifiers.snova_37_17_2_esk); + keyOids.add(BCObjectIdentifiers.snova_37_17_2_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_37_17_2_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_49_11_3_ssk); + keyOids.add(BCObjectIdentifiers.snova_49_11_3_esk); + keyOids.add(BCObjectIdentifiers.snova_49_11_3_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_49_11_3_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_56_25_2_ssk); + keyOids.add(BCObjectIdentifiers.snova_56_25_2_esk); + keyOids.add(BCObjectIdentifiers.snova_56_25_2_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_56_25_2_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_60_10_4_ssk); + keyOids.add(BCObjectIdentifiers.snova_60_10_4_esk); + keyOids.add(BCObjectIdentifiers.snova_60_10_4_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_60_10_4_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_66_15_3_ssk); + keyOids.add(BCObjectIdentifiers.snova_66_15_3_esk); + keyOids.add(BCObjectIdentifiers.snova_66_15_3_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_66_15_3_shake_esk); + keyOids.add(BCObjectIdentifiers.snova_75_33_2_ssk); + keyOids.add(BCObjectIdentifiers.snova_75_33_2_esk); + keyOids.add(BCObjectIdentifiers.snova_75_33_2_shake_ssk); + keyOids.add(BCObjectIdentifiers.snova_75_33_2_shake_esk); + } + + public SnovaKeyFactorySpi() + { + super(keyOids); + } + + public SnovaKeyFactorySpi(ASN1ObjectIdentifier keyOid) + { + super(keyOid); + } + + public final KeySpec engineGetKeySpec(Key key, Class keySpec) + throws InvalidKeySpecException + { + if (key instanceof BCSnovaPrivateKey) + { + if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new PKCS8EncodedKeySpec(key.getEncoded()); + } + } + else if (key instanceof BCSnovaPublicKey) + { + if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) + { + return new X509EncodedKeySpec(key.getEncoded()); + } + } + else + { + throw new InvalidKeySpecException("Unsupported key type: " + + key.getClass() + "."); + } + + throw new InvalidKeySpecException("Unknown key specification: " + + keySpec + "."); + } + + public final Key engineTranslateKey(Key key) + throws InvalidKeyException + { + if (key instanceof BCSnovaPrivateKey || key instanceof BCSnovaPublicKey) + { + return key; + } + + throw new InvalidKeyException("Unsupported key type"); + } + + public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) + throws IOException + { + return new BCSnovaPrivateKey(keyInfo); + } + + public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) + throws IOException + { + return new BCSnovaPublicKey(keyInfo); + } + + public static class SNOVA_24_5_4_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_4_SSK() + { + super(BCObjectIdentifiers.snova_24_5_4_ssk); + } + } + + public static class SNOVA_24_5_4_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_4_ESK() + { + super(BCObjectIdentifiers.snova_24_5_4_esk); + } + } + + public static class SNOVA_24_5_4_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_4_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_24_5_4_shake_ssk); + } + } + + public static class SNOVA_24_5_4_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_4_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_24_5_4_shake_esk); + } + } + + public static class SNOVA_24_5_5_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_5_SSK() + { + super(BCObjectIdentifiers.snova_24_5_5_ssk); + } + } + + public static class SNOVA_24_5_5_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_5_ESK() + { + super(BCObjectIdentifiers.snova_24_5_5_esk); + } + } + + public static class SNOVA_24_5_5_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_5_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_24_5_5_shake_ssk); + } + } + + public static class SNOVA_24_5_5_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_24_5_5_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_24_5_5_shake_esk); + } + } + + public static class SNOVA_25_8_3_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_25_8_3_SSK() + { + super(BCObjectIdentifiers.snova_25_8_3_ssk); + } + } + + public static class SNOVA_25_8_3_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_25_8_3_ESK() + { + super(BCObjectIdentifiers.snova_25_8_3_esk); + } + } + + public static class SNOVA_25_8_3_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_25_8_3_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_25_8_3_shake_ssk); + } + } + + public static class SNOVA_25_8_3_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_25_8_3_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_25_8_3_shake_esk); + } + } + + public static class SNOVA_29_6_5_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_29_6_5_SSK() + { + super(BCObjectIdentifiers.snova_29_6_5_ssk); + } + } + + public static class SNOVA_29_6_5_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_29_6_5_ESK() + { + super(BCObjectIdentifiers.snova_29_6_5_esk); + } + } + + public static class SNOVA_29_6_5_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_29_6_5_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_29_6_5_shake_ssk); + } + } + + public static class SNOVA_29_6_5_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_29_6_5_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_29_6_5_shake_esk); + } + } + + public static class SNOVA_37_8_4_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_37_8_4_SSK() + { + super(BCObjectIdentifiers.snova_37_8_4_ssk); + } + } + + public static class SNOVA_37_8_4_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_37_8_4_ESK() + { + super(BCObjectIdentifiers.snova_37_8_4_esk); + } + } + + public static class SNOVA_37_8_4_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_37_8_4_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_37_8_4_shake_ssk); + } + } + + public static class SNOVA_37_8_4_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_37_8_4_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_37_8_4_shake_esk); + } + } + + public static class SNOVA_37_17_2_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_37_17_2_SSK() + { + super(BCObjectIdentifiers.snova_37_17_2_ssk); + } + } + + public static class SNOVA_37_17_2_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_37_17_2_ESK() + { + super(BCObjectIdentifiers.snova_37_17_2_esk); + } + } + + public static class SNOVA_37_17_2_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_37_17_2_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_37_17_2_shake_ssk); + } + } + + public static class SNOVA_37_17_2_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_37_17_2_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_37_17_2_shake_esk); + } + } + + public static class SNOVA_49_11_3_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_49_11_3_SSK() + { + super(BCObjectIdentifiers.snova_49_11_3_ssk); + } + } + + public static class SNOVA_49_11_3_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_49_11_3_ESK() + { + super(BCObjectIdentifiers.snova_49_11_3_esk); + } + } + + public static class SNOVA_49_11_3_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_49_11_3_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_49_11_3_shake_ssk); + } + } + + public static class SNOVA_49_11_3_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_49_11_3_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_49_11_3_shake_esk); + } + } + + public static class SNOVA_56_25_2_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_56_25_2_SSK() + { + super(BCObjectIdentifiers.snova_56_25_2_ssk); + } + } + + public static class SNOVA_56_25_2_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_56_25_2_ESK() + { + super(BCObjectIdentifiers.snova_56_25_2_esk); + } + } + + public static class SNOVA_56_25_2_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_56_25_2_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_56_25_2_shake_ssk); + } + } + + public static class SNOVA_56_25_2_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_56_25_2_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_56_25_2_shake_esk); + } + } + + public static class SNOVA_60_10_4_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_60_10_4_SSK() + { + super(BCObjectIdentifiers.snova_60_10_4_ssk); + } + } + + public static class SNOVA_60_10_4_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_60_10_4_ESK() + { + super(BCObjectIdentifiers.snova_60_10_4_esk); + } + } + + public static class SNOVA_60_10_4_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_60_10_4_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_60_10_4_shake_ssk); + } + } + + public static class SNOVA_60_10_4_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_60_10_4_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_60_10_4_shake_esk); + } + } + + public static class SNOVA_66_15_3_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_66_15_3_SSK() + { + super(BCObjectIdentifiers.snova_66_15_3_ssk); + } + } + + public static class SNOVA_66_15_3_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_66_15_3_ESK() + { + super(BCObjectIdentifiers.snova_66_15_3_esk); + } + } + + public static class SNOVA_66_15_3_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_66_15_3_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_66_15_3_shake_ssk); + } + } + + public static class SNOVA_66_15_3_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_66_15_3_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_66_15_3_shake_esk); + } + } + + public static class SNOVA_75_33_2_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_75_33_2_SSK() + { + super(BCObjectIdentifiers.snova_75_33_2_ssk); + } + } + + public static class SNOVA_75_33_2_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_75_33_2_ESK() + { + super(BCObjectIdentifiers.snova_75_33_2_esk); + } + } + + public static class SNOVA_75_33_2_SHAKE_SSK + extends SnovaKeyFactorySpi + { + public SNOVA_75_33_2_SHAKE_SSK() + { + super(BCObjectIdentifiers.snova_75_33_2_shake_ssk); + } + } + + public static class SNOVA_75_33_2_SHAKE_ESK + extends SnovaKeyFactorySpi + { + public SNOVA_75_33_2_SHAKE_ESK() + { + super(BCObjectIdentifiers.snova_75_33_2_shake_esk); + } + } +} + + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SnovaKeyPairGeneratorSpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SnovaKeyPairGeneratorSpi.java new file mode 100644 index 0000000000..3a78437f73 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/snova/SnovaKeyPairGeneratorSpi.java @@ -0,0 +1,590 @@ +package org.bouncycastle.pqc.jcajce.provider.snova; + + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.pqc.crypto.snova.SnovaKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaKeyPairGenerator; +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.snova.SnovaPublicKeyParameters; +import org.bouncycastle.pqc.jcajce.provider.util.SpecUtil; +import org.bouncycastle.pqc.jcajce.spec.SnovaParameterSpec; +import org.bouncycastle.util.Strings; + +public class SnovaKeyPairGeneratorSpi + extends java.security.KeyPairGenerator +{ + private static Map parameters = new HashMap(); + + static + { + parameters.put("SNOVA_24_5_4_SSK", SnovaParameters.SNOVA_24_5_4_SSK); + parameters.put("SNOVA_24_5_4_ESK", SnovaParameters.SNOVA_24_5_4_ESK); + parameters.put("SNOVA_24_5_4_SHAKE_SSK", SnovaParameters.SNOVA_24_5_4_SHAKE_SSK); + parameters.put("SNOVA_24_5_4_SHAKE_ESK", SnovaParameters.SNOVA_24_5_4_SHAKE_ESK); + parameters.put("SNOVA_24_5_5_SSK", SnovaParameters.SNOVA_24_5_5_SSK); + parameters.put("SNOVA_24_5_5_ESK", SnovaParameters.SNOVA_24_5_5_ESK); + parameters.put("SNOVA_24_5_5_SHAKE_SSK", SnovaParameters.SNOVA_24_5_5_SHAKE_SSK); + parameters.put("SNOVA_24_5_5_SHAKE_ESK", SnovaParameters.SNOVA_24_5_5_SHAKE_ESK); + parameters.put("SNOVA_25_8_3_SSK", SnovaParameters.SNOVA_25_8_3_SSK); + parameters.put("SNOVA_25_8_3_ESK", SnovaParameters.SNOVA_25_8_3_ESK); + parameters.put("SNOVA_25_8_3_SHAKE_SSK", SnovaParameters.SNOVA_25_8_3_SHAKE_SSK); + parameters.put("SNOVA_25_8_3_SHAKE_ESK", SnovaParameters.SNOVA_25_8_3_SHAKE_ESK); + parameters.put("SNOVA_29_6_5_SSK", SnovaParameters.SNOVA_29_6_5_SSK); + parameters.put("SNOVA_29_6_5_ESK", SnovaParameters.SNOVA_29_6_5_ESK); + parameters.put("SNOVA_29_6_5_SHAKE_SSK", SnovaParameters.SNOVA_29_6_5_SHAKE_SSK); + parameters.put("SNOVA_29_6_5_SHAKE_ESK", SnovaParameters.SNOVA_29_6_5_SHAKE_ESK); + parameters.put("SNOVA_37_8_4_SSK", SnovaParameters.SNOVA_37_8_4_SSK); + parameters.put("SNOVA_37_8_4_ESK", SnovaParameters.SNOVA_37_8_4_ESK); + parameters.put("SNOVA_37_8_4_SHAKE_SSK", SnovaParameters.SNOVA_37_8_4_SHAKE_SSK); + parameters.put("SNOVA_37_8_4_SHAKE_ESK", SnovaParameters.SNOVA_37_8_4_SHAKE_ESK); + parameters.put("SNOVA_37_17_2_SSK", SnovaParameters.SNOVA_37_17_2_SSK); + parameters.put("SNOVA_37_17_2_ESK", SnovaParameters.SNOVA_37_17_2_ESK); + parameters.put("SNOVA_37_17_2_SHAKE_SSK", SnovaParameters.SNOVA_37_17_2_SHAKE_SSK); + parameters.put("SNOVA_37_17_2_SHAKE_ESK", SnovaParameters.SNOVA_37_17_2_SHAKE_ESK); + parameters.put("SNOVA_49_11_3_SSK", SnovaParameters.SNOVA_49_11_3_SSK); + parameters.put("SNOVA_49_11_3_ESK", SnovaParameters.SNOVA_49_11_3_ESK); + parameters.put("SNOVA_49_11_3_SHAKE_SSK", SnovaParameters.SNOVA_49_11_3_SHAKE_SSK); + parameters.put("SNOVA_49_11_3_SHAKE_ESK", SnovaParameters.SNOVA_49_11_3_SHAKE_ESK); + parameters.put("SNOVA_56_25_2_SSK", SnovaParameters.SNOVA_56_25_2_SSK); + parameters.put("SNOVA_56_25_2_ESK", SnovaParameters.SNOVA_56_25_2_ESK); + parameters.put("SNOVA_56_25_2_SHAKE_SSK", SnovaParameters.SNOVA_56_25_2_SHAKE_SSK); + parameters.put("SNOVA_56_25_2_SHAKE_ESK", SnovaParameters.SNOVA_56_25_2_SHAKE_ESK); + parameters.put("SNOVA_60_10_4_SSK", SnovaParameters.SNOVA_60_10_4_SSK); + parameters.put("SNOVA_60_10_4_ESK", SnovaParameters.SNOVA_60_10_4_ESK); + parameters.put("SNOVA_60_10_4_SHAKE_SSK", SnovaParameters.SNOVA_60_10_4_SHAKE_SSK); + parameters.put("SNOVA_60_10_4_SHAKE_ESK", SnovaParameters.SNOVA_60_10_4_SHAKE_ESK); + parameters.put("SNOVA_66_15_3_SSK", SnovaParameters.SNOVA_66_15_3_SSK); + parameters.put("SNOVA_66_15_3_ESK", SnovaParameters.SNOVA_66_15_3_ESK); + parameters.put("SNOVA_66_15_3_SHAKE_SSK", SnovaParameters.SNOVA_66_15_3_SHAKE_SSK); + parameters.put("SNOVA_66_15_3_SHAKE_ESK", SnovaParameters.SNOVA_66_15_3_SHAKE_ESK); + parameters.put("SNOVA_75_33_2_SSK", SnovaParameters.SNOVA_75_33_2_SSK); + parameters.put("SNOVA_75_33_2_ESK", SnovaParameters.SNOVA_75_33_2_ESK); + parameters.put("SNOVA_75_33_2_SHAKE_SSK", SnovaParameters.SNOVA_75_33_2_SHAKE_SSK); + parameters.put("SNOVA_75_33_2_SHAKE_ESK", SnovaParameters.SNOVA_75_33_2_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_4_SSK.getName(), SnovaParameters.SNOVA_24_5_4_SSK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_4_ESK.getName(), SnovaParameters.SNOVA_24_5_4_ESK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_4_SHAKE_SSK.getName(), SnovaParameters.SNOVA_24_5_4_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_4_SHAKE_ESK.getName(), SnovaParameters.SNOVA_24_5_4_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_5_SSK.getName(), SnovaParameters.SNOVA_24_5_5_SSK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_5_ESK.getName(), SnovaParameters.SNOVA_24_5_5_ESK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_SSK.getName(), SnovaParameters.SNOVA_24_5_5_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_ESK.getName(), SnovaParameters.SNOVA_24_5_5_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_25_8_3_SSK.getName(), SnovaParameters.SNOVA_25_8_3_SSK); + parameters.put(SnovaParameterSpec.SNOVA_25_8_3_ESK.getName(), SnovaParameters.SNOVA_25_8_3_ESK); + parameters.put(SnovaParameterSpec.SNOVA_25_8_3_SHAKE_SSK.getName(), SnovaParameters.SNOVA_25_8_3_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_25_8_3_SHAKE_ESK.getName(), SnovaParameters.SNOVA_25_8_3_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_29_6_5_SSK.getName(), SnovaParameters.SNOVA_29_6_5_SSK); + parameters.put(SnovaParameterSpec.SNOVA_29_6_5_ESK.getName(), SnovaParameters.SNOVA_29_6_5_ESK); + parameters.put(SnovaParameterSpec.SNOVA_29_6_5_SHAKE_SSK.getName(), SnovaParameters.SNOVA_29_6_5_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_29_6_5_SHAKE_ESK.getName(), SnovaParameters.SNOVA_29_6_5_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_37_8_4_SSK.getName(), SnovaParameters.SNOVA_37_8_4_SSK); + parameters.put(SnovaParameterSpec.SNOVA_37_8_4_ESK.getName(), SnovaParameters.SNOVA_37_8_4_ESK); + parameters.put(SnovaParameterSpec.SNOVA_37_8_4_SHAKE_SSK.getName(), SnovaParameters.SNOVA_37_8_4_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_37_8_4_SHAKE_ESK.getName(), SnovaParameters.SNOVA_37_8_4_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_37_17_2_SSK.getName(), SnovaParameters.SNOVA_37_17_2_SSK); + parameters.put(SnovaParameterSpec.SNOVA_37_17_2_ESK.getName(), SnovaParameters.SNOVA_37_17_2_ESK); + parameters.put(SnovaParameterSpec.SNOVA_37_17_2_SHAKE_SSK.getName(), SnovaParameters.SNOVA_37_17_2_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_37_17_2_SHAKE_ESK.getName(), SnovaParameters.SNOVA_37_17_2_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_49_11_3_SSK.getName(), SnovaParameters.SNOVA_49_11_3_SSK); + parameters.put(SnovaParameterSpec.SNOVA_49_11_3_ESK.getName(), SnovaParameters.SNOVA_49_11_3_ESK); + parameters.put(SnovaParameterSpec.SNOVA_49_11_3_SHAKE_SSK.getName(), SnovaParameters.SNOVA_49_11_3_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_49_11_3_SHAKE_ESK.getName(), SnovaParameters.SNOVA_49_11_3_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_56_25_2_SSK.getName(), SnovaParameters.SNOVA_56_25_2_SSK); + parameters.put(SnovaParameterSpec.SNOVA_56_25_2_ESK.getName(), SnovaParameters.SNOVA_56_25_2_ESK); + parameters.put(SnovaParameterSpec.SNOVA_56_25_2_SHAKE_SSK.getName(), SnovaParameters.SNOVA_56_25_2_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_56_25_2_SHAKE_ESK.getName(), SnovaParameters.SNOVA_56_25_2_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_60_10_4_SSK.getName(), SnovaParameters.SNOVA_60_10_4_SSK); + parameters.put(SnovaParameterSpec.SNOVA_60_10_4_ESK.getName(), SnovaParameters.SNOVA_60_10_4_ESK); + parameters.put(SnovaParameterSpec.SNOVA_60_10_4_SHAKE_SSK.getName(), SnovaParameters.SNOVA_60_10_4_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_60_10_4_SHAKE_ESK.getName(), SnovaParameters.SNOVA_60_10_4_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_66_15_3_SSK.getName(), SnovaParameters.SNOVA_66_15_3_SSK); + parameters.put(SnovaParameterSpec.SNOVA_66_15_3_ESK.getName(), SnovaParameters.SNOVA_66_15_3_ESK); + parameters.put(SnovaParameterSpec.SNOVA_66_15_3_SHAKE_SSK.getName(), SnovaParameters.SNOVA_66_15_3_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_66_15_3_SHAKE_ESK.getName(), SnovaParameters.SNOVA_66_15_3_SHAKE_ESK); + parameters.put(SnovaParameterSpec.SNOVA_75_33_2_SSK.getName(), SnovaParameters.SNOVA_75_33_2_SSK); + parameters.put(SnovaParameterSpec.SNOVA_75_33_2_ESK.getName(), SnovaParameters.SNOVA_75_33_2_ESK); + parameters.put(SnovaParameterSpec.SNOVA_75_33_2_SHAKE_SSK.getName(), SnovaParameters.SNOVA_75_33_2_SHAKE_SSK); + parameters.put(SnovaParameterSpec.SNOVA_75_33_2_SHAKE_ESK.getName(), SnovaParameters.SNOVA_75_33_2_SHAKE_ESK); + } + + SnovaKeyGenerationParameters param; + private SnovaParameters snovaParameters; + SnovaKeyPairGenerator engine = new SnovaKeyPairGenerator(); + + SecureRandom random = CryptoServicesRegistrar.getSecureRandom(); + boolean initialised = false; + + public SnovaKeyPairGeneratorSpi() + { + super("Snova"); + } + + protected SnovaKeyPairGeneratorSpi(SnovaParameters SnovaParameters) + { + super(SnovaParameters.getName()); + this.snovaParameters = SnovaParameters; + } + + public void initialize( + int strength, + SecureRandom random) + { + throw new IllegalArgumentException("use AlgorithmParameterSpec"); + } + + public void initialize( + AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + String name = getNameFromParams(params); + + if (name != null) + { + param = new SnovaKeyGenerationParameters(random, (SnovaParameters)parameters.get(name)); + + engine.init(param); + initialised = true; + } + else + { + throw new InvalidAlgorithmParameterException("invalid ParameterSpec: " + params); + } + } + + private static String getNameFromParams(AlgorithmParameterSpec paramSpec) + { + if (paramSpec instanceof SnovaParameterSpec) + { + SnovaParameterSpec SnovaParams = (SnovaParameterSpec)paramSpec; + return SnovaParams.getName(); + } + else + { + return Strings.toLowerCase(SpecUtil.getNameFrom(paramSpec)); + } + } + + public KeyPair generateKeyPair() + { + if (!initialised) + { + param = new SnovaKeyGenerationParameters(random, SnovaParameters.SNOVA_24_5_4_SSK); + + engine.init(param); + initialised = true; + } + + AsymmetricCipherKeyPair pair = engine.generateKeyPair(); + SnovaPublicKeyParameters pub = (SnovaPublicKeyParameters)pair.getPublic(); + SnovaPrivateKeyParameters priv = (SnovaPrivateKeyParameters)pair.getPrivate(); + + return new KeyPair(new BCSnovaPublicKey(pub), new BCSnovaPrivateKey(priv)); + } + + public static class SNOVA_24_5_4_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_4_SSK() + { + super(SnovaParameters.SNOVA_24_5_4_SSK); + } + } + + public static class SNOVA_24_5_4_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_4_ESK() + { + super(SnovaParameters.SNOVA_24_5_4_ESK); + } + } + + public static class SNOVA_24_5_4_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_4_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_24_5_4_SHAKE_SSK); + } + } + + public static class SNOVA_24_5_4_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_4_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_24_5_4_SHAKE_ESK); + } + } + + public static class SNOVA_24_5_5_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_5_SSK() + { + super(SnovaParameters.SNOVA_24_5_5_SSK); + } + } + + public static class SNOVA_24_5_5_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_5_ESK() + { + super(SnovaParameters.SNOVA_24_5_5_ESK); + } + } + + public static class SNOVA_24_5_5_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_5_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_24_5_5_SHAKE_SSK); + } + } + + public static class SNOVA_24_5_5_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_24_5_5_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_24_5_5_SHAKE_ESK); + } + } + + public static class SNOVA_25_8_3_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_25_8_3_SSK() + { + super(SnovaParameters.SNOVA_25_8_3_SSK); + } + } + + public static class SNOVA_25_8_3_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_25_8_3_ESK() + { + super(SnovaParameters.SNOVA_25_8_3_ESK); + } + } + + public static class SNOVA_25_8_3_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_25_8_3_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_25_8_3_SHAKE_SSK); + } + } + + public static class SNOVA_25_8_3_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_25_8_3_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_25_8_3_SHAKE_ESK); + } + } + + public static class SNOVA_29_6_5_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_29_6_5_SSK() + { + super(SnovaParameters.SNOVA_29_6_5_SSK); + } + } + + public static class SNOVA_29_6_5_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_29_6_5_ESK() + { + super(SnovaParameters.SNOVA_29_6_5_ESK); + } + } + + public static class SNOVA_29_6_5_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_29_6_5_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_29_6_5_SHAKE_SSK); + } + } + + public static class SNOVA_29_6_5_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_29_6_5_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_29_6_5_SHAKE_ESK); + } + } + + public static class SNOVA_37_8_4_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_8_4_SSK() + { + super(SnovaParameters.SNOVA_37_8_4_SSK); + } + } + + public static class SNOVA_37_8_4_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_8_4_ESK() + { + super(SnovaParameters.SNOVA_37_8_4_ESK); + } + } + + public static class SNOVA_37_8_4_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_8_4_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_37_8_4_SHAKE_SSK); + } + } + + public static class SNOVA_37_8_4_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_8_4_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_37_8_4_SHAKE_ESK); + } + } + + public static class SNOVA_37_17_2_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_17_2_SSK() + { + super(SnovaParameters.SNOVA_37_17_2_SSK); + } + } + + public static class SNOVA_37_17_2_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_17_2_ESK() + { + super(SnovaParameters.SNOVA_37_17_2_ESK); + } + } + + public static class SNOVA_37_17_2_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_17_2_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_37_17_2_SHAKE_SSK); + } + } + + public static class SNOVA_37_17_2_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_37_17_2_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_37_17_2_SHAKE_ESK); + } + } + + public static class SNOVA_49_11_3_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_49_11_3_SSK() + { + super(SnovaParameters.SNOVA_49_11_3_SSK); + } + } + + public static class SNOVA_49_11_3_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_49_11_3_ESK() + { + super(SnovaParameters.SNOVA_49_11_3_ESK); + } + } + + public static class SNOVA_49_11_3_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_49_11_3_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_49_11_3_SHAKE_SSK); + } + } + + public static class SNOVA_49_11_3_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_49_11_3_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_49_11_3_SHAKE_ESK); + } + } + + public static class SNOVA_56_25_2_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_56_25_2_SSK() + { + super(SnovaParameters.SNOVA_56_25_2_SSK); + } + } + + public static class SNOVA_56_25_2_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_56_25_2_ESK() + { + super(SnovaParameters.SNOVA_56_25_2_ESK); + } + } + + public static class SNOVA_56_25_2_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_56_25_2_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_56_25_2_SHAKE_SSK); + } + } + + public static class SNOVA_56_25_2_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_56_25_2_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_56_25_2_SHAKE_ESK); + } + } + + public static class SNOVA_60_10_4_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_60_10_4_SSK() + { + super(SnovaParameters.SNOVA_60_10_4_SSK); + } + } + + public static class SNOVA_60_10_4_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_60_10_4_ESK() + { + super(SnovaParameters.SNOVA_60_10_4_ESK); + } + } + + public static class SNOVA_60_10_4_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_60_10_4_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_60_10_4_SHAKE_SSK); + } + } + + public static class SNOVA_60_10_4_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_60_10_4_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_60_10_4_SHAKE_ESK); + } + } + + public static class SNOVA_66_15_3_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_66_15_3_SSK() + { + super(SnovaParameters.SNOVA_66_15_3_SSK); + } + } + + public static class SNOVA_66_15_3_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_66_15_3_ESK() + { + super(SnovaParameters.SNOVA_66_15_3_ESK); + } + } + + public static class SNOVA_66_15_3_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_66_15_3_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_66_15_3_SHAKE_SSK); + } + } + + public static class SNOVA_66_15_3_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_66_15_3_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_66_15_3_SHAKE_ESK); + } + } + + public static class SNOVA_75_33_2_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_75_33_2_SSK() + { + super(SnovaParameters.SNOVA_75_33_2_SSK); + } + } + + public static class SNOVA_75_33_2_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_75_33_2_ESK() + { + super(SnovaParameters.SNOVA_75_33_2_ESK); + } + } + + public static class SNOVA_75_33_2_SHAKE_SSK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_75_33_2_SHAKE_SSK() + { + super(SnovaParameters.SNOVA_75_33_2_SHAKE_SSK); + } + } + + public static class SNOVA_75_33_2_SHAKE_ESK + extends SnovaKeyPairGeneratorSpi + { + public SNOVA_75_33_2_SHAKE_ESK() + { + super(SnovaParameters.SNOVA_75_33_2_SHAKE_ESK); + } + } +} + diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java index 5c3871f144..2a64e117e3 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/BaseKeyFactorySpi.java @@ -49,6 +49,14 @@ public PrivateKey engineGeneratePrivate(KeySpec keySpec) return generatePrivate(keyInfo); } + catch (InvalidKeySpecException e) + { + throw e; + } + catch (IllegalStateException e) + { + throw new InvalidKeySpecException(e.getMessage()); + } catch (Exception e) { throw new InvalidKeySpecException(e.toString()); @@ -76,6 +84,10 @@ public PublicKey engineGeneratePublic(KeySpec keySpec) return generatePublic(keyInfo); } + catch (InvalidKeySpecException e) + { + throw e; + } catch (Exception e) { throw new InvalidKeySpecException(e.toString()); diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/KdfUtil.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/KdfUtil.java new file mode 100644 index 0000000000..56ec3ba431 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/KdfUtil.java @@ -0,0 +1,200 @@ +package org.bouncycastle.pqc.jcajce.provider.util; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.crypto.DerivationFunction; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.Xof; +import org.bouncycastle.crypto.agreement.kdf.ConcatenationKDFGenerator; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA384Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.digests.SHAKEDigest; +import org.bouncycastle.crypto.generators.HKDFBytesGenerator; +import org.bouncycastle.crypto.generators.KDF2BytesGenerator; +import org.bouncycastle.crypto.macs.KMAC; +import org.bouncycastle.crypto.params.HKDFParameters; +import org.bouncycastle.crypto.params.KDFParameters; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.jcajce.spec.KEMKDFSpec; +import org.bouncycastle.util.Arrays; + +public class KdfUtil +{ + /** + * Generate a byte[] secret key from the passed in secret. Note: passed in secret will be erased after use. + * + * @param kdfSpec definition of the KDF and the output size to produce. + * @param secret the secret value to initialize the KDF with (erased after secret key generation). + * @return a generated secret key. + */ + public static byte[] makeKeyBytes(KEMKDFSpec kdfSpec, byte[] secret) + { + byte[] keyBytes; + try + { + if (kdfSpec == null) + { + keyBytes = new byte[secret.length]; + System.arraycopy(secret, 0, keyBytes, 0, keyBytes.length); + } + else + { + keyBytes = makeKeyBytes(kdfSpec.getKdfAlgorithm(), secret, kdfSpec.getOtherInfo(), + kdfSpec.getKeySize()); + } + } + finally + { + Arrays.clear(secret); + } + + return keyBytes; + } + + static byte[] makeKeyBytes(AlgorithmIdentifier kdfAlgorithm, byte[] secret, byte[] otherInfo, int keySize) + { + byte[] keyBytes = new byte[(keySize + 7) / 8]; + + if (kdfAlgorithm == null) + { + System.arraycopy(secret, 0, keyBytes, 0, keyBytes.length); + } + else if (X9ObjectIdentifiers.id_kdf_kdf2.equals(kdfAlgorithm.getAlgorithm())) + { + AlgorithmIdentifier digAlg = AlgorithmIdentifier.getInstance(kdfAlgorithm.getParameters()); + DerivationFunction kdf = new KDF2BytesGenerator(getDigest(digAlg.getAlgorithm())); + + kdf.init(new KDFParameters(secret, otherInfo)); + + kdf.generateBytes(keyBytes, 0, keyBytes.length); + } + else if (X9ObjectIdentifiers.id_kdf_kdf3.equals(kdfAlgorithm.getAlgorithm())) + { + AlgorithmIdentifier digAlg = AlgorithmIdentifier.getInstance(kdfAlgorithm.getParameters()); + DerivationFunction kdf = new ConcatenationKDFGenerator(getDigest(digAlg.getAlgorithm())); + + kdf.init(new KDFParameters(secret, otherInfo)); + + kdf.generateBytes(keyBytes, 0, keyBytes.length); + } + else if (PKCSObjectIdentifiers.id_alg_hkdf_with_sha256.equals(kdfAlgorithm.getAlgorithm())) + { + if (kdfAlgorithm.getParameters() == null) + { + DerivationFunction kdf = new HKDFBytesGenerator(new SHA256Digest()); + + kdf.init(new HKDFParameters(secret, null, otherInfo)); + + kdf.generateBytes(keyBytes, 0, keyBytes.length); + } + else + { + throw new IllegalStateException("HDKF parameter support not added"); + } + } + else if (PKCSObjectIdentifiers.id_alg_hkdf_with_sha384.equals(kdfAlgorithm.getAlgorithm())) + { + if (kdfAlgorithm.getParameters() == null) + { + DerivationFunction kdf = new HKDFBytesGenerator(new SHA384Digest()); + + kdf.init(new HKDFParameters(secret, null, otherInfo)); + + kdf.generateBytes(keyBytes, 0, keyBytes.length); + } + else + { + throw new IllegalStateException("HDKF parameter support not added"); + } + } + else if (PKCSObjectIdentifiers.id_alg_hkdf_with_sha512.equals(kdfAlgorithm.getAlgorithm())) + { + if (kdfAlgorithm.getParameters() == null) + { + DerivationFunction kdf = new HKDFBytesGenerator(new SHA512Digest()); + + kdf.init(new HKDFParameters(secret, null, otherInfo)); + + kdf.generateBytes(keyBytes, 0, keyBytes.length); + } + else + { + throw new IllegalStateException("HDKF parameter support not added"); + } + } + else if (NISTObjectIdentifiers.id_Kmac128.equals(kdfAlgorithm.getAlgorithm())) + { + byte[] customStr = new byte[0]; + if (kdfAlgorithm.getParameters() != null) + { + customStr = ASN1OctetString.getInstance(kdfAlgorithm.getParameters()).getOctets(); + } + + KMAC mac = new KMAC(128, customStr); + + mac.init(new KeyParameter(secret, 0, secret.length)); + + mac.update(otherInfo, 0, otherInfo.length); + + mac.doFinal(keyBytes, 0, keyBytes.length); + } + else if (NISTObjectIdentifiers.id_Kmac256.equals(kdfAlgorithm.getAlgorithm())) + { + byte[] customStr = new byte[0]; + if (kdfAlgorithm.getParameters() != null) + { + customStr = ASN1OctetString.getInstance(kdfAlgorithm.getParameters()).getOctets(); + } + + KMAC mac = new KMAC(256, customStr); + + mac.init(new KeyParameter(secret, 0, secret.length)); + + mac.update(otherInfo, 0, otherInfo.length); + + mac.doFinal(keyBytes, 0, keyBytes.length); + } + else if (NISTObjectIdentifiers.id_shake256.equals(kdfAlgorithm.getAlgorithm())) + { + Xof xof = new SHAKEDigest(256); + + xof.update(secret, 0, secret.length); + xof.update(otherInfo, 0, otherInfo.length); + + xof.doFinal(keyBytes, 0, keyBytes.length); + } + else + { + throw new IllegalArgumentException("Unrecognized KDF: " + kdfAlgorithm.getAlgorithm()); + } + + return keyBytes; + } + + static Digest getDigest(ASN1ObjectIdentifier oid) + { + if (oid.equals(NISTObjectIdentifiers.id_sha256)) + { + return new SHA256Digest(); + } + if (oid.equals(NISTObjectIdentifiers.id_sha512)) + { + return new SHA512Digest(); + } + if (oid.equals(NISTObjectIdentifiers.id_shake128)) + { + return new SHAKEDigest(128); + } + if (oid.equals(NISTObjectIdentifiers.id_shake256)) + { + return new SHAKEDigest(256); + } + + throw new IllegalArgumentException("unrecognized digest OID: " + oid); + } +} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/WrapUtil.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/WrapUtil.java index cce10a7b91..5a99f1cd7d 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/WrapUtil.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/util/WrapUtil.java @@ -2,26 +2,14 @@ import java.security.InvalidKeyException; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.crypto.DerivationFunction; -import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.Wrapper; -import org.bouncycastle.crypto.Xof; -import org.bouncycastle.crypto.agreement.kdf.ConcatenationKDFGenerator; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.digests.SHA512Digest; -import org.bouncycastle.crypto.digests.SHAKEDigest; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.ARIAEngine; import org.bouncycastle.crypto.engines.CamelliaEngine; import org.bouncycastle.crypto.engines.RFC3394WrapEngine; import org.bouncycastle.crypto.engines.RFC5649WrapEngine; import org.bouncycastle.crypto.engines.SEEDEngine; -import org.bouncycastle.crypto.generators.KDF2BytesGenerator; -import org.bouncycastle.crypto.params.KDFParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jcajce.spec.KTSParameterSpec; import org.bouncycastle.util.Arrays; @@ -67,10 +55,10 @@ public static Wrapper getKeyUnwrapper(KTSParameterSpec ktsParameterSpec, byte[] public static Wrapper getWrapper(String keyAlgorithmName) { Wrapper kWrap; - + if (keyAlgorithmName.equalsIgnoreCase("AESWRAP") || keyAlgorithmName.equalsIgnoreCase("AES")) { - kWrap = new RFC3394WrapEngine(new AESEngine()); + kWrap = new RFC3394WrapEngine(AESEngine.newInstance()); } else if (keyAlgorithmName.equalsIgnoreCase("ARIA")) { @@ -103,67 +91,26 @@ else if (keyAlgorithmName.equalsIgnoreCase("ARIA-KWP")) return kWrap; } - private static byte[] makeKeyBytes(KTSParameterSpec ktsSpec, byte[] secret) - throws InvalidKeyException + public static byte[] trimSecret(String algName, byte[] secret) { - AlgorithmIdentifier kdfAlgorithm = ktsSpec.getKdfAlgorithm(); - byte[] otherInfo = ktsSpec.getOtherInfo(); - byte[] keyBytes = new byte[(ktsSpec.getKeySize() + 7) / 8]; - - if (X9ObjectIdentifiers.id_kdf_kdf2.equals(kdfAlgorithm.getAlgorithm())) + if (algName.equals("SEED")) { - AlgorithmIdentifier digAlg = AlgorithmIdentifier.getInstance(kdfAlgorithm.getParameters()); - DerivationFunction kdf = new KDF2BytesGenerator(getDigest(digAlg.getAlgorithm())); - - kdf.init(new KDFParameters(secret, otherInfo)); - - kdf.generateBytes(keyBytes, 0, keyBytes.length); + return Arrays.copyOfRange(secret, 0, 16); } - else if (X9ObjectIdentifiers.id_kdf_kdf3.equals(kdfAlgorithm.getAlgorithm())) - { - AlgorithmIdentifier digAlg = AlgorithmIdentifier.getInstance(kdfAlgorithm.getParameters()); - DerivationFunction kdf = new ConcatenationKDFGenerator(getDigest(digAlg.getAlgorithm())); - - kdf.init(new KDFParameters(secret, otherInfo)); - - kdf.generateBytes(keyBytes, 0, keyBytes.length); - } - else if (NISTObjectIdentifiers.id_shake256.equals(kdfAlgorithm.getAlgorithm())) - { - Xof xof = new SHAKEDigest(256); - - xof.update(secret, 0, secret.length); - xof.update(otherInfo, 0, otherInfo.length); - - xof.doFinal(keyBytes, 0, keyBytes.length); - } - else - { - throw new InvalidKeyException("Unrecognized KDF: " + kdfAlgorithm.getAlgorithm()); - } - - return keyBytes; + + return secret; } - static Digest getDigest(ASN1ObjectIdentifier oid) + private static byte[] makeKeyBytes(KTSParameterSpec ktsSpec, byte[] secret) + throws InvalidKeyException { - if (oid.equals(NISTObjectIdentifiers.id_sha256)) - { - return new SHA256Digest(); - } - if (oid.equals(NISTObjectIdentifiers.id_sha512)) + try { - return new SHA512Digest(); + return KdfUtil.makeKeyBytes(ktsSpec.getKdfAlgorithm(), secret, ktsSpec.getOtherInfo(), ktsSpec.getKeySize()); } - if (oid.equals(NISTObjectIdentifiers.id_shake128)) + catch (IllegalArgumentException e) { - return new SHAKEDigest(128); + throw new InvalidKeyException(e.getMessage()); } - if (oid.equals(NISTObjectIdentifiers.id_shake256)) - { - return new SHAKEDigest(256); - } - - throw new IllegalArgumentException("unrecognized digest OID: " + oid); } } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/KyberParameterSpec.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/KyberParameterSpec.java index 2858b2cf7c..9cb5ddad20 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/KyberParameterSpec.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/KyberParameterSpec.java @@ -4,15 +4,15 @@ import java.util.HashMap; import java.util.Map; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.util.Strings; public class KyberParameterSpec implements AlgorithmParameterSpec { - public static final KyberParameterSpec kyber512 = new KyberParameterSpec(KyberParameters.kyber512); - public static final KyberParameterSpec kyber768 = new KyberParameterSpec(KyberParameters.kyber768); - public static final KyberParameterSpec kyber1024 = new KyberParameterSpec(KyberParameters.kyber1024); + public static final KyberParameterSpec kyber512 = new KyberParameterSpec(MLKEMParameters.ml_kem_512); + public static final KyberParameterSpec kyber768 = new KyberParameterSpec(MLKEMParameters.ml_kem_768); + public static final KyberParameterSpec kyber1024 = new KyberParameterSpec(MLKEMParameters.ml_kem_1024); private static Map parameters = new HashMap(); @@ -25,7 +25,7 @@ public class KyberParameterSpec private final String name; - private KyberParameterSpec(KyberParameters parameters) + private KyberParameterSpec(MLKEMParameters parameters) { this.name = Strings.toUpperCase(parameters.getName()); } diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/MayoParameterSpec.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/MayoParameterSpec.java new file mode 100644 index 0000000000..9f3ee3e061 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/MayoParameterSpec.java @@ -0,0 +1,48 @@ +package org.bouncycastle.pqc.jcajce.spec; + +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.pqc.crypto.mayo.MayoParameters; +import org.bouncycastle.util.Strings; + +public class MayoParameterSpec + implements AlgorithmParameterSpec +{ + public static final MayoParameterSpec mayo1 = new MayoParameterSpec(MayoParameters.mayo1); + public static final MayoParameterSpec mayo2 = new MayoParameterSpec(MayoParameters.mayo2); + public static final MayoParameterSpec mayo3 = new MayoParameterSpec(MayoParameters.mayo3); + public static final MayoParameterSpec mayo5 = new MayoParameterSpec(MayoParameters.mayo5); + + private static Map parameters = new HashMap(); + + static + { +// parameters.put("mayo1", mayo1); +// parameters.put("mayo2", mayo2); +// parameters.put("mayo3", mayo3); +// parameters.put("mayo5", mayo5); + parameters.put("MAYO_1", mayo1); + parameters.put("MAYO_2", mayo2); + parameters.put("MAYO_3", mayo3); + parameters.put("MAYO_5", mayo5); + } + + private final String name; + + private MayoParameterSpec(MayoParameters parameters) + { + this.name = parameters.getName(); + } + + public String getName() + { + return name; + } + + public static MayoParameterSpec fromName(String name) + { + return (MayoParameterSpec)parameters.get(Strings.toLowerCase(name)); + } +} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/RainbowParameterSpec.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/RainbowParameterSpec.java deleted file mode 100644 index b1efc87996..0000000000 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/RainbowParameterSpec.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bouncycastle.pqc.jcajce.spec; - -import java.security.spec.AlgorithmParameterSpec; -import java.util.HashMap; -import java.util.Map; - -import org.bouncycastle.pqc.crypto.crystals.dilithium.DilithiumParameters; -import org.bouncycastle.pqc.crypto.rainbow.RainbowParameters; -import org.bouncycastle.util.Strings; - -public class RainbowParameterSpec - implements AlgorithmParameterSpec -{ - public static final RainbowParameterSpec rainbowIIIclassic = new RainbowParameterSpec(RainbowParameters.rainbowIIIclassic); - public static final RainbowParameterSpec rainbowIIIcircumzenithal = new RainbowParameterSpec(RainbowParameters.rainbowIIIcircumzenithal); - public static final RainbowParameterSpec rainbowIIIcompressed = new RainbowParameterSpec(RainbowParameters.rainbowIIIcompressed); - - public static final RainbowParameterSpec rainbowVclassic = new RainbowParameterSpec(RainbowParameters.rainbowVclassic); - public static final RainbowParameterSpec rainbowVcircumzenithal = new RainbowParameterSpec(RainbowParameters.rainbowVcircumzenithal); - public static final RainbowParameterSpec rainbowVcompressed = new RainbowParameterSpec(RainbowParameters.rainbowVcompressed); - - private static Map parameters = new HashMap(); - - static - { - parameters.put("rainbow-iii-classic", rainbowIIIclassic); - parameters.put("rainbow-iii-circumzenithal", rainbowIIIcircumzenithal); - parameters.put("rainbow-iii-compressed", rainbowIIIcompressed); - parameters.put("rainbow-v-classic", rainbowVclassic); - parameters.put("rainbow-v-circumzenithal", rainbowVcircumzenithal); - parameters.put("rainbow-v-compressed", rainbowVcompressed); - } - - private final String name; - - private RainbowParameterSpec(RainbowParameters parameters) - { - this.name = Strings.toUpperCase(parameters.getName()); - } - - public String getName() - { - return name; - } - - public static RainbowParameterSpec fromName(String name) - { - return (RainbowParameterSpec)parameters.get(Strings.toLowerCase(name)); - } -} diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SPHINCSPlusParameterSpec.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SPHINCSPlusParameterSpec.java index 014844263e..1493078648 100644 --- a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SPHINCSPlusParameterSpec.java +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SPHINCSPlusParameterSpec.java @@ -21,8 +21,8 @@ public class SPHINCSPlusParameterSpec public static final SPHINCSPlusParameterSpec sha2_256f_robust = new SPHINCSPlusParameterSpec("sha2-256f-robust"); public static final SPHINCSPlusParameterSpec sha2_256s_robust = new SPHINCSPlusParameterSpec("sha2-256s-robust"); - public static final SPHINCSPlusParameterSpec sha2_128f = new SPHINCSPlusParameterSpec("sha2-128s"); - public static final SPHINCSPlusParameterSpec sha2_128s = new SPHINCSPlusParameterSpec("sha2-128f"); + public static final SPHINCSPlusParameterSpec sha2_128f = new SPHINCSPlusParameterSpec("sha2-128f"); + public static final SPHINCSPlusParameterSpec sha2_128s = new SPHINCSPlusParameterSpec("sha2-128s"); public static final SPHINCSPlusParameterSpec sha2_192f = new SPHINCSPlusParameterSpec("sha2-192f"); public static final SPHINCSPlusParameterSpec sha2_192s = new SPHINCSPlusParameterSpec("sha2-192s"); diff --git a/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SnovaParameterSpec.java b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SnovaParameterSpec.java new file mode 100644 index 0000000000..2e72629f24 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/pqc/jcajce/spec/SnovaParameterSpec.java @@ -0,0 +1,145 @@ +package org.bouncycastle.pqc.jcajce.spec; + +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; +import java.util.Map; + +import org.bouncycastle.pqc.crypto.snova.SnovaParameters; +import org.bouncycastle.util.Strings; + +public class SnovaParameterSpec + implements AlgorithmParameterSpec +{ + public static final SnovaParameterSpec SNOVA_24_5_4_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_4_SSK); + public static final SnovaParameterSpec SNOVA_24_5_4_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_4_ESK); + public static final SnovaParameterSpec SNOVA_24_5_4_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_4_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_24_5_4_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_4_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_24_5_5_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_5_SSK); + public static final SnovaParameterSpec SNOVA_24_5_5_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_5_ESK); + public static final SnovaParameterSpec SNOVA_24_5_5_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_5_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_24_5_5_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_24_5_5_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_25_8_3_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_25_8_3_SSK); + public static final SnovaParameterSpec SNOVA_25_8_3_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_25_8_3_ESK); + public static final SnovaParameterSpec SNOVA_25_8_3_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_25_8_3_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_25_8_3_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_25_8_3_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_29_6_5_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_29_6_5_SSK); + public static final SnovaParameterSpec SNOVA_29_6_5_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_29_6_5_ESK); + public static final SnovaParameterSpec SNOVA_29_6_5_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_29_6_5_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_29_6_5_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_29_6_5_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_37_8_4_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_8_4_SSK); + public static final SnovaParameterSpec SNOVA_37_8_4_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_8_4_ESK); + public static final SnovaParameterSpec SNOVA_37_8_4_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_8_4_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_37_8_4_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_8_4_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_37_17_2_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_17_2_SSK); + public static final SnovaParameterSpec SNOVA_37_17_2_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_17_2_ESK); + public static final SnovaParameterSpec SNOVA_37_17_2_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_17_2_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_37_17_2_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_37_17_2_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_49_11_3_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_49_11_3_SSK); + public static final SnovaParameterSpec SNOVA_49_11_3_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_49_11_3_ESK); + public static final SnovaParameterSpec SNOVA_49_11_3_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_49_11_3_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_49_11_3_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_49_11_3_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_56_25_2_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_56_25_2_SSK); + public static final SnovaParameterSpec SNOVA_56_25_2_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_56_25_2_ESK); + public static final SnovaParameterSpec SNOVA_56_25_2_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_56_25_2_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_56_25_2_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_56_25_2_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_60_10_4_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_60_10_4_SSK); + public static final SnovaParameterSpec SNOVA_60_10_4_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_60_10_4_ESK); + public static final SnovaParameterSpec SNOVA_60_10_4_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_60_10_4_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_60_10_4_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_60_10_4_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_66_15_3_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_66_15_3_SSK); + public static final SnovaParameterSpec SNOVA_66_15_3_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_66_15_3_ESK); + public static final SnovaParameterSpec SNOVA_66_15_3_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_66_15_3_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_66_15_3_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_66_15_3_SHAKE_ESK); + + public static final SnovaParameterSpec SNOVA_75_33_2_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_75_33_2_SSK); + public static final SnovaParameterSpec SNOVA_75_33_2_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_75_33_2_ESK); + public static final SnovaParameterSpec SNOVA_75_33_2_SHAKE_SSK = new SnovaParameterSpec(SnovaParameters.SNOVA_75_33_2_SHAKE_SSK); + public static final SnovaParameterSpec SNOVA_75_33_2_SHAKE_ESK = new SnovaParameterSpec(SnovaParameters.SNOVA_75_33_2_SHAKE_ESK); + + + private static Map parameters = new HashMap(); + + static + { + parameters.put("SNOVA_24_5_4_SSK", SNOVA_24_5_4_SSK); + parameters.put("SNOVA_24_5_4_ESK", SNOVA_24_5_4_ESK); + parameters.put("SNOVA_24_5_4_SHAKE_SSK", SNOVA_24_5_4_SHAKE_SSK); + parameters.put("SNOVA_24_5_4_SHAKE_ESK", SNOVA_24_5_4_SHAKE_ESK); + + parameters.put("SNOVA_24_5_5_SSK", SNOVA_24_5_5_SSK); + parameters.put("SNOVA_24_5_5_ESK", SNOVA_24_5_5_ESK); + parameters.put("SNOVA_24_5_5_SHAKE_SSK", SNOVA_24_5_5_SHAKE_SSK); + parameters.put("SNOVA_24_5_5_SHAKE_ESK", SNOVA_24_5_5_SHAKE_ESK); + + parameters.put("SNOVA_25_8_3_SSK", SNOVA_25_8_3_SSK); + parameters.put("SNOVA_25_8_3_ESK", SNOVA_25_8_3_ESK); + parameters.put("SNOVA_25_8_3_SHAKE_SSK", SNOVA_25_8_3_SHAKE_SSK); + parameters.put("SNOVA_25_8_3_SHAKE_ESK", SNOVA_25_8_3_SHAKE_ESK); + + parameters.put("SNOVA_29_6_5_SSK", SNOVA_29_6_5_SSK); + parameters.put("SNOVA_29_6_5_ESK", SNOVA_29_6_5_ESK); + parameters.put("SNOVA_29_6_5_SHAKE_SSK", SNOVA_29_6_5_SHAKE_SSK); + parameters.put("SNOVA_29_6_5_SHAKE_ESK", SNOVA_29_6_5_SHAKE_ESK); + + parameters.put("SNOVA_37_8_4_SSK", SNOVA_37_8_4_SSK); + parameters.put("SNOVA_37_8_4_ESK", SNOVA_37_8_4_ESK); + parameters.put("SNOVA_37_8_4_SHAKE_SSK", SNOVA_37_8_4_SHAKE_SSK); + parameters.put("SNOVA_37_8_4_SHAKE_ESK", SNOVA_37_8_4_SHAKE_ESK); + + parameters.put("SNOVA_37_17_2_SSK", SNOVA_37_17_2_SSK); + parameters.put("SNOVA_37_17_2_ESK", SNOVA_37_17_2_ESK); + parameters.put("SNOVA_37_17_2_SHAKE_SSK", SNOVA_37_17_2_SHAKE_SSK); + parameters.put("SNOVA_37_17_2_SHAKE_ESK", SNOVA_37_17_2_SHAKE_ESK); + + parameters.put("SNOVA_49_11_3_SSK", SNOVA_49_11_3_SSK); + parameters.put("SNOVA_49_11_3_ESK", SNOVA_49_11_3_ESK); + parameters.put("SNOVA_49_11_3_SHAKE_SSK", SNOVA_49_11_3_SHAKE_SSK); + parameters.put("SNOVA_49_11_3_SHAKE_ESK", SNOVA_49_11_3_SHAKE_ESK); + + parameters.put("SNOVA_56_25_2_SSK", SNOVA_56_25_2_SSK); + parameters.put("SNOVA_56_25_2_ESK", SNOVA_56_25_2_ESK); + parameters.put("SNOVA_56_25_2_SHAKE_SSK", SNOVA_56_25_2_SHAKE_SSK); + parameters.put("SNOVA_56_25_2_SHAKE_ESK", SNOVA_56_25_2_SHAKE_ESK); + + parameters.put("SNOVA_60_10_4_SSK", SNOVA_60_10_4_SSK); + parameters.put("SNOVA_60_10_4_ESK", SNOVA_60_10_4_ESK); + parameters.put("SNOVA_60_10_4_SHAKE_SSK", SNOVA_60_10_4_SHAKE_SSK); + parameters.put("SNOVA_60_10_4_SHAKE_ESK", SNOVA_60_10_4_SHAKE_ESK); + + parameters.put("SNOVA_66_15_3_SSK", SNOVA_66_15_3_SSK); + parameters.put("SNOVA_66_15_3_ESK", SNOVA_66_15_3_ESK); + parameters.put("SNOVA_66_15_3_SHAKE_SSK", SNOVA_66_15_3_SHAKE_SSK); + parameters.put("SNOVA_66_15_3_SHAKE_ESK", SNOVA_66_15_3_SHAKE_ESK); + + parameters.put("SNOVA_75_33_2_SSK", SNOVA_75_33_2_SSK); + parameters.put("SNOVA_75_33_2_ESK", SNOVA_75_33_2_ESK); + parameters.put("SNOVA_75_33_2_SHAKE_SSK", SNOVA_75_33_2_SHAKE_SSK); + parameters.put("SNOVA_75_33_2_SHAKE_ESK", SNOVA_75_33_2_SHAKE_ESK); + } + + private final String name; + + private SnovaParameterSpec(SnovaParameters parameters) + { + this.name = parameters.getName(); + } + + public String getName() + { + return name; + } + + public static SnovaParameterSpec fromName(String name) + { + return (SnovaParameterSpec)parameters.get(Strings.toLowerCase(name)); + } +} diff --git a/prov/src/main/java/org/bouncycastle/x509/PKIXCertPathReviewer.java b/prov/src/main/java/org/bouncycastle/x509/PKIXCertPathReviewer.java index 95bab614dd..d8d090f066 100644 --- a/prov/src/main/java/org/bouncycastle/x509/PKIXCertPathReviewer.java +++ b/prov/src/main/java/org/bouncycastle/x509/PKIXCertPathReviewer.java @@ -91,7 +91,9 @@ public class PKIXCertPathReviewer extends CertPathValidatorUtilities private static final String AUTH_INFO_ACCESS = Extension.authorityInfoAccess.getId(); private static final String RESOURCE_NAME = "org.bouncycastle.x509.CertPathReviewerMessages"; - + + private static final int NAME_CHECK_MAX = (1 << 10); + // input parameters protected CertPath certPath; @@ -501,9 +503,15 @@ private void checkNameConstraints() ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.subjAltNameExtError"); throw new CertPathReviewerException(msg,ae,certPath,index); } - + if (altName != null) { + if (altName.size() > NAME_CHECK_MAX) + { + ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.subjAltNameExtError"); + throw new CertPathReviewerException(msg,certPath,index); + } + for (int j = 0; j < altName.size(); j++) { GeneralName name = GeneralName.getInstance(altName.getObjectAt(j)); @@ -519,87 +527,6 @@ private void checkNameConstraints() new Object[] {new UntrustedInput(name)}); throw new CertPathReviewerException(msg,cpve,certPath,index); } -// switch(o.getTagNo()) TODO - move resources to PKIXNameConstraints -// { -// case 1: -// String email = ASN1IA5String.getInstance(o, true).getString(); -// -// try -// { -// checkPermittedEmail(permittedSubtreesEmail, email); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.notPermittedEmail", -// new Object[] {new UntrustedInput(email)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// try -// { -// checkExcludedEmail(excludedSubtreesEmail, email); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.excludedEmail", -// new Object[] {new UntrustedInput(email)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// break; -// case 4: -// ASN1Sequence altDN = ASN1Sequence.getInstance(o, true); -// -// try -// { -// checkPermittedDN(permittedSubtreesDN, altDN); -// } -// catch (CertPathValidatorException cpve) -// { -// X509Name altDNName = new X509Name(altDN); -// ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.notPermittedDN", -// new Object[] {new UntrustedInput(altDNName)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// try -// { -// checkExcludedDN(excludedSubtreesDN, altDN); -// } -// catch (CertPathValidatorException cpve) -// { -// X509Name altDNName = new X509Name(altDN); -// ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.excludedDN", -// new Object[] {new UntrustedInput(altDNName)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// break; -// case 7: -// byte[] ip = ASN1OctetString.getInstance(o, true).getOctets(); -// -// try -// { -// checkPermittedIP(permittedSubtreesIP, ip); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.notPermittedIP", -// new Object[] {IPtoString(ip)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// -// try -// { -// checkExcludedIP(excludedSubtreesIP, ip); -// } -// catch (CertPathValidatorException cpve) -// { -// ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,"CertPathReviewer.excludedIP", -// new Object[] {IPtoString(ip)}); -// throw new CertPathReviewerException(msg,cpve,certPath,index); -// } -// } } } } diff --git a/prov/src/main/java/org/bouncycastle/x509/X509V2AttributeCertificate.java b/prov/src/main/java/org/bouncycastle/x509/X509V2AttributeCertificate.java index 8eb5e983af..9ef019376b 100644 --- a/prov/src/main/java/org/bouncycastle/x509/X509V2AttributeCertificate.java +++ b/prov/src/main/java/org/bouncycastle/x509/X509V2AttributeCertificate.java @@ -265,12 +265,12 @@ public Set getCriticalExtensionOIDs() { return getExtensionOIDs(true); } - + public boolean hasUnsupportedCriticalExtension() { - Set extensions = getCriticalExtensionOIDs(); + Extensions extensions = cert.getAcinfo().getExtensions(); - return extensions != null && !extensions.isEmpty(); + return extensions != null && extensions.hasAnyCriticalExtensions(); } public X509Attribute[] getAttributes() diff --git a/prov/src/main/java/org/bouncycastle/x509/extension/AuthorityKeyIdentifierStructure.java b/prov/src/main/java/org/bouncycastle/x509/extension/AuthorityKeyIdentifierStructure.java index bcd5993264..b629286e46 100644 --- a/prov/src/main/java/org/bouncycastle/x509/extension/AuthorityKeyIdentifierStructure.java +++ b/prov/src/main/java/org/bouncycastle/x509/extension/AuthorityKeyIdentifierStructure.java @@ -1,6 +1,7 @@ package org.bouncycastle.x509.extension; import java.io.IOException; +import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PublicKey; import java.security.cert.CertificateParsingException; @@ -59,48 +60,36 @@ public AuthorityKeyIdentifierStructure( super((ASN1Sequence)extension.getParsedValue()); } - private static ASN1Sequence fromCertificate( - X509Certificate certificate) + private static ASN1Sequence fromCertificate(X509Certificate certificate) throws CertificateParsingException { try { - if (certificate.getVersion() != 3) - { - GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate)); - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(certificate.getPublicKey().getEncoded()); - - return (ASN1Sequence)new AuthorityKeyIdentifier( - info, new GeneralNames(genName), certificate.getSerialNumber()).toASN1Primitive(); - } - else + GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate)); + GeneralNames genNames = new GeneralNames(genName); + BigInteger serialNumber = certificate.getSerialNumber(); + + if (certificate.getVersion() == 3) { - GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate)); - - byte[] ext = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId()); - + byte[] ext = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId()); if (ext != null) { - ASN1OctetString str = (ASN1OctetString)X509ExtensionUtil.fromExtensionValue(ext); - - return (ASN1Sequence)new AuthorityKeyIdentifier( - str.getOctets(), new GeneralNames(genName), certificate.getSerialNumber()).toASN1Primitive(); - } - else - { - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(certificate.getPublicKey().getEncoded()); - - return (ASN1Sequence)new AuthorityKeyIdentifier( - info, new GeneralNames(genName), certificate.getSerialNumber()).toASN1Primitive(); + ASN1OctetString str = (ASN1OctetString)X509ExtensionUtil.fromExtensionValue(ext); + return (ASN1Sequence)new AuthorityKeyIdentifier(str.getOctets(), genNames, serialNumber) + .toASN1Primitive(); } } + + SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(certificate.getPublicKey().getEncoded()); + + return (ASN1Sequence)new AuthorityKeyIdentifier(info, genNames, serialNumber).toASN1Primitive(); } catch (Exception e) { throw new CertificateParsingException("Exception extracting certificate details: " + e.toString()); } } - + private static ASN1Sequence fromKey( PublicKey pubKey) throws InvalidKeyException diff --git a/prov/src/main/java/org/bouncycastle/x509/extension/package-info.java b/prov/src/main/java/org/bouncycastle/x509/extension/package-info.java new file mode 100644 index 0000000000..1a1f5d19cb --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/x509/extension/package-info.java @@ -0,0 +1,4 @@ +/** + * Helper classes for dealing with common X.509 extensions. + */ +package org.bouncycastle.x509.extension; diff --git a/prov/src/main/java/org/bouncycastle/x509/package-info.java b/prov/src/main/java/org/bouncycastle/x509/package-info.java new file mode 100644 index 0000000000..d99d598228 --- /dev/null +++ b/prov/src/main/java/org/bouncycastle/x509/package-info.java @@ -0,0 +1,6 @@ +/** + *

      + * Classes for supporting the generation of X.509 certificates and X.509 attribute certificates. + *

      + */ +package org.bouncycastle.x509; diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java index de4b6c6b04..4b514109db 100644 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java +++ b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ec/GMSignatureSpi.java @@ -31,7 +31,7 @@ public class GMSignatureSpi private SM2Signer signer; - GMSignatureSpi(SM2Signer signer) + protected GMSignatureSpi(SM2Signer signer) { super("SM3withSM2"); this.signer = signer; diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java index 21391a5323..a54d4aa287 100644 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java +++ b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java @@ -17,19 +17,20 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.util.MessageDigestUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Exceptions; import org.bouncycastle.util.Strings; - class X509SignatureUtil { private static final Map algNames = new HashMap(); @@ -42,29 +43,56 @@ class X509SignatureUtil algNames.put(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1withDSA"); } - private static final ASN1Null derNull = DERNull.INSTANCE; + static byte[] getExtensionValue(Extensions extensions, String oid) + { + if (oid != null) + { + ASN1ObjectIdentifier asn1Oid = ASN1ObjectIdentifier.tryFromID(oid); + if (asn1Oid != null) + { + ASN1OctetString extValue = Extensions.getExtensionValue(extensions, asn1Oid); + if (null != extValue) + { + try + { + return extValue.getEncoded(); + } + catch (Exception e) + { + throw Exceptions.illegalStateException("error parsing " + e.getMessage(), e); + } + } + } + } + return null; + } + + private static boolean isAbsentOrEmptyParameters(ASN1Encodable parameters) + { + return parameters == null || DERNull.INSTANCE.equals(parameters); + } - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) + static void setSignatureParameters(Signature signature, ASN1Encodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { - if (params != null && !derNull.equals(params)) + if (!isAbsentOrEmptyParameters(params)) { + String sigAlgName = signature.getAlgorithm(); - AlgorithmParameters sigParams; + String sigParamsAlg; + if (sigAlgName.indexOf("MGF1") > 0) + { + sigParamsAlg = "PSS"; + } + else + { + sigParamsAlg = Strings.toUpperCase(sigAlgName); + } try { - if (signature.getAlgorithm().indexOf("MGF1") > 0) - { - sigParams = AlgorithmParameters.getInstance("PSS"); - } - else - { - sigParams = AlgorithmParameters.getInstance(Strings.toUpperCase(signature.getAlgorithm())); - } - + AlgorithmParameters sigParams = AlgorithmParameters.getInstance(sigParamsAlg); + sigParams.init(params.toASN1Primitive().getEncoded()); } catch (IOException e) @@ -73,38 +101,38 @@ static void setSignatureParameters( } } } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) + + static String getSignatureName(AlgorithmIdentifier sigAlgId) { + ASN1ObjectIdentifier sigAlgOid = sigAlgId.getAlgorithm(); ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) + + if (!isAbsentOrEmptyParameters(params)) { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) + if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgOid)) { RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - + return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "WITHRSAANDMGF1"; } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) + if (X9ObjectIdentifiers.ecdsa_with_SHA2.equals(sigAlgOid)) { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "WITHECDSA"; + AlgorithmIdentifier ecDsaParams = AlgorithmIdentifier.getInstance(params); + + return getDigestAlgName(ecDsaParams.getAlgorithm()) + "WITHECDSA"; } } // deal with the "weird" ones. - String algName = (String)algNames.get(sigAlgId.getAlgorithm()); + String algName = (String)algNames.get(sigAlgOid); if (algName != null) { return algName; } - return findAlgName(sigAlgId.getAlgorithm()); + return findAlgName(sigAlgOid); } - + /** * Return the digest algorithm using one of the standard JCA string * representations rather the the algorithm identifier (if possible). @@ -155,7 +183,7 @@ private static String findAlgName(ASN1ObjectIdentifier algOid) private static String lookupAlg(Provider prov, ASN1ObjectIdentifier algOid) { - String algName = prov.getProperty("Alg.Alias.Signature." + algOid); + String algName = prov.getProperty("Alg.Alias.Signature." + algOid); if (algName != null) { diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java index 22e4a21516..b5c1f9fd3d 100644 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java +++ b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java @@ -43,7 +43,7 @@ public final class BouncyCastleProvider extends Provider implements ConfigurableProvider { - private static String info = "BouncyCastle Security Provider v1.78.1"; + private static String info = "BouncyCastle Security Provider v1.81"; public static final String PROVIDER_NAME = "BC"; @@ -118,7 +118,7 @@ public final class BouncyCastleProvider extends Provider */ public BouncyCastleProvider() { - super(PROVIDER_NAME, 1.7801, info); + super(PROVIDER_NAME, 1.8100, info); setup(); } diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java index d256e7d1a0..9e5e6a9872 100644 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java +++ b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java @@ -37,7 +37,9 @@ import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.IssuingDistributionPoint; import org.bouncycastle.asn1.x509.TBSCertList; +import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.jce.X509Principal; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.x509.extension.X509ExtensionUtil; @@ -102,30 +104,41 @@ public X509CRLObject( } } - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) + if (getVersion() == 2) { - return false; - } + Extensions extensions = c.getExtensions(); + if (extensions != null) + { + Enumeration e = extensions.oids(); + while (e.hasMoreElements()) + { + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); + if (Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid)) + { + continue; + } + + Extension ext = extensions.getExtension(oid); + if (ext.isCritical()) + { + return true; + } + } + } + } - return !extns.isEmpty(); + return false; } private Set getExtensionOIDs(boolean critical) { if (this.getVersion() == 2) { - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -162,26 +175,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public byte[] getEncoded() @@ -250,12 +244,9 @@ public Date getThisUpdate() public Date getNextUpdate() { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } + Time nextUpdate = c.getNextUpdate(); - return null; + return null == nextUpdate ? null : nextUpdate.getDate(); } private Set loadCRLEntries() @@ -353,16 +344,7 @@ public String getSigAlgOID() public byte[] getSigAlgParams() { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; + return Arrays.clone(sigAlgParams); } /** @@ -404,7 +386,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java index 1e4c262dd3..0ff3c41c21 100644 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java +++ b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java @@ -34,6 +34,7 @@ import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -83,7 +84,7 @@ public X509CertificateObject( try { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); + byte[] bytes = getExtensionOctets(c, Extension.basicConstraints); if (bytes != null) { @@ -97,10 +98,10 @@ public X509CertificateObject( try { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); + byte[] bytes = getExtensionOctets(c, Extension.keyUsage); if (bytes != null) { - ASN1BitString bits = ASN1BitString.getInstance(ASN1Primitive.fromByteArray(bytes)); + ASN1BitString bits = ASN1BitString.getInstance(ASN1Primitive.fromByteArray(bytes)); bytes = bits.getBytes(); int length = (bytes.length * 8) - bits.getPadBits(); @@ -312,32 +313,29 @@ public boolean[] getKeyUsage() public List getExtendedKeyUsage() throws CertificateParsingException { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); + byte[] extOctets = getExtensionOctets(c, Extension.extendedKeyUsage); + if (null == extOctets) + { + return null; + } - if (bytes != null) + try { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); + ASN1Sequence seq = ASN1Sequence.getInstance(extOctets); - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) + List list = new ArrayList(); + for (int i = 0; i != seq.size(); i++) { - throw new CertificateParsingException("error processing extended key usage extension"); + list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); } + return Collections.unmodifiableList(list); + } + catch (Exception e) + { + throw new CertificateParsingException("error processing extended key usage extension"); } - - return null; } - + public int getBasicConstraints() { if (basicConstraints != null) @@ -365,13 +363,13 @@ public int getBasicConstraints() public Collection getSubjectAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); + return getAlternativeNames(c, Extension.subjectAlternativeName); } public Collection getIssuerAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); + return getAlternativeNames(c, Extension.issuerAlternativeName); } public Set getCriticalExtensionOIDs() @@ -379,7 +377,7 @@ public Set getCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -403,44 +401,9 @@ public Set getCriticalExtensionOIDs() return null; } - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - public byte[] getExtensionValue(String oid) { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public Set getNonCriticalExtensionOIDs() @@ -448,7 +411,7 @@ public Set getNonCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -474,36 +437,32 @@ public Set getNonCriticalExtensionOIDs() public boolean hasUnsupportedCriticalExtension() { - if (this.getVersion() == 3) + if (getVersion() == 3) { - Extensions extensions = c.getTBSCertificate().getExtensions(); - + Extensions extensions = c.getExtensions(); if (extensions != null) { - Enumeration e = extensions.oids(); - + Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) + + if (Extension.keyUsage.equals(oid) || + Extension.certificatePolicies.equals(oid) || + Extension.policyMappings.equals(oid) || + Extension.inhibitAnyPolicy.equals(oid) || + Extension.cRLDistributionPoints.equals(oid) || + Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid) || + Extension.policyConstraints.equals(oid) || + Extension.basicConstraints.equals(oid) || + Extension.subjectAlternativeName.equals(oid) || + Extension.nameConstraints.equals(oid)) { continue; } - Extension ext = extensions.getExtension(oid); - + Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { return true; @@ -644,7 +603,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -799,17 +758,18 @@ private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) return id1.getParameters().equals(id2.getParameters()); } - private static Collection getAlternativeNames(byte[] extVal) + private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) throws CertificateParsingException { - if (extVal == null) + byte[] extOctets = getExtensionOctets(c, oid); + if (extOctets == null) { return null; } try { Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); + Enumeration it = ASN1Sequence.getInstance(extOctets).getObjects(); while (it.hasMoreElements()) { GeneralName genName = GeneralName.getInstance(it.nextElement()); @@ -854,4 +814,11 @@ private static Collection getAlternativeNames(byte[] extVal) throw new CertificateParsingException(e.getMessage()); } } + + private static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) + { + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); + + return extValue == null ? null : extValue.getOctets(); + } } diff --git a/prov/src/main/jdk1.1/org/bouncycastle/pqc/jcajce/provider/util/SpecUtil.java b/prov/src/main/jdk1.1/org/bouncycastle/pqc/jcajce/provider/util/SpecUtil.java new file mode 100644 index 0000000000..4ffa4c6d9a --- /dev/null +++ b/prov/src/main/jdk1.1/org/bouncycastle/pqc/jcajce/provider/util/SpecUtil.java @@ -0,0 +1,15 @@ +package org.bouncycastle.pqc.jcajce.provider.util; + +import java.lang.reflect.Method; +import java.security.spec.AlgorithmParameterSpec; + +public class SpecUtil +{ + private static Class[] NO_PARAMS = new Class[0]; + private static Object[] NO_ARGS = new Object[0]; + + public static String getNameFrom(final AlgorithmParameterSpec paramSpec) + { + return null; + } +} diff --git a/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/KeyFactorySpi.java b/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/KeyFactorySpi.java index f67a553fb7..4359196180 100644 --- a/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/KeyFactorySpi.java +++ b/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/KeyFactorySpi.java @@ -5,22 +5,26 @@ import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; +import java.security.interfaces.EdECPrivateKey; +import java.security.interfaces.EdECPublicKey; +import java.security.spec.EdECPrivateKeySpec; +import java.security.spec.EdECPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; +import java.security.spec.NamedParameterSpec; import java.security.spec.X509EncodedKeySpec; +import java.util.Optional; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; import org.bouncycastle.crypto.params.Ed448PublicKeyParameters; @@ -28,6 +32,7 @@ import org.bouncycastle.crypto.params.X448PublicKeyParameters; import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; +import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.jcajce.interfaces.EdDSAPublicKey; import org.bouncycastle.jcajce.interfaces.XDHPublicKey; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; @@ -129,6 +134,28 @@ else if (spec.isAssignableFrom(RawEncodedKeySpec.class)) return new RawEncodedKeySpec(((EdDSAPublicKey)key).getPointEncoding()); } } + else if (spec.isAssignableFrom(EdECPrivateKeySpec.class)) + { + if (key instanceof EdECPrivateKey) + { + Optional bytes = ((EdECPrivateKey)key).getBytes(); + if (bytes.isPresent()) + { + return new EdECPrivateKeySpec(((EdECPrivateKey)key).getParams(), bytes.get()); + } + else + { + throw new IllegalArgumentException("no byte[] data associated with key"); + } + } + } + else if (spec.isAssignableFrom(EdECPublicKeySpec.class)) + { + if (key instanceof EdECPublicKey) + { + return new EdECPublicKeySpec(((EdECPublicKey)key).getParams(), ((EdECPublicKey)key).getPoint()); + } + } return super.engineGetKeySpec(key, spec); } @@ -144,7 +171,32 @@ protected PrivateKey engineGeneratePrivate( { return new BC15EdDSAPrivateKey((Ed25519PrivateKeyParameters)parameters); } - throw new IllegalStateException("openssh private key not Ed25519 private key"); + throw new InvalidKeySpecException("openssh private key not Ed25519 private key"); + } + else if (keySpec instanceof EdECPrivateKeySpec) + { + EdECPrivateKeySpec edSpec = (EdECPrivateKeySpec)keySpec; + try + { + AsymmetricKeyParameter parameters; + if (NamedParameterSpec.ED448.getName().equalsIgnoreCase(edSpec.getParams().getName())) + { + parameters = SignatureSpi.getEd448PrivateKey(edSpec.getBytes()); + } + else if (NamedParameterSpec.ED25519.getName().equalsIgnoreCase(edSpec.getParams().getName())) + { + parameters = SignatureSpi.getEd25519PrivateKey(edSpec.getBytes()); + } + else + { + throw new InvalidKeySpecException("unrecognized named parameters: " + edSpec.getParams().getName()); + } + return new BC15EdDSAPrivateKey(parameters); + } + catch (InvalidKeyException e) + { + throw new InvalidKeySpecException(e.getMessage(), e); + } } return super.engineGeneratePrivate(keySpec); @@ -210,6 +262,31 @@ else if (keySpec instanceof RawEncodedKeySpec) throw new InvalidKeySpecException("factory not a specific type, cannot recognise raw encoding"); } } + else if (keySpec instanceof EdECPublicKeySpec) + { + EdECPublicKeySpec edSpec = (EdECPublicKeySpec)keySpec; + try + { + AsymmetricKeyParameter parameters; + if (NamedParameterSpec.ED448.getName().equalsIgnoreCase(edSpec.getParams().getName())) + { + parameters = SignatureSpi.getEd448PublicKey(edSpec.getPoint()); + } + else if (NamedParameterSpec.ED25519.getName().equalsIgnoreCase(edSpec.getParams().getName())) + { + parameters = SignatureSpi.getEd25519PublicKey(edSpec.getPoint()); + } + else + { + throw new InvalidKeySpecException("unrecognized named parameters: " + edSpec.getParams().getName()); + } + return new BC15EdDSAPublicKey(parameters); + } + catch (InvalidKeyException e) + { + throw new InvalidKeySpecException(e.getMessage(), e); + } + } else if (keySpec instanceof OpenSSHPublicKeySpec) { CipherParameters parameters = OpenSSHPublicKeyUtil.parsePublicKey(((OpenSSHPublicKeySpec)keySpec).getEncoded()); @@ -218,7 +295,7 @@ else if (keySpec instanceof OpenSSHPublicKeySpec) return new BC15EdDSAPublicKey(new byte[0], ((Ed25519PublicKeyParameters)parameters).getEncoded()); } - throw new IllegalStateException("openssh public key not Ed25519 public key"); + throw new InvalidKeySpecException("openssh public key not Ed25519 public key"); } return super.engineGeneratePublic(keySpec); diff --git a/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/SignatureSpi.java b/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/SignatureSpi.java index 6891498db8..2eee706e0e 100644 --- a/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/SignatureSpi.java +++ b/prov/src/main/jdk1.15/org/bouncycastle/jcajce/provider/asymmetric/edec/SignatureSpi.java @@ -83,7 +83,7 @@ else if (priv instanceof Ed448PrivateKeyParameters) signer.init(true, priv); } - private static Ed25519PrivateKeyParameters getEd25519PrivateKey(byte[] keyData) + static Ed25519PrivateKeyParameters getEd25519PrivateKey(byte[] keyData) throws InvalidKeyException { if (Ed25519PrivateKeyParameters.KEY_SIZE != keyData.length) @@ -94,7 +94,7 @@ private static Ed25519PrivateKeyParameters getEd25519PrivateKey(byte[] keyData) return new Ed25519PrivateKeyParameters(keyData, 0); } - private static Ed25519PublicKeyParameters getEd25519PublicKey(EdECPoint point) + static Ed25519PublicKeyParameters getEd25519PublicKey(EdECPoint point) throws InvalidKeyException { byte[] keyData = getPublicKeyData(Ed25519PublicKeyParameters.KEY_SIZE, point); @@ -102,7 +102,7 @@ private static Ed25519PublicKeyParameters getEd25519PublicKey(EdECPoint point) return new Ed25519PublicKeyParameters(keyData, 0); } - private static Ed448PrivateKeyParameters getEd448PrivateKey(byte[] keyData) + static Ed448PrivateKeyParameters getEd448PrivateKey(byte[] keyData) throws InvalidKeyException { if (Ed448PrivateKeyParameters.KEY_SIZE != keyData.length) @@ -113,7 +113,7 @@ private static Ed448PrivateKeyParameters getEd448PrivateKey(byte[] keyData) return new Ed448PrivateKeyParameters(keyData, 0); } - private static Ed448PublicKeyParameters getEd448PublicKey(EdECPoint point) + static Ed448PublicKeyParameters getEd448PublicKey(EdECPoint point) throws InvalidKeyException { byte[] keyData = getPublicKeyData(Ed448PublicKeyParameters.KEY_SIZE, point); diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMCipherSpi.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMCipherSpi.java new file mode 100644 index 0000000000..8731c92a51 --- /dev/null +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMCipherSpi.java @@ -0,0 +1,363 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.CipherSpi; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.crypto.Wrapper; +import org.bouncycastle.jcajce.spec.KEMParameterSpec; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.jcajce.provider.util.WrapUtil; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Exceptions; + +class MLKEMCipherSpi + extends CipherSpi +{ + private final String algorithmName; + private MLKEMGenerator kemGen; + private KTSParameterSpec kemParameterSpec; + private BCMLKEMPublicKey wrapKey; + private BCMLKEMPrivateKey unwrapKey; + + private AlgorithmParameters engineParams; + private MLKEMParameters mlkemParamters; + + MLKEMCipherSpi(String algorithmName) + { + this.algorithmName = algorithmName; + this.mlkemParamters = null; + } + + MLKEMCipherSpi(MLKEMParameters kyberParameters) + { + this.mlkemParamters = kyberParameters; + this.algorithmName = kyberParameters.getName(); + } + + @Override + protected void engineSetMode(String mode) + throws NoSuchAlgorithmException + { + throw new NoSuchAlgorithmException("Cannot support mode " + mode); + } + + @Override + protected void engineSetPadding(String padding) + throws NoSuchPaddingException + { + throw new NoSuchPaddingException("Padding " + padding + " unknown"); + } + + protected int engineGetKeySize( + Key key) + { + return 2048; // TODO + //throw new IllegalArgumentException("not an valid key!"); + } + + @Override + protected int engineGetBlockSize() + { + return 0; + } + + @Override + protected int engineGetOutputSize(int i) + { + return -1; // can't use with update/doFinal + } + + @Override + protected byte[] engineGetIV() + { + return null; + } + + @Override + protected AlgorithmParameters engineGetParameters() + { + if (engineParams == null) + { + try + { + engineParams = AlgorithmParameters.getInstance(algorithmName, "BCPQC"); + + engineParams.init(kemParameterSpec); + } + catch (Exception e) + { + throw Exceptions.illegalStateException(e.toString(), e); + } + } + + return engineParams; + } + + @Override + protected void engineInit(int opmode, Key key, SecureRandom random) + throws InvalidKeyException + { + try + { + engineInit(opmode, key, (AlgorithmParameterSpec)null, random); + } + catch (InvalidAlgorithmParameterException e) + { + throw Exceptions.illegalArgumentException(e.getMessage(), e); + } + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec paramSpec, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException + { + if (paramSpec == null) + { + // TODO: default should probably use shake. + kemParameterSpec = new KEMParameterSpec("AES-KWP"); + } + else + { + if (!(paramSpec instanceof KTSParameterSpec)) + { + throw new InvalidAlgorithmParameterException(algorithmName + " can only accept KTSParameterSpec"); + } + + kemParameterSpec = (KTSParameterSpec)paramSpec; + } + + if (opmode == Cipher.WRAP_MODE) + { + if (key instanceof BCMLKEMPublicKey) + { + wrapKey = (BCMLKEMPublicKey)key; + kemGen = new MLKEMGenerator(CryptoServicesRegistrar.getSecureRandom(random)); + } + else + { + throw new InvalidKeyException("Only a " + algorithmName + " public key can be used for wrapping"); + } + } + else if (opmode == Cipher.UNWRAP_MODE) + { + if (key instanceof BCMLKEMPrivateKey) + { + unwrapKey = (BCMLKEMPrivateKey)key; + } + else + { + throw new InvalidKeyException("Only a " + algorithmName + " private key can be used for unwrapping"); + } + } + else + { + throw new InvalidParameterException("Cipher only valid for wrapping/unwrapping"); + } + + if (mlkemParamters != null) + { + String canonicalAlgName = MLKEMParameterSpec.fromName(mlkemParamters.getName()).getName(); + if (!canonicalAlgName.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("cipher locked to " + canonicalAlgName); + } + } + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameters algorithmParameters, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException + { + AlgorithmParameterSpec paramSpec = null; + + if (algorithmParameters != null) + { + try + { + paramSpec = algorithmParameters.getParameterSpec(KEMParameterSpec.class); + } + catch (Exception e) + { + throw new InvalidAlgorithmParameterException("can't handle parameter " + algorithmParameters.toString()); + } + } + + engineInit(opmode, key, paramSpec, random); + } + + @Override + protected byte[] engineUpdate(byte[] bytes, int i, int i1) + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + @Override + protected int engineUpdate(byte[] bytes, int i, int i1, byte[] bytes1, int i2) + throws ShortBufferException + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + @Override + protected byte[] engineDoFinal(byte[] bytes, int i, int i1) + throws IllegalBlockSizeException, BadPaddingException + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + @Override + protected int engineDoFinal(byte[] bytes, int i, int i1, byte[] bytes1, int i2) + throws ShortBufferException, IllegalBlockSizeException, BadPaddingException + { + throw new IllegalStateException("Not supported in a wrapping mode"); + } + + protected byte[] engineWrap( + Key key) + throws IllegalBlockSizeException, InvalidKeyException + { + byte[] encoded = key.getEncoded(); + if (encoded == null) + { + throw new InvalidKeyException("Cannot wrap key, null encoding."); + } + + SecretWithEncapsulation secEnc = null; + try + { + secEnc = kemGen.generateEncapsulated(wrapKey.getKeyParams()); + + Wrapper kWrap = WrapUtil.getKeyWrapper(kemParameterSpec, secEnc.getSecret()); + + byte[] encapsulation = secEnc.getEncapsulation(); + + byte[] keyToWrap = key.getEncoded(); + + byte[] rv = Arrays.concatenate(encapsulation, kWrap.wrap(keyToWrap, 0, keyToWrap.length)); + + Arrays.clear(keyToWrap); + + return rv; + } + catch (IllegalArgumentException e) + { + throw new IllegalBlockSizeException("unable to generate KTS secret: " + e.getMessage()); + } + finally + { + try + { + if (secEnc != null) + { + secEnc.destroy(); + } + } + catch (Exception e) + { + throw new IllegalBlockSizeException("unable to destroy interim values: " + e.getMessage()); + } + } + } + + protected Key engineUnwrap( + byte[] wrappedKey, + String wrappedKeyAlgorithm, + int wrappedKeyType) + throws InvalidKeyException, NoSuchAlgorithmException + { + // TODO: add support for other types. + if (wrappedKeyType != Cipher.SECRET_KEY) + { + throw new InvalidKeyException("only SECRET_KEY supported"); + } + byte[] secret = null; + try + { + MLKEMExtractor kemExt = new MLKEMExtractor(unwrapKey.getKeyParams()); + + secret = kemExt.extractSecret(Arrays.copyOfRange(wrappedKey, 0, kemExt.getEncapsulationLength())); + + Wrapper kWrap = WrapUtil.getKeyUnwrapper(kemParameterSpec, secret); + + byte[] keyEncBytes = Arrays.copyOfRange(wrappedKey, kemExt.getEncapsulationLength(), wrappedKey.length); + + SecretKey rv = new SecretKeySpec(kWrap.unwrap(keyEncBytes, 0, keyEncBytes.length), wrappedKeyAlgorithm); + + return rv; + } + catch (IllegalArgumentException e) + { + throw new NoSuchAlgorithmException("unable to extract KTS secret: " + e.getMessage()); + } + catch (InvalidCipherTextException e) + { + throw new InvalidKeyException("unable to extract KTS secret: " + e.getMessage()); + } + finally + { + if (secret != null) + { + Arrays.clear(secret); + } + } + } + + public static class Base + extends MLKEMCipherSpi + { + public Base() + throws NoSuchAlgorithmException + { + super("MLKEM"); + } + } + + public static class MLKEM512 + extends MLKEMCipherSpi + { + public MLKEM512() + { + super(MLKEMParameters.ml_kem_512); + } + } + + public static class MLKEM768 + extends MLKEMCipherSpi + { + public MLKEM768() + { + super(MLKEMParameters.ml_kem_768); + } + } + + public static class MLKEM1024 + extends MLKEMCipherSpi + { + public MLKEM1024() + { + super(MLKEMParameters.ml_kem_1024); + } + } +} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyGeneratorSpi.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyGeneratorSpi.java new file mode 100644 index 0000000000..6b09d0f4f0 --- /dev/null +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMKeyGeneratorSpi.java @@ -0,0 +1,159 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import java.security.InvalidAlgorithmParameterException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.KeyGeneratorSpi; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; +import org.bouncycastle.jcajce.spec.KEMExtractSpec; +import org.bouncycastle.jcajce.spec.KEMGenerateSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; +import org.bouncycastle.util.Arrays; + +public class MLKEMKeyGeneratorSpi + extends KeyGeneratorSpi +{ + private KEMGenerateSpec genSpec; + private SecureRandom random; + private KEMExtractSpec extSpec; + private MLKEMParameters kyberParameters; + + public MLKEMKeyGeneratorSpi() + { + this(null); + } + + protected MLKEMKeyGeneratorSpi(MLKEMParameters kyberParameters) + { + this.kyberParameters = kyberParameters; + } + + protected void engineInit(SecureRandom secureRandom) + { + throw new UnsupportedOperationException("Operation not supported"); + } + + protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec, SecureRandom secureRandom) + throws InvalidAlgorithmParameterException + { + this.random = secureRandom; + if (algorithmParameterSpec instanceof KEMGenerateSpec) + { + this.genSpec = (KEMGenerateSpec)algorithmParameterSpec; + this.extSpec = null; + if (kyberParameters != null) + { + String canonicalAlgName = MLKEMParameterSpec.fromName(kyberParameters.getName()).getName(); + if (!canonicalAlgName.equals(genSpec.getPublicKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } + } + else if (algorithmParameterSpec instanceof KEMExtractSpec) + { + this.genSpec = null; + this.extSpec = (KEMExtractSpec)algorithmParameterSpec; + if (kyberParameters != null) + { + String canonicalAlgName = MLKEMParameterSpec.fromName(kyberParameters.getName()).getName(); + if (!canonicalAlgName.equals(extSpec.getPrivateKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } + } + else + { + throw new InvalidAlgorithmParameterException("unknown spec"); + } + } + + protected void engineInit(int i, SecureRandom secureRandom) + { + throw new UnsupportedOperationException("Operation not supported"); + } + + protected SecretKey engineGenerateKey() + { + if (genSpec != null) + { + BCMLKEMPublicKey pubKey = (BCMLKEMPublicKey)genSpec.getPublicKey(); + MLKEMGenerator kemGen = new MLKEMGenerator(random); + + SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(pubKey.getKeyParams()); + + byte[] sharedSecret = secEnc.getSecret(); + + byte[] secret = KdfUtil.makeKeyBytes(genSpec, sharedSecret); + + Arrays.clear(sharedSecret); + + SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secret, genSpec.getKeyAlgorithmName()), secEnc.getEncapsulation()); + + try + { + secEnc.destroy(); + } + catch (Exception e) + { + throw new IllegalStateException("key cleanup failed"); + } + + return rv; + } + else + { + BCMLKEMPrivateKey privKey = (BCMLKEMPrivateKey)extSpec.getPrivateKey(); + MLKEMExtractor kemExt = new MLKEMExtractor(privKey.getKeyParams()); + + byte[] encapsulation = extSpec.getEncapsulation(); + byte[] sharedSecret = kemExt.extractSecret(encapsulation); + byte[] secret = KdfUtil.makeKeyBytes(extSpec, sharedSecret); + + Arrays.clear(sharedSecret); + + SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secret, extSpec.getKeyAlgorithmName()), encapsulation); + + Arrays.clear(secret); + + return rv; + } + } + + public static class MLKEM512 + extends MLKEMKeyGeneratorSpi + { + public MLKEM512() + { + super(MLKEMParameters.ml_kem_512); + } + } + + public static class MLKEM768 + extends MLKEMKeyGeneratorSpi + { + public MLKEM768() + { + super(MLKEMParameters.ml_kem_768); + } + } + + public static class MLKEM1024 + extends MLKEMKeyGeneratorSpi + { + public MLKEM1024() + { + super(MLKEMParameters.ml_kem_1024); + } + } +} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java index 14d816c8da..e12e92d440 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java @@ -10,9 +10,10 @@ import java.util.Set; import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Enumerated; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.CRLReason; @@ -78,9 +79,9 @@ public X509CRLEntryObject( */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); + Extensions extensions = c.getExtensions(); - return extns != null && !extns.isEmpty(); + return extensions != null && extensions.hasAnyCriticalExtensions(); } private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) @@ -90,16 +91,15 @@ private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCert return null; } - byte[] ext = getExtensionValue(X509Extension.certificateIssuer.getId()); - if (ext == null) + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), Extension.certificateIssuer); + if (extValue == null) { return previousCertificateIssuer; } try { - GeneralName[] names = GeneralNames.getInstance( - X509ExtensionUtil.fromExtensionValue(ext)).getNames(); + GeneralName[] names = GeneralNames.getInstance(extValue.getOctets()).getNames(); for (int i = 0; i < names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) @@ -168,26 +168,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } /** diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java index a0055b04c8..e11c0e9949 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLImpl.java @@ -41,6 +41,7 @@ import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.IssuingDistributionPoint; import org.bouncycastle.asn1.x509.TBSCertList; +import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.jcajce.interfaces.BCX509Certificate; import org.bouncycastle.jcajce.io.OutputStreamFactory; import org.bouncycastle.jcajce.util.JcaJceHelper; @@ -76,30 +77,41 @@ abstract class X509CRLImpl this.isIndirect = isIndirect; } - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) + if (getVersion() == 2) { - return false; - } + Extensions extensions = c.getExtensions(); + if (extensions != null) + { + Enumeration e = extensions.oids(); + while (e.hasMoreElements()) + { + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); + + if (Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid)) + { + continue; + } - extns.remove(Extension.issuingDistributionPoint.getId()); - extns.remove(Extension.deltaCRLIndicator.getId()); + Extension ext = extensions.getExtension(oid); + if (ext.isCritical()) + { + return true; + } + } + } + } - return !extns.isEmpty(); + return false; } private Set getExtensionOIDs(boolean critical) { if (this.getVersion() == 2) { - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -136,19 +148,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - try - { - return extValue.getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public byte[] getEncoded() @@ -285,14 +285,11 @@ public Date getThisUpdate() public Date getNextUpdate() { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } + Time nextUpdate = c.getNextUpdate(); - return null; + return null == nextUpdate ? null : nextUpdate.getDate(); } - + private Set loadCRLEntries() { Set entrySet = new HashSet(); @@ -430,7 +427,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -595,28 +592,10 @@ public boolean isRevoked(Certificate cert) return false; } - protected static byte[] getExtensionOctets(CertificateList c, String oid) + static byte[] getExtensionOctets(CertificateList c, ASN1ObjectIdentifier oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - return extValue.getOctets(); - } - return null; - } + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); - protected static ASN1OctetString getExtensionValue(CertificateList c, String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - if (null != exts) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (null != ext) - { - return ext.getExtnValue(); - } - } - return null; + return extValue == null ? null : extValue.getOctets(); } } - diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java index dfb0b0dc8d..964a705db4 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java @@ -135,7 +135,7 @@ private static boolean isIndirectCRL(CertificateList c) throws CRLException { try { - byte[] extOctets = getExtensionOctets(c, Extension.issuingDistributionPoint.getId()); + byte[] extOctets = getExtensionOctets(c, Extension.issuingDistributionPoint); if (null == extOctets) { return false; diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java index 527be010bf..f9ed96804b 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateImpl.java @@ -244,7 +244,7 @@ public boolean[] getKeyUsage() public List getExtendedKeyUsage() throws CertificateParsingException { - byte[] extOctets = getExtensionOctets(c, "2.5.29.37"); + byte[] extOctets = getExtensionOctets(c, Extension.extendedKeyUsage); if (null == extOctets) { return null; @@ -294,13 +294,13 @@ public int getBasicConstraints() public Collection getSubjectAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(c, Extension.subjectAlternativeName.getId()); + return getAlternativeNames(c, Extension.subjectAlternativeName); } public Collection getIssuerAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(c, Extension.issuerAlternativeName.getId()); + return getAlternativeNames(c, Extension.issuerAlternativeName); } public Set getCriticalExtensionOIDs() @@ -308,7 +308,7 @@ public Set getCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -332,22 +332,9 @@ public Set getCriticalExtensionOIDs() return null; } - public byte[] getExtensionValue(String oid) + public byte[] getExtensionValue(String oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - try - { - return extValue.getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public Set getNonCriticalExtensionOIDs() @@ -355,7 +342,7 @@ public Set getNonCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -381,35 +368,32 @@ public Set getNonCriticalExtensionOIDs() public boolean hasUnsupportedCriticalExtension() { - if (this.getVersion() == 3) + if (getVersion() == 3) { - Extensions extensions = c.getTBSCertificate().getExtensions(); - + Extensions extensions = c.getExtensions(); if (extensions != null) { - Enumeration e = extensions.oids(); - + Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - if (oid.equals(Extension.keyUsage) - || oid.equals(Extension.certificatePolicies) - || oid.equals(Extension.policyMappings) - || oid.equals(Extension.inhibitAnyPolicy) - || oid.equals(Extension.cRLDistributionPoints) - || oid.equals(Extension.issuingDistributionPoint) - || oid.equals(Extension.deltaCRLIndicator) - || oid.equals(Extension.policyConstraints) - || oid.equals(Extension.basicConstraints) - || oid.equals(Extension.subjectAlternativeName) - || oid.equals(Extension.nameConstraints)) + if (Extension.keyUsage.equals(oid) || + Extension.certificatePolicies.equals(oid) || + Extension.policyMappings.equals(oid) || + Extension.inhibitAnyPolicy.equals(oid) || + Extension.cRLDistributionPoints.equals(oid) || + Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid) || + Extension.policyConstraints.equals(oid) || + Extension.basicConstraints.equals(oid) || + Extension.subjectAlternativeName.equals(oid) || + Extension.nameConstraints.equals(oid)) { continue; } - Extension ext = extensions.getExtension(oid); - + Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { return true; @@ -475,7 +459,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -678,7 +662,7 @@ private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) return id1.getParameters().equals(id2.getParameters()); } - private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, String oid) + private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) throws CertificateParsingException { byte[] extOctets = getExtensionOctets(c, oid); @@ -737,27 +721,10 @@ private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certifi } } - protected static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, String oid) + static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) { - ASN1OctetString extValue = getExtensionValue(c, oid); - if (null != extValue) - { - return extValue.getOctets(); - } - return null; - } + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); - protected static ASN1OctetString getExtensionValue(org.bouncycastle.asn1.x509.Certificate c, String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - if (null != exts) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (null != ext) - { - return ext.getExtnValue(); - } - } - return null; + return extValue == null ? null : extValue.getOctets(); } } diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java index a08a326deb..613fa78553 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java @@ -14,6 +14,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; @@ -232,7 +233,7 @@ private static BasicConstraints createBasicConstraints(org.bouncycastle.asn1.x50 { try { - byte[] extOctets = getExtensionOctets(c, "2.5.29.19"); + byte[] extOctets = getExtensionOctets(c, Extension.basicConstraints); if (null == extOctets) { return null; @@ -250,7 +251,7 @@ private static boolean[] createKeyUsage(org.bouncycastle.asn1.x509.Certificate c { try { - byte[] extOctets = getExtensionOctets(c, "2.5.29.15"); + byte[] extOctets = getExtensionOctets(c, Extension.keyUsage); if (null == extOctets) { return null; diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java index 925ccc3206..1d594b178c 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java @@ -17,13 +17,14 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.internal.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.util.MessageDigestUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -40,22 +41,47 @@ class X509SignatureUtil algNames.put(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1withDSA"); } - private static final ASN1Null derNull = DERNull.INSTANCE; + static byte[] getExtensionValue(Extensions extensions, String oid) + { + if (oid != null) + { + ASN1ObjectIdentifier asn1Oid = ASN1ObjectIdentifier.tryFromID(oid); + if (asn1Oid != null) + { + ASN1OctetString extValue = Extensions.getExtensionValue(extensions, asn1Oid); + if (null != extValue) + { + try + { + return extValue.getEncoded(); + } + catch (Exception e) + { + throw new IllegalStateException("error parsing " + e.toString()); + } + } + } + } + return null; + } + + private static boolean isAbsentOrEmptyParameters(ASN1Encodable parameters) + { + return parameters == null || DERNull.INSTANCE.equals(parameters); + } - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) + static void setSignatureParameters(Signature signature, ASN1Encodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { - if (params != null && !derNull.equals(params)) + if (!isAbsentOrEmptyParameters(params)) { - - AlgorithmParameters sigParams; + String sigAlgName = signature.getAlgorithm(); try { - sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider().getName()); - + AlgorithmParameters sigParams = AlgorithmParameters.getInstance(sigAlgName, + signature.getProvider().getName()); + sigParams.init(params.toASN1Primitive().getEncoded()); } catch (NoSuchProviderException e) @@ -66,8 +92,8 @@ static void setSignatureParameters( { throw new SignatureException("IOException decoding parameters: " + e.getMessage()); } - - if (signature.getAlgorithm().endsWith("MGF1")) + + if (sigAlgName.endsWith("MGF1")) { try { @@ -80,38 +106,38 @@ static void setSignatureParameters( } } } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) + + static String getSignatureName(AlgorithmIdentifier sigAlgId) { + ASN1ObjectIdentifier sigAlgOid = sigAlgId.getAlgorithm(); ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) + + if (!isAbsentOrEmptyParameters(params)) { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) + if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgOid)) { RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - + return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) + if (X9ObjectIdentifiers.ecdsa_with_SHA2.equals(sigAlgOid)) { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; + AlgorithmIdentifier ecDsaParams = AlgorithmIdentifier.getInstance(params); + + return getDigestAlgName(ecDsaParams.getAlgorithm()) + "withECDSA"; } } // deal with the "weird" ones. - String algName = (String)algNames.get(sigAlgId.getAlgorithm()); + String algName = (String)algNames.get(sigAlgOid); if (algName != null) { return algName; } - return findAlgName(sigAlgId.getAlgorithm()); + return findAlgName(sigAlgOid); } - + /** * Return the digest algorithm using one of the standard JCA string * representations rather the the algorithm identifier (if possible). @@ -162,7 +188,7 @@ private static String findAlgName(ASN1ObjectIdentifier algOid) private static String lookupAlg(Provider prov, ASN1ObjectIdentifier algOid) { - String algName = prov.getProperty("Alg.Alias.Signature." + algOid); + String algName = prov.getProperty("Alg.Alias.Signature." + algOid); if (algName != null) { diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/CertUtil.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/CertUtil.java index 11a456ec26..135e1f521a 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/CertUtil.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/CertUtil.java @@ -1,17 +1,15 @@ package org.bouncycastle.jce.cert; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; +import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.OIDTokenizer; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.util.Strings; @@ -336,12 +334,7 @@ static byte[] parseOID(String oid) throws IOException { throw new IOException("token: " + token + ": " + ex.toString()); } - ASN1Object derData = new ASN1ObjectIdentifier(oid); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + return new ASN1ObjectIdentifier(oid).getEncoded(ASN1Encoding.DER); } /** @@ -452,12 +445,7 @@ private static byte[] parseIPv6(String data) private static byte[] parseURI(String data) throws IOException { // TODO do parsing test - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + return new DERIA5String(data).getEncoded(ASN1Encoding.DER); } /** @@ -479,13 +467,8 @@ private static byte[] parseRfc822(String data) throws IOException { throw new IOException("wrong format of rfc822Name:" + data); } - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + // TODO more test for illegal characters + return new DERIA5String(data).getEncoded(ASN1Encoding.DER); } /** @@ -502,13 +485,8 @@ private static byte[] parseRfc822(String data) throws IOException */ private static byte[] parseDNSName(String data) throws IOException { - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); + // TODO more test for illegal characters + return new DERIA5String(data).getEncoded(ASN1Encoding.DER); } /** @@ -524,12 +502,8 @@ private static byte[] parseDNSName(String data) throws IOException */ private static byte[] parseX509Name(String data) throws IOException { - // TODO more test for illegal charateers - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - derOutStream.writeObject(new X509Name(trimX509Name(data))); - derOutStream.close(); - return outStream.toByteArray(); + // TODO more test for illegal characters + return new X509Name(trimX509Name(data)).getEncoded(ASN1Encoding.DER); } /** diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java index 4b1e7b5131..5816c4bd1e 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java @@ -1,7 +1,5 @@ package org.bouncycastle.jce.cert; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.PublicKey; @@ -9,7 +7,6 @@ import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; @@ -20,17 +17,15 @@ import java.util.List; import java.util.Set; -import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1OutputStream; +import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.BERTags; -import org.bouncycastle.asn1.DERGeneralizedTime; -import org.bouncycastle.asn1.ASN1GeneralizedTime; -import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; @@ -40,6 +35,7 @@ import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.jce.PrincipalUtil; import org.bouncycastle.util.Integers; +import org.bouncycastle.util.Arrays; /** * A CertSelector that selects @@ -78,10 +74,8 @@ * TODO: implement name constraints * TODO: implement match check for path to names
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, + * Uses {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.bouncycastle.asn1.ASN1OutputStream DEROutputStream}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.OIDTokenizer OIDTokenizer}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name}, @@ -285,8 +279,7 @@ public void setIssuer(String issuerDN) throws IOException * Note that the byte array specified here is cloned to protect against * subsequent modifications.
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, + * Uses {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name} * @@ -306,9 +299,7 @@ public void setIssuer(byte[] issuerDN) throws IOException } else { - ByteArrayInputStream inStream = new ByteArrayInputStream(issuerDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); + ASN1Object obj = ASN1Primitive.fromByteArray(issuerDN); if (obj instanceof ASN1Sequence) { this.issuerDNX509 = new X509Name((ASN1Sequence)obj); @@ -372,8 +363,7 @@ public void setSubject(String subjectDN) throws IOException * the ASN.1 notation for this structure, see * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, + * Uses {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name} * @@ -393,10 +383,7 @@ public void setSubject(byte[] subjectDN) throws IOException } else { - ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - + ASN1Object obj = ASN1Primitive.fromByteArray(subjectDN); if (obj instanceof ASN1Sequence) { this.subjectDNX509 = new X509Name((ASN1Sequence)obj); @@ -736,11 +723,11 @@ public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException { if (keyPurposeSet == null || keyPurposeSet.isEmpty()) { - this.keyPurposeSet = keyPurposeSet; + this.keyPurposeSet = null; } else { - this.keyPurposeSet = new HashSet(); + HashSet checkKeyPurposeSet = new HashSet(); Iterator iter = keyPurposeSet.iterator(); Object obj; KeyPurposeId purposeID; @@ -749,15 +736,16 @@ public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException obj = iter.next(); if (obj instanceof String) { - purposeID = (KeyPurposeId)keyPurposeIdMap.get((String)obj); + String str = (String)obj; + purposeID = (KeyPurposeId)keyPurposeIdMap.get(str); if (purposeID == null) { - throw new IOException("unknown purposeID " - + (String)obj); + throw new IOException("unknown purposeID " + str); } - this.keyPurposeSet.add(purposeID); + checkKeyPurposeSet.add(purposeID); } } + this.keyPurposeSet = Collections.unmodifiableSet(checkKeyPurposeSet); } } @@ -857,8 +845,7 @@ else if (data instanceof byte[]) } else { - throw new IOException( - "parsing error: unknown data type"); + throw new IOException("parsing error: unknown data type"); } } } @@ -909,6 +896,7 @@ public void addSubjectAlternativeName(int type, String name) tmpList.add(Integers.valueOf(type)); tmpList.add(name); subjectAltNames.add(tmpList); + // FIXME Surely this affects the entry we just added to subjectAltNames?? tmpList.set(1, encoded); subjectAltNamesByte.add(tmpList); } @@ -1095,7 +1083,7 @@ public void setPolicy(Set certPolicySet) throws IOException } else { - policyOID = new HashSet(); + HashSet checkPolicyOID = new HashSet(); Iterator iter = certPolicySet.iterator(); Object item; while (iter.hasNext()) @@ -1104,15 +1092,15 @@ public void setPolicy(Set certPolicySet) throws IOException if (item instanceof String) { CertUtil.parseOID((String)item); - policyOID.add(new ASN1ObjectIdentifier((String)item)); + checkPolicyOID.add(new ASN1ObjectIdentifier((String)item)); } else { - throw new IOException( - "certPolicySet contains null values or non String objects"); + throw new IOException("certPolicySet contains null values or non String objects"); } } - policy = new HashSet(certPolicySet); + this.policy = Collections.unmodifiableSet(new HashSet(certPolicySet)); + this.policyOID = Collections.unmodifiableSet(checkPolicyOID); } } @@ -1198,8 +1186,7 @@ else if (data instanceof byte[]) } else { - throw new IOException( - "parsing error: unknown data type"); + throw new IOException("parsing error: unknown data type"); } } } @@ -1249,6 +1236,7 @@ public void addPathToName(int type, String name) throws IOException tmpList.add(Integers.valueOf(type)); tmpList.add(name); pathToNames.add(tmpList); + // FIXME Surely this affects the entry we just added to pathToNames?? tmpList.set(1, encoded); pathToNamesByte.add(tmpList); throw new UnsupportedOperationException(); @@ -1341,7 +1329,7 @@ public String getIssuerAsString() { if (issuerDN instanceof String) { - return new String((String)issuerDN); + return (String)issuerDN; } else if (issuerDNX509 != null) { @@ -1365,8 +1353,7 @@ else if (issuerDNX509 != null) * Note that the byte array returned is cloned to protect against subsequent * modifications.
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1OutputStream DEROutputStream}, - * {@link org.bouncycastle.asn1.x509.X509Name X509Name} to gnerate byte[] + * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} to generate byte[] * output for String issuerDN. * * @return a byte array containing the required issuer distinguished name in @@ -1383,13 +1370,7 @@ public byte[] getIssuerAsBytes() throws IOException } else if (issuerDNX509 != null) { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - - derOutStream.writeObject(issuerDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); + return issuerDNX509.getEncoded(ASN1Encoding.DER); } return null; @@ -1414,7 +1395,7 @@ public String getSubjectAsString() { if (subjectDN instanceof String) { - return new String((String)subjectDN); + return (String)subjectDN; } else if (subjectDNX509 != null) { @@ -1438,8 +1419,7 @@ else if (subjectDNX509 != null) * Note that the byte array returned is cloned to protect against subsequent * modifications.
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1OutputStream DEROutputStream}, - * {@link org.bouncycastle.asn1.x509.X509Name X509Name} to gnerate byte[] + * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} to generate byte[] * output for String subjectDN. * * @return a byte array containing the required subject distinguished name @@ -1456,13 +1436,7 @@ public byte[] getSubjectAsBytes() throws IOException } else if (subjectDNX509 != null) { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ASN1OutputStream derOutStream = ASN1OutputStream.create(outStream, ASN1Encoding.DER); - - derOutStream.writeObject(subjectDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); + return subjectDNX509.getEncoded(ASN1Encoding.DER); } return null; @@ -1635,19 +1609,7 @@ public boolean[] getKeyUsage() */ public Set getExtendedKeyUsage() { - if (keyPurposeSet == null || keyPurposeSet.isEmpty()) - { - return keyPurposeSet; - } - - Set returnSet = new HashSet(); - Iterator iter = keyPurposeSet.iterator(); - while (iter.hasNext()) - { - returnSet.add(iter.next().toString()); - } - - return Collections.unmodifiableSet(returnSet); + return keyPurposeSet; } /** @@ -1705,7 +1667,7 @@ public boolean getMatchAllSubjectAltNames() */ public Collection getSubjectAlternativeNames() { - if (subjectAltNames != null) + if (subjectAltNames == null) { return null; } @@ -1714,19 +1676,18 @@ public Collection getSubjectAlternativeNames() List returnList; Iterator iter = subjectAltNames.iterator(); List obj; + Object data; while (iter.hasNext()) { obj = (List)iter.next(); returnList = new ArrayList(); returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) + data = obj.get(1); + if (data instanceof byte[]) { - returnList.add(((byte[])obj.get(1)).clone()); - } - else - { - returnList.add(obj.get(1)); + data = Arrays.clone((byte[])data); } + returnList.add(data); returnAltNames.add(returnList); } @@ -1796,12 +1757,7 @@ public int getBasicConstraints() */ public Set getPolicy() { - if (policy == null) - { - return null; - } - - return Collections.unmodifiableSet(policy); + return policy; } /** @@ -1844,20 +1800,18 @@ public Collection getPathToNames() List returnList; Iterator iter = pathToNames.iterator(); List obj; - + Object data; while (iter.hasNext()) { obj = (List)iter.next(); returnList = new ArrayList(); returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else + data = obj.get(1); + if (data instanceof byte[]) { - returnList.add(obj.get(1)); + data = Arrays.clone((byte[])data); } + returnList.add(data); returnPathToNames.add(returnList); } @@ -1870,8 +1824,7 @@ public Collection getPathToNames() * TODO: implement output for currently unsupported options(name * constraints)
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, + * Uses {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.x509.KeyPurposeId KeyPurposeId} * * @return a String describing the contents of the @@ -1901,19 +1854,13 @@ public String toString() { if (subjectKeyID != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - subjectKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray(subjectKeyID); sb.append(" Subject Key Identifier: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } if (authorityKeyID != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - authorityKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray(authorityKeyID); sb.append(" Authority Key Identifier: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } @@ -1966,10 +1913,7 @@ public String toString() while (iter.hasNext()) { obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray((byte[])obj.get(1)); sb.append(" Type: ").append(obj.get(0)).append(" Data: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } @@ -1990,10 +1934,7 @@ public String toString() while (iter.hasNext()) { obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); + ASN1Object derObject = ASN1Primitive.fromByteArray((byte[])obj.get(1)); sb.append(" Type: ").append(obj.get(0)).append(" Data: ") .append(ASN1Dump.dumpAsString(derObject)).append('\n'); } @@ -2013,11 +1954,10 @@ public String toString() *
      * TODO: implement missing tests (name constraints and path to names)
      *
      - * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, + * Uses {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, - * {@link org.bouncycastle.asn1.DERGeneralizedTime DERGeneralizedTime}, + * {@link org.bouncycastle.asn1.ASN1GeneralizedTime ASN1GeneralizedTime}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name}, * {@link org.bouncycastle.asn1.x509.X509Extensions X509Extensions}, * {@link org.bouncycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage}, @@ -2048,8 +1988,7 @@ public boolean match(Certificate cert) { return false; } - if (serialNumber != null - && !serialNumber.equals(certX509.getSerialNumber())) + if (serialNumber != null && !serialNumber.equals(certX509.getSerialNumber())) { return false; } @@ -2057,16 +1996,14 @@ public boolean match(Certificate cert) { if (issuerDNX509 != null) { - if (!issuerDNX509.equals(PrincipalUtil - .getIssuerX509Principal(certX509), true)) + if (!issuerDNX509.equals(PrincipalUtil.getIssuerX509Principal(certX509), true)) { return false; } } if (subjectDNX509 != null) { - if (!subjectDNX509.equals(PrincipalUtil - .getSubjectX509Principal(certX509), true)) + if (!subjectDNX509.equals(PrincipalUtil.getSubjectX509Principal(certX509), true)) { return false; } @@ -2078,50 +2015,40 @@ public boolean match(Certificate cert) } if (subjectKeyID != null) { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectKeyIdentifier - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); if (data == null) { return false; } try { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); - if (!Arrays.equals(subjectKeyID, testData)) + byte[] testData = ASN1OctetString.getInstance(data).getOctets(); + if (!Arrays.areEqual(subjectKeyID, testData)) { return false; } } - catch (IOException ex) + catch (Exception ex) { return false; } } if (authorityKeyID != null) { - byte[] data = certX509 - .getExtensionValue(X509Extensions.AuthorityKeyIdentifier - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (data == null) { return false; } try { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); - if (!Arrays.equals(authorityKeyID, testData)) + byte[] testData = ASN1OctetString.getInstance(data).getOctets(); + if (!Arrays.areEqual(authorityKeyID, testData)) { return false; } } - catch (IOException ex) + catch (Exception ex) { return false; } @@ -2143,31 +2070,19 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.PrivateKeyUsagePeriod - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.PrivateKeyUsagePeriod.getId()); if (data != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); // TODO fix this, Sequence contains tagged objects - ASN1Sequence derObject = (ASN1Sequence)derInputStream - .readObject(); - ASN1GeneralizedTime derDate = ASN1GeneralizedTime - .getInstance(derObject.getObjectAt(0)); - SimpleDateFormat dateF = new SimpleDateFormat( - "yyyyMMddHHmmssZ"); + ASN1Sequence derObject = ASN1Sequence.getInstance( + ASN1OctetString.getInstance(data).getOctets()); + ASN1GeneralizedTime derDate = ASN1GeneralizedTime.getInstance(derObject.getObjectAt(0)); + SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssZ"); if (privateKeyValid.before(dateF.parse(derDate.getTime()))) { return false; } - derDate = ASN1GeneralizedTime.getInstance(derObject - .getObjectAt(1)); + derDate = ASN1GeneralizedTime.getInstance(derObject.getObjectAt(1)); if (privateKeyValid.after(dateF.parse(derDate.getTime()))) { return false; @@ -2183,7 +2098,8 @@ public boolean match(Certificate cert) { try { - SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certX509.getPublicKey().getEncoded()); + SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance( + certX509.getPublicKey().getEncoded()); AlgorithmIdentifier algInfo = publicKeyInfo.getAlgorithmId(); if (!algInfo.getAlgorithm().equals(subjectKeyAlgID)) { @@ -2197,8 +2113,7 @@ public boolean match(Certificate cert) } if (subjectPublicKeyByte != null) { - if (!Arrays.equals(subjectPublicKeyByte, certX509.getPublicKey() - .getEncoded())) + if (!Arrays.areEqual(subjectPublicKeyByte, certX509.getPublicKey().getEncoded())) { return false; } @@ -2229,21 +2144,14 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.ExtendedKeyUsage - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.ExtendedKeyUsage.getId()); if (data != null) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance( - derInputStream.readObject()); + ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(data); tempIter = keyPurposeSet.iterator(); while (tempIter.hasNext()) { - if (!extendedKeyUsage - .hasKeyPurposeId((KeyPurposeId)tempIter.next())) + if (!extendedKeyUsage.hasKeyPurposeId((KeyPurposeId)tempIter.next())) { return false; } @@ -2271,30 +2179,21 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.CertificatePolicies - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (data == null) { return false; } if (!policyOID.isEmpty()) { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration policySequence = ((ASN1Sequence)derInputStream - .readObject()).getObjects(); + ASN1Sequence seq = ASN1Sequence.getInstance( + ASN1OctetString.getInstance(data).getOctets()); + Enumeration policySequence = seq.getObjects(); ASN1Sequence policyObject; boolean test = false; while (policySequence.hasMoreElements() && !test) { - policyObject = (ASN1Sequence)policySequence - .nextElement(); + policyObject = (ASN1Sequence)policySequence.nextElement(); if (policyOID.contains(policyObject.getObjectAt(0))) { test = true; @@ -2315,20 +2214,14 @@ public boolean match(Certificate cert) { try { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectAlternativeName - .getId()); + byte[] data = certX509.getExtensionValue(X509Extensions.SubjectAlternativeName.getId()); if (data == null) { return false; } - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration altNamesSequence = ((ASN1Sequence)derInputStream.readObject()).getObjects(); + ASN1Sequence seq = ASN1Sequence.getInstance( + ASN1OctetString.getInstance(data).getOctets()); + Enumeration altNamesSequence = seq.getObjects(); boolean test = false; Set testSet = new HashSet(subjectAltNamesByte); while (altNamesSequence.hasMoreElements() && !test) @@ -2392,8 +2285,7 @@ public Object clone() } if (subjectPublicKeyByte != null) { - copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte - .clone(); + copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte.clone(); } if (keyUsage != null) { @@ -2401,22 +2293,16 @@ public Object clone() } if (keyPurposeSet != null) { - copy.keyPurposeSet = new HashSet(keyPurposeSet); + copy.keyPurposeSet = keyPurposeSet; } if (policy != null) { - copy.policy = new HashSet(policy); - copy.policyOID = new HashSet(); - Iterator iter = policyOID.iterator(); - while (iter.hasNext()) - { - copy.policyOID.add(new ASN1ObjectIdentifier( - ((ASN1ObjectIdentifier)iter.next()).getId())); - } + copy.policy = policy; + copy.policyOID = policyOID; } if (subjectAltNames != null) { - copy.subjectAltNames = new HashSet(getSubjectAlternativeNames()); + copy.subjectAltNames = (Set)getSubjectAlternativeNames(); Iterator iter = subjectAltNamesByte.iterator(); List obj; List cloneObj; @@ -2431,7 +2317,7 @@ public Object clone() } if (pathToNames != null) { - copy.pathToNames = new HashSet(getPathToNames()); + copy.pathToNames = (Set)getPathToNames(); Iterator iter = pathToNamesByte.iterator(); List obj; List cloneObj; diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLEntryObject.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLEntryObject.java index af7be81ce9..9b0a50b568 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLEntryObject.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLEntryObject.java @@ -12,6 +12,7 @@ import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x500.X500Name; @@ -78,9 +79,9 @@ public X509CRLEntryObject( */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); + Extensions extensions = c.getExtensions(); - return extns != null && !extns.isEmpty(); + return extensions != null && extensions.hasAnyCriticalExtensions(); } private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) @@ -90,16 +91,15 @@ private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCert return null; } - byte[] ext = getExtensionValue(X509Extension.certificateIssuer.getId()); - if (ext == null) + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), Extension.certificateIssuer); + if (extValue == null) { return previousCertificateIssuer; } try { - GeneralName[] names = GeneralNames.getInstance( - X509ExtensionUtil.fromExtensionValue(ext)).getNames(); + GeneralName[] names = GeneralNames.getInstance(extValue.getOctets()).getNames(); for (int i = 0; i < names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) @@ -121,8 +121,8 @@ public X509Principal getCertificateIssuer() { return null; } - try - { + try + { return new X509Principal(certificateIssuer.getEncoded()); } catch (Exception e) @@ -130,6 +130,7 @@ public X509Principal getCertificateIssuer() throw new IllegalStateException(e.toString()); } } + private Set getExtensionOIDs(boolean critical) { Extensions extensions = c.getExtensions(); @@ -168,26 +169,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } /** diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLObject.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLObject.java index 43fcadc46c..3020ee486b 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLObject.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CRLObject.java @@ -37,9 +37,10 @@ import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.IssuingDistributionPoint; import org.bouncycastle.asn1.x509.TBSCertList; +import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.RFC3280CertPathUtilities; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.x509.extension.X509ExtensionUtil; @@ -104,30 +105,41 @@ public X509CRLObject( } } - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ public boolean hasUnsupportedCriticalExtension() { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) + if (getVersion() == 2) { - return false; - } + Extensions extensions = c.getExtensions(); + if (extensions != null) + { + Enumeration e = extensions.oids(); + while (e.hasMoreElements()) + { + ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); + if (Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid)) + { + continue; + } + + Extension ext = extensions.getExtension(oid); + if (ext.isCritical()) + { + return true; + } + } + } + } - return !extns.isEmpty(); + return false; } private Set getExtensionOIDs(boolean critical) { if (this.getVersion() == 2) { - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -164,26 +176,7 @@ public Set getNonCriticalExtensionOIDs() public byte[] getExtensionValue(String oid) { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public byte[] getEncoded() @@ -252,14 +245,11 @@ public Date getThisUpdate() public Date getNextUpdate() { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } + Time nextUpdate = c.getNextUpdate(); - return null; + return null == nextUpdate ? null : nextUpdate.getDate(); } - + private Set loadCRLEntries() { Set entrySet = new HashSet(); @@ -355,16 +345,7 @@ public String getSigAlgOID() public byte[] getSigAlgParams() { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; + return Arrays.clone(sigAlgParams); } /** @@ -406,7 +387,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertList().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CertificateObject.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CertificateObject.java index 21bae59d99..ee198b6196 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CertificateObject.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/X509CertificateObject.java @@ -34,6 +34,7 @@ import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -57,7 +58,6 @@ import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.RFC3280CertPathUtilities; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.util.Arrays; @@ -85,7 +85,7 @@ public X509CertificateObject( try { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); + byte[] bytes = getExtensionOctets(c, Extension.basicConstraints); if (bytes != null) { @@ -99,10 +99,10 @@ public X509CertificateObject( try { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); + byte[] bytes = getExtensionOctets(c, Extension.keyUsage); if (bytes != null) { - ASN1BitString bits = ASN1BitString.getInstance(ASN1Primitive.fromByteArray(bytes)); + ASN1BitString bits = ASN1BitString.getInstance(ASN1Primitive.fromByteArray(bytes)); bytes = bits.getBytes(); int length = (bytes.length * 8) - bits.getPadBits(); @@ -314,32 +314,29 @@ public boolean[] getKeyUsage() public List getExtendedKeyUsage() throws CertificateParsingException { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); + byte[] extOctets = getExtensionOctets(c, Extension.extendedKeyUsage); + if (null == extOctets) + { + return null; + } - if (bytes != null) + try { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); + ASN1Sequence seq = ASN1Sequence.getInstance(extOctets); - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) + List list = new ArrayList(); + for (int i = 0; i != seq.size(); i++) { - throw new CertificateParsingException("error processing extended key usage extension"); + list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); } + return Collections.unmodifiableList(list); + } + catch (Exception e) + { + throw new CertificateParsingException("error processing extended key usage extension"); } - - return null; } - + public int getBasicConstraints() { if (basicConstraints != null) @@ -367,13 +364,13 @@ public int getBasicConstraints() public Collection getSubjectAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); + return getAlternativeNames(c, Extension.subjectAlternativeName); } public Collection getIssuerAlternativeNames() throws CertificateParsingException { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); + return getAlternativeNames(c, Extension.issuerAlternativeName); } public Set getCriticalExtensionOIDs() @@ -381,7 +378,7 @@ public Set getCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -405,44 +402,9 @@ public Set getCriticalExtensionOIDs() return null; } - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - public byte[] getExtensionValue(String oid) { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; + return X509SignatureUtil.getExtensionValue(c.getExtensions(), oid); } public Set getNonCriticalExtensionOIDs() @@ -450,7 +412,7 @@ public Set getNonCriticalExtensionOIDs() if (this.getVersion() == 3) { Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -476,36 +438,32 @@ public Set getNonCriticalExtensionOIDs() public boolean hasUnsupportedCriticalExtension() { - if (this.getVersion() == 3) + if (getVersion() == 3) { - Extensions extensions = c.getTBSCertificate().getExtensions(); - + Extensions extensions = c.getExtensions(); if (extensions != null) { - Enumeration e = extensions.oids(); - + Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) + + if (Extension.keyUsage.equals(oid) || + Extension.certificatePolicies.equals(oid) || + Extension.policyMappings.equals(oid) || + Extension.inhibitAnyPolicy.equals(oid) || + Extension.cRLDistributionPoints.equals(oid) || + Extension.issuingDistributionPoint.equals(oid) || + Extension.deltaCRLIndicator.equals(oid) || + Extension.policyConstraints.equals(oid) || + Extension.basicConstraints.equals(oid) || + Extension.subjectAlternativeName.equals(oid) || + Extension.nameConstraints.equals(oid)) { continue; } - Extension ext = extensions.getExtension(oid); - + Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { return true; @@ -646,7 +604,7 @@ public String toString() } } - Extensions extensions = c.getTBSCertificate().getExtensions(); + Extensions extensions = c.getExtensions(); if (extensions != null) { @@ -801,17 +759,18 @@ private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) return id1.getParameters().equals(id2.getParameters()); } - private static Collection getAlternativeNames(byte[] extVal) + private static Collection getAlternativeNames(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) throws CertificateParsingException { - if (extVal == null) + byte[] extOctets = getExtensionOctets(c, oid); + if (extOctets == null) { return null; } try { Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); + Enumeration it = ASN1Sequence.getInstance(extOctets).getObjects(); while (it.hasMoreElements()) { GeneralName genName = GeneralName.getInstance(it.nextElement()); @@ -856,4 +815,11 @@ private static Collection getAlternativeNames(byte[] extVal) throw new CertificateParsingException(e.getMessage()); } } + + private static byte[] getExtensionOctets(org.bouncycastle.asn1.x509.Certificate c, ASN1ObjectIdentifier oid) + { + ASN1OctetString extValue = Extensions.getExtensionValue(c.getExtensions(), oid); + + return extValue == null ? null : extValue.getOctets(); + } } diff --git a/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java b/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java index 1994e1f3cf..a1090e3bcb 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberCipherSpi.java @@ -22,30 +22,38 @@ import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.SecretWithEncapsulation; import org.bouncycastle.crypto.Wrapper; -import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jcajce.spec.KEMParameterSpec; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.pqc.jcajce.provider.util.WrapUtil; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Exceptions; +import org.bouncycastle.util.Strings; class KyberCipherSpi extends CipherSpi { private final String algorithmName; - private KyberKEMGenerator kemGen; - private KEMParameterSpec kemParameterSpec; + private MLKEMGenerator kemGen; + private KTSParameterSpec kemParameterSpec; private BCKyberPublicKey wrapKey; private BCKyberPrivateKey unwrapKey; - private SecureRandom random; private AlgorithmParameters engineParams; + private MLKEMParameters kyberParameters; KyberCipherSpi(String algorithmName) - throws NoSuchAlgorithmException { this.algorithmName = algorithmName; + this.kyberParameters = null; + } + + KyberCipherSpi(MLKEMParameters kyberParameters) + { + this.kyberParameters = kyberParameters; + this.algorithmName = Strings.toUpperCase(kyberParameters.getName()); } @Override @@ -125,11 +133,6 @@ protected void engineInit(int opmode, Key key, SecureRandom random) protected void engineInit(int opmode, Key key, AlgorithmParameterSpec paramSpec, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { - if (random == null) - { - this.random = CryptoServicesRegistrar.getSecureRandom(); - } - if (paramSpec == null) { // TODO: default should probably use shake. @@ -137,12 +140,12 @@ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec paramSpec, } else { - if (!(paramSpec instanceof KEMParameterSpec)) + if (!(paramSpec instanceof KTSParameterSpec)) { throw new InvalidAlgorithmParameterException(algorithmName + " can only accept KTSParameterSpec"); } - kemParameterSpec = (KEMParameterSpec)paramSpec; + kemParameterSpec = (KTSParameterSpec)paramSpec; } if (opmode == Cipher.WRAP_MODE) @@ -150,11 +153,11 @@ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec paramSpec, if (key instanceof BCKyberPublicKey) { wrapKey = (BCKyberPublicKey)key; - kemGen = new KyberKEMGenerator(random); + kemGen = new MLKEMGenerator(CryptoServicesRegistrar.getSecureRandom(random)); } else { - throw new InvalidKeyException("Only an RSA public key can be used for wrapping"); + throw new InvalidKeyException("Only a " + algorithmName + " public key can be used for wrapping"); } } else if (opmode == Cipher.UNWRAP_MODE) @@ -165,17 +168,26 @@ else if (opmode == Cipher.UNWRAP_MODE) } else { - throw new InvalidKeyException("Only an RSA private key can be used for unwrapping"); + throw new InvalidKeyException("Only a " + algorithmName + " private key can be used for unwrapping"); } } else { throw new InvalidParameterException("Cipher only valid for wrapping/unwrapping"); } + + if (kyberParameters != null) + { + String canonicalAlgName = Strings.toUpperCase(kyberParameters.getName()); + if (!canonicalAlgName.equals(key.getAlgorithm())) + { + throw new InvalidKeyException("cipher locked to " + canonicalAlgName); + } + } } @Override - protected void engineInit(int opmode, Key key, AlgorithmParameters algorithmParameters, SecureRandom secureRandom) + protected void engineInit(int opmode, Key key, AlgorithmParameters algorithmParameters, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; @@ -223,8 +235,8 @@ protected int engineDoFinal(byte[] bytes, int i, int i1, byte[] bytes1, int i2) } protected byte[] engineWrap( - Key key) - throws IllegalBlockSizeException, InvalidKeyException + Key key) + throws IllegalBlockSizeException, InvalidKeyException { byte[] encoded = key.getEncoded(); if (encoded == null) @@ -232,20 +244,15 @@ protected byte[] engineWrap( throw new InvalidKeyException("Cannot wrap key, null encoding."); } + SecretWithEncapsulation secEnc = null; try { - SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(wrapKey.getKeyParams()); - - Wrapper kWrap = WrapUtil.getWrapper(kemParameterSpec.getKeyAlgorithmName()); - - KeyParameter keyParameter = new KeyParameter(secEnc.getSecret()); + secEnc = kemGen.generateEncapsulated(wrapKey.getKeyParams()); - kWrap.init(true, keyParameter); + Wrapper kWrap = WrapUtil.getKeyWrapper(kemParameterSpec, secEnc.getSecret()); byte[] encapsulation = secEnc.getEncapsulation(); - secEnc.destroy(); - byte[] keyToWrap = key.getEncoded(); byte[] rv = Arrays.concatenate(encapsulation, kWrap.wrap(keyToWrap, 0, keyToWrap.length)); @@ -258,9 +265,19 @@ protected byte[] engineWrap( { throw new IllegalBlockSizeException("unable to generate KTS secret: " + e.getMessage()); } - catch (Exception e) + finally { - throw new IllegalBlockSizeException("unable to destroy interim values: " + e.getMessage()); + try + { + if (secEnc != null) + { + secEnc.destroy(); + } + } + catch (Exception e) + { + throw new IllegalBlockSizeException("unable to destroy interim values: " + e.getMessage()); + } } } @@ -275,26 +292,19 @@ protected Key engineUnwrap( { throw new InvalidKeyException("only SECRET_KEY supported"); } + byte[] secret = null; try { - KyberKEMExtractor kemExt = new KyberKEMExtractor(unwrapKey.getKeyParams()); - - byte[] secret = kemExt.extractSecret(Arrays.copyOfRange(wrappedKey, 0, kemExt.getEncapsulationLength())); + MLKEMExtractor kemExt = new MLKEMExtractor(unwrapKey.getKeyParams()); - Wrapper kWrap = WrapUtil.getWrapper(kemParameterSpec.getKeyAlgorithmName()); + secret = kemExt.extractSecret(Arrays.copyOfRange(wrappedKey, 0, kemExt.getEncapsulationLength())); - KeyParameter keyParameter = new KeyParameter(secret); - - Arrays.clear(secret); - - kWrap.init(false, keyParameter); + Wrapper kWrap = WrapUtil.getKeyUnwrapper(kemParameterSpec, secret); byte[] keyEncBytes = Arrays.copyOfRange(wrappedKey, kemExt.getEncapsulationLength(), wrappedKey.length); SecretKey rv = new SecretKeySpec(kWrap.unwrap(keyEncBytes, 0, keyEncBytes.length), wrappedKeyAlgorithm); - Arrays.clear(keyParameter.getKey()); - return rv; } catch (IllegalArgumentException e) @@ -305,6 +315,13 @@ protected Key engineUnwrap( { throw new InvalidKeyException("unable to extract KTS secret: " + e.getMessage()); } + finally + { + if (secret != null) + { + Arrays.clear(secret); + } + } } public static class Base @@ -313,7 +330,34 @@ public static class Base public Base() throws NoSuchAlgorithmException { - super("Kyber"); + super("KYBER"); + } + } + + public static class Kyber512 + extends KyberCipherSpi + { + public Kyber512() + { + super(MLKEMParameters.ml_kem_512); + } + } + + public static class Kyber768 + extends KyberCipherSpi + { + public Kyber768() + { + super(MLKEMParameters.ml_kem_768); + } + } + + public static class Kyber1024 + extends KyberCipherSpi + { + public Kyber1024() + { + super(MLKEMParameters.ml_kem_1024); } } } diff --git a/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java b/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java index 4896fd4325..33355b88a5 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/pqc/jcajce/provider/kyber/KyberKeyGeneratorSpi.java @@ -12,9 +12,11 @@ import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; import org.bouncycastle.jcajce.spec.KEMExtractSpec; import org.bouncycastle.jcajce.spec.KEMGenerateSpec; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; public class KyberKeyGeneratorSpi extends KeyGeneratorSpi @@ -22,6 +24,17 @@ public class KyberKeyGeneratorSpi private KEMGenerateSpec genSpec; private SecureRandom random; private KEMExtractSpec extSpec; + private MLKEMParameters kyberParameters; + + public KyberKeyGeneratorSpi() + { + this(null); + } + + protected KyberKeyGeneratorSpi(MLKEMParameters kyberParameters) + { + this.kyberParameters = kyberParameters; + } protected void engineInit(SecureRandom secureRandom) { @@ -36,11 +49,27 @@ protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec, SecureR { this.genSpec = (KEMGenerateSpec)algorithmParameterSpec; this.extSpec = null; + if (kyberParameters != null) + { + String canonicalAlgName = Strings.toUpperCase(kyberParameters.getName()); + if (!canonicalAlgName.equals(genSpec.getPublicKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } } else if (algorithmParameterSpec instanceof KEMExtractSpec) { this.genSpec = null; this.extSpec = (KEMExtractSpec)algorithmParameterSpec; + if (kyberParameters != null) + { + String canonicalAlgName = Strings.toUpperCase(kyberParameters.getName()); + if (!canonicalAlgName.equals(extSpec.getPrivateKey().getAlgorithm())) + { + throw new InvalidAlgorithmParameterException("key generator locked to " + canonicalAlgName); + } + } } else { @@ -58,11 +87,16 @@ protected SecretKey engineGenerateKey() if (genSpec != null) { BCKyberPublicKey pubKey = (BCKyberPublicKey)genSpec.getPublicKey(); - KyberKEMGenerator kemGen = new KyberKEMGenerator(random); + MLKEMGenerator kemGen = new MLKEMGenerator(random); SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(pubKey.getKeyParams()); - SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secEnc.getSecret(), genSpec.getKeyAlgorithmName()), secEnc.getEncapsulation()); + byte[] sharedSecret = secEnc.getSecret(); + byte[] secret = Arrays.copyOfRange(sharedSecret, 0, (genSpec.getKeySize() + 7) / 8); + + Arrays.clear(sharedSecret); + + SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secret, genSpec.getKeyAlgorithmName()), secEnc.getEncapsulation()); try { @@ -78,10 +112,13 @@ protected SecretKey engineGenerateKey() else { BCKyberPrivateKey privKey = (BCKyberPrivateKey)extSpec.getPrivateKey(); - KyberKEMExtractor kemExt = new KyberKEMExtractor(privKey.getKeyParams()); + MLKEMExtractor kemExt = new MLKEMExtractor(privKey.getKeyParams()); byte[] encapsulation = extSpec.getEncapsulation(); - byte[] secret = kemExt.extractSecret(encapsulation); + byte[] sharedSecret = kemExt.extractSecret(encapsulation); + byte[] secret = Arrays.copyOfRange(sharedSecret, 0, (extSpec.getKeySize() + 7) / 8); + + Arrays.clear(sharedSecret); SecretKey rv = new SecretKeyWithEncapsulation(new SecretKeySpec(secret, extSpec.getKeyAlgorithmName()), encapsulation); @@ -90,4 +127,31 @@ protected SecretKey engineGenerateKey() return rv; } } + + public static class Kyber512 + extends KyberKeyGeneratorSpi + { + public Kyber512() + { + super(MLKEMParameters.ml_kem_512); + } + } + + public static class Kyber768 + extends KyberKeyGeneratorSpi + { + public Kyber768() + { + super(MLKEMParameters.ml_kem_768); + } + } + + public static class Kyber1024 + extends KyberKeyGeneratorSpi + { + public Kyber1024() + { + super(MLKEMParameters.ml_kem_1024); + } + } } diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java index 6df1bf6d2d..41ed06db8b 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java @@ -46,23 +46,28 @@ public class BCECPrivateKey implements ECPrivateKey, PKCS12BagAttributeCarrier, ECPointEncoder { - private String algorithm = "EC"; - private boolean withCompression; + static final long serialVersionUID = 994553197664784084L; - private transient BigInteger d; - private transient ECParameterSpec ecSpec; - private transient ProviderConfiguration configuration; - private transient ASN1BitString publicKey; + private String algorithm = "EC"; + private boolean withCompression; + + private transient BigInteger d; + private transient ECParameterSpec ecSpec; + private transient ProviderConfiguration configuration; + private transient ASN1BitString publicKey; + private transient PrivateKeyInfo privateKeyInfo; + private transient byte[] encoding; private transient ECPrivateKeyParameters baseKey; private transient PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl(); + protected BCECPrivateKey() { } - BCECPrivateKey( - ECPrivateKey key, + public BCECPrivateKey( + ECPrivateKey key, ProviderConfiguration configuration) { this.d = key.getD(); @@ -73,8 +78,8 @@ protected BCECPrivateKey() } public BCECPrivateKey( - String algorithm, - ECPrivateKeySpec spec, + String algorithm, + ECPrivateKeySpec spec, ProviderConfiguration configuration) { this.algorithm = algorithm; @@ -83,12 +88,26 @@ public BCECPrivateKey( this.configuration = configuration; this.baseKey = convertToBaseKey(this); } + + public BCECPrivateKey( + String algorithm, + BCECPrivateKey key) + { + this.algorithm = algorithm; + this.d = key.d; + this.ecSpec = key.ecSpec; + this.withCompression = key.withCompression; + this.attrCarrier = key.attrCarrier; + this.publicKey = key.publicKey; + this.configuration = key.configuration; + this.baseKey = key.baseKey; + } public BCECPrivateKey( - String algorithm, - ECPrivateKeyParameters params, - BCECPublicKey pubKey, - ECParameterSpec spec, + String algorithm, + ECPrivateKeyParameters params, + BCECPublicKey pubKey, + ECParameterSpec spec, ProviderConfiguration configuration) { ECDomainParameters dp = params.getParameters(); @@ -116,49 +135,26 @@ public BCECPrivateKey( } public BCECPrivateKey( - String algorithm, - ECPrivateKeyParameters params, - ProviderConfiguration configuration) + String algorithm, + ECPrivateKeyParameters params, + ProviderConfiguration configuration) { this.algorithm = algorithm; this.d = params.getD(); this.ecSpec = null; this.configuration = configuration; - this.baseKey = convertToBaseKey(this); - } - - public BCECPrivateKey( - String algorithm, - BCECPrivateKey key) - { - this.algorithm = algorithm; - this.d = key.d; - this.ecSpec = key.ecSpec; - this.withCompression = key.withCompression; - this.publicKey = key.publicKey; - this.attrCarrier = key.attrCarrier; - this.configuration = key.configuration; - } - - BCECPrivateKey( - PrivateKeyInfo info, - ProviderConfiguration configuration) - throws IOException - { - this.configuration = configuration; - - populateFromPrivKeyInfo(info); + this.baseKey = params; } BCECPrivateKey( - String algorithm, - PrivateKeyInfo info, + String algorithm, + PrivateKeyInfo info, ProviderConfiguration configuration) throws IOException { + this.algorithm = algorithm; this.configuration = configuration; populateFromPrivKeyInfo(info); - this.algorithm = algorithm; } private void populateFromPrivKeyInfo(PrivateKeyInfo info) @@ -306,6 +302,16 @@ public Enumeration getBagAttributeKeys() return attrCarrier.getBagAttributeKeys(); } + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java index 344dbe4280..8c2c701cfd 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java @@ -47,10 +47,10 @@ public class BCECGOST3410PrivateKey implements ECPrivateKey, PKCS12BagAttributeCarrier, ECPointEncoder { - private String algorithm = "ECGOST3410"; - private boolean withCompression; + private String algorithm = "ECGOST3410"; + private boolean withCompression; - private transient BigInteger d; + private transient BigInteger d; private transient ECParameterSpec ecSpec; private transient ASN1BitString publicKey; private transient PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl(); @@ -60,7 +60,7 @@ protected BCECGOST3410PrivateKey() } BCECGOST3410PrivateKey( - ECPrivateKey key) + ECPrivateKey key) { this.d = key.getD(); this.algorithm = key.getAlgorithm(); @@ -68,19 +68,19 @@ protected BCECGOST3410PrivateKey() } public BCECGOST3410PrivateKey( - ECPrivateKeySpec spec) + ECPrivateKeySpec spec) { this.d = spec.getD(); this.ecSpec = spec.getParams(); } public BCECGOST3410PrivateKey( - String algorithm, - ECPrivateKeyParameters params, - BCECGOST3410PublicKey pubKey, - ECParameterSpec spec) + String algorithm, + ECPrivateKeyParameters params, + BCECGOST3410PublicKey pubKey, + ECParameterSpec spec) { - ECDomainParameters dp = params.getParameters(); + ECDomainParameters dp = params.getParameters(); this.algorithm = algorithm; this.d = params.getD(); @@ -88,11 +88,11 @@ public BCECGOST3410PrivateKey( if (spec == null) { this.ecSpec = new ECParameterSpec( - dp.getCurve(), - dp.getG(), - dp.getN(), - dp.getH(), - dp.getSeed()); + dp.getCurve(), + dp.getG(), + dp.getN(), + dp.getH(), + dp.getSeed()); } else { @@ -103,8 +103,8 @@ public BCECGOST3410PrivateKey( } public BCECGOST3410PrivateKey( - String algorithm, - ECPrivateKeyParameters params) + String algorithm, + ECPrivateKeyParameters params) { this.algorithm = algorithm; this.d = params.getD(); @@ -112,8 +112,8 @@ public BCECGOST3410PrivateKey( } public BCECGOST3410PrivateKey( - String algorithm, - BCECGOST3410PrivateKey key) + String algorithm, + BCECGOST3410PrivateKey key) { this.algorithm = algorithm; this.d = key.d; @@ -124,7 +124,7 @@ public BCECGOST3410PrivateKey( } BCECGOST3410PrivateKey( - PrivateKeyInfo info) + PrivateKeyInfo info) throws IOException { populateFromPrivKeyInfo(info); @@ -133,20 +133,20 @@ public BCECGOST3410PrivateKey( private void populateFromPrivKeyInfo(PrivateKeyInfo info) throws IOException { - X962Parameters params = X962Parameters.getInstance(info.getPrivateKeyAlgorithm().getParameters()); + X962Parameters params = X962Parameters.getInstance(info.getPrivateKeyAlgorithm().getParameters()); if (params.isNamedCurve()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)params.getParameters(); - X9ECParameters ecP = ECGOST3410NamedCurves.getByOIDX9(oid); + X9ECParameters ecP = ECGOST3410NamedCurves.getByOIDX9(oid); ecSpec = new ECNamedCurveParameterSpec( - ECUtil.getCurveName(oid), - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); + ECUtil.getCurveName(oid), + ecP.getCurve(), + ecP.getG(), + ecP.getN(), + ecP.getH(), + ecP.getSeed()); } else if (params.isImplicitlyCA()) { @@ -154,23 +154,23 @@ else if (params.isImplicitlyCA()) } else { - X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters()); + X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters()); ecSpec = new ECParameterSpec(ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); + ecP.getG(), + ecP.getN(), + ecP.getH(), + ecP.getSeed()); } if (info.parsePrivateKey() instanceof ASN1Integer) { - ASN1Integer derD = ASN1Integer.getInstance(info.parsePrivateKey()); + ASN1Integer derD = ASN1Integer.getInstance(info.parsePrivateKey()); this.d = derD.getValue(); } else { - ECPrivateKeyStructure ec = new ECPrivateKeyStructure(ASN1Sequence.getInstance(info.parsePrivateKey())); + ECPrivateKeyStructure ec = new ECPrivateKeyStructure(ASN1Sequence.getInstance(info.parsePrivateKey())); this.d = ec.getKey(); this.publicKey = ec.getPublicKey(); @@ -200,14 +200,14 @@ public String getFormat() */ public byte[] getEncoded() { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream dOut = ASN1OutputStream.create(bOut, ASN1Encoding.DER); - X962Parameters params = null; + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ASN1OutputStream dOut = ASN1OutputStream.create(bOut, ASN1Encoding.DER); + X962Parameters params = null; if (ecSpec instanceof ECNamedCurveParameterSpec) { ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveParameterSpec)ecSpec).getName()); - + params = new X962Parameters(curveOid); } else if (ecSpec == null) @@ -222,16 +222,16 @@ else if (ecSpec == null) ECPoint g = pG.getCurve().createPoint(pG.getAffineXCoord().toBigInteger(), pG.getAffineYCoord().toBigInteger()); X9ECParameters ecP = new X9ECParameters( - p.getCurve(), - new X9ECPoint(g, withCompression), - p.getN(), - p.getH(), - p.getSeed()); + p.getCurve(), + new X9ECPoint(g, withCompression), + p.getN(), + p.getH(), + p.getSeed()); params = new X962Parameters(ecP); } - PrivateKeyInfo info; + PrivateKeyInfo info; ECPrivateKeyStructure keyStructure; if (publicKey != null) @@ -271,7 +271,7 @@ public ECParameterSpec getParameters() { return (ECParameterSpec)ecSpec; } - + public BigInteger getD() { return d; @@ -279,7 +279,7 @@ public BigInteger getD() public void setBagAttribute( ASN1ObjectIdentifier oid, - ASN1Encodable attribute) + ASN1Encodable attribute) { attrCarrier.setBagAttribute(oid, attribute); } @@ -294,10 +294,20 @@ public Enumeration getBagAttributeKeys() { return attrCarrier.getBagAttributeKeys(); } - + + public boolean hasFriendlyName() + { + return attrCarrier.hasFriendlyName(); + } + + public void setFriendlyName(String friendlyName) + { + attrCarrier.setFriendlyName(friendlyName); + } + public void setPointFormat(String style) { - withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); + withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); } ECParameterSpec engineGetSpec() @@ -332,7 +342,7 @@ public int hashCode() return getD().hashCode() ^ engineGetSpec().hashCode(); } - private ASN1BitString getPublicKeyDetails(BCECGOST3410PublicKey pub) + private ASN1BitString getPublicKeyDetails(BCECGOST3410PublicKey pub) { try { diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java index f59df72c3f..a2991bbcf4 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java @@ -64,7 +64,7 @@ import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.GOST28147Parameters; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.ntt.NTTObjectIdentifiers; +import org.bouncycastle.internal.asn1.ntt.NTTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.AuthenticatedSafe; import org.bouncycastle.asn1.pkcs.CertBag; import org.bouncycastle.asn1.pkcs.ContentInfo; diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java index 25c201ed61..d461361cd9 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java @@ -24,20 +24,19 @@ import javax.crypto.spec.RC5ParameterSpec; import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.crypto.fpe.FPEEngine; -import org.bouncycastle.crypto.fpe.FPEFF1Engine; -import org.bouncycastle.crypto.fpe.FPEFF3_1Engine; -import org.bouncycastle.crypto.params.FPEParameters; -import org.bouncycastle.internal.asn1.cms.GCMParameters; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.DefaultBufferedBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.engines.DSTU7624Engine; +import org.bouncycastle.crypto.fpe.FPEEngine; +import org.bouncycastle.crypto.fpe.FPEFF1Engine; +import org.bouncycastle.crypto.fpe.FPEFF3_1Engine; import org.bouncycastle.crypto.modes.AEADBlockCipher; import org.bouncycastle.crypto.modes.AEADCipher; import org.bouncycastle.crypto.modes.CBCBlockCipher; @@ -60,19 +59,24 @@ import org.bouncycastle.crypto.paddings.BlockCipherPadding; import org.bouncycastle.crypto.paddings.ISO10126d2Padding; import org.bouncycastle.crypto.paddings.ISO7816d4Padding; +import org.bouncycastle.crypto.paddings.PKCS7Padding; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.paddings.TBCPadding; import org.bouncycastle.crypto.paddings.X923Padding; import org.bouncycastle.crypto.paddings.ZeroBytePadding; import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.FPEParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.params.ParametersWithSBox; import org.bouncycastle.crypto.params.RC2Parameters; import org.bouncycastle.crypto.params.RC5Parameters; +import org.bouncycastle.internal.asn1.cms.GCMParameters; import org.bouncycastle.jcajce.PBKDF1Key; import org.bouncycastle.jcajce.PBKDF1KeyWithParameters; +import org.bouncycastle.jcajce.PBKDF2Key; +import org.bouncycastle.jcajce.PBKDF2KeyWithParameters; import org.bouncycastle.jcajce.PKCS12Key; import org.bouncycastle.jcajce.PKCS12KeyWithParameters; import org.bouncycastle.jcajce.spec.AEADParameterSpec; @@ -92,7 +96,7 @@ public class BaseBlockCipher // // specs we can handle. // - private Class[] availableSpecs = + private static final Class[] availableSpecs = { RC2ParameterSpec.class, RC5ParameterSpec.class, @@ -155,9 +159,28 @@ protected BaseBlockCipher( cipher = new BufferedGenericBlockCipher(provider.get()); } + protected BaseBlockCipher( + int keySizeInBits, + BlockCipherProvider provider) + { + baseEngine = provider.get(); + engineProvider = provider; + this.keySizeInBits = keySizeInBits; + + cipher = new BufferedGenericBlockCipher(provider.get()); + } + protected BaseBlockCipher( AEADBlockCipher engine) { + this(0, engine); + } + + protected BaseBlockCipher( + int keySizeInBits, + AEADBlockCipher engine) + { + this.keySizeInBits = keySizeInBits; this.baseEngine = engine.getUnderlyingCipher(); if (engine.getAlgorithmName().indexOf("GCM") >= 0) { @@ -186,6 +209,16 @@ protected BaseBlockCipher( boolean fixedIv, int ivLength) { + this(0, engine, fixedIv, ivLength); + } + + protected BaseBlockCipher( + int keySizeInBits, + AEADBlockCipher engine, + boolean fixedIv, + int ivLength) + { + this.keySizeInBits = keySizeInBits; this.baseEngine = engine.getUnderlyingCipher(); this.fixedIv = fixedIv; this.ivLength = ivLength; @@ -199,6 +232,19 @@ protected BaseBlockCipher( this(engine, true, ivLength); } + protected BaseBlockCipher( + int keySizeInBits, + org.bouncycastle.crypto.BlockCipher engine, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + baseEngine = engine; + + this.fixedIv = true; + this.cipher = new BufferedGenericBlockCipher(engine); + this.ivLength = ivLength / 8; + } + protected BaseBlockCipher( org.bouncycastle.crypto.BlockCipher engine, boolean fixedIv, @@ -218,6 +264,19 @@ protected BaseBlockCipher( this(engine, true, ivLength); } + protected BaseBlockCipher( + int keySizeInBits, + BufferedBlockCipher engine, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + baseEngine = engine.getUnderlyingCipher(); + + this.cipher = new BufferedGenericBlockCipher(engine); + this.fixedIv = true; + this.ivLength = ivLength / 8; + } + protected BaseBlockCipher( BufferedBlockCipher engine, boolean fixedIv, @@ -350,7 +409,7 @@ else if (modeName.equals("CBC")) { ivLength = baseEngine.getBlockSize(); cipher = new BufferedGenericBlockCipher( - new CBCBlockCipher(baseEngine)); + CBCBlockCipher.newInstance(baseEngine)); } else if (modeName.startsWith("OFB")) { @@ -376,12 +435,12 @@ else if (modeName.startsWith("CFB")) int wordSize = Integer.parseInt(modeName.substring(3)); cipher = new BufferedGenericBlockCipher( - new CFBBlockCipher(baseEngine, wordSize)); + CFBBlockCipher.newInstance(baseEngine, wordSize)); } else { cipher = new BufferedGenericBlockCipher( - new CFBBlockCipher(baseEngine, 8 * baseEngine.getBlockSize())); + CFBBlockCipher.newInstance(baseEngine, 8 * baseEngine.getBlockSize())); } } else if (modeName.startsWith("PGPCFB")) @@ -423,8 +482,8 @@ else if (modeName.equals("SIC")) throw new IllegalArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); } fixedIv = false; - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( - new SICBlockCipher(baseEngine))); + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + SICBlockCipher.newInstance(baseEngine))); } else if (modeName.equals("CTR")) { @@ -432,31 +491,31 @@ else if (modeName.equals("CTR")) fixedIv = false; if (baseEngine instanceof DSTU7624Engine) { - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( new KCTRBlockCipher(baseEngine))); } else { - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( - new SICBlockCipher(baseEngine))); + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + SICBlockCipher.newInstance(baseEngine))); } } else if (modeName.equals("GOFB")) { ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( new GOFBBlockCipher(baseEngine))); } else if (modeName.equals("GCFB")) { ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( new GCFBBlockCipher(baseEngine))); } else if (modeName.equals("CTS")) { ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(new CBCBlockCipher(baseEngine))); + cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(CBCBlockCipher.newInstance(baseEngine))); } else if (modeName.equals("CCM")) { @@ -467,7 +526,7 @@ else if (modeName.equals("CCM")) } else { - cipher = new AEADGenericBlockCipher(new CCMBlockCipher(baseEngine)); + cipher = new AEADGenericBlockCipher(CCMBlockCipher.newInstance(baseEngine)); } } else if (modeName.equals("OCB")) @@ -505,7 +564,7 @@ else if (modeName.equals("GCM")) else { ivLength = 12; - cipher = new AEADGenericBlockCipher(new GCMBlockCipher(baseEngine)); + cipher = new AEADGenericBlockCipher(GCMBlockCipher.newInstance(baseEngine)); } } else @@ -538,7 +597,7 @@ protected void engineSetPadding( { if (cipher.wrapOnNoPadding()) { - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher(cipher.getUnderlyingCipher())); + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher(cipher.getUnderlyingCipher())); } } else if (paddingName.equals("WITHCTS") || paddingName.equals("CTSPADDING") || paddingName.equals("CS3PADDING")) @@ -587,7 +646,7 @@ else if (paddingName.equals("TBCPADDING")) protected void engineInit( int opmode, Key key, - final AlgorithmParameterSpec params, + final AlgorithmParameterSpec paramSpec, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { @@ -609,7 +668,7 @@ protected void engineInit( // // for RC5-64 we must have some default parameters // - if (params == null && (baseEngine != null && baseEngine.getAlgorithmName().startsWith("RC5-64"))) + if (paramSpec == null && (baseEngine != null && baseEngine.getAlgorithmName().startsWith("RC5-64"))) { throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in."); } @@ -629,9 +688,9 @@ protected void engineInit( throw new InvalidKeyException("PKCS12 requires a SecretKey/PBEKey"); } - if (params instanceof PBEParameterSpec) + if (paramSpec instanceof PBEParameterSpec) { - pbeSpec = (PBEParameterSpec)params; + pbeSpec = (PBEParameterSpec)paramSpec; } if (k instanceof PBEKey && pbeSpec == null) @@ -680,9 +739,9 @@ else if (key instanceof PBKDF1Key) { PBKDF1Key k = (PBKDF1Key)key; - if (params instanceof PBEParameterSpec) + if (paramSpec instanceof PBEParameterSpec) { - pbeSpec = (PBEParameterSpec)params; + pbeSpec = (PBEParameterSpec)paramSpec; } if (k instanceof PBKDF1KeyWithParameters && pbeSpec == null) { @@ -695,6 +754,25 @@ else if (key instanceof PBKDF1Key) ivParam = (ParametersWithIV)param; } } + else if (key instanceof PBKDF2Key) + { + PBKDF2Key k = (PBKDF2Key)key; + + if (paramSpec instanceof PBEParameterSpec) + { + pbeSpec = (PBEParameterSpec)paramSpec; + } + if (k instanceof PBKDF2KeyWithParameters && pbeSpec == null) + { + pbeSpec = new PBEParameterSpec(((PBKDF2KeyWithParameters)k).getSalt(), ((PBKDF2KeyWithParameters)k).getIterationCount()); + } + + param = PBE.Util.makePBEParameters(k.getEncoded(), PKCS5S2, PBE.SHA512, keySizeInBits, 0, pbeSpec, cipher.getAlgorithmName()); + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } else if (key instanceof BCPBEKey) { BCPBEKey k = (BCPBEKey)key; @@ -710,12 +788,12 @@ else if (key instanceof BCPBEKey) if (k.getParam() != null) { - param = adjustParameters(params, k.getParam()); + param = adjustParameters(paramSpec, k.getParam()); } - else if (params instanceof PBEParameterSpec) + else if (paramSpec instanceof PBEParameterSpec) { - pbeSpec = (PBEParameterSpec)params; - param = PBE.Util.makePBEParameters(k, params, cipher.getUnderlyingCipher().getAlgorithmName()); + pbeSpec = (PBEParameterSpec)paramSpec; + param = PBE.Util.makePBEParameters(k, paramSpec, cipher.getUnderlyingCipher().getAlgorithmName()); } else { @@ -730,7 +808,7 @@ else if (params instanceof PBEParameterSpec) else if (key instanceof PBEKey) { PBEKey k = (PBEKey)key; - pbeSpec = (PBEParameterSpec)params; + pbeSpec = (PBEParameterSpec)paramSpec; if (k instanceof PKCS12KeyWithParameters && pbeSpec == null) { pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount()); @@ -755,6 +833,8 @@ else if (!(key instanceof RepeatedSecretKeySpec)) param = null; } + AlgorithmParameterSpec params = paramSpec; + if (params instanceof AEADParameterSpec) { if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) @@ -809,7 +889,7 @@ else if (params instanceof GOST28147ParameterSpec) GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; param = new ParametersWithSBox( - new KeyParameter(key.getEncoded()), ((GOST28147ParameterSpec)params).getSbox()); + new KeyParameter(key.getEncoded()), ((GOST28147ParameterSpec)params).getSBox()); if (gost28147Param.getIV() != null && ivLength != 0) { @@ -886,9 +966,9 @@ else if (params instanceof FPEParameterSpec) { FPEParameterSpec spec = (FPEParameterSpec)params; - param = new FPEParameters((KeyParameter)param, spec.getRadix(), spec.getTweak(), spec.isUsingInverseFunction()); + param = new FPEParameters((KeyParameter)param, spec.getRadixConverter(), spec.getTweak(), spec.isUsingInverseFunction()); } - else if (gcmSpecClass != null && gcmSpecClass.isInstance(params)) + else if (GcmSpecUtil.isGcmSpec(params)) { if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) { @@ -993,7 +1073,7 @@ else if (params instanceof GOST28147ParameterSpec) // need to pick up IV and SBox. GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; - param = new ParametersWithSBox(param, gost28147Param.getSbox()); + param = new ParametersWithSBox(param, gost28147Param.getSBox()); if (gost28147Param.getIV() != null && ivLength != 0) { @@ -1016,7 +1096,7 @@ else if (params instanceof GOST28147ParameterSpec) // need to pick up IV and SBox. GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; - param = new ParametersWithSBox(param, gost28147Param.getSbox()); + param = new ParametersWithSBox(param, gost28147Param.getSBox()); if (gost28147Param.getIV() != null && ivLength != 0) { @@ -1254,7 +1334,7 @@ private static class BufferedGenericBlockCipher BufferedGenericBlockCipher(org.bouncycastle.crypto.BlockCipher cipher) { - this.cipher = new PaddedBufferedBlockCipher(cipher); + this(cipher, new PKCS7Padding()); } BufferedGenericBlockCipher(org.bouncycastle.crypto.BlockCipher cipher, BlockCipherPadding padding) diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/BouncyCastleProvider.java b/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/BouncyCastleProvider.java index f2cc535c01..a652e5cb59 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/BouncyCastleProvider.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/BouncyCastleProvider.java @@ -51,7 +51,7 @@ public final class BouncyCastleProvider extends Provider implements ConfigurableProvider { - private static String info = "BouncyCastle Security Provider v1.78.1"; + private static String info = "BouncyCastle Security Provider v1.81"; public static final String PROVIDER_NAME = "BC"; @@ -96,7 +96,7 @@ public final class BouncyCastleProvider extends Provider private static final String[] ASYMMETRIC_CIPHERS = { - "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145", "GM", "EdEC", "SPHINCSPlus", "Dilithium", "Falcon", "NTRU" + "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145", "GM", "EdEC", "SPHINCSPlus", "Dilithium", "Falcon", "NTRU", "CONTEXT", "SLHDSA", "MLDSA", "MLKEM" }; /* @@ -135,7 +135,7 @@ public final class BouncyCastleProvider extends Provider */ public BouncyCastleProvider() { - super(PROVIDER_NAME, 1.7801, info); + super(PROVIDER_NAME, 1.8100, info); AccessController.doPrivileged(new PrivilegedAction() { diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java b/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java index e1c0f30cab..1db3eedc13 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java @@ -62,6 +62,7 @@ import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Properties; class RFC3280CertPathUtilities { @@ -557,14 +558,29 @@ protected static Set processCRLF( X509Certificate signCert = (X509Certificate)validCerts.get(i); boolean[] keyUsage = signCert.getKeyUsage(); - if (keyUsage != null && (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN])) + if (keyUsage == null) { - lastException = new AnnotatedException( - "Issuer certificate key usage extension does not permit CRL signing."); + if (Properties.isOverrideSet("org.bouncycastle.x509.allow_ca_without_crl_sign", true)) + { + checkKeys.add(validKeys.get(i)); + } + else + { + lastException = new AnnotatedException( + "No key usage extension on issuer certificate."); + } } else { - checkKeys.add(validKeys.get(i)); + if (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN]) + { + lastException = new AnnotatedException( + "Issuer certificate key usage extension does not permit CRL signing."); + } + else + { + checkKeys.add(validKeys.get(i)); + } } } diff --git a/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/X509SignatureUtil.java b/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/X509SignatureUtil.java index 3338e07046..8e5c90a3b3 100644 --- a/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/X509SignatureUtil.java +++ b/prov/src/main/jdk1.4/org/bouncycastle/jce/provider/X509SignatureUtil.java @@ -6,27 +6,54 @@ import java.security.SignatureException; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.Extensions; +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.internal.asn1.oiw.OIWObjectIdentifiers; class X509SignatureUtil { - private static final ASN1Null derNull = DERNull.INSTANCE; - - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) + static byte[] getExtensionValue(Extensions extensions, String oid) + { + if (oid != null) + { + ASN1ObjectIdentifier asn1Oid = ASN1ObjectIdentifier.tryFromID(oid); + if (asn1Oid != null) + { + ASN1OctetString extValue = Extensions.getExtensionValue(extensions, asn1Oid); + if (null != extValue) + { + try + { + return extValue.getEncoded(); + } + catch (Exception e) + { + throw new IllegalStateException("error parsing " + e.toString()); + } + } + } + } + return null; + } + + private static boolean isAbsentOrEmptyParameters(ASN1Encodable parameters) + { + return parameters == null || DERNull.INSTANCE.equals(parameters); + } + + static void setSignatureParameters(Signature signature, ASN1Encodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { - if (params != null && !derNull.equals(params)) + if (!isAbsentOrEmptyParameters(params)) { /* AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider()); @@ -51,25 +78,31 @@ static void setSignatureParameters( */ } } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) + + static String getSignatureName(AlgorithmIdentifier sigAlgId) { + ASN1ObjectIdentifier sigAlgOid = sigAlgId.getAlgorithm(); ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) + + if (!isAbsentOrEmptyParameters(params)) { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { + if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgOid)) + { RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - + return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; } + if (X9ObjectIdentifiers.ecdsa_with_SHA2.equals(sigAlgOid)) + { + AlgorithmIdentifier ecDsaParams = AlgorithmIdentifier.getInstance(params); + + return getDigestAlgName(ecDsaParams.getAlgorithm()) + "withECDSA"; + } } - return sigAlgId.getAlgorithm().getId(); + return sigAlgOid.getId(); } - + /** * Return the digest algorithm using one of the standard JCA string * representations rather the the algorithm identifier (if possible). diff --git a/prov/src/main/jdk1.5/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java b/prov/src/main/jdk1.5/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java new file mode 100644 index 0000000000..5ccc3eb33a --- /dev/null +++ b/prov/src/main/jdk1.5/org/bouncycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java @@ -0,0 +1,1632 @@ +package org.bouncycastle.jcajce.provider.symmetric.util; + +import java.lang.reflect.Constructor; +import java.nio.ByteBuffer; +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.ShortBufferException; +import javax.crypto.interfaces.PBEKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEParameterSpec; +import javax.crypto.spec.RC2ParameterSpec; +import javax.crypto.spec.RC5ParameterSpec; + +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.crypto.BlockCipher; +import org.bouncycastle.crypto.BufferedBlockCipher; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.CryptoServicesRegistrar; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.DefaultBufferedBlockCipher; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.OutputLengthException; +import org.bouncycastle.crypto.engines.DSTU7624Engine; +import org.bouncycastle.crypto.fpe.FPEEngine; +import org.bouncycastle.crypto.fpe.FPEFF1Engine; +import org.bouncycastle.crypto.fpe.FPEFF3_1Engine; +import org.bouncycastle.crypto.modes.AEADBlockCipher; +import org.bouncycastle.crypto.modes.AEADCipher; +import org.bouncycastle.crypto.modes.CBCBlockCipher; +import org.bouncycastle.crypto.modes.CCMBlockCipher; +import org.bouncycastle.crypto.modes.CFBBlockCipher; +import org.bouncycastle.crypto.modes.CTSBlockCipher; +import org.bouncycastle.crypto.modes.EAXBlockCipher; +import org.bouncycastle.crypto.modes.GCFBBlockCipher; +import org.bouncycastle.crypto.modes.GCMBlockCipher; +import org.bouncycastle.crypto.modes.GCMSIVBlockCipher; +import org.bouncycastle.crypto.modes.GOFBBlockCipher; +import org.bouncycastle.crypto.modes.KCCMBlockCipher; +import org.bouncycastle.crypto.modes.KCTRBlockCipher; +import org.bouncycastle.crypto.modes.KGCMBlockCipher; +import org.bouncycastle.crypto.modes.OCBBlockCipher; +import org.bouncycastle.crypto.modes.OFBBlockCipher; +import org.bouncycastle.crypto.modes.OpenPGPCFBBlockCipher; +import org.bouncycastle.crypto.modes.PGPCFBBlockCipher; +import org.bouncycastle.crypto.modes.SICBlockCipher; +import org.bouncycastle.crypto.paddings.BlockCipherPadding; +import org.bouncycastle.crypto.paddings.ISO10126d2Padding; +import org.bouncycastle.crypto.paddings.ISO7816d4Padding; +import org.bouncycastle.crypto.paddings.PKCS7Padding; +import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; +import org.bouncycastle.crypto.paddings.TBCPadding; +import org.bouncycastle.crypto.paddings.X923Padding; +import org.bouncycastle.crypto.paddings.ZeroBytePadding; +import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.FPEParameters; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.crypto.params.ParametersWithSBox; +import org.bouncycastle.crypto.params.RC2Parameters; +import org.bouncycastle.crypto.params.RC5Parameters; +import org.bouncycastle.internal.asn1.cms.GCMParameters; +import org.bouncycastle.jcajce.PBKDF1Key; +import org.bouncycastle.jcajce.PBKDF1KeyWithParameters; +import org.bouncycastle.jcajce.PBKDF2Key; +import org.bouncycastle.jcajce.PBKDF2KeyWithParameters; +import org.bouncycastle.jcajce.PKCS12Key; +import org.bouncycastle.jcajce.PKCS12KeyWithParameters; +import org.bouncycastle.jcajce.spec.AEADParameterSpec; +import org.bouncycastle.jcajce.spec.FPEParameterSpec; +import org.bouncycastle.jcajce.spec.GOST28147ParameterSpec; +import org.bouncycastle.jcajce.spec.RepeatedSecretKeySpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +public class BaseBlockCipher + extends BaseWrapCipher + implements PBE +{ + private static final int BUF_SIZE = 512; + + // + // specs we can handle. + // + private static final Class[] availableSpecs = + { + RC2ParameterSpec.class, + RC5ParameterSpec.class, + GcmSpecUtil.gcmSpecClass, + GOST28147ParameterSpec.class, + IvParameterSpec.class, + PBEParameterSpec.class + }; + + private BlockCipher baseEngine; + private BlockCipherProvider engineProvider; + private GenericBlockCipher cipher; + private ParametersWithIV ivParam; + private AEADParameters aeadParams; + + private int keySizeInBits; + private int scheme = -1; + private int digest; + + private int ivLength = 0; + + private boolean padded; + private boolean fixedIv = true; + private PBEParameterSpec pbeSpec = null; + private String pbeAlgorithm = null; + + private String modeName = null; + + protected BaseBlockCipher( + BlockCipher engine) + { + baseEngine = engine; + + cipher = new BufferedGenericBlockCipher(engine); + } + + protected BaseBlockCipher( + BlockCipher engine, + int scheme, + int digest, + int keySizeInBits, + int ivLength) + { + baseEngine = engine; + + this.scheme = scheme; + this.digest = digest; + this.keySizeInBits = keySizeInBits; + this.ivLength = ivLength; + + cipher = new BufferedGenericBlockCipher(engine); + } + + protected BaseBlockCipher( + BlockCipherProvider provider) + { + baseEngine = provider.get(); + engineProvider = provider; + + cipher = new BufferedGenericBlockCipher(provider.get()); + } + + protected BaseBlockCipher( + int keySizeInBits, + BlockCipherProvider provider) + { + baseEngine = provider.get(); + engineProvider = provider; + this.keySizeInBits = keySizeInBits; + + cipher = new BufferedGenericBlockCipher(provider.get()); + } + + protected BaseBlockCipher( + AEADBlockCipher engine) + { + this(0, engine); + } + + protected BaseBlockCipher( + int keySizeInBits, + AEADBlockCipher engine) + { + this.keySizeInBits = keySizeInBits; + this.baseEngine = engine.getUnderlyingCipher(); + if (engine.getAlgorithmName().indexOf("GCM") >= 0) + { + this.ivLength = 12; + } + else + { + this.ivLength = baseEngine.getBlockSize(); + } + this.cipher = new AEADGenericBlockCipher(engine); + } + + protected BaseBlockCipher( + AEADCipher engine, + boolean fixedIv, + int ivLength) + { + this.baseEngine = null; + this.fixedIv = fixedIv; + this.ivLength = ivLength; + this.cipher = new AEADGenericBlockCipher(engine); + } + + protected BaseBlockCipher( + AEADBlockCipher engine, + boolean fixedIv, + int ivLength) + { + this(0, engine, fixedIv, ivLength); + } + + protected BaseBlockCipher( + int keySizeInBits, + AEADBlockCipher engine, + boolean fixedIv, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + this.baseEngine = engine.getUnderlyingCipher(); + this.fixedIv = fixedIv; + this.ivLength = ivLength; + this.cipher = new AEADGenericBlockCipher(engine); + } + + protected BaseBlockCipher( + org.bouncycastle.crypto.BlockCipher engine, + int ivLength) + { + this(engine, true, ivLength); + } + + protected BaseBlockCipher( + int keySizeInBits, + org.bouncycastle.crypto.BlockCipher engine, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + baseEngine = engine; + + this.fixedIv = true; + this.cipher = new BufferedGenericBlockCipher(engine); + this.ivLength = ivLength / 8; + } + + protected BaseBlockCipher( + org.bouncycastle.crypto.BlockCipher engine, + boolean fixedIv, + int ivLength) + { + baseEngine = engine; + + this.fixedIv = fixedIv; + this.cipher = new BufferedGenericBlockCipher(engine); + this.ivLength = ivLength / 8; + } + + protected BaseBlockCipher( + BufferedBlockCipher engine, + int ivLength) + { + this(engine, true, ivLength); + } + + protected BaseBlockCipher( + int keySizeInBits, + BufferedBlockCipher engine, + int ivLength) + { + this.keySizeInBits = keySizeInBits; + baseEngine = engine.getUnderlyingCipher(); + + this.cipher = new BufferedGenericBlockCipher(engine); + this.fixedIv = true; + this.ivLength = ivLength / 8; + } + + protected BaseBlockCipher( + BufferedBlockCipher engine, + boolean fixedIv, + int ivLength) + { + baseEngine = engine.getUnderlyingCipher(); + + this.cipher = new BufferedGenericBlockCipher(engine); + this.fixedIv = fixedIv; + this.ivLength = ivLength / 8; + } + + protected int engineGetBlockSize() + { + if (baseEngine == null) + { + return -1; + } + return baseEngine.getBlockSize(); + } + + protected byte[] engineGetIV() + { + if (aeadParams != null) + { + return aeadParams.getNonce(); + } + + return (ivParam != null) ? ivParam.getIV() : null; + } + + protected int engineGetKeySize( + Key key) + { + return key.getEncoded().length * 8; + } + + protected int engineGetOutputSize( + int inputLen) + { + return cipher.getOutputSize(inputLen); + } + + protected AlgorithmParameters engineGetParameters() + { + if (engineParams == null) + { + if (pbeSpec != null) + { + try + { + engineParams = createParametersInstance(pbeAlgorithm); + engineParams.init(pbeSpec); + } + catch (Exception e) + { + return null; + } + } + else if (aeadParams != null) + { + // CHACHA20-Poly1305 + if (baseEngine == null) + { + try + { + engineParams = createParametersInstance(PKCSObjectIdentifiers.id_alg_AEADChaCha20Poly1305.getId()); + engineParams.init(new DEROctetString(aeadParams.getNonce()).getEncoded()); + } + catch (Exception e) + { + throw new RuntimeException(e.toString()); + } + } + else + { + try + { + engineParams = createParametersInstance("GCM"); + engineParams.init(new GCMParameters(aeadParams.getNonce(), aeadParams.getMacSize() / 8).getEncoded()); + } + catch (Exception e) + { + throw new RuntimeException(e.toString()); + } + } + } + else if (ivParam != null) + { + String name = cipher.getUnderlyingCipher().getAlgorithmName(); + + if (name.indexOf('/') >= 0) + { + name = name.substring(0, name.indexOf('/')); + } + + try + { + engineParams = createParametersInstance(name); + engineParams.init(new IvParameterSpec(ivParam.getIV())); + } + catch (Exception e) + { + throw new RuntimeException(e.toString()); + } + } + } + + return engineParams; + } + + protected void engineSetMode( + String mode) + throws NoSuchAlgorithmException + { + if (baseEngine == null) + { + throw new NoSuchAlgorithmException("no mode supported for this algorithm"); + } + modeName = Strings.toUpperCase(mode); + + if (modeName.equals("ECB")) + { + ivLength = 0; + cipher = new BufferedGenericBlockCipher(baseEngine); + } + else if (modeName.equals("CBC")) + { + ivLength = baseEngine.getBlockSize(); + cipher = new BufferedGenericBlockCipher( + CBCBlockCipher.newInstance(baseEngine)); + } + else if (modeName.startsWith("OFB")) + { + ivLength = baseEngine.getBlockSize(); + if (modeName.length() != 3) + { + int wordSize = Integer.parseInt(modeName.substring(3)); + + cipher = new BufferedGenericBlockCipher( + new OFBBlockCipher(baseEngine, wordSize)); + } + else + { + cipher = new BufferedGenericBlockCipher( + new OFBBlockCipher(baseEngine, 8 * baseEngine.getBlockSize())); + } + } + else if (modeName.startsWith("CFB")) + { + ivLength = baseEngine.getBlockSize(); + if (modeName.length() != 3) + { + int wordSize = Integer.parseInt(modeName.substring(3)); + + cipher = new BufferedGenericBlockCipher( + CFBBlockCipher.newInstance(baseEngine, wordSize)); + } + else + { + cipher = new BufferedGenericBlockCipher( + CFBBlockCipher.newInstance(baseEngine, 8 * baseEngine.getBlockSize())); + } + } + else if (modeName.startsWith("PGPCFB")) + { + boolean inlineIV = modeName.equals("PGPCFBWITHIV"); + + if (!inlineIV && modeName.length() != 6) + { + throw new NoSuchAlgorithmException("no mode support for " + modeName); + } + + ivLength = baseEngine.getBlockSize(); + cipher = new BufferedGenericBlockCipher( + new PGPCFBBlockCipher(baseEngine, inlineIV)); + } + else if (modeName.equals("OPENPGPCFB")) + { + ivLength = 0; + cipher = new BufferedGenericBlockCipher( + new OpenPGPCFBBlockCipher(baseEngine)); + } + else if (modeName.equals("FF1")) + { + ivLength = 0; + cipher = new BufferedFPEBlockCipher( + new FPEFF1Engine(baseEngine)); + } + else if (modeName.equals("FF3-1")) + { + ivLength = 0; + cipher = new BufferedFPEBlockCipher( + new FPEFF3_1Engine(baseEngine)); + } + else if (modeName.equals("SIC")) + { + ivLength = baseEngine.getBlockSize(); + if (ivLength < 16) + { + throw new IllegalArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); + } + fixedIv = false; + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + SICBlockCipher.newInstance(baseEngine))); + } + else if (modeName.equals("CTR")) + { + ivLength = baseEngine.getBlockSize(); + fixedIv = false; + if (baseEngine instanceof DSTU7624Engine) + { + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + new KCTRBlockCipher(baseEngine))); + } + else + { + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + SICBlockCipher.newInstance(baseEngine))); + } + } + else if (modeName.equals("GOFB")) + { + ivLength = baseEngine.getBlockSize(); + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + new GOFBBlockCipher(baseEngine))); + } + else if (modeName.equals("GCFB")) + { + ivLength = baseEngine.getBlockSize(); + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher( + new GCFBBlockCipher(baseEngine))); + } + else if (modeName.equals("CTS")) + { + ivLength = baseEngine.getBlockSize(); + cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(CBCBlockCipher.newInstance(baseEngine))); + } + else if (modeName.equals("CCM")) + { + ivLength = 12; // CCM nonce 7..13 bytes + if (baseEngine instanceof DSTU7624Engine) + { + cipher = new AEADGenericBlockCipher(new KCCMBlockCipher(baseEngine)); + } + else + { + cipher = new AEADGenericBlockCipher(CCMBlockCipher.newInstance(baseEngine)); + } + } + else if (modeName.equals("OCB")) + { + if (engineProvider != null) + { + /* + * RFC 7253 4.2. Nonce is a string of no more than 120 bits + */ + ivLength = 15; + cipher = new AEADGenericBlockCipher(new OCBBlockCipher(baseEngine, engineProvider.get())); + } + else + { + throw new NoSuchAlgorithmException("can't support mode " + mode); + } + } + else if (modeName.equals("EAX")) + { + ivLength = baseEngine.getBlockSize(); + cipher = new AEADGenericBlockCipher(new EAXBlockCipher(baseEngine)); + } + else if (modeName.equals("GCM-SIV")) + { + ivLength = 12; + cipher = new AEADGenericBlockCipher(new GCMSIVBlockCipher(baseEngine)); + } + else if (modeName.equals("GCM")) + { + if (baseEngine instanceof DSTU7624Engine) + { + ivLength = baseEngine.getBlockSize(); + cipher = new AEADGenericBlockCipher(new KGCMBlockCipher(baseEngine)); + } + else + { + ivLength = 12; + cipher = new AEADGenericBlockCipher(GCMBlockCipher.newInstance(baseEngine)); + } + } + else + { + throw new NoSuchAlgorithmException("can't support mode " + mode); + } + } + + protected void engineSetPadding( + String padding) + throws NoSuchPaddingException + { + if (baseEngine == null) + { + throw new NoSuchPaddingException("no padding supported for this algorithm"); + } + + String paddingName = Strings.toUpperCase(padding); + + if (paddingName.equals("NOPADDING")) + { + if (cipher.wrapOnNoPadding()) + { + cipher = new BufferedGenericBlockCipher(new DefaultBufferedBlockCipher(cipher.getUnderlyingCipher())); + } + } + else if (paddingName.equals("WITHCTS") || paddingName.equals("CTSPADDING") || paddingName.equals("CS3PADDING")) + { + cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(cipher.getUnderlyingCipher())); + } + else + { + padded = true; + + if (isAEADModeName(modeName)) + { + throw new NoSuchPaddingException("Only NoPadding can be used with AEAD modes."); + } + else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) + { + cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher()); + } + else if (paddingName.equals("ZEROBYTEPADDING")) + { + cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ZeroBytePadding()); + } + else if (paddingName.equals("ISO10126PADDING") || paddingName.equals("ISO10126-2PADDING")) + { + cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO10126d2Padding()); + } + else if (paddingName.equals("X9.23PADDING") || paddingName.equals("X923PADDING")) + { + cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new X923Padding()); + } + else if (paddingName.equals("ISO7816-4PADDING") || paddingName.equals("ISO9797-1PADDING")) + { + cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO7816d4Padding()); + } + else if (paddingName.equals("TBCPADDING")) + { + cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new TBCPadding()); + } + else + { + throw new NoSuchPaddingException("Padding " + padding + " unknown."); + } + } + } + + protected void engineInit( + int opmode, + Key key, + final AlgorithmParameterSpec paramSpec, + SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException + { + CipherParameters param; + + this.pbeSpec = null; + this.pbeAlgorithm = null; + this.engineParams = null; + this.aeadParams = null; + + // + // basic key check + // + if (!(key instanceof SecretKey)) + { + throw new InvalidKeyException("Key for algorithm " + ((key != null) ? key.getAlgorithm() : null) + " not suitable for symmetric enryption."); + } + + // + // for RC5-64 we must have some default parameters + // + if (paramSpec == null && (baseEngine != null && baseEngine.getAlgorithmName().startsWith("RC5-64"))) + { + throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in."); + } + + // + // a note on iv's - if ivLength is zero the IV gets ignored (we don't use it). + // + if (scheme == PKCS12 || key instanceof PKCS12Key) + { + SecretKey k; + try + { + k = (SecretKey)key; + } + catch (Exception e) + { + throw new InvalidKeyException("PKCS12 requires a SecretKey/PBEKey"); + } + + if (paramSpec instanceof PBEParameterSpec) + { + pbeSpec = (PBEParameterSpec)paramSpec; + } + + if (k instanceof PBEKey && pbeSpec == null) + { + PBEKey pbeKey = (PBEKey)k; + if (pbeKey.getSalt() == null) + { + throw new InvalidAlgorithmParameterException("PBEKey requires parameters to specify salt"); + } + pbeSpec = new PBEParameterSpec(pbeKey.getSalt(), pbeKey.getIterationCount()); + } + + if (pbeSpec == null && !(k instanceof PBEKey)) + { + throw new InvalidKeyException("Algorithm requires a PBE key"); + } + + if (key instanceof BCPBEKey) + { + // PKCS#12 sets an IV, if we get a key that doesn't have ParametersWithIV we need to reject it. If the + // key has no parameters it means it's an old-school JCE PBE Key - we use getEncoded() on it. + CipherParameters pbeKeyParam = ((BCPBEKey)key).getParam(); + if (pbeKeyParam instanceof ParametersWithIV) + { + param = pbeKeyParam; + } + else if (pbeKeyParam == null) + { + param = PBE.Util.makePBEParameters(k.getEncoded(), PKCS12, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName()); + } + else + { + throw new InvalidKeyException("Algorithm requires a PBE key suitable for PKCS12"); + } + } + else + { + param = PBE.Util.makePBEParameters(k.getEncoded(), PKCS12, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName()); + } + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } + else if (key instanceof PBKDF1Key) + { + PBKDF1Key k = (PBKDF1Key)key; + + if (paramSpec instanceof PBEParameterSpec) + { + pbeSpec = (PBEParameterSpec)paramSpec; + } + if (k instanceof PBKDF1KeyWithParameters && pbeSpec == null) + { + pbeSpec = new PBEParameterSpec(((PBKDF1KeyWithParameters)k).getSalt(), ((PBKDF1KeyWithParameters)k).getIterationCount()); + } + + param = PBE.Util.makePBEParameters(k.getEncoded(), PKCS5S1, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName()); + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } + else if (key instanceof PBKDF2Key) + { + PBKDF2Key k = (PBKDF2Key)key; + + if (paramSpec instanceof PBEParameterSpec) + { + pbeSpec = (PBEParameterSpec)paramSpec; + } + if (k instanceof PBKDF2KeyWithParameters && pbeSpec == null) + { + pbeSpec = new PBEParameterSpec(((PBKDF2KeyWithParameters)k).getSalt(), ((PBKDF2KeyWithParameters)k).getIterationCount()); + } + + param = PBE.Util.makePBEParameters(k.getEncoded(), PKCS5S2, PBE.SHA512, keySizeInBits, 0, pbeSpec, cipher.getAlgorithmName()); + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } + else if (key instanceof BCPBEKey) + { + BCPBEKey k = (BCPBEKey)key; + + if (k.getOID() != null) + { + pbeAlgorithm = k.getOID().getId(); + } + else + { + pbeAlgorithm = k.getAlgorithm(); + } + + if (k.getParam() != null) + { + param = adjustParameters(paramSpec, k.getParam()); + } + else if (paramSpec instanceof PBEParameterSpec) + { + pbeSpec = (PBEParameterSpec)paramSpec; + param = PBE.Util.makePBEParameters(k, paramSpec, cipher.getUnderlyingCipher().getAlgorithmName()); + } + else + { + throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); + } + + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } + else if (key instanceof PBEKey) + { + PBEKey k = (PBEKey)key; + pbeSpec = (PBEParameterSpec)paramSpec; + if (k instanceof PKCS12KeyWithParameters && pbeSpec == null) + { + pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount()); + } + + param = PBE.Util.makePBEParameters(k.getEncoded(), scheme, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName()); + if (param instanceof ParametersWithIV) + { + ivParam = (ParametersWithIV)param; + } + } + else if (!(key instanceof RepeatedSecretKeySpec)) + { + if (scheme == PKCS5S1 || scheme == PKCS5S1_UTF8 || scheme == PKCS5S2 || scheme == PKCS5S2_UTF8) + { + throw new InvalidKeyException("Algorithm requires a PBE key"); + } + param = new KeyParameter(key.getEncoded()); + } + else + { + param = null; + } + + AlgorithmParameterSpec params; + params = paramSpec; + + if (params instanceof AEADParameterSpec) + { + if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) + { + throw new InvalidAlgorithmParameterException("AEADParameterSpec can only be used with AEAD modes."); + } + + AEADParameterSpec aeadSpec = (AEADParameterSpec)params; + + KeyParameter keyParam; + if (param instanceof ParametersWithIV) + { + keyParam = (KeyParameter)((ParametersWithIV)param).getParameters(); + } + else + { + keyParam = (KeyParameter)param; + } + param = aeadParams = new AEADParameters(keyParam, aeadSpec.getMacSizeInBits(), aeadSpec.getNonce(), aeadSpec.getAssociatedData()); + } + else if (params instanceof IvParameterSpec) + { + if (ivLength != 0) + { + IvParameterSpec p = (IvParameterSpec)params; + + if (p.getIV().length != ivLength && !(cipher instanceof AEADGenericBlockCipher) && fixedIv) + { + throw new InvalidAlgorithmParameterException("IV must be " + ivLength + " bytes long."); + } + + if (param instanceof ParametersWithIV) + { + param = new ParametersWithIV(((ParametersWithIV)param).getParameters(), p.getIV()); + } + else + { + param = new ParametersWithIV(param, p.getIV()); + } + ivParam = (ParametersWithIV)param; + } + else + { + if (modeName != null && modeName.equals("ECB")) + { + throw new InvalidAlgorithmParameterException("ECB mode does not use an IV"); + } + } + } + else if (params instanceof GOST28147ParameterSpec) + { + GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; + + param = new ParametersWithSBox( + new KeyParameter(key.getEncoded()), ((GOST28147ParameterSpec)params).getSBox()); + + if (gost28147Param.getIV() != null && ivLength != 0) + { + if (param instanceof ParametersWithIV) + { + param = new ParametersWithIV(((ParametersWithIV)param).getParameters(), gost28147Param.getIV()); + } + else + { + param = new ParametersWithIV(param, gost28147Param.getIV()); + } + ivParam = (ParametersWithIV)param; + } + } + else if (params instanceof RC2ParameterSpec) + { + RC2ParameterSpec rc2Param = (RC2ParameterSpec)params; + + param = new RC2Parameters(key.getEncoded(), ((RC2ParameterSpec)params).getEffectiveKeyBits()); + + if (rc2Param.getIV() != null && ivLength != 0) + { + if (param instanceof ParametersWithIV) + { + param = new ParametersWithIV(((ParametersWithIV)param).getParameters(), rc2Param.getIV()); + } + else + { + param = new ParametersWithIV(param, rc2Param.getIV()); + } + ivParam = (ParametersWithIV)param; + } + } + else if (params instanceof RC5ParameterSpec) + { + RC5ParameterSpec rc5Param = (RC5ParameterSpec)params; + + param = new RC5Parameters(key.getEncoded(), ((RC5ParameterSpec)params).getRounds()); + if (baseEngine.getAlgorithmName().startsWith("RC5")) + { + if (baseEngine.getAlgorithmName().equals("RC5-32")) + { + if (rc5Param.getWordSize() != 32) + { + throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 32 not " + rc5Param.getWordSize() + "."); + } + } + else if (baseEngine.getAlgorithmName().equals("RC5-64")) + { + if (rc5Param.getWordSize() != 64) + { + throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 64 not " + rc5Param.getWordSize() + "."); + } + } + } + else + { + throw new InvalidAlgorithmParameterException("RC5 parameters passed to a cipher that is not RC5."); + } + if ((rc5Param.getIV() != null) && (ivLength != 0)) + { + if (param instanceof ParametersWithIV) + { + param = new ParametersWithIV(((ParametersWithIV)param).getParameters(), rc5Param.getIV()); + } + else + { + param = new ParametersWithIV(param, rc5Param.getIV()); + } + ivParam = (ParametersWithIV)param; + } + } + else if (params instanceof FPEParameterSpec) + { + FPEParameterSpec spec = (FPEParameterSpec)params; + + param = new FPEParameters((KeyParameter)param, spec.getRadixConverter(), spec.getTweak(), spec.isUsingInverseFunction()); + } + else if (GcmSpecUtil.isGcmSpec(params)) + { + if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) + { + throw new InvalidAlgorithmParameterException("GCMParameterSpec can only be used with AEAD modes."); + } + + final KeyParameter keyParam; + if (param instanceof ParametersWithIV) + { + keyParam = (KeyParameter)((ParametersWithIV)param).getParameters(); + } + else + { + keyParam = (KeyParameter)param; + } + + param = aeadParams = GcmSpecUtil.extractAeadParameters(keyParam, params); + } + else if (params != null && !(params instanceof PBEParameterSpec)) + { + throw new InvalidAlgorithmParameterException("unknown parameter type."); + } + + if ((ivLength != 0) && !(param instanceof ParametersWithIV) && !(param instanceof AEADParameters)) + { + SecureRandom ivRandom = random; + + if (ivRandom == null) + { + ivRandom = CryptoServicesRegistrar.getSecureRandom(); + } + + if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE)) + { + byte[] iv = new byte[ivLength]; + + ivRandom.nextBytes(iv); + param = new ParametersWithIV(param, iv); + ivParam = (ParametersWithIV)param; + } + else if (cipher.getUnderlyingCipher().getAlgorithmName().indexOf("PGPCFB") < 0) + { + throw new InvalidAlgorithmParameterException("no IV set when one expected"); + } + } + + + if (random != null && padded) + { + param = new ParametersWithRandom(param, random); + } + + try + { + switch (opmode) + { + case Cipher.ENCRYPT_MODE: + case Cipher.WRAP_MODE: + cipher.init(true, param); + break; + case Cipher.DECRYPT_MODE: + case Cipher.UNWRAP_MODE: + cipher.init(false, param); + break; + default: + throw new InvalidParameterException("unknown opmode " + opmode + " passed"); + } + + if (cipher instanceof AEADGenericBlockCipher && aeadParams == null) + { + AEADCipher aeadCipher = ((AEADGenericBlockCipher)cipher).cipher; + + aeadParams = new AEADParameters((KeyParameter)ivParam.getParameters(), aeadCipher.getMac().length * 8, ivParam.getIV()); + } + } + catch (IllegalArgumentException e) + { + throw new InvalidAlgorithmParameterException(e.getMessage(), e); + } + catch (Exception e) + { + throw new InvalidKeyOrParametersException(e.getMessage(), e); + } + } + + private CipherParameters adjustParameters(AlgorithmParameterSpec params, CipherParameters param) + { + CipherParameters key; + + if (param instanceof ParametersWithIV) + { + key = ((ParametersWithIV)param).getParameters(); + if (params instanceof IvParameterSpec) + { + IvParameterSpec iv = (IvParameterSpec)params; + + ivParam = new ParametersWithIV(key, iv.getIV()); + param = ivParam; + } + else if (params instanceof GOST28147ParameterSpec) + { + // need to pick up IV and SBox. + GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; + + param = new ParametersWithSBox(param, gost28147Param.getSBox()); + + if (gost28147Param.getIV() != null && ivLength != 0) + { + ivParam = new ParametersWithIV(key, gost28147Param.getIV()); + param = ivParam; + } + } + } + else + { + if (params instanceof IvParameterSpec) + { + IvParameterSpec iv = (IvParameterSpec)params; + + ivParam = new ParametersWithIV(param, iv.getIV()); + param = ivParam; + } + else if (params instanceof GOST28147ParameterSpec) + { + // need to pick up IV and SBox. + GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; + + param = new ParametersWithSBox(param, gost28147Param.getSBox()); + + if (gost28147Param.getIV() != null && ivLength != 0) + { + param = new ParametersWithIV(param, gost28147Param.getIV()); + } + } + } + return param; + } + + protected void engineInit( + int opmode, + Key key, + AlgorithmParameters params, + SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException + { + AlgorithmParameterSpec paramSpec = null; + + if (params != null) + { + paramSpec = SpecUtil.extractSpec(params, availableSpecs); + + if (paramSpec == null) + { + throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString()); + } + } + + engineInit(opmode, key, paramSpec, random); + + engineParams = params; + } + + protected void engineInit( + int opmode, + Key key, + SecureRandom random) + throws InvalidKeyException + { + try + { + engineInit(opmode, key, (AlgorithmParameterSpec)null, random); + } + catch (InvalidAlgorithmParameterException e) + { + throw new InvalidKeyException(e.getMessage()); + } + } + + protected void engineUpdateAAD(byte[] input, int offset, int length) + { + cipher.updateAAD(input, offset, length); + } + + protected void engineUpdateAAD(ByteBuffer src) + { + int remaining = src.remaining(); + if (remaining < 1) + { + // No data to update + } + else if (src.hasArray()) + { + engineUpdateAAD(src.array(), src.arrayOffset() + src.position(), remaining); + src.position(src.limit()); + } + else if (remaining <= BUF_SIZE) + { + byte[] data = new byte[remaining]; + src.get(data); + engineUpdateAAD(data, 0, data.length); + Arrays.fill(data, (byte)0); + } + else + { + byte[] data = new byte[BUF_SIZE]; + do + { + int length = Math.min(data.length, remaining); + src.get(data, 0, length); + engineUpdateAAD(data, 0, length); + remaining -= length; + } + while (remaining > 0); + Arrays.fill(data, (byte)0); + } + } + + protected byte[] engineUpdate( + byte[] input, + int inputOffset, + int inputLen) + { + int length = cipher.getUpdateOutputSize(inputLen); + + if (length > 0) + { + byte[] out = new byte[length]; + + int len = cipher.processBytes(input, inputOffset, inputLen, out, 0); + + if (len == 0) + { + return null; + } + else if (len != out.length) + { + byte[] tmp = new byte[len]; + + System.arraycopy(out, 0, tmp, 0, len); + + return tmp; + } + + return out; + } + + cipher.processBytes(input, inputOffset, inputLen, null, 0); + + return null; + } + + protected int engineUpdate( + byte[] input, + int inputOffset, + int inputLen, + byte[] output, + int outputOffset) + throws ShortBufferException + { + if (outputOffset + cipher.getUpdateOutputSize(inputLen) > output.length) + { + throw new ShortBufferException("output buffer too short for input."); + } + + try + { + return cipher.processBytes(input, inputOffset, inputLen, output, outputOffset); + } + catch (DataLengthException e) + { + // should never occur + throw new IllegalStateException(e.toString()); + } + } + + protected byte[] engineDoFinal( + byte[] input, + int inputOffset, + int inputLen) + throws IllegalBlockSizeException, BadPaddingException + { + int len = 0; + byte[] tmp = new byte[engineGetOutputSize(inputLen)]; + + if (inputLen != 0) + { + len = cipher.processBytes(input, inputOffset, inputLen, tmp, 0); + } + + try + { + len += cipher.doFinal(tmp, len); + } + catch (DataLengthException e) + { + throw new IllegalBlockSizeException(e.getMessage()); + } + + if (len == tmp.length) + { + return tmp; + } + + if (len > tmp.length) + { + throw new IllegalBlockSizeException("internal buffer overflow"); + } + + byte[] out = new byte[len]; + + System.arraycopy(tmp, 0, out, 0, len); + + return out; + } + + protected int engineDoFinal( + byte[] input, + int inputOffset, + int inputLen, + byte[] output, + int outputOffset) + throws IllegalBlockSizeException, BadPaddingException, ShortBufferException + { + int len = 0; + + if (outputOffset + engineGetOutputSize(inputLen) > output.length) + { + throw new ShortBufferException("output buffer too short for input."); + } + + try + { + if (inputLen != 0) + { + len = cipher.processBytes(input, inputOffset, inputLen, output, outputOffset); + } + + return (len + cipher.doFinal(output, outputOffset + len)); + } + catch (OutputLengthException e) + { + throw new IllegalBlockSizeException(e.getMessage()); + } + catch (DataLengthException e) + { + throw new IllegalBlockSizeException(e.getMessage()); + } + } + + private boolean isAEADModeName( + String modeName) + { + return "CCM".equals(modeName) || "EAX".equals(modeName) || "GCM".equals(modeName) || "GCM-SIV".equals(modeName) || "OCB".equals(modeName); + } + + /* + * The ciphers that inherit from us. + */ + + static private interface GenericBlockCipher + { + public void init(boolean forEncryption, CipherParameters params) + throws IllegalArgumentException; + + public boolean wrapOnNoPadding(); + + public String getAlgorithmName(); + + public org.bouncycastle.crypto.BlockCipher getUnderlyingCipher(); + + public int getOutputSize(int len); + + public int getUpdateOutputSize(int len); + + public void updateAAD(byte[] input, int offset, int length); + + public int processByte(byte in, byte[] out, int outOff) + throws DataLengthException; + + public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) + throws DataLengthException; + + public int doFinal(byte[] out, int outOff) + throws IllegalStateException, + BadPaddingException; + } + + private static class BufferedGenericBlockCipher + implements GenericBlockCipher + { + private BufferedBlockCipher cipher; + + BufferedGenericBlockCipher(BufferedBlockCipher cipher) + { + this.cipher = cipher; + } + + BufferedGenericBlockCipher(org.bouncycastle.crypto.BlockCipher cipher) + { + this(cipher, new PKCS7Padding()); + } + + BufferedGenericBlockCipher(org.bouncycastle.crypto.BlockCipher cipher, BlockCipherPadding padding) + { + this.cipher = new PaddedBufferedBlockCipher(cipher, padding); + } + + public void init(boolean forEncryption, CipherParameters params) + throws IllegalArgumentException + { + cipher.init(forEncryption, params); + } + + public boolean wrapOnNoPadding() + { + return !(cipher instanceof CTSBlockCipher); + } + + public String getAlgorithmName() + { + return cipher.getUnderlyingCipher().getAlgorithmName(); + } + + public org.bouncycastle.crypto.BlockCipher getUnderlyingCipher() + { + return cipher.getUnderlyingCipher(); + } + + public int getOutputSize(int len) + { + return cipher.getOutputSize(len); + } + + public int getUpdateOutputSize(int len) + { + return cipher.getUpdateOutputSize(len); + } + + public void updateAAD(byte[] input, int offset, int length) + { + throw new UnsupportedOperationException("AAD is not supported in the current mode."); + } + + public int processByte(byte in, byte[] out, int outOff) + throws DataLengthException + { + return cipher.processByte(in, out, outOff); + } + + public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) + throws DataLengthException + { + return cipher.processBytes(in, inOff, len, out, outOff); + } + + public int doFinal(byte[] out, int outOff) + throws IllegalStateException, BadPaddingException + { + try + { + return cipher.doFinal(out, outOff); + } + catch (InvalidCipherTextException e) + { + throw new BadPaddingException(e.getMessage()); + } + } + } + + private static class BufferedFPEBlockCipher + implements GenericBlockCipher + { + private FPEEngine cipher; + private ErasableOutputStream eOut = new ErasableOutputStream(); + + BufferedFPEBlockCipher(FPEEngine cipher) + { + this.cipher = cipher; + } + + public void init(boolean forEncryption, CipherParameters params) + throws IllegalArgumentException + { + cipher.init(forEncryption, params); + } + + public boolean wrapOnNoPadding() + { + return false; + } + + public String getAlgorithmName() + { + return cipher.getAlgorithmName(); + } + + public org.bouncycastle.crypto.BlockCipher getUnderlyingCipher() + { + throw new IllegalStateException("not applicable for FPE"); + } + + public int getOutputSize(int len) + { + return eOut.size() + len; + } + + public int getUpdateOutputSize(int len) + { + return 0; + } + + public void updateAAD(byte[] input, int offset, int length) + { + throw new UnsupportedOperationException("AAD is not supported in the current mode."); + } + + public int processByte(byte in, byte[] out, int outOff) + throws DataLengthException + { + eOut.write(in); + + return 0; + } + + public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) + throws DataLengthException + { + eOut.write(in, inOff, len); + + return 0; + } + + public int doFinal(byte[] out, int outOff) + throws IllegalStateException, BadPaddingException + { + try + { + return cipher.processBlock(eOut.getBuf(), 0, eOut.size(), out, outOff); + } + finally + { + eOut.erase(); + } + } + } + + private static class AEADGenericBlockCipher + implements GenericBlockCipher + { + private static final Constructor aeadBadTagConstructor; + + static + { + Class aeadBadTagClass = ClassUtil.loadClass(BaseBlockCipher.class, "javax.crypto.AEADBadTagException"); + if (aeadBadTagClass != null) + { + aeadBadTagConstructor = findExceptionConstructor(aeadBadTagClass); + } + else + { + aeadBadTagConstructor = null; + } + } + + private static Constructor findExceptionConstructor(Class clazz) + { + try + { + return clazz.getConstructor(new Class[]{String.class}); + } + catch (Exception e) + { + return null; + } + } + + private AEADCipher cipher; + + AEADGenericBlockCipher(AEADCipher cipher) + { + this.cipher = cipher; + } + + public void init(boolean forEncryption, CipherParameters params) + throws IllegalArgumentException + { + cipher.init(forEncryption, params); + } + + public String getAlgorithmName() + { + if (cipher instanceof AEADBlockCipher) + { + return ((AEADBlockCipher)cipher).getUnderlyingCipher().getAlgorithmName(); + } + + return cipher.getAlgorithmName(); + } + + public boolean wrapOnNoPadding() + { + return false; + } + + public org.bouncycastle.crypto.BlockCipher getUnderlyingCipher() + { + if (cipher instanceof AEADBlockCipher) + { + return ((AEADBlockCipher)cipher).getUnderlyingCipher(); + } + + return null; + } + + public int getOutputSize(int len) + { + return cipher.getOutputSize(len); + } + + public int getUpdateOutputSize(int len) + { + return cipher.getUpdateOutputSize(len); + } + + public void updateAAD(byte[] input, int offset, int length) + { + cipher.processAADBytes(input, offset, length); + } + + public int processByte(byte in, byte[] out, int outOff) + throws DataLengthException + { + return cipher.processByte(in, out, outOff); + } + + public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) + throws DataLengthException + { + return cipher.processBytes(in, inOff, len, out, outOff); + } + + public int doFinal(byte[] out, int outOff) + throws IllegalStateException, BadPaddingException + { + try + { + return cipher.doFinal(out, outOff); + } + catch (InvalidCipherTextException e) + { + if (aeadBadTagConstructor != null) + { + BadPaddingException aeadBadTag = null; + try + { + aeadBadTag = (BadPaddingException)aeadBadTagConstructor + .newInstance(new Object[]{e.getMessage()}); + } + catch (Exception i) + { + // Shouldn't happen, but fall through to BadPaddingException + } + if (aeadBadTag != null) + { + throw aeadBadTag; + } + } + throw new BadPaddingException(e.getMessage()); + } + } + } +} diff --git a/prov/src/main/jdk1.9/module-info.java b/prov/src/main/jdk1.9/module-info.java index 2b23fe2ed2..d13c8420c1 100644 --- a/prov/src/main/jdk1.9/module-info.java +++ b/prov/src/main/jdk1.9/module-info.java @@ -7,6 +7,9 @@ provides java.security.Provider with org.bouncycastle.jce.provider.BouncyCastleProvider,org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; opens org.bouncycastle.jcajce.provider.asymmetric.edec to java.base; + opens org.bouncycastle.jcajce.provider.asymmetric.mldsa to java.base; + opens org.bouncycastle.jcajce.provider.asymmetric.mlkem to java.base; + opens org.bouncycastle.jcajce.provider.asymmetric.slhdsa to java.base; opens org.bouncycastle.pqc.jcajce.provider.lms to java.base; opens org.bouncycastle.pqc.jcajce.provider.falcon to java.base; opens org.bouncycastle.pqc.jcajce.provider.dilithium to java.base; @@ -42,6 +45,7 @@ exports org.bouncycastle.crypto.encodings; exports org.bouncycastle.crypto.engines; exports org.bouncycastle.crypto.examples; + exports org.bouncycastle.crypto.fpe; exports org.bouncycastle.crypto.generators; exports org.bouncycastle.crypto.hpke; exports org.bouncycastle.crypto.io; @@ -56,6 +60,8 @@ exports org.bouncycastle.crypto.prng; exports org.bouncycastle.crypto.prng.drbg; exports org.bouncycastle.crypto.signers; + exports org.bouncycastle.crypto.threshold; + exports org.bouncycastle.crypto.tls; exports org.bouncycastle.crypto.util; exports org.bouncycastle.i18n; exports org.bouncycastle.i18n.filter; @@ -74,7 +80,10 @@ exports org.bouncycastle.jcajce.provider.asymmetric.elgamal; exports org.bouncycastle.jcajce.provider.asymmetric.gost; exports org.bouncycastle.jcajce.provider.asymmetric.ies; + exports org.bouncycastle.jcajce.provider.asymmetric.mldsa; + exports org.bouncycastle.jcajce.provider.asymmetric.mlkem; exports org.bouncycastle.jcajce.provider.asymmetric.rsa; + exports org.bouncycastle.jcajce.provider.asymmetric.slhdsa; exports org.bouncycastle.jcajce.provider.asymmetric.util; exports org.bouncycastle.jcajce.provider.asymmetric.x509; exports org.bouncycastle.jcajce.provider.config; @@ -112,13 +121,13 @@ exports org.bouncycastle.pqc.crypto.bike; exports org.bouncycastle.pqc.crypto.cmce; exports org.bouncycastle.pqc.crypto.crystals.dilithium; - exports org.bouncycastle.pqc.crypto.crystals.kyber; + exports org.bouncycastle.pqc.crypto.mldsa; + exports org.bouncycastle.pqc.crypto.mlkem; exports org.bouncycastle.pqc.crypto.falcon; exports org.bouncycastle.pqc.crypto.frodo; - exports org.bouncycastle.crypto.fpe; - exports org.bouncycastle.pqc.crypto.gemss; exports org.bouncycastle.pqc.crypto.hqc; exports org.bouncycastle.pqc.crypto.lms; + exports org.bouncycastle.pqc.crypto.mayo; exports org.bouncycastle.pqc.crypto.newhope; exports org.bouncycastle.pqc.crypto.ntru; exports org.bouncycastle.pqc.crypto.ntruprime; @@ -127,6 +136,8 @@ exports org.bouncycastle.pqc.crypto.saber; exports org.bouncycastle.pqc.crypto.sphincs; exports org.bouncycastle.pqc.crypto.sphincsplus; + exports org.bouncycastle.pqc.crypto.slhdsa; + exports org.bouncycastle.pqc.crypto.snova; exports org.bouncycastle.pqc.crypto.util; exports org.bouncycastle.pqc.crypto.xmss; exports org.bouncycastle.pqc.math.ntru; @@ -147,19 +158,17 @@ exports org.bouncycastle.pqc.jcajce.provider.ntruprime; exports org.bouncycastle.pqc.jcajce.provider.newhope; exports org.bouncycastle.pqc.jcajce.provider.picnic; - exports org.bouncycastle.pqc.jcajce.provider.rainbow; exports org.bouncycastle.pqc.jcajce.provider.saber; exports org.bouncycastle.pqc.jcajce.provider.sphincs; exports org.bouncycastle.pqc.jcajce.provider.sphincsplus; exports org.bouncycastle.pqc.jcajce.provider.util; exports org.bouncycastle.pqc.jcajce.provider.xmss; exports org.bouncycastle.pqc.jcajce.spec; + exports org.bouncycastle.pqc.legacy.crypto.gemss; exports org.bouncycastle.pqc.legacy.crypto.gmss; exports org.bouncycastle.pqc.legacy.crypto.gmss.util; exports org.bouncycastle.pqc.legacy.crypto.qtesla; exports org.bouncycastle.pqc.legacy.crypto.mceliece; - exports org.bouncycastle.pqc.legacy.crypto.rainbow; - exports org.bouncycastle.pqc.legacy.crypto.rainbow.util; exports org.bouncycastle.pqc.legacy.math.linearalgebra; exports org.bouncycastle.util; exports org.bouncycastle.util.encoders; diff --git a/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/MLKEM.java b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/MLKEM.java new file mode 100644 index 0000000000..b9013ee4b6 --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/MLKEM.java @@ -0,0 +1,62 @@ +package org.bouncycastle.jcajce.provider.asymmetric; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.MLKEMKeyFactorySpi; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; + +public class MLKEM +{ + private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".mlkem."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.ML-KEM", PREFIX + "MLKEMKeyFactorySpi"); + provider.addAlgorithm("Alg.Alias.KeyFactory.MLKEM", "ML-KEM"); + + addKeyFactoryAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMKeyFactorySpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512, new MLKEMKeyFactorySpi.MLKEM512()); + addKeyFactoryAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMKeyFactorySpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768, new MLKEMKeyFactorySpi.MLKEM768()); + addKeyFactoryAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMKeyFactorySpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024, new MLKEMKeyFactorySpi.MLKEM1024()); + + provider.addAlgorithm("KeyPairGenerator.ML-KEM", PREFIX + "MLKEMKeyPairGeneratorSpi"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.MLKEM", "ML-KEM"); + + addKeyPairGeneratorAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMKeyPairGeneratorSpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addKeyPairGeneratorAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMKeyPairGeneratorSpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addKeyPairGeneratorAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMKeyPairGeneratorSpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + + provider.addAlgorithm("KeyGenerator.ML-KEM", PREFIX + "MLKEMKeyGeneratorSpi"); + + addKeyGeneratorAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMKeyGeneratorSpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addKeyGeneratorAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMKeyGeneratorSpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addKeyGeneratorAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMKeyGeneratorSpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + + AsymmetricKeyInfoConverter keyFact = new MLKEMKeyFactorySpi(); + + provider.addAlgorithm("Cipher.ML-KEM", PREFIX + "MLKEMCipherSpi$Base"); + provider.addAlgorithm("Alg.Alias.Cipher.MLKEM", "ML-KEM"); + + addCipherAlgorithm(provider, "ML-KEM-512", PREFIX + "MLKEMCipherSpi$MLKEM512", NISTObjectIdentifiers.id_alg_ml_kem_512); + addCipherAlgorithm(provider, "ML-KEM-768", PREFIX + "MLKEMCipherSpi$MLKEM768", NISTObjectIdentifiers.id_alg_ml_kem_768); + addCipherAlgorithm(provider, "ML-KEM-1024", PREFIX + "MLKEMCipherSpi$MLKEM1024", NISTObjectIdentifiers.id_alg_ml_kem_1024); + + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_512, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_768, keyFact); + provider.addKeyInfoConverter(NISTObjectIdentifiers.id_alg_ml_kem_1024, keyFact); + + provider.addAlgorithm("KEM.ML-KEM", PREFIX + "MLKEMSpi"); + provider.addAlgorithm("Alg.Alias.KEM." + NISTObjectIdentifiers.id_alg_ml_kem_512, "ML-KEM"); + provider.addAlgorithm("Alg.Alias.KEM." + NISTObjectIdentifiers.id_alg_ml_kem_768, "ML-KEM"); + provider.addAlgorithm("Alg.Alias.KEM." + NISTObjectIdentifiers.id_alg_ml_kem_1024, "ML-KEM"); + } + } +} diff --git a/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMDecapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMDecapsulatorSpi.java new file mode 100644 index 0000000000..30f3e94f99 --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMDecapsulatorSpi.java @@ -0,0 +1,78 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.BCMLKEMPrivateKey; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; + +import javax.crypto.DecapsulateException; +import javax.crypto.KEMSpi; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.security.InvalidKeyException; +import java.util.Arrays; +import java.util.Objects; + +public class MLKEMDecapsulatorSpi + implements KEMSpi.DecapsulatorSpi +{ + BCMLKEMPrivateKey privateKey; + KTSParameterSpec parameterSpec; + MLKEMExtractor kemExt; + + public MLKEMDecapsulatorSpi(BCMLKEMPrivateKey privateKey, KTSParameterSpec parameterSpec) + { + this.privateKey = privateKey; + this.parameterSpec = parameterSpec; + + this.kemExt = new MLKEMExtractor(privateKey.getKeyParams()); + } + + @Override + public SecretKey engineDecapsulate(byte[] encapsulation, int from, int to, String algorithm) throws DecapsulateException + { + Objects.checkFromToIndex(from, to, engineSecretSize()); + Objects.requireNonNull(algorithm, "null algorithm"); + Objects.requireNonNull(encapsulation, "null encapsulation"); + + if (encapsulation.length != engineEncapsulationSize()) + { + throw new DecapsulateException("incorrect encapsulation size"); + } + + // if algorithm is Generic then use parameterSpec to wrap key + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + algorithm.equals("Generic")) + { + algorithm = parameterSpec.getKeyAlgorithmName(); + } + + // check spec algorithm mismatch provided algorithm + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + !parameterSpec.getKeyAlgorithmName().equals(algorithm)) + { + throw new UnsupportedOperationException(parameterSpec.getKeyAlgorithmName() + " does not match " + algorithm); + } + + // Only use KDF when ktsParameterSpec is provided + // Considering any ktsParameterSpec with "Generic" as ktsParameterSpec not provided + boolean useKDF = parameterSpec.getKdfAlgorithm() != null; + + byte[] secret = kemExt.extractSecret(encapsulation); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); + + return new SecretKeySpec(secretKey, algorithm); + } + + @Override + public int engineSecretSize() + { + return parameterSpec.getKeySize() / 8; + } + + @Override + public int engineEncapsulationSize() + { + return kemExt.getEncapsulationLength(); + } +} diff --git a/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMEncapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMEncapsulatorSpi.java new file mode 100644 index 0000000000..4f453da7ae --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMEncapsulatorSpi.java @@ -0,0 +1,89 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.BCMLKEMPublicKey; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; + +import javax.crypto.KEM; +import javax.crypto.KEMSpi; +import javax.crypto.spec.SecretKeySpec; +import java.security.InvalidKeyException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Objects; + +public class MLKEMEncapsulatorSpi + implements KEMSpi.EncapsulatorSpi +{ + private final BCMLKEMPublicKey publicKey; + private final KTSParameterSpec parameterSpec; + private final MLKEMGenerator kemGen; + + public MLKEMEncapsulatorSpi(BCMLKEMPublicKey publicKey, KTSParameterSpec parameterSpec, SecureRandom random) + { + this.publicKey = publicKey; + this.parameterSpec = parameterSpec; + + this.kemGen = new MLKEMGenerator(random); + } + + + @Override + public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm) + { + Objects.checkFromToIndex(from, to, engineSecretSize()); + Objects.requireNonNull(algorithm, "null algorithm"); + + // if algorithm is Generic then use parameterSpec to wrap key + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + algorithm.equals("Generic")) + { + algorithm = parameterSpec.getKeyAlgorithmName(); + } + + // check spec algorithm mismatch provided algorithm + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + !parameterSpec.getKeyAlgorithmName().equals(algorithm)) + { + throw new UnsupportedOperationException(parameterSpec.getKeyAlgorithmName() + " does not match " + algorithm); + } + + // Only use KDF when ktsParameterSpec is provided + // Considering any ktsParameterSpec with "Generic" as ktsParameterSpec not provided + boolean useKDF = parameterSpec.getKdfAlgorithm() != null; + + SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(publicKey.getKeyParams()); + + byte[] encapsulation = secEnc.getEncapsulation(); + byte[] secret = secEnc.getSecret(); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); + + return new KEM.Encapsulated(new SecretKeySpec(secretKey, algorithm), encapsulation, null); //TODO: DER encoding for params } + } + + @Override + public int engineSecretSize() + { + return parameterSpec.getKeySize() / 8; + } + + + @Override + public int engineEncapsulationSize() + { + //TODO: Maybe make parameterSet public or add getEncapsulationSize() in KEMGenerator.java + switch (publicKey.getKeyParams().getParameters().getName()) + { + case "ML-KEM-512": + return 768; + case "ML-KEM-768": + return 1088; + case "ML-KEM-1024": + return 1568; + default: + return -1; + } + } +} diff --git a/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMSpi.java b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMSpi.java new file mode 100644 index 0000000000..db4fed4ff4 --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/jcajce/provider/asymmetric/mlkem/MLKEMSpi.java @@ -0,0 +1,61 @@ +package org.bouncycastle.jcajce.provider.asymmetric.mlkem; + +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.BCMLKEMPrivateKey; +import org.bouncycastle.jcajce.provider.asymmetric.mlkem.BCMLKEMPublicKey; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; + +import javax.crypto.KEMSpi; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +public class MLKEMSpi + implements KEMSpi +{ + @Override + public EncapsulatorSpi engineNewEncapsulator(PublicKey publicKey, AlgorithmParameterSpec spec, SecureRandom secureRandom) + throws InvalidAlgorithmParameterException, InvalidKeyException + { + if (!(publicKey instanceof BCMLKEMPublicKey)) + { + throw new InvalidKeyException("unsupported key"); + } + if (spec == null) + { + // Do not wrap key, no KDF + spec = new KTSParameterSpec.Builder("Generic", 256).withNoKdf().build(); + } + if (!(spec instanceof KTSParameterSpec)) + { + throw new InvalidAlgorithmParameterException("MLKEM can only accept KTSParameterSpec"); + } + if (secureRandom == null) + { + secureRandom = new SecureRandom(); + } + return new MLKEMEncapsulatorSpi((BCMLKEMPublicKey) publicKey, (KTSParameterSpec) spec, secureRandom); + } + + @Override + public DecapsulatorSpi engineNewDecapsulator(PrivateKey privateKey, AlgorithmParameterSpec spec) + throws InvalidAlgorithmParameterException, InvalidKeyException + { + if (!(privateKey instanceof BCMLKEMPrivateKey)) + { + throw new InvalidKeyException("unsupported key"); + } + if (spec == null) + { + // Do not unwrap key, no KDF + spec = new KTSParameterSpec.Builder("Generic", 256).withNoKdf().build(); + } + if (!(spec instanceof KTSParameterSpec)) + { + throw new InvalidAlgorithmParameterException("MLKEM can only accept KTSParameterSpec"); + } + return new MLKEMDecapsulatorSpi((BCMLKEMPrivateKey) privateKey, (KTSParameterSpec) spec); + } +} diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/HQC.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/HQC.java new file mode 100644 index 0000000000..c501d1637f --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/HQC.java @@ -0,0 +1,58 @@ +package org.bouncycastle.pqc.jcajce.provider; + +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; +import org.bouncycastle.pqc.jcajce.provider.hqc.HQCKeyFactorySpi; + +public class HQC +{ + private static final String PREFIX = "org.bouncycastle.pqc.jcajce.provider" + ".hqc."; + + public static class Mappings + extends AsymmetricAlgorithmProvider + { + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("KeyFactory.HQC", PREFIX + "HQCKeyFactorySpi"); + provider.addAlgorithm("Alg.Alias.KeyFactory.HQC", "HQC"); + addKeyFactoryAlgorithm(provider, "HQC128", PREFIX + "HQCKeyFactorySpi$HQC128", BCObjectIdentifiers.hqc128, new HQCKeyFactorySpi.HQC128()); + addKeyFactoryAlgorithm(provider, "HQC192", PREFIX + "HQCKeyFactorySpi$HQC192", BCObjectIdentifiers.hqc192, new HQCKeyFactorySpi.HQC192()); + addKeyFactoryAlgorithm(provider, "HQC256", PREFIX + "HQCKeyFactorySpi$HQC256", BCObjectIdentifiers.hqc256, new HQCKeyFactorySpi.HQC256()); + + provider.addAlgorithm("KeyPairGenerator.HQC", PREFIX + "HQCKeyPairGeneratorSpi"); + provider.addAlgorithm("Alg.Alias.KeyPairGenerator.HQC", "HQC"); + addKeyPairGeneratorAlgorithm(provider, "HQC128", PREFIX + "HQCKeyPairGeneratorSpi$HQC128", BCObjectIdentifiers.hqc128); + addKeyPairGeneratorAlgorithm(provider, "HQC192", PREFIX + "HQCKeyPairGeneratorSpi$HQC192", BCObjectIdentifiers.hqc192); + addKeyPairGeneratorAlgorithm(provider, "HQC256", PREFIX + "HQCKeyPairGeneratorSpi$HQC256", BCObjectIdentifiers.hqc256); + + provider.addAlgorithm("KeyGenerator.HQC", PREFIX + "HQCKeyGeneratorSpi"); + addKeyGeneratorAlgorithm(provider, "HQC128", PREFIX + "HQCKeyGeneratorSpi$HQC128", BCObjectIdentifiers.hqc128); + addKeyGeneratorAlgorithm(provider, "HQC192", PREFIX + "HQCKeyGeneratorSpi$HQC192", BCObjectIdentifiers.hqc192); + addKeyGeneratorAlgorithm(provider, "HQC256", PREFIX + "HQCKeyGeneratorSpi$HQC256", BCObjectIdentifiers.hqc256); + + AsymmetricKeyInfoConverter keyFact = new HQCKeyFactorySpi(); + + provider.addAlgorithm("Cipher.HQC", PREFIX + "HQCCipherSpi$Base"); + provider.addAlgorithm("Alg.Alias.Cipher.HQC", "HQC"); + + addCipherAlgorithm(provider, "HQC128", PREFIX + "HQCCipherSpi$HQC128", BCObjectIdentifiers.hqc128); + addCipherAlgorithm(provider, "HQC192", PREFIX + "HQCCipherSpi$HQC192", BCObjectIdentifiers.hqc192); + addCipherAlgorithm(provider, "HQC256", PREFIX + "HQCCipherSpi$HQC256", BCObjectIdentifiers.hqc256); + + provider.addKeyInfoConverter(BCObjectIdentifiers.hqc128, keyFact); + provider.addKeyInfoConverter(BCObjectIdentifiers.hqc192, keyFact); + provider.addKeyInfoConverter(BCObjectIdentifiers.hqc256, keyFact); + + provider.addAlgorithm("KEM.HQC", PREFIX + "HQCKEMSpi"); + provider.addAlgorithm("Alg.Alias.KEM." + BCObjectIdentifiers.hqc128, "HQC"); + provider.addAlgorithm("Alg.Alias.KEM." + BCObjectIdentifiers.hqc192, "HQC"); + provider.addAlgorithm("Alg.Alias.KEM." + BCObjectIdentifiers.hqc256, "HQC"); + } + } +} diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/Util.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/Util.java deleted file mode 100644 index 08f37ba137..0000000000 --- a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/Util.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider; - -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.crypto.DerivationFunction; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.Xof; -import org.bouncycastle.crypto.agreement.kdf.ConcatenationKDFGenerator; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.digests.SHA512Digest; -import org.bouncycastle.crypto.digests.SHAKEDigest; -import org.bouncycastle.crypto.generators.KDF2BytesGenerator; -import org.bouncycastle.crypto.params.KDFParameters; -import org.bouncycastle.jcajce.spec.KTSParameterSpec; - -import java.security.InvalidKeyException; - -public class Util -{ - public static byte[] makeKeyBytes(KTSParameterSpec ktsSpec, byte[] secret) - throws InvalidKeyException - { - AlgorithmIdentifier kdfAlgorithm = ktsSpec.getKdfAlgorithm(); - byte[] otherInfo = ktsSpec.getOtherInfo(); - byte[] keyBytes = new byte[(ktsSpec.getKeySize() + 7) / 8]; - - if (X9ObjectIdentifiers.id_kdf_kdf2.equals(kdfAlgorithm.getAlgorithm())) - { - AlgorithmIdentifier digAlg = AlgorithmIdentifier.getInstance(kdfAlgorithm.getParameters()); - DerivationFunction kdf = new KDF2BytesGenerator(getDigest(digAlg.getAlgorithm())); - - kdf.init(new KDFParameters(secret, otherInfo)); - - kdf.generateBytes(keyBytes, 0, keyBytes.length); - } - else if (X9ObjectIdentifiers.id_kdf_kdf3.equals(kdfAlgorithm.getAlgorithm())) - { - AlgorithmIdentifier digAlg = AlgorithmIdentifier.getInstance(kdfAlgorithm.getParameters()); - DerivationFunction kdf = new ConcatenationKDFGenerator(getDigest(digAlg.getAlgorithm())); - - kdf.init(new KDFParameters(secret, otherInfo)); - - kdf.generateBytes(keyBytes, 0, keyBytes.length); - } - else if (NISTObjectIdentifiers.id_shake256.equals(kdfAlgorithm.getAlgorithm())) - { - Xof xof = new SHAKEDigest(256); - - xof.update(secret, 0, secret.length); - xof.update(otherInfo, 0, otherInfo.length); - - xof.doFinal(keyBytes, 0, keyBytes.length); - } - else - { - throw new InvalidKeyException("Unrecognized KDF: " + kdfAlgorithm.getAlgorithm()); - } - - return keyBytes; - } - - static Digest getDigest(ASN1ObjectIdentifier oid) - { - if (oid.equals(NISTObjectIdentifiers.id_sha256)) - { - return new SHA256Digest(); - } - if (oid.equals(NISTObjectIdentifiers.id_sha512)) - { - return new SHA512Digest(); - } - if (oid.equals(NISTObjectIdentifiers.id_shake128)) - { - return new SHAKEDigest(128); - } - if (oid.equals(NISTObjectIdentifiers.id_shake256)) - { - return new SHAKEDigest(256); - } - - throw new IllegalArgumentException("unrecognized digest OID: " + oid); - } -} diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCDecapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCDecapsulatorSpi.java new file mode 100644 index 0000000000..c5cb327ac1 --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCDecapsulatorSpi.java @@ -0,0 +1,80 @@ +package org.bouncycastle.pqc.jcajce.provider.hqc; + +import org.bouncycastle.pqc.jcajce.provider.hqc.BCHQCPrivateKey; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; + +import org.bouncycastle.pqc.crypto.hqc.HQCKEMExtractor; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; + +import javax.crypto.DecapsulateException; +import javax.crypto.KEMSpi; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import java.util.Arrays; +import java.util.Objects; + +public class HQCDecapsulatorSpi + implements KEMSpi.DecapsulatorSpi +{ + BCHQCPrivateKey privateKey; + KTSParameterSpec parameterSpec; + HQCKEMExtractor kemExt; + + public HQCDecapsulatorSpi(BCHQCPrivateKey privateKey, KTSParameterSpec parameterSpec) + { + this.privateKey = privateKey; + this.parameterSpec = parameterSpec; + + this.kemExt = new HQCKEMExtractor(privateKey.getKeyParams()); + } + + @Override + public SecretKey engineDecapsulate(byte[] encapsulation, int from, int to, String algorithm) + throws DecapsulateException + { + Objects.checkFromToIndex(from, to, engineSecretSize()); + Objects.requireNonNull(algorithm, "null algorithm"); + Objects.requireNonNull(encapsulation, "null encapsulation"); + + if (encapsulation.length != engineEncapsulationSize()) + { + throw new DecapsulateException("incorrect encapsulation size"); + } + + // if algorithm is Generic then use parameterSpec to wrap key + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + algorithm.equals("Generic")) + { + algorithm = parameterSpec.getKeyAlgorithmName(); + } + + // check spec algorithm mismatch provided algorithm + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + !parameterSpec.getKeyAlgorithmName().equals(algorithm)) + { + throw new UnsupportedOperationException(parameterSpec.getKeyAlgorithmName() + " does not match " + algorithm); + } + + // Only use KDF when ktsParameterSpec is provided + // Considering any ktsParameterSpec with "Generic" as ktsParameterSpec not provided + boolean useKDF = parameterSpec.getKdfAlgorithm() != null; + + byte[] secret = kemExt.extractSecret(encapsulation); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); + + return new SecretKeySpec(secretKey, algorithm); + } + + @Override + public int engineSecretSize() + { + return parameterSpec.getKeySize() / 8; + } + + @Override + public int engineEncapsulationSize() + { + return kemExt.getEncapsulationLength(); + } +} \ No newline at end of file diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCEncapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCEncapsulatorSpi.java new file mode 100644 index 0000000000..c3623c4e4a --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCEncapsulatorSpi.java @@ -0,0 +1,87 @@ +package org.bouncycastle.pqc.jcajce.provider.hqc; + +import org.bouncycastle.crypto.SecretWithEncapsulation; +import org.bouncycastle.pqc.jcajce.provider.hqc.BCHQCPublicKey; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.pqc.crypto.hqc.HQCKEMGenerator; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; + +import javax.crypto.KEM; +import javax.crypto.KEMSpi; +import javax.crypto.spec.SecretKeySpec; + +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Objects; + +public class HQCEncapsulatorSpi + implements KEMSpi.EncapsulatorSpi +{ + private final BCHQCPublicKey publicKey; + private final KTSParameterSpec parameterSpec; + private final HQCKEMGenerator kemGen; + + public HQCEncapsulatorSpi(BCHQCPublicKey publicKey, KTSParameterSpec parameterSpec, SecureRandom random) + { + this.publicKey = publicKey; + this.parameterSpec = parameterSpec; + + this.kemGen = new HQCKEMGenerator(random); + } + + @Override + public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm) + { + Objects.checkFromToIndex(from, to, engineSecretSize()); + Objects.requireNonNull(algorithm, "null algorithm"); + + // if algorithm is Generic then use parameterSpec to wrap key + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + algorithm.equals("Generic")) + { + algorithm = parameterSpec.getKeyAlgorithmName(); + } + + // check spec algorithm mismatch provided algorithm + if (!parameterSpec.getKeyAlgorithmName().equals("Generic") && + !parameterSpec.getKeyAlgorithmName().equals(algorithm)) + { + throw new UnsupportedOperationException(parameterSpec.getKeyAlgorithmName() + " does not match " + algorithm); + } + + // Only use KDF when ktsParameterSpec is provided + // Considering any ktsParameterSpec with "Generic" as ktsParameterSpec not provided + boolean useKDF = parameterSpec.getKdfAlgorithm() != null; + + SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(publicKey.getKeyParams()); + + byte[] encapsulation = secEnc.getEncapsulation(); + byte[] secret = secEnc.getSecret(); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); + + return new KEM.Encapsulated(new SecretKeySpec(secretKey, algorithm), encapsulation, null); //TODO: DER encoding for params + } + + @Override + public int engineSecretSize() + { + return parameterSpec.getKeySize() / 8; + } + + @Override + public int engineEncapsulationSize() + { + //TODO: Maybe make parameterSet public or add getEncapsulationSize() in HQCKEMGenerator.java + switch (publicKey.getKeyParams().getParameters().getName()) + { + case "HQC-128": + return 128; + case "HQC-192": + return 192; + case "HQC-256": + return 256; + default: + return -1; + } + } +} \ No newline at end of file diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKEMSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKEMSpi.java new file mode 100644 index 0000000000..329ef16f2f --- /dev/null +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/hqc/HQCKEMSpi.java @@ -0,0 +1,62 @@ +package org.bouncycastle.pqc.jcajce.provider.hqc; + +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.KEMSpi; + +import org.bouncycastle.jcajce.spec.KTSParameterSpec; + +public class HQCKEMSpi + implements KEMSpi +{ + + @Override + public EncapsulatorSpi engineNewEncapsulator(PublicKey publicKey, AlgorithmParameterSpec spec, + SecureRandom secureRandom) + throws InvalidAlgorithmParameterException, InvalidKeyException + { + if (!(publicKey instanceof BCHQCPublicKey)) + { + throw new InvalidKeyException("unsupported key"); + } + if (spec == null) + { + // Do not wrap key, no KDF + spec = new KTSParameterSpec.Builder("Generic", 256).withNoKdf().build(); + } + if (!(spec instanceof KTSParameterSpec)) + { + throw new InvalidAlgorithmParameterException("HQC can only accept KTSParameterSpec"); + } + if (secureRandom == null) + { + secureRandom = new SecureRandom(); + } + return new HQCEncapsulatorSpi((BCHQCPublicKey)publicKey, (KTSParameterSpec)spec, secureRandom); + } + + @Override + public DecapsulatorSpi engineNewDecapsulator(PrivateKey privateKey, AlgorithmParameterSpec spec) + throws InvalidAlgorithmParameterException, InvalidKeyException + { + if (!(privateKey instanceof BCHQCPrivateKey)) + { + throw new InvalidKeyException("unsupported key"); + } + if (spec == null) + { + // Do not unwrap key, no KDF + spec = new KTSParameterSpec.Builder("Generic", 256).withNoKdf().build(); + } + if (!(spec instanceof KTSParameterSpec)) + { + throw new InvalidAlgorithmParameterException("HQC can only accept KTSParameterSpec"); + } + return new HQCDecapsulatorSpi((BCHQCPrivateKey)privateKey, (KTSParameterSpec)spec); + } +} \ No newline at end of file diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUDecapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUDecapsulatorSpi.java index f51faf3509..71c174efa9 100644 --- a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUDecapsulatorSpi.java +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUDecapsulatorSpi.java @@ -4,7 +4,7 @@ import org.bouncycastle.jcajce.spec.KTSParameterSpec; import org.bouncycastle.pqc.crypto.ntru.NTRUKEMExtractor; -import org.bouncycastle.pqc.jcajce.provider.Util; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; import javax.crypto.DecapsulateException; import javax.crypto.KEMSpi; @@ -60,19 +60,7 @@ public SecretKey engineDecapsulate(byte[] encapsulation, int from, int to, Strin boolean useKDF = parameterSpec.getKdfAlgorithm() != null; byte[] secret = kemExt.extractSecret(encapsulation); - - if (useKDF) - { - try - { - secret = Util.makeKeyBytes(parameterSpec, secret); - } - catch (InvalidKeyException e) - { - throw new IllegalStateException(e); - } - } - byte[] secretKey = Arrays.copyOfRange(secret, from, to); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); return new SecretKeySpec(secretKey, algorithm); } diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUEncapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUEncapsulatorSpi.java index 81c94d49e4..fea938b4ee 100644 --- a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUEncapsulatorSpi.java +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntru/NTRUEncapsulatorSpi.java @@ -3,7 +3,7 @@ import org.bouncycastle.crypto.SecretWithEncapsulation; import org.bouncycastle.jcajce.spec.KTSParameterSpec; import org.bouncycastle.pqc.crypto.ntru.NTRUKEMGenerator; -import org.bouncycastle.pqc.jcajce.provider.Util; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; import javax.crypto.KEM; import javax.crypto.KEMSpi; @@ -56,25 +56,9 @@ public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm) byte[] encapsulation = secEnc.getEncapsulation(); byte[] secret = secEnc.getSecret(); - - byte[] secretKey; - - if (useKDF) - { - try - { - secret = Util.makeKeyBytes(parameterSpec, secret); - } - catch (InvalidKeyException e) - { - throw new IllegalStateException(e); - } - } - - secretKey = Arrays.copyOfRange(secret, from, to); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); return new KEM.Encapsulated(new SecretKeySpec(secretKey, algorithm), encapsulation, null); //TODO: DER encoding for params - } @Override diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeDecapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeDecapsulatorSpi.java index 847fd006e0..945237dca6 100644 --- a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeDecapsulatorSpi.java +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeDecapsulatorSpi.java @@ -2,7 +2,7 @@ import org.bouncycastle.jcajce.spec.KTSParameterSpec; import org.bouncycastle.pqc.crypto.ntruprime.SNTRUPrimeKEMExtractor; -import org.bouncycastle.pqc.jcajce.provider.Util; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; import org.bouncycastle.util.Arrays; import javax.crypto.DecapsulateException; @@ -56,22 +56,9 @@ public SecretKey engineDecapsulate(byte[] encapsulation, int from, int to, Strin // Only use KDF when ktsParameterSpec is provided // Considering any ktsParameterSpec with "Generic" as ktsParameterSpec not provided - boolean useKDF = parameterSpec.getKdfAlgorithm() != null; - byte[] secret = kemExt.extractSecret(encapsulation); - if (useKDF) - { - try - { - secret = Util.makeKeyBytes(parameterSpec, secret); - } - catch (InvalidKeyException e) - { - throw new IllegalStateException(e); - } - } - byte[] secretKey = Arrays.copyOfRange(secret, from, to); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); return new SecretKeySpec(secretKey, algorithm); } diff --git a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeEncapsulatorSpi.java b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeEncapsulatorSpi.java index e15d83eed6..13698138a7 100644 --- a/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeEncapsulatorSpi.java +++ b/prov/src/main/jdk21/org/bouncycastle/pqc/jcajce/provider/ntruprime/SNTRUPrimeEncapsulatorSpi.java @@ -3,7 +3,7 @@ import org.bouncycastle.crypto.SecretWithEncapsulation; import org.bouncycastle.jcajce.spec.KTSParameterSpec; import org.bouncycastle.pqc.crypto.ntruprime.SNTRUPrimeKEMGenerator; -import org.bouncycastle.pqc.jcajce.provider.Util; +import org.bouncycastle.pqc.jcajce.provider.util.KdfUtil; import org.bouncycastle.util.Arrays; import javax.crypto.KEM; @@ -51,28 +51,12 @@ public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm) // Only use KDF when ktsParameterSpec is provided // Considering any ktsParameterSpec with "Generic" as ktsParameterSpec not provided - boolean useKDF = parameterSpec.getKdfAlgorithm() != null; - SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(publicKey.getKeyParams()); byte[] encapsulation = secEnc.getEncapsulation(); byte[] secret = secEnc.getSecret(); - byte[] secretKey; - - if (useKDF) - { - try - { - secret = Util.makeKeyBytes(parameterSpec, secret); - } - catch (InvalidKeyException e) - { - throw new IllegalStateException(e); - } - } - - secretKey = Arrays.copyOfRange(secret, from, to); + byte[] secretKey = Arrays.copyOfRange(KdfUtil.makeKeyBytes(parameterSpec, secret), from, to); return new KEM.Encapsulated(new SecretKeySpec(secretKey, algorithm), encapsulation, null); //TODO: DER encoding for params diff --git a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/AllTests.java b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/AllTests.java index 662cd00fe9..b14545d2f2 100644 --- a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/AllTests.java +++ b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/AllTests.java @@ -32,6 +32,8 @@ public static Test suite() suite.addTestSuite(CompositeKeyTest.class); suite.addTestSuite(CompositeSignaturesTest.class); suite.addTestSuite(BouncyCastleProviderTest.class); + suite.addTestSuite(PQCSignatureTest.class); + suite.addTestSuite(SecretKeyUtilTest.class); return new BCTestSetup(suite); } diff --git a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeKeyTest.java b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeKeyTest.java index 75d7a41762..7110a98859 100644 --- a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeKeyTest.java +++ b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeKeyTest.java @@ -113,15 +113,4 @@ public void testGenericCompositeKey() CompositePrivateKey compPrivKey = (CompositePrivateKey)keyFact.generatePrivate(new PKCS8EncodedKeySpec(genPrivKey)); } - - public void testExplicitCompositeKey() - throws Exception - { - KeyFactory keyFact = KeyFactory.getInstance("COMPOSITE", "BC"); - - CompositePublicKey compPubKey = (CompositePublicKey)keyFact.generatePublic(new X509EncodedKeySpec(expPubKey)); - - // System.out.println(ASN1Dump.dumpAsString(ASN1Primitive.fromByteArray(expPubKey))); - CompositePrivateKey compPrivKey = (CompositePrivateKey)keyFact.generatePrivate(new PKCS8EncodedKeySpec(expPrivKey)); - } } diff --git a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeSignaturesTest.java b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeSignaturesTest.java index 25405c7d80..0621709a51 100644 --- a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeSignaturesTest.java +++ b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/CompositeSignaturesTest.java @@ -1,48 +1,37 @@ package org.bouncycastle.jcajce.provider.test; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.Signature; -import java.security.spec.X509EncodedKeySpec; import junit.framework.TestCase; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.jcajce.CompositePrivateKey; import org.bouncycastle.jcajce.CompositePublicKey; -import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeSignaturesConstants; +import org.bouncycastle.jcajce.provider.asymmetric.compositesignatures.CompositeIndex; import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPublicKey; +import org.bouncycastle.jcajce.spec.ContextParameterSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Base64; public class CompositeSignaturesTest extends TestCase { private static String[] compositeSignaturesOIDs = { - "2.16.840.1.114027.80.8.1.1", //id-MLDSA44-RSA2048-PSS-SHA256 - "2.16.840.1.114027.80.8.1.2", //id-MLDSA44-RSA2048-PKCS15-SHA256 - "2.16.840.1.114027.80.8.1.3", //id-MLDSA44-Ed25519-SHA512 - "2.16.840.1.114027.80.8.1.4", //id-MLDSA44-ECDSA-P256-SHA256 - "2.16.840.1.114027.80.8.1.5", //id-MLDSA44-ECDSA-brainpoolP256r1-SHA256 - "2.16.840.1.114027.80.8.1.6", //id-MLDSA65-RSA3072-PSS-SHA512 - "2.16.840.1.114027.80.8.1.7", //id-MLDSA65-RSA3072-PKCS15-SHA512 - "2.16.840.1.114027.80.8.1.8", //id-MLDSA65-ECDSA-P256-SHA512 - "2.16.840.1.114027.80.8.1.9", //id-MLDSA65-ECDSA-brainpoolP256r1-SHA512 - "2.16.840.1.114027.80.8.1.10", //id-MLDSA65-Ed25519-SHA512 - "2.16.840.1.114027.80.8.1.11", //id-MLDSA87-ECDSA-P384-SHA512 - "2.16.840.1.114027.80.8.1.12", //id-MLDSA87-ECDSA-brainpoolP384r1-SHA512 - "2.16.840.1.114027.80.8.1.13", //id-MLDSA87-Ed448-SHA512 - // Falcon composites below were excluded from the draft. See MiscObjectIdentifiers for details. - "2.16.840.1.114027.80.8.1.14", //id-Falcon512-ECDSA-P256-SHA256 - "2.16.840.1.114027.80.8.1.15", //id-Falcon512-ECDSA-brainpoolP256r1-SHA256 - "2.16.840.1.114027.80.8.1.16", //id-Falcon512-Ed25519-SHA512 + "2.16.840.1.114027.80.8.1.21", //id-MLDSA44-RSA2048-PSS-SHA256 + "2.16.840.1.114027.80.8.1.22", //id-MLDSA44-RSA2048-PKCS15-SHA256 + "2.16.840.1.114027.80.8.1.23", //id-MLDSA44-Ed25519-SHA512 + "2.16.840.1.114027.80.8.1.24", //id-MLDSA44-ECDSA-P256-SHA256 + "2.16.840.1.114027.80.8.1.26", //id-MLDSA65-RSA3072-PSS-SHA512 + "2.16.840.1.114027.80.8.1.27", //id-MLDSA65-RSA3072-PKCS15-SHA512 + "2.16.840.1.114027.80.8.1.28", //id-MLDSA65-ECDSA-P256-SHA512 + "2.16.840.1.114027.80.8.1.29", //id-MLDSA65-ECDSA-brainpoolP256r1-SHA512 + "2.16.840.1.114027.80.8.1.30", //id-MLDSA65-Ed25519-SHA512 + "2.16.840.1.114027.80.8.1.31", //id-MLDSA87-ECDSA-P384-SHA512 + "2.16.840.1.114027.80.8.1.32", //id-MLDSA87-ECDSA-brainpoolP384r1-SHA512 + "2.16.840.1.114027.80.8.1.33", //id-MLDSA87-Ed448-SHA512 }; public static final String messageToBeSigned = "Hello, how was your day?"; @@ -55,8 +44,9 @@ public void setUp() public void testKeyPairGeneration() throws Exception { - for (String oid : compositeSignaturesOIDs) + for (ASN1ObjectIdentifier asnOid : CompositeIndex.getSupportedIdentifiers()) { + String oid = asnOid.getId(); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(oid, "BC"); KeyPair keyPair = keyPairGenerator.generateKeyPair(); CompositePublicKey compositePublicKey = (CompositePublicKey)keyPair.getPublic(); @@ -70,86 +60,73 @@ public void testKeyPairGeneration() BCRSAPublicKey rsaPublicKey = null; BCRSAPublicKey rsaPrivateKey = null; - switch (CompositeSignaturesConstants.ASN1IdentifierCompositeNameMap.get(new ASN1ObjectIdentifier(oid))) - { - case MLDSA44_RSA2048_PSS_SHA256: - case MLDSA44_RSA2048_PKCS15_SHA256: - TestCase.assertEquals("DILITHIUM2", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM2", firstPrivateKeyAlgorithm); - TestCase.assertEquals("RSA", secondPublicKeyAlgorithm); - TestCase.assertEquals("RSA", secondPrivateKeyAlgorithm); - rsaPublicKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); - rsaPrivateKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); - TestCase.assertEquals(2048, rsaPublicKey.getModulus().bitLength()); - TestCase.assertEquals(2048, rsaPrivateKey.getModulus().bitLength()); - break; - case MLDSA44_Ed25519_SHA512: - TestCase.assertEquals("DILITHIUM2", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM2", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ED25519", secondPublicKeyAlgorithm); - TestCase.assertEquals("ED25519", secondPrivateKeyAlgorithm); - break; - case MLDSA44_ECDSA_P256_SHA256: - case MLDSA44_ECDSA_brainpoolP256r1_SHA256: - TestCase.assertEquals("DILITHIUM2", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM2", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); - break; - case MLDSA65_RSA3072_PSS_SHA512: - case MLDSA65_RSA3072_PKCS15_SHA512: - TestCase.assertEquals("DILITHIUM3", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM3", firstPrivateKeyAlgorithm); - TestCase.assertEquals("RSA", secondPublicKeyAlgorithm); - TestCase.assertEquals("RSA", secondPrivateKeyAlgorithm); - rsaPublicKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); - rsaPrivateKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); - TestCase.assertEquals(3072, rsaPublicKey.getModulus().bitLength()); - TestCase.assertEquals(3072, rsaPrivateKey.getModulus().bitLength()); - break; - case MLDSA65_Ed25519_SHA512: - TestCase.assertEquals("DILITHIUM3", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM3", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ED25519", secondPublicKeyAlgorithm); - TestCase.assertEquals("ED25519", secondPrivateKeyAlgorithm); - break; - case MLDSA65_ECDSA_P256_SHA512: - case MLDSA65_ECDSA_brainpoolP256r1_SHA512: - TestCase.assertEquals("DILITHIUM3", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM3", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); - break; - case MLDSA87_Ed448_SHA512: - TestCase.assertEquals("DILITHIUM5", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM5", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ED448", secondPublicKeyAlgorithm); - TestCase.assertEquals("ED448", secondPrivateKeyAlgorithm); - break; - case MLDSA87_ECDSA_P384_SHA512: - case MLDSA87_ECDSA_brainpoolP384r1_SHA512: - TestCase.assertEquals("DILITHIUM5", firstPublicKeyAlgorithm); - TestCase.assertEquals("DILITHIUM5", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); - break; - case Falcon512_Ed25519_SHA512: - TestCase.assertEquals("FALCON-512", firstPublicKeyAlgorithm); - TestCase.assertEquals("FALCON-512", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ED25519", secondPublicKeyAlgorithm); - TestCase.assertEquals("ED25519", secondPrivateKeyAlgorithm); - break; - case Falcon512_ECDSA_P256_SHA256: - case Falcon512_ECDSA_brainpoolP256r1_SHA256: - TestCase.assertEquals("FALCON-512", firstPublicKeyAlgorithm); - TestCase.assertEquals("FALCON-512", firstPrivateKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); - TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); - break; - default: - throw new IllegalStateException( - "Unexpected key algorithm." + CompositeSignaturesConstants.ASN1IdentifierCompositeNameMap.get(new ASN1ObjectIdentifier(oid))); - } +// switch (CompositeSignaturesConstants.ASN1IdentifierCompositeNameMap.get(new ASN1ObjectIdentifier(oid))) +// { +// case MLDSA44_RSA2048_PSS_SHA256: +// case MLDSA44_RSA2048_PKCS15_SHA256: +// TestCase.assertEquals("ML-DSA-44", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-44", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("RSA", secondPublicKeyAlgorithm); +// TestCase.assertEquals("RSA", secondPrivateKeyAlgorithm); +// rsaPublicKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); +// rsaPrivateKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); +// TestCase.assertEquals(2048, rsaPublicKey.getModulus().bitLength()); +// TestCase.assertEquals(2048, rsaPrivateKey.getModulus().bitLength()); +// break; +// case MLDSA44_Ed25519_SHA512: +// TestCase.assertEquals("ML-DSA-44", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-44", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("ED25519", secondPublicKeyAlgorithm); +// TestCase.assertEquals("ED25519", secondPrivateKeyAlgorithm); +// break; +// case MLDSA44_ECDSA_P256_SHA256: +// case MLDSA44_ECDSA_brainpoolP256r1_SHA256: +// TestCase.assertEquals("ML-DSA-44", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-44", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); +// TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); +// break; +// case MLDSA65_RSA3072_PSS_SHA512: +// case MLDSA65_RSA3072_PKCS15_SHA512: +// TestCase.assertEquals("ML-DSA-65", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-65", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("RSA", secondPublicKeyAlgorithm); +// TestCase.assertEquals("RSA", secondPrivateKeyAlgorithm); +// rsaPublicKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); +// rsaPrivateKey = (BCRSAPublicKey)compositePublicKey.getPublicKeys().get(1); +// TestCase.assertEquals(3072, rsaPublicKey.getModulus().bitLength()); +// TestCase.assertEquals(3072, rsaPrivateKey.getModulus().bitLength()); +// break; +// case MLDSA65_Ed25519_SHA512: +// TestCase.assertEquals("ML-DSA-65", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-65", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("ED25519", secondPublicKeyAlgorithm); +// TestCase.assertEquals("ED25519", secondPrivateKeyAlgorithm); +// break; +// case MLDSA65_ECDSA_P256_SHA512: +// case MLDSA65_ECDSA_brainpoolP256r1_SHA512: ompositeK +// TestCase.assertEquals("ML-DSA-65", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-65", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); +// TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); +// break; +// case MLDSA87_Ed448_SHA512: +// TestCase.assertEquals("ML-DSA-87", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-87", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("ED448", secondPublicKeyAlgorithm); +// TestCase.assertEquals("ED448", secondPrivateKeyAlgorithm); +// break; +// case MLDSA87_ECDSA_P384_SHA512: +// case MLDSA87_ECDSA_brainpoolP384r1_SHA512: +// TestCase.assertEquals("ML-DSA-87", firstPublicKeyAlgorithm); +// TestCase.assertEquals("ML-DSA-87", firstPrivateKeyAlgorithm); +// TestCase.assertEquals("ECDSA", secondPublicKeyAlgorithm); +// TestCase.assertEquals("ECDSA", secondPrivateKeyAlgorithm); +// break; +// default: +// throw new IllegalStateException( +// "Unexpected key algorithm." + CompositeSignaturesConstants.ASN1IdentifierCompositeNameMap.get(new ASN1ObjectIdentifier(oid))); +// } } } @@ -171,6 +148,33 @@ public void testSigningAndVerificationInternal() } } + public void testContextParameterSpec() + throws Exception + { + String oid = "2.16.840.1.114027.80.8.1.24"; // MLDSA44withECDSA_P256_SHA256 + + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(oid, "BC"); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + Signature signature = Signature.getInstance(oid, "BC"); + signature.initSign(keyPair.getPrivate()); + + signature.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + signature.update(Strings.toUTF8ByteArray(messageToBeSigned)); + byte[] signatureValue = signature.sign(); + + signature = Signature.getInstance(oid, "BC"); + + signature.initVerify(keyPair.getPublic()); + + signature.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + signature.update(Strings.toUTF8ByteArray(messageToBeSigned)); + TestCase.assertTrue(signature.verify(signatureValue)); + } + + /* + //TODO: samples now out of date public void testDecodingAndVerificationExternal() throws Exception { @@ -199,14 +203,15 @@ public void testDecodingAndVerificationExternal() X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decode(publicKeyBase64)); KeyFactory keyFactory = KeyFactory.getInstance(oid, "BC"); CompositePublicKey compositePublicKey = (CompositePublicKey)keyFactory.generatePublic(pubKeySpec); - + Signature signature = Signature.getInstance(oid, "BC"); signature.initVerify(compositePublicKey); signature.update(Base64.decode(messageBase64)); - assertTrue(signature.verify(Base64.decode(signatureValueBase64))); + assertTrue(oid.toString(), signature.verify(Base64.decode(signatureValueBase64))); count++; } assertEquals(compositeSignaturesOIDs.length, count); } + */ } diff --git a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/PQCSignatureTest.java b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/PQCSignatureTest.java new file mode 100644 index 0000000000..cad9e540aa --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/PQCSignatureTest.java @@ -0,0 +1,67 @@ +package org.bouncycastle.jcajce.provider.test; + +import java.security.Key; +import java.security.KeyPairGenerator; +import java.security.Security; +import java.security.Signature; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +public class PQCSignatureTest + extends TestCase +{ + public void setUp() + { + if (Security.getProvider("BC") == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + private static Signature deriveSignatureFromKey(Key key) + throws Exception + { + return Signature.getInstance(key.getAlgorithm(), "BC"); + } + + public void testNistSignature() + throws Exception + { + ASN1ObjectIdentifier[] nistOids = new ASN1ObjectIdentifier[] + { + NISTObjectIdentifiers.id_slh_dsa_sha2_128s, + NISTObjectIdentifiers.id_slh_dsa_sha2_128f, + NISTObjectIdentifiers.id_slh_dsa_shake_128s, + NISTObjectIdentifiers.id_slh_dsa_shake_128f, + NISTObjectIdentifiers.id_slh_dsa_sha2_192s, + NISTObjectIdentifiers.id_slh_dsa_sha2_192f, + NISTObjectIdentifiers.id_slh_dsa_shake_192s, + NISTObjectIdentifiers.id_slh_dsa_shake_192f, + NISTObjectIdentifiers.id_slh_dsa_sha2_256s, + NISTObjectIdentifiers.id_slh_dsa_sha2_256f, + NISTObjectIdentifiers.id_slh_dsa_shake_256s, + NISTObjectIdentifiers.id_slh_dsa_shake_256f, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256 + }; + + for (int i = 0; i != nistOids.length; i++) + { + KeyPairGenerator ml_dsa_kp = KeyPairGenerator.getInstance(nistOids[i].getId(), "BC"); + Signature ml_dsa_sig = deriveSignatureFromKey(ml_dsa_kp.generateKeyPair().getPrivate()); + } + } +} diff --git a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/RandomTest.java b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/RandomTest.java index 5804c43f6d..0b4f11fec4 100644 --- a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/RandomTest.java +++ b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/RandomTest.java @@ -2,7 +2,6 @@ import java.security.SecureRandom; -import junit.framework.Assert; import junit.framework.TestCase; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -18,7 +17,7 @@ public void testCheckRandom() random.nextBytes(rng); - Assert.assertTrue(checkNonConstant(rng)); + assertTrue(checkNonConstant(rng)); } public void testCheckNonceIVRandom() @@ -30,7 +29,7 @@ public void testCheckNonceIVRandom() random.nextBytes(rng); - Assert.assertTrue(checkNonConstant(rng)); + assertTrue(checkNonConstant(rng)); } private boolean checkNonConstant(byte[] data) diff --git a/prov/src/test/java/org/bouncycastle/jcajce/provider/test/SecretKeyUtilTest.java b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/SecretKeyUtilTest.java new file mode 100644 index 0000000000..a545cdea09 --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/jcajce/provider/test/SecretKeyUtilTest.java @@ -0,0 +1,24 @@ +package org.bouncycastle.jcajce.provider.test; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.internal.asn1.ntt.NTTObjectIdentifiers; +import org.bouncycastle.jcajce.provider.util.SecretKeyUtil; + +public class SecretKeyUtilTest + extends TestCase +{ + public void testgetKeySize() + { + assertEquals(192, SecretKeyUtil.getKeySize(PKCSObjectIdentifiers.des_EDE3_CBC)); + + assertEquals(128, SecretKeyUtil.getKeySize(NISTObjectIdentifiers.id_aes128_CBC)); + assertEquals(192, SecretKeyUtil.getKeySize(NISTObjectIdentifiers.id_aes192_CBC)); + assertEquals(256, SecretKeyUtil.getKeySize(NISTObjectIdentifiers.id_aes256_CBC)); + + assertEquals(128, SecretKeyUtil.getKeySize(NTTObjectIdentifiers.id_camellia128_cbc)); + assertEquals(192, SecretKeyUtil.getKeySize(NTTObjectIdentifiers.id_camellia192_cbc)); + assertEquals(256, SecretKeyUtil.getKeySize(NTTObjectIdentifiers.id_camellia256_cbc)); + } +} diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java index 217258a3de..b35575dcea 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; import java.security.Security; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.DSAParameterSpec; @@ -98,10 +99,25 @@ private void basicTest(String algorithm, Class algorithmParameterSpec, byte[] as } } + private void java21NullCheck() + throws Exception + { + try + { + AlgorithmParameters algParams = AlgorithmParameters.getInstance("1.2.840.113549.1.1.1", "BC"); + fail("no exception"); + } + catch (GeneralSecurityException e) + { + // okay.. + } + } + public void performTest() throws Exception { basicTest("DSA", DSAParameterSpec.class, dsaParams); + java21NullCheck(); AlgorithmParameters al = AlgorithmParameters.getInstance("EC", "BC"); diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/BCFKSStoreTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/BCFKSStoreTest.java index 3f4d0c57cb..eb4f742d1e 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/BCFKSStoreTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/BCFKSStoreTest.java @@ -847,6 +847,15 @@ public void shouldStoreSecretKeys() SecretKeySpec hmacKey256 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff01ff"), "HmacSHA256"); SecretKeySpec hmacKey384 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff0102ff"), "HmacSHA384"); SecretKeySpec hmacKey512 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff010203ff"), "HmacSHA512"); + SecretKeySpec hmacKey512_224 = new SecretKeySpec(Hex.decode("ff0102030405060708090a0b0c0d0eff"), "HmacSHA512/224"); + SecretKeySpec hmacKey512_256 = new SecretKeySpec(Hex.decode("ff0102030405060708090a0b0c0d0eff01ff"), "HmacSHA512/256"); + SecretKeySpec hmacKey3_224 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff"), "HmacSHA3-224"); + SecretKeySpec hmacKey3_256 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff01ff"), "HmacSHA3-256"); + SecretKeySpec hmacKey3_384 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff0102ff"), "HmacSHA3-384"); + SecretKeySpec hmacKey3_512 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff010203ff"), "HmacSHA3-512"); + + SecretKeySpec kmacKey128 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff01fd"), "KMAC128"); + SecretKeySpec kmacKey256 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0eff010203fd"), "KMAC256"); SecretKeySpec camellia128 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0e0f"), "Camellia"); SecretKeySpec camellia192 = new SecretKeySpec(Hex.decode("000102030405060708090a0b0c0d0e0f0001020304050607"), "Camellia"); @@ -865,33 +874,47 @@ public void shouldStoreSecretKeys() store1.setKeyEntry("secret7", hmacKey256, "secretPwd7".toCharArray(), null); store1.setKeyEntry("secret8", hmacKey384, "secretPwd8".toCharArray(), null); store1.setKeyEntry("secret9", hmacKey512, "secretPwd9".toCharArray(), null); - - store1.setKeyEntry("secret10", camellia128, "secretPwd10".toCharArray(), null); - store1.setKeyEntry("secret11", camellia192, "secretPwd11".toCharArray(), null); - store1.setKeyEntry("secret12", camellia256, "secretPwd12".toCharArray(), null); - store1.setKeyEntry("secret13", seed, "secretPwd13".toCharArray(), null); - store1.setKeyEntry("secret14", aria128, "secretPwd14".toCharArray(), null); - store1.setKeyEntry("secret15", aria192, "secretPwd15".toCharArray(), null); - store1.setKeyEntry("secret16", aria256, "secretPwd16".toCharArray(), null); + store1.setKeyEntry("secret10", hmacKey512_224, "secretPwd10".toCharArray(), null); + store1.setKeyEntry("secret11", hmacKey512_256, "secretPwd11".toCharArray(), null); + store1.setKeyEntry("secret12", hmacKey3_224, "secretPwd12".toCharArray(), null); + store1.setKeyEntry("secret13", hmacKey3_256, "secretPwd13".toCharArray(), null); + store1.setKeyEntry("secret14", hmacKey3_384, "secretPwd14".toCharArray(), null); + store1.setKeyEntry("secret15", hmacKey3_512, "secretPwd15".toCharArray(), null); + + store1.setKeyEntry("secret16", camellia128, "secretPwd16".toCharArray(), null); + store1.setKeyEntry("secret17", camellia192, "secretPwd17".toCharArray(), null); + store1.setKeyEntry("secret18", camellia256, "secretPwd18".toCharArray(), null); + store1.setKeyEntry("secret19", seed, "secretPwd19".toCharArray(), null); + store1.setKeyEntry("secret20", aria128, "secretPwd20".toCharArray(), null); + store1.setKeyEntry("secret21", aria192, "secretPwd21".toCharArray(), null); + store1.setKeyEntry("secret22", aria256, "secretPwd22".toCharArray(), null); + + store1.setKeyEntry("secret23", kmacKey128, "secretPwd23".toCharArray(), null); + store1.setKeyEntry("secret24", kmacKey256, "secretPwd24".toCharArray(), null); checkSecretKey(store1, "secret1", "secretPwd1".toCharArray(), aesKey); checkSecretKey(store1, "secret2", "secretPwd2".toCharArray(), edeKey1); // TRIPLEDES and TDEA will convert to DESEDE checkSecretKey(store1, "secret3", "secretPwd3".toCharArray(), edeKey1); checkSecretKey(store1, "secret4", "secretPwd4".toCharArray(), edeKey1); - // TODO: -// checkSecretKey(store1, "secret5", "secretPwd5".toCharArray(), hmacKey1); -// checkSecretKey(store1, "secret6", "secretPwd6".toCharArray(), hmacKey224); -// checkSecretKey(store1, "secret7", "secretPwd7".toCharArray(), hmacKey256); -// checkSecretKey(store1, "secret8", "secretPwd8".toCharArray(), hmacKey384); -// checkSecretKey(store1, "secret9", "secretPwd9".toCharArray(), hmacKey512); - - checkSecretKey(store1, "secret10", "secretPwd10".toCharArray(), camellia128); - checkSecretKey(store1, "secret11", "secretPwd11".toCharArray(), camellia192); - checkSecretKey(store1, "secret12", "secretPwd12".toCharArray(), camellia256); - checkSecretKey(store1, "secret13", "secretPwd13".toCharArray(), seed); - checkSecretKey(store1, "secret14", "secretPwd14".toCharArray(), aria128); - checkSecretKey(store1, "secret15", "secretPwd15".toCharArray(), aria192); - checkSecretKey(store1, "secret16", "secretPwd16".toCharArray(), aria256); + + checkSecretKey(store1, "secret5", "secretPwd5".toCharArray(), hmacKey1); + checkSecretKey(store1, "secret6", "secretPwd6".toCharArray(), hmacKey224); + checkSecretKey(store1, "secret7", "secretPwd7".toCharArray(), hmacKey256); + checkSecretKey(store1, "secret8", "secretPwd8".toCharArray(), hmacKey384); + checkSecretKey(store1, "secret9", "secretPwd9".toCharArray(), hmacKey512); + checkSecretKey(store1, "secret10", "secretPwd10".toCharArray(), hmacKey512_224); + checkSecretKey(store1, "secret11", "secretPwd11".toCharArray(), hmacKey512_256); + + checkSecretKey(store1, "secret16", "secretPwd16".toCharArray(), camellia128); + checkSecretKey(store1, "secret17", "secretPwd17".toCharArray(), camellia192); + checkSecretKey(store1, "secret18", "secretPwd18".toCharArray(), camellia256); + checkSecretKey(store1, "secret19", "secretPwd19".toCharArray(), seed); + checkSecretKey(store1, "secret20", "secretPwd20".toCharArray(), aria128); + checkSecretKey(store1, "secret21", "secretPwd21".toCharArray(), aria192); + checkSecretKey(store1, "secret22", "secretPwd22".toCharArray(), aria256); + + checkSecretKey(store1, "secret23", "secretPwd23".toCharArray(), kmacKey128); + checkSecretKey(store1, "secret24", "secretPwd24".toCharArray(), kmacKey256); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); @@ -905,14 +928,23 @@ public void shouldStoreSecretKeys() checkSecretKey(store2, "secret2", "secretPwd2".toCharArray(), edeKey1); // TRIPLEDES and TDEA will convert to DESEDE checkSecretKey(store2, "secret3", "secretPwd3".toCharArray(), edeKey1); checkSecretKey(store2, "secret4", "secretPwd4".toCharArray(), edeKey1); - // TODO: -// checkSecretKey(store2, "secret5", "secretPwd5".toCharArray(), hmacKey1); -// checkSecretKey(store2, "secret6", "secretPwd6".toCharArray(), hmacKey224); -// checkSecretKey(store2, "secret7", "secretPwd7".toCharArray(), hmacKey256); -// checkSecretKey(store2, "secret8", "secretPwd8".toCharArray(), hmacKey384); -// checkSecretKey(store2, "secret9", "secretPwd9".toCharArray(), hmacKey512); - - isTrue("", null == store2.getKey("secret17", new char[0])); + + checkSecretKey(store2, "secret5", "secretPwd5".toCharArray(), hmacKey1); + checkSecretKey(store2, "secret6", "secretPwd6".toCharArray(), hmacKey224); + checkSecretKey(store2, "secret7", "secretPwd7".toCharArray(), hmacKey256); + checkSecretKey(store2, "secret8", "secretPwd8".toCharArray(), hmacKey384); + checkSecretKey(store2, "secret9", "secretPwd9".toCharArray(), hmacKey512); + checkSecretKey(store2, "secret10", "secretPwd10".toCharArray(), hmacKey512_224); + checkSecretKey(store2, "secret11", "secretPwd11".toCharArray(), hmacKey512_256); + checkSecretKey(store2, "secret12", "secretPwd12".toCharArray(), hmacKey3_224); + checkSecretKey(store2, "secret13", "secretPwd13".toCharArray(), hmacKey3_256); + checkSecretKey(store2, "secret14", "secretPwd14".toCharArray(), hmacKey3_384); + checkSecretKey(store2, "secret15", "secretPwd15".toCharArray(), hmacKey3_512); + + checkSecretKey(store2, "secret23", "secretPwd23".toCharArray(), kmacKey128); + checkSecretKey(store2, "secret24", "secretPwd24".toCharArray(), kmacKey256); + + isTrue("", null == store2.getKey("secret27", new char[0])); } public void shouldFailOnWrongPassword() diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java index 379bd44fa2..5bed6176f6 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java @@ -58,7 +58,7 @@ protected void oidTest(String[] oids, String[] names, int groupSize) if (!areEqual(data, result)) { - fail("failed OID test"); + fail("failed OID test: " + names[i]); } if (k.getEncoded().length != (16 + ((i / groupSize) * 8))) diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/BlockCipherTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/BlockCipherTest.java index 2209f35b66..0f3bf103df 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/BlockCipherTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/BlockCipherTest.java @@ -7,6 +7,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.InvalidParameterException; @@ -37,12 +38,17 @@ import javax.crypto.spec.RC5ParameterSpec; import javax.crypto.spec.SecretKeySpec; +import org.bouncycastle.crypto.BufferedBlockCipher; +import org.bouncycastle.crypto.DefaultMultiBlockCipher; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestFailedException; + /** * basic test class for a block cipher, basically this just exercises the provider, and makes sure we * are behaving sensibly, correctness of the implementation is shown in the lightweight test classes. @@ -842,6 +848,61 @@ else if (algorithm.startsWith("RC5")) fail("" + algorithm + " failed encryption - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(bytes))); } + // + // Try the doFinal - same input/output same index, index + // + byte[] data = Arrays.concatenate(input, new byte[2 * in.getBlockSize()]); + int len = 0; + try + { + if (algorithm.indexOf("GCM") > 0) + { + out = Cipher.getInstance(algorithm, "BC"); + out.init(Cipher.ENCRYPT_MODE, key, rand); + } + + len = out.doFinal(data, 0, input.length, data, 0); + } + catch (Exception e) + { + fail(e.toString()); + } + + if (!Arrays.areEqual(data, 0, len, output, 0, output.length)) + { + fail("" + algorithm + " failed doFinal - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(data))); + } + + // + // Try the doFinal - same input/output shifted offset + // + data = Arrays.concatenate(input, new byte[2 * in.getBlockSize()]); + len = 0; + try + { + + if (algorithm.indexOf("GCM") > 0) + { + out = Cipher.getInstance(algorithm, "BC"); + out.init(Cipher.ENCRYPT_MODE, key, rand); + } + + len = out.doFinal(data, 0, input.length, data, 1); + +// System.out.println(Hex.toHexString(output)); +// System.out.println(Hex.toHexString(Arrays.copyOfRange(data, 1, 1 + len))); +// System.out.println(len + " " + output.length); + } + catch (Exception e) + { + fail(e.toString()); + } + + if (!Arrays.areEqual(data, 1, 1 + len, output, 0, output.length)) + { + fail("" + algorithm + " failed doFinal - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(data))); + } + // // decryption pass // @@ -1738,6 +1799,159 @@ public void performTest() testExceptions(); testIncorrectCipherModes(); + doFinalTest(); + testOverlapping(); + testOverlapping2(); + testOverlap(); + } + + private void doFinalTest() + { + try + { + int INPUT_LENGTH = 32; + int offset = 1; + byte[] PT = new byte[INPUT_LENGTH + offset]; + SecretKey KEY = new SecretKeySpec(new byte[16], "AES"); + Cipher c = Cipher.getInstance("AES/ECB/NoPadding", "BC"); + c.init(Cipher.ENCRYPT_MODE, KEY); + int len = c.doFinal(PT, 0, INPUT_LENGTH, PT, offset); + + byte[] expected = Hex.decode("0066e94bd4ef8a2c3b884cfa59ca342b2e66e94bd4ef8a2c3b884cfa59ca342b2e"); + + isTrue("expected not match PT", areEqual(expected, PT)); + } + catch (GeneralSecurityException e) + { + fail(e.toString()); + } + } + + private void testOverlapping() + { + //Skip the dofinal of the test + BufferedBlockCipher bc = new BufferedBlockCipher(AESEngine.newInstance()); + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[16]; + random.nextBytes(keyBytes); + KeyParameter key = new KeyParameter(keyBytes); + + int offset = 2 + random.nextInt(bc.getBlockSize() - 1); + byte[] data = new byte[bc.getBlockSize() * 2 + offset]; + byte[] expected = new byte[bc.getOutputSize(bc.getBlockSize() * 2)]; + random.nextBytes(data); + + bc.init(true, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, expected, 0); + bc.init(true, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + bc.getBlockSize() * 2))) + { + fail("failed for overlapping encryption"); + } + + bc.init(false, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, expected, 0); + bc.init(false, key); + bc.processBytes(data, 0, bc.getBlockSize() * 2 + 1, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + bc.getBlockSize() * 2))) + { + fail("failed for overlapping decryption"); + } + } + + private void testOverlapping2() + { + //Skip the dofinal of the test + DefaultMultiBlockCipher bc = new AESEngine(); + SecureRandom random = new SecureRandom(); + byte[] keyBytes = new byte[16]; + random.nextBytes(keyBytes); + KeyParameter key = new KeyParameter(keyBytes); + + int offset = 2 + random.nextInt(bc.getBlockSize() - 1); + byte[] data = new byte[bc.getBlockSize() * 2 + offset]; + byte[] expected = new byte[bc.getBlockSize() * 2]; + random.nextBytes(data); + + bc.init(true, key); + bc.processBlocks(data, 0, 2, expected, 0); + bc.init(true, key); + bc.processBlocks(data, 0, 2, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + bc.getBlockSize() * 2))) + { + fail("failed to overlapping of encryption"); + } + + bc.init(false, key); + bc.processBlocks(data, 0, 2, expected, 0); + bc.init(false, key); + bc.processBlocks(data, 0, 2, data, offset); + + if (!areEqual(expected, Arrays.copyOfRange(data, offset, offset + bc.getBlockSize() * 2))) + { + fail("failed to overlapping of encryption"); + } + } + + public void testOverlap() + { + try + { + int l = 32; + byte[] msg = new byte[l]; + Arrays.fill(msg, (byte)1); + + byte[] workingArray = new byte[l * 2]; + Arrays.fill(workingArray, (byte)1); + System.arraycopy(msg, 0, workingArray, 0, msg.length); + + byte[] originalWorkingArray = new byte[workingArray.length]; + System.arraycopy(workingArray, 0, originalWorkingArray, 0, workingArray.length); + + Cipher javaEncrypt = Cipher.getInstance("AES/ECB/NoPadding", BouncyCastleProvider.PROVIDER_NAME); + javaEncrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[16], "AES")); + + // + // Expected encryption + // + byte[] expectedOutput = new byte[msg.length]; + javaEncrypt.doFinal(msg, 0, msg.length, expectedOutput, 0); + + + // + // We expect to see the "expectedOutput" being written at each offset. + // + for (int outputOffset = 0; outputOffset < msg.length; outputOffset++) + { + javaEncrypt.doFinal(workingArray, 0, msg.length, workingArray, outputOffset); + + // Grab a copy of the produced cipher text + byte[] ct = Arrays.copyOfRange(workingArray, outputOffset, outputOffset + msg.length); +// System.out.println("\nOutput Offset: " + outputOffset); +// System.out.println("Expected: " + pad(outputOffset * 2) + Hex.toHexString(expectedOutput)); +// System.out.println("Actual : " + Hex.toHexString(workingArray)); + + isTrue(Arrays.areEqual(ct, expectedOutput)); + + System.arraycopy(originalWorkingArray, 0, workingArray, 0, originalWorkingArray.length); + } + } + catch (Exception e) + { + fail(e.getMessage(), e); + } + + } + + public String pad(int len) + { + char[] buf = new char[len]; + Arrays.fill(buf, ' '); + return new String(buf); } public static void main( diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java index 07a1e6b992..8b133f984c 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java @@ -117,6 +117,54 @@ private void v0Test() } } + private void noSigV0Test() + throws Exception + { + // create certificates and CRLs + KeyPair rootPair = TestUtils.generateRSAKeyPair(); + KeyPair interPair = TestUtils.generateRSAKeyPair(); + KeyPair endPair = TestUtils.generateRSAKeyPair(); + + X509Certificate rootCert = TestUtils.generateNoSigRootCert(rootPair); + X509Certificate interCert = TestUtils.generateIntermediateCert(interPair.getPublic(), rootPair.getPrivate(), rootCert); + X509Certificate endCert = TestUtils.generateEndEntityCert(endPair.getPublic(), interPair.getPrivate(), interCert); + + BigInteger revokedSerialNumber = BigInteger.valueOf(2); + X509CRL rootCRL = TestCertificateGen.createCRL(rootCert, rootPair.getPrivate(), revokedSerialNumber); + X509CRL interCRL = TestCertificateGen.createCRL(interCert, interPair.getPrivate(), revokedSerialNumber); + + // create CertStore to support path building + List list = new ArrayList(); + + list.add(rootCert); + list.add(interCert); + list.add(endCert); + list.add(rootCRL); + list.add(interCRL); + + CollectionCertStoreParameters params = new CollectionCertStoreParameters(list); + CertStore store = CertStore.getInstance("Collection", params); + + // build the path + CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); + X509CertSelector pathConstraints = new X509CertSelector(); + + pathConstraints.setSubject(endCert.getSubjectX500Principal().getEncoded()); + + PKIXBuilderParameters buildParams = new PKIXBuilderParameters(Collections.singleton(new TrustAnchor(rootCert, null)), pathConstraints); + + buildParams.addCertStore(store); + buildParams.setDate(new Date()); + + PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(buildParams); + CertPath path = result.getCertPath(); + + if (path.getCertificates().size() != 2) + { + fail("wrong number of certs in v0Test path"); + } + } + private void eeInSelectorTest() throws Exception { @@ -206,10 +254,11 @@ private void eeOnlyInSelectorTest() public void performTest() throws Exception { - baseTest(); - v0Test(); - eeInSelectorTest(); - eeOnlyInSelectorTest(); +// baseTest(); +// v0Test(); + noSigV0Test(); +// eeInSelectorTest(); +// eeOnlyInSelectorTest(); } public String getName() diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java index 896158e7c6..dbcedc5f2a 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java @@ -393,11 +393,157 @@ private void constraintTest() } + private static byte[] crlFake = Base64.decode( + "MIIBzTCBtgIBATANBgkqhkiG9w0BAQsFADAiMQswCQYDVQQGEwJYWDETMBEGA1UE" + + "CgwKQ1JMcyAnciBVcxcNMjQwMzI1MTg0NzAwWhcNMjQwNDAxMTg0NzAwWqBgMF4w" + + "CgYDVR0UBAMCAQEwHwYDVR0jBBgwFoAU/NE0t8uklbG2WeoLBWIe6JqPtDowLwYD" + + "VR0cAQH/BCUwI6AeoByGGmh0dHA6Ly9mb28uZXhhbXBsZS9jcmwuZGxshAH/MA0G" + + "CSqGSIb3DQEBCwUAA4IBAQAN8oDSvWsg3JvUJ4MkXvczaFb72VH0J/VL5PV2cBSm" + + "MfaVBKnUsNr1IcxT06KF8gNrDTpKqJ9fetO290swZfcPt9sEVUBVQUpdlQc3tya1" + + "jYWmFkA3tkpqH5rBCQa3CBm1Cg8cbFBtwWgWr70NsVvfD6etjAEP9Ze+MSXnGV0p" + + "w9EeOV07HnSD/PGQwqCiaSn5DdIDVoH8eFSGmgNLw+b4SwUjmz8PqsZwvHxJvleV" + + "1D8cj7zdR4ywgRMjEfJZ8Bp+Tdu64Gv0doDS0iEJIshLHYkcW1okpq/tPm8kKAbD" + + "reparePNQwhScVcDiSL73eEBIPokgG3QhohiucP5MeF1"); + + private static byte[] crlIssuer = Base64.decode( + "MIIDMzCCAhugAwIBAgIUPOARSBZTC4SU8f/RrhdPXfZVh9EwDQYJKoZIhvcNAQEL\n" + + "BQAwIzELMAkGA1UEBhMCWFgxFDASBgNVBAoMC0NlcnRzICdyIFVzMB4XDTI0MDMy\n" + + "NTE4NDcwMFoXDTI1MDMyNTE4NDcwMFowIjELMAkGA1UEBhMCWFgxEzARBgNVBAoM\n" + + "CkNSTHMgJ3IgVXMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCleY8S\n" + + "gEwPfvfUcIuix5dC7MgFudzaJROINa3u7cW0Rh+mivfepuGl9I683qinDebmE1Sq\n" + + "bVyHDi4RqpM+BCQ0EnW6idriL+13BqNU4QRd68gwF4eNXw9rtmixVGvcvcUngNnz\n" + + "XPrJyWqarjFQ8ECH09I9q/Fv3OAWPmTbzAgWdXV7cx/pCHFNEU3qSWeXkbumKV5l\n" + + "DqTs/J82/n5HZfRjUVIMbf4X6/9wA9BQX8aYbUMng49M5GVd/bg3RXGBLF4lXIUd\n" + + "IPpGYrKT2V+EFq9yKqbnXawTXKw7mBNoIbaN950f1VMdf8czsPNxdeCHJzNtQV70\n" + + "aOqa2hLzxAxzAz7DAgMBAAGjYDBeMB0GA1UdDgQWBBRdiKBrVfofgq1XL7AZu3Wk\n" + + "t83qzjAfBgNVHSMEGDAWgBS04fYwVDNa70uNyIJtV75OHwEHmTAMBgNVHRMBAf8E\n" + + "AjAAMA4GA1UdDwEB/wQEAwIBAjANBgkqhkiG9w0BAQsFAAOCAQEAF5XrOXxVfCFb\n" + + "S5EXxpAk8iXMAOfcfYiWEUT9DdJ3ABeAFnhbiLdlKq8J3BGr1Iiveo2pE9fKz9s/\n" + + "2tZjzbe9Kfg05mfyn9DS5AoWjieW5zaAZpDR9pKkq9/d7pDTbHwvDnNLoMMHRPZP\n" + + "2tsBhjcPPay8zWKLz+8dfPyrGpbGfFg/zd3KBNefc12Sl0Iw6XQUaIpDxyJBvpIU\n" + + "0Xo1R1F22gJ7oG1zI28mr6SGyBvJ8r1c0sQ1qQt+iA/0M5qXRjuLIhO8/ajlMQwP\n" + + "Sdasa53HOErxWqsxNRpwJkaynSiKSwGeqLxdTYwWcWrsYB7RqKgjbQnhSBSd3TKm\n" + + "H2P790A+oQ=="); + + private static byte[] crlSecretary = Base64.decode( + "MIIDejCCAmKgAwIBAgIUI4Xq9G+KWEr2NPfGbY4A2dfXp50wDQYJKoZIhvcNAQEL\n" + + "BQAwIzELMAkGA1UEBhMCWFgxFDASBgNVBAoMC0NlcnRzICdyIFVzMB4XDTI0MDMy\n" + + "NTE4NDcwMFoXDTI1MDMyNTE4NDcwMFowIjELMAkGA1UEBhMCWFgxEzARBgNVBAoM\n" + + "CkNSTHMgJ3IgVXMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCkynb7\n" + + "zm0ooFfVkkqj9ppBiTh0YGUqv7/jQoFMDJ/XVtYGUJdyPTXoD9cP1ZypzONmK07U\n" + + "Rc0WMug47hv2tZgrVOxqrGQqDD7e4LM3luinwG5eW3XYT4eJr6Urbk8KSdKSYzqj\n" + + "wjY217KQ8DDgioUInWBUyz5UWrG014QbcEgwX0JGpQrwaaPQtbUd58f5x/LCdsXC\n" + + "p41ySSNsYoKhDawnNblLVxhr+Vp7eQ0wj7LaD/+k12ZDMQbkj3PsGBiWqm+e2uwV\n" + + "n9cq9kK6ARN0svju5dpDw5hERRrQ1GR87WvHWHUtmnR7s7+xacRpZTUvJ5Xsi0Rf\n" + + "Eq1SDPYPyT8ksrt7AgMBAAGjgaYwgaMwHQYDVR0OBBYEFPzRNLfLpJWxtlnqCwVi\n" + + "Huiaj7Q6MB8GA1UdIwQYMBaAFLTh9jBUM1rvS43Igm1Xvk4fAQeZMAwGA1UdEwEB\n" + + "/wQCMAAwUwYDVR0fBEwwSjBIoB6gHIYaaHR0cDovL2Zvby5leGFtcGxlL2NybC5k\n" + + "bGyiJqQkMCIxCzAJBgNVBAYTAlhYMRMwEQYDVQQKDApDUkxzICdyIFVzMA0GCSqG\n" + + "SIb3DQEBCwUAA4IBAQBY72Z1LwWsVbnYl6ZhWDAAuy0bwTMKwF8JwpG1PpFzC6p0\n" + + "DJd36c3ZOzRYgjpmApi3X9lFx0oyuZOjBIlMtqnXgKjYBytF2jmf8DziIsCnvMI8\n" + + "1IiFRjWjm56y0xaxBqv9yzvTqKG198vxakxPAUn8oONMtLvqHAvoQyHCBej5Xirg\n" + + "joJkPeHeRwl9sgYZcqowNHGHiBX8KtXeatkHkpmxZO5cunGD+RcOnBpJEfZJhopX\n" + + "GaW1DPRY0qqPFhnLcQsv8UZEyDxyYH/HuGaZy3u9lT1SqlOx2zzQnTK6EyIc92n3\n" + + "suILIm4MBrqXYXUlHkMzLmpJGH9lg9xaFn3vCU7Q"); + + private static byte[] crlRoot = Base64.decode( + "MIIDFjCCAf6gAwIBAgIUF/hP3a/TkmHlfhYYUiFNw/H5lMwwDQYJKoZIhvcNAQEL\n" + + "BQAwIzELMAkGA1UEBhMCWFgxFDASBgNVBAoMC0NlcnRzICdyIFVzMB4XDTI0MDMy\n" + + "NTE4NDcwMFoXDTI1MDMyNTE4NDcwMFowIzELMAkGA1UEBhMCWFgxFDASBgNVBAoM\n" + + "C0NlcnRzICdyIFVzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAomfH\n" + + "KuGQzqGkFGSsKLESgJbRRRQsIuJ19w/sumNHNPnbl93rEgdoF1y2yUFcY0ZipZCg\n" + + "lIpfhOkp6I+WLtF59t8vLw30P1ZBwmbjC54EwGLH3WRDPS0j+33TfDjNdQRwY4u6\n" + + "j2EK6drXPhBPsaG0map3VfWQelaStAoIC6evoYFzfO2E7Ik4xv06U47WHefseBue\n" + + "ZcsFvfW3bf/E04PFc2YssUyqjiaa0sU/w7l9xj2P+vCqpM393ZWJX6GRcns/wUJ/\n" + + "na7iXpIO82EV3/eExeXoHc912L+m0HoB86RYQat+wyhX6Z5i1ApU6zXqGU7D8cPD\n" + + "DrbIjwLDMwKPbC9FjwIDAQABo0IwQDAdBgNVHQ4EFgQUtOH2MFQzWu9LjciCbVe+\n" + + "Th8BB5kwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAgQwDQYJKoZIhvcN\n" + + "AQELBQADggEBAJGeqkMrzOgesGaCHJJgX/qpG7bp4KPPL0bi7EYnT1cuy5ss053I\n" + + "Ooh5APYn+GrufWjYn4mwSekvuRTB6VdR4YMeoYPMxWJRp3l7s0aHLo98BbW9WX+4\n" + + "ju+K/Dndbrs1v7r4IB79hu4QtR7BVaEQ8UjqY+/I1VeYKtAd7scQGKpSNOPN3YVu\n" + + "+QY3fXy+nfDhj7drUeAHVj+Qz/6RZOIhmIPj7adsZhDQwvMG3cAkAfVGncP7n+cN\n" + + "nqZyYu8PPQp4g+QM42kXXBu5N8QwkCtcMe2nvKiQvEOZww70N3mTIK8CSxLla5pI\n" + + "635lNPBZubGF6m35P7EArB0JuU2KYNgUxis=\n"); + + private static byte[] crlVictim = Base64.decode( + "MIIDjTCCAnWgAwIBAgIUW8wsCzJEg7WzpMvkUKyloeKqKLYwDQYJKoZIhvcNAQEL\n" + + "BQAwIzELMAkGA1UEBhMCWFgxFDASBgNVBAoMC0NlcnRzICdyIFVzMB4XDTI0MDMy\n" + + "NTE4NDcwMFoXDTI1MDMyNTE4NDcwMFowJTELMAkGA1UEBhMCWFgxFjAUBgNVBAoM\n" + + "DVVubHVja3kgJ3IgV2UwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6\n" + + "erJm/+hf6IhoqCYfX+y6uiVSSF/J6VyENk+oXS2g71g1sapGCXRO8xlDqH1rhFzC\n" + + "IJ56nC14K9w4r+6D3FUKw4G5sKMRTMX7U5brjd8wRd3XHAIUdSCP9SVrNz6bmcjf\n" + + "B27vBT0ifIC7bQg7Y01BoqnBPObuwT7ufk951rFzCIagzSylzR/GRNhMYo4rO6jw\n" + + "Ih84LpAxUQ1vFAaBb5GCVhXoUWecu+RtIaIDo9tn8PF16O6VW8zPmsoV9HELD8Sx\n" + + "HuoSXXcsF2OW55XLeAO+l1tikAVqA6nUvQx03bb3TW7W+3v6nGzG308fHA32TdLk\n" + + "ZLK9nPnF5hF4pFmWpjwHAgMBAAGjgbYwgbMwHQYDVR0OBBYEFMitbC8lM9mw/hc6\n" + + "TnvL5vpAyfpZMB8GA1UdIwQYMBaAFLTh9jBUM1rvS43Igm1Xvk4fAQeZMAwGA1Ud\n" + + "EwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMFMGA1UdHwRMMEowSKAeoByGGmh0dHA6\n" + + "Ly9mb28uZXhhbXBsZS9jcmwuZGxsoiakJDAiMQswCQYDVQQGEwJYWDETMBEGA1UE\n" + + "CgwKQ1JMcyAnciBVczANBgkqhkiG9w0BAQsFAAOCAQEAmysx1oqEUDUpLg98K9Rw\n" + + "AXTykVDjjG0ZKg7UtDcaIeBfomhXv+Sh2oz9zqqZQ5/4HGIwe2fAsbQZmlH//8Yb\n" + + "ovEZCo3WmhJSyTDB2KLebPJLw5HOi7QrAjYJWKR+pkuQmxMPoSAdMXRkiBmzYjZL\n" + + "lxHaT6Y2IMZ6kVtHCmcOFaHWJyPAUZ4ymO03cb/1M73ioecf9jMgIf7YBaopty2p\n" + + "X2GVHaCE1m7u+2WU45b34PBRY/ZvhZvuJKi3TfuaLMJFPz6HY4XbHPnlBP4EwXpC\n" + + "5VaJvOMXWZPWh/yrCVEKMzFxesbwHV/vyOUls0P4kIY383/78MvzchHLhwR7h2fy\n" + + "Iw=="); + + private void testNoKeyUsageCRLSigner() + throws Exception + { + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + + X509Certificate root = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(crlRoot)); + X509Certificate crlIss = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(crlIssuer)); + X509Certificate secretary = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(crlSecretary)); + X509Certificate victim = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(crlVictim)); + + X509CRL fakeCrl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(crlFake)); + + List list = new ArrayList(); + +// list.add(root); +// list.add(crlIss); + list.add(secretary); + list.add(victim); + list.add(fakeCrl); + + System.setProperty("org.bouncycastle.x509.allow_ca_without_crl_sign", "false"); + + CertPath cp = cf.generateCertPath(Collections.singletonList(victim)); + + CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); + CertStore store = CertStore.getInstance("Collection", ccsp, "BC"); + Date validDate = new Date(fakeCrl.getThisUpdate().getTime() + 60 * 60 * 1000); + + //Searching for rootCert by subjectDN without CRL + Set trust = new HashSet(); + trust.add(new TrustAnchor(root, null)); + // + CertPathValidator cpb = CertPathValidator.getInstance("PKIX", "BC"); + X509CertSelector targetConstraints = new X509CertSelector(); + targetConstraints.setSubject(victim.getSubjectX500Principal().getEncoded()); + PKIXParameters params = new PKIXParameters(trust); + params.addCertStore(store); + params.setDate(validDate); + + try + { + PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)cpb.validate(cp, params); + fail("path should have failed"); + } + catch (CertPathValidatorException e) + { + isTrue("No CRLs found for issuer \"o=Certs 'r Us,c=XX\"".equals(e.getMessage())); + } + + System.setProperty("org.bouncycastle.x509.allow_ca_without_crl_sign", "true"); + } + public void performTest() throws Exception { constraintTest(); - + testNoKeyUsageCRLSigner(); CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); // initialise CertStore @@ -431,6 +577,8 @@ public void performTest() MyChecker checker = new MyChecker(); param.addCertPathChecker(checker); + System.setProperty("org.bouncycastle.x509.allow_ca_without_crl_sign", "true"); + PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)cpv.validate(cp, param); PolicyNode policyTree = result.getPolicyTree(); @@ -463,6 +611,8 @@ public void performTest() result = (PKIXCertPathValidatorResult)cpv.validate(cp, param); + System.setProperty("org.bouncycastle.x509.allow_ca_without_crl_sign", "false"); + isTrue(result.getTrustAnchor().getTrustedCert().equals(rootCert)); // @@ -514,6 +664,8 @@ public void performTest() } } + System.setProperty("org.bouncycastle.x509.allow_ca_without_crl_sign", "true"); + checkCircProcessing(); checkPolicyProcessingAtDomainMatch(); validateWithExtendedKeyUsage(); @@ -1799,13 +1951,7 @@ public ASN1Primitive toASN1Primitive() // // before and after dates // - { - ASN1EncodableVector validity = new ASN1EncodableVector(2); - validity.add(startDate); - validity.add(endDate); - - v.add(new DERSequence(validity)); - } + v.add(new DERSequence(startDate, endDate)); if (subject != null) { @@ -1839,7 +1985,7 @@ public ASN1Primitive toASN1Primitive() } } - public class DodgyExtensions + public static class DodgyExtensions extends ASN1Object { private Hashtable extensions = new Hashtable(); diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/DESedeTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/DESedeTest.java index 684fb17335..416e0cb55b 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/DESedeTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/DESedeTest.java @@ -19,6 +19,7 @@ import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; @@ -79,50 +80,11 @@ public String getName() return "DESEDE"; } - private boolean equalArray( - byte[] a, - byte[] b) + private static boolean equalPrefix(byte[] a, byte[] b, int length) { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - private boolean equalArray( - byte[] a, - byte[] b, - int length) - { - if (a.length < length) - { - return false; - } - - if (b.length < length) - { - return false; - } - - for (int i = 0; i != length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; + return a.length >= length + && b.length >= length + && Arrays.areEqual(a, 0, length, b, 0, length); } private void wrapTest( @@ -142,7 +104,7 @@ private void wrapTest( try { byte[] cText = wrapper.wrap(new SecretKeySpec(in, alg)); - if (!equalArray(cText, out)) + if (!Arrays.areEqual(cText, out)) { fail("failed wrap test " + id + " expected " + new String(Hex.encode(out)) + " got " + new String(Hex.encode(cText))); } @@ -157,7 +119,7 @@ private void wrapTest( try { Key pText = wrapper.unwrap(out, alg, Cipher.SECRET_KEY); - if (!equalArray(pText.getEncoded(), in)) + if (!Arrays.areEqual(pText.getEncoded(), in)) { fail("failed unwrap test " + id + " expected " + new String(Hex.encode(in)) + " got " + new String(Hex.encode(pText.getEncoded()))); } @@ -242,7 +204,7 @@ public void test( bytes = bOut.toByteArray(); - if (!equalArray(bytes, output)) + if (!Arrays.areEqual(bytes, output)) { fail(alg + " failed encryption - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(bytes))); } @@ -265,13 +227,14 @@ public void test( bytes[i] = (byte)dIn.read(); } dIn.readFully(bytes, input.length / 2, bytes.length - input.length / 2); + dIn.close(); } catch (Exception e) { fail(alg + " failed encryption - " + e.toString()); } - if (!equalArray(bytes, input)) + if (!Arrays.areEqual(bytes, input)) { fail(alg + " failed decryption - expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(bytes))); } @@ -284,7 +247,7 @@ public void test( SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg, "BC"); DESedeKeySpec keySpec = (DESedeKeySpec)keyFactory.getKeySpec((SecretKey)key, DESedeKeySpec.class); - if (!equalArray(key.getEncoded(), keySpec.getKey(), 16)) + if (!equalPrefix(key.getEncoded(), keySpec.getKey(), 16)) { fail(alg + " KeySpec does not match key."); } diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/DetDSATest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/DetDSATest.java index 8e75b474c5..1c4a7cef9b 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/DetDSATest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/DetDSATest.java @@ -14,8 +14,8 @@ import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.encoders.Hex; @@ -78,13 +78,16 @@ private void doTestHMACDetDSATest(String algName, PrivateKey privKey, BigInteger private void testECHMacDeterministic() throws Exception { - X9ECParameters x9ECParameters = NISTNamedCurves.getByName("P-192"); - ECCurve curve = x9ECParameters.getCurve(); + X9ECParameters x9ECParameters = CustomNamedCurves.getByName("P-192"); + ECCurve.AbstractFp curve = (ECCurve.AbstractFp)x9ECParameters.getCurve(); + BigInteger q = curve.getQ(); + + org.bouncycastle.math.ec.ECPoint g = x9ECParameters.getG().normalize(); ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(new BigInteger("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), new ECParameterSpec( - new EllipticCurve(new ECFieldFp(((ECCurve.Fp)curve).getQ()), curve.getA().toBigInteger(), curve.getB().toBigInteger(), null), - new ECPoint(x9ECParameters.getG().getXCoord().toBigInteger(), x9ECParameters.getG().getYCoord().toBigInteger()), + new EllipticCurve(new ECFieldFp(q), curve.getA().toBigInteger(), curve.getB().toBigInteger(), null), + new ECPoint(g.getAffineXCoord().toBigInteger(), g.getAffineYCoord().toBigInteger()), x9ECParameters.getN(), x9ECParameters.getH().intValue()) ); diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/FIPSDESTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/FIPSDESTest.java index 80024d458a..f9af706d6c 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/FIPSDESTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/FIPSDESTest.java @@ -16,6 +16,7 @@ import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; @@ -54,26 +55,6 @@ public String getName() return "FIPSDESTest"; } - private boolean equalArray( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - public TestResult test( String algorithm, byte[] input, @@ -89,8 +70,6 @@ public TestResult test( try { - String baseAlgorithm; - key = new SecretKeySpec(Hex.decode("0123456789abcdef"), "DES"); in = Cipher.getInstance(algorithm, "BC"); @@ -151,7 +130,7 @@ public TestResult test( bytes = bOut.toByteArray(); - if (!equalArray(bytes, output)) + if (!Arrays.areEqual(bytes, output)) { return new SimpleTestResult(false, getName() + ": " + algorithm + " failed encryption - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(bytes))); } @@ -174,13 +153,14 @@ public TestResult test( bytes[i] = (byte)dIn.read(); } dIn.readFully(bytes, input.length / 2, bytes.length - input.length / 2); + dIn.close(); } catch (Exception e) { return new SimpleTestResult(false, getName() + ": " + algorithm + " failed encryption - " + e.toString()); } - if (!equalArray(bytes, input)) + if (!Arrays.areEqual(bytes, input)) { return new SimpleTestResult(false, getName() + ": " + algorithm + " failed decryption - expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(bytes))); } diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/PBETest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/PBETest.java index 7a6791161f..c7ea5a707b 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/PBETest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/PBETest.java @@ -36,6 +36,7 @@ import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; /** @@ -524,6 +525,83 @@ public void testNullSalt() } } + private void testExtendedPBEParameterSpec() + throws Exception + { + String keyAlgo = "PBKDF2WITHHMACSHA512"; + String cipherAlgo = "2.16.840.1.101.3.4.1.2"; + + SecureRandom random = new FixedSecureRandom(Hex.decode( + "000102030405060708090a0b0c0d0e0f" + + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf")); + + char[] password = "abcdefghijklmnop".toCharArray(); + PBEKeySpec pbeKeySpec = new PBEKeySpec(password); + + SecretKeyFactory factory = SecretKeyFactory.getInstance(keyAlgo, "BC"); + SecretKey key = factory.generateSecret(pbeKeySpec); + + byte[] salt = new byte[16]; + random.nextBytes(salt); + byte[] iv = new byte[16]; + random.nextBytes(iv); + + PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 1000, new IvParameterSpec(iv)); + + Cipher encryptCipher = Cipher.getInstance(cipherAlgo, "BC"); + Cipher decryptCipher = Cipher.getInstance(cipherAlgo, "BC"); + + encryptCipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec); + decryptCipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec); + + byte[] input = Strings.toByteArray("testing"); + byte[] encryptedBytes = encryptCipher.doFinal(input); + byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes); + + decryptCipher = Cipher.getInstance(cipherAlgo, "BC"); + decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Hex.decode("8d12394d80835639c2cf7d4703e76cea"), "AES"), pbeParamSpec.getParameterSpec()); + decryptedBytes = decryptCipher.doFinal(encryptedBytes); + + isTrue(Arrays.areEqual(input, decryptedBytes)); + } + + private void testNoIvPBEParameterSpec() + throws Exception + { + String cipherAlgo = "PBEWITHSHA256AND256BITAES-CBC-BC"; + + SecureRandom random = new FixedSecureRandom(Hex.decode( + "000102030405060708090a0b0c0d0e0f" + + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf")); + + char[] password = "abcdefghijklmnop".toCharArray(); + PBEKeySpec pbeKeySpec = new PBEKeySpec(password); + + SecretKeyFactory factory = SecretKeyFactory.getInstance( + "PBEWITHSHA256AND256BITAES-CBC-BC", + "BC"); + SecretKey key = factory.generateSecret(pbeKeySpec); + + byte[] salt = new byte[16]; + random.nextBytes(salt); + // simulate the situation for issue #1985 + byte[] iv = new byte[0]; + + PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 1000, new IvParameterSpec(iv)); + + Cipher encryptCipher = Cipher.getInstance(cipherAlgo, "BC"); + Cipher decryptCipher = Cipher.getInstance(cipherAlgo, "BC"); + + encryptCipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec); + decryptCipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec); + + byte[] input = Strings.toByteArray("testing"); + byte[] encryptedBytes = encryptCipher.doFinal(input); + byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes); + + isTrue(Arrays.areEqual(input, decryptedBytes)); + } + public void performTest() throws Exception { @@ -668,6 +746,8 @@ public void performTest() openSSLTests[i].perform(); } + testExtendedPBEParameterSpec(); + testNoIvPBEParameterSpec(); testPKCS12Interop(); testPBEHMac("PBEWithHMacSHA1", hMac1); diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java index 05d2ff588e..3bfc031ef6 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java @@ -2,7 +2,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.Key; @@ -21,8 +20,6 @@ import java.security.spec.RSAPublicKeySpec; import java.util.Enumeration; -import javax.swing.KeyStroke; - import org.bouncycastle.asn1.ASN1BMPString; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1InputStream; @@ -48,12 +45,12 @@ import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.internal.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.jcajce.PKCS12StoreParameter; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; import org.bouncycastle.jce.PKCS12Util; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.provider.JDKPKCS12StoreParameter; import org.bouncycastle.jce.provider.X509CertificateObject; -import org.bouncycastle.pqc.jcajce.spec.DilithiumParameterSpec; import org.bouncycastle.pqc.jcajce.spec.FalconParameterSpec; import org.bouncycastle.pqc.jcajce.spec.NTRUParameterSpec; import org.bouncycastle.pqc.jcajce.spec.SPHINCSPlusParameterSpec; @@ -946,6 +943,361 @@ public class PKCS12StoreTest private static byte[] rawKeyBagStore = Base64.decode("MIIFlgIBAzCCBY8GCSqGSIb3DQEHAaCCBYAEggV8MIIFeDCCAv4GCSqGSIb3DQEHAaCCAu8EggLrMIIC5zCCAuMGCyqGSIb3DQEMCgEBoIICejCCAnYCAQAwDQYJKoZIhvcNAQEBBQAEggJgMIICXAIBAAKBgQCF4Tw78b8eDuwY+FomQazkPFuAxDbWTs//AozC4MvzBatdJeDu+s9WyK3PdU+gI7wFish0r2FP8M5dj/rA0ieCJ9UDTGWVKm06DB0y7zmAO3SS/3TXGQRekMmOXBtVlZa4AYVy8Tr+Ls69gfo3sgqJU8uH0ebWuoQTKJz/mpst0wIDAQABAoGBAIJbpu/jWylkdEV4BSd9CWCO2LYP2CliQirXC8JxaoTuf0ZKrLNlqd+htYPsgSS3xstKsBbV8hYJrpbxq8J2npok973j0bm9sW9RL8XmAYJbaat27IzQQkGj2j4CNWPJzQC3NsDWQJPMJMFHvT1ZIj5ASwvOHwKpM6haLPxX24o5AkEA/zBVPpO6Ic9Yfd8Fk+BN/DykpPbLMUNZFl/I2MavoXTh5Ng7J4/S5ABxkvvQdqKf1Nhal5CznakU4BjFUGr+dwJBAIZOLwlfToFgekV4SmcPnq4aNGdetDfEettRGJLrKf+qrZrTzW3Rj6N2cjxKHsE5/xOpyjOtgVv3cTQm0x//VoUCQAdQBUFTzmOlo22H9Ir2RIXT3wvzHoN84JKpkAHWP7YquUZrg9ZwYqSx9o81tBWSN25L/NyXAu6jp7t8OjtBtaUCQCILB1k0001wCw4444MkLnCrK8VX+A56uzmEYNo8ybSIquCn91Zy3BnvGB24G/uWm9V8IEjhHf0Vx5gUj0d5DZECQGRs4BMYE+y2Tpn7/zbjhZh/iAdttDq5/b2BBMbSiosSKRIGkOyHTu0SJKoxoDnHA5ryLK8NoSwoGjID5qESjA8xVjAjBgkqhkiG9w0BCRUxFgQU3U3Taaj7rCAV2GyyVEnAUZvc4JkwLwYJKoZIhvcNAQkUMSIeIABPAE4AVgBJAEYAXwBUAGUAcwB0AF8AQQBsAGkAYQBzMIICcgYJKoZIhvcNAQcBoIICYwSCAl8wggJbMIICVwYLKoZIhvcNAQwKAQOgggHuMIIB6gYKKoZIhvcNAQkWAaCCAdoEggHWMIIB0jCCATugAwIBAgIICNurBKCCK6gwDQYJKoZIhvcNAQEFBQAwIDERMA8GA1UEAwwIT05WSUYgVFQxCzAJBgNVBAYTAlVTMCAXDTcwMDEwMTAwMDAwMFoYDzk5OTkxMjMxMjM1OTU5WjAgMREwDwYDVQQDDAhPTlZJRiBUVDELMAkGA1UEBhMCVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIXhPDvxvx4O7Bj4WiZBrOQ8W4DENtZOz/8CjMLgy/MFq10l4O76z1bIrc91T6AjvAWKyHSvYU/wzl2P+sDSJ4In1QNMZZUqbToMHTLvOYA7dJL/dNcZBF6QyY5cG1WVlrgBhXLxOv4uzr2B+jeyColTy4fR5ta6hBMonP+amy3TAgMBAAGjEzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEARmnQ9q/lUycK5P4shGFlwK0Uy3dHZs4VxOBSinejSTTy1FL4+SRzwA+YDMmfRrI0WHY/upUCYyugDj5kDg5K6/mSiIWGr0PDjl+8qw352fpUQgY4vnpGBaJoLQf/KRFilVhZJz0QDq5iHo16UkibDDHYQqdt6la5SHKx4U6AJwYxVjAjBgkqhkiG9w0BCRUxFgQU3U3Taaj7rCAV2GyyVEnAUZvc4JkwLwYJKoZIhvcNAQkUMSIeIABPAE4AVgBJAEYAXwBUAGUAcwB0AF8AQQBsAGkAYQBz"); + // Valid PKCS #12 File with SHA-256 HMAC and PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a1 = Base64.decode( + "MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhvRzw4sC4xcwICCAACASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQITk9UIFVTRUQCAQE=\n"); + + // Valid PKCS #12 File with SHA-256 HMAC and SHA-512 PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a2 = Base64.decode("MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAi4j6UBBY2iOgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEFpHSS5zrk/9pkDo1JRbtE6AggPgtbMLGoFd5KLpVXMdcxLrT129L7/vCr0B\n" + + "0I2tnhPPA7aFtRjjuGbwooCMQwxw9qzuCX1eH4xK2LUw6Gbd2H47WimSOWJMaiUb\n" + + "wy4alIWELYufe74kXPmKPCyH92lN1hqu8s0EGhIl7nBhWbFzow1+qpIc9/lpujJo\n" + + "wodSY+pNBD8oBeoU1m6DgOjgc62apL7m0nwavDUqEt7HAqtTBxKxu/3lpb1q8nbl\n" + + "XLTqROax5feXErf+GQAqs24hUJIPg3O1eCMDVzH0h5pgZyRN9ZSIP0HC1i+d1lnb\n" + + "JwHyrAhZv8GMdAVKaXHETbq8zTpxT3UE/LmH1gyZGOG2B21D2dvNDKa712sHOS/t\n" + + "3XkFngHDLx+a9pVftt6p7Nh6jqI581tb7fyc7HBV9VUc/+xGgPgHZouaZw+I3PUz\n" + + "fjHboyLQer22ndBz+l1/S2GhhZ4xLXg4l0ozkgn7DX92S/UlbmcZam1apjGwkGY/\n" + + "7ktA8BarNW211mJF+Z+hci+BeDiM7eyEguLCYRdH+/UBiUuYjG1hi5Ki3+42pRZD\n" + + "FZkTHGOrcG6qE2KJDsENj+RkGiylG98v7flm4iWFVAB78AlAogT38Bod40evR7Ok\n" + + "c48sOIW05eCH/GLSO0MHKcttYUQNMqIDiG1TLzP1czFghhG97AxiTzYkKLx2cYfs\n" + + "pgg5PE9drq1fNzBZMUmC2bSwRhGRb5PDu6meD8uqvjxoIIZQAEV53xmD63umlUH1\n" + + "jhVXfcWSmhU/+vV/IWStZgQbwhF7DmH2q6S8itCkz7J7Byp5xcDiUOZ5Gpf9RJnk\n" + + "DTZoOYM5iA8kte6KCwA+jnmCgstI5EbRbnsNcjNvAT3q/X776VdmnehW0VeL+6k4\n" + + "z+GvQkr+D2sxPpldIb5hrb+1rcp9nOQgtpBnbXaT16Lc1HdTNe5kx4ScujXOWwfd\n" + + "Iy6bR6H0QFq2SLKAAC0qw4E8h1j3WPxll9e0FXNtoRKdsRuX3jzyqDBrQ6oGskkL\n" + + "wnyMtVjSX+3c9xbFc4vyJPFMPwb3Ng3syjUDrOpU5RxaMEAWt4josadWKEeyIC2F\n" + + "wrS1dzFn/5wv1g7E7xWq+nLq4zdppsyYOljzNUbhOEtJ2lhme3NJ45fxnxXmrPku\n" + + "gBda1lLf29inVuzuTjwtLjQwGk+usHJm9R/K0hTaSNRgepXnjY0cIgS+0gEY1/BW\n" + + "k3+Y4GE2JXds2cQToe5rCSYH3QG0QTyUAGvwX6hAlhrRRgUG3vxtYSixQ3UUuwzs\n" + + "eQW2SUFLl1611lJ7cQwFSPyr0sL0p81vdxWiigwjkfPtgljZ2QpmzR5rX2xiqItH\n" + + "Dy4E+iVigIYwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhDiwsh\n" + + "4wt3aAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEELNFnEpJT65wsXwd\n" + + "fZ1g56cEggTQRo04bP/fWfPPZrTEczq1qO1HHV86j76Sgxau2WQ9OQAG998HFtNq\n" + + "NxO8R66en6QFhqpWCI73tSJD+oA29qOsT+Xt2bR2z5+K7D4QoiXuLa3gXv62VkjB\n" + + "0DLCHAS7Mu+hkp5OKCpXCS7fo0OnAiQjM4EluAsiwwLrHu7z1E16UwpmlgKQnaC1\n" + + "S44fV9znS9TxofRTnuCq1lupdn2qQjSydOU6inQeKLBflKRiLrJHOobaFmjWwp1U\n" + + "OQAMuZrALhHyIbOFXMPYk3mmU/1UPuRGcbcV5v2Ut2UME+WYExXSCOYR3/R4UfVk\n" + + "IfEzeRPFs2slJMIDS2fmMyFkEEElBckhKO9IzhQV3koeKUBdM066ufyax/uIyXPm\n" + + "MiB9fAqbQQ4jkQTT80bKkBAP1Bvyg2L8BssstR5iCoZgWnfA9Uz4RI5GbRqbCz7H\n" + + "iSkuOIowEqOox3IWbXty5VdWBXNjZBHpbE0CyMLSH/4QdGVw8R0DiCAC0mmaMaZq\n" + + "32yrBR32E472N+2KaicvX31MwB/LkZN46c34TGanL5LJZx0DR6ITjdNgP8TlSSrp\n" + + "7y2mqi7VbKp/C/28Cj5r+m++Gk6EOUpLHsZ2d2hthrr7xqoPzUAEkkyYWedHJaoQ\n" + + "TkoIisZb0MGlXb9thjQ8Ee429ekfjv7CQfSDS6KTE/+mhuJ33mPz1ZcIacHjdHhE\n" + + "6rbrKhjSrLbgmrGa8i7ezd89T4EONu0wkG9KW0wM2cn5Gb12PF6rxjTfzypG7a50\n" + + "yc1IJ2Wrm0B7gGuYpVoCeIohr7IlxPYdeQGRO/SlzTd0xYaJVm9FzJaMNK0ZqnZo\n" + + "QMEPaeq8PC3kMjpa8eAiHXk9K3DWdOWYviGVCPVYIZK6Cpwe+EwfXs+2hZgZlYzc\n" + + "vpUWg60md1PD4UsyLQagaj37ubR6K4C4mzlhFx5NovV/C/KD+LgekMbjCtwEQeWy\n" + + "agev2l9KUEz73/BT4TgQFM5K2qZpVamwmsOmldPpekGPiUCu5YxYg/y4jUKvAqj1\n" + + "S9t4wUAScCJx8OvXUfgpmS2+mhFPBiFps0M4O3nWG91Q6mKMqbNHPUcFDn9P7cUh\n" + + "s1xu3NRLyJ+QIfVfba3YBTV8A6WBYEmL9lxf1uL1WS2Bx6+Crh0keyNUPo9cRjpx\n" + + "1oj/xkInoc2HQODEkvuK9DD7VrLr7sDhfmJvr1mUfJMQ5/THk7Z+E+NAuMdMtkM2\n" + + "yKXxghZAbBrQkU3mIW150i7PsjlUw0o0/LJvQwJIsh6yeJDHY8mby9mIdeP3LQAF\n" + + "clYKzNwmgwbdtmVAXmQxLuhmEpXfstIzkBrNJzChzb2onNSfa+r5L6XEHNHl7wCw\n" + + "TuuV/JWldNuYXLfVfuv3msfSjSWkv6aRtRWIvmOv0Qba2o05LlwFMd1PzKM5uN4D\n" + + "DYtsS9A6yQOXEsvUkWcLOJnCs8SkJRdXhJTxdmzeBqM1JttKwLbgGMbpjbxlg3ns\n" + + "N+Z+sEFox+2ZWOglgnBHj0mCZOiAC8wqUu+sxsLT4WndaPWKVqoRQChvDaZaNOaN\n" + + "qHciF9HPUcfZow+fH8TnSHneiQcDe6XcMhSaQ2MtpY8/jrgNKguZt22yH9gw/VpT\n" + + "3/QOB7FBgKFIEbvUaf3nVjFIlryIheg+LeiBd2isoMNNXaBwcg2YXukxJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAgUr2yP+/DBrgICCAACASAwDAYIKoZIhvcNAgsF\n" + + "ADAMBggqhkiG9w0CCQUABCA5zFL93jw8ItGlcbHKhqkNwbgpp6layuOuxSju4/Vd\n" + + "6QQITk9UIFVTRUQCAQE="); + + // Valid PKCS #12 File with SHA-512 HMAC and PRF + private static final byte[] pkcs12WithPBMac1PBKdf2_a3 = Base64.decode("MIIKrAIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAisrqL8obSBaQICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEECjXYYca0pwsgn1Imb9WqFGAggPgT7RcF5YzEJANZU9G3tSdpCHnyWatTlhm\n" + + "iCEcBGgwI5gz0+GoX+JCojgYY4g+KxeqznyCu+6GeD00T4Em7SWme9nzAfBFzng0\n" + + "3lYCSnahSEKfgHerbzAtq9kgXkclPVk0Liy92/buf0Mqotjjs/5o78AqP86Pwbj8\n" + + "xYNuXOU1ivO0JiW2c2HefKYvUvMYlOh99LCoZPLHPkaaZ4scAwDjFeTICU8oowVk\n" + + "LKvslrg1pHbfmXHMFJ4yqub37hRtj2CoJNy4+UA2hBYlBi9WnuAJIsjv0qS3kpLe\n" + + "4+J2DGe31GNG8pD01XD0l69OlailK1ykh4ap2u0KeD2z357+trCFbpWMMXQcSUCO\n" + + "OcVjxYqgv/l1++9huOHoPSt224x4wZfJ7cO2zbAAx/K2CPhdvi4CBaDHADsRq/c8\n" + + "SAi+LX5SCocGT51zL5KQD6pnr2ExaVum+U8a3nMPPMv9R2MfFUksYNGgFvS+lcZf\n" + + "R3qk/G9iXtSgray0mwRA8pWzoXl43vc9HJuuCU+ryOc/h36NChhQ9ltivUNaiUc2\n" + + "b9AAQSrZD8Z7KtxjbH3noS+gjDtimDB0Uh199zaCwQ95y463zdYsNCESm1OT979o\n" + + "Y+81BWFMFM/Hog5s7Ynhoi2E9+ZlyLK2UeKwvWjGzvcdPvxHR+5l/h6PyWROlpaZ\n" + + "zmzZBm+NKmbXtMD2AEa5+Q32ZqJQhijXZyIji3NS65y81j/a1ZrvU0lOVKA+MSPN\n" + + "KU27/eKZuF1LEL6qaazTUmpznLLdaVQy5aZ1qz5dyCziKcuHIclhh+RCblHU6XdE\n" + + "6pUTZSRQQiGUIkPUTnU9SFlZc7VwvxgeynLyXPCSzOKNWYGajy1LxDvv28uhMgNd\n" + + "WF51bNkl1QYl0fNunGO7YFt4wk+g7CQ/Yu2w4P7S3ZLMw0g4eYclcvyIMt4vxXfp\n" + + "VTKIPyzMqLr+0dp1eCPm8fIdaBZUhMUC/OVqLwgnPNY9cXCrn2R1cGKo5LtvtjbH\n" + + "2skz/D5DIOErfZSBJ8LE3De4j8MAjOeC8ia8LaM4PNfW/noQP1LBsZtTDTqEy01N\n" + + "Z5uliIocyQzlyWChErJv/Wxh+zBpbk1iXc2Owmh2GKjx0VSe7XbiqdoKkONUNUIE\n" + + "siseASiU/oXdJYUnBYVEUDJ1HPz7qnKiFhSgxNJZnoPfzbbx1hEzV+wxQqNnWIqQ\n" + + "U0s7Jt22wDBzPBHGao2tnGRLuBZWVePJGbsxThGKwrf3vYsNJTxme5KJiaxcPMwE\n" + + "r+ln2AqVOzzXHXgIxv/dvK0Qa7pH3AvGzcFjQChTRipgqiRrLor0//8580h+Ly2l\n" + + "IFo7bCuztmcwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAi1c7S5\n" + + "IEG77wICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEN6rzRtIdYxqOnY+\n" + + "aDS3AFYEggTQNdwUoZDXCryOFBUI/z71vfoyAxlnwJLRHNXQUlI7w0KkH22aNnSm\n" + + "xiaXHoCP1HgcmsYORS7p/ITi/9atCHqnGR4zHmePNhoMpNHFehdjlUUWgt004vUJ\n" + + "5ZwTdXweM+K4We6CfWA/tyvsyGNAsuunel+8243Zsv0mGLKpjA+ZyALt51s0knmX\n" + + "OD2DW49FckImUVnNC5LmvEIAmVC/ZNycryZQI+2EBkJKe+BC3834GexJnSwtUBg3\n" + + "Xg33ZV7X66kw8tK1Ws5zND5GQAJyIu47mnjZkIWQBY+XbWowrBZ8uXIQuxMZC0p8\n" + + "u62oIAtZaVQoVTR1LyR/7PISFW6ApwtbTn6uQxsb16qF8lEM0S1+x0AfJY6Zm11t\n" + + "yCqbb2tYZF+X34MoUkR/IYC/KCq/KJdpnd8Yqgfrwjg8dR2WGIxbp2GBHq6BK/DI\n" + + "ehOLMcLcsOuP0DEXppfcelMOGNIs+4h4KsjWiHVDMPsqLdozBdm6FLGcno3lY5FO\n" + + "+avVrlElAOB+9evgaBbD2lSrEMoOjAoD090tgXXwYBEnWnIpdk+56cf5IpshrLBA\n" + + "/+H13LBLes+X1o5dd0Mu+3abp5RtAv7zLPRRtXkDYJPzgNcTvJ2Wxw2C+zrAclzZ\n" + + "7IRdcLESUa4CsN01aEvQgOtkCNVjSCtkJGP0FstsWM4hP7lfSB7P2tDL+ugy6GvB\n" + + "X1sz9fMC7QMAFL98nDm/yqcnejG1BcQXZho8n0svSfbcVByGlPZGMuI9t25+0B2M\n" + + "TAx0f6zoD8+fFmhcVgS6MQPybGKFawckYl0zulsePqs+G4voIW17owGKsRiv06Jm\n" + + "ZSwd3KoGmjM49ADzuG9yrQ5PSa0nhVk1tybNape4HNYHrAmmN0ILlN+E0Bs/Edz4\n" + + "ntYZuoc/Z35tCgm79dV4/Vl6HUZ1JrLsLrEWCByVytwVFyf3/MwTWdf+Ac+XzBuC\n" + + "yEMqPlvnPWswdnaid35pxios79fPl1Hr0/Q6+DoA5GyYq8SFdP7EYLrGMGa5GJ+x\n" + + "5nS7z6U4UmZ2sXuKYHnuhB0zi6Y04a+fhT71x02eTeC7aPlEB319UqysujJVJnso\n" + + "bkcwOu/Jj0Is9YeFd693dB44xeZuYyvlwoD19lqcim0TSa2Tw7D1W/yu47dKrVP2\n" + + "VKxRqomuAQOpoZiuSfq1/7ysrV8U4hIlIU2vnrSVJ8EtPQKsoBW5l70dQGwXyxBk\n" + + "BUTHqfJ4LG/kPGRMOtUzgqFw2DjJtbym1q1MZgp2ycMon4vp7DeQLGs2XfEANB+Y\n" + + "nRwtjpevqAnIuK6K3Y02LY4FXTNQpC37Xb04bmdIQAcE0MaoP4/hY87aS82PQ68g\n" + + "3bI79uKo4we2g+WaEJlEzQ7147ZzV2wbDq89W69x1MWTfaDwlEtd4UaacYchAv7B\n" + + "TVaaVFiRAUywWaHGePpZG2WV1feH/zd+temxWR9qMFgBZySg1jipBPVciwl0LqlW\n" + + "s/raIBYmLmAaMMgM3759UkNVznDoFHrY4z2EADXp0RHHVzJS1x+yYvp/9I+AcW55\n" + + "oN0UP/3uQ6eyz/ix22sovQwhMJ8rmgR6CfyRPKmXu1RPK3puNv7mbFTfTXpYN2vX\n" + + "vhEZReXY8hJF/9o4G3UrJ1F0MgUHMCG86cw1z0bhPSaXVoufOnx/fRoxJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwgZ0wgY0wSQYJKoZIhvcN\n" + + "AQUOMDwwLAYJKoZIhvcNAQUMMB8ECFDaXOUaOcUPAgIIAAIBQDAMBggqhkiG9w0C\n" + + "CwUAMAwGCCqGSIb3DQILBQAEQHIAM8C9OAsHUCj9CmOJioqf7YwD4O/b3UiZ3Wqo\n" + + "F6OmQIRDc68SdkZJ6024l4nWlnhTE7a4lb2Tru4k3NOTa1oECE5PVCBVU0VEAgEB"); + + // Invalid PKCS #12 File with Incorrect Iteration Count + private static final byte[] pkcs12WithPBMac1PBKdf2_a4 = Base64.decode("MIIKiwIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfTBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhvRzw4sC4xcwICCAECASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQITk9UIFVTRUQCAggA"); + + // Invalid PKCS #12 File with Incorrect Salt + private static final byte[] pkcs12WithPBMac1PBKdf2_a5 = Base64.decode("MIIKigIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwfDBtMEkGCSqGSIb3DQEF\n" + + "DjA8MCwGCSqGSIb3DQEFDDAfBAhOT1QgVVNFRAICCAACASAwDAYIKoZIhvcNAgkF\n" + + "ADAMBggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG\n" + + "3QQIb0c8OLAuMXMCAQE="); + + // Invalid PKCS #12 File with Missing Key Length + private static final byte[] pkcs12WithPBMac1PBKdf2_a6 = Base64.decode("MIIKiAIBAzCCCgUGCSqGSIb3DQEHAaCCCfYEggnyMIIJ7jCCBGIGCSqGSIb3DQEH\n" + + "BqCCBFMwggRPAgEAMIIESAYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG\n" + + "SIb3DQEFDDAcBAg9pxXxY2yscwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME\n" + + "ASoEEK7yYaFQDi1pYwWzm9F/fs+AggPgFIT2XapyaFgDppdvLkdvaF3HXw+zjzKb\n" + + "7xFC76DtVPhVTWVHD+kIss+jsj+XyvMwY0aCuAhAG/Dig+vzWomnsqB5ssw5/kTb\n" + + "+TMQ5PXLkNeoBmB6ArKeGc/QmCBQvQG/a6b+nXSWmxNpP+71772dmWmB8gcSJ0kF\n" + + "Fj75NrIbmNiDMCb71Q8gOzBMFf6BpXf/3xWAJtxyic+tSNETfOJa8zTZb0+lV0w9\n" + + "5eUmDrPUpuxEVbb0KJtIc63gRkcfrPtDd6Ii4Zzbzj2Evr4/S4hnrQBsiryVzJWy\n" + + "IEjaD0y6+DmG0JwMgRuGi1wBoGowi37GMrDCOyOZWC4n5wHLtYyhR6JaElxbrhxP\n" + + "H46z2USLKmZoF+YgEQgYcSBXMgP0t36+XQocFWYi2N5niy02TnctwF430FYsQlhJ\n" + + "Suma4I33E808dJuMv8T/soF66HsD4Zj46hOf4nWmas7IaoSAbGKXgIa7KhGRJvij\n" + + "xM3WOX0aqNi/8bhnxSA7fCmIy/7opyx5UYJFWGBSmHP1pBHBVmx7Ad8SAsB9MSsh\n" + + "nbGjGiUk4h0QcOi29/M9WwFlo4urePyI8PK2qtVAmpD3rTLlsmgzguZ69L0Q/CFU\n" + + "fbtqsMF0bgEuh8cfivd1DYFABEt1gypuwCUtCqQ7AXK2nQqOjsQCxVz9i9K8NDeD\n" + + "aau98VAl0To2sk3/VR/QUq0PRwU1jPN5BzUevhE7SOy/ImuJKwpGqqFljYdrQmj5\n" + + "jDe+LmYH9QGVRlfN8zuU+48FY8CAoeBeHn5AAPml0PYPVUnt3/jQN1+v+CahNVI+\n" + + "La8q1Nen+j1R44aa2I3y/pUgtzXRwK+tPrxTQbG030EU51LYJn8amPWmn3w75ZIA\n" + + "MJrXWeKj44de7u4zdUsEBVC2uM44rIHM8MFjyYAwYsey0rcp0emsaxzar+7ZA67r\n" + + "lDoXvvS3NqsnTXHcn3T9tkPRoee6L7Dh3x4Od96lcRwgdYT5BwyH7e34ld4VTUmJ\n" + + "bDEq7Ijvn4JKrwQJh1RCC+Z/ObfkC42xAm7G010u3g08xB0Qujpdg4a7VcuWrywF\n" + + "c7hLNquuaF4qoDaVwYXHH3iuX6YlJ/3siTKbYCVXPEZOAMBP9lF/OU76UMJBQNfU\n" + + "0xjDx+3AhUVgnGuCsmYlK6ETDp8qOZKGyV0KrNSGtqLx3uMhd7PETeW+ML3tDQ/0\n" + + "X9fMkcZHi4C2fXnoHV/qa2dGhBj4jjQ0Xh1poU6mxGn2Mebe2hDsBZkkBpnn7pK4\n" + + "wP/VqXdQTwqEuvzGHLVFsCuADe40ZFBmtBrf70wG7ZkO8SUZ8Zz1IX3+S024g7yj\n" + + "QRev/6x6TtkwggWEBgkqhkiG9w0BBwGgggV1BIIFcTCCBW0wggVpBgsqhkiG9w0B\n" + + "DAoBAqCCBTEwggUtMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAhTxzw+\n" + + "VptrYAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEK9nSqc1I2t4tMVG\n" + + "bWHpdtQEggTQzCwI7j34gCTvfj6nuOSndAjShGv7mN2j7WMV0pslTpq2b9Bn3vn1\n" + + "Y0JMvL4E7sLrUzNU02pdOcfCnEpMFccNv2sQrLp1mOCKxu8OjSqHZLoKVL0ROVsZ\n" + + "8dMECLLigDlPKRiSyLErl14tErX4/zbkUaWMROO28kFbTbubQ8YoHlRUwsKW1xLg\n" + + "vfi0gRkG/zHXRfQHjX/8NStv7hXlehn7/Gy2EKPsRFhadm/iUHAfmCMkMgHTU248\n" + + "JER9+nsXltd59H+IeDpj/kbxZ+YvHow9XUZKu828d3MQnUpLZ1BfJGhMBPVwbVUD\n" + + "A40CiQBVdCoGtPJyalL28xoS3H0ILFCnwQOr6u0HwleNJPGHq78HUyH6Hwxnh0b0\n" + + "5o163r6wTFZn5cMOxpbs/Ttd+3TrxmrYpd2XnuRme3cnaYJ0ILvpc/8eLLR7SKjD\n" + + "T4JhZ0h/CfcV2WWvhpQugkY0pWrZ+EIMneB1dZB96mJVLxOi148OeSgi0PsxZMNi\n" + + "YM33rTpwQT5WqOsEyDwUQpne5b8Kkt/s7EN0LJNnPyJJRL1LcqOdr6j+6YqRtPa7\n" + + "a9oWJqMcuTP+bqzGRJh+3HDlFBw2Yzp9iadv4KmB2MzhStLUoi2MSjvnnkkd5Led\n" + + "sshAd6WbKfF7kLAHQHT4Ai6dMEO4EKkEVF9JBtxCR4JEn6C98Lpg+Lk+rfY7gHOf\n" + + "ZxtgGURwgXRY3aLUrdT55ZKgk3ExVKPzi5EhdpAau7JKhpOwyKozAp/OKWMNrz6h\n" + + "obu2Mbn1B+IA60psYHHxynBgsJHv7WQmbYh8HyGfHgVvaA8pZCYqxxjpLjSJrR8B\n" + + "Bu9H9xkTh7KlhxgreXYv19uAYbUd95kcox9izad6VPnovgFSb+Omdy6PJACPj6hF\n" + + "W6PJbucP0YPpO0VtWtQdZZ3df1P0hZ7qvKwOPFA+gKZSckgqASfygiP9V3Zc8jIi\n" + + "wjNzoDM2QT+UUJKiiGYXJUEOO9hxzFHlGj759DcNRhpgl5AgR57ofISD9yBuCAJY\n" + + "PQ/aZHPFuRTrcVG3RaIbCAS73nEznKyFaLOXfzyfyaSmyhsH253tnyL1MejC+2bR\n" + + "Eko/yldgFUxvU5JI+Q3KJ6Awj+PnduHXx71E4UwSuu2xXYMpxnQwI6rroQpZBX82\n" + + "HhqgcLV83P8lpzQwPdHjH5zkoxmWdC0+jU/tcQfNXYpJdyoaX7tDmVclLhwl9ps/\n" + + "O841pIsNLJWXwvxG6B+3LN/kw4QjwN194PopiOD7+oDm5mhttO78CrBrRxHMD/0Q\n" + + "qniZjKzSZepxlZq+J792u8vtMnuzzChxu0Bf3PhIXcJNcVhwUtr0yKe/N+NvC0tm\n" + + "p8wyik/BlndxN9eKbdTOi2wIi64h2QG8nOk66wQ/PSIJYwZl6eDNEQSzH/1mGCfU\n" + + "QnUT17UC/p+Qgenf6Auap2GWlvsJrB7u/pytz65rtjt/ouo6Ih6EwWqwVVpGXZD0\n" + + "7gVWH0Ke/Vr6aPGNvkLcmftPuDZsn9jiig3guhdeyRVf10Ox369kKWcG75q77hxE\n" + + "IzSzDyUlBNbnom9SIjut3r+qVYmWONatC6q/4D0I42Lnjd3dEyZx7jmH3g/S2ASM\n" + + "FzWr9pvXc61dsYOkdZ4PYa9XPUZxXFagZsoS3F1sU799+IJVU0tC0MExJTAjBgkq\n" + + "hkiG9w0BCRUxFgQUwWO5DorvVWYF3BWUmAw0rUEajScwejBqMEYGCSqGSIb3DQEF\n" + + "DjA5MCkGCSqGSIb3DQEFDDAcBAhvRzw4sC4xcwICCAAwDAYIKoZIhvcNAgkFADAM\n" + + "BggqhkiG9w0CCQUABCB6pW2FOdcCNj87zS64NUXG36K5aXDnFHctIk5Bf4kG3QQI\n" + + "b0c8OLAuMXMCAggA"); + /** * we generate a self signed certificate for the sake of testing - RSA */ @@ -1097,13 +1449,13 @@ private void testGOSTStore() private void testDilithiumStore() throws Exception { - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Dilithium", "BC"); + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); - kpg.initialize(DilithiumParameterSpec.dilithium3); + kpg.initialize(MLDSAParameterSpec.ml_dsa_65); KeyPair kp = kpg.generateKeyPair(); - Certificate cert = TestUtils.createSelfSignedCert("CN=Dilithium Test", "Dilithium3", kp); + Certificate cert = TestUtils.createSelfSignedCert("CN=Dilithium Test", "ML-DSA-65", kp); KeyStore pkcs12 = KeyStore.getInstance("PKCS12", BC); @@ -1248,6 +1600,113 @@ private void testSphincsPlusStore() certs[0].verify(certs[0].getPublicKey()); } + public void testPKCS12StoreFriendlyName() + throws Exception + { + byte[] storeBytes = Base64.decode("MIIMeQIBAzCCDD8GCSqGSIb3DQEHAaCCDDAEggwsMIIMKDCCBt8GCSqGSIb3DQEHBqCCBtAwggbMAgEAMIIGxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIxlXZpvmdr1cCAggAgIIGmGsxcWF3VsCSkOcYj/pwVyEIexkcXGFN2vBuoCV1INgYDo0Kn+Px5tZRTk4YYiEE5+UAE23t7tozlaamXfX9WWq2lRYCHkD5QdGco+L5ZYJFtGLjf900O5S1lPKje/NdahXMR3imaDZ0R2PQg5qhGz9zXSySlbOwMvSERhcxvJ5lP7jjZpfnQ2Vd2nqL5VCm9kNCmTHCPpi5moVcX+qiZm/CYhCVTotSYh/wgvlMh200fe5KC0ZJ0XKUK1fmy3v8PaFbj/MuZ68ySurIXg/X6eOV8NjuhnlUigRvD0eMcExBq+RJ9nRbfQGPWvxwjqcxCu9ukyURZKlezVqWuRIT0vzX8EfEuqdhDTyP1OfmVf2AfnUMpHTdAX/v6H00L4L5kvRRXLl+aWRbr0VDN4p85z3pkmek99WUmkZAj5i0+nXVN+FCnHj6cv5OjbfIuF0APKyMTe/lpX+xPUPtvygFOUTe2Kv+QdUuAyfGzDES96UGNfFh7xMD+6NG6foQtLyDbvmehn2nqPdvSEoTQmGE5fQ5pijCeBmNTW8VUqbdmIynhOJaE1i/WkPeYnl4thIe+yP6OvgWQe9FOG+GpRyIm7bQZ09cmngQuAAUNDI3tQOyZaRhMQEq5Di11JpRKGix/ATt3qBLTE7LFu4iCj/GDNucny3Y2cC+R3Jg7qYto1oB5vI5UZ/521U+3MQPxIY/7XgM5gtBXc+NWBNRNd0yRPmSsLSJ6DtT5TFZM+4I/o9gRw1pII4WskxQhZFDptnhDoGhO7JeEOYJEtkqUQCS6imf/DnDPNeFYJsnnqyV3JGWfQKTNXqNNYWeY6yA3zxIGl78rBZGah7uZwTlvaQuyl4x5FRXx4OPD2wW5OvpZDcG3L3DzL2ke5YH5GiAIB4lEw483ck21R0trqVPFRCGLzwJkr88QaprlQbkCTGnq4oTp7I6Y4XNTUI9SwRQs1WVntjd+Y10rZUp+Lls1SukrWvq4qKqJpB3OzXkYD+v/6V3MjzGTjq1hGXXw02fSfeGQOh04189/lPJG1nlWND3UecUn2tBWSLqgUKmrvTIaDabRk/h3ji9FYOFzhVqsvgUTzR9naDO9XsGT8wnWkSCB8vgs88Hlijqq0NRj75SEPazYOjNn2X4L0iWwnxwA2K2mSNXdJIAs9PmEFSppQ/OGIjzrwVqjDlBHOPTD0y9NEYFZOD8dkXh+bLi0EzGRLZsgCDkVVz5Ex2ZrjnuLxQ3tAFMkaIea6h9YwNq1f2r7Z0x5t96Vp1F/+weRMZRcauThJ23CfKcrQO28kW+whoWQIPbaO25+8u5k7ihlApndeeTo0UqRKYX9xOYd+OKgV9TH3xws4zWSgQizApzkc3itAS0VV7ID4wlPtJKgaCYsFOWldtwhxQzdHgxLOV6GH2Op6ao64Zh/Nq0vTlX+I09HwmibgGN76xf7sBeXVGEWpteFYHyv56P7m9y2o3rjw8DDoXEjuaYZoO9wYN5YfN3qtMSNBdu2U77Pci85Hqo3AwC6badPGA7OYx4MuVML0GL/Qn9QpvmpFdFyxl3ssUTFA/8vuZDvQFCHzIxKZmnlV1qvpnQjjGXNtM5OElEpTd2KLI6nQbHYH1fdJFw52ID+TRPviB5WQk3OF5CNTOui6V+xh9fYcgqw+QyWxQQOykIycFPlIbIOuciviqKWMPbgWz7WS0L8TxeqTB5ndUl1+bMYKhcz15ZoXcPaG1ImCv/h9VHWodspPkJQuwThlphGj/MqRudjMzwYrrJUYyX4IkWIHyRhKT90osZZtV48jcyhIHYkSXOvTXT4YXeIoWBarQ+/UVCQdYhvntENgbOEM1wBKCDMJzv8F4gQFNAnswWnVwS1O8TSFfsxmdFdtnb5ujHHQ0zXRhso/4EM//xvW1zFWE8ny12TgNQ6+oYkS949LeUHEzG0HzY978xaLND3SwbGImjhLhG+w8CgPbwCOZOdGK0CDC3jybkxxGAgm7hdYnV3VcrCU1IxjVUv6U/EXTY2tiPZe+VVRD+q34YqjEXdBu/giTf2WDxZ5DRl7NPldlyAUvcKIyRVSfr9Xa33zD0sDUGck515JQn2eOwk2mEabYSE6sIQrlNEniVvV0ajBuj/1RjqVTPnEz2vCb644aZtEpHhDoq17rcbqSMIYQ0vrdOO9vWJE34lDgPwIwU5dvzDmCdvO8+7SWYwv0FgaCWLR53/ODx6pXUsI5zCjKtlkUpi8VkIAe7JfwrP91QWLaWMsKaRyTUMIIFQQYJKoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0BDAEDMA4ECDF59fPGZHKyAgIIAASCBMjReiOrtzXOEajEU8kzlbi26HhZ47sHc34n2Um2C2fYNd2DsvqdUmlc+Yy/y+I61LwVSJSNEt2ShIcYga31p2sFMaPJkhSoBMI2o8znYzV/W8ZTHgEV+qeFNgU/eEUHJnt/cxvLaFgFXhxvrS9wTRMBWOmaNyp6IqPpoTaADuZSV19nebY7M3AEtEX0XIGKgatCfdXSM4HaqBgFBTcfos8oGLxubQQc1EUhXVVA5zppYfV3JKwX0T5/NoRY5spsBZSBVo76YtR17w7mL9ff+XSQImx8EkPIuG9gFVD06c5Yvf2aHa79sg5qTQq35aN1Dn7Nx3ieRTSrXDd8Mltcjt6mP4FPWluNul/yjwMUnRxYIN67xDrLDMQ9sKH1P5mXl6C6JrQO9qWCoPMal3syHtBkJbFax1B2BvG/PSvHnNaU5UhT/vOliDWPWmZGdaI3gUvh85vClViqooGX2HWvNHHhfcPl8YpF8ez8QwXI/L15jOjDhfP0zkVW/QtY3ryq1GtcTDH5/w3Gfc1EBsiGEjvjlfml3PU+kpBB17Aw5z2hUhoJZQ282p4HHuVO1lMpxkSuLol4lNsPZlxNU3IB9Z7V8b6cU3i8v5FN5moZdoS4Ad2TBMWB+oAIRBkYV3AH0/fwlgbMYuwvrrJcn/oG5uHAKxUXTMPBNGrwS9KFCMUQDhKOcIvmYRUfptyMniAputrlaE31xnCnHUe7oOvwiSPhmMFvx9X4NbEx0OtmGw3pvPbLQI2rxHeOHuM9biT4iutxsrJ6X9MRvDbgsSkCCBrQ7N7mIDpH4pwtPNztf0PYKPq9ufggHgG+OBJDy70kfCu04vb/l57TfHzWQLOQ4Fz8d/wbYa1IPxOuAqS4XALi1ZpHVWPNEnp/Wb+Hceny+87gropC04Q6fBtUhvgjbhxoGSp4GThTQjXEQ2tsQENIpkqvNUuwkgXgrRmSV8r3S4l3JofIvg/r2YSut/xlFboDIyPO9d75X3dP8CxPHJ9juQBQGESIR+ywDXWuSlV43aQnrrcNZFSvjd6Ysykd7atRFr6266etdu6cfRYmoodsd9EMnNDIePJl5KK3u/qGN41OxwNkkfWOFUas6BVH2CUuyhwf1wzgsCB/P0UU4dSiW0icIKh2zts+8E/ZEFBRalP6MSEZyVO+Th9k9cMsIWj8KNvssKD5iLLS+cgjvIYaXhmbmes3h1KojWXSNJMcDC8MRMYHwYQnjnhJfhxCA8EJ4eXH4asZuAYsjVEaz8BDUASKNh2Dnz8iaOWTdVX9hplusuZYDXh93VxRi9ToncdBhfOLKD7hcOjk+rr8vEc/JAAANgCOSal7HVEMgedQSqID3fSSnZnVD/VBYXpUfjWwGXlddZVfCtfcVFLvW7bNE11+eEW5iibwiVAmbcK5r/QHS7K2qKKh/1c4EsxpTkLao3scId7ptlkdWrhgSEE4aBCzICR1+FfzvEUDs4tlhCVAWWquLxRZ9OO5yOYP2l6h/J4oRNcrvM9kYk6ModNLiNgm5LwcLloBxyPOqR5upIZZJOLEgI4k/KLIkYFaOz6aZjxETgYgEOTBVVkAOV2IoAvdgmyW7ooLO4ThuAUJblb9A1ctBPBqZOl9BhOGlg52x0dKMgIZqjkxJTAjBgkqhkiG9w0BCRUxFgQUkvWjJYxEoUuNeJD2ioU/QLI0O9YwMTAhMAkGBSsOAwIaBQAEFIBH3wpDttZkuTsu3QrSXRtfzJinBAgoZmuwkXAvCQICCAA="); + char[] storePassword = "Axw9eE51lKEx0IuqHbzlJ+sx".toCharArray(); + ByteArrayInputStream stream = new ByteArrayInputStream(storeBytes); + + KeyStore store1 = KeyStore.getInstance("PKCS12", BC); + store1.load(stream, storePassword); + + // overwriteFriendlyName=FALSE AND friendlyName is null -> friendlyName should stay null + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + PKCS12StoreParameter storeParameter = new PKCS12StoreParameter(outStream, storePassword, false, false); + store1.store(storeParameter); + + byte[] outBytes = outStream.toByteArray(); + stream = new ByteArrayInputStream(outBytes); + KeyStore store2 = KeyStore.getInstance("PKCS12", BC); + store2.load(stream, storePassword); + + String alias1 = store1.aliases().nextElement(); + String alias2 = store2.aliases().nextElement(); + PKCS12BagAttributeCarrier cert2 = (PKCS12BagAttributeCarrier)store2.getCertificate(alias2); + + if (cert2.hasFriendlyName()) + { + fail("with overwriteFriendlyName=false, default friendlyName should not be written to new store"); + } + + // overwriteFriendlyName=FALSE AND friendlyName is null -> friendlyName should be default value + outStream = new ByteArrayOutputStream(); + storeParameter = new PKCS12StoreParameter(outStream, storePassword, false, true); + store1.store(storeParameter); + + outBytes = outStream.toByteArray(); + stream = new ByteArrayInputStream(outBytes); + store2.load(stream, storePassword); + + alias1 = store1.aliases().nextElement(); + alias2 = store2.aliases().nextElement(); + cert2 = (PKCS12BagAttributeCarrier)store2.getCertificate(alias2); + + if (!cert2.hasFriendlyName()) + { + fail("with overwriteFriendlyName=true, default friendlyName should be written to new store"); + } + + // Add custom friendlyName to store1 + if (store1.isKeyEntry(alias1)) + { + KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)store1.getEntry(alias1, new KeyStore.PasswordProtection(storePassword)); + ((PKCS12BagAttributeCarrier)pkEntry.getCertificate()).setFriendlyName("my_custom_friendly_name"); + ((PKCS12BagAttributeCarrier)pkEntry.getPrivateKey()).setFriendlyName("my_custom_friendly_name"); + } + else + { + KeyStore.TrustedCertificateEntry entry = (KeyStore.TrustedCertificateEntry)store1.getEntry(alias1, null); + ((PKCS12BagAttributeCarrier)entry.getTrustedCertificate()).setFriendlyName("my_custom_friendly_name"); + } + + // overwriteFriendlyName=TRUE AND friendlyName is null then added -> friendlyName should be default value + outStream = new ByteArrayOutputStream(); + storeParameter = new PKCS12StoreParameter(outStream, storePassword, false, true); + store1.store(storeParameter); + + outBytes = outStream.toByteArray(); + stream = new ByteArrayInputStream(outBytes); + store2.load(stream, storePassword); + + alias1 = store1.aliases().nextElement(); + alias2 = store2.aliases().nextElement(); + + if (alias2.equals("my_custom_friendly_name")) + { + fail("with overwriteFriendlyName=true, default friendlyName should be written to new store"); + } + + // overwriteFriendlyName=FALSE AND friendlyName is null then added -> friendlyName should be added value + // Add custom friendlyName to store1 + if (store1.isKeyEntry(alias1)) + { + KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)store1.getEntry(alias1, new KeyStore.PasswordProtection(storePassword)); + ((PKCS12BagAttributeCarrier)pkEntry.getCertificate()).setFriendlyName("my_custom_friendly_name"); + ((PKCS12BagAttributeCarrier)pkEntry.getPrivateKey()).setFriendlyName("my_custom_friendly_name"); + } + else + { + KeyStore.TrustedCertificateEntry entry = (KeyStore.TrustedCertificateEntry)store1.getEntry(alias1, null); + ((PKCS12BagAttributeCarrier)entry.getTrustedCertificate()).setFriendlyName("my_custom_friendly_name"); + } + + outStream = new ByteArrayOutputStream(); + storeParameter = new PKCS12StoreParameter(outStream, storePassword, false, false); + store1.store(storeParameter); + + outBytes = outStream.toByteArray(); + stream = new ByteArrayInputStream(outBytes); + store2.load(stream, storePassword); + + alias2 = store2.aliases().nextElement(); + + if (!alias2.equals("my_custom_friendly_name")) + { + fail("with overwriteFriendlyName=false, added friendlyName should be written to new store"); + } + } + public void testPKCS12Store() throws Exception { @@ -2041,6 +2500,73 @@ private void testIterationCount() System.clearProperty("org.bouncycastle.pkcs12.max_it_count"); } + private void testPBMac1PBKdf2() + throws Exception + { + KeyStore store = KeyStore.getInstance("PKCS12", BC); + final char[] password = "1234".toCharArray(); + ByteArrayInputStream stream; + // valid test vectors + for (byte[] test_vector : new byte[][]{pkcs12WithPBMac1PBKdf2_a1, pkcs12WithPBMac1PBKdf2_a2, pkcs12WithPBMac1PBKdf2_a3}) + { + // + // load test + // + stream = new ByteArrayInputStream(test_vector); + store.load(stream, password); + + try + { + store.load(stream, "not right".toCharArray()); + fail("no exception"); + } + catch (IOException ignored) {} + + // + // save test + // + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + store.store(bOut, passwd); + stream = new ByteArrayInputStream(bOut.toByteArray()); + store.load(stream, passwd); + + // + // save test using LoadStoreParameter + // + bOut = new ByteArrayOutputStream(); + PKCS12StoreParameter storeParam = new PKCS12StoreParameter(bOut, passwd, true); + store.store(storeParam); + byte[] data = bOut.toByteArray(); + stream = new ByteArrayInputStream(data); + store.load(stream, passwd); + } + // invalid test vectors + for (byte[] test_vector : new byte[][]{pkcs12WithPBMac1PBKdf2_a4, pkcs12WithPBMac1PBKdf2_a5}) + { + stream = new ByteArrayInputStream(test_vector); + try + { + store.load(stream, password); + fail("no exception"); + } + catch (IOException e) + { + isTrue(e.getMessage().contains("PKCS12 key store mac invalid - wrong password or corrupted file.")); + } + } + // invalid test vector that throws exception + stream = new ByteArrayInputStream(pkcs12WithPBMac1PBKdf2_a6); + try + { + store.load(stream, password); + fail("no exception"); + } + catch (IOException e) + { + isTrue(e.getMessage().contains("Key length must be present when using PBMAC1.")); + } + } + private void testBCFKSLoad() throws Exception { @@ -2115,6 +2641,42 @@ private void testLoadRepeatedLocalKeyID() isTrue(store.getCertificateChain("45cbf1116fb3f38b2984b3c7224cae70a74f7789").length == 1); } + private void checkNoDuplicateOracleTrustedCertAttribute() + throws Exception + { + String keystoreType = "PKCS12"; + String certificateAlias = "myAlias"; + String keystorePassword = "myPassword"; + + KeyPair kp1 = TestUtils.generateRSAKeyPair(); + KeyPair kp2 = TestUtils.generateRSAKeyPair(); + + // generate certificate + X509Certificate rootCertificate = TestUtils.generateRootCert(kp1, new X500Name("CN=KP1 ROOT")); + X509Certificate originalCertificate = TestUtils.generateEndEntityCert(kp2.getPublic(), new X500Name("CN=KP3 EE"), KeyPurposeId.id_kp_capwapAC, KeyPurposeId.id_kp_capwapWTP, kp1.getPrivate(), rootCertificate); + + // store original certificate to a truststore + KeyStore firstTrustStore = KeyStore.getInstance("PKCS12", "BC"); + firstTrustStore.load(null, new char[0]); + firstTrustStore.setCertificateEntry(certificateAlias, originalCertificate); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + firstTrustStore.store(bOut, keystorePassword.toCharArray()); + + // read certificate from the truststore + KeyStore firstTrustStoreReadAgain = KeyStore.getInstance("PKCS12", "BC"); + firstTrustStoreReadAgain.load(new ByteArrayInputStream(bOut.toByteArray()), keystorePassword.toCharArray()); + Certificate certificateReadFromFirstTrustStore = firstTrustStoreReadAgain.getCertificate(certificateAlias); + + KeyStore secondTrustStore = KeyStore.getInstance("PKCS12", "BC"); + secondTrustStore.load(null, new char[0]); + secondTrustStore.setCertificateEntry(certificateAlias, certificateReadFromFirstTrustStore); + bOut = new ByteArrayOutputStream(); + secondTrustStore.store(bOut, keystorePassword.toCharArray()); + + KeyStore secondTrustStoreReadWithoutBc = KeyStore.getInstance("PKCS12", "SunJSSE"); + secondTrustStoreReadWithoutBc.load(new ByteArrayInputStream(bOut.toByteArray()), keystorePassword.toCharArray()); + } + public String getName() { return "PKCS12Store"; @@ -2127,7 +2689,7 @@ private void testJKS() { return; } - + KeyStore ks = KeyStore.getInstance("PKCS12", BC); ks.load(new ByteArrayInputStream(JKS_Store), JKS_TEST_PWD); @@ -2145,7 +2707,7 @@ private void testStoreType(String storeType, boolean isMacExpected) KeyStore keyStore = KeyStore.getInstance(storeType, "BC"); keyStore.load(null, null); - keyStore.setKeyEntry("key", kp.getPrivate(), null, new Certificate[] { cert }); + keyStore.setKeyEntry("key", kp.getPrivate(), null, new Certificate[]{cert}); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); @@ -2155,9 +2717,6 @@ private void testStoreType(String storeType, boolean isMacExpected) inStore.load(new ByteArrayInputStream(bOut.toByteArray()), passwd); - FileOutputStream fOut = new FileOutputStream("/tmp/" + storeType + ".p12"); - fOut.write(bOut.toByteArray()); - fOut.close(); Key k = inStore.getKey("key", null); Pfx pfx = Pfx.getInstance(bOut.toByteArray()); @@ -2172,7 +2731,7 @@ private void testStoreType(String storeType, boolean isMacExpected) } } - + private void testAES256_AES128() throws Exception { @@ -2188,7 +2747,9 @@ private void testAES256GCM_AES128_GCM() public void performTest() throws Exception { + testPKCS12StoreFriendlyName(); testIterationCount(); + testPBMac1PBKdf2(); testPKCS12Store(); testGOSTStore(); testChainCycle(); @@ -2235,6 +2796,7 @@ public void performTest() } testOrphanedCertCleanup(); + checkNoDuplicateOracleTrustedCertAttribute(); } public static void main( diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/PQCDHTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/PQCDHTest.java new file mode 100644 index 0000000000..7c9f299cad --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/PQCDHTest.java @@ -0,0 +1,89 @@ +package org.bouncycastle.jce.provider.test; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Security; +import java.security.spec.ECGenParameterSpec; + +import javax.crypto.KeyAgreement; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; + +import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; +import org.bouncycastle.jcajce.spec.HybridValueParameterSpec; +import org.bouncycastle.jcajce.spec.KEMExtractSpec; +import org.bouncycastle.jcajce.spec.KEMGenerateSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.SimpleTest; + +public class PQCDHTest + extends SimpleTest +{ + public String getName() + { + return "PQCDHTest"; + } + + private void testMLKemECDH() + throws Exception + { + + KeyPairGenerator kemKeyGen = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + kemKeyGen.initialize(MLKEMParameterSpec.ml_kem_768); + + KeyPair kemKp = kemKeyGen.generateKeyPair(); + + KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC", "BC"); + + ecKeyGen.initialize(new ECGenParameterSpec("P-256")); + + KeyPair ecKp = ecKeyGen.generateKeyPair(); + + byte[] ukm = Hex.decode("030f136fa7fef90d185655ed1c6d46bacdb820"); + + KeyGenerator keyGen = KeyGenerator.getInstance("ML-KEM", "BC"); + + keyGen.init(new KEMGenerateSpec.Builder(kemKp.getPublic(), "DEF", 256).withNoKdf().build()); + + SecretKeyWithEncapsulation secEnc1 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + KeyAgreement agreement = KeyAgreement.getInstance("ECCDHwithSHA256CKDF", "BC"); + + agreement.init(ecKp.getPrivate(), new HybridValueParameterSpec(secEnc1.getEncoded(), new UserKeyingMaterialSpec(ukm))); + + agreement.doPhase(ecKp.getPublic(), true); + + SecretKey k1 = agreement.generateSecret("AES[256]"); + + keyGen.init(new KEMExtractSpec.Builder(kemKp.getPrivate(), secEnc1.getEncapsulation(), "DEF", 256).withNoKdf().build()); + + SecretKeyWithEncapsulation secEnc2 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + agreement.init(ecKp.getPrivate(), new HybridValueParameterSpec(secEnc2.getEncoded(), new UserKeyingMaterialSpec(ukm))); + + agreement.doPhase(ecKp.getPublic(), true); + + SecretKey k2 = agreement.generateSecret("AES[256]"); + + isTrue(Arrays.areEqual(k1.getEncoded(), k2.getEncoded())); + } + + @Override + public void performTest() + throws Exception + { + testMLKemECDH(); + } + + public static void main(String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new PQCDHTest()); + } +} diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/PSSTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/PSSTest.java index 75931bf195..462c06d5d7 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/PSSTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/PSSTest.java @@ -47,27 +47,6 @@ public void nextBytes( } } - private boolean arrayEquals( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - private RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); @@ -109,7 +88,7 @@ public void performTest() throws Exception s.update(msg1a); byte[] sig = s.sign(); - if (!arrayEquals(sig1a, sig)) + if (!Arrays.areEqual(sig1a, sig)) { fail("PSS Sign test expected " + new String(Hex.encode(sig1a)) + " got " + new String(Hex.encode(sig))); } @@ -135,7 +114,7 @@ public void performTest() throws Exception } AlgorithmParameters pss = s.getParameters(); - if (!arrayEquals(pss.getEncoded(), new byte[] { 0x30, 0x00 })) + if (!Arrays.areEqual(pss.getEncoded(), new byte[]{ 0x30, 0x00 })) { fail("failed default encoding test."); } @@ -148,7 +127,7 @@ public void performTest() throws Exception pss = s.getParameters(); - if (!arrayEquals(sig1b, sig)) + if (!Arrays.areEqual(sig1b, sig)) { fail("PSS Sign test expected " + new String(Hex.encode(sig1b)) + " got " + new String(Hex.encode(sig))); } @@ -251,7 +230,7 @@ public void performTest() throws Exception pss = s.getParameters(); - if (!arrayEquals(sig1c, sig)) + if (!Arrays.areEqual(sig1c, sig)) { fail("PSS Sign test expected " + new String(Hex.encode(sig1c)) + " got " + new String(Hex.encode(sig))); } diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java index 226b948364..9aab17bfc6 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java @@ -8,92 +8,99 @@ public class RegressionTest { - public static Test[] tests = { - new FIPSDESTest(), - new DESedeTest(), - new AESTest(), + public static Test[] tests = { new AEADTest(), - new CamelliaTest(), - new SEEDTest(), new AESSICTest(), - new GOST28147Test(), - new PBETest(), + new AESTest(), + new AlgorithmParametersTest(), + new ARIATest(), + new BCFKSStoreTest(), new BlockCipherTest(), - new MacTest(), - new HMacTest(), - new SealedTest(), - new RSATest(), - new DHTest(), + new CamelliaTest(), + new CertLocaleTest(), + new CertPathBuilderTest(), + new CertPathTest(), + new CertPathValidatorTest(), + new CertStoreTest(), + new CertTest(), + new CertUniqueIDTest(), + new ChaCha20Poly1305Test(), + new CipherStreamTest(), + new CipherStreamTest2(), + new CMacTest(), + new CRL5Test(), + new DESedeTest(), + new DetDSATest(), new DHIESTest(), + new DHTest(), + new DigestTest(), + new DoFinalTest(), + new DRBGTest(), new DSATest(), - new ImplicitlyCaTest(), - new ECNRTest(), + new DSTU4145Test(), + new DSTU7624Test(), + new ECDSA5Test(), + new ECEncodingTest(), new ECIESTest(), new ECIESVectorTest(), - new ECDSA5Test(), - new GOST3410Test(), + new ECNRTest(), + new EdECTest(), new ElGamalTest(), - new IESTest(), - new SigTest(), - new CertTest(), - new PKCS10CertRequestTest(), new EncryptedPrivateKeyInfoTest(), + new FIPSDESTest(), + new GMacTest(), + new GOST28147Test(), + new GOST3410KeyPairTest(), + new GOST3410Test(), + new GOST3412Test(), + new HMacTest(), + new IESTest(), + new ImplicitlyCaTest(), + new KeccakTest(), new KeyStoreTest(), - new PKCS12StoreTest(), - new DigestTest(), - new PSSTest(), - new WrapTest(), - new DoFinalTest(), - new CipherStreamTest(), - new CipherStreamTest2(), + new MacTest(), + new MQVTest(), + new MultiCertStoreTest(), new NamedCurveTest(), - new PKIXTest(), new NetscapeCertRequestTest(), - new X509StreamParserTest(), - new X509CertificatePairTest(), - new CertPathTest(), - new CertStoreTest(), - new CertPathValidatorTest(), - new CertPathBuilderTest(), - new ECEncodingTest(), - new AlgorithmParametersTest(), new NISTCertPathTest(), - new PKIXPolicyMappingTest(), - new SlotTwoTest(), - new PKIXNameConstraintsTest(), - new MultiCertStoreTest(), new NoekeonTest(), - new SerialisationTest(), - new SigNameTest(), - new MQVTest(), - new CMacTest(), - new GMacTest(), new OCBTest(), - new DSTU4145Test(), - new CRL5Test(), + new OpenSSHSpecTests(), + new PBETest(), + new PKCS10CertRequestTest(), + new PKCS12StorePBETest(), + new PKCS12StoreTest(), + new PKIXNameConstraintsTest(), + new PKIXPolicyMappingTest(), + new PKIXTest(), new Poly1305Test(), + new PQCDHTest(), + new PSSTest(), + new RSATest(), + new SealedTest(), + new SEEDTest(), + new SerialisationTest(), + new Shacal2Test(), + new SigNameTest(), + new SignatureTest(), + new SigTest(), + new SipHash128Test(), new SipHashTest(), - new KeccakTest(), new SkeinTest(), - new Shacal2Test(), - new DetDSATest(), - new ThreefishTest(), + new SlotTwoTest(), + new SM2CipherTest(), new SM2SignatureTest(), new SM4Test(), + new ThreefishTest(), new TLSKDFTest(), - new BCFKSStoreTest(), - new DSTU7624Test(), - new GOST3412Test(), - new GOST3410KeyPairTest(), - new EdECTest(), - new OpenSSHSpecTests(), - new SM2CipherTest(), - new ZucTest(), - new ChaCha20Poly1305Test(), - new SipHash128Test(), - new XOFTest(), + new WrapTest(), + new X509CertificatePairTest(), + new X509LDAPCertStoreTest(), + new X509StreamParserTest(), new XIESTest(), - new CertLocaleTest() + new XOFTest(), + new ZucTest(), }; public static void main(String[] args) diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/SimpleTestTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/SimpleTestTest.java index 8b63244078..2427f33d1b 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/SimpleTestTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/SimpleTestTest.java @@ -11,6 +11,7 @@ public class SimpleTestTest { public void testJCE() { + System.setProperty("org.bouncycastle.bks.enable_v1", "true"); if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/TestCertificateGen.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/TestCertificateGen.java index 1758e27387..e95599ca3f 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/TestCertificateGen.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/TestCertificateGen.java @@ -1,15 +1,10 @@ package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.math.BigInteger; import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; -import java.security.SecureRandom; import java.security.Signature; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; @@ -29,17 +24,13 @@ import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; -import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.CRLNumber; import org.bouncycastle.asn1.x509.CRLReason; -import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.ExtensionsGenerator; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.TBSCertList; import org.bouncycastle.asn1.x509.TBSCertificate; @@ -190,83 +181,6 @@ public static X509Certificate createCertWithIDs(X500Name signerName, String sigN return (X509Certificate)CertificateFactory.getInstance("X.509", "BC").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); } - /** - * Create a random 1024 bit RSA key pair - */ - public static KeyPair generateRSAKeyPair() - throws Exception - { - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); - - kpGen.initialize(1024, new SecureRandom()); - - return kpGen.generateKeyPair(); - } - - public static X509Certificate generateRootCert(KeyPair pair) - throws Exception - { - return createSelfSignedCert("CN=Test CA Certificate", "SHA256withRSA", pair); - } - - public static X509Certificate generateRootCert(KeyPair pair, X500Name dn) - throws Exception - { - return createSelfSignedCert(dn, "SHA256withRSA", pair); - } - - public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) - throws Exception - { - return generateIntermediateCert( - intKey, new X500Name("CN=Test Intermediate Certificate"), caKey, caCert); - } - - public static X509Certificate generateIntermediateCert(PublicKey intKey, X500Name subject, PrivateKey caKey, X509Certificate caCert) - throws Exception - { - Certificate caCertLw = Certificate.getInstance(caCert.getEncoded()); - - ExtensionsGenerator extGen = new ExtensionsGenerator(); - - extGen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(getDigest(caCertLw.getSubjectPublicKeyInfo()), - new GeneralNames(new GeneralName(caCertLw.getIssuer())), - caCertLw.getSerialNumber().getValue())); - extGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(intKey.getEncoded())))); - extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); - extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); - - return createCert( - caCertLw.getSubject(), - caKey, subject, "SHA256withRSA", extGen.generate(), intKey); - } - - public static X509Certificate generateEndEntityCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) - throws Exception - { - return generateEndEntityCert( - intKey, new X500Name("CN=Test End Certificate"), caKey, caCert); - } - - public static X509Certificate generateEndEntityCert(PublicKey entityKey, X500Name subject, PrivateKey caKey, X509Certificate caCert) - throws Exception - { - Certificate caCertLw = Certificate.getInstance(caCert.getEncoded()); - - ExtensionsGenerator extGen = new ExtensionsGenerator(); - - extGen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(getDigest(caCertLw.getSubjectPublicKeyInfo()), - new GeneralNames(new GeneralName(caCertLw.getIssuer())), - caCertLw.getSerialNumber().getValue())); - extGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(entityKey.getEncoded()))); - extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); - extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); - - return createCert( - caCertLw.getSubject(), - caKey, subject, "SHA256withRSA", extGen.generate(), entityKey); - } - public static X509CRL createCRL( X509Certificate caCert, PrivateKey caKey, @@ -309,23 +223,23 @@ public static X509CRL createCRL( return (X509CRL)CertificateFactory.getInstance("X.509", "BC").generateCRL(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); } - private static byte[] getDigest(SubjectPublicKeyInfo spki) - throws IOException - { - return getDigest(spki.getPublicKeyData().getBytes()); - } - - private static byte[] getDigest(byte[] bytes) - { - try - { - return MessageDigest.getInstance("SHA1").digest(bytes); - } - catch (NoSuchAlgorithmException e) - { - return null; - } - } +// private static byte[] getDigest(SubjectPublicKeyInfo spki) +// throws IOException +// { +// return getDigest(spki.getPublicKeyData().getBytes()); +// } + +// private static byte[] getDigest(byte[] bytes) +// { +// try +// { +// return MessageDigest.getInstance("SHA1").digest(bytes); +// } +// catch (NoSuchAlgorithmException e) +// { +// return null; +// } +// } private static DERBitString booleanToBitString(boolean[] id) { diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/TestUtils.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/TestUtils.java index ce58460f31..b274b3d1ac 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/TestUtils.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/TestUtils.java @@ -32,6 +32,7 @@ import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -52,6 +53,7 @@ import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.asn1.x509.V1TBSCertificateGenerator; import org.bouncycastle.asn1.x509.V3TBSCertificateGenerator; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.SHA1Digest; @@ -73,7 +75,7 @@ class TestUtils algIds.put("SHA1withECDSA", new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1)); algIds.put("SHA256withECDSA", new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA256)); algIds.put("Ed448", new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448)); - algIds.put("Dilithium3", new AlgorithmIdentifier(BCObjectIdentifiers.dilithium3)); + algIds.put("ML-DSA-65", new AlgorithmIdentifier(NISTObjectIdentifiers.id_ml_dsa_65)); algIds.put("Falcon-512", new AlgorithmIdentifier(BCObjectIdentifiers.falcon_512)); algIds.put("SPHINCS+", new AlgorithmIdentifier(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3)); } @@ -116,6 +118,32 @@ public static X509Certificate createSelfSignedCert(X500Name dn, String sigName, return (X509Certificate)CertificateFactory.getInstance("X.509", "BC").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); } + public static X509Certificate createNoSigCert(X500Name dn, KeyPair keyPair) + throws Exception + { + V1TBSCertificateGenerator certGen = new V1TBSCertificateGenerator(); + + long time = System.currentTimeMillis(); + + certGen.setSerialNumber(new ASN1Integer(serialNumber.getAndIncrement())); + certGen.setIssuer(dn); + certGen.setSubject(dn); + certGen.setStartDate(new Time(new Date(time - 5000))); + certGen.setEndDate(new Time(new Date(time + 30 * 60 * 1000))); + certGen.setSignature(new AlgorithmIdentifier(X509ObjectIdentifiers.id_alg_noSignature, DERNull.INSTANCE)); + certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); + + TBSCertificate tbsCert = certGen.generateTBSCertificate(); + + ASN1EncodableVector v = new ASN1EncodableVector(); + + v.add(tbsCert); + v.add(new AlgorithmIdentifier(X509ObjectIdentifiers.id_alg_noSignature, DERNull.INSTANCE)); + v.add(new DERBitString(new byte[0])); + + return (X509Certificate)CertificateFactory.getInstance("X.509", "BC").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); + } + public static X509Certificate createCert(X500Name signerName, PrivateKey signerKey, String dn, String sigName, Extensions extensions, PublicKey pubKey) throws Exception { @@ -166,6 +194,12 @@ public static KeyPair generateRSAKeyPair() return kpGen.generateKeyPair(); } + public static X509Certificate generateNoSigRootCert(KeyPair pair) + throws Exception + { + return createNoSigCert(new X500Name("CN=Test CA Certificate"), pair); + } + public static X509Certificate generateRootCert(KeyPair pair) throws Exception { @@ -204,11 +238,10 @@ public static X509Certificate generateIntermediateCert(PublicKey intKey, X500Nam caKey, subject, "SHA256withRSA", extGen.generate(), intKey); } - public static X509Certificate generateEndEntityCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) + public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { - return generateEndEntityCert( - intKey, new X500Name("CN=Test End Certificate"), caKey, caCert); + return generateEndEntityCert(entityKey, new X500Name("CN=Test End Certificate"), caKey, caCert); } public static X509Certificate generateEndEntityCert(PublicKey entityKey, X500Name subject, PrivateKey caKey, X509Certificate caCert) @@ -222,8 +255,8 @@ public static X509Certificate generateEndEntityCert(PublicKey entityKey, X500Nam new GeneralNames(new GeneralName(caCertLw.getIssuer())), caCertLw.getSerialNumber().getValue())); extGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(entityKey.getEncoded()))); - extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); - extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); + extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); + extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); return createCert( caCertLw.getSubject(), @@ -247,8 +280,8 @@ public static X509Certificate generateEndEntityCert(PublicKey entityKey, X500Nam new GeneralNames(new GeneralName(caCertLw.getIssuer())), caCertLw.getSerialNumber().getValue())); extGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(entityKey.getEncoded()))); - extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); - extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); + extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); + extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); if (keyPurpose2 == null) { extGen.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(keyPurpose1)); diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/X509LDAPCertStoreTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/X509LDAPCertStoreTest.java index 98419dab77..03c31c2ed2 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/X509LDAPCertStoreTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/X509LDAPCertStoreTest.java @@ -9,12 +9,12 @@ import com.unboundid.ldap.sdk.LDAPResult; import com.unboundid.ldap.sdk.ResultCode; import com.unboundid.ldif.LDIFException; -import junit.framework.TestCase; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.jce.X509LDAPCertStoreParameters; import org.bouncycastle.jce.exception.ExtCertPathBuilderException; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.test.TestResourceFinder; +import org.bouncycastle.util.test.SimpleTest; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; @@ -39,18 +39,10 @@ import java.util.List; public class X509LDAPCertStoreTest - extends TestCase + extends SimpleTest { - public void setUp() - { - if (Security.getProvider("BC") == null) - { - Security.addProvider(new BouncyCastleProvider()); - } - } - - public void testLdapFilter() - throws Exception + public void performTest() + throws Exception { BcFilterCheck filterCheck = new BcFilterCheck(); @@ -96,7 +88,7 @@ public void testLdapFilter() //shut down ldap server ds.shutDown(true); - assertTrue(filterCheck.isUsed()); + isTrue(filterCheck.isUsed()); } private static InMemoryDirectoryServer mockLdapServer(BcFilterCheck filterCheck) @@ -116,7 +108,7 @@ private static InMemoryDirectoryServer mockLdapServer(BcFilterCheck filterCheck) return new InMemoryDirectoryServer(serverConfig); } - public static void readEntriesFromFile(InMemoryDirectoryServer ds) throws IOException, LDAPException, LDIFException + private void readEntriesFromFile(InMemoryDirectoryServer ds) throws IOException, LDAPException, LDIFException { InputStream src = TestResourceFinder.findTestResource("ldap/", "X509LDAPCertTest.ldif"); BufferedReader bin = new BufferedReader(new InputStreamReader(src)); @@ -168,11 +160,12 @@ public static void readEntriesFromFile(InMemoryDirectoryServer ds) throws IOExce // addEntry(ds, "dn: cn=chars[*()\\\0],dc=people,dc=test", "objectClass: Person", "objectClass: organizationalPerson", "sn: chars", "cn: chars[*()\\\0]"); // } - public static void addEntry(InMemoryDirectoryServer ds, String... args) + private void addEntry(InMemoryDirectoryServer ds, String... args) throws LDIFException, LDAPException { LDAPResult result = ds.add(args); - assertEquals(0, result.getResultCode().intValue()); + + isEquals(0, result.getResultCode().intValue()); } static void verifyCert(X509Certificate cert) @@ -199,7 +192,6 @@ static void verifyCert(X509Certificate cert) { CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(pkixParams); - } catch (ExtCertPathBuilderException exception) { @@ -210,7 +202,7 @@ static void verifyCert(X509Certificate cert) /* check we get a suitably escaped subject. */ - static class BcFilterCheck + class BcFilterCheck extends InMemoryOperationInterceptor { private volatile boolean used = false; @@ -219,7 +211,7 @@ public void processSearchResult(InMemoryInterceptedSearchResult result) { String filter = result.getRequest().getFilter().toString(); - assertEquals("(&(cn=*chars[\\2a\\28\\29\\00]*)(userCertificate=*))", filter); + isEquals("(&(cn=*chars[\\2a\\28\\29\\00]*)(userCertificate=*))", filter); used = true; @@ -231,4 +223,16 @@ boolean isUsed() return used; } } + + public String getName() + { + return "X509LDAPCertStore"; + } + + public static void main(String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new X509LDAPCertStoreTest()); + } } diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/AllTests.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/AllTests.java index b2059df179..51e9d6ece8 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/AllTests.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/AllTests.java @@ -46,6 +46,8 @@ public static Test suite() suite.addTestSuite(LMSTest.class); suite.addTestSuite(SphincsPlusTest.class); suite.addTestSuite(SphincsPlusKeyPairGeneratorTest.class); + suite.addTestSuite(SLHDSAKeyPairGeneratorTest.class); + suite.addTestSuite(SLHDSATest.class); suite.addTestSuite(PicnicTest.class); suite.addTestSuite(PicnicKeyPairGeneratorTest.class); suite.addTestSuite(CMCEKeyPairGeneratorTest.class); @@ -63,14 +65,19 @@ public static Test suite() suite.addTestSuite(SNTRUPrimeKeyPairGeneratorTest.class); suite.addTestSuite(KyberTest.class); suite.addTestSuite(KyberKeyPairGeneratorTest.class); + suite.addTestSuite(MLKEMTest.class); + suite.addTestSuite(MLKEMKeyPairGeneratorTest.class); suite.addTestSuite(DilithiumKeyPairGeneratorTest.class); suite.addTestSuite(DilithiumTest.class); + suite.addTestSuite(MLDSAKeyPairGeneratorTest.class); + suite.addTestSuite(MLDSATest.class); suite.addTestSuite(BIKEKeyPairGeneratorTest.class); suite.addTestSuite(BIKETest.class); suite.addTestSuite(HQCKeyPairGeneratorTest.class); suite.addTestSuite(HQCTest.class); - suite.addTestSuite(RainbowKeyPairGeneratorTest.class); - suite.addTestSuite(RainbowTest.class); + suite.addTestSuite(MayoKeyPairGeneratorTest.class); + suite.addTestSuite(MayoTest.class); + suite.addTestSuite(SnovaTest.class); return new BCTestSetup(suite); } diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumKeyPairGeneratorTest.java index 6dce5215be..122847af29 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumKeyPairGeneratorTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumKeyPairGeneratorTest.java @@ -68,9 +68,9 @@ public void testKeyPairEncoding() DilithiumParameterSpec.dilithium3, DilithiumParameterSpec.dilithium5, }; - kf = KeyFactory.getInstance("Dilithium", "BC"); + kf = KeyFactory.getInstance("Dilithium", "BCPQC"); - kpg = KeyPairGenerator.getInstance("Dilithium", "BC"); + kpg = KeyPairGenerator.getInstance("Dilithium", "BCPQC"); for (int i = 0; i != specs.length; i++) { diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumTest.java index 8385a82f4f..dd043070d0 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/DilithiumTest.java @@ -242,10 +242,10 @@ public void testDilithiumRandomSig() public void testDilithiumKATSig() throws Exception { - byte[] pubK = Hex.decode("1C0EE1111B08003F28E65E8B3BDEB037CF8F221DFCDAF5950EDB38D506D85BEF6177E3DE0D4F1EF5847735947B56D08E841DB2444FA2B729ADEB1417CA7ADF42A1490C5A097F002760C1FC419BE8325AAD0197C52CED80D3DF18E7774265B289912CECA1BE3A90D8A4FDE65C84C610864E47DEECAE3EEA4430B9909559408D11A6ABDB7DB9336DF7F96EAB4864A6579791265FA56C348CB7D2DDC90E133A95C3F6B13601429F5408BD999AA479C1018159550EC55A113C493BE648F4E036DD4F8C809E036B4FBB918C2C484AD8E1747AE05585AB433FDF461AF03C25A773700721AA05F7379FE7F5ED96175D4021076E7F52B60308EFF5D42BA6E093B3D0815EB3496646E49230A9B35C8D41900C2BB8D3B446A23127F7E096D85A1C794AD4C89277904FC6BFEC57B1CDD80DF9955030FDCA741AFBDAC827B13CCD5403588AF4644003C2265DFA4D419DBCCD2064892386518BE9D51C16498275EBECF5CDC7A820F2C29314AC4A6F08B2252AD3CFB199AA42FE0B4FB571975C1020D949E194EE1EAD937BFB550BB3BA8E357A029C29F077554602E1CA2F2289CB9169941C3AAFDB8E58C7F2AC77291FB4147C65F6B031D3EBA42F2ACFD9448A5BC22B476E07CCCEDA2306C554EC9B7AB655F1D7318C2B7E67D5F69BEDF56000FDA98986B5AB1B3A22D8DFD6681697B23A55C96E8710F3F98C044FB15F606313EE56C0F1F5CA0F512E08484FCB358E6E528FFA89F8A866CCFF3C0C5813147EC59AF0470C4AAD0141D34F101DA2E5E1BD52D0D4C9B13B3E3D87D1586105796754E7978CA1C68A7D85DF112B7AB921B359A9F03CBD27A7EAC87A9A80B0B26B4C9657ED85AD7FA2616AB345EB8226F69FC0F48183FF574BCD767B5676413ADB12EA2150A0E97683EE54243C25B7EA8A718606F86993D8D0DACE834ED341EEB724FE3D5FF0BC8B8A7B8104BA269D34133A4CF8300A2D688496B59B6FCBC61AE96062EA1D8E5B410C5671F424417ED693329CD983001FFCD10023D598859FB7AD5FD263547117100690C6CE7438956E6CC57F1B5DE53BB0DC72CE9B6DEAA85789599A70F0051F1A0E25E86D888B00DF36BDBC93EF7217C45ACE11C0790D70E9953E5B417BA2FD9A4CAF82F1FCE6F45F53E215B8355EF61D891DF1C794231C162DD24164B534A9D48467CDC323624C2F95D4402FF9D66AB1191A8124144AFA35D4E31DC86CAA797C31F68B85854CD959C4FAC5EC53B3B56D374B888A9E979A6576B6345EC8522C9606990281BF3EF7C5945D10FD21A2A1D2E5404C5CF21220641391B98BCF825398305B56E58B611FE5253203E3DF0D22466A73B3F0FBE43B9A62928091898B8A0E5B269DB586B0E4DDEF50D682A12D2C1BE824149AA254C6381BB412D77C3F9AA902B688C81715A59C839558556D35ED4FC83B4AB18181F40F73DCD76860D8D8BF94520237C2AC0E463BA09E3C9782380DC07FE4FCBA340CC2003439FD2314610638070D6C9EEA0A70BAE83B5D5D3C5D3FDE26DD01606C8C520158E7E5104020F248CEAA666457C10AEBF068F8A3BD5CE7B52C6AF0ABD5944AF1AD4752C9113976083C03B6C34E1D47ED69644CAD782C2F7D05F8A148961D965FA2E1723A8DDEBC22A90CD783DD1F4DB38FB9AE5A6714B3D946781643D317B7DD79381CF789A9588BB3E193B92A0B60D6B07D047F6984B0609EC57543C394CA8D5E5BCC2A731A79618BD1E2E0DA8704AF98F20F5F8F5452DDF646B95B341DD7F0D2CC1FA15BD9895CD5B65AA1CB94B5E2E788FDA9825B656639193D98328154A4F2C35495A38B6EA0D2FFAAA35DF92C203C7F31CBBCA7BD03C3C2302190CECD161FD49237E4F839E3F3"); - byte[] privK = Hex.decode("1C0EE1111B08003F28E65E8B3BDEB037CF8F221DFCDAF5950EDB38D506D85BEF394D1695059DFF40AE256C5D5EDABFB69F5F40F37A588F50532CA408A8168AB187D0AD11522110931494BF2CAEAE36979711BC585B32F08C78496F379D604D5321C8C62B59EDC23AE1FC7742135918E01B02E411630E26E675400D5AD2C776FCC0A6711A966C11312AD9A821D8086542A600A4B42C1940720242628106210A43852331709308108B188C022492C1B28412C4218B042181C8610248059C9201C0348819326C582046891868A2C28D82346A1C094200A28CE3A6491C112CC24812E0902191985062C084622451CA062C64240E1BB3312496854B4606DB2668C38268441046C9B6211404811445502442084422710B92459AA0811A91709C241003957004C504C82692D29200C0B260C0A26809190AA2300E188969E0008DD84862DA14712018051907440412409B1240118010D142819928508B1091022464A0206D1246211C838C1B4769010690CC062481846920982C24120521B15041360298446ED1A63111056AD3A840CAA84C62B00003134A53344614194004C54CE306695AB08961168ECB10808B168ED990640B94602483851AB30454262251B8251C424A0B814842C4445A102023808409B7254CC64814854D19380E601651D8326A0A918908C170E0964D18468C01328D91C4054A0061230868A2104210A8611306218A248E620689C9B24508278451200D980466DC42054424852426282221612016090BA62C0A1144E0928158480D422210A006098B246E81288CC0248090308D8436404CA68450042494B68DA2926D18B344A00085E3B805140504A4C290842281C3262D0B2066CC903198382810166CC13445C0102224C688034632D840901C20680415289A188144988D9C206E9C302CC1B820614221080310A0C28C58128553204C0330814CA48D44C08D51404C1CA72C440865A03840DA20808106858C260DE2A88C9C4411594228C42604441426A1426408C0851101869B483199B20C80464459A88C0042089882900AB54562244812960544124600C88813A061E1284D0AB9914B962099B84400314E98128500B60183A00D14150E1881101901224A06681A498DE1A28411C63121262591A06D030524A1B6089444724334125BB42041B650D0888D0B074D1C94644C208E8B8808E0300944200549864D03134E19C9840937611A43684A80900204311C1742184080C8308EE1A241C33404A3282251247188D6FEF46712CA182872AB2919678AFF9D94E743E063A39E0C35CAF72A7F2EDA28E65858520D5D8467DE747CF340653B52C268F55413F5ADDC7D49011EC33EDD537423A84288869337AEA0781A124269071451722DB3BB8F2CE5B1552F83D2AF07F25613918A9F4E6F1257603888E589308CA5F95F07143D23BAAE17520B36B6E0E94FAF6845EB2131AEC383E63BC8644EE5F1ACCBA82F9211E57AFCBF509C1131A37466BC91B357DCBBBC14CCC319C4CC6AC75FCDC82C6596D07770C8277AD370B192A0B4E05F812E0E265D2912AA29F03FC9F72DFA69C9B1291A3FC583642B235F6991A954788347F60A0328C48ECEE51BA02DFF323ABD911667CB14549B618F1C5D250CAC9E35E071601992FBEC0BAE6F74213081404744D12F2A0E04BDB265E0924CADA40D1FA1F38ACA4606BFD4575712B8260A456FDDEEEFE7CA259BCDA97B9B939A5FD2889C9B49FB7D4E3553DEA61B3339BD0E6B16BF3BB227103BF9202E72DC502E28F7CE1559A4631F372520324E4EBA07545F78BF4D94B0E5B8BF51B8F176533D5CFEA5232F283A47605FA65DDB17C891C251011C4E98EEB6EB00CB65BA31C8F025C87A9FE02DBC10C5D83A065EBA5D7B2A19D5A1CB2C160AE166E867F2AF8C7D49D63FB83A614957FC0A3B5A5C74990E9A2B02120C7E6DE37E155FB472F50F0A45E47CF5F9D7A4C82982C9DC86AE877C3FD1885943E439FB003C7A9A42F71B4FF6F0A28B140CBDBA6E71B13AC31B23DE9EAB7837E15A69F833EB7B56A71D8BC2CAF1F2A31C345BD5F46EE013A7C689372337191DAA800C0AC6C46C9FF688B1A01347F257C474AA3D97C1D63A8C00E0A37B681673F57C1C9C8FCCD46F174C74A29D84CEB71F7E6B2F8CD2B089ED43F7C96DAE81A223418C20B16F1DF3D1A978AE28F6DF35EC559D04D20EC74B224AEA31A289B015B069E9CBBBF7CF6DE94CFB2A96E4AE3462C96003CDDA87DB561AF2CE3C0BA1D90413FDCE3CCF4390C02C1CB9F654F4820EC33015457D4A629FBF39419CAB7642D6885E103FCE0D4206CCE7C12C6FC44FA33AD0864C3371A7CBE820E3B371B656A38F2E7FF18FE4A50C8AB3F85D783FB57835CED8490B84EE0D99AF0D64C483CEB6366FF54F8AC8A40DB1AFA573A4FB326C74F0236ECEF3DA7120665CCE05DD654B5071723A8348E7CD7793513819B61CB64E1328E8B22E7664BD6B41B5710D19EA8809D4450850E907DFC4D0B75F588CECE962E9E0937CE1402446A4D2891A46E6617FB29D4FCD712606F7819ECA60F7E0D5B19E7FFB57C73C16FFEEB90038410CB9FCBB5E9D51EB3EB6297E9FF6AB7088FE2D9B237BC24CF7F8290118A5E0E00A0B903FB6375C848176CD0A8C8875CC59199CDA11A87A78F65CC404330B087571FD0633E27129FDAB5A8A1F793E52412B0083FD5C74DB3CF60C2543CE7C91B2800E40203F8D99FE5FDE5B108E7EDC80EBB9BB34986EC5C5A8F580E75752907FF0F294C866C2CF1F362E840B6881BD43219201781C63B0039A95BCFB4A0FECE569DF00523CE9C084B022B3B022242E28419796ACF0A0C995F948DBFFFD30D77ED105A3C9943C406B305BC81A6A248A291548F2A67F438D966A57D53F4B7BE15354E581BE16F7AD64D164E85787DF5849C810AFC28D06482F441B5FDE3DB2ED36DD25AA6664D4D43FFA32EDA25689C9F4A5D514FC66231C5401520922524438EF1DC78D693C9718DEBBD243312674C899F18910E389C8EBE505824BCC42CD4A9ACE193768220219011F3B1F335427BFF9E8BDED5C08711A09C2B71CB964C56A8393BFD2B56E9B6B2F513E682587DC1B8ED196066326871025628036700063176D345DE384E182D6C417A32AB11095EF59BB4D171B9CF81D17AC42664DED933CCB722C69857FFC53C8E7F2474B0CB2DFF2DDC8A5C601C84A701981199BCCF74112A6EC062C4FEB601A028AF01032ADB6BD15D4C2B9550AA850AD62CCC3A3665D5212B12E0FD5C5326A1E5EB1F10D557D94605E8E3F356E08FF7FD884ED3C4205463594C9AF2F39E4B1274695234B54EECED93F460EDF1A13C2CB4B17D322F6F79FE16F0357C1C4739863E796791F8647FABF730AB00E0DA509706D94571740F61F7BAF366D2774C9B5B8C61DD6BE9819A6028B264BB2E4AEA54B56D4ECAB5B528CE0C0C0CCDB73023352CB00445BAB6F7467B4644D4361C464FAC6B5B137D32391021B475FCB5F31774FD8ECABDF65475F25574C65559CB331F41C0F498B74DD941C344C50D8E64F9578714A32561FAACEAF78148E6DA4B566826925714B17108AFDD546385A3CD454D5CAA16960916282A47C4315CE236BD9E3255C604EBDC39772DB5CE0B236"); + byte[] pubK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139fdd6a6ce5bc76e94faa9e9250abd4cee02cf1ee46a8e99ce12d7395781fa7519021273da3365519724efbe279add6c35f92c9d42b032832f1bf29ebbecd3ec87a3af3da33c611f7f35fa35acab174024f118979e23bf2fe069269a2ec45fbc1b9c1fb0e1f05486a6a833eb48adc2960641d9af6eb8b7381b1ec55d889f26b084ddfa1c9ed9b962d342694cede83825309d9db6bd6ba7582132534861e44a04388a694242411761d34e7c085d282b723c65948a2ac764d9702bd8ed7fe9931d7d8704a39e6508844f3f84843c305594fe6e5404e08f18ed039ac6563cbaa34b0ca38320299d6256ec0f78d421f088159d49dc439cbc539a55884a3eb4efc9cf190b42f713441cb97004245d41437a39b7b77fc602fbbfd619a42363714b265173cae68fd8a1b3ca2bd30ae60c53e5604577a4a3b1f1506e697c37432dbd883553aac8d382a3d250cf5b29e4d1be2cbcd531ff0e07e89c1f7dbc8d4529aeebe55b5ce4d0214bfdec69e080bd3ef36cca6a54933f1ef2f37867c0d38fd5865b87929115808c7e2595458e993bacc6c5a3b9f5025001e9b41447708bfbaa0462efa63876c42f769908b432f5485508a393224960551d77eadfaf4411cbc49fdff46f2f155ddd6ec30867905b709888ca0f30f935fb8d7f4803cfc7a5f7790ca181d99ca21f2621d69a5c6d49c76b4969da62740a378470332b30947ab31ccdb9ba0c7b625879eec4bd81f0200ba23504a7dc3b118bc2ab1145df13af3c8cc39f577873b84911b3d85fbbf4cb19e4d36b10a938eeb78b599dc86615fd6cec6eb7b8f7afa5f6d6be19ea81630d36ccfb2f487de50d0cf46da8d3fe3512812043c0e3ef2d7231fb0b0a35a0fb283be30a1247780f30ae0294e8b6f5897383edb895595f577524df54593cdf927b4967616ee3913e4d6b29b0dbd7c33a2a45e4ef1b1954ea5d91ce37efc1302e7ce02a97395565da2a5c5d3fdb0d87684e9b1c0ad07ec33df2dfad528e2ea0966d2a47dd5ee88e77d653c0d004fab0165f0757c4da40af327e7192536c79947a80a827aa2107dacfae3debfc8fad3d6e08076d938c510a276bdf6721a1f087cb169515028ad5ce27a1047abd92809934ca63b893f71f9a34a99c0fd30310c47e9aa37394d0ab73b254d3ca69d9c5549c9479aae24264ac5ea64d3fd821c3962ec77e709f9d30bc7b65a52e48c16e80603558caca1811411c3155d1f949fc9cf9aa9385a7199e99be77a66fad7eed91258de55b2c4c83f9a050adebea5f09758f40dac4a1c394ee8d687879150d26426895ab1938e14ae11b376254c91fc6130436996f8ed43bd27be20ec9067111c116ec94cc2b06cc91a13c5d10bbd7eecea4792f17b2b77631ef145e9fb41a83eaa11c2b72a48fb90fdbd88644c4edf8ab20dce3118364b276ac1237b36c8926e346aab5a111aa0bf341c518b7bff9e9dbb8bcb4728601b3760663e67650331e6fb54ac82fc414cb8ddfc160a25311ec5272de46217fef8b992ff89754fbee351f21bb90b6c97078b510c983350681266c8fed1f0583c5151e7b8fe3b7292319699687cc6b641fdbd689428543bc0fa1facc109de65b62784c2d985ab15d77d3af12af6d03e8d1859a553688584d75ef673a1de74093ee108c761fff32c217c231b0e2953daf521429264c0963bc8a5cdeddc617a7285b934ea51ddb5cdab23bcede86be36e001bc65c65e9a1c94baff4fab8eb5f8ed42ec377423633fe00049142467c47c5d58a7202c8e9104841c1f7f380145a6a0a828c570235e507ae5868a6062f722bb98ff6be"); + byte[] privK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139ff037b84e75537e0a1cf02a517acfe323ffffe11df72e4f38430e0e66a2654b2f2ef757da47649d9f63fa03f1bf6fe6bc7c62971a98a2bd9d36eb0ec43ad4e9d940df3bb5874f5c92192aa31e0535d3cf70950bba858d11a688eaf854f63ecfc520c50d624891434265d8b0680c03061040299a104082c0910c8508d1100d44a6509408292211125b90508a2688e1302dc4021280028ac302611820851237808a000ae2040421b4910bb80550a08051b2511c28428a3672a494504910201bb45161424424a75001328181942d62a850023449ca94200b296213156408924c48122100b605030208e0060200a311e1802021116483a62898029291480801083041066613200e5b360951400c53000aa08851944842e316704ab2089b92440025121b0309418209c2a0800b290a819851c4340da4424500a0105b048e603400138928a4422648002c90202d194068e2146d19278a083746e4146914006422c660d3a03013242844965014166da0284dcc462e94367100232e1c114909a2040131060a2172c2142ada000c5a260d13228a62c444e3142d013445980224d33841c0308121a621e348720b1984d2c89108b8690887714a2884d496451a9301ca2285da30859ac851dcc00820106060465262302aa224251044640b2842988011540692144251d236719bb4900b082890188e41c469e1a469032160e01409d3020c20c88c1cb23164086218476920228ccb8470089528029550533270013405888424541041d202881aa84ccac88181008d0392899ab809d9900c9a1290614065c9322d89860c123521cc4266c8360010062411028ea3b44d44023043a0285a002ed1980c4882658922441c010212907084226e12134d011902519064113364c91806c2c04589262908b63024308cda022e0c27250b367058162c5116420b4946c1208841246c99466a04434e18a86c821661922028639409c30211029520211782d43868003460c84688e0160000a32dc0a82824b640831464c81022a2086503234ac8122ea098418c2072cc308a62c665093408412682da429089328514967081226001176d5948428ab88d592051d80892e2c0889044700ac0245a020904218a59c45094441094140820460209270c441020dcc8209212015038250c456e4a1666223770dc808ca426412222441ba3618a343099844099c42952046d88146ccb242a7cd129a8d333115c62d033b6a8357cf7cd10268ab12f16fceb7975d0a28a6c4822213c9a772df084ad91a669e2040550fc5e8d0aeb10fab2375fc9625ef9cd48c19631997a1cb6455d2c6286c569c9637add0317ce990996b28e51c3f3f717fb5907bbdd53961ad3497f2c3c473cce170906ac4c624a89aa8fbe624d99385e9c9548bf05e8cafd47d2476e41b73001f813726499e88b2b3b6f596ca311657850346598994c40e34747161e4e76264deef2a3019389d1594c942301af47b7544c23ecda2df2dece81e487d8f3f58ea89cd811d7275807ff1b0369ba86470088c174a3099fdafbe5fbb4d158801053b2b435d54059e26dee76d10a7a372f06b0b88b985b32f52052387438be8dc8bc6ae7369e2da9aa5e2585f8de403d091ccb7f790d54ddb34c608b0876f2825e9113be20a2b85867a01bda53287ac780bcd8b606d2e6d7712c56ce0142d22fe6b786de544963e134fecedfafb83d763061d799096a59e30d4472e440ae1faaabdf42640ce69740ceb9cae1a9612c21931b74af3f780236123321b205b6efd6cbb134f4c73d63c0c13e660b59d5920bc33197c355853d8d1cddc7959f7bc500ac81d985016f5b89a0eec79b0d9364ead8e38577c2a6549f2d067cb09438fdb21220aec80f6e22a476f332a2a4a0b7acbeb9e078d2b5a92ae84c924f7cb19fc7df377beb6546af97aa985c747cd111a127a674b4c26d89c14485b82e3a498a12d05406febd6c4d4b8bc051ab2cb91224b078538374b794b7dd9ddf3ac2b4a671fb7b9cf5acb78622ae2709eb2db16943aa24a9c97a81077bc784d25c0ea5991d2de883798a1f0e78f3361ed6a10dded81b1d683658331534fd7c01bc0eb00dfc4c3c84f0693046ff806bb200dd7bd4c0e6abca3f2934b4814fc0e1f8be615a2dda7c8a8d06cf9ce8566b40f4a6543b25bacddc926863fc0fa2007d6d7bf6d18dc98df696bd0865bf0be4c492b8043a32def8e3595ba7da345252f38f95be10fd7fb899b498fa01b09de5d5608eabc44a721aa04c4ef1dcb86102ac5f5f79c9708dcf5c5e896edd8c2c7bde3fa83e6ffce22d66174e31657a0b6361585e669d3031952f08631ae1f16ff90b90d0aad3c6d7e1dd0a9c41ab00a6e1c4f96af9ac5b79fcf821ffc016cb059245fb78dbe6c633d965aaab5333be07195c4b74b18e4600ce783c0a914ef4281016e80a7c9aa92d0fd789879c5e6751125ecb154432311e41cebd4fab3a31e4d2ce22d0f8c67737bf8a0dd85fe1349d5079a4d5feb3fee9378ca47ae46cc58a3f02038cfd53c4cee9cc4270cebc3d115a39c831e8ed41c4dbe4051b51d7872ba0c2bb163e0085201188eaa624a6bea9400a3a1fcc355a57f15704e61fda55a5dbaea8448fa5cb2d377a07f58305ad107e844ab4806e5bf99c1f513ee1d0a2acc04549f0801742169a77971d0adbfbfe0dd2ee5d16bc461e35748d1f3f6f4598321e8c49e79e740f990359858d2729dde007fcb26fdda9aa6e2ec4bd736f2836e7e4c83440191c849f6a53c72a4f8f830d001ea3b18f3cb4a5bd3cf066032b4932cfd2e62a9b55723fa61c688c935518af6860cd649bfbf1bf5fdc1f36dcaefaa157438d1cc8d56a150161511df82631f5e88e773e4ce263f276b7b3678d4c6fc75311d411c0d01bfdb595bb70552838e1b86517c837d909e772b428599e1fe569f77ce61531fde6fd31cdce1bdee4ba467fcbfbb9feeaad99fef67d4906e036c73662ddce158d4e5d4635e5d366f79f31a19d1b3dc4a591b0df194bb06c18147f41d88d1a409becdfb67eb063d16312266fd51b521ba9115e2e5e2aeae6ec511cede13ed4132ffbe0273f6c7039b3874f058804a54809af60557a21d9b4b831d04156a7c22dcbcdfe14f62437f449cb5ef12bf4251d485496cd835c0c2bc58bd845963dfa76ecd68519c4bdaf110be7ab052876dc3407591568c956ea3bf107c90fd5853a292f59a8d4b58b5d3fddf29bdbeac36852e3c69766fe460176a801831292b8e88a74a01ecbbe09a7b4d74cfd7fd628841944d9d556dbd60c76f96f07dc53443805ee9aa09365de4fb8179252c6b099b5dd351fdefc23dbd8090596c5d208ffd2c5661d8e5612dd574fc69045c769a969e600d77cfe192f1d3ae911289355c585811491b0ccd73692ab158824ab9edf8ac8193f0b33e6138b72c6dcd5d344f807b3da92425037de5ea4eead1c795effaa145e2ecdd327606eb2609929b9474b2bb04653602555c068385e92f06f29ca613ce5b4404f01ab1805db0acaa890330d291f40692df382509302b6dc8668f2c8f2d3a44fd58dca26e9802794f73d25b3149e6d576441"); byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode("3D7F3A26A1A6DC133D036981F7406AE0858C74121BDA303DD5DA8D9ACB68409F1051C88C4B163C252DDB5E78E8EB867279A17289B34CD3BA4AA199AE56B28356EE49FF8304086E7CAA6B0DBA7EF60AD5ED9411A82FF9BE7D6177908977EF67CCD532A4723F125F4748B350C3948F2AC6C4F006CACB8C92CDC0941CDE2EFB4B732BF85954F4BA8417561403A863E0261A29D79987859976B4F8BDC7BC5EF215A07ED6004343CC7CFE79ECC7143AFD525CA35ADB5D603CAF97BD0A80104E4DE48FB41668F314415096E3547554D25FA09E9C14E60BD15A6DDCD0710A0FED464079229CA65A636E15D9215283767241FB6EED385B51416660F95AA8A619B55FA38B9A7CB710FBC0AD6237C72BECFB9D3182229E06A696B5E32B4B2EF2164349B54266BA9734EAD45387CA913507E3E75B49FEA7D3BD03A7EEE2EE8AFE048DD9E38686D5A1C5DB31A8FC960FD3575496CD301CDB952D8CF85792DEDF7FF6FA5BBF5101288EE80AFE1183B4A6689AE72E66B50393DC3345DF62BA2DCB999158FD8FD9A75AF95ED9C3EA325FEC21C5B611B267B938AE02580C72FB94E8910DBA88A32811B6FEE8A04355EBDEEDFAEC85F5FFDD6811FA4A3CC6323CDD93E6CE7F98688022401AF54288BF888B289F972FB98ECABF0D2C364344BBD2FFDAAE518A66370FF6BCA7D996B03BA3140890840E5EDD3EB98672D266F47A2E15255656CA978F14943BD40B1B21041173F6058391AA259D7E4F76C10DA3CF3AEE9B71A127A55DCB80AD822337C1D79C763CD7774A31A58743A4797D52DD3959A66BDB08338D007E2CA7CD19B0C553045C40D3E7AB0D318378799DD9A02B6C2B0C7C9B8DB986668598605163709193AC4DF5B19A5CE28BDD7CAD59AFF10FAA2220284DBE5D4C7FDF2792C559A6076865081D5F4513CFAE092458FD410E18BE1BC5F970660BB0C89C020079C121A1953C2AF9298A6342D1C47C413B4B3C35DD91358DEBE7DC109F35A3512514DBEBB544851709EC1A750550422F1C9FA40B50DE08DBFDE90593D229E01BD9F0756CBA1EBACB8CC2139D4CADC778BF937BD524E8845ECF964A04F7C43CD056F6A7A810C77C8B8FA73359CD1EB8670E1AF7F4BC247B7EC515C1BBA404B76635762D4E0EF451150C8A58437C06FD2C4154A00D63408F1EEE5D1B67F7F4893C158A765237C4FDB215CC0E3F4D60437AF43EF9AC575C0C6B85A93D5493DAB60961D55C4BEACE3A907597CCFC7C6EFB5453DCF83796AFD070322A650BDEA47B76DFF7756CEA567961830E7DC49B2A8923C59BECADD06435D6EFBC7F5307FDA057DAEB1C5B4F6E64D8E141A46090C9EF90D3816453F975C3C7158560DAFEE463148AC0E1E5351020F0A7C08A7C14C1AA9581C936EF845E011E82DE64FB4CB49DA4E3C8D079EF7DEEB41665C6ED43A4F161CBB795AC4FE1A67D6FE18CFB1A15BC02066A2598EFAA9FACC5BDD7257C68E309B2E2622D8C647A3D4656DEB71D414100049AA42C991F997F81A9B391449C4DAB874F9F309463A508E950501590FBC2ED4E80C2D63CE0DB72DE74D7CF9AAC845BE2502B89247D971EB5169A583677CC88C569067E726F9DDD1B49E80220F5B764CE4A32049E20C7FC2A573BFB911EB4AF50B9C2E1F5195AE76FC2F54D0BA33F2CDE2DB3084C5E5F25155D8D81082EAEF09C598A699373B5CCFD7DFB9ED2DDA4DD4681B073B24D6135D65A8ECB41CEB156B8D8F77A4DA1747239D0E7DE48441E90C62FB26DDB0E802DEEA997A6A2569885D0CBB2833A12D4BE92FFCB9AE3A3CFB01874C6A82427A7052ED0E6652DA9BA95280E24B65F8EAB174812011DD12D9062B1004C60DE85685D7D41FB5F04E9707E034A305B60145DF6686818CCA3457BA1DEEE0235D3B1D026F69A2AC556A1A93455F712C3A737BB4A30CE52F0204AB79F65B3E305EF89686D213B08AA538F4BA486C8709C8627C51DE86596D8EB035D807AFFC6F68D88E0B145DEABE8AAAEB411D085827E7CB47E3C568207FBEE7BA9568B414C0CADB05DA7D36F83037847A9F7233135F49FC14496485071CA5C5A0D1725C016E7482B6F9892D64FF76C6AF73330EE4C654654943F9966DAF3356C7ED8E4A0DD2F58B73B144D5FA286ADBE2A24776FEB78A4DD241EC3BF1DF78D5DDE6A48F8655F6FFC7D28543CA41F52F15CDC7CF092F48CEA91356D0EB1444A3290451033871F0006373F5A62CE9586ED95D3E361EFAD629B3A4D2C3643405DB4B7F837B7128C11E55C95C7F2AD80D507247485CFD4BE0A2EDDB877B3CE385C3ECFE71FF27ECA5D608AED19424037154B56BDB1A36908A09F1A50B1D89A21E6C0FB5C8AD21EC6DD997124DDF07F13BE0058583B070B2DF895223B7FB4A3A00343620436D6DA8114B779BC85CF9DE15C7EB6F26FD49F668FB33073554051B35DD0E5F62A66C47AF7CB3585A56E310FD7FB6336A5923AC5ACD57C72B348A1D8B42F52ABED61BFA58CAEBC9B20531F707C8A07813E66101282C30D86739AAD90790CFE9DE3C5D438318B696BB15BC2160A11FF03211CCEC77939F420BE1B6A8211565332779B86F18DA825F2F1174F4B9DF8C8F6F617648EE78C882688C4CE10C5FDE814B3917FF757AD7FE749129988CC43762002F89B24FADDC2D0926484C0C8B12B9944B177DB4A890E4826F72A4A0E19018781ECE90FB485443C7BE06C20C9DA7055F0AA87706B5A90DDB91834FAF746C2836C7C47496D8A0FD36FDAC574E924F7B514EDD7828215810D7370699C6C6C22D0AF97C289B49B99E4521EE8E8946FFCA48189C6653FA7F81D185E420D39B3BB34EDEC3D672AC0BA3890108400E25ED4CC877729F241E0D5BAED7EFC2BCAFC453BCEF9653C722D62C694420E509968F0BD3AADCCBD4E078B5E5B7E6A7833758167EC693E590982DCD54DCEA98BD3672E486E2A6F64A54366EEE3179636552CB832684B100D2AD75E91D86D7892DB3D7B3565953D35328973DAEF53955D8519B54A812550D8C11DD2A284845394A5395A7BC20F12450DC0C41769A2EDDA0A3256CFCFAF408F2405D31D795A8E1BC8C2A3E324595A96173575EF054F04214B0321A9A607E6DC6FA0EAF5CD0F26A3C1DEB15BDA4DB06E196AA145ED7ACD2E311B5C29AFFB26BC126E37FDBA4ECBE3A171CE7901161D62064B5F6B667D6011CEB90A19B8D05A4D2B1BFDDD8886F8F622F63D7E14D61B87A9177AF6EFCBA41E95BA35B2D0E330F9CAE832EA3CAA46DFBA1CB2D88D96B34F5DE2C12255AF89D0BC7FA9E5AAF1FC0A84CC3B6E9BDF25652A44F0DB30C4CEBE9298373CF54E73DA942D060F112B2F525364A3ACB0D2D3DEE2E7F908202D3E7C8FAEC5CFD7E0E3F506272A405D7486A0A7B2C7D9F3F8FC06222546647AAEB4CCFE00000000000000000000000000000000000000000000000000111E2D37"); + byte[] s = Hex.decode("fcc4f40c043066771043d494eb13181802151a8f82c5c4e29582f6b0fa35023fa7042b68c6630fd99b8152265f4e439ff2430197e57d4195f3bdb6e92e707f964006001f748b94ed0249414226b5f439ab4daa261f9b549f40fd2c690521a5934230c808899473ce5abb67f406a020db59ead7c5eac5c53156a4bb603603b46db9c2fa5f5bf26fbb67c3a98a399ef245d30d761a1adda9d4439d1d1ce86480c2b123e984209fcc830a300b1c8108e320d34a27a752b2d0cec268de0f9f9eee7f4c7cca6f64d8a0288f6c92699cded9cacca31d80e6bb5107af87d1021fc6787d79f001e04a4aabfbaef2b172c5010e6389ab8075496f50558fba91c70e6440640f522b6a38bbe429cfd5352031eb651721823a3705514b6aebb9c3954f79fd01cb228d731d7a41b462cc1a1c855905ff17f14d7f8b71d0f17c03e4239d2881012f94466fcd1e66e62227d6812f8b81157b8954a671391c064838cb215c79fc6fc9d85ef0c891aea9e9ab16500cf06613a02ca82d25decfdbd1a81090b280b4e3213a5db5f7020d30d8169ea176975f72d1910c64684afc2516a35ec35308c4d127fd5c9f54786d2f7ff60c6110514d6bd7720507ec9ede750e4b9929b20ffa65dd714eb11e4e0865c3d2930d8170018e9eb29b72b1e66b7a65afae1617d752ea435f88db7f87dbd29e9859957eb73b766c38675e96d1be9c4404297e6e40b5009fa9adde177980d25bf3b76c130682f8105c1257bd20b9624b09157d2f6ed42dd9b080903603786a0ec3a0d8a847999eb4788f23f1a95db1f5818dadcbad60078a8b1be01d02ac3ee9ba88cf5909a4d4318d9fd2a439aa37e8da68f6208dc5ec3cd659a5aaa3362ad0ff4a3ba6ed5ea75cb710c83bda0afbc14ae4a61e19a0ab4e9597bcfdb9da986308322cd7f534b173f76e0151e693b52bd2029a7ea294bad8ced7ca0485e58c73a71eb5ddc1bfa12f2a0026aec90db969e6cea486e6628903e75275a39a1105aad7abe683660e02b6fc12bd59227358bc20a49eec69b4c03318c90bb3d9725ac1fe6f9609349b14eea21ea996cb118258035213a8fab19339cea94043667cf2ee596c3fb01d136d40450adbf9761d047e6897b975d291a53097b747bc9d6342e91b88bd0a2e7d6444973557ffae72123d84b228131951dda7a10f993f2427a9a9dc822d822363c9517dca0bfffa2f6aa66e3fe5802c05026b72c03813ef26a90855565d419d402ad1b3b1719c2d23637c425eb1cfaa6e5bb82c87735b802ffb1fdd6693385af5f96a73a8e482e9128f428571edd73c1495be9ffb2a6b5a28a1b8a30ec737f82989e328433255e53cb901764f0c0341cb67e5c6275fee34e35c3e6057cc1af790bb111b5a7a2f86de7c680f42d838ac4e8059677c9d382f167af649253f31c00120e797ec93d0a31af80b44ad2fbf0a8a1f67d1a63ee448d85442677f24c60d581555fb6c693bf8829e5062f4b3a66f028c7505600464138d4c026100e55d878434aba2d41d0e90d4dda9e2bd46c337efce479f999cb50adc080575ecebfd1ce6ad6450f9d7ec025c793493e8c11059d3fae194476efd16742fa2d1a399d6cdffc0a6cf1e4e13ec0f515c21846b9da843f2b0af70de17f7bcbc11a2f11e9cb1efa24a28477c0fc5ea4f6a644e608c028e5aab8f82109a07ce8a06e99012593f32051d865f561cfb365312ef49338ceeeb3842ce1ee2381a1641043c32c852a1add433075ddb94863749b3c7dc6ac10e681293deba2a355843a1ead7448f2af81beb5500357a81a5375355941ea2172c96e1cfb84120f93496943d344af409a8573bbf5961d1dd044bc2ce21ad2b7c5c721b324d697e786e711a8c08d358f52b96507b6d380048e4783740ff996610aa6a2b5e6788d68b065717b507bcb2df05e0af6268735bd5e929798ac5e0f12fdab6da267dab9102c6ae20451e644499c2c8408eeeac9abc7130dee6c33144819ef78905b45dbb9fef7ebc92871092a8aebaf9c754544b055fbdc52b760687b15b22d3582e3d881c5afc00b360f504c67fc90ccdb1ee8d8626f7f12596fdf9ba95621bd00a5f6331261da4340d5bc5a4cc222f60d9e220f6e1b56d1492b20d68b75d7cef20df2737821980efca83822f19cb4f5ece26665e6b07c43b65715df26632534e84d7b3d109a5fb026052bc9323a02a41a5d194ef0990713a578219b989b9a5383cb64e4cdd8ab3ca7807895272490b3cf72a01ae21615bf6af12f2283cc1cc400ed660bba87dfe9bc1e26c29c50ff3a01a14f83b52d20116f8b7b3b133810476a38c588d36f85c5c9def402b13e89201aacdacdf2c6ea8cc0e819423e86f080d6690a136ac4879c26e9a45c80a0d5d77d7ec4f0e395ac5bfb0b67d6ba617fff4f3f0bdbf50a383827db69a405590ad8bd752f55ef299800e1a5eeca7dec712b4343cd82ed6cd96c60fa0c65a960105d3717d3391ac116c868202c11b11ef2cdb2e8a3f3df1940c8f98c372c6d9989044b922f48b38e97168ce900a5af99bd9a81cd1e26109bf5de678e5c1d42b8fd29a738ee2125aca3ca9f5dc18a0e36a16bd64c04c498667e95fbc582affcdbc4ef896fcc1971352e2195d235321f750bb5ebb44bc3c411f7129518780dee0fb706ed16cc749753b8ee44ca7008a6922ab90c803002260f6f5c605436306d96c9b7c538a19cef0d35479d1dd5e5874e3b1a2ff4c1b50b942c3f166d7d9e51f870faba93a2ddf2b32b21f7552606af24772b428cf47d473f8a5cd2fab4c1bdbcbcc9abb6d017e2f0f3f18e224c4f3b1f0384021dd8d58e8b62c1f2011cf17343b0cf86774fc8b85882fbfc6e884cfc97bafb90d6381a647aef10dbcfe263863311fb30d91d885b049d41050f461b08de163cbb1b49ae1b4bcd64175bb3b96b154cd2946dd2961b629bd13beda7867c93b31242aaad973db6f92093880461a43071a62b361cff82bae2f32be33f1e36062f8f7ab7fb3c50c8c5ea6d7e0fb023ab994c45e8b43bcc6ace4e7b0529a41842b64aabf0cfa30c5d98f7897ace3074dd75f0f61f228d911def6258b3b3e95487d301ebdd9c80fe323e7929897784c04da3b52c5ff6fee1f28e309bede2ca244af7a30ae146137f472cff9ecfc2d1fb7e20f9108a6c8bcec4cbb877f3fa15820e5e21596949dd4b2d659f3e450d6f5e715cb307da9af905af6f695b519f5af28e2c3bc4c7633f1191486be9969746cc8c0b70405d9c7f77f8cadc2cacd9c492b774902cf9ced338fe612909795ae6c951258faa52b5f5a363ddedf5a10a4d4e8e253242b626f7ec8d5eff9050a393b3e44494b748397afb6cbccd4f8f9fa364955787a878a96a5acc0c6cbd9eaf6123242446e96a8b7c0d7dff1000000000000000000000000000000000000000000000000091c2c38"); KeyPairGenerator kpg = KeyPairGenerator.getInstance("Dilithium", "BC"); SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); @@ -257,6 +257,7 @@ public void testDilithiumKATSig() SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()); ASN1BitString pubSeq = pubInfo.getPublicKeyData(); + assertTrue(Arrays.areEqual(pubSeq.getOctets(), pubK)); PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); @@ -273,7 +274,7 @@ public void testDilithiumKATSig() byte[] genS = sig.sign(); assertTrue(Arrays.areEqual(s, genS)); - + sig = Signature.getInstance("Dilithium", "BC"); sig.initVerify(kp.getPublic()); diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/FalconTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/FalconTest.java index 5908b82825..df2c864705 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/FalconTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/FalconTest.java @@ -2,6 +2,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.InvalidAlgorithmParameterException; @@ -9,6 +10,8 @@ import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.Provider; +import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; @@ -23,10 +26,14 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.pqc.jcajce.interfaces.FalconKey; import org.bouncycastle.pqc.jcajce.interfaces.FalconPrivateKey; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; import org.bouncycastle.pqc.jcajce.spec.FalconParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; public class FalconTest extends TestCase @@ -41,8 +48,72 @@ public void setUp() } } + public void testOQSPublicKeyExample() + throws Exception + { + try + { + // Register BouncyCastle PQC provider + Security.addProvider(new BouncyCastlePQCProvider()); + + for (Provider provider : Security.getProviders()) + { + if ("BCPQC".equals(provider.getName())) + { + System.out.println("Provider: " + provider.getName() + " " + provider.getVersion()); + } + } + + // Read public key + byte[] data = ("-----BEGIN PUBLIC KEY-----\n" + + "MIIDjzAHBgUrzg8DCwOCA4IACQTGjlTc0dE3Gt3rHNvjaQ1VdPgRBbdS3LK+50W7\n" + + "FEESAMeCdwFMSFiBhjlVDvCHnodDXnzLRacPjekdlvWew6pAYSITnjmk6hXQQCOJ\n" + + "NSnppbCbCC+R1XEjBrCPvFnTNm5maSjzUoMT75iZ9sNu0SALQeFGa0w9vvaK4g7S\n" + + "UiU02OYjZdUdTVG7DCK8RxaGRVCmCH5G60YmJNuYcExZtV01L6jYuDprjjd05aoT\n" + + "2Kp0pjp1Ms2gj6AsubmcG7c0MFEN07pCvEyROYWqMgST6FseW6l5y1XVHrA8tsDH\n" + + "ga0xum3zcRaNIEXhXgKaXeEusTQRAxqVvfI5dghVaiRp1eIWgTgRwaya7IuGkFXK\n" + + "CXWDPy9myAGUn5pEvL2WM5uZtrJC5daKQreojXT96rmg+MoKlhnkaYbOcgWBGVAJ\n" + + "+akOqdwBoK6UU58cpVR+yGnrqE6cAwZdgthQyAWYBaxSI86ydoIia0tacomTrLw7\n" + + "ujD1CC2YuzJjRQOpjyPd+7SCpSEzacao4CNvso3H5+jkJIW15hjbn1sVupYyk+cJ\n" + + "bnk91o5NuqbYTQbKnohShayHfZh6NiJAmm0QB2WSGgQVq5J1BKjGHcSOp9hOSMLM\n" + + "TGr6PvIlQRVy8XQjA1Tdj7CFt9iNX5eYSSlWIgVuIkLrKClvMBmnS+zErVnR/OBO\n" + + "xokvoKFWHKqpTn5NCw1bxIBO5XTZ4UWplh37h29WYgKwt6QljS6+6xCXTL2m1tZh\n" + + "q8grMflqsctTmlQl14TWVqllkAATrUQned44pmahupl1TETfHVp9cMbCfBYHWbTe\n" + + "IRVkpYbgCCjMJKSDjocEqONhQkktxC0lxlQIVKlWTJ83tFMHW9Z7tdlJyHefF6dh\n" + + "R4Ozi6eEyGE49ZkAC3JmR2EKDXUYUFNfIoKX5LIBwBLCN/B6pKMSpBENe0jhbtlL\n" + + "XSHIpy0yl8rKsudMFjxJapSzyxs4rbFTe0SFMDjgwz9MJHROcpgHLEmOGBlFr8bP\n" + + "uJm+A/yWn3sh+vS1A+NsBH4R8gedRK7YSdoJBnUkp/LUyPJK+oGAwoJZXwiFyQxN\n" + + "r0R8x8Iqy3Y4oXWGLcYnQUEpAPjFQbCEONrlpUanxPSoQ9sMLKinxemTWD35rsXN\n" + + "iW09ZO6hYaiVggY8ETeZHXnN8eCcG7s88GejwisLGVY1I4cdkHLuNxmEn9yr4adL\n" + + "Huc6\n" + + "-----END PUBLIC KEY-----").getBytes(); + + PemReader reader = new PemReader(new InputStreamReader(new ByteArrayInputStream(data))); + PemObject pemObject = reader.readPemObject(); + reader.close(); + + byte[] keyBytes = pemObject.getContent(); + + // Load the public key + KeyFactory keyFactory = KeyFactory.getInstance("Falcon", "BCPQC"); + PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(keyBytes)); + + // Print information + System.out.println("Public Key Algorithm : " + publicKey.getAlgorithm()); + System.out.println("Public Key Format : " + publicKey.getFormat()); + System.out.println("Encoded Key Length : " + publicKey.getEncoded().length + " bytes"); + System.out.println("Encoded Key (Base64) : " + Base64.toBase64String(publicKey.getEncoded())); + + } + catch (Exception e) + { + System.err.println("Failed to read Falcon-512 public key."); + e.printStackTrace(); + } + } + public void testPrivateKeyRecovery() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("Falcon", "BC"); @@ -80,7 +151,7 @@ public void testPrivateKeyRecovery() } public void testPublicKeyRecovery() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("Falcon", "BC"); @@ -233,7 +304,7 @@ private void doTestRestrictedKeyPairGen(FalconParameterSpec spec, FalconParamete } public void testFalconRandomSig() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("Falcon", "BC"); @@ -266,10 +337,11 @@ public void testFalconRandomSig() * pk = 096BA86CB658A8F445C9A5E4C28374BEC879C8655F68526923240918074D0147C03162E4A49200648C652803C6FD7509AE9AA799D6310D0BD42724E0635920186207000767CA5A8546B1755308C304B84FC93B069E265985B398D6B834698287FF829AA820F17A7F4226AB21F601EBD7175226BAB256D8888F009032566D6383D68457EA155A94301870D589C678ED304259E9D37B193BC2A7CCBCBEC51D69158C44073AEC9792630253318BC954DBF50D15028290DC2D309C7B7B02A6823744D463DA17749595CB77E6D16D20D1B4C3AAD89D320EBE5A672BB96D6CD5C1EFEC8B811200CBB062E473352540EDDEF8AF9499F8CDD1DC7C6873F0C7A6BCB7097560271F946849B7F373640BB69CA9B518AA380A6EB0A7275EE84E9C221AED88F5BFBAF43A3EDE8E6AA42558104FAF800E018441930376C6F6E751569971F47ADBCA5CA00C801988F317A18722A29298925EA154DBC9024E120524A2D41DC0F18FD8D909F6C50977404E201767078BA9A1F9E40A8B2BA9C01B7DA3A0B73A4C2A6B4F518BBEE3455D0AF2204DDC031C805C72CCB647940B1E6794D859AAEBCEA0DEB581D61B9248BD9697B5CB974A8176E8F910469CAE0AB4ED92D2AEE9F7EB50296DAF8057476305C1189D1D9840A0944F0447FB81E511420E67891B98FA6C257034D5A063437D379177CE8D3FA6EAF12E2DBB7EB8E498481612B1929617DA5FB45E4CDF893927D8BA842AA861D9C50471C6D0C6DF7E2BB26465A0EB6A3A709DE792AAFAAF922AA95DD5920B72B4B8856C6E632860B10F5CC08450003671AF388961872B466400ADB815BA81EA794945D19A100622A6CA0D41C4EA620C21DC125119E372418F04402D9FA7180F7BC89AFA54F8082244A42F46E5B5ABCE87B50A7D6FEBE8D7BBBAC92657CBDA1DB7C25572A4C1D0BAEA30447A865A2B1036B880037E2F4D26D453E9E913259779E9169B28A62EB809A5C744E04E260E1F2BBDA874F1AC674839DDB47B3148C5946DE0180148B7973D63C58193B17CD05D16E80CD7928C2A338363A23A81C0608C87505589B9DA1C617E7B70786B6754FBB30A5816810B9E126CFCC5AA49326E9D842973874B6359B5DB75610BA68A98C7B5E83F125A82522E13B83FB8F864E2A97B73B5D544A7415B6504A13939EAB1595D64FAF41FAB25A864A574DE524405E878339877886D2FC07FA0311508252413EDFA1158466667AFF78386DAF7CB4C9B850992F96E20525330599AB601D454688E294C8C3E * sk = 59044102F3CFBE1BE03C144102F7EF75FBEF83043F7CFC20C20BEEC007DE3F041FBF0BFF401041030C40040FAE7E103F7E100085FC013D1410C80C2F000810461C2F480BEE8017D17F07F1411BA24013C1BDF83DC407D17E07C13917F0F9044045FC40BD0FF07D07EF0003DFC1F3CFFD1FC03FEFC0B8FC6E7B0BBDBD0FE0BE17D14307EFFE0FBFC6F81FBFF43EC1F87041D42083EC3DC2F4407BF84EC4140FC403F037F3FEC013E0FEE02180082F83FBE07BFFE043F40EC6FFB1BF200007FFBFFA0FFF6FFBCE83EBFEBEFC0FFDF3F103FC6F3FF0500A18718308007D03F200E4213BF04FFD17D000F0017A17F180E04FFF07DEC2244048148E8704503EE06F86080243F81FFF03BF4003F07EF3DE02FBFFC00420C1F40FBDF0707E043FF5FFD0000430400C4F49F4207C142F80EC3E010BFF7C13F07FF85F7F17E07C17FF33FC4EC303FFBCFFEEC41830FF0831BDF45F05F06FC503B0C0F84E4013E100E7E1441450C2FBEEBC0C0FBEFC60BCFFEF3CFBDF4303EF800BF2BE0BF001F01F43F41FFE08517B001141E00144F7EF8007CEBDFFFF4213A0B9F8A0FE04103C17E0820BB1C30C30C00FFFFC00007D18017CFF90C3101E7E103040FC4FBE04213E07AF80FFEFC80FBFBD0810BCFB8FBC087FB8FFF1010C2E81002F3EF3BF01F07E41FBC07F2C0FB8F43F401C5D81FFCEBE07C07E0BF17EEBEE830C514003FF7EF3E08403D1FFFFE105F840C20BDF0607FFFEF46E7EFFF08000400DE830000F3F82EF9D82E84EFFF3CEC4E81E01002103102EFC080F3B0801041BAE42F7F040F83EC31010031BC0410FAFF9F0004010133A089FFEF7BE8317A0020FEF010052BA04107E100F821C2F41F44F4EF7B000F02E41F82F380830FE08A1F707FF82EC7F42E81004041103E8307B13D0FDFF8F830F9FC5FFCD7E040F410FFFB9F423750860C11C5FFA144EC0080F02DC0F420820450790020BCF80EFFFBCEC4FBFF4200AFC00C02060C004303EF81FFA104107E4117AF01F81202FC1E44143FFE206EB3E881BB13F13920403FF7A000144102E7FFC2143E7FF4AF3F13F07E181DC317E240F4500303F2DDDCF1E1513E3EF15E8DC1309E50AEE03EFDC17081706FD03E6ECE4F30EBD1909051906E90CE806EB0B19E719EFFBF10D0DF1DC0CF6F1F4F8FEFBE9F9550E2107FCDCCBDFE9F4F7EE1AF8142115F910002AF2F5FF141ADA220AECFE040CEF0B29EB201930F2D3E401E5DEEFF4DDEA17F1FE141217F81C36050109F8F61F02DD19F90310C7F40208E9052C3942F8FFF2CCF9FDF83CFA12DC091C0D02F00411F5281E40D7F92DBA11D73D04C10BFD13E617110AF3ED05F6CFE705E0F70E1FF80533FC120C002CE81FF52638190FE3FED6F0FBBB23E6F408EF32220B13DD27F007E5FA00D72614F0E302210707EC111E070E2A032DF91DE3FCE800F1F9F2F7FE170101180412CBD1E90019F2011522DAEAED13F8E5F425DCEF24E01CE614E7DCEC01F2F4F914F4010107ED26E2E9DF0BF5F007EA07FAFBC6D7E607FAFCFD270DFD0D17FC4EF0EE00071AECDE09F8F215E113F80209CCF308D7E6251ECE0EDFED0CC9F4050B2714F61BF703F0EBF104010DEBFBF21AFC1BF01823FEDEFAF7F807E3F3020AEB01FE19EEE8E90D00E5FAED1EFDF628E5F0E6F0FC13F4FB05FB0B09EA0A0E08EE13293212E90CE4FEF223F4FF030BEBED1B402ED2F6171102BC0CF9E9F335ED0C01FAF0FEFAE41DF0050A162C11171CD90BEE211218EDFAFA0F03F4171412F319D60B01FAEE1F2823F0D6EF12D6DFEAFBFC170DECDA06E7CED500031E * sm = 026833B3C07507E4201748494D832B6EE2A6C93BFF9B0EE343B550D1F85A3D0DE0D704C6D17842951309D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8290765843D1E460D17A527D2BCA405BD55BBC7DA09A8C620BE0AF4A767D9DB96B80F55E466676751EAABA7B93B86D71132DAA0EB376782B9EEE37519CE10FDD33FE9F29312C31D8736206D165CF4C528AA3DDC017845E1F0DD5B0A44FF961C42D874A95533E5B438982F524CA954D87533BFBE42C63FF2ABC77A34C79DB55A99171BBCB72C842A6530AF2F753F0C34AC632F9F1E7949F0BF6C67665B27722A8857D626B6FF1A136D923A39F4069B7477FF946E5247A6627791D49B59EDC9E2525A860E6E9828D18F64A9F17222E8166A02453859BBDA0B8186D8C9928BB571E4146401D7430E225904673AD21CCAC54C146C248A1DD69AB6491E901D6D71B152155BE97DE057F3916A3F1B4273308C29B2F4D9697167B90681B1583ED930A71E990467DEA368134BECEEBD597F9BEC922E816F1B0570D728F4AE0464C1F797657F87A4E52DCDCAEB9272662EA66D7C6CD8781B31AF555AD93F5F65E75816CB8DC306BB67E592B5261BACA7C509629EA2AF8ABB80CBA89EE535B76DFD9CCBBE3BF48F2BC8AA34B26E1103291053F5CB8DE3A45AFA5A76DF8B2122ED2C82FBCF2259290D41A14F86B12F35F5D49762B34CFF13EE7E42EDEC70201D7F37C33316288FA3078E36E58108865C3CFE263D563692043DECC62F3426F86061285B7B1B336F56FF41BB65E9CD6D9B92FD90F864AA1C923CB8C755F5CDE1770D862595427149D7721AAAB5D194AEA9ACDECA15BE43CBA6A62B5A33909E9FC4DA1C5814FBD7CD6A2FA572E318B42C6C319140B86E66392580A11A2B431F44C1F9270E4F7B2490F3B325A9977A71A575915636635B9969DBD6D220B24C3D99CEBBBD834B88222BD08C3ABE124E80 + * * @throws Exception */ public void testFalconKATSig() - throws Exception + throws Exception { byte[] pubK = Hex.decode("096BA86CB658A8F445C9A5E4C28374BEC879C8655F68526923240918074D0147C03162E4A49200648C652803C6FD7509AE9AA799D6310D0BD42724E0635920186207000767CA5A8546B1755308C304B84FC93B069E265985B398D6B834698287FF829AA820F17A7F4226AB21F601EBD7175226BAB256D8888F009032566D6383D68457EA155A94301870D589C678ED304259E9D37B193BC2A7CCBCBEC51D69158C44073AEC9792630253318BC954DBF50D15028290DC2D309C7B7B02A6823744D463DA17749595CB77E6D16D20D1B4C3AAD89D320EBE5A672BB96D6CD5C1EFEC8B811200CBB062E473352540EDDEF8AF9499F8CDD1DC7C6873F0C7A6BCB7097560271F946849B7F373640BB69CA9B518AA380A6EB0A7275EE84E9C221AED88F5BFBAF43A3EDE8E6AA42558104FAF800E018441930376C6F6E751569971F47ADBCA5CA00C801988F317A18722A29298925EA154DBC9024E120524A2D41DC0F18FD8D909F6C50977404E201767078BA9A1F9E40A8B2BA9C01B7DA3A0B73A4C2A6B4F518BBEE3455D0AF2204DDC031C805C72CCB647940B1E6794D859AAEBCEA0DEB581D61B9248BD9697B5CB974A8176E8F910469CAE0AB4ED92D2AEE9F7EB50296DAF8057476305C1189D1D9840A0944F0447FB81E511420E67891B98FA6C257034D5A063437D379177CE8D3FA6EAF12E2DBB7EB8E498481612B1929617DA5FB45E4CDF893927D8BA842AA861D9C50471C6D0C6DF7E2BB26465A0EB6A3A709DE792AAFAAF922AA95DD5920B72B4B8856C6E632860B10F5CC08450003671AF388961872B466400ADB815BA81EA794945D19A100622A6CA0D41C4EA620C21DC125119E372418F04402D9FA7180F7BC89AFA54F8082244A42F46E5B5ABCE87B50A7D6FEBE8D7BBBAC92657CBDA1DB7C25572A4C1D0BAEA30447A865A2B1036B880037E2F4D26D453E9E913259779E9169B28A62EB809A5C744E04E260E1F2BBDA874F1AC674839DDB47B3148C5946DE0180148B7973D63C58193B17CD05D16E80CD7928C2A338363A23A81C0608C87505589B9DA1C617E7B70786B6754FBB30A5816810B9E126CFCC5AA49326E9D842973874B6359B5DB75610BA68A98C7B5E83F125A82522E13B83FB8F864E2A97B73B5D544A7415B6504A13939EAB1595D64FAF41FAB25A864A574DE524405E878339877886D2FC07FA0311508252413EDFA1158466667AFF78386DAF7CB4C9B850992F96E20525330599AB601D454688E294C8C3E"); byte[] privK = Hex.decode("59044102F3CFBE1BE03C144102F7EF75FBEF83043F7CFC20C20BEEC007DE3F041FBF0BFF401041030C40040FAE7E103F7E100085FC013D1410C80C2F000810461C2F480BEE8017D17F07F1411BA24013C1BDF83DC407D17E07C13917F0F9044045FC40BD0FF07D07EF0003DFC1F3CFFD1FC03FEFC0B8FC6E7B0BBDBD0FE0BE17D14307EFFE0FBFC6F81FBFF43EC1F87041D42083EC3DC2F4407BF84EC4140FC403F037F3FEC013E0FEE02180082F83FBE07BFFE043F40EC6FFB1BF200007FFBFFA0FFF6FFBCE83EBFEBEFC0FFDF3F103FC6F3FF0500A18718308007D03F200E4213BF04FFD17D000F0017A17F180E04FFF07DEC2244048148E8704503EE06F86080243F81FFF03BF4003F07EF3DE02FBFFC00420C1F40FBDF0707E043FF5FFD0000430400C4F49F4207C142F80EC3E010BFF7C13F07FF85F7F17E07C17FF33FC4EC303FFBCFFEEC41830FF0831BDF45F05F06FC503B0C0F84E4013E100E7E1441450C2FBEEBC0C0FBEFC60BCFFEF3CFBDF4303EF800BF2BE0BF001F01F43F41FFE08517B001141E00144F7EF8007CEBDFFFF4213A0B9F8A0FE04103C17E0820BB1C30C30C00FFFFC00007D18017CFF90C3101E7E103040FC4FBE04213E07AF80FFEFC80FBFBD0810BCFB8FBC087FB8FFF1010C2E81002F3EF3BF01F07E41FBC07F2C0FB8F43F401C5D81FFCEBE07C07E0BF17EEBEE830C514003FF7EF3E08403D1FFFFE105F840C20BDF0607FFFEF46E7EFFF08000400DE830000F3F82EF9D82E84EFFF3CEC4E81E01002103102EFC080F3B0801041BAE42F7F040F83EC31010031BC0410FAFF9F0004010133A089FFEF7BE8317A0020FEF010052BA04107E100F821C2F41F44F4EF7B000F02E41F82F380830FE08A1F707FF82EC7F42E81004041103E8307B13D0FDFF8F830F9FC5FFCD7E040F410FFFB9F423750860C11C5FFA144EC0080F02DC0F420820450790020BCF80EFFFBCEC4FBFF4200AFC00C02060C004303EF81FFA104107E4117AF01F81202FC1E44143FFE206EB3E881BB13F13920403FF7A000144102E7FFC2143E7FF4AF3F13F07E181DC317E240F4500303F2DDDCF1E1513E3EF15E8DC1309E50AEE03EFDC17081706FD03E6ECE4F30EBD1909051906E90CE806EB0B19E719EFFBF10D0DF1DC0CF6F1F4F8FEFBE9F9550E2107FCDCCBDFE9F4F7EE1AF8142115F910002AF2F5FF141ADA220AECFE040CEF0B29EB201930F2D3E401E5DEEFF4DDEA17F1FE141217F81C36050109F8F61F02DD19F90310C7F40208E9052C3942F8FFF2CCF9FDF83CFA12DC091C0D02F00411F5281E40D7F92DBA11D73D04C10BFD13E617110AF3ED05F6CFE705E0F70E1FF80533FC120C002CE81FF52638190FE3FED6F0FBBB23E6F408EF32220B13DD27F007E5FA00D72614F0E302210707EC111E070E2A032DF91DE3FCE800F1F9F2F7FE170101180412CBD1E90019F2011522DAEAED13F8E5F425DCEF24E01CE614E7DCEC01F2F4F914F4010107ED26E2E9DF0BF5F007EA07FAFBC6D7E607FAFCFD270DFD0D17FC4EF0EE00071AECDE09F8F215E113F80209CCF308D7E6251ECE0EDFED0CC9F4050B2714F61BF703F0EBF104010DEBFBF21AFC1BF01823FEDEFAF7F807E3F3020AEB01FE19EEE8E90D00E5FAED1EFDF628E5F0E6F0FC13F4FB05FB0B09EA0A0E08EE13293212E90CE4FEF223F4FF030BEBED1B402ED2F6171102BC0CF9E9F335ED0C01FAF0FEFAE41DF0050A162C11171CD90BEE211218EDFAFA0F03F4171412F319D60B01FAEE1F2823F0D6EF12D6DFEAFBFC170DECDA06E7CED500031E"); @@ -292,9 +364,9 @@ public void testFalconKATSig() PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); ASN1Sequence privSeq = ASN1Sequence.getInstance(privInfo.parsePrivateKey()); - + byte[] privCat = Arrays.concatenate( - new byte[] { 0x59 }, + new byte[]{0x59}, ASN1OctetString.getInstance(privSeq.getObjectAt(1)).getOctets(), ASN1OctetString.getInstance(privSeq.getObjectAt(2)).getOctets(), ASN1OctetString.getInstance(privSeq.getObjectAt(3)).getOctets()); @@ -321,7 +393,7 @@ public void testFalconKATSig() } private static class RiggedRandom - extends SecureRandom + extends SecureRandom { public void nextBytes(byte[] bytes) { diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCKeyPairGeneratorTest.java index f5e08f860a..f866b4fbd5 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCKeyPairGeneratorTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCKeyPairGeneratorTest.java @@ -31,9 +31,9 @@ public void testKeyPairEncoding() HQCParameterSpec[] specs = new HQCParameterSpec[] { - HQCParameterSpec.hqc128, - HQCParameterSpec.hqc192, - HQCParameterSpec.hqc256 + HQCParameterSpec.hqc128, + HQCParameterSpec.hqc192, + HQCParameterSpec.hqc256 }; kf = KeyFactory.getInstance("HQC", "BCPQC"); diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCTest.java index 107512a2be..3451ba96eb 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/HQCTest.java @@ -16,10 +16,15 @@ import org.bouncycastle.jcajce.spec.KEMExtractSpec; import org.bouncycastle.jcajce.spec.KEMGenerateSpec; import org.bouncycastle.jcajce.spec.KEMParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.crypto.hqc.HQCKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.hqc.HQCKeyPairGenerator; +import org.bouncycastle.pqc.crypto.hqc.HQCParameters; import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; import org.bouncycastle.pqc.jcajce.spec.HQCParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; /** * KEM tests for HQC with the BCPQC provider. @@ -27,16 +32,28 @@ public class HQCTest extends TestCase { + public static void main(String[] args) + throws Exception + { + HQCTest test = new HQCTest(); + test.setUp(); + test.testGenerateAES(); + } + public void setUp() { if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastlePQCProvider()); } +// if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) +// { +// Security.addProvider(new BouncyCastleProvider()); +// } } public void testBasicKEMAES() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); kpg.initialize(HQCParameterSpec.hqc128, new SecureRandom()); @@ -51,7 +68,7 @@ public void testBasicKEMAES() } public void testBasicKEMCamellia() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); kpg.initialize(HQCParameterSpec.hqc128, new SecureRandom()); @@ -61,7 +78,7 @@ public void testBasicKEMCamellia() } public void testBasicKEMSEED() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); kpg.initialize(HQCParameterSpec.hqc128, new SecureRandom()); @@ -70,7 +87,7 @@ public void testBasicKEMSEED() } public void testBasicKEMARIA() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); kpg.initialize(HQCParameterSpec.hqc128, new SecureRandom()); @@ -80,7 +97,7 @@ public void testBasicKEMARIA() } private void performKEMScipher(KeyPair kp, String algorithm, KEMParameterSpec ktsParameterSpec) - throws Exception + throws Exception { Cipher w1 = Cipher.getInstance(algorithm, "BCPQC"); @@ -109,7 +126,7 @@ private void performKEMScipher(KeyPair kp, String algorithm, KEMParameterSpec kt } public void testGenerateAES() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); kpg.initialize(HQCParameterSpec.hqc128, new SecureRandom()); @@ -123,7 +140,7 @@ public void testGenerateAES() SecretKeyWithEncapsulation secEnc1 = (SecretKeyWithEncapsulation)keyGen.generateKey(); assertEquals("AES", secEnc1.getAlgorithm()); - assertEquals(16, secEnc1.getEncoded().length); + assertEquals(32, secEnc1.getEncoded().length); keyGen.init(new KEMExtractSpec(kp.getPrivate(), secEnc1.getEncapsulation(), "AES")); @@ -135,7 +152,7 @@ public void testGenerateAES() } public void testGenerateAES256() - throws Exception + throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); kpg.initialize(HQCParameterSpec.hqc256, new SecureRandom()); @@ -159,4 +176,45 @@ public void testGenerateAES256() assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded())); } + + public void testReedSolomon() + throws Exception + { + byte[] seed = Hex.decode("416a32ada1c7a569c34d5334273a781c340aac25eb7614271aa6930d0358fb30fd87e111336a29e165dc60d9643a3e9b");//b + byte[] kemSeed = Hex.decode("13f36c0636ff93af6d702f7774097c185bf67cddc9b09f9b584d736c4faf40e073b0499efa0c926e9a44fec1e45ee4cf"); + //HQCKeyPairGenerator kpg = new HQCKeyPairGenerator(); + //kpg.init(new HQCKeyGenerationParameters(); + KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); + SecureRandom random = new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(seed)}); + SecureRandom kemRandom = new FixedSecureRandom(new FixedSecureRandom.Source[]{new FixedSecureRandom.Data(kemSeed)}); + kpg.initialize(HQCParameterSpec.hqc128, random); + KeyPair kp = kpg.generateKeyPair(); + String algorithm = "HQC"; + KEMParameterSpec ktsParameterSpec = new KEMParameterSpec("ARIA-KWP"); + Cipher w1 = Cipher.getInstance(algorithm, "BCPQC"); + + byte[] keyBytes; + if (algorithm.endsWith("KWP")) + { + keyBytes = Hex.decode("000102030405060708090a0b0c0d0e0faa"); + } + else + { + keyBytes = Hex.decode("000102030405060708090a0b0c0d0e0f"); + } + SecretKey key = new SecretKeySpec(keyBytes, "AES"); + + w1.init(Cipher.WRAP_MODE, kp.getPublic(), ktsParameterSpec, kemRandom); + + byte[] data = w1.wrap(key); + + Cipher w2 = Cipher.getInstance(algorithm, "BCPQC"); + + w2.init(Cipher.UNWRAP_MODE, kp.getPrivate(), ktsParameterSpec); + + Key k = w2.unwrap(data, "AES", Cipher.SECRET_KEY); + + assertTrue(Arrays.areEqual(keyBytes, k.getEncoded())); + } + } diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/KyberTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/KyberTest.java index 1d00846de6..b3b757a8bf 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/KyberTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/KyberTest.java @@ -48,8 +48,8 @@ public void testBasicKEMAES() performKEMScipher(kpg.generateKeyPair(), "Kyber", new KEMParameterSpec("AES-KWP")); kpg.initialize(KyberParameterSpec.kyber768, new SecureRandom()); - performKEMScipher(kpg.generateKeyPair(), "Kyber", new KEMParameterSpec("AES")); - performKEMScipher(kpg.generateKeyPair(), "Kyber", new KEMParameterSpec("AES-KWP")); + performKEMScipher(kpg.generateKeyPair(), "Kyber", new KTSParameterSpec.Builder("AES", 256).build()); + performKEMScipher(kpg.generateKeyPair(), "Kyber", new KTSParameterSpec.Builder("AES-KWP", 256).build()); } public void testBasicKEMCamellia() diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/LMSTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/LMSTest.java index aee03eefa0..095fc8e345 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/LMSTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/LMSTest.java @@ -23,6 +23,7 @@ import org.bouncycastle.pqc.jcajce.spec.LMSKeyGenParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Base64; /** * LMS is now promoted to the BC provider. @@ -30,6 +31,12 @@ public class LMSTest extends TestCase { + private static final byte[] nestedPublicKey = Base64.decode("MFAwDQYLKoZIhvcNAQkQAxEDPwAEPAAAAAEAAAAFAAAAAa3sRFhG3xQtT/xfuJJswgV80jvx/sFlYxteNrZ0hheITiUL/bJ8wJpphIpoSB/E9g=="); + private static final byte[] nestedPrivateKey = Base64.decode("MIG6AgEBMA0GCyqGSIb3DQEJEAMRBGcEZQAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAUAAAABrexEWEbfFC1P/F+4kmzCBQAAAAAAAAAgAAAAIO01yI+Hj7eX+P2clcPDW0SzllJ4uzQt1JenbcllHpQngT0AAAAAAQAAAAUAAAABrexEWEbfFC1P/F+4kmzCBXzSO/H+wWVjG142tnSGF4hOJQv9snzAmmmEimhIH8T2"); + + private static byte[] lmsPublicEnc = Base64.decode("MFAwDQYLKoZIhvcNAQkQAxEDPwAEPAAAAAEAAAAFAAAAAXjGRFXZMjGgOKA/sHWwYWNl6eTf5nI+RcEvlnIKQHQXpxNDreZCkeFm6x9CBN4YlA=="); + private static byte[] lmsPrivateEnc = Base64.decode("MIGhAgEBMA0GCyqGSIb3DQEJEAMRBE4ETAAAAAEAAAAAAAAABQAAAAF4xkRV2TIxoDigP7B1sGFjAAAAAAAAACAAAAAghIRA7xa5TChn4+0KIh1LvGLp14alEkmcz3m3v7kTiBeBPQAAAAABAAAABQAAAAF4xkRV2TIxoDigP7B1sGFjZenk3+ZyPkXBL5ZyCkB0F6cTQ63mQpHhZusfQgTeGJQ="); + public void setUp() { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) @@ -38,6 +45,20 @@ public void setUp() } } + public void testLmsOldKeyEncoding() + throws Exception + { + PKCS8EncodedKeySpec lmsPrivateKeySpec = new PKCS8EncodedKeySpec(lmsPrivateEnc); + X509EncodedKeySpec lmsPublicKeySpec = new X509EncodedKeySpec(lmsPublicEnc); + + KeyFactory kFact = KeyFactory.getInstance("LMS", "BC"); + + PrivateKey lmsPrivateKey = kFact.generatePrivate(lmsPrivateKeySpec); + PublicKey lmsPublicKey = kFact.generatePublic(lmsPublicKeySpec); + + trySigning(new KeyPair(lmsPublicKey, lmsPrivateKey)); + } + public void testKeyPairGenerators() throws Exception { @@ -82,6 +103,28 @@ private void trySigning(KeyPair keyPair) assertTrue(signer.verify(sig)); } + public void testKeyEncoding() + throws Exception + { + KeyFactory kf = KeyFactory.getInstance("LMS", "BC"); + + PublicKey oldLmsPub = kf.generatePublic(new X509EncodedKeySpec(nestedPublicKey)); + PrivateKey oldLmsPriv = kf.generatePrivate(new PKCS8EncodedKeySpec(nestedPrivateKey)); + + trySigning(new KeyPair(oldLmsPub, oldLmsPriv)); + + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("LMS", "BC"); + + kpGen.initialize(new LMSKeyGenParameterSpec(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w1)); + + KeyPair kp = kpGen.generateKeyPair(); + + PublicKey newLmsPub = kf.generatePublic(new X509EncodedKeySpec(kp.getPublic().getEncoded())); + PrivateKey newLmsPriv = kf.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + trySigning(new KeyPair(newLmsPub, newLmsPriv)); + } + public void testKeyFactoryLMSKey() throws Exception { @@ -97,7 +140,7 @@ public void testKeyFactoryLMSKey() PublicKey pub1 = kFact.generatePublic(x509KeySpec); - assertEquals(kp.getPublic(), pub1); + assertTrue(Arrays.areEqual(kp.getPublic().getEncoded(), pub1.getEncoded())); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded()); diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLDSAKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLDSAKeyPairGeneratorTest.java new file mode 100644 index 0000000000..5436818599 --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLDSAKeyPairGeneratorTest.java @@ -0,0 +1,196 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLDSAPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLDSAPublicKey; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jcajce.spec.MLDSAPrivateKeySpec; +import org.bouncycastle.jcajce.spec.MLDSAPublicKeySpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +/** + * KeyFactory/KeyPairGenerator tests for MLDSA with BC provider. + */ +public class MLDSAKeyPairGeneratorTest + extends MainProvKeyPairGeneratorTest +{ + protected void setUp() + { + super.setUp(); + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public void testKeyFactory() + throws Exception + { + kf = KeyFactory.getInstance("ML-DSA", "BC"); + kf = KeyFactory.getInstance("HASH-ML-DSA", "BC"); + } + + public void testKeyPairGeneratorNames() + throws Exception + { + ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[] { + NISTObjectIdentifiers.id_ml_dsa_44, + NISTObjectIdentifiers.id_ml_dsa_65, + NISTObjectIdentifiers.id_ml_dsa_87, + NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, + NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, + NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, + }; + + String[] algs = new String[]{ + "ML-DSA-44", + "ML-DSA-65", + "ML-DSA-87", + "ML-DSA-44-WITH-SHA512", + "ML-DSA-65-WITH-SHA512", + "ML-DSA-87-WITH-SHA512" + }; + + for (int i = 0; i != oids.length; i++) + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(oids[i].getId(), "BC"); + + KeyPair kp = kpGen.generateKeyPair(); + + assertEquals(algs[i], kp.getPrivate().getAlgorithm()); + assertEquals(algs[i], kp.getPublic().getAlgorithm()); + } + + // + // a bit of a cheat as we just look for "getName()" on the parameter spec. + // + for (int i = 0; i != algs.length; i++) + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algs[i], "BC"); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase(algs[i]))); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toUpperCase(algs[i]))); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase(algs[i])), new SecureRandom()); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toUpperCase(algs[i])), new SecureRandom()); + } + + try + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algs[0], "BC"); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase("Not Valid"))); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("unknown parameter set name: NOT VALID", e.getMessage()); + } + } + + public void testKeyPairEncoding() + throws Exception + { + MLDSAParameterSpec[] params = + new MLDSAParameterSpec[] + { + MLDSAParameterSpec.ml_dsa_44, + MLDSAParameterSpec.ml_dsa_65, + MLDSAParameterSpec.ml_dsa_87, + MLDSAParameterSpec.ml_dsa_44_with_sha512, + MLDSAParameterSpec.ml_dsa_65_with_sha512, + MLDSAParameterSpec.ml_dsa_87_with_sha512, + }; + + // expected object identifiers + ASN1ObjectIdentifier[] oids = + { + NISTObjectIdentifiers.id_ml_dsa_44, + NISTObjectIdentifiers.id_ml_dsa_65, + NISTObjectIdentifiers.id_ml_dsa_87, + NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512, + NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512, + NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512, + }; + + // + // We use HASH here as (while not recommended) use of both pure and pre-hash keys allowed + kf = KeyFactory.getInstance("HASH-ML-DSA", "BC"); + + kpg = KeyPairGenerator.getInstance("HASH-ML-DSA", "BC"); + + for (int i = 0; i != params.length; i++) + { + kpg.initialize(params[i], new SecureRandom()); + KeyPair keyPair = kpg.generateKeyPair(); + performKeyPairEncodingTest(keyPair); + performKeyPairEncodingTest(params[i].getName(), keyPair); + performKeyPairEncodingTest(oids[i].getId(), keyPair); + assertNotNull(((MLDSAPrivateKey)keyPair.getPrivate()).getParameterSpec()); + assertNotNull(((MLDSAPublicKey)keyPair.getPublic()).getParameterSpec()); + assertEquals(oids[i], SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()).getAlgorithm().getAlgorithm()); + assertTrue(oids[i].toString(), Arrays.areEqual(((MLDSAPublicKey)keyPair.getPublic()).getPublicData(), ((MLDSAPrivateKey)keyPair.getPrivate()).getPublicKey().getPublicData())); + } + } + + public void testKeyParameterSpec() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA-44", "BC"); + KeyFactory kFact = KeyFactory.getInstance("ML-DSA", "BC"); + + KeyPair kp = kpg.generateKeyPair(); + + MLDSAPrivateKeySpec privSpec = (MLDSAPrivateKeySpec)kFact.getKeySpec(kp.getPrivate(), MLDSAPrivateKeySpec.class); + + assertTrue(privSpec.isSeed()); + + MLDSAPrivateKey privKey = (MLDSAPrivateKey)kFact.generatePrivate(privSpec); + + assertEquals(privKey, kp.getPrivate()); + assertEquals(privKey.getPublicKey(), kp.getPublic()); + + privSpec = new MLDSAPrivateKeySpec(privKey.getParameterSpec(), privKey.getPrivateData(), privKey.getPublicKey().getPublicData()); + + assertTrue(!privSpec.isSeed()); + + privKey = (MLDSAPrivateKey)kFact.generatePrivate(privSpec); + + assertEquals(privKey, kp.getPrivate()); + assertEquals(privKey.getPublicKey(), kp.getPublic()); + + MLDSAPublicKeySpec pubSpec = new MLDSAPublicKeySpec(privKey.getParameterSpec(), privKey.getPublicKey().getPublicData()); + + PublicKey pubKey = kFact.generatePublic(pubSpec); + + assertEquals(kp.getPublic(), pubKey); + + pubSpec = (MLDSAPublicKeySpec)kFact.getKeySpec(kp.getPrivate(), MLDSAPublicKeySpec.class); + + pubKey = kFact.generatePublic(pubSpec); + + assertEquals(kp.getPublic(), pubKey); + + pubSpec = (MLDSAPublicKeySpec)kFact.getKeySpec(kp.getPublic(), MLDSAPublicKeySpec.class); + + pubKey = kFact.generatePublic(pubSpec); + + assertEquals(kp.getPublic(), pubKey); + + privSpec = new MLDSAPrivateKeySpec(privKey.getParameterSpec(), privKey.getPrivateData(), null); + + privKey = (MLDSAPrivateKey)kFact.generatePrivate(privSpec); + + assertNotNull(privKey.getPublicKey()); + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLDSATest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLDSATest.java new file mode 100644 index 0000000000..20228acafb --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLDSATest.java @@ -0,0 +1,930 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.Signature; +import java.security.SignatureException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1BitString; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.MLDSAProxyPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLDSAKey; +import org.bouncycastle.jcajce.interfaces.MLDSAPrivateKey; +import org.bouncycastle.jcajce.spec.ContextParameterSpec; +import org.bouncycastle.jcajce.spec.MLDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Base64; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; + +/** + * MLDSA now in BC provider + */ +public class MLDSATest + extends TestCase +{ + byte[] msg = Strings.toByteArray("Hello World!"); + + static private final String[] names = new String[]{ + "ML-DSA-44", + "ML-DSA-65", + "ML-DSA-87", + "ML-DSA-44-WITH-SHA512", + "ML-DSA-65-WITH-SHA512", + "ML-DSA-87-WITH-SHA512" + }; + + public void setUp() + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + Security.addProvider(new BouncyCastleProvider()); + } + + public void testParametersAndParamSpecs() + throws Exception + { + MLDSAParameters mldsaParameters[] = new MLDSAParameters[] + { + MLDSAParameters.ml_dsa_44, + MLDSAParameters.ml_dsa_65, + MLDSAParameters.ml_dsa_87, + MLDSAParameters.ml_dsa_44_with_sha512, + MLDSAParameters.ml_dsa_65_with_sha512, + MLDSAParameters.ml_dsa_87_with_sha512 + }; + + for (int i = 0; i != names.length; i++) + { + assertEquals(names[i], MLDSAParameterSpec.fromName(mldsaParameters[i].getName()).getName()); + } + + for (int i = 0; i != names.length; i++) + { + assertEquals(names[i], MLDSAParameterSpec.fromName(names[i]).getName()); + } + } + + public void testKeyFactory() + throws Exception + { + KeyFactory kFact = KeyFactory.getInstance("ML-DSA", "BC"); + KeyPairGenerator kpGen44 = KeyPairGenerator.getInstance("ML-DSA-44"); + KeyPair kp44 = kpGen44.generateKeyPair(); + KeyPairGenerator kpGen65 = KeyPairGenerator.getInstance("ML-DSA-65"); + KeyPair kp65 = kpGen65.generateKeyPair(); + KeyPairGenerator kpGen87 = KeyPairGenerator.getInstance("ML-DSA-87"); + KeyPair kp87 = kpGen87.generateKeyPair(); + KeyPairGenerator kpGen44withSha512 = KeyPairGenerator.getInstance("ML-DSA-44-WITH-SHA512"); + KeyPair kp44withSha512 = kpGen44withSha512.generateKeyPair(); + KeyPairGenerator kpGen65withSha512 = KeyPairGenerator.getInstance("ML-DSA-65-WITH-SHA512"); + KeyPair kp65withSha512 = kpGen65withSha512.generateKeyPair(); + KeyPairGenerator kpGen87withSha512 = KeyPairGenerator.getInstance("ML-DSA-87-WITH-SHA512"); + KeyPair kp87withSha512 = kpGen87withSha512.generateKeyPair(); + + tryKeyFact(KeyFactory.getInstance("ML-DSA-44", "BC"), kp44, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_ml_dsa_44.toString(), "BC"), kp44, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance("ML-DSA-65", "BC"), kp65, kp44, "2.16.840.1.101.3.4.3.17"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_ml_dsa_65.toString(), "BC"), kp65, kp44, "2.16.840.1.101.3.4.3.17"); + tryKeyFact(KeyFactory.getInstance("ML-DSA-87", "BC"), kp87, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_ml_dsa_87.toString(), "BC"), kp87, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance("ML-DSA-44-WITH-SHA512", "BC"), kp44withSha512, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_ml_dsa_44_with_sha512.toString(), "BC"), kp44withSha512, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance("ML-DSA-65-WITH-SHA512", "BC"), kp65withSha512, kp44, "2.16.840.1.101.3.4.3.17"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_ml_dsa_65_with_sha512.toString(), "BC"), kp65withSha512, kp44, "2.16.840.1.101.3.4.3.17"); + tryKeyFact(KeyFactory.getInstance("ML-DSA-87-WITH-SHA512", "BC"), kp87withSha512, kp65, "2.16.840.1.101.3.4.3.18"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_ml_dsa_87_with_sha512.toString(), "BC"), kp87withSha512, kp65, "2.16.840.1.101.3.4.3.18"); + } + + private void tryKeyFact(KeyFactory kFact, KeyPair kpValid, KeyPair kpInvalid, String oid) + throws Exception + { + kFact.generatePrivate(new PKCS8EncodedKeySpec(kpValid.getPrivate().getEncoded())); + kFact.generatePrivate(new PKCS8EncodedKeySpec(((MLDSAPrivateKey)kpValid.getPrivate()).getPrivateKey(true).getEncoded())); + kFact.generatePrivate(new PKCS8EncodedKeySpec(((MLDSAPrivateKey)kpValid.getPrivate()).getPrivateKey(false).getEncoded())); + kFact.generatePublic(new X509EncodedKeySpec(kpValid.getPublic().getEncoded())); + + try + { + kFact.generatePrivate(new PKCS8EncodedKeySpec(kpInvalid.getPrivate().getEncoded())); + fail("no exception"); + } + catch (InvalidKeySpecException e) + { + assertEquals("incorrect algorithm OID for key: " + oid, e.getMessage()); + } + try + { + kFact.generatePublic(new X509EncodedKeySpec(kpInvalid.getPublic().getEncoded())); + fail("no exception"); + } + catch (InvalidKeySpecException e) + { + assertEquals("incorrect algorithm OID for key: " + oid, e.getMessage()); + } + } + + public void testPrivateKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_65, new MLDSATest.RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("ML-DSA", "BC"); + + MLDSAKey privKey = (MLDSAKey)kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(privKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + MLDSAKey privKey2 = (MLDSAKey)oIn.readObject(); + + assertEquals(privKey, privKey2); + + assertEquals(kp.getPublic(), ((MLDSAPrivateKey)privKey2).getPublicKey()); + assertEquals(((MLDSAPrivateKey)privKey).getPublicKey(), ((MLDSAPrivateKey)privKey2).getPublicKey()); + } + + public void testDefaultPrivateKeyEncoding() + throws Exception + { + KeyPairGenerator kpGen44 = KeyPairGenerator.getInstance("ML-DSA-44"); + + byte[] seed = Hex.decode("000102030405060708090a0b0c0d0e0f" + "100102030405060708090a0b0c0d0e0f"); + + kpGen44.initialize(MLDSAParameterSpec.ml_dsa_44, new FixedSecureRandom(seed)); + KeyPair kp44 = kpGen44.generateKeyPair(); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp44.getPrivate().getEncoded()); + ASN1OctetString seq = ASN1OctetString.getInstance(ASN1Sequence.getInstance(privInfo.getPrivateKey().getOctets()).getObjectAt(0)); + + assertTrue(Arrays.areEqual(seq.getOctets(), seed)); + + ASN1OctetString privData = ASN1OctetString.getInstance(ASN1Sequence.getInstance(privInfo.getPrivateKey().getOctets()).getObjectAt(1)); + + assertTrue(Arrays.areEqual(privData.getOctets(), ((MLDSAPrivateKey)kp44.getPrivate()).getPrivateData())); + } + + public void testSeedPrivateKeyEncoding() + throws Exception + { + KeyPairGenerator kpGen44 = KeyPairGenerator.getInstance("ML-DSA-44"); + + byte[] seed = Hex.decode("000102030405060708090a0b0c0d0e0f" + "100102030405060708090a0b0c0d0e0f"); + + kpGen44.initialize(MLDSAParameterSpec.ml_dsa_44, new FixedSecureRandom(seed)); + KeyPair kp44 = kpGen44.generateKeyPair(); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(((MLDSAPrivateKey)kp44.getPrivate()).getPrivateKey(true).getEncoded()); + + ASN1OctetString k = privInfo.getPrivateKey(); + + assertTrue(Arrays.areEqual(ASN1OctetString.getInstance((ASN1TaggedObject)privInfo.parsePrivateKey(), false).getOctets(), seed)); + } + + public void testExpandedKeyPrivateKeyEncoding() + throws Exception + { + KeyPairGenerator kpGen44 = KeyPairGenerator.getInstance("ML-DSA-44"); + + byte[] seed = Hex.decode("000102030405060708090a0b0c0d0e0f" + "100102030405060708090a0b0c0d0e0f"); + byte[] expandedKey = Base64.decode("w/FofbPea45APAHeQqNeZL4KcvMHr8V/inNsUbmYlE0vTZbckQVhHq8sQi2F3yC7B1/aLXIta1rImyPmzsYITzPH4Iz+3/ysH0n3TDx9HFKMp5WwuOX7ZRnNqS/RaiaYltSR0LBwyi5uPgGqw1Cb/mAsJkoJuGx31QGfc1KTMSQYAjEiqU0QJjHAlAyBtiRSxkGZIFFYGAYIIEXSSC4YE2rAooADOQoIQmwbKARSQiWBRExbOIkEQEVJIEQcEUCTxhEjQCahpJFLwDEIhIFamETJqDEbEWrKyCwBKWnCQECcNgYDtAQMMWwMQTFjwCiisEUTQEGiFAoRQibaQmmaokgjFUYJREmMBHAClSABlyRQFAlQECCgRiSCJIEQEwoACSRElg0QEjBSFAgIOQLIuDCiRHHcFoIZp0zkCDCbBIkbFYnYFAQMQ1ELGSCYICDSBGhhBmAcoS0JQ0HBEGGUiIlTIkYaGGpJMJHLtCDAEDKBpgXUAgoSxQAjQm0EuUQjCBDcIkbKwkUUom0clomLKHETNpBioEBTpEDLEkocIzJiQI0JBAIaMQHaRCQbkW0KSHHgBGADoi0AFHHYFA3hgg0ayU1iloyIAEmQBJLLKC4JgQADhiGbmIiUggBcwCWDIiwByWCSEExaRC0ZkgALM0kTlZCJAnHUNEaYlJEEMU6JtAUAo0gRJ23kokkSxoREsjCSomBUyCFEAEpUJmkDkWVLloSSQkpjkm0AEQqZxFEIE4gjGCGTpkEhsEAUEyIZqEAjJg1BRlHBmCEJg4AZSGobNE5gMIWRRmTMtGBcgCVhpo2bwCDjFFLbAkJksHCZRAEKMVBjQi1jhkQQpg3EgmybBjDDqC3hRIBMoGHUpiHIMilQEgpQMA7QEClMBolUNihTAmDQAICTEm6IqEATCCEMOCoEEYwKN4maRDAjkSEJRmnIohALgAADBCoBhjFgJiIYkWmTQiHkKA4cImYLk3CSBIKUEA4gE2ibMkRjkkUKACyMRkYRoWQUl0wbmW2QBkkJR4AgR2iCJAYUMgpLKGwgKVHiBE4iBRALNYwbFwwUAGpQwAwDQSwSwQAQAi7REgrSIAlbkHEJyZAASWDMMm4YlSHiwFFIFkrbFI6IJJERJUhLlkXRyCAAk5GDoC2JyJGYQgkRRGkTJE2jRCzUGFEiF1DAghECNIJIgHAgQWlvzZh7vICP92WCMX3B8zbvb7tgGJ1FERU17RMAxgnav4gEW/oe9DFzrwvEKF4Ku25tc0FQgdmnvLQFYwpTQuDjTxsug4GZViD6JP0GvZpbvfRhSWIjeFVdQcspJ26wR3IaM4M8yRhim1xEfUf7HcopRHQ6bzJ0B7rhE60A1mouwYG8ekzSxQ4WPtqecHdT57vYaEjOqjM0g3vUKa8ybDzUUVJDXx/6pcww596LIBNHygVaBGdRyAhNYxzSg0Z9BuxN295I3WJLU13+yYsdgvMq/qoj0LVZPevCjMBLnGnBAGsXxpYmTZbiyE6v5vQO3xWB6So6vX+G82gl0T33gZEw0B0stRf76XAcHHNkQl5nz1ZdkCS2QGh8Or4nmnuatXYkfXSP8YWDFz7bgtISNta6w7iiluZOySkDb8unuWXa2lUiSbHOJJ1vJ3kxa/jOpQvKULjQ49VFJQpH+vVVZKRtXkvpkFnOmISVSx0rfus9NJCPpQm8S7DJH6pRA1ZgKYsLochGcs0pjWJGAZtUC9V0Bz7gz5XEWJzouDZZe7DfOagc/Ts7irQmpLMFuBeno9kzplKmYSDW1N88uO9CsCP4JOY/EKusbqzRu/032a0I9kozn8gyw3aAU6MArCVbfmr4/L+LV+MhLlnxe2RHy9iLw0SmVI2nJDNoLWichbLKJ7euagFMjqyw45WTmIYXKvX8rsl9TATOwcvL+0okzt8GuDyDmWej1UoGPPC74eyRfVVifPCPfb0M/o+QVwsNMggT11piJcEYmPS3hJWlTJ6t3WDIqwpvh9Bh2OBmNyJ0xMC3Zw3rNWVCLalzxf3RdOhINiSS91DtDP5FDqnZ8Br0HK5GCN00NPfWNt0FjNAWYuRoIBPqx471i+91mQAM7cRwP8izxj7D+wcGQMyQs/FA3ALXU62532rTt/eG90vPtTtj6Jvxcqx+l5oclJIZ/6qQjaqpzP6DIhlPa0e6FBiwRefdazXu2C5gPKtyY9YukXWftFnu3xDqRvxcYd/LBeK0utJYtERs4U2naS0W/8DMRrTTtiME4QZf8QSHnQoEjOS+ZNxb1yUUdmH0FKqeLgPNfXfVmD1B6ZTp/B02o3uRd7y9k4f5IKIPQedW4gdUIfycBP20lYmV5U1xcYVG6r/r1L1kfeCwlEsJ/3NsapVQx2JVuJ+EKBdqsx3zUHHSLnk3kRoZ4q0E5KRPccxgEGCpb2rK4W+hwvskcqfhKZQhYij4B10yzeno8FNIxT2vvXyALAxg2t4nSCVX7Wc1jv9ufEV3z1d5xzo5IDRHVkM1qT+V6zx+mkwXXksaVLiMNkeoy3/FF7uJxNcLajSwUwxht5LAzALa3LqlMyleIvK2fGWiqLaDkp1aYwvzc4i66sm42x2LHE6XwVVR/RnHj/1cg9rbcdVr1huGWA+TmLc0u01EYZrZnc0fGi9BnlYvm3JcEaNJ3f09cB/iN7pgMD/j8kzhykd0RsJgS5sU1ggAFkK4E9kt3WPrNqyIP1jdUZ30+Qnj6KL/bcTcvaxbC6Y1E0sIQgTSaQC9n3yhKawohtEjRDGnbqqltCw9qw6MRjTXWEPeju5YwRpN0DeVNB+3B8/sLeR7aR2tvbk7tyHvB9pW6WSInfmsGnTPqVChU7F0m/qYeP6PwjGK8TY69Pr0ziBh0JOLKYRVG2RwQnZGsGoLoXSHxZCV90Q5mIRagpGDBslvJTcxWtnUWT/ktFYkiFXHvW09hD/jqjzBRXSKOzfZnr5Xery2BIcmslYrSYbb38dY/3TmFL2k56R7nXS2uQEzhFJhT1OjOoOZ6hy6fGlNHhTXhiK0ZmF6AGb/Nw1nS0zW3HEa0wTJ5gnFUQrgkgon3NBtah5+dBsxNGn02O24vF4Lg8Va1Zj04igpuE/CctbUlJ5YKqqAj2SwL5hpBtNk8eV0srIFaFImaMcgzTJXt4tz5gOI3Ds3fkLjt3NBdLwMjw9VegdKHboCCYhVPzFY2lG++5LqJud37flp7Ikni17qpdUYO7khvsMLeUru6ouFqdV6fVdVywn2bW22Xs0DNNIfXGjnfhwhZ4AEvOqyFXmYHYqRYWOtBIxWu0aUtvtjcIi8gkDNsi0kY2Iuf6UFqwN7zqvuGYwsuC+n0UODwdi/48k1FWz/pOzqeaxo9O6AccKNEdDaXT4kwuJZsuvuKo0zv9IxDkVYoRB5Jx+vt58MtKGSxSpylWpJfw=="); + + kpGen44.initialize(MLDSAParameterSpec.ml_dsa_44, new FixedSecureRandom(seed)); + KeyPair kp44 = kpGen44.generateKeyPair(); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(((MLDSAPrivateKey)kp44.getPrivate()).getPrivateKey(false).getEncoded()); + + assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(privInfo.parsePrivateKey()).getOctets(), expandedKey)); + } + + public void testPrivateKeyRecoding() + throws Exception + { + // TODO: rebuild with newer encodings. +// byte[] mldsa44_sequence = Base64.decode("MIIKPgIBADALBglghkgBZQMEAxEEggoqMIIKJgQgAAECAwQFBgcICQoLDA0ODxABAgMEBQYHCAkKCwwNDg+BggoAw/FofbPea45APAHeQqNeZL4KcvMHr8V/inNsUbmYlE0vTZbckQVhHq8sQi2F3yC7B1/aLXIta1rImyPmzsYITzPH4Iz+3/ysH0n3TDx9HFKMp5WwuOX7ZRnNqS/RaiaYltSR0LBwyi5uPgGqw1Cb/mAsJkoJuGx31QGfc1KTMSQYAjEiqU0QJjHAlAyBtiRSxkGZIFFYGAYIIEXSSC4YE2rAooADOQoIQmwbKARSQiWBRExbOIkEQEVJIEQcEUCTxhEjQCahpJFLwDEIhIFamETJqDEbEWrKyCwBKWnCQECcNgYDtAQMMWwMQTFjwCiisEUTQEGiFAoRQibaQmmaokgjFUYJREmMBHAClSABlyRQFAlQECCgRiSCJIEQEwoACSRElg0QEjBSFAgIOQLIuDCiRHHcFoIZp0zkCDCbBIkbFYnYFAQMQ1ELGSCYICDSBGhhBmAcoS0JQ0HBEGGUiIlTIkYaGGpJMJHLtCDAEDKBpgXUAgoSxQAjQm0EuUQjCBDcIkbKwkUUom0clomLKHETNpBioEBTpEDLEkocIzJiQI0JBAIaMQHaRCQbkW0KSHHgBGADoi0AFHHYFA3hgg0ayU1iloyIAEmQBJLLKC4JgQADhiGbmIiUggBcwCWDIiwByWCSEExaRC0ZkgALM0kTlZCJAnHUNEaYlJEEMU6JtAUAo0gRJ23kokkSxoREsjCSomBUyCFEAEpUJmkDkWVLloSSQkpjkm0AEQqZxFEIE4gjGCGTpkEhsEAUEyIZqEAjJg1BRlHBmCEJg4AZSGobNE5gMIWRRmTMtGBcgCVhpo2bwCDjFFLbAkJksHCZRAEKMVBjQi1jhkQQpg3EgmybBjDDqC3hRIBMoGHUpiHIMilQEgpQMA7QEClMBolUNihTAmDQAICTEm6IqEATCCEMOCoEEYwKN4maRDAjkSEJRmnIohALgAADBCoBhjFgJiIYkWmTQiHkKA4cImYLk3CSBIKUEA4gE2ibMkRjkkUKACyMRkYRoWQUl0wbmW2QBkkJR4AgR2iCJAYUMgpLKGwgKVHiBE4iBRALNYwbFwwUAGpQwAwDQSwSwQAQAi7REgrSIAlbkHEJyZAASWDMMm4YlSHiwFFIFkrbFI6IJJERJUhLlkXRyCAAk5GDoC2JyJGYQgkRRGkTJE2jRCzUGFEiF1DAghECNIJIgHAgQWlvzZh7vICP92WCMX3B8zbvb7tgGJ1FERU17RMAxgnav4gEW/oe9DFzrwvEKF4Ku25tc0FQgdmnvLQFYwpTQuDjTxsug4GZViD6JP0GvZpbvfRhSWIjeFVdQcspJ26wR3IaM4M8yRhim1xEfUf7HcopRHQ6bzJ0B7rhE60A1mouwYG8ekzSxQ4WPtqecHdT57vYaEjOqjM0g3vUKa8ybDzUUVJDXx/6pcww596LIBNHygVaBGdRyAhNYxzSg0Z9BuxN295I3WJLU13+yYsdgvMq/qoj0LVZPevCjMBLnGnBAGsXxpYmTZbiyE6v5vQO3xWB6So6vX+G82gl0T33gZEw0B0stRf76XAcHHNkQl5nz1ZdkCS2QGh8Or4nmnuatXYkfXSP8YWDFz7bgtISNta6w7iiluZOySkDb8unuWXa2lUiSbHOJJ1vJ3kxa/jOpQvKULjQ49VFJQpH+vVVZKRtXkvpkFnOmISVSx0rfus9NJCPpQm8S7DJH6pRA1ZgKYsLochGcs0pjWJGAZtUC9V0Bz7gz5XEWJzouDZZe7DfOagc/Ts7irQmpLMFuBeno9kzplKmYSDW1N88uO9CsCP4JOY/EKusbqzRu/032a0I9kozn8gyw3aAU6MArCVbfmr4/L+LV+MhLlnxe2RHy9iLw0SmVI2nJDNoLWichbLKJ7euagFMjqyw45WTmIYXKvX8rsl9TATOwcvL+0okzt8GuDyDmWej1UoGPPC74eyRfVVifPCPfb0M/o+QVwsNMggT11piJcEYmPS3hJWlTJ6t3WDIqwpvh9Bh2OBmNyJ0xMC3Zw3rNWVCLalzxf3RdOhINiSS91DtDP5FDqnZ8Br0HK5GCN00NPfWNt0FjNAWYuRoIBPqx471i+91mQAM7cRwP8izxj7D+wcGQMyQs/FA3ALXU62532rTt/eG90vPtTtj6Jvxcqx+l5oclJIZ/6qQjaqpzP6DIhlPa0e6FBiwRefdazXu2C5gPKtyY9YukXWftFnu3xDqRvxcYd/LBeK0utJYtERs4U2naS0W/8DMRrTTtiME4QZf8QSHnQoEjOS+ZNxb1yUUdmH0FKqeLgPNfXfVmD1B6ZTp/B02o3uRd7y9k4f5IKIPQedW4gdUIfycBP20lYmV5U1xcYVG6r/r1L1kfeCwlEsJ/3NsapVQx2JVuJ+EKBdqsx3zUHHSLnk3kRoZ4q0E5KRPccxgEGCpb2rK4W+hwvskcqfhKZQhYij4B10yzeno8FNIxT2vvXyALAxg2t4nSCVX7Wc1jv9ufEV3z1d5xzo5IDRHVkM1qT+V6zx+mkwXXksaVLiMNkeoy3/FF7uJxNcLajSwUwxht5LAzALa3LqlMyleIvK2fGWiqLaDkp1aYwvzc4i66sm42x2LHE6XwVVR/RnHj/1cg9rbcdVr1huGWA+TmLc0u01EYZrZnc0fGi9BnlYvm3JcEaNJ3f09cB/iN7pgMD/j8kzhykd0RsJgS5sU1ggAFkK4E9kt3WPrNqyIP1jdUZ30+Qnj6KL/bcTcvaxbC6Y1E0sIQgTSaQC9n3yhKawohtEjRDGnbqqltCw9qw6MRjTXWEPeju5YwRpN0DeVNB+3B8/sLeR7aR2tvbk7tyHvB9pW6WSInfmsGnTPqVChU7F0m/qYeP6PwjGK8TY69Pr0ziBh0JOLKYRVG2RwQnZGsGoLoXSHxZCV90Q5mIRagpGDBslvJTcxWtnUWT/ktFYkiFXHvW09hD/jqjzBRXSKOzfZnr5Xery2BIcmslYrSYbb38dY/3TmFL2k56R7nXS2uQEzhFJhT1OjOoOZ6hy6fGlNHhTXhiK0ZmF6AGb/Nw1nS0zW3HEa0wTJ5gnFUQrgkgon3NBtah5+dBsxNGn02O24vF4Lg8Va1Zj04igpuE/CctbUlJ5YKqqAj2SwL5hpBtNk8eV0srIFaFImaMcgzTJXt4tz5gOI3Ds3fkLjt3NBdLwMjw9VegdKHboCCYhVPzFY2lG++5LqJud37flp7Ikni17qpdUYO7khvsMLeUru6ouFqdV6fVdVywn2bW22Xs0DNNIfXGjnfhwhZ4AEvOqyFXmYHYqRYWOtBIxWu0aUtvtjcIi8gkDNsi0kY2Iuf6UFqwN7zqvuGYwsuC+n0UODwdi/48k1FWz/pOzqeaxo9O6AccKNEdDaXT4kwuJZsuvuKo0zv9IxDkVYoRB5Jx+vt58MtKGSxSpylWpJfw=="); + byte[] mldsa44_seed_only = Base64.decode("MDICAQAwCwYJYIZIAWUDBAMRBCAAAQIDBAUGBwgJCgsMDQ4PEAECAwQFBgcICQoLDA0ODw=="); + byte[] mldsa44_wrap_seed_only = Base64.decode("MDQCAQAwCwYJYIZIAWUDBAMRBCIEIAABAgMEBQYHCAkKCwwNDg8QAQIDBAUGBwgJCgsMDQ4P"); + byte[] mldsa44_expanded_only = Base64.decode("MIIKFAIBADALBglghkgBZQMEAxEEggoAw/FofbPea45APAHeQqNeZL4KcvMHr8V/inNsUbmYlE0vTZbckQVhHq8sQi2F3yC7B1/aLXIta1rImyPmzsYITzPH4Iz+3/ysH0n3TDx9HFKMp5WwuOX7ZRnNqS/RaiaYltSR0LBwyi5uPgGqw1Cb/mAsJkoJuGx31QGfc1KTMSQYAjEiqU0QJjHAlAyBtiRSxkGZIFFYGAYIIEXSSC4YE2rAooADOQoIQmwbKARSQiWBRExbOIkEQEVJIEQcEUCTxhEjQCahpJFLwDEIhIFamETJqDEbEWrKyCwBKWnCQECcNgYDtAQMMWwMQTFjwCiisEUTQEGiFAoRQibaQmmaokgjFUYJREmMBHAClSABlyRQFAlQECCgRiSCJIEQEwoACSRElg0QEjBSFAgIOQLIuDCiRHHcFoIZp0zkCDCbBIkbFYnYFAQMQ1ELGSCYICDSBGhhBmAcoS0JQ0HBEGGUiIlTIkYaGGpJMJHLtCDAEDKBpgXUAgoSxQAjQm0EuUQjCBDcIkbKwkUUom0clomLKHETNpBioEBTpEDLEkocIzJiQI0JBAIaMQHaRCQbkW0KSHHgBGADoi0AFHHYFA3hgg0ayU1iloyIAEmQBJLLKC4JgQADhiGbmIiUggBcwCWDIiwByWCSEExaRC0ZkgALM0kTlZCJAnHUNEaYlJEEMU6JtAUAo0gRJ23kokkSxoREsjCSomBUyCFEAEpUJmkDkWVLloSSQkpjkm0AEQqZxFEIE4gjGCGTpkEhsEAUEyIZqEAjJg1BRlHBmCEJg4AZSGobNE5gMIWRRmTMtGBcgCVhpo2bwCDjFFLbAkJksHCZRAEKMVBjQi1jhkQQpg3EgmybBjDDqC3hRIBMoGHUpiHIMilQEgpQMA7QEClMBolUNihTAmDQAICTEm6IqEATCCEMOCoEEYwKN4maRDAjkSEJRmnIohALgAADBCoBhjFgJiIYkWmTQiHkKA4cImYLk3CSBIKUEA4gE2ibMkRjkkUKACyMRkYRoWQUl0wbmW2QBkkJR4AgR2iCJAYUMgpLKGwgKVHiBE4iBRALNYwbFwwUAGpQwAwDQSwSwQAQAi7REgrSIAlbkHEJyZAASWDMMm4YlSHiwFFIFkrbFI6IJJERJUhLlkXRyCAAk5GDoC2JyJGYQgkRRGkTJE2jRCzUGFEiF1DAghECNIJIgHAgQWlvzZh7vICP92WCMX3B8zbvb7tgGJ1FERU17RMAxgnav4gEW/oe9DFzrwvEKF4Ku25tc0FQgdmnvLQFYwpTQuDjTxsug4GZViD6JP0GvZpbvfRhSWIjeFVdQcspJ26wR3IaM4M8yRhim1xEfUf7HcopRHQ6bzJ0B7rhE60A1mouwYG8ekzSxQ4WPtqecHdT57vYaEjOqjM0g3vUKa8ybDzUUVJDXx/6pcww596LIBNHygVaBGdRyAhNYxzSg0Z9BuxN295I3WJLU13+yYsdgvMq/qoj0LVZPevCjMBLnGnBAGsXxpYmTZbiyE6v5vQO3xWB6So6vX+G82gl0T33gZEw0B0stRf76XAcHHNkQl5nz1ZdkCS2QGh8Or4nmnuatXYkfXSP8YWDFz7bgtISNta6w7iiluZOySkDb8unuWXa2lUiSbHOJJ1vJ3kxa/jOpQvKULjQ49VFJQpH+vVVZKRtXkvpkFnOmISVSx0rfus9NJCPpQm8S7DJH6pRA1ZgKYsLochGcs0pjWJGAZtUC9V0Bz7gz5XEWJzouDZZe7DfOagc/Ts7irQmpLMFuBeno9kzplKmYSDW1N88uO9CsCP4JOY/EKusbqzRu/032a0I9kozn8gyw3aAU6MArCVbfmr4/L+LV+MhLlnxe2RHy9iLw0SmVI2nJDNoLWichbLKJ7euagFMjqyw45WTmIYXKvX8rsl9TATOwcvL+0okzt8GuDyDmWej1UoGPPC74eyRfVVifPCPfb0M/o+QVwsNMggT11piJcEYmPS3hJWlTJ6t3WDIqwpvh9Bh2OBmNyJ0xMC3Zw3rNWVCLalzxf3RdOhINiSS91DtDP5FDqnZ8Br0HK5GCN00NPfWNt0FjNAWYuRoIBPqx471i+91mQAM7cRwP8izxj7D+wcGQMyQs/FA3ALXU62532rTt/eG90vPtTtj6Jvxcqx+l5oclJIZ/6qQjaqpzP6DIhlPa0e6FBiwRefdazXu2C5gPKtyY9YukXWftFnu3xDqRvxcYd/LBeK0utJYtERs4U2naS0W/8DMRrTTtiME4QZf8QSHnQoEjOS+ZNxb1yUUdmH0FKqeLgPNfXfVmD1B6ZTp/B02o3uRd7y9k4f5IKIPQedW4gdUIfycBP20lYmV5U1xcYVG6r/r1L1kfeCwlEsJ/3NsapVQx2JVuJ+EKBdqsx3zUHHSLnk3kRoZ4q0E5KRPccxgEGCpb2rK4W+hwvskcqfhKZQhYij4B10yzeno8FNIxT2vvXyALAxg2t4nSCVX7Wc1jv9ufEV3z1d5xzo5IDRHVkM1qT+V6zx+mkwXXksaVLiMNkeoy3/FF7uJxNcLajSwUwxht5LAzALa3LqlMyleIvK2fGWiqLaDkp1aYwvzc4i66sm42x2LHE6XwVVR/RnHj/1cg9rbcdVr1huGWA+TmLc0u01EYZrZnc0fGi9BnlYvm3JcEaNJ3f09cB/iN7pgMD/j8kzhykd0RsJgS5sU1ggAFkK4E9kt3WPrNqyIP1jdUZ30+Qnj6KL/bcTcvaxbC6Y1E0sIQgTSaQC9n3yhKawohtEjRDGnbqqltCw9qw6MRjTXWEPeju5YwRpN0DeVNB+3B8/sLeR7aR2tvbk7tyHvB9pW6WSInfmsGnTPqVChU7F0m/qYeP6PwjGK8TY69Pr0ziBh0JOLKYRVG2RwQnZGsGoLoXSHxZCV90Q5mIRagpGDBslvJTcxWtnUWT/ktFYkiFXHvW09hD/jqjzBRXSKOzfZnr5Xery2BIcmslYrSYbb38dY/3TmFL2k56R7nXS2uQEzhFJhT1OjOoOZ6hy6fGlNHhTXhiK0ZmF6AGb/Nw1nS0zW3HEa0wTJ5gnFUQrgkgon3NBtah5+dBsxNGn02O24vF4Lg8Va1Zj04igpuE/CctbUlJ5YKqqAj2SwL5hpBtNk8eV0srIFaFImaMcgzTJXt4tz5gOI3Ds3fkLjt3NBdLwMjw9VegdKHboCCYhVPzFY2lG++5LqJud37flp7Ikni17qpdUYO7khvsMLeUru6ouFqdV6fVdVywn2bW22Xs0DNNIfXGjnfhwhZ4AEvOqyFXmYHYqRYWOtBIxWu0aUtvtjcIi8gkDNsi0kY2Iuf6UFqwN7zqvuGYwsuC+n0UODwdi/48k1FWz/pOzqeaxo9O6AccKNEdDaXT4kwuJZsuvuKo0zv9IxDkVYoRB5Jx+vt58MtKGSxSpylWpJfw=="); +// byte[] mldsa44_wrap_expanded_only = Base64.decode("MIIKGAIBADALBglghkgBZQMEAxEEggoEBIIKAMPxaH2z3muOQDwB3kKjXmS+CnLzB6/Ff4pzbFG5mJRNL02W3JEFYR6vLEIthd8guwdf2i1yLWtayJsj5s7GCE8zx+CM/t/8rB9J90w8fRxSjKeVsLjl+2UZzakv0WommJbUkdCwcMoubj4BqsNQm/5gLCZKCbhsd9UBn3NSkzEkGAIxIqlNECYxwJQMgbYkUsZBmSBRWBgGCCBF0kguGBNqwKKAAzkKCEJsGygEUkIlgURMWziJBEBFSSBEHBFAk8YRI0AmoaSRS8AxCISBWphEyagxGxFqysgsASlpwkBAnDYGA7QEDDFsDEExY8AoorBFE0BBohQKEUIm2kJpmqJIIxVGCURJjARwApUgAZckUBQJUBAgoEYkgiSBEBMKAAkkRJYNEBIwUhQICDkCyLgwokRx3BaCGadM5AgwmwSJGxWJ2BQEDENRCxkgmCAg0gRoYQZgHKEtCUNBwRBhlIiJUyJGGhhqSTCRy7QgwBAygaYF1AIKEsUAI0JtBLlEIwgQ3CJGysJFFKJtHJaJiyhxEzaQYqBAU6RAyxJKHCMyYkCNCQQCGjEB2kQkG5FtCkhx4ARgA6ItABRx2BQN4YINGslNYpaMiABJkASSyyguCYEAA4Yhm5iIlIIAXMAlgyIsAclgkhBMWkQtGZIACzNJE5WQiQJx1DRGmJSRBDFOibQFAKNIESdt5KJJEsaERLIwkqJgVMghRABKVCZpA5FlS5aEkkJKY5JtABEKmcRRCBOIIxghk6ZBIbBAFBMiGahAIyYNQUZRwZghCYOAGUhqGzROYDCFkUZkzLRgXIAlYaaNm8Ag4xRS2wJCZLBwmUQBCjFQY0ItY4ZEEKYNxIJsmwYww6gt4USATKBh1KYhyDIpUBIKUDAO0BApTAaJVDYoUwJg0ACAkxJuiKhAEwghDDgqBBGMCjeJmkQwI5EhCUZpyKIQC4AAAwQqAYYxYCYiGJFpk0Ih5CgOHCJmC5NwkgSClBAOIBNomzJEY5JFCgAsjEZGEaFkFJdMG5ltkAZJCUeAIEdogiQGFDIKSyhsIClR4gROIgUQCzWMGxcMFABqUMAMA0EsEsEAEAIu0RIK0iAJW5BxCcmQAElgzDJuGJUh4sBRSBZK2xSOiCSRESVIS5ZF0cggAJORg6AticiRmEIJEURpEyRNo0Qs1BhRIhdQwIIRAjSCSIBwIEFpb82Ye7yAj/dlgjF9wfM272+7YBidRREVNe0TAMYJ2r+IBFv6HvQxc68LxCheCrtubXNBUIHZp7y0BWMKU0Lg408bLoOBmVYg+iT9Br2aW730YUliI3hVXUHLKSdusEdyGjODPMkYYptcRH1H+x3KKUR0Om8ydAe64ROtANZqLsGBvHpM0sUOFj7annB3U+e72GhIzqozNIN71CmvMmw81FFSQ18f+qXMMOfeiyATR8oFWgRnUcgITWMc0oNGfQbsTdveSN1iS1Nd/smLHYLzKv6qI9C1WT3rwozAS5xpwQBrF8aWJk2W4shOr+b0Dt8VgekqOr1/hvNoJdE994GRMNAdLLUX++lwHBxzZEJeZ89WXZAktkBofDq+J5p7mrV2JH10j/GFgxc+24LSEjbWusO4opbmTskpA2/Lp7ll2tpVIkmxziSdbyd5MWv4zqULylC40OPVRSUKR/r1VWSkbV5L6ZBZzpiElUsdK37rPTSQj6UJvEuwyR+qUQNWYCmLC6HIRnLNKY1iRgGbVAvVdAc+4M+VxFic6Lg2WXuw3zmoHP07O4q0JqSzBbgXp6PZM6ZSpmEg1tTfPLjvQrAj+CTmPxCrrG6s0bv9N9mtCPZKM5/IMsN2gFOjAKwlW35q+Py/i1fjIS5Z8XtkR8vYi8NEplSNpyQzaC1onIWyyie3rmoBTI6ssOOVk5iGFyr1/K7JfUwEzsHLy/tKJM7fBrg8g5lno9VKBjzwu+HskX1VYnzwj329DP6PkFcLDTIIE9daYiXBGJj0t4SVpUyerd1gyKsKb4fQYdjgZjcidMTAt2cN6zVlQi2pc8X90XToSDYkkvdQ7Qz+RQ6p2fAa9ByuRgjdNDT31jbdBYzQFmLkaCAT6seO9YvvdZkADO3EcD/Is8Y+w/sHBkDMkLPxQNwC11Otud9q07f3hvdLz7U7Y+ib8XKsfpeaHJSSGf+qkI2qqcz+gyIZT2tHuhQYsEXn3Ws17tguYDyrcmPWLpF1n7RZ7t8Q6kb8XGHfywXitLrSWLREbOFNp2ktFv/AzEa007YjBOEGX/EEh50KBIzkvmTcW9clFHZh9BSqni4DzX131Zg9QemU6fwdNqN7kXe8vZOH+SCiD0HnVuIHVCH8nAT9tJWJleVNcXGFRuq/69S9ZH3gsJRLCf9zbGqVUMdiVbifhCgXarMd81Bx0i55N5EaGeKtBOSkT3HMYBBgqW9qyuFvocL7JHKn4SmUIWIo+AddMs3p6PBTSMU9r718gCwMYNreJ0glV+1nNY7/bnxFd89Xecc6OSA0R1ZDNak/les8fppMF15LGlS4jDZHqMt/xRe7icTXC2o0sFMMYbeSwMwC2ty6pTMpXiLytnxloqi2g5KdWmML83OIuurJuNsdixxOl8FVUf0Zx4/9XIPa23HVa9YbhlgPk5i3NLtNRGGa2Z3NHxovQZ5WL5tyXBGjSd39PXAf4je6YDA/4/JM4cpHdEbCYEubFNYIABZCuBPZLd1j6zasiD9Y3VGd9PkJ4+ii/23E3L2sWwumNRNLCEIE0mkAvZ98oSmsKIbRI0Qxp26qpbQsPasOjEY011hD3o7uWMEaTdA3lTQftwfP7C3ke2kdrb25O7ch7wfaVulkiJ35rBp0z6lQoVOxdJv6mHj+j8IxivE2OvT69M4gYdCTiymEVRtkcEJ2RrBqC6F0h8WQlfdEOZiEWoKRgwbJbyU3MVrZ1Fk/5LRWJIhVx71tPYQ/46o8wUV0ijs32Z6+V3q8tgSHJrJWK0mG29/HWP905hS9pOeke510trkBM4RSYU9TozqDmeocunxpTR4U14YitGZhegBm/zcNZ0tM1txxGtMEyeYJxVEK4JIKJ9zQbWoefnQbMTRp9NjtuLxeC4PFWtWY9OIoKbhPwnLW1JSeWCqqgI9ksC+YaQbTZPHldLKyBWhSJmjHIM0yV7eLc+YDiNw7N35C47dzQXS8DI8PVXoHSh26AgmIVT8xWNpRvvuS6ibnd+35aeyJJ4te6qXVGDu5Ib7DC3lK7uqLhanVen1XVcsJ9m1ttl7NAzTSH1xo534cIWeABLzqshV5mB2KkWFjrQSMVrtGlLb7Y3CIvIJAzbItJGNiLn+lBasDe86r7hmMLLgvp9FDg8HYv+PJNRVs/6Ts6nmsaPTugHHCjRHQ2l0+JMLiWbLr7iqNM7/SMQ5FWKEQeScfr7efDLShksUqcpVqSX8="); +// byte[] mldsa44_seed_with_pub_key = Base64.decode("MIIFVwIBATALBglghkgBZQMEAxEEIAABAgMEBQYHCAkKCwwNDg8QAQIDBAUGBwgJCgsMDQ4PgYIFIQDD8Wh9s95rjkA8Ad5Co15kvgpy8wevxX+Kc2xRuZiUTcEHWDP0MI8enUbboCTOE020U+28L6HkQZZ4JzkhORY54IkHcSKSRcKkiNkLdbm9jWKOEiQAWKuYJyQ3dcbNWa4ogK+E4LsT2jHguWA/rmSJ42Azys2/d+kIMTmmKt3Y2PyiWU5zzj/2TNOQUHaHuJhAmXAT7iCrcEz+6vCsH/dKQrcVjMjIfbibRyRMLZIrLhqXqV4vboYE/yu9jzNRUGQH5rmenF+wDtnvu7YNO/2hWYRZJKrbTgy+nuBEBAkCKorHWVaGJvmXcEPSodB+5cRIQ5+uCCswH1lJT00+SzKsCacs68iBFcte5TkAOwTzq7slL1lAptILPkzwAhNhqKGCVz4B+qRiB6CK8917el2ioTKPxyHBtgHTKPIEoIdRAgi0+uaVBPAQ21VUlYDcILBd0mAH/7rxXsIdfq5PmklvIVD0VNxeDmwIbQH0J/LNr9kKCfmHSAXgZ3Vh/DQa2eVukKv7PZiBGSCyBHukEFK+791XNCydlSNsJkvz+xvp5cEkAseNxGJoUigCW4a5r2FV37JD9FQE6PDeCrKSL428p8vMl4Vpp6I+G90JuVv7+c0ShDh9n/PdnF/hC3v9uHso/COKsYvaKN4CIo9pwiyrm44XLuDSoX+F8DcmmaLYcEqW+o06/mVz5+dTSSrWZgiXqkIkPFI44AgwC/21SI9piGtdXouzcjxmIrgg1n1utPGESQXE2xxd3AkYJtVnPpdvMoEv/MSN2OMl5LGeO0DhPD4rdRYkT1HnT1/dbb5QoKpWHBiUgxTb2xJGzljMMaFooPi9mQiUas1fSjGk/7gNKgfi88nR8HiAPm5me3NGfxcS3plrI1UewwB9ubOOBfAQiRYQI2w5ax12ygyiPSS8ekYLv1HD2TfpfdVzwIQhWYnYWDls6WhW+sJ15Al5QJ3kGe2fIQflEH6196P5Xo/4Kmv1A02jzeN3KSPb/KutI8HM4TXWAgsQX+7XmH+zzS3lXqdjRhhQ0RQ9HK4HFZ2OFw9/2KhsbR0vMIcsc0VB0zsx096ZIgMynAbyQ5rI3mFeKM7n+CD4m5KXMYSupfesNv9e8Of/FROnwR9It9N2BzQVcLWwiMuwYiqgchfUfmZFWcD2if5e23xuSt/t8hYReU/I2SydkhzTUNfwbELIkjcsxwWVkpYFIf7rT2i5Atkl6auBag5Eg/fjEuiR7RsFS1C/AcHx5lxqqbckZ/eXinG7kPDw9ZSpjHki4/PeKTeviCs4aOGtLC9kexDAU++k2cFQe7fqbUHST+eENU2m9HQ1/WfUt1426wDUdYZTqInnvk/PjUbkvE0RNbFzS+0w9Qsnh28YfLXRt/j+IcZhG4buivL2G0N/UqHtwWpyh3Wigic5tqpMaTZ54RN1/jJWmsQS3rvd8rHaZPk2CbH0Iss1PrcROzksogqZBQn4Y1zwDsF6yqdscqaMJXmH5+7REdQACUTCzU2Qj4x59doVByXnKY+Of8fAB1XTjurYgq8DrbKnzfUThC3zEodT/HTcLdP7gEIhPizDQYxNA6LlGUxGzpy7+iMs3j38WiSbToASbB1dCsFtR7Jp0P8qc9LJmX36CW87JON1pEVaTCth/HQS8AXUsGU7HSorD/CkCwehxKlABcRbpPTIZC/dtR9LkrkI5T9AyTWMDS2pPzICo+PUhOOkU3pSKS6o20VnvZtj2uU8M31K6I16H5KbqXMr"); + + KeyFactory kFact = KeyFactory.getInstance("ML-DSA", "BC"); + +// checkEncodeRecode(kFact, mldsa44_sequence); + checkEncodeRecode(kFact, mldsa44_seed_only); + checkEncodeRecode(kFact, mldsa44_wrap_seed_only); + checkEncodeRecode(kFact, mldsa44_expanded_only); +// checkEncodeRecode(kFact, mldsa44_wrap_expanded_only); +// checkEncodeRecode(kFact, mldsa44_seed_with_pub_key); + } + + private void checkEncodeRecode(KeyFactory kFact, byte[] encoding) + throws Exception + { + PrivateKey key = kFact.generatePrivate(new PKCS8EncodedKeySpec(encoding)); + + assertTrue(Arrays.areEqual(encoding, key.getEncoded())); + } + + + public void testPublicKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_87, new MLDSATest.RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("ML-DSA", "BC"); + + MLDSAKey pubKey = (MLDSAKey)kFact.generatePublic(new X509EncodedKeySpec(kp.getPublic().getEncoded())); + + assertEquals(kp.getPublic().hashCode(), pubKey.hashCode()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(pubKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + MLDSAKey pubKey2 = (MLDSAKey)oIn.readObject(); + + assertEquals(pubKey, pubKey2); + assertEquals(pubKey.hashCode(), pubKey2.hashCode()); + } + + public void testRestrictedSignature() + throws Exception + { + doTestRestrictedSignature("ML-DSA-44", MLDSAParameterSpec.ml_dsa_44, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedSignature("ML-DSA-65", MLDSAParameterSpec.ml_dsa_65, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedSignature("ML-DSA-87", MLDSAParameterSpec.ml_dsa_87, MLDSAParameterSpec.ml_dsa_44); + doTestRestrictedSignature("ML-DSA-44-WITH-SHA512", MLDSAParameterSpec.ml_dsa_44_with_sha512, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedSignature("ML-DSA-65-WITH-SHA512", MLDSAParameterSpec.ml_dsa_65_with_sha512, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedSignature("ML-DSA-87-WITH-SHA512", MLDSAParameterSpec.ml_dsa_87_with_sha512, MLDSAParameterSpec.ml_dsa_44); + } + + private void doTestRestrictedSignature(String sigName, MLDSAParameterSpec spec, MLDSAParameterSpec altSpec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance(sigName, "BC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance(sigName, "BC"); + + assertEquals(sigName, sig.getAlgorithm()); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(altSpec, new SecureRandom()); + + kp = kpg.generateKeyPair(); + + try + { + sig.initVerify(kp.getPublic()); + fail("no exception"); + } + catch (InvalidKeyException e) + { + assertEquals("signature configured for " + spec.getName(), e.getMessage()); + } + } + + /* + public void testMLDSA() + throws Exception + { + + KeyPairGenerator kpGen44 = KeyPairGenerator.getInstance("ML-DSA-44"); + KeyPair kp44 = kpGen44.generateKeyPair(); + KeyPairGenerator kpGen65 = KeyPairGenerator.getInstance("ML-DSA-65"); + KeyPair kp65 = kpGen65.generateKeyPair(); + KeyPairGenerator kpGen87 = KeyPairGenerator.getInstance("ML-DSA-87"); + KeyPair kp87 = kpGen87.generateKeyPair(); + + outputKeyPair("ml-dsa-44", kp44); + outputKeyPair("ml-dsa-65", kp65); + outputKeyPair("ml-dsa-87", kp87); + } + + private void outputKeyPair(String algorithm, KeyPair kp) + throws Exception + { + KeyFactory kFact = KeyFactory.getInstance("ML-DSA", "BC"); + + System.setProperty("seed", "true"); + System.setProperty("expanded", "true"); + FileWriter fWrt = new FileWriter("/tmp/ml-dsa-pems/" + algorithm + "-priv.pem"); + + PemWriter pWrt = new PemWriter(fWrt); + + pWrt.writeObject(new PemObject("PRIVATE KEY", kp.getPrivate().getEncoded())); + + pWrt.close(); + + PrivateKey priv = kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + System.setProperty("seed", "true"); + System.setProperty("expanded", "false"); + fWrt = new FileWriter("/tmp/ml-dsa-pems/" + algorithm + "-seed-only-priv.pem"); + + pWrt = new PemWriter(fWrt); + + pWrt.writeObject(new PemObject("PRIVATE KEY", priv.getEncoded())); + + pWrt.close(); + + priv = kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + System.setProperty("seed", "false"); + System.setProperty("expanded", "true"); + fWrt = new FileWriter("/tmp/ml-dsa-pems/" + algorithm + "-expanded-only-priv.pem"); + + pWrt = new PemWriter(fWrt); + + pWrt.writeObject(new PemObject("PRIVATE KEY", priv.getEncoded())); + + pWrt.close(); + + fWrt = new FileWriter("/tmp/ml-dsa-pems/" + algorithm + "-pub.pem"); + + pWrt = new PemWriter(fWrt); + + pWrt.writeObject(new PemObject("PUBLIC KEY", kp.getPublic().getEncoded())); + + pWrt.close(); + } + */ + + public void testRestrictedKeyPairGen() + throws Exception + { + doTestRestrictedKeyPairGen(MLDSAParameterSpec.ml_dsa_44, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedKeyPairGen(MLDSAParameterSpec.ml_dsa_65, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedKeyPairGen(MLDSAParameterSpec.ml_dsa_87, MLDSAParameterSpec.ml_dsa_44); + doTestRestrictedKeyPairGen(MLDSAParameterSpec.ml_dsa_44_with_sha512, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedKeyPairGen(MLDSAParameterSpec.ml_dsa_65_with_sha512, MLDSAParameterSpec.ml_dsa_87); + doTestRestrictedKeyPairGen(MLDSAParameterSpec.ml_dsa_87_with_sha512, MLDSAParameterSpec.ml_dsa_44); + } + + private void doTestRestrictedKeyPairGen(MLDSAParameterSpec spec, MLDSAParameterSpec altSpec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + assertEquals(spec.getName(), kpg.getAlgorithm()); + assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); + assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); + + kpg = KeyPairGenerator.getInstance(spec.getName(), "BC"); + + try + { + kpg.initialize(altSpec, new SecureRandom()); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("key pair generator locked to " + spec.getName(), e.getMessage()); + } + } + + public void testMLDSARandomSig() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_44, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + public void testMLDSARandomMsgAndMuSig() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_44, new SecureRandom()); + + final KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("ML-DSA-CALCULATE-MU", "BC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] mu = sig.sign(); + + sig = Signature.getInstance("ML-DSA-EXTERNAL-MU", "BC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(mu, 0, mu.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + sig = Signature.getInstance("ML-DSA-EXTERNAL-MU", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(mu, 0, mu.length); + + assertTrue(sig.verify(s)); + + sig = Signature.getInstance("ML-DSA-CALCULATE-MU", "BC"); + + sig.initSign(new MLDSAProxyPrivateKey(kp.getPublic())); + + sig.update(msg, 0, msg.length); + + byte[] mu2 = sig.sign(); + + assertTrue(Arrays.areEqual(mu, mu2)); + } + + public void testMLDSAMuKatTest() + throws Exception + { + byte[] pk = Hex.decode("3BB5567D7049939D8A5911BBE1FEC62843DAD05447BFC37CEF917C431DD20B8EE32A985C4F681DB63186FCB455A9163559301728E6F03F9C915FBF48571CF7DC76B1D1373B1C57B1C479DCAF136EE893D04B8E8C3A86D28483E84CB6814A17DDE3FE4152B69ADFBFD40B1AF8D4CD66101070B9979E6EEEFD4ED21111D129FE959E39E8C00311EA624A54F3340FC6BE06A0A826A3E74DD4161FC9EEF6097562316E62BBAF4D482732BABBB1C5132B86C8D7D733DC9595DDB93EF6BF5D79A860885D3F3BE31908787587A99D84017D00E814E4F697F2688ADF3967AB05F61C0D0F02BD5B8C4EA51010103265F49F90F2D1D5DE55305B59CB3658146F1696F12EE25875136A234E35F10B7BE95FCCDAD326D9CEDCF64F7DA0E9F0697A9A04E4C7237CDFBAAFC6974DA04D158EA2CDC7A3F87CE0E5BE9DCD54ED84ABAFC6C9889C3427A904C2DFF70581E1BF0F544BC1954AAC852DFAB032D140AC94CACE5889DFD43BF9DB490CDF3342C15E4F88EC5F16B789828367A488CFAA6FED1E94322759EAAA211041444D10ACF8E1DF1EF840B68412603DA6BBC4FE69C8D2627C032A266475B1314119D843F54689300EAC933060D0A7106EDF58CC6B1F313B8FDE024C0179E7B67B08CC030B7B3BC610E9C2A60BFDEE54A1D5E0F53E8533456AEB4D0978DA9C7E904AC31B676222C9369D3FC74EDC8642C4F3C19E31B14F1E5EB3FCA413478E5B03DA9FB50755EECD2F0F513502232367A12A02A0B1B86C9FA8FD2990B8A7296818F9DA6E70228AC8BBC55A9374E1719BA180A29147CC1E379CF10FAFDF6FB0FFBB35CD033FBB6660042F9A61AEFBFBF6ECDBB146A3233644D5596AF68CE3C89BB77E75D60D2D044400374179483B3DC65FC029246A9C950D5AA4825C359B45EFB7B24E36C0A0B2592BD50F992484D170F4C3D77F8F7755D86FF1DE21332A7D1F70D069DAD0CFF4B4B3BBBC6A535C48E0262333AA87C22DD70D07610EA105D506BFCA77283B64C262F2A38FAAE68E96B9491A229B0A2FC6BF967F2C2DDDA1A8804F5B6E37C2AEFB768B33DC1D05B0E3C86BD4F799346101B2E44BCA78AF5CB50C8F57B104F054054CF2975DEFB661A8BE18BAA9296D3372B1460338F58E6B9CDCCF25CE371B3BF39E90E9B35037BE4F24BEA1ACF75A643ABD19E7D312DF45F27E04CD3D94E1569029F1EBB806E2617252263BD10EE898B90526675A42B90FB64F4C5B0F18B3446049B2F85BD1DD526E7AC5C41E3DF0F0920EAFAF804B808FF0E5B2E064BB39909AD39FB3BED06D1A97288A1D7F7B8EBBCD257869B736B87E18990E0E7DB4E2EB70FDE0B9B235DB741161C68F71E2C1AE9525AC68569D3AAD61584EE29EE5581C0F67439B9F1DE7EC65073929D08119A45B6C10028CC34132E57F8B969D4195095E891276822C83FA6AD3743B1F3597AE188A0324AF4C198995246338533123092A80F4B40D557B7AEF5CAA6C9F65B03E86A9D580370659F2BD76D1A79468BBE725E07CD67E0094CEB4D8CAC55C76B6AAE7C9DA8B7CD851679105B9934D8F8C5CE2F69124AC41EC8E8F4470AD4CCAA55C7F3533558D366D5A78410B4232927CAACA135166CD0792D9CDD595711633DADC81685939D1107AC085919534747095FD24026031480CC5E16BBA2A7083B0E94D3C67EF3901B30E1BF8645A96EC8DE67999E985EECD714603371C854F90F7545A45C455154E596BB9406769935022133B9195106AD5BB1BEDADF9BC05518E480832F6C961FF35F8B1C6D030CAE8CC9D47C8B573B6F8CD06510D9D9C33505EB9080089F41434E5695759B4641B2F06F33B4C8EAEA86116B7A45422FBB1E1FC0AF4C75CCFB94DEA99"); + byte[] mu = Hex.decode("ACFA27834894431BAA18EB0353DA5383BCFD8585E60F1A4382566E0D85E0519F67084AC615088A85074D901D8DBD36AE487B23281E1172F6C03C8CD31A4B683B"); + byte[] sig = Hex.decode("146E97D0704552E762FBF3B0387C255B381D84A1B98EACAF572E71EB0317133758BBF3631CA6C3412238327AEA511432CCF868841BC7F71E484DDB8158E20687AFA3381DC14B96E045036AF004955CF7C9BC9DBCDD3EE558C73E9E16AAD91603E0D839294684B358559F0B2278B5ABB6224395E02849CD7E4DC52805058809674D9CC79744A25436AFBBEB77784F6F85ABF315E963794270C763128F5EDB8E390E0CD2328B868FF6AEE3BC1DE73DC66DBD9D967E9BD1E0E96008C8678C5C28ED73349C297E86DEFC00653E97D873DD6443E4164A0D5231E8C9EFB4EA2F068FECA57BDAEA4A7989C96ED307A578013F705073E875B045CDDF8D131DC6A72DD4EB63495C0DDF53706EB43E44B7B4FAD7C835CB6E9C0D771894A11289A43D3454E4FC8301C9CEC180EAD4B763D332E4760CFE2DDCA5893D0190E6BB7E36E9B596AE714B5B30C65BA0B0675595BDED190BCEA2450063BA157E4CE7DAC45F66FC270BB0608C82196F5EAC4B53C5E2F8C59C3D18222428F935EB3F4E54C1FE7DE4BFDE305C2AFC36C91894387DDDC957C4D2737E9FCDE5C7CAE453A4C45D4FE10A811C78179D6DDB4E33F5E374245EBC3D3DEA4351C8F55E10CD0F79B70010E897BD3F376F7693937F2DF58A7BAB9A0AF5595E3383C426DEC394EBE410C026A2F3E6B2E8200BDAAF15F33DFA4ADEBD59F386AE6C8F097E1183CA9577FFC008C710705DC73A87B6EDBACC23CC8C4FE652916CF8DDFFBACB92EF6BAA668E5772A0A06A2F4DE1F307ABDF6A028BE7F82ECECDA72A411CFBF377B1B3B2AB731563611F8BC933478913A8C1FFF1BB7C76F7B6E55125A41A4FC12C306349546AEA527FA24C0815AAAF8AA3E5367654A6B2BBC886804F25A57E64EAFC0E1D3F805979500A7EF16AE8F0A6E13A3DB3B72A9A91B9D11D9C1A19A0300663C7E931A4AD5EB503EE6F4F7264B66C43C98AB26A5DC42BEFEBC5CAEDC08F7B328C5556B904AA173867737AB3EAEA09722680DF5CB5EF3A1C0D549731EF800D0C72AE8D90BD6C21BB4F4F0E2F4147181C4054F29EAB4A0AFCA49E7406C1A711F38659A638646E5CB3C142747EF843F6517A905F70BD93818816641A45C894E2D44E6CAB7DA0524C9998AF62EF0047CE1A7C5EDD490938402FB1B7015273FBDEB85E536946F0AB7051062536ACD21BAD2311E4A45AF17714426645293EF0D6266DB59692DD99286ABA0C9C77581ECE32CC4C7FBFABA55D719E35E68FC0A6C7031F999BB08153C2501FD61BEA99198DEF0C514A6A1A8FF6E5D9411BC0B7BD2B66E364AF51D007F49DC9E2A756396B1842BF6FCDDF0A2F9E8AF485AB8AF4653FB1F9570E99633DD4914624177CF3D2027053B0BA0D60FBCFEF92EAD69494C56D2717C427666AA313884FAC83BC42DAF224826E127F4B33A6340DEB52942E2792D90023FEBFC935E5B18C6EC8B2A6861C3F2C929A3FFA38C2DD23A97EBAA2CC694199BE95E93BDA5C4CBD13712D03A0C3CDC1F0A1C9B64A88F0E752A167F8F093077CA73B538A8738EA7F2B878A29FAA7D42266FCE8CF16A9BB413FD50FCF6057F77E16C916704AE7622AF72D666AD06C2596E9CE3A297786C134A430441958484EB058C8DB19D1A6E788336D67D52E877CEB4C9F204E4D995FE2685AAB6EEFCFA6D0FD1D61B0C8F532953B32642A34657BFBAD90B8F0C85A821054770C6A2E27D8CE315618DB82EA24A1D486C12934EBC9133F38B72481748B8C9D432A3D1E1AF85DEFB2BEE0C155006BE17E879811E2FE08A337D54A03E5884384000DE817A3D9BBE94941A52A58ECE851F605B9F69E1C3112CFF92AB332D6E694A65EFD58ED61F57F84947A75A5C9776A9A7FD187C5015425ED708DC242CDAA30BEE759BBD9CBB046DF3F4D54F481208216AF5CA7892150DD9829A3AB540BBFCFC2E303E9205ABB4D65D7287B5BBCC85F8987AD7B182058E36DA5C37FE5658138ED49D65B11B67360A1FEE9E44D2D2C3164BEF63B426DB495540B383AAE5F54283F91B1E543F7F965289CB9F64928E6AC208D9791DE234ABA43FC2B44D89317277136F791C782A773340998C526015C0415211676F53BDCE809974D6450E39CA2C814F644D75CB4F349D28EDF08B1CE58616D16816B4C021C5F16CCD5FB539BEFA6C9F03704FFE1010589350C20AE319545B0E39AE7CAA7FCED9A3D2151ACF6CBAB5FBB0D0E83313A45E6209046BF1A89D5F808969CC62167B014E969EAD6B2088B7738FAB3D277D1CDD6F4C6816B847AD1D30083F77564CABEB55CB4A8BB8C6BD47A59B6772DCCC8431A01C04184965B8F25BF8333281AC7686852FAFD77B374E76D8839CFE1F594E212531325F0CD6F8C2853194B4D668F843776F0E563E00CBBE6F5D6EBE4EBC11A5F70D3872F669939BD4A21A26FCD836DB79EC271CB463A521264DD62CD0A664B1EF3D7B4C84793F2B9C36369BEB651858CA9D5DCA23D6F8137C6C1F96FEE19DD3A4CD08A4FD4CD579F0F994E302A62F37121189B2A61E8591A98E0396766047B77E8D4533E62891B77AD0F7607DC0AF1D7D327E8E7B45991A508B5B22FD3398BEA7F80966EBEF5A1ACF9F5FCCF9C0C6E61A05DBB583EB048CAA41C28E87530820D21E90BFD2CFF29C8FEC2F7F1FC90605F2C84553A709CB9F53C1BDF12DC20524E76870ACB7624AD238B5BB8EEC8D5D37F02F12D1DF2384E7EC70CFDCC25831305682080326E702795ABFC6DF60BE923AB245887A35EB5EC00B7A109F86A8F7DCF2E59DBD8C4C9D645588F4D25C768F499C3FA65C98FEB48B07A4B01C7AF8AF28ADBC5C487A5C1FB059EF91B3A77C8321126978B5EAD648BB96C6210C6EF505B6E40098E415E0324D1CCD0A5B0560455BA894AD84CFA8E9B37706EFC23B00513BA3D6DF77D38E203AAD4E718286BE73A729C7CB2CB2EEC65726EA48E657DA31A548972B21642C01512421A21E2A4151A995CDC2DA9A7602E747CB62C893D555BA4455ACD880282459257622B370F3AEE7C99C2D8CD31050E6F1050340EB287BE92133C2479F07780ED355CC124FBDD2C7ADC2A129DA3A99C964F1BB32B5609C36ABB69AFABC0F1445362DFBE2A381C3D88973EDFF9D98ECD0E5EDA94D394B784ABC97470283FBB87403A5DCD4BCF55F24F4368BDE39E63E3C906FD2EA6C4103EF571FCD269700472C761B2E2C52F9F10C195C7947AE378B40724499C8EB3AE5ED4B3B06DCE02F29424662BF209AA14D39C1EEC5E3E5DE7B7CADFD1D8ED9D0AA552FF54353F0E9BD1CD02965A47D83F1359BE6FE0C0144BC0EA8BD2C37CAB4DFBEEB31833F4146316023C4D556C7C8093C3CAD4E7040B122B375963767893A9B4DEE5EDEEFAFC0409121A326F7072A2ACD5DCEEF1F2F4FD051E26373B3F464B97999A9B9FA4ABC9E2FDFE00000000000000000000000000000C1E2F42"); + + KeyFactory keyFactory = KeyFactory.getInstance("ML-DSA-44", "BC"); + + SubjectPublicKeyInfo mlDsaInfo = new SubjectPublicKeyInfo(new AlgorithmIdentifier(NISTObjectIdentifiers.id_ml_dsa_44), pk); + + Signature sigImpl = Signature.getInstance("ML-DSA-EXTERNAL-MU", "BC"); + + sigImpl.initVerify(keyFactory.generatePublic(new X509EncodedKeySpec(mlDsaInfo.getEncoded()))); + + sigImpl.update(mu, 0, mu.length); + + assertTrue(sigImpl.verify(sig)); + } + + public void testMLDSAMuExceptionTest() + throws Exception + { + // mu shortened by 1 byte + byte[] mu = Hex.decode("FA27834894431BAA18EB0353DA5383BCFD8585E60F1A4382566E0D85E0519F67084AC615088A85074D901D8DBD36AE487B23281E1172F6C03C8CD31A4B683B"); + byte[] sig = Hex.decode("146E97D0704552E762FBF3B0387C255B381D84A1B98EACAF572E71EB0317133758BBF3631CA6C3412238327AEA511432CCF868841BC7F71E484DDB8158E20687AFA3381DC14B96E045036AF004955CF7C9BC9DBCDD3EE558C73E9E16AAD91603E0D839294684B358559F0B2278B5ABB6224395E02849CD7E4DC52805058809674D9CC79744A25436AFBBEB77784F6F85ABF315E963794270C763128F5EDB8E390E0CD2328B868FF6AEE3BC1DE73DC66DBD9D967E9BD1E0E96008C8678C5C28ED73349C297E86DEFC00653E97D873DD6443E4164A0D5231E8C9EFB4EA2F068FECA57BDAEA4A7989C96ED307A578013F705073E875B045CDDF8D131DC6A72DD4EB63495C0DDF53706EB43E44B7B4FAD7C835CB6E9C0D771894A11289A43D3454E4FC8301C9CEC180EAD4B763D332E4760CFE2DDCA5893D0190E6BB7E36E9B596AE714B5B30C65BA0B0675595BDED190BCEA2450063BA157E4CE7DAC45F66FC270BB0608C82196F5EAC4B53C5E2F8C59C3D18222428F935EB3F4E54C1FE7DE4BFDE305C2AFC36C91894387DDDC957C4D2737E9FCDE5C7CAE453A4C45D4FE10A811C78179D6DDB4E33F5E374245EBC3D3DEA4351C8F55E10CD0F79B70010E897BD3F376F7693937F2DF58A7BAB9A0AF5595E3383C426DEC394EBE410C026A2F3E6B2E8200BDAAF15F33DFA4ADEBD59F386AE6C8F097E1183CA9577FFC008C710705DC73A87B6EDBACC23CC8C4FE652916CF8DDFFBACB92EF6BAA668E5772A0A06A2F4DE1F307ABDF6A028BE7F82ECECDA72A411CFBF377B1B3B2AB731563611F8BC933478913A8C1FFF1BB7C76F7B6E55125A41A4FC12C306349546AEA527FA24C0815AAAF8AA3E5367654A6B2BBC886804F25A57E64EAFC0E1D3F805979500A7EF16AE8F0A6E13A3DB3B72A9A91B9D11D9C1A19A0300663C7E931A4AD5EB503EE6F4F7264B66C43C98AB26A5DC42BEFEBC5CAEDC08F7B328C5556B904AA173867737AB3EAEA09722680DF5CB5EF3A1C0D549731EF800D0C72AE8D90BD6C21BB4F4F0E2F4147181C4054F29EAB4A0AFCA49E7406C1A711F38659A638646E5CB3C142747EF843F6517A905F70BD93818816641A45C894E2D44E6CAB7DA0524C9998AF62EF0047CE1A7C5EDD490938402FB1B7015273FBDEB85E536946F0AB7051062536ACD21BAD2311E4A45AF17714426645293EF0D6266DB59692DD99286ABA0C9C77581ECE32CC4C7FBFABA55D719E35E68FC0A6C7031F999BB08153C2501FD61BEA99198DEF0C514A6A1A8FF6E5D9411BC0B7BD2B66E364AF51D007F49DC9E2A756396B1842BF6FCDDF0A2F9E8AF485AB8AF4653FB1F9570E99633DD4914624177CF3D2027053B0BA0D60FBCFEF92EAD69494C56D2717C427666AA313884FAC83BC42DAF224826E127F4B33A6340DEB52942E2792D90023FEBFC935E5B18C6EC8B2A6861C3F2C929A3FFA38C2DD23A97EBAA2CC694199BE95E93BDA5C4CBD13712D03A0C3CDC1F0A1C9B64A88F0E752A167F8F093077CA73B538A8738EA7F2B878A29FAA7D42266FCE8CF16A9BB413FD50FCF6057F77E16C916704AE7622AF72D666AD06C2596E9CE3A297786C134A430441958484EB058C8DB19D1A6E788336D67D52E877CEB4C9F204E4D995FE2685AAB6EEFCFA6D0FD1D61B0C8F532953B32642A34657BFBAD90B8F0C85A821054770C6A2E27D8CE315618DB82EA24A1D486C12934EBC9133F38B72481748B8C9D432A3D1E1AF85DEFB2BEE0C155006BE17E879811E2FE08A337D54A03E5884384000DE817A3D9BBE94941A52A58ECE851F605B9F69E1C3112CFF92AB332D6E694A65EFD58ED61F57F84947A75A5C9776A9A7FD187C5015425ED708DC242CDAA30BEE759BBD9CBB046DF3F4D54F481208216AF5CA7892150DD9829A3AB540BBFCFC2E303E9205ABB4D65D7287B5BBCC85F8987AD7B182058E36DA5C37FE5658138ED49D65B11B67360A1FEE9E44D2D2C3164BEF63B426DB495540B383AAE5F54283F91B1E543F7F965289CB9F64928E6AC208D9791DE234ABA43FC2B44D89317277136F791C782A773340998C526015C0415211676F53BDCE809974D6450E39CA2C814F644D75CB4F349D28EDF08B1CE58616D16816B4C021C5F16CCD5FB539BEFA6C9F03704FFE1010589350C20AE319545B0E39AE7CAA7FCED9A3D2151ACF6CBAB5FBB0D0E83313A45E6209046BF1A89D5F808969CC62167B014E969EAD6B2088B7738FAB3D277D1CDD6F4C6816B847AD1D30083F77564CABEB55CB4A8BB8C6BD47A59B6772DCCC8431A01C04184965B8F25BF8333281AC7686852FAFD77B374E76D8839CFE1F594E212531325F0CD6F8C2853194B4D668F843776F0E563E00CBBE6F5D6EBE4EBC11A5F70D3872F669939BD4A21A26FCD836DB79EC271CB463A521264DD62CD0A664B1EF3D7B4C84793F2B9C36369BEB651858CA9D5DCA23D6F8137C6C1F96FEE19DD3A4CD08A4FD4CD579F0F994E302A62F37121189B2A61E8591A98E0396766047B77E8D4533E62891B77AD0F7607DC0AF1D7D327E8E7B45991A508B5B22FD3398BEA7F80966EBEF5A1ACF9F5FCCF9C0C6E61A05DBB583EB048CAA41C28E87530820D21E90BFD2CFF29C8FEC2F7F1FC90605F2C84553A709CB9F53C1BDF12DC20524E76870ACB7624AD238B5BB8EEC8D5D37F02F12D1DF2384E7EC70CFDCC25831305682080326E702795ABFC6DF60BE923AB245887A35EB5EC00B7A109F86A8F7DCF2E59DBD8C4C9D645588F4D25C768F499C3FA65C98FEB48B07A4B01C7AF8AF28ADBC5C487A5C1FB059EF91B3A77C8321126978B5EAD648BB96C6210C6EF505B6E40098E415E0324D1CCD0A5B0560455BA894AD84CFA8E9B37706EFC23B00513BA3D6DF77D38E203AAD4E718286BE73A729C7CB2CB2EEC65726EA48E657DA31A548972B21642C01512421A21E2A4151A995CDC2DA9A7602E747CB62C893D555BA4455ACD880282459257622B370F3AEE7C99C2D8CD31050E6F1050340EB287BE92133C2479F07780ED355CC124FBDD2C7ADC2A129DA3A99C964F1BB32B5609C36ABB69AFABC0F1445362DFBE2A381C3D88973EDFF9D98ECD0E5EDA94D394B784ABC97470283FBB87403A5DCD4BCF55F24F4368BDE39E63E3C906FD2EA6C4103EF571FCD269700472C761B2E2C52F9F10C195C7947AE378B40724499C8EB3AE5ED4B3B06DCE02F29424662BF209AA14D39C1EEC5E3E5DE7B7CADFD1D8ED9D0AA552FF54353F0E9BD1CD02965A47D83F1359BE6FE0C0144BC0EA8BD2C37CAB4DFBEEB31833F4146316023C4D556C7C8093C3CAD4E7040B122B375963767893A9B4DEE5EDEEFAFC0409121A326F7072A2ACD5DCEEF1F2F4FD051E26373B3F464B97999A9B9FA4ABC9E2FDFE00000000000000000000000000000C1E2F42"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_44, new SecureRandom()); + + final KeyPair kp = kpg.generateKeyPair(); + + Signature sigImpl = Signature.getInstance("ML-DSA-EXTERNAL-MU", "BC"); + + sigImpl.initVerify(kp.getPublic()); + + sigImpl.update(mu, 0, mu.length); + try + { + sigImpl.verify(sig); + fail("no exception"); + } + catch (SignatureException e) + { + assertEquals("mu value must be 64 bytes", e.getMessage()); + } + + sigImpl.initSign(kp.getPrivate()); + + sigImpl.update(mu, 0, mu.length); + + try + { + sigImpl.sign(); + fail("no exception"); + } + catch (Exception e) + { + assertEquals("mu value must be 64 bytes", e.getMessage()); + } + + } + + public void testMLDSAKATSig() + throws Exception + { + byte[] pubK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139fdd6a6ce5bc76e94faa9e9250abd4cee02cf1ee46a8e99ce12d7395781fa7519021273da3365519724efbe279add6c35f92c9d42b032832f1bf29ebbecd3ec87a3af3da33c611f7f35fa35acab174024f118979e23bf2fe069269a2ec45fbc1b9c1fb0e1f05486a6a833eb48adc2960641d9af6eb8b7381b1ec55d889f26b084ddfa1c9ed9b962d342694cede83825309d9db6bd6ba7582132534861e44a04388a694242411761d34e7c085d282b723c65948a2ac764d9702bd8ed7fe9931d7d8704a39e6508844f3f84843c305594fe6e5404e08f18ed039ac6563cbaa34b0ca38320299d6256ec0f78d421f088159d49dc439cbc539a55884a3eb4efc9cf190b42f713441cb97004245d41437a39b7b77fc602fbbfd619a42363714b265173cae68fd8a1b3ca2bd30ae60c53e5604577a4a3b1f1506e697c37432dbd883553aac8d382a3d250cf5b29e4d1be2cbcd531ff0e07e89c1f7dbc8d4529aeebe55b5ce4d0214bfdec69e080bd3ef36cca6a54933f1ef2f37867c0d38fd5865b87929115808c7e2595458e993bacc6c5a3b9f5025001e9b41447708bfbaa0462efa63876c42f769908b432f5485508a393224960551d77eadfaf4411cbc49fdff46f2f155ddd6ec30867905b709888ca0f30f935fb8d7f4803cfc7a5f7790ca181d99ca21f2621d69a5c6d49c76b4969da62740a378470332b30947ab31ccdb9ba0c7b625879eec4bd81f0200ba23504a7dc3b118bc2ab1145df13af3c8cc39f577873b84911b3d85fbbf4cb19e4d36b10a938eeb78b599dc86615fd6cec6eb7b8f7afa5f6d6be19ea81630d36ccfb2f487de50d0cf46da8d3fe3512812043c0e3ef2d7231fb0b0a35a0fb283be30a1247780f30ae0294e8b6f5897383edb895595f577524df54593cdf927b4967616ee3913e4d6b29b0dbd7c33a2a45e4ef1b1954ea5d91ce37efc1302e7ce02a97395565da2a5c5d3fdb0d87684e9b1c0ad07ec33df2dfad528e2ea0966d2a47dd5ee88e77d653c0d004fab0165f0757c4da40af327e7192536c79947a80a827aa2107dacfae3debfc8fad3d6e08076d938c510a276bdf6721a1f087cb169515028ad5ce27a1047abd92809934ca63b893f71f9a34a99c0fd30310c47e9aa37394d0ab73b254d3ca69d9c5549c9479aae24264ac5ea64d3fd821c3962ec77e709f9d30bc7b65a52e48c16e80603558caca1811411c3155d1f949fc9cf9aa9385a7199e99be77a66fad7eed91258de55b2c4c83f9a050adebea5f09758f40dac4a1c394ee8d687879150d26426895ab1938e14ae11b376254c91fc6130436996f8ed43bd27be20ec9067111c116ec94cc2b06cc91a13c5d10bbd7eecea4792f17b2b77631ef145e9fb41a83eaa11c2b72a48fb90fdbd88644c4edf8ab20dce3118364b276ac1237b36c8926e346aab5a111aa0bf341c518b7bff9e9dbb8bcb4728601b3760663e67650331e6fb54ac82fc414cb8ddfc160a25311ec5272de46217fef8b992ff89754fbee351f21bb90b6c97078b510c983350681266c8fed1f0583c5151e7b8fe3b7292319699687cc6b641fdbd689428543bc0fa1facc109de65b62784c2d985ab15d77d3af12af6d03e8d1859a553688584d75ef673a1de74093ee108c761fff32c217c231b0e2953daf521429264c0963bc8a5cdeddc617a7285b934ea51ddb5cdab23bcede86be36e001bc65c65e9a1c94baff4fab8eb5f8ed42ec377423633fe00049142467c47c5d58a7202c8e9104841c1f7f380145a6a0a828c570235e507ae5868a6062f722bb98ff6be"); + byte[] privK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139ff037b84e75537e0a1cf02a517acfe323ffffe11df72e4f38430e0e66a2654b2f2ef757da47649d9f63fa03f1bf6fe6bc7c62971a98a2bd9d36eb0ec43ad4e9d940df3bb5874f5c92192aa31e0535d3cf70950bba858d11a688eaf854f63ecfc520c50d624891434265d8b0680c03061040299a104082c0910c8508d1100d44a6509408292211125b90508a2688e1302dc4021280028ac302611820851237808a000ae2040421b4910bb80550a08051b2511c28428a3672a494504910201bb45161424424a75001328181942d62a850023449ca94200b296213156408924c48122100b605030208e0060200a311e1802021116483a62898029291480801083041066613200e5b360951400c53000aa08851944842e316704ab2089b92440025121b0309418209c2a0800b290a819851c4340da4424500a0105b048e603400138928a4422648002c90202d194068e2146d19278a083746e4146914006422c660d3a03013242844965014166da0284dcc462e94367100232e1c114909a2040131060a2172c2142ada000c5a260d13228a62c444e3142d013445980224d33841c0308121a621e348720b1984d2c89108b8690887714a2884d496451a9301ca2285da30859ac851dcc00820106060465262302aa224251044640b2842988011540692144251d236719bb4900b082890188e41c469e1a469032160e01409d3020c20c88c1cb23164086218476920228ccb8470089528029550533270013405888424541041d202881aa84ccac88181008d0392899ab809d9900c9a1290614065c9322d89860c123521cc4266c8360010062411028ea3b44d44023043a0285a002ed1980c4882658922441c010212907084226e12134d011902519064113364c91806c2c04589262908b63024308cda022e0c27250b367058162c5116420b4946c1208841246c99466a04434e18a86c821661922028639409c30211029520211782d43868003460c84688e0160000a32dc0a82824b640831464c81022a2086503234ac8122ea098418c2072cc308a62c665093408412682da429089328514967081226001176d5948428ab88d592051d80892e2c0889044700ac0245a020904218a59c45094441094140820460209270c441020dcc8209212015038250c456e4a1666223770dc808ca426412222441ba3618a343099844099c42952046d88146ccb242a7cd129a8d333115c62d033b6a8357cf7cd10268ab12f16fceb7975d0a28a6c4822213c9a772df084ad91a669e2040550fc5e8d0aeb10fab2375fc9625ef9cd48c19631997a1cb6455d2c6286c569c9637add0317ce990996b28e51c3f3f717fb5907bbdd53961ad3497f2c3c473cce170906ac4c624a89aa8fbe624d99385e9c9548bf05e8cafd47d2476e41b73001f813726499e88b2b3b6f596ca311657850346598994c40e34747161e4e76264deef2a3019389d1594c942301af47b7544c23ecda2df2dece81e487d8f3f58ea89cd811d7275807ff1b0369ba86470088c174a3099fdafbe5fbb4d158801053b2b435d54059e26dee76d10a7a372f06b0b88b985b32f52052387438be8dc8bc6ae7369e2da9aa5e2585f8de403d091ccb7f790d54ddb34c608b0876f2825e9113be20a2b85867a01bda53287ac780bcd8b606d2e6d7712c56ce0142d22fe6b786de544963e134fecedfafb83d763061d799096a59e30d4472e440ae1faaabdf42640ce69740ceb9cae1a9612c21931b74af3f780236123321b205b6efd6cbb134f4c73d63c0c13e660b59d5920bc33197c355853d8d1cddc7959f7bc500ac81d985016f5b89a0eec79b0d9364ead8e38577c2a6549f2d067cb09438fdb21220aec80f6e22a476f332a2a4a0b7acbeb9e078d2b5a92ae84c924f7cb19fc7df377beb6546af97aa985c747cd111a127a674b4c26d89c14485b82e3a498a12d05406febd6c4d4b8bc051ab2cb91224b078538374b794b7dd9ddf3ac2b4a671fb7b9cf5acb78622ae2709eb2db16943aa24a9c97a81077bc784d25c0ea5991d2de883798a1f0e78f3361ed6a10dded81b1d683658331534fd7c01bc0eb00dfc4c3c84f0693046ff806bb200dd7bd4c0e6abca3f2934b4814fc0e1f8be615a2dda7c8a8d06cf9ce8566b40f4a6543b25bacddc926863fc0fa2007d6d7bf6d18dc98df696bd0865bf0be4c492b8043a32def8e3595ba7da345252f38f95be10fd7fb899b498fa01b09de5d5608eabc44a721aa04c4ef1dcb86102ac5f5f79c9708dcf5c5e896edd8c2c7bde3fa83e6ffce22d66174e31657a0b6361585e669d3031952f08631ae1f16ff90b90d0aad3c6d7e1dd0a9c41ab00a6e1c4f96af9ac5b79fcf821ffc016cb059245fb78dbe6c633d965aaab5333be07195c4b74b18e4600ce783c0a914ef4281016e80a7c9aa92d0fd789879c5e6751125ecb154432311e41cebd4fab3a31e4d2ce22d0f8c67737bf8a0dd85fe1349d5079a4d5feb3fee9378ca47ae46cc58a3f02038cfd53c4cee9cc4270cebc3d115a39c831e8ed41c4dbe4051b51d7872ba0c2bb163e0085201188eaa624a6bea9400a3a1fcc355a57f15704e61fda55a5dbaea8448fa5cb2d377a07f58305ad107e844ab4806e5bf99c1f513ee1d0a2acc04549f0801742169a77971d0adbfbfe0dd2ee5d16bc461e35748d1f3f6f4598321e8c49e79e740f990359858d2729dde007fcb26fdda9aa6e2ec4bd736f2836e7e4c83440191c849f6a53c72a4f8f830d001ea3b18f3cb4a5bd3cf066032b4932cfd2e62a9b55723fa61c688c935518af6860cd649bfbf1bf5fdc1f36dcaefaa157438d1cc8d56a150161511df82631f5e88e773e4ce263f276b7b3678d4c6fc75311d411c0d01bfdb595bb70552838e1b86517c837d909e772b428599e1fe569f77ce61531fde6fd31cdce1bdee4ba467fcbfbb9feeaad99fef67d4906e036c73662ddce158d4e5d4635e5d366f79f31a19d1b3dc4a591b0df194bb06c18147f41d88d1a409becdfb67eb063d16312266fd51b521ba9115e2e5e2aeae6ec511cede13ed4132ffbe0273f6c7039b3874f058804a54809af60557a21d9b4b831d04156a7c22dcbcdfe14f62437f449cb5ef12bf4251d485496cd835c0c2bc58bd845963dfa76ecd68519c4bdaf110be7ab052876dc3407591568c956ea3bf107c90fd5853a292f59a8d4b58b5d3fddf29bdbeac36852e3c69766fe460176a801831292b8e88a74a01ecbbe09a7b4d74cfd7fd628841944d9d556dbd60c76f96f07dc53443805ee9aa09365de4fb8179252c6b099b5dd351fdefc23dbd8090596c5d208ffd2c5661d8e5612dd574fc69045c769a969e600d77cfe192f1d3ae911289355c585811491b0ccd73692ab158824ab9edf8ac8193f0b33e6138b72c6dcd5d344f807b3da92425037de5ea4eead1c795effaa145e2ecdd327606eb2609929b9474b2bb04653602555c068385e92f06f29ca613ce5b4404f01ab1805db0acaa890330d291f40692df382509302b6dc8668f2c8f2d3a44fd58dca26e9802794f73d25b3149e6d576441"); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + byte[] s = Hex.decode("237c7b8820733d2cf35345f8a851996061675570ce42923ee2cd437e41b4a9b391481f71ece9e0b64c584a73710d8d688a930ac0bf02abf57c6e4709e724a9e4178c629018bc0b73b37a087dd3e7ea8da65b1145bcfeed1a7c1223607eaf0aef04ab2b60d47460945c621a4f9356130bcb5e94f00c710d1cfe99c05ea0cf9e0779577f3671560316bf24ec9cf2572b13e9a50d5fbcca4ddce481f740db1d7e200268459629d66eb5a0b5603ad6468a4a04498d84df62ee394d6fc5a3a7b1ef9de0cebe88168e5d6f771efc1ea315e78b83cb2c0ef88f167ee170dffddb9acaa5df380af1f80353746b6a5530c9fde8458eec99b478dcc6673236b277c41cde9eba586b9808146ccfae6fd8bea1d0654f65cac7583ab7050711b1a322d8da6c6aad16608a9053a655580d66016fc9cefaa17fe0fed5080dbd4daa9692f96794243a2813677ad542e1e164efa9341bd0fdba956a1b4b594f1a70fb3c14aed1217b861dcb749a56b281205d7df5d472a08fb376955524dda1017bcc8be85768191d0e18570fa8f263bd592a8d5358cf7f6ac28e0c664776acf51b689cf2e96603cb7de14978cc56f00819a217b5ae5e3c083c487f5a23c07939737c9ed6b2a51e04f39ddc69da569b88054fc64769098056d83539759d0cc487a711125bf73de1f6671695f5633645534e6cb2d374645c3c9fd39c5347c4b82fb1a452fbb6137f3c470eb1fc7240a5c2a281a1dd45670807552bcc0d160a6775b6dfebbc68500eb76e1e96db1ca0f31413c96f87354ab7071c7786c9e67d0d6476282bd676af23feeb7127b7864daca72f994a85bd10f1f66ea1240882f9b62895f19c0aaad1cf35cda81b311993194d977337d9a10728a7f3d82c8d7fe35cd7047d233c8efe1d9b66b2828c9b582dc2e4605683ace6be76ba351b6d7a1db23a81854d17e9601e7dc69beaae6426ef307300508d204b433026e0534dd0f0123b06252524769f2f86771c8cf5ee82f0b3b3010828a300578871af9b6031f34342cb2d5ea4093c50b621b10248d0a32c1cd5684ca50b5f9886e2df6deca3213bd5cd79d63b5dc8266beb4d80beeed82c9ee801ed35c6a9f69947e806e791173b5b883e20192573e85e7003f99c5ab417e72f03563eb93b163f4c2300675e8c1ab9f80cf62c88b1876fd0bd4258e0e083da712e341fbbceef37d59e090f6eca0cb3e8e6b7fe1c7f35c3a9db958cd273fcc581b285e30e3c35714f01d2eda306a6e66d9609d4ae88248bf76a991acb8b833255aaafcb27498d009eff0aa5264e1874b17eb646dfce4707e8bfb946babfa4f7affe388c0656b9dc4a8bbc670e64d42676db5b3cd017ce6d52e2547d43745e66ed9b1ca2228594546b4c2c636f524edec65d9ade60a9fd3b2586af169ada64574d85594cbaac5f3827d3c4317e51722c497f09dcaa4b7c4f03bd4fef3ba847d38d252fccecd7e207830fe4d60733b49527b5d29e71d2b736a97d9d34475fb081d0bc8810507f672ae03232bc32a33c711a3f12826fe1801f40962061e3d3fdeb3368e91eab892cdac18f0e06a4312e67f445578dbeaf54f5c3cbdbae0ab2dd84525a32253b3720d83c9b3e50ecf0554c89d15bd352b0636b40b79d38fc5cca5e696c1ff0cd2f0934fb3eaadccc1b6d5fac5544b6fe5c6e0a317c4fcfff2b1f70718b7e4e7cf3db3bf1c002031ef50c049bdffc3b78358e0be20eb57ed41bae04cdd09091afefa457a8aebb3376370ee04a7f48d444b7f1170edab68e0b970e8fc2850976536ce3bb14586af06baeac171278a5e949e00af7cdb0d4b841244ccccc797ff3fd4187077d4c9d33873cab0bf6e690591b9021f80c52d47494051ac1ff75554b6b1907903dc530ec6b42d025f723d7d4e539222e683e47532541f25f14b0c007b093b7ccbfc0172e78e543517f632149d842821a2b414d0db9aac1398b5e99c269ef4e303e1373f9bcdf8211b55c65ec19f93a0422a7148cabd4c311f11a49efc757534d00cae3c84cb849e975193145538917f81225cc96457bc1a2ab8fa72afa8563dc314766ffd19a10db92dabf9a0656066728d384f598229fa94e906b8a3222b0dfe164afd9c116f31c315ee53ffb0b0d582ee0abfad259f1b4095c00a347673fd4e17ea7d8f974dbf2ed90311cb167d61aebea7b0b17a34f5b721fecafcfbc3feac7091b81851f8a5b051add8e724a503386a53b70d106d86a99813d579ef75a065cf70cc1ab9d80c39a01d3c5946049efed8d4e383b5ca65827a9cee08cba792a903347f7547a64745f8e17d71a0d40d71d15484b9a6814c86230aa05539e907cddda5efb3162c356f35829bc32a28bc80ec9454e5bfec24a6dd74675e3b913647f3d176a6773c1a0e40edd17ecd13aee3493710b1154f855f2591e62cc7073c608bbaa77104e8d4993b67cf81f65af89c8c91d695f7560daa68ad14160cb7df4e7a61b1860255320dbb813676df1285c015aec994d7bc0ce29751416b31ed15b69172968ddaa515692b8febccb4e3298e8bf169c20b965903b80f26f20a6a3bd5facd1bc38c6c817e23bf35187ff75f982ae9ed65a43f6199b61ae84683e1befcf9c0178b8ea2890f96a6e08d33d44c3ce50d9ccbd1cdf96df6b2f5e8f1c6cb04300f7f6d483108390aea8ed31b07b32c87c542ab475946d525e24c16b2d0afb86687e47cce7abb5b7fc41d6a9953a59a8b221d057b793845cfab414726b3753d87c020253fb93722263ceee93a66acf163c86eb7bd62136f70ec414b5562862f1202deeb9feaf7981416be2a09c0e7c1f18ee95314b54d0497bac2986d90e9ed3990220e96ae1622e11f2ee91c1b16128e7384a87fabc6731c7b0b00bb707fd1abe0392c95e4c435460b47d2199829b076b4ef6b11ad32825cad85794a674eefdd6173dca39dcbf397c1b9531380a72d142b7d4005d884fcbd59211827820fc5b2bc605e5c717c31e124cd1f57180d4ba598833f097056f809b71214fbee25f7fe7f14e3df8cb6bbf6c3f3de82885f71bfd874e6b7ad11db7210fd73c0ccbaa60f008a86a59a9860c0c851672da17b077d35977c52cf35bf06d450f3ec061977f627324c55aada361c6abb3de77e828a63aef6dc37cdf0caf3b98c3a409e3cdbdd2edd0dc4feb1a6ede8df7252cb658413f22728142304d7d02b06e438b10814f7731a489e79b6b8a6b0fca6b63fe9a61ff2994704bdff918e1ae6a99df07d3e18a216890465397b6eda5f47ad2f216817544b8840c6af1704d9a71a02c73b6a29fb6fb17787d97a8984790a34736050607093d3f557d9ba5afb8ced3d4dee1e8eef1f8fc0117474f558c96b2b4c2d6d9f8439198aac0cad2d3eaed0d1a243d44456486cfdce4e6f1000000000000000000000000000000000000000000000015222c39"); + byte[] seed = Hex.decode("7c9935a0b07694aa0c6d10e4db6b1add2fd81a25ccb148032dcd739936737f2d"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_44, katRandom); + + KeyPair kp = kpg.generateKeyPair(); + + SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()); + + ASN1BitString pubSeq = pubInfo.getPublicKeyData(); + + assertTrue(Arrays.areEqual(pubSeq.getOctets(), pubK)); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); + ASN1OctetString seq = privInfo.getPrivateKey(); + + assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(ASN1Sequence.getInstance(seq.getOctets()).getObjectAt(0)).getOctets(), seed)); + + Signature sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initSign(kp.getPrivate()); + + sig.update(msg, 0, msg.length); + + byte[] genS = sig.sign(); + + assertTrue(Arrays.areEqual(s, genS)); + + sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + // check randomisation + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + genS = sig.sign(); + + assertFalse(Arrays.areEqual(s, genS)); + + sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + public void testMLDSAKATSigWithContext() + throws Exception + { + byte[] pubK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139fdd6a6ce5bc76e94faa9e9250abd4cee02cf1ee46a8e99ce12d7395781fa7519021273da3365519724efbe279add6c35f92c9d42b032832f1bf29ebbecd3ec87a3af3da33c611f7f35fa35acab174024f118979e23bf2fe069269a2ec45fbc1b9c1fb0e1f05486a6a833eb48adc2960641d9af6eb8b7381b1ec55d889f26b084ddfa1c9ed9b962d342694cede83825309d9db6bd6ba7582132534861e44a04388a694242411761d34e7c085d282b723c65948a2ac764d9702bd8ed7fe9931d7d8704a39e6508844f3f84843c305594fe6e5404e08f18ed039ac6563cbaa34b0ca38320299d6256ec0f78d421f088159d49dc439cbc539a55884a3eb4efc9cf190b42f713441cb97004245d41437a39b7b77fc602fbbfd619a42363714b265173cae68fd8a1b3ca2bd30ae60c53e5604577a4a3b1f1506e697c37432dbd883553aac8d382a3d250cf5b29e4d1be2cbcd531ff0e07e89c1f7dbc8d4529aeebe55b5ce4d0214bfdec69e080bd3ef36cca6a54933f1ef2f37867c0d38fd5865b87929115808c7e2595458e993bacc6c5a3b9f5025001e9b41447708bfbaa0462efa63876c42f769908b432f5485508a393224960551d77eadfaf4411cbc49fdff46f2f155ddd6ec30867905b709888ca0f30f935fb8d7f4803cfc7a5f7790ca181d99ca21f2621d69a5c6d49c76b4969da62740a378470332b30947ab31ccdb9ba0c7b625879eec4bd81f0200ba23504a7dc3b118bc2ab1145df13af3c8cc39f577873b84911b3d85fbbf4cb19e4d36b10a938eeb78b599dc86615fd6cec6eb7b8f7afa5f6d6be19ea81630d36ccfb2f487de50d0cf46da8d3fe3512812043c0e3ef2d7231fb0b0a35a0fb283be30a1247780f30ae0294e8b6f5897383edb895595f577524df54593cdf927b4967616ee3913e4d6b29b0dbd7c33a2a45e4ef1b1954ea5d91ce37efc1302e7ce02a97395565da2a5c5d3fdb0d87684e9b1c0ad07ec33df2dfad528e2ea0966d2a47dd5ee88e77d653c0d004fab0165f0757c4da40af327e7192536c79947a80a827aa2107dacfae3debfc8fad3d6e08076d938c510a276bdf6721a1f087cb169515028ad5ce27a1047abd92809934ca63b893f71f9a34a99c0fd30310c47e9aa37394d0ab73b254d3ca69d9c5549c9479aae24264ac5ea64d3fd821c3962ec77e709f9d30bc7b65a52e48c16e80603558caca1811411c3155d1f949fc9cf9aa9385a7199e99be77a66fad7eed91258de55b2c4c83f9a050adebea5f09758f40dac4a1c394ee8d687879150d26426895ab1938e14ae11b376254c91fc6130436996f8ed43bd27be20ec9067111c116ec94cc2b06cc91a13c5d10bbd7eecea4792f17b2b77631ef145e9fb41a83eaa11c2b72a48fb90fdbd88644c4edf8ab20dce3118364b276ac1237b36c8926e346aab5a111aa0bf341c518b7bff9e9dbb8bcb4728601b3760663e67650331e6fb54ac82fc414cb8ddfc160a25311ec5272de46217fef8b992ff89754fbee351f21bb90b6c97078b510c983350681266c8fed1f0583c5151e7b8fe3b7292319699687cc6b641fdbd689428543bc0fa1facc109de65b62784c2d985ab15d77d3af12af6d03e8d1859a553688584d75ef673a1de74093ee108c761fff32c217c231b0e2953daf521429264c0963bc8a5cdeddc617a7285b934ea51ddb5cdab23bcede86be36e001bc65c65e9a1c94baff4fab8eb5f8ed42ec377423633fe00049142467c47c5d58a7202c8e9104841c1f7f380145a6a0a828c570235e507ae5868a6062f722bb98ff6be"); + byte[] privK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139ff037b84e75537e0a1cf02a517acfe323ffffe11df72e4f38430e0e66a2654b2f2ef757da47649d9f63fa03f1bf6fe6bc7c62971a98a2bd9d36eb0ec43ad4e9d940df3bb5874f5c92192aa31e0535d3cf70950bba858d11a688eaf854f63ecfc520c50d624891434265d8b0680c03061040299a104082c0910c8508d1100d44a6509408292211125b90508a2688e1302dc4021280028ac302611820851237808a000ae2040421b4910bb80550a08051b2511c28428a3672a494504910201bb45161424424a75001328181942d62a850023449ca94200b296213156408924c48122100b605030208e0060200a311e1802021116483a62898029291480801083041066613200e5b360951400c53000aa08851944842e316704ab2089b92440025121b0309418209c2a0800b290a819851c4340da4424500a0105b048e603400138928a4422648002c90202d194068e2146d19278a083746e4146914006422c660d3a03013242844965014166da0284dcc462e94367100232e1c114909a2040131060a2172c2142ada000c5a260d13228a62c444e3142d013445980224d33841c0308121a621e348720b1984d2c89108b8690887714a2884d496451a9301ca2285da30859ac851dcc00820106060465262302aa224251044640b2842988011540692144251d236719bb4900b082890188e41c469e1a469032160e01409d3020c20c88c1cb23164086218476920228ccb8470089528029550533270013405888424541041d202881aa84ccac88181008d0392899ab809d9900c9a1290614065c9322d89860c123521cc4266c8360010062411028ea3b44d44023043a0285a002ed1980c4882658922441c010212907084226e12134d011902519064113364c91806c2c04589262908b63024308cda022e0c27250b367058162c5116420b4946c1208841246c99466a04434e18a86c821661922028639409c30211029520211782d43868003460c84688e0160000a32dc0a82824b640831464c81022a2086503234ac8122ea098418c2072cc308a62c665093408412682da429089328514967081226001176d5948428ab88d592051d80892e2c0889044700ac0245a020904218a59c45094441094140820460209270c441020dcc8209212015038250c456e4a1666223770dc808ca426412222441ba3618a343099844099c42952046d88146ccb242a7cd129a8d333115c62d033b6a8357cf7cd10268ab12f16fceb7975d0a28a6c4822213c9a772df084ad91a669e2040550fc5e8d0aeb10fab2375fc9625ef9cd48c19631997a1cb6455d2c6286c569c9637add0317ce990996b28e51c3f3f717fb5907bbdd53961ad3497f2c3c473cce170906ac4c624a89aa8fbe624d99385e9c9548bf05e8cafd47d2476e41b73001f813726499e88b2b3b6f596ca311657850346598994c40e34747161e4e76264deef2a3019389d1594c942301af47b7544c23ecda2df2dece81e487d8f3f58ea89cd811d7275807ff1b0369ba86470088c174a3099fdafbe5fbb4d158801053b2b435d54059e26dee76d10a7a372f06b0b88b985b32f52052387438be8dc8bc6ae7369e2da9aa5e2585f8de403d091ccb7f790d54ddb34c608b0876f2825e9113be20a2b85867a01bda53287ac780bcd8b606d2e6d7712c56ce0142d22fe6b786de544963e134fecedfafb83d763061d799096a59e30d4472e440ae1faaabdf42640ce69740ceb9cae1a9612c21931b74af3f780236123321b205b6efd6cbb134f4c73d63c0c13e660b59d5920bc33197c355853d8d1cddc7959f7bc500ac81d985016f5b89a0eec79b0d9364ead8e38577c2a6549f2d067cb09438fdb21220aec80f6e22a476f332a2a4a0b7acbeb9e078d2b5a92ae84c924f7cb19fc7df377beb6546af97aa985c747cd111a127a674b4c26d89c14485b82e3a498a12d05406febd6c4d4b8bc051ab2cb91224b078538374b794b7dd9ddf3ac2b4a671fb7b9cf5acb78622ae2709eb2db16943aa24a9c97a81077bc784d25c0ea5991d2de883798a1f0e78f3361ed6a10dded81b1d683658331534fd7c01bc0eb00dfc4c3c84f0693046ff806bb200dd7bd4c0e6abca3f2934b4814fc0e1f8be615a2dda7c8a8d06cf9ce8566b40f4a6543b25bacddc926863fc0fa2007d6d7bf6d18dc98df696bd0865bf0be4c492b8043a32def8e3595ba7da345252f38f95be10fd7fb899b498fa01b09de5d5608eabc44a721aa04c4ef1dcb86102ac5f5f79c9708dcf5c5e896edd8c2c7bde3fa83e6ffce22d66174e31657a0b6361585e669d3031952f08631ae1f16ff90b90d0aad3c6d7e1dd0a9c41ab00a6e1c4f96af9ac5b79fcf821ffc016cb059245fb78dbe6c633d965aaab5333be07195c4b74b18e4600ce783c0a914ef4281016e80a7c9aa92d0fd789879c5e6751125ecb154432311e41cebd4fab3a31e4d2ce22d0f8c67737bf8a0dd85fe1349d5079a4d5feb3fee9378ca47ae46cc58a3f02038cfd53c4cee9cc4270cebc3d115a39c831e8ed41c4dbe4051b51d7872ba0c2bb163e0085201188eaa624a6bea9400a3a1fcc355a57f15704e61fda55a5dbaea8448fa5cb2d377a07f58305ad107e844ab4806e5bf99c1f513ee1d0a2acc04549f0801742169a77971d0adbfbfe0dd2ee5d16bc461e35748d1f3f6f4598321e8c49e79e740f990359858d2729dde007fcb26fdda9aa6e2ec4bd736f2836e7e4c83440191c849f6a53c72a4f8f830d001ea3b18f3cb4a5bd3cf066032b4932cfd2e62a9b55723fa61c688c935518af6860cd649bfbf1bf5fdc1f36dcaefaa157438d1cc8d56a150161511df82631f5e88e773e4ce263f276b7b3678d4c6fc75311d411c0d01bfdb595bb70552838e1b86517c837d909e772b428599e1fe569f77ce61531fde6fd31cdce1bdee4ba467fcbfbb9feeaad99fef67d4906e036c73662ddce158d4e5d4635e5d366f79f31a19d1b3dc4a591b0df194bb06c18147f41d88d1a409becdfb67eb063d16312266fd51b521ba9115e2e5e2aeae6ec511cede13ed4132ffbe0273f6c7039b3874f058804a54809af60557a21d9b4b831d04156a7c22dcbcdfe14f62437f449cb5ef12bf4251d485496cd835c0c2bc58bd845963dfa76ecd68519c4bdaf110be7ab052876dc3407591568c956ea3bf107c90fd5853a292f59a8d4b58b5d3fddf29bdbeac36852e3c69766fe460176a801831292b8e88a74a01ecbbe09a7b4d74cfd7fd628841944d9d556dbd60c76f96f07dc53443805ee9aa09365de4fb8179252c6b099b5dd351fdefc23dbd8090596c5d208ffd2c5661d8e5612dd574fc69045c769a969e600d77cfe192f1d3ae911289355c585811491b0ccd73692ab158824ab9edf8ac8193f0b33e6138b72c6dcd5d344f807b3da92425037de5ea4eead1c795effaa145e2ecdd327606eb2609929b9474b2bb04653602555c068385e92f06f29ca613ce5b4404f01ab1805db0acaa890330d291f40692df382509302b6dc8668f2c8f2d3a44fd58dca26e9802794f73d25b3149e6d576441"); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + byte[] s = Hex.decode("098d5709482f9975b8c5c2e04f2dd8b54b4cf14fab51794948e88ab469656e1989a76c1a67bb93f8e8ae33f691773da3a86876c850e77ae2a4f58189f0f98d4fd5c748c9f760cd75f7c1912ad06df232c6ac38d49ceb8f648bfdd5998797812d8d2326cf5a07292a9c0d8fb87ae33cf85723c2e6383f1072d0c2b96aa4f00c981fb2e0c619344fa5ebb9761b8d2f2011639724b6a66cf502a9795da237776bc5da3a0ce35da57a2f36edf365d138c013582a21c8e4e26a43b259240c2af48504fa298ca816bfe1620dedfa72ea338da2a81e03b207bda413d2bbe38f9a4939f877bdfe2ed80261ea2293e4f9ad5fd8c5a94311d1564e18b58239de393750c5b2f7b579f47eb748a7c0635adc63a2396b4d1fda5071936eed5a3b3a3dbdd31eaf40ae09371ac7a910e056c0f84c1729cff8cc53f35aa68cbe97c4649e8d7c52381b3e1b5899c08bf758556149fb37bff2db4056741188036ae4e64190b843d213a090db1f0a338d0e9ace2b6b9caac158a6ba27092ff0ca082dc64aeaf748f2ae35597d184e7b5c03dcd2da11aff5ffe98f5075cc355d1214314ed256c637b762c54d038ca3f4a85d583f4bb68ea705a40481c35a0ae4de8c8ea7c417f2d1e1a101d6aec6aac87aef3dd4ace3a86a2b205ab9e98a9cf579f61c6a683820aa3c8b8eaa492800398f196e40300cc1e155d8e81344a07af407438a71c30bf4b936037312829020f4648899c9eff03f37d48373d462ce419e9dfe638437ea0e6871c4a78a93388000a759468eb8ad25bd60fa8363efe0ba826349598228402a286a1d7f95122b23cc051d325a539b5179afe1c0b049060d072ddc1635c4228ba13d768e704aadb5692e0eec1ffed5a9ea4ffbf45725b924afe2362bbf592d7b8ffcccb558374471ebd69ab9712c366b8f503e4aaf6ab9cb7c4124fa5767757f6b66bbbda7457e2bd35bc8927167e5520d81ff05d89e15891d6e8cf8b91cc8af0c02e2c82c93095504f61e8cb0e62dcde96c3ee0558921946cf7d20c9485e93269e9c44c6a6a8c5a266f1fe1610ae24a73897e05e69cfc1fef396e38d66119115dc6dd6d965eb053a5b6d7dbe8ae40b99f853ccdb7f569bf9b18d394abf2496bddd77801d4a9530c871c24b2b7a3ae4d335c7be3522aeeb7bb4ace52b7d213ccb086eb031aad103020413fb21b44dfabae7e1d95845dff10cd434c357b3b9f6f2a6c4e5c9c0f8d8490f31fe1faaa2f860c7f54453923e57d80ec26ebcacb3e79375ae7b0900f1f1eefe7bb491d079a0b561bb4a280ac1bc3daae702b2ca9e9cf7ff2804f5b98861d900f047d415e8911cd177cd691dfd079f6a439b4dfd407d3b3d78a33aa818f8948815c14e311d0fb6f32006863bd2a538177d1d9d9283ba7ec43932534900ab745cd54a6a115ee2786bfe1c3f8bb085f30c58cefceccb95f5d3388151df1af838e6711739d1a0d543b42e6d7948a5d8ce55fefd5ebe5d616cfa6d386c611f781b12d04eba65a3a57780b851daee6f038fe393d8bbdcd2d0bb706881d82ac55d0faa22e0c8756c676048f48fa8de39a2e8a5f1581ecc03045a3c90e1f5584a2db606c7d2ee0b724f7a84b0b21202b68729f4850da6723454536d43afce781198049f3dbbec600dbafa18fcbed25aef8095349595fe9ebdf75d951353b8cc6898a5bd4e7c0595920d9cdd1db426c694c119539a987888eaa9ca0767a3719eb967547636a24d1d8b0ae7006466b8b968476d7dd70fe5fd5c678bf37eff54da49f135db340448960d64bf097bc120660a27ca8d0f1fe28e9758ae7b171427a19bda0133a176c8d75b82b6b33f03a68013233ef124b8c56ac181f09563c5e07d445b383ddf275f3390ed27903bb1b58bee5d53b7fe871b8480e024caa1a2693681a8192ae992ba2578177dd9a9153d42d6fd1c952c840711d46e96ce4f0ec089d460347cef11cbee0eaabbeee8454552d404a3acf2d99c763ad9c000a4aa7e31cd61061741561ffd60b79c4a1881abe794db591de66837092ff93d4aa49deb083cdbd2b70de2edeb99b4f0b52dab10e5b5eab3e5bd12a8c1b042614266aa1bfe8511e7769a20510ed5e393144a9b72c0ec93a95f35d4f38a50253f3e244044ed24f69b149b5e7d887a5c2ca6c80e60aaef2667a63d49601e73ab9c5e2e09ca29aaf666719ff3b5ba32299749445e8e3f9563af2b95578f1995cf2814707e42640cd65f87518f1007aedc202cd401ba51efb0b1256ef43bdfc63d1bc46481c85ca1f1d938b5e0c802859efde08f3dfd27bee7d0f004b4abfd019165422f4b7fccd7ca4952850ca5c6c6079b8bed3bfc876923bb5e19dce7e672721486f496187d2928336c5f7ab6b4a32d7eb196b05795d55c8665645e9673c6f2a792a6f319cee59bf152a1482feb2ef325128bc8c22be9f47feb6693ff51c278a19d8256dfaa3b14ad4e299e8cda06bb9aa103a77c6062debaa42fab40d7b602343e74949d1f35c9fdfa0af0c86fcfc740e385e08bb30d37ad8d4d818bf4588fb0ef3cccf2133f7cd6501848f69e833d3988b9d627f693cb9ad4724427afa9efffd249fad1473074366e3e777ea67655264e1e3502b41ac628e0a6cc7577886b061643f2c61540497e04c81ec6db1bb33dfa53574b2e4a10c968b8d2d13dbe374159a189056ca052bd0cb8f95dac9aad2dc90b43831ea973b14fb642c4772005940fa5e41136660b588526684d7a62bfefb6d1549b5bedf3b262d5c27a85cd52f79c51e668c80a18ca543e4963a2970b7ddddd3297cabf1d51ed24fc3c55ee5c83dac281cfcef06a4e24fee98f0a84ed7ddbfaaccf2b2e7ef3abc0abd21fa2f0f24a494dd70d4b4ce685b31ca337393943a8db71011901d1061f08c56a672201b7726b158dca828ac9217629c66fac9adec98851412421d22caeadc7483c407566fcee45044e7aea3639fd0534c9d242d129dc4b0f1aa056f597bd3972852815d10bcdcd4149caf4eb8e29d61fda97a137b81d2d2800fd9a9cbcb2ab8d6351faf7d67e6385f98be98ea1f97fad8ba928338ccf0b249354991947b47b00196e51d6af3ec3d49b21e4b053147284e391d5beefcc92544752cff02fe03f5bf9276ed6b313d210aa55bfee3b2f72aed7eaaf03c7cb471b5f67d7fe13b8679e418807c8e82559489f3121268febe301b1361b929f8c3805e1f5909133ec381fecfc225ceb1c46ef9f2ab271900999a5ad596c79ce7f43e7d0ba82a177134c7b2e37c58e0fdc20a60055a4d0223320ffbed994cb26698722f8299f5600d069bab541819636ab6112a395152565b5e636e78858da6acb0b5b6cd373e45485b96a0b7bae1e8fc2d56658d98a1afb6b7b8d7dde8e9424c768a8e8fabc1d2e0e4f00000000000000000000000000000000000000000000000131f2d39"); + byte[] seed = Hex.decode("7c9935a0b07694aa0c6d10e4db6b1add2fd81a25ccb148032dcd739936737f2d"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); + SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); + + kpg.initialize(MLDSAParameterSpec.ml_dsa_44, katRandom); + + KeyPair kp = kpg.generateKeyPair(); + + SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()); + + ASN1BitString pubSeq = pubInfo.getPublicKeyData(); + + assertTrue(Arrays.areEqual(pubSeq.getOctets(), pubK)); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); + ASN1OctetString seq = privInfo.getPrivateKey(); + + assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(ASN1Sequence.getInstance(seq.getOctets()).getObjectAt(0)).getOctets(), seed)); + + Signature sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initSign(kp.getPrivate()); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + byte[] genS = sig.sign(); + + assertTrue(Hex.toHexString(genS), Arrays.areEqual(s, genS)); + + sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + // check randomisation + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + genS = sig.sign(); + + AlgorithmParameters sp = sig.getParameters(); + + ContextParameterSpec sspec = sp.getParameterSpec(ContextParameterSpec.class); + + assertTrue(Arrays.areEqual(Strings.toByteArray("Hello, world!"), sspec.getContext())); + + assertFalse(Arrays.areEqual(s, genS)); + + sig = Signature.getInstance("ML-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(genS)); + + AlgorithmParameters vp = sig.getParameters(); + + ContextParameterSpec vspec = vp.getParameterSpec(ContextParameterSpec.class); + + assertTrue(Arrays.areEqual(Strings.toByteArray("Hello, world!"), vspec.getContext())); + } + +// public void testHashMLDSAKATSig() +// throws Exception +// { +// byte[] pubK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139fdd6a6ce5bc76e94faa9e9250abd4cee02cf1ee46a8e99ce12d7395781fa7519021273da3365519724efbe279add6c35f92c9d42b032832f1bf29ebbecd3ec87a3af3da33c611f7f35fa35acab174024f118979e23bf2fe069269a2ec45fbc1b9c1fb0e1f05486a6a833eb48adc2960641d9af6eb8b7381b1ec55d889f26b084ddfa1c9ed9b962d342694cede83825309d9db6bd6ba7582132534861e44a04388a694242411761d34e7c085d282b723c65948a2ac764d9702bd8ed7fe9931d7d8704a39e6508844f3f84843c305594fe6e5404e08f18ed039ac6563cbaa34b0ca38320299d6256ec0f78d421f088159d49dc439cbc539a55884a3eb4efc9cf190b42f713441cb97004245d41437a39b7b77fc602fbbfd619a42363714b265173cae68fd8a1b3ca2bd30ae60c53e5604577a4a3b1f1506e697c37432dbd883553aac8d382a3d250cf5b29e4d1be2cbcd531ff0e07e89c1f7dbc8d4529aeebe55b5ce4d0214bfdec69e080bd3ef36cca6a54933f1ef2f37867c0d38fd5865b87929115808c7e2595458e993bacc6c5a3b9f5025001e9b41447708bfbaa0462efa63876c42f769908b432f5485508a393224960551d77eadfaf4411cbc49fdff46f2f155ddd6ec30867905b709888ca0f30f935fb8d7f4803cfc7a5f7790ca181d99ca21f2621d69a5c6d49c76b4969da62740a378470332b30947ab31ccdb9ba0c7b625879eec4bd81f0200ba23504a7dc3b118bc2ab1145df13af3c8cc39f577873b84911b3d85fbbf4cb19e4d36b10a938eeb78b599dc86615fd6cec6eb7b8f7afa5f6d6be19ea81630d36ccfb2f487de50d0cf46da8d3fe3512812043c0e3ef2d7231fb0b0a35a0fb283be30a1247780f30ae0294e8b6f5897383edb895595f577524df54593cdf927b4967616ee3913e4d6b29b0dbd7c33a2a45e4ef1b1954ea5d91ce37efc1302e7ce02a97395565da2a5c5d3fdb0d87684e9b1c0ad07ec33df2dfad528e2ea0966d2a47dd5ee88e77d653c0d004fab0165f0757c4da40af327e7192536c79947a80a827aa2107dacfae3debfc8fad3d6e08076d938c510a276bdf6721a1f087cb169515028ad5ce27a1047abd92809934ca63b893f71f9a34a99c0fd30310c47e9aa37394d0ab73b254d3ca69d9c5549c9479aae24264ac5ea64d3fd821c3962ec77e709f9d30bc7b65a52e48c16e80603558caca1811411c3155d1f949fc9cf9aa9385a7199e99be77a66fad7eed91258de55b2c4c83f9a050adebea5f09758f40dac4a1c394ee8d687879150d26426895ab1938e14ae11b376254c91fc6130436996f8ed43bd27be20ec9067111c116ec94cc2b06cc91a13c5d10bbd7eecea4792f17b2b77631ef145e9fb41a83eaa11c2b72a48fb90fdbd88644c4edf8ab20dce3118364b276ac1237b36c8926e346aab5a111aa0bf341c518b7bff9e9dbb8bcb4728601b3760663e67650331e6fb54ac82fc414cb8ddfc160a25311ec5272de46217fef8b992ff89754fbee351f21bb90b6c97078b510c983350681266c8fed1f0583c5151e7b8fe3b7292319699687cc6b641fdbd689428543bc0fa1facc109de65b62784c2d985ab15d77d3af12af6d03e8d1859a553688584d75ef673a1de74093ee108c761fff32c217c231b0e2953daf521429264c0963bc8a5cdeddc617a7285b934ea51ddb5cdab23bcede86be36e001bc65c65e9a1c94baff4fab8eb5f8ed42ec377423633fe00049142467c47c5d58a7202c8e9104841c1f7f380145a6a0a828c570235e507ae5868a6062f722bb98ff6be"); +// byte[] privK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139ff037b84e75537e0a1cf02a517acfe323ffffe11df72e4f38430e0e66a2654b2f2ef757da47649d9f63fa03f1bf6fe6bc7c62971a98a2bd9d36eb0ec43ad4e9d940df3bb5874f5c92192aa31e0535d3cf70950bba858d11a688eaf854f63ecfc520c50d624891434265d8b0680c03061040299a104082c0910c8508d1100d44a6509408292211125b90508a2688e1302dc4021280028ac302611820851237808a000ae2040421b4910bb80550a08051b2511c28428a3672a494504910201bb45161424424a75001328181942d62a850023449ca94200b296213156408924c48122100b605030208e0060200a311e1802021116483a62898029291480801083041066613200e5b360951400c53000aa08851944842e316704ab2089b92440025121b0309418209c2a0800b290a819851c4340da4424500a0105b048e603400138928a4422648002c90202d194068e2146d19278a083746e4146914006422c660d3a03013242844965014166da0284dcc462e94367100232e1c114909a2040131060a2172c2142ada000c5a260d13228a62c444e3142d013445980224d33841c0308121a621e348720b1984d2c89108b8690887714a2884d496451a9301ca2285da30859ac851dcc00820106060465262302aa224251044640b2842988011540692144251d236719bb4900b082890188e41c469e1a469032160e01409d3020c20c88c1cb23164086218476920228ccb8470089528029550533270013405888424541041d202881aa84ccac88181008d0392899ab809d9900c9a1290614065c9322d89860c123521cc4266c8360010062411028ea3b44d44023043a0285a002ed1980c4882658922441c010212907084226e12134d011902519064113364c91806c2c04589262908b63024308cda022e0c27250b367058162c5116420b4946c1208841246c99466a04434e18a86c821661922028639409c30211029520211782d43868003460c84688e0160000a32dc0a82824b640831464c81022a2086503234ac8122ea098418c2072cc308a62c665093408412682da429089328514967081226001176d5948428ab88d592051d80892e2c0889044700ac0245a020904218a59c45094441094140820460209270c441020dcc8209212015038250c456e4a1666223770dc808ca426412222441ba3618a343099844099c42952046d88146ccb242a7cd129a8d333115c62d033b6a8357cf7cd10268ab12f16fceb7975d0a28a6c4822213c9a772df084ad91a669e2040550fc5e8d0aeb10fab2375fc9625ef9cd48c19631997a1cb6455d2c6286c569c9637add0317ce990996b28e51c3f3f717fb5907bbdd53961ad3497f2c3c473cce170906ac4c624a89aa8fbe624d99385e9c9548bf05e8cafd47d2476e41b73001f813726499e88b2b3b6f596ca311657850346598994c40e34747161e4e76264deef2a3019389d1594c942301af47b7544c23ecda2df2dece81e487d8f3f58ea89cd811d7275807ff1b0369ba86470088c174a3099fdafbe5fbb4d158801053b2b435d54059e26dee76d10a7a372f06b0b88b985b32f52052387438be8dc8bc6ae7369e2da9aa5e2585f8de403d091ccb7f790d54ddb34c608b0876f2825e9113be20a2b85867a01bda53287ac780bcd8b606d2e6d7712c56ce0142d22fe6b786de544963e134fecedfafb83d763061d799096a59e30d4472e440ae1faaabdf42640ce69740ceb9cae1a9612c21931b74af3f780236123321b205b6efd6cbb134f4c73d63c0c13e660b59d5920bc33197c355853d8d1cddc7959f7bc500ac81d985016f5b89a0eec79b0d9364ead8e38577c2a6549f2d067cb09438fdb21220aec80f6e22a476f332a2a4a0b7acbeb9e078d2b5a92ae84c924f7cb19fc7df377beb6546af97aa985c747cd111a127a674b4c26d89c14485b82e3a498a12d05406febd6c4d4b8bc051ab2cb91224b078538374b794b7dd9ddf3ac2b4a671fb7b9cf5acb78622ae2709eb2db16943aa24a9c97a81077bc784d25c0ea5991d2de883798a1f0e78f3361ed6a10dded81b1d683658331534fd7c01bc0eb00dfc4c3c84f0693046ff806bb200dd7bd4c0e6abca3f2934b4814fc0e1f8be615a2dda7c8a8d06cf9ce8566b40f4a6543b25bacddc926863fc0fa2007d6d7bf6d18dc98df696bd0865bf0be4c492b8043a32def8e3595ba7da345252f38f95be10fd7fb899b498fa01b09de5d5608eabc44a721aa04c4ef1dcb86102ac5f5f79c9708dcf5c5e896edd8c2c7bde3fa83e6ffce22d66174e31657a0b6361585e669d3031952f08631ae1f16ff90b90d0aad3c6d7e1dd0a9c41ab00a6e1c4f96af9ac5b79fcf821ffc016cb059245fb78dbe6c633d965aaab5333be07195c4b74b18e4600ce783c0a914ef4281016e80a7c9aa92d0fd789879c5e6751125ecb154432311e41cebd4fab3a31e4d2ce22d0f8c67737bf8a0dd85fe1349d5079a4d5feb3fee9378ca47ae46cc58a3f02038cfd53c4cee9cc4270cebc3d115a39c831e8ed41c4dbe4051b51d7872ba0c2bb163e0085201188eaa624a6bea9400a3a1fcc355a57f15704e61fda55a5dbaea8448fa5cb2d377a07f58305ad107e844ab4806e5bf99c1f513ee1d0a2acc04549f0801742169a77971d0adbfbfe0dd2ee5d16bc461e35748d1f3f6f4598321e8c49e79e740f990359858d2729dde007fcb26fdda9aa6e2ec4bd736f2836e7e4c83440191c849f6a53c72a4f8f830d001ea3b18f3cb4a5bd3cf066032b4932cfd2e62a9b55723fa61c688c935518af6860cd649bfbf1bf5fdc1f36dcaefaa157438d1cc8d56a150161511df82631f5e88e773e4ce263f276b7b3678d4c6fc75311d411c0d01bfdb595bb70552838e1b86517c837d909e772b428599e1fe569f77ce61531fde6fd31cdce1bdee4ba467fcbfbb9feeaad99fef67d4906e036c73662ddce158d4e5d4635e5d366f79f31a19d1b3dc4a591b0df194bb06c18147f41d88d1a409becdfb67eb063d16312266fd51b521ba9115e2e5e2aeae6ec511cede13ed4132ffbe0273f6c7039b3874f058804a54809af60557a21d9b4b831d04156a7c22dcbcdfe14f62437f449cb5ef12bf4251d485496cd835c0c2bc58bd845963dfa76ecd68519c4bdaf110be7ab052876dc3407591568c956ea3bf107c90fd5853a292f59a8d4b58b5d3fddf29bdbeac36852e3c69766fe460176a801831292b8e88a74a01ecbbe09a7b4d74cfd7fd628841944d9d556dbd60c76f96f07dc53443805ee9aa09365de4fb8179252c6b099b5dd351fdefc23dbd8090596c5d208ffd2c5661d8e5612dd574fc69045c769a969e600d77cfe192f1d3ae911289355c585811491b0ccd73692ab158824ab9edf8ac8193f0b33e6138b72c6dcd5d344f807b3da92425037de5ea4eead1c795effaa145e2ecdd327606eb2609929b9474b2bb04653602555c068385e92f06f29ca613ce5b4404f01ab1805db0acaa890330d291f40692df382509302b6dc8668f2c8f2d3a44fd58dca26e9802794f73d25b3149e6d576441"); +// byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); +// byte[] s = Hex.decode("eea01acc8fe6631c9260996def0c75d84998cf4512c7b67bc4246bbfbff165a404d02bca30da1c2b61d91d7986a467fd4b3a1131077ac138b4011ef07fc1f3ca6237e7fc6550c7e071c939f4554f265362eb26158ee1a2e57c72d20beb78168d9e2d7faf54763755a44bdc29e575884133062453a9e3e761a13a82143d7db7215ab0b8628c096e0f298491a8d67517ab8a90be7db5d311eddc7e883d50eb873decd9b3e420155008c0a3632d51f93a9c67ea336273c8f26617c7cfa2a3aa6d9aa075e75fc60fb587fb5522cb6bac4ef1979a069a15aed3171660ce5da2c27af188e9d3bc62eebdbd798f1a650c7d46411e3cabeb27be3ae787b5f4d82a2e2cf4eee84b4fc82edea4533a47bf7d3791933d1c5ce19c1792a6420c9dcd540dc3a494d9b518ce5f4f85d7747c2fa45d812d16f089682c57a96061210c942dbaca8dbde509f56f498d68f0b4e6f4a51373c9f5a5db2e20ec8254ea9d59f69d732fd1b1149fbd0b608368086a3b6acbe5de156fc508390ddc9ca28d201fdc67140a767b2d99d08051255e73d423750e91b1aa31982cc7014e46c75b69ec972f15745bafbe4878f73d8800d80ad22716f15f4d964f0468e8583add1a4ba8f544e9b83dd6c5ebf744436e254bd699e8909e712d9f6e69fbda39be69a4e0bb58cdd0ddbd369cf5a6475b1ad5fe2849c439611516bd13de14b34b26a731c5a5bde4fae538782a6daeb6fbdaf4cf1af40f3b9c7896e87ac71b3fc95eea02f2f28bf62b9d613998ad973added64515a699fc89304b8fe4d4c97759662b720835c2b28585648e54dedfbfa40fd1455e8a945a390765e3b1a2588286bd4f2995eca39ce9eca6d2e32d92e18c930e4b99109f148db96f1763703aeb431c3c815d577c2b0282181932bb182325bf45e1355d91c8ec669ccd94429dc4ea0abc562988bd2b27b39f2dd0e4ace6fc9148cd064005e9cf0f8105a6534261942774c2a02f150f8d250822745b1cc40e1d57c68dea152c0f5088712266e5a37eb7760204c2747561688990d3cf7c76660e5671727c7ebde56420c91549a48b3763062ff92a4679e7d3e8569303eeff650c0ae606234d70a350aa9862b912825b13c1ec7bd6bf346717b0f30c45c1925873f04d469fd28f82f19375531ffb83851c471ebf623c86130d929e739bd8721d97ca9a83676f26c0a75493b5b02f0921aea91baae2da96532ab9db04dc997d5f800f58a891f6ef26e5478de1ce9b4da04eccac4cee81de5c3b1010ef28242217ec737beb36815c4af1de9a4160180ea896120ce96869bf551bb6be079482f4ab5c0f7f234c50bb4139ff9fba1b594c85cc3780434fc00f7d0492cfc86c0d1889784b113650e3c29bb2e9ed6f94df5ea42afac8060856fb90fab5f4c6fb6875fd67e0438335bcd5199b72706cf358492e5f4945bf2a686aa2861908d6a71ba4e760c87e75a7ff31169993cf048817512aeac4e960771879be541b1adcd6c2da9f9d2153e728d4ee1e91acd7f704e0b472856cfd8f85e2f30b0f6e427f190dbc1079343fdc71f9ac0b8aa5e6fdfd60fe9c90e4bebd4a91dbf16378bcc2a330aeed5b7e8dd617fbf3c6ed9b2c2ac82f2e9d03c975b2a832a667864090da9ca91ad1af97278f6cfebeaf2cc681957f3d75d17a5710de85444b636cf7e0dbac06852fe669f87bc7c430ff548ee0b34f1a68e86f1b26290f8a056c0bccd18a540ce04ee7fdee47f5176b811021a89d170e71250a040e10f8f900236617c6be92217b77aa00854d6376739d5a63d32a377da20c368092367fc6afb62e0b898c01462a399aa3dba4beb0d03d7f8a2e84b499a41e7a6e50cd5e09b4d6d8cb3e8ee3a2d1b50775f9caf7335f1ea15b2312352831418ce2529542011a19c6ece5c1e6dfe7e37821933594ca6f55ca6c799b32f88b21d59744c10538ea7208eb61a04d24476c326068ac9ad4199080e02b95766f6a18738c7e4506d18e9c5c526ef4f28ef14662667dc865ffd446026cefca1b39be77cdfd7773aac0bf570647c21979b9f0ff0d67f2a9940e1e1c27e9e3296c7d890c5627e9126fa09bed1f242aa23112d828529ce431939c9ecc0d4311742a1fa5f9f283eb0135093d3e6aa9e89d4641415678f0b2ecb1210a611d062c5e17f01521aa45d778e2a0770cfda540ce1b5bbb3fabfc783601480b080f4e7275e69705b6cff043a3b503da77fbdc05702b790b1cf4dccfb6b2df00bf0ee896420175e1293a6b8fbc96cf9759a6c0e56067dc9e2522621af2cf830e2bb648f0ca3560bdf9c2c0c01bb23806455bc40889472398f9daf71f0ab9e1aab2fe8d6c8c504a1a45d99229828a9588a559a7172b041b2bbcdbe2e59b749b3e1219abf51a39164c9fac17bd8c83eab1e0e04e029550b689134194d486083b956706a6706274324d63ff79c35f37cf8c2932910e60e1da7cc6c4d9b966fb11437f7d4e94221e4b9ce51ea04325e4b75e45dbbbaadeeadd432e776c9b14cff55529c24b43211b52d1f27de0d86c0f253ec3c2262fdfb1ecb18442174321bbed4c1454522d747be4f53f9ea445d4db360c5c0ddbac51179c7f6016249bcadcce47d4abaf0604047d806f556d11aba411239a32a80d4403c72198036917b6c3b9c5fefcbb73b4d11cea0cc09b419ab8bb0a093131b4c32280fac586bee305e14a18432bbaf1ad6ffc67863edd564df4f9518c6363b80d83c59440bde98c2eeed939bfa1d8f720a805088e2090ab1af71ad5190978b2e23a7d58fc28ab2ed623f2cc65d67629a2fbbe84309a3e0447f3805728155cca522217f9e66b5b2d794fec7131b091f7f77df37e8d726f150d416018941a7b48617fe291a3a3594df80bb1927d87d8f8d5cb945c39c977e7a4f9882e3facd6f26e42390a1f7d14e55797bd22ae78ac11208084be07399d2f9cd2fa331784c5e65de766d87c3d19aad2c7993485e65f11b2c03533f265d9268f8d7f9ce14f97a76891e2b764d2e0a7baf2f81c6fcfd15c78552bba4952fe375c9872a25fddfa19a29695320858fa8a910c29d0739edff01da6d80f757906f7103984c4910c44220ce83fb5b46527c918d186b5c096ea4d1c85df71b4e7d625bb2df5a898880a18238eb4388f66f0d5daf074bdfc6e3b4695ef5faaf754ed764b80463d724d1fc41b598861207d1971cfe1e857cf2bf8dcc4afae1e44c622d96194d3f85fa5a37aed9a154074fbc54d50724658678dfba30bce2fc853bf87f7379d80865f08f0a772afedd8f45808b49605ff3d2875a6ce7b90f4a61fc55734f791bf2e6ed554309111a385158627d7e828491a2b7c6d1f00315162c42435b62656f89bbbcbfe1e6e8f0f7f9000711123b5b6ea7b0b7b8c9d2e5e9f5fc09727a9b9e9fb3d3d6e9ebf4000000000000000000000000000011253642"); +// byte[] seed = Hex.decode("7c9935a0b07694aa0c6d10e4db6b1add2fd81a25ccb148032dcd739936737f2d"); +// +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("HASH-ML-DSA", "BC"); +// SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); +// +// kpg.initialize(MLDSAParameterSpec.ml_dsa_44, katRandom); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()); +// +// ASN1BitString pubSeq = pubInfo.getPublicKeyData(); +// +// assertTrue(Arrays.areEqual(pubSeq.getOctets(), pubK)); +// +// PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); +// ASN1OctetString seq = privInfo.getPrivateKey(); +// +// assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(ASN1Sequence.getInstance(seq.getOctets()).getObjectAt(0)).getOctets(), seed)); +// +// Signature sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initSign(kp.getPrivate()); +// +// sig.update(msg, 0, msg.length); +// +// byte[] genS = sig.sign(); +// +// assertTrue(Arrays.areEqual(s, genS)); +// +// sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initVerify(kp.getPublic()); +// +// sig.update(msg, 0, msg.length); +// +// assertTrue(sig.verify(s)); +// +// // check randomisation +// +// sig.initSign(kp.getPrivate(), new SecureRandom()); +// +// sig.update(msg, 0, msg.length); +// +// genS = sig.sign(); +// +// assertFalse(Arrays.areEqual(s, genS)); +// +// sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initVerify(kp.getPublic()); +// +// sig.update(msg, 0, msg.length); +// +// assertTrue(sig.verify(genS)); +// +// AlgorithmParameters algP = sig.getParameters(); +// +// assertTrue(null == algP); +// +// // test using ml-dsa-44 for the key, should be the same. +// +// kpg = KeyPairGenerator.getInstance("ML-DSA", "BC"); +// katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); +// +// kpg.initialize(MLDSAParameterSpec.ml_dsa_44_with_sha512, katRandom); +// +// kp = kpg.generateKeyPair(); +// +// sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initSign(kp.getPrivate()); +// +// sig.update(msg, 0, msg.length); +// +// genS = sig.sign(); +// +// assertTrue(Arrays.areEqual(s, genS)); +// +// sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initVerify(kp.getPublic()); +// +// sig.update(msg, 0, msg.length); +// +// assertTrue(sig.verify(s)); +// } + +// public void testHashMLDSAKATSigWithContext() +// throws Exception +// { +// byte[] pubK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139fdd6a6ce5bc76e94faa9e9250abd4cee02cf1ee46a8e99ce12d7395781fa7519021273da3365519724efbe279add6c35f92c9d42b032832f1bf29ebbecd3ec87a3af3da33c611f7f35fa35acab174024f118979e23bf2fe069269a2ec45fbc1b9c1fb0e1f05486a6a833eb48adc2960641d9af6eb8b7381b1ec55d889f26b084ddfa1c9ed9b962d342694cede83825309d9db6bd6ba7582132534861e44a04388a694242411761d34e7c085d282b723c65948a2ac764d9702bd8ed7fe9931d7d8704a39e6508844f3f84843c305594fe6e5404e08f18ed039ac6563cbaa34b0ca38320299d6256ec0f78d421f088159d49dc439cbc539a55884a3eb4efc9cf190b42f713441cb97004245d41437a39b7b77fc602fbbfd619a42363714b265173cae68fd8a1b3ca2bd30ae60c53e5604577a4a3b1f1506e697c37432dbd883553aac8d382a3d250cf5b29e4d1be2cbcd531ff0e07e89c1f7dbc8d4529aeebe55b5ce4d0214bfdec69e080bd3ef36cca6a54933f1ef2f37867c0d38fd5865b87929115808c7e2595458e993bacc6c5a3b9f5025001e9b41447708bfbaa0462efa63876c42f769908b432f5485508a393224960551d77eadfaf4411cbc49fdff46f2f155ddd6ec30867905b709888ca0f30f935fb8d7f4803cfc7a5f7790ca181d99ca21f2621d69a5c6d49c76b4969da62740a378470332b30947ab31ccdb9ba0c7b625879eec4bd81f0200ba23504a7dc3b118bc2ab1145df13af3c8cc39f577873b84911b3d85fbbf4cb19e4d36b10a938eeb78b599dc86615fd6cec6eb7b8f7afa5f6d6be19ea81630d36ccfb2f487de50d0cf46da8d3fe3512812043c0e3ef2d7231fb0b0a35a0fb283be30a1247780f30ae0294e8b6f5897383edb895595f577524df54593cdf927b4967616ee3913e4d6b29b0dbd7c33a2a45e4ef1b1954ea5d91ce37efc1302e7ce02a97395565da2a5c5d3fdb0d87684e9b1c0ad07ec33df2dfad528e2ea0966d2a47dd5ee88e77d653c0d004fab0165f0757c4da40af327e7192536c79947a80a827aa2107dacfae3debfc8fad3d6e08076d938c510a276bdf6721a1f087cb169515028ad5ce27a1047abd92809934ca63b893f71f9a34a99c0fd30310c47e9aa37394d0ab73b254d3ca69d9c5549c9479aae24264ac5ea64d3fd821c3962ec77e709f9d30bc7b65a52e48c16e80603558caca1811411c3155d1f949fc9cf9aa9385a7199e99be77a66fad7eed91258de55b2c4c83f9a050adebea5f09758f40dac4a1c394ee8d687879150d26426895ab1938e14ae11b376254c91fc6130436996f8ed43bd27be20ec9067111c116ec94cc2b06cc91a13c5d10bbd7eecea4792f17b2b77631ef145e9fb41a83eaa11c2b72a48fb90fdbd88644c4edf8ab20dce3118364b276ac1237b36c8926e346aab5a111aa0bf341c518b7bff9e9dbb8bcb4728601b3760663e67650331e6fb54ac82fc414cb8ddfc160a25311ec5272de46217fef8b992ff89754fbee351f21bb90b6c97078b510c983350681266c8fed1f0583c5151e7b8fe3b7292319699687cc6b641fdbd689428543bc0fa1facc109de65b62784c2d985ab15d77d3af12af6d03e8d1859a553688584d75ef673a1de74093ee108c761fff32c217c231b0e2953daf521429264c0963bc8a5cdeddc617a7285b934ea51ddb5cdab23bcede86be36e001bc65c65e9a1c94baff4fab8eb5f8ed42ec377423633fe00049142467c47c5d58a7202c8e9104841c1f7f380145a6a0a828c570235e507ae5868a6062f722bb98ff6be"); +// byte[] privK = Hex.decode("dc7bc9a2e0b6dc66823ae4fbde971c0cfc46f9d96bbfbeebb3470ae0a5a0139ff037b84e75537e0a1cf02a517acfe323ffffe11df72e4f38430e0e66a2654b2f2ef757da47649d9f63fa03f1bf6fe6bc7c62971a98a2bd9d36eb0ec43ad4e9d940df3bb5874f5c92192aa31e0535d3cf70950bba858d11a688eaf854f63ecfc520c50d624891434265d8b0680c03061040299a104082c0910c8508d1100d44a6509408292211125b90508a2688e1302dc4021280028ac302611820851237808a000ae2040421b4910bb80550a08051b2511c28428a3672a494504910201bb45161424424a75001328181942d62a850023449ca94200b296213156408924c48122100b605030208e0060200a311e1802021116483a62898029291480801083041066613200e5b360951400c53000aa08851944842e316704ab2089b92440025121b0309418209c2a0800b290a819851c4340da4424500a0105b048e603400138928a4422648002c90202d194068e2146d19278a083746e4146914006422c660d3a03013242844965014166da0284dcc462e94367100232e1c114909a2040131060a2172c2142ada000c5a260d13228a62c444e3142d013445980224d33841c0308121a621e348720b1984d2c89108b8690887714a2884d496451a9301ca2285da30859ac851dcc00820106060465262302aa224251044640b2842988011540692144251d236719bb4900b082890188e41c469e1a469032160e01409d3020c20c88c1cb23164086218476920228ccb8470089528029550533270013405888424541041d202881aa84ccac88181008d0392899ab809d9900c9a1290614065c9322d89860c123521cc4266c8360010062411028ea3b44d44023043a0285a002ed1980c4882658922441c010212907084226e12134d011902519064113364c91806c2c04589262908b63024308cda022e0c27250b367058162c5116420b4946c1208841246c99466a04434e18a86c821661922028639409c30211029520211782d43868003460c84688e0160000a32dc0a82824b640831464c81022a2086503234ac8122ea098418c2072cc308a62c665093408412682da429089328514967081226001176d5948428ab88d592051d80892e2c0889044700ac0245a020904218a59c45094441094140820460209270c441020dcc8209212015038250c456e4a1666223770dc808ca426412222441ba3618a343099844099c42952046d88146ccb242a7cd129a8d333115c62d033b6a8357cf7cd10268ab12f16fceb7975d0a28a6c4822213c9a772df084ad91a669e2040550fc5e8d0aeb10fab2375fc9625ef9cd48c19631997a1cb6455d2c6286c569c9637add0317ce990996b28e51c3f3f717fb5907bbdd53961ad3497f2c3c473cce170906ac4c624a89aa8fbe624d99385e9c9548bf05e8cafd47d2476e41b73001f813726499e88b2b3b6f596ca311657850346598994c40e34747161e4e76264deef2a3019389d1594c942301af47b7544c23ecda2df2dece81e487d8f3f58ea89cd811d7275807ff1b0369ba86470088c174a3099fdafbe5fbb4d158801053b2b435d54059e26dee76d10a7a372f06b0b88b985b32f52052387438be8dc8bc6ae7369e2da9aa5e2585f8de403d091ccb7f790d54ddb34c608b0876f2825e9113be20a2b85867a01bda53287ac780bcd8b606d2e6d7712c56ce0142d22fe6b786de544963e134fecedfafb83d763061d799096a59e30d4472e440ae1faaabdf42640ce69740ceb9cae1a9612c21931b74af3f780236123321b205b6efd6cbb134f4c73d63c0c13e660b59d5920bc33197c355853d8d1cddc7959f7bc500ac81d985016f5b89a0eec79b0d9364ead8e38577c2a6549f2d067cb09438fdb21220aec80f6e22a476f332a2a4a0b7acbeb9e078d2b5a92ae84c924f7cb19fc7df377beb6546af97aa985c747cd111a127a674b4c26d89c14485b82e3a498a12d05406febd6c4d4b8bc051ab2cb91224b078538374b794b7dd9ddf3ac2b4a671fb7b9cf5acb78622ae2709eb2db16943aa24a9c97a81077bc784d25c0ea5991d2de883798a1f0e78f3361ed6a10dded81b1d683658331534fd7c01bc0eb00dfc4c3c84f0693046ff806bb200dd7bd4c0e6abca3f2934b4814fc0e1f8be615a2dda7c8a8d06cf9ce8566b40f4a6543b25bacddc926863fc0fa2007d6d7bf6d18dc98df696bd0865bf0be4c492b8043a32def8e3595ba7da345252f38f95be10fd7fb899b498fa01b09de5d5608eabc44a721aa04c4ef1dcb86102ac5f5f79c9708dcf5c5e896edd8c2c7bde3fa83e6ffce22d66174e31657a0b6361585e669d3031952f08631ae1f16ff90b90d0aad3c6d7e1dd0a9c41ab00a6e1c4f96af9ac5b79fcf821ffc016cb059245fb78dbe6c633d965aaab5333be07195c4b74b18e4600ce783c0a914ef4281016e80a7c9aa92d0fd789879c5e6751125ecb154432311e41cebd4fab3a31e4d2ce22d0f8c67737bf8a0dd85fe1349d5079a4d5feb3fee9378ca47ae46cc58a3f02038cfd53c4cee9cc4270cebc3d115a39c831e8ed41c4dbe4051b51d7872ba0c2bb163e0085201188eaa624a6bea9400a3a1fcc355a57f15704e61fda55a5dbaea8448fa5cb2d377a07f58305ad107e844ab4806e5bf99c1f513ee1d0a2acc04549f0801742169a77971d0adbfbfe0dd2ee5d16bc461e35748d1f3f6f4598321e8c49e79e740f990359858d2729dde007fcb26fdda9aa6e2ec4bd736f2836e7e4c83440191c849f6a53c72a4f8f830d001ea3b18f3cb4a5bd3cf066032b4932cfd2e62a9b55723fa61c688c935518af6860cd649bfbf1bf5fdc1f36dcaefaa157438d1cc8d56a150161511df82631f5e88e773e4ce263f276b7b3678d4c6fc75311d411c0d01bfdb595bb70552838e1b86517c837d909e772b428599e1fe569f77ce61531fde6fd31cdce1bdee4ba467fcbfbb9feeaad99fef67d4906e036c73662ddce158d4e5d4635e5d366f79f31a19d1b3dc4a591b0df194bb06c18147f41d88d1a409becdfb67eb063d16312266fd51b521ba9115e2e5e2aeae6ec511cede13ed4132ffbe0273f6c7039b3874f058804a54809af60557a21d9b4b831d04156a7c22dcbcdfe14f62437f449cb5ef12bf4251d485496cd835c0c2bc58bd845963dfa76ecd68519c4bdaf110be7ab052876dc3407591568c956ea3bf107c90fd5853a292f59a8d4b58b5d3fddf29bdbeac36852e3c69766fe460176a801831292b8e88a74a01ecbbe09a7b4d74cfd7fd628841944d9d556dbd60c76f96f07dc53443805ee9aa09365de4fb8179252c6b099b5dd351fdefc23dbd8090596c5d208ffd2c5661d8e5612dd574fc69045c769a969e600d77cfe192f1d3ae911289355c585811491b0ccd73692ab158824ab9edf8ac8193f0b33e6138b72c6dcd5d344f807b3da92425037de5ea4eead1c795effaa145e2ecdd327606eb2609929b9474b2bb04653602555c068385e92f06f29ca613ce5b4404f01ab1805db0acaa890330d291f40692df382509302b6dc8668f2c8f2d3a44fd58dca26e9802794f73d25b3149e6d576441"); +// byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); +// byte[] s = Hex.decode("42a2ad149a7f35856ed92005232a2d33dc4a1ad0cb0fb7b772f56956082fb9a630fd7284bca55b5cef3a55ad73c2225d7c2d143d0023cd988890b81c271b97e6ed99250bd141550e4eb0276d4a59f19023d0bd725fe2c4f3301655ae91089851db6ecd24bc448ac06c1bbad4254bb1370678858586d55ffa4a9112dd48fd14c224d35d9c2987dc8bff84578d9a5fd0a1e34f7fb34523a305f623cef1766ac8b336c6c1a062f8d273e4f5636969c8c5afb3102436f9549a68ceb5393065944f0a231eb53ef7c6d3bca1fdf2544e3637f5efa96752455e4816d8747c5af14d3996eb241b2dc28fff9a9d93d148193195a87d6763dd94a5d9dfcd8623baf73ecebf545291bd236f44a3b9c5b8d231b7d7e991f6fbd67bbf3740611ef64c66765e25dc0e968900c407565097adf82f7b2387d03f93757a88c1a7590fdca09e19579ecc124629a26e80851b1ca5f29bff6ed37fc779bfc304e93169004b7c742ff4ab9ead2e96e313f1ddd8f6f94d58298ecd2393e119f5536d46e934ff11323f06df447685fbc1f8017a1a98ed717c8c7e4aa9be3b9f0c9f4e43c802c9542a26c013a07f5dcf2cfac584e8a998712cb6f00d4e51f9a3d65bac5197b49bd5291db44fbb90160a364818548b0bb59d34f48fbfc86b7f9d765a427074bee154dacce37f2bae727e99ec55bf7b5d618eebabc73cb015d18c6ba4c45a4c5f8c8802beceb9fd183989f4ccd3964a995a19a4a4492ca043c4be3ff76505d97174db15e15d56acf3e78147c0136373e784d627360e1ad41decdbb5a92cf271cba3a969f366ef53fa1150a1514b18b8c6835a44c9139456c162dfa59e525892e38ad6864097f5108752b4b8d3f847bdc0c185f6da216da8ee00c06ee8b54d66adfa85d2f8851ecbafea5d063604d6abf28a0df4042d788cc539cbfce523f1183dd7c955990ef9709d9db2d28a0ac55382b92b3869ae40072119278e005be9acd8b30507d55a065815db29fe5ad0ded3094d9e92762b1d52a7790e146d4b4b7e81389af5e1bff9485ba72ffebf902aa343e5ad737f57bee177ed8514f0549083407f6a645234be6ece678c59f905e3af7190602e4c1d8815a28e791d476c10ecfbcfc9539e995e72c8cad9f7b515a53e0c912be7071c13c2d350b1965627ec610e17bc52c13108dd3f2e2fd703edf13d76ee62d904f45d6f89b5814a6570ab5e041b14186c63bc0b93de643aa4828ae4747c964474102cfb77aed3412248c67a8fbd2971072058ddda17df2b152449c63b164dd1ca152c893e38afd042d9f186e677969dc3caa6d2105b54d7e8dc47bda7f63606e8670f3f671b0e43d1cf0884cdde011743a9748e50b66cebacfd4595c346a8229883fd92945e65fab2c9a1dad85d6ae11ed3dcd07dbe1bf031fce1c23f5d1fc61dd970b40dec577abd5b2bb697f6b24406ef7d623b45b0a96a79a8171805d599ea99fab55682eba390c0dbd7f53999ca7cd5e4e471139b5e877be6fdcab79ba7cc7693a07bf537f4e05669a977610d2f526e7ed6edf75164b09e6ed608ec755744571694218a36ad96362381fbfb967ec0e0180fb8efd4972c8614f82e262e0628a083f360ed927dc85b9b95d5c53eb371848f3ee1c7dd069918f74e7a1f25fc6f955e72be0202a401e28c7fc20c8378469b6bc370700b6fce04224a3f3815598f15f44ad95972208c215126753db78fa84fac87b62da8b1249360ff2171643cb100c07f8caffbd9aa4d94b0b192eb49af6c9d3b68357d708d597004a178c116efe72f5ec80d2269c592e65eb12b5968f3c153bb900ea3d49a91e155dc38383844bb849f8f78c9038d30ab7b6719830a7667a725f67b6318615b37f0d0a2dedf7e2f741d1807abd4614087449ce789ff10deee23befcac04de3376245143f24df1a1f95d7442439b2e6f983959598c95577e2d262e96f8fa4cc4a1fd59e2b4d9c4394071630c2e0569c4fa3784bfb0d39f42e366c8fee583412be0c6d4c67fff9d570926210fe632fa125245496af25cd084d723994c94e2ff659637784c31e9a555a788c8fc7410839ee1c6e80544d825b79fcf238afd1c0d6be0fa32ecb8b93463d98b9f2b3495c81f25877a613227bdaf8b94342da81c0f2995872a5a75341503bfaec2bb7f95db0f340f4732a832f4effab9bf4da476528a15fbfc5104fe3dae3a5fdd05ebc42989d96f1eb056c3ffc79de35d229a55e301c33975b92c4a7de50962a2fcb83912441189ac1a4e4ad38e30ecc3df084f0ecd8745750323debdea86ab87e725d41fd044fd507f279e7dfbb6a04b34cb150ed9fda95d7393cf8e611589ec56a5dc9a9de4dc80c36e7cbcfb77501bc69b93437ce3642ee35da9a0d71b76a641847fb9798e18b1d073a7b832958f65079648b47370bfc175869dfc412b0b3074fc43d608acd2b602f7b9d2fb831c3a37de56600a34135a1d029bb5f582732b2dc45f992c4a6dcc2c3b1cad807ad4e741490b5cad74a6e7a416fe91b1ad216c428558c3f8d0797d4acca85ca864a5194cf1273622ffeed9624f702b4725a93057a90d155ee081183d87517123647fbd31216b664107a124adef5e1dbedb7e714f6b49696fa21a4a3c2c822cc675b2a171949cd64d10fa188913a9e3318dc9829aa3e6bdeac781afd2b20211c6aeda61deedc8ef7d1426f7cf464af6a700bfce3e0df99f417b1440807870ca0af461cec38cde60e6861f817901a56db98af64e9be3648585513f833a3e5c6fedc613dfff720e76a0800139d53957b1f91e7efcd0e6308613740705e589d48934f5e9a193af901b3335e767310830ebc6662ef8d33e7c87e242b65595c61212f9ac459c09995cf4a996584bf473d4c58db901c2c994f62e6022720987e653d1e3100a84db6e077b9e4387b9df33048d201969b5fb215cb142000bb21e7e5cc3e74b934cfb80e9d117fcecb1c68479390f173cb8e33853f66a51d157287324b3f8a590e40646877c5435e3251fdd5c19791471b51f07c5265dd79aeb2997545e7a3c7b6484f34734871145260d019b28692be1357ff27b9361ff90c1e5f308a1832a900dc915c3771cb83e964e99667e5e46a713c152ce2e33d45ef4050d34671391ec20f93fcb9b9597781e1ca4d4ba1762fced1f9a06311905c6bdda492f72ce9a1c9f20cc26d020aa0a3cede4bf35a7735fe41d1ae0e0ecbb5da8ccd68f37c7acaebc1f8fc764db3bed1dbf4053911b9105e09605de322fb8750717c756330856835ed2c713ff7957f8a99f7ed485e480949b2a9b9d1d8acc0eafeee71977a56a07132c495067aeb7b9dae1e7132036424b7993949cbfd2dedff91b42494a555d6a72757aa2aebfd0f0fb161a617c8890a4a5afc0d1d9dadef300000000000000000000000000000000000000000000000c1a2a39"); +// byte[] seed = Hex.decode("7c9935a0b07694aa0c6d10e4db6b1add2fd81a25ccb148032dcd739936737f2d"); +// +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("HASH-ML-DSA", "BC"); +// SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); +// +// kpg.initialize(MLDSAParameterSpec.ml_dsa_44, katRandom); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()); +// +// ASN1BitString pubSeq = pubInfo.getPublicKeyData(); +// +// assertTrue(Arrays.areEqual(pubSeq.getOctets(), pubK)); +// +// PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); +// ASN1OctetString seq = privInfo.getPrivateKey(); +// +// assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(ASN1Sequence.getInstance(seq.getOctets()).getObjectAt(0)).getOctets(), seed)); +// +// Signature sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initSign(kp.getPrivate()); +// +// sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); +// +// sig.update(msg, 0, msg.length); +// +// byte[] genS = sig.sign(); +// +// assertTrue(Hex.toHexString(genS), Arrays.areEqual(s, genS)); +// +// sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initVerify(kp.getPublic()); +// +// sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); +// +// sig.update(msg, 0, msg.length); +// +// assertTrue(sig.verify(s)); +// +// // check randomisation +// +// sig.initSign(kp.getPrivate(), new SecureRandom()); +// +// sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); +// +// sig.update(msg, 0, msg.length); +// +// genS = sig.sign(); +// +// assertFalse(Arrays.areEqual(s, genS)); +// +// sig = Signature.getInstance("HASH-ML-DSA", "BC"); +// +// sig.initVerify(kp.getPublic()); +// +// sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); +// +// sig.update(msg, 0, msg.length); +// +// assertTrue(sig.verify(genS)); +// } + + private static class RiggedRandom + extends SecureRandom + { + public void nextBytes(byte[] bytes) + { + for (int i = 0; i != bytes.length; i++) + { + bytes[i] = (byte)(i & 0xff); + } + } + } + + public static void main(String[] args) + throws Exception + { + byte[] enc = Hex.decode("30820A2604201BA29BED84A27773E818F0B3FDABB60D37AFAE2CF8CB14844130C2F3A003B1BA81820A004CE51DC37BB794EB06DB74F14F050585CD70139D8ECDB6F0D2277144662158D969E49D22ED3BAB11A549FEA12174B4C6C9652D70229C78D7D9737443CF7E6387D01D7390342777C200309C05303F388A2AE1ED0BA183A1EE6C0808DEE411DF19CA18CAEC042F9E90DA15F6606CA35E57B917297E7ACD2C981265E5A40ABA67D88B36202219712009461A328D90C66100882DA4480C6482604A80456320269AC82C23845060A084A0A0208CA46820115044942C5C20404A044EC4162900C911549488E22602CC8889134906210068C38650138968529091C83688634406A3A404922045D99620DC066903150810B490CBC44C09878894346C20102422336C004981418044A4A08C44860502100040A091043042548221090564D03890194060A0C05004A205A3262DD9866D09A349C9C641CBB6699A10311A884D88244A6232701C9688400820514226DAA468C4046424260209010AC24668C0348E1C9421DC088489029058065183260223B38D82B60C000704A328660096858AA4099BC409934429A4424C40424D63B490101565C0C468C8222E02888083460000282542A02460320CD4262CE2146889C0851B376013468A5C1609603862A3364C60A231CB2491D2186E091149401291882404013485C4A64864304600272A0AA3502131700243291B096810274124030EA0B60094000202B40812980C0C1528CC8804D0069099368493382922B58D54C0410CC58C133081C9204022C86864960102870088306EA3464C08A090003362D8008A5A9881840072E3A805C0188011329044206C93125081205081422D028789CB2650499849610840DA10020A19219AB4880844201AB7400A47880432729404602020202412065A264C1C39911825104AC6094C20668022262427041216100282100C3202E33650E448440C246DCAA2641C126904856D8A46905A868C12422EC1A44820349109152103428C53842D24136DE34880202368C828400C81040B826D124469C9260C24B090824204D2B46483B441E4C40D011429D0248249062D99828D992842A3184622044244464D118371C0100448C0648A101199066243B26CD3304AC810010AB4245AA84118B460D3340CC4840DC84048D9164D53B4206218698484445336401BA2840195208846428B2221C4B84811358A1A17005490711C411103A18D104828C4A20853140609B5910C129183B82C5C1424A4446D09B8051A3766D4820961A6201015862224605C1870203709AF99F0C00D4D82188D2DE0792B0010C0AE9CC07F6C172F8974187DD7A3ED3C904068E1806D73B53910EC410ECC02B1980DF524F78A0F4CD155D6595E9C27FA19D96DE7376B4894083FA8BCC1752ACF88075ADA57A9D6606FE887EE0D8BE481A754DC061FA3F7F9CC21501F4C6BB325D1890A5DA77BCF5C97B0BA9E7D2BD055665C4E2E15F50606FA649689E046C22063EB272AA351BDE346AD2424D7054F4E23CAD899E25FB5A5E9D1653ECFD50772092D2D25A4EB62B42CDAA23DE42C7B50D23F8BB429D8E8479779FCD4173B69C3B343A08874FBEAAF1D727D929CA4F8011CBA9DB33C1DA0E4BCFA8D1397DB74A5ADCFF0A2BAB74139B51E3F6BDA077579073E6050352FE7F85FC028EAA91FD1DA18D35BC9EE6B8148BEA2B22F17BF24DFC387C2E1591B2DAE0DE0DF9B36313360E14F926A31E19B0473C45DDE050C2A1CB394C8BD4E9403B065414EF8C01F42AD4C4FA69BD831376327947EC0F9D2E129EB3034CA5DF04260AD1B15C66123BC220BAF53DE2CA65E7A0E7CDFFF4EEFB3FC386FBD04BC06BDE385C79ABC81CE8A447A64CC916AA7FCC9471CA6710252A2220BD27A6D3413BD4AD36240C69FD95C9BA3249E3D03745289CE7C8AAB2168974BABA116F02F9AD5EB4210193C37E28D7E6925D64EC3C551F0398C75A3A34A4F07E5BB84E412CAD58EB1FC1D059D747E3177BC51E68A833358BB0254266F88F2A4DE4D6FE4285F213ED479ADB6E2AA320343B80051CA6D4929478812405ADD1F8054B56BCBE02E43D66CFEA6FE976E9FDBEC9EEB2A86D0111165DDA1E622E040F05D171822A74F5458B5925FB0AFF0D623A4666452DC2B11F8D14C477F676BCD1BED62FD1427A25CB743EAE47FB6AF0C51B2DDA77B5EB0EF001839384DA8D7390DF8654BA0C8EB94A92D20BE50500450E7A3D3B374AD02943F2D22046611F8C23B68B7679E9D81AC4B3A01261D85CAAD696EF65E39D2D0D7308ACFA954A8D89A6BE9EE3FBC313BE89035E4431212A7B0DCBADFBAEC294F7CECBDD4D59709276D2DDF4428D9D019F2814B60B9A388C47DD7E26A00131DC853148A79F02D395C33205C1CFBB688C1FEE9A8453B2B371B431E7DA86DB98A090AF0A6CBF131811BE86B2BAEF3C2D61E9EE1D628BAC2D9A4CF8ECD32CC8B926D01DBDFA10327375B9461827B52DAA483F918E5F30894BEBF73332E2169472E72B61A16E2F9A5876D429E5B5791F61ECDF2F73F69DD7609AD36C1CC0DF6C8A5744055E863F63F069CE304D1BCA0680DC64AD9B00ABC39662C74C59AA677F59A6B101C393B7EB7B427125AA1785ED2E4ADD2FA074599A954E1D1B8BE2D18A65A86BB1D2274C7B11FB2228A5C632B705B428ADBFCAE399C7748F08557F3AAA459010F803049B08D9832706C2E52BF88836C6BB31BCCB93C16E413294EE9BDFF5023A5DA482783C4134A5FB7AB93AD58B85A6105640671DC3B86066BF690B3F3730AB2A9D25437690E31AC3F1CC17437F9E641E3C4CA28A8D7C1FD6BD27E534CD31F25DC9E6105C86C3DA36379C7D84C51F116B975C3A4D4D3641671581CD654B1794087649AB9479D3DD80C147D169E34E6FD9A7478FC318FCD92435C874ABF0F1939C6795ED10B5659A271DE900D08E580F74D670557888CD790495442D129B4A41577801F456A7286A1B860849A45E0CD1882390C012E644ECCB9393E9863B55B470647456916D3EBE20DC16A90C09F2DDB0525A151661D04FA916F7AC66E78AB76CE15FF9E6EC14520CAFF8CF8BF81DFBBAC96E2D85ACDEF6950FFBEA257D6817151B5D5EF32329C016A00F75AE006261A6CF5DB50CA909554E48790C11FC4A3B7A07C8EC15439E59754AF8F513D1B9526670A18FCD89CA476DF41FA8D59F56988BF38A85E2996F1CAFBCF8D039E1ED9FE5C258B825953B4669FBCB652DB604A90E02B803B72DC414EDAF62B31C640126A90CD946DBAAE786637695A0BCE6007E671844A90BC24DD8EAA36364D739A350F7D442C6C1B06CD5CFEB2F2C997BDB599DFD4933FBC8C3DD70DE8F20D52479149D477E765358F64A403E6B7D42B8B302A404026AEA4EBCD9755EE1727977C0228505587F0104F9D57B52D87B3A894992CE3D9C12E1ED625132584F521C5076504AC979053E1DE85E1A2D0F78D70B4A4F680EEAD0876710289448DB78DBF3BC1CEE48033C58BEF2CB9348871A5BB6132BED61E30AE4A4E23B2A2A49C15438CE23697ABEE47F1FC482BB02F26512796F5D8A3BC407DFB5745734FC96ADDD8204B8B6BA0B48C62089FC8F9951782969B661F0B66BDEA3AFE0E40AA9B5C2E4DA8B42D56907EDA4AE42CFA2E38EFC961C4EAB9C0824B36A503E85A41C5"); + + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLKEMKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLKEMKeyPairGeneratorTest.java new file mode 100644 index 0000000000..714dda6261 --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLKEMKeyPairGeneratorTest.java @@ -0,0 +1,170 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLKEMPrivateKey; +import org.bouncycastle.jcajce.interfaces.MLKEMPublicKey; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMPrivateKeySpec; +import org.bouncycastle.jcajce.spec.MLKEMPublicKeySpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + +/** + * KeyFactory/KeyPairGenerator tests for MLKEM with BCPQC provider. + */ +public class MLKEMKeyPairGeneratorTest + extends KeyPairGeneratorTest +{ + protected void setUp() + { + super.setUp(); + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public void testKeyFactory() + throws Exception + { + kf = KeyFactory.getInstance("ML-KEM", "BC"); + } + + public void testKeyPairGeneratorNames() + throws Exception + { + ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[]{ + NISTObjectIdentifiers.id_alg_ml_kem_512, + NISTObjectIdentifiers.id_alg_ml_kem_768, + NISTObjectIdentifiers.id_alg_ml_kem_1024 + }; + + String[] algs = new String[]{ + "ML-KEM-512", + "ML-KEM-768", + "ML-KEM-1024" + }; + + for (int i = 0; i != oids.length; i++) + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(oids[i].getId(), "BC"); + + KeyPair kp = kpGen.generateKeyPair(); + + assertEquals(algs[i], kp.getPrivate().getAlgorithm()); + assertEquals(algs[i], kp.getPublic().getAlgorithm()); + } + + // + // a bit of a cheat as we just look for "getName()" on the parameter spec. + // + for (int i = 0; i != algs.length; i++) + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algs[i], "BC"); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase(algs[i]))); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toUpperCase(algs[i]))); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase(algs[i])), new SecureRandom()); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toUpperCase(algs[i])), new SecureRandom()); + } + + try + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algs[0], "BC"); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase("Not Valid"))); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("unknown parameter set name: NOT VALID", e.getMessage()); + } + } + + public void testKeyPairEncoding() + throws Exception + { + MLKEMParameterSpec[] params = + new MLKEMParameterSpec[] + { + MLKEMParameterSpec.ml_kem_512, + MLKEMParameterSpec.ml_kem_768, + MLKEMParameterSpec.ml_kem_1024, + }; + // expected object identifiers + ASN1ObjectIdentifier[] oids = + { + NISTObjectIdentifiers.id_alg_ml_kem_512, + NISTObjectIdentifiers.id_alg_ml_kem_768, + NISTObjectIdentifiers.id_alg_ml_kem_1024, + }; + kf = KeyFactory.getInstance("ML-KEM", "BC"); + + kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + for (int i = 0; i != params.length; i++) + { + kpg.initialize(params[i], new SecureRandom()); + KeyPair keyPair = kpg.generateKeyPair(); + performKeyPairEncodingTest(keyPair); + assertEquals(oids[i], SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()).getAlgorithm().getAlgorithm()); + assertTrue(oids[i].toString(), Arrays.areEqual(((MLKEMPublicKey)keyPair.getPublic()).getPublicData(), ((MLKEMPrivateKey)keyPair.getPrivate()).getPublicKey().getPublicData())); + } + } + + public void testKeyParameterSpec() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM-512", "BC"); + KeyFactory kFact = KeyFactory.getInstance("ML-KEM", "BC"); + + KeyPair kp = kpg.generateKeyPair(); + + MLKEMPrivateKeySpec privSpec = (MLKEMPrivateKeySpec)kFact.getKeySpec(kp.getPrivate(), MLKEMPrivateKeySpec.class); + + assertTrue(privSpec.isSeed()); + + MLKEMPrivateKey privKey = (MLKEMPrivateKey)kFact.generatePrivate(privSpec); + + assertEquals(privKey, kp.getPrivate()); + assertEquals(privKey.getPublicKey(), kp.getPublic()); + + privSpec = new MLKEMPrivateKeySpec(privKey.getParameterSpec(), privKey.getPrivateData(), privKey.getPublicKey().getPublicData()); + + assertTrue(!privSpec.isSeed()); + + privKey = (MLKEMPrivateKey)kFact.generatePrivate(privSpec); + + assertEquals(privKey, kp.getPrivate()); + assertEquals(privKey.getPublicKey(), kp.getPublic()); + + MLKEMPublicKeySpec pubSpec = new MLKEMPublicKeySpec(privKey.getParameterSpec(), privKey.getPublicKey().getPublicData()); + + PublicKey pubKey = kFact.generatePublic(pubSpec); + + assertEquals(kp.getPublic(), pubKey); + + pubSpec = (MLKEMPublicKeySpec)kFact.getKeySpec(kp.getPrivate(), MLKEMPublicKeySpec.class); + + pubKey = kFact.generatePublic(pubSpec); + + assertEquals(kp.getPublic(), pubKey); + + pubSpec = (MLKEMPublicKeySpec)kFact.getKeySpec(kp.getPublic(), MLKEMPublicKeySpec.class); + + pubKey = kFact.generatePublic(pubSpec); + + assertEquals(kp.getPublic(), pubKey); + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLKEMTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLKEMTest.java new file mode 100644 index 0000000000..4fe14f5536 --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MLKEMTest.java @@ -0,0 +1,485 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; +import org.bouncycastle.jcajce.interfaces.MLKEMPrivateKey; +import org.bouncycastle.jcajce.spec.KEMExtractSpec; +import org.bouncycastle.jcajce.spec.KEMGenerateSpec; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Base64; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; + +/** + * KEM tests for MLKEM with the BC provider. + */ +public class MLKEMTest + extends TestCase +{ + static private final String[] names = new String[]{ + "ML-KEM-512", + "ML-KEM-768", + "ML-KEM-1024" + }; + + public void setUp() + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + Security.addProvider(new BouncyCastleProvider()); + } + + public void testParametersAndParamSpecs() + throws Exception + { + MLKEMParameters mlKemParameters[] = new MLKEMParameters[] + { + MLKEMParameters.ml_kem_512, + MLKEMParameters.ml_kem_768, + MLKEMParameters.ml_kem_1024 + }; + + for (int i = 0; i != names.length; i++) + { + assertEquals(names[i], MLKEMParameterSpec.fromName(mlKemParameters[i].getName()).getName()); + } + + for (int i = 0; i != names.length; i++) + { + assertEquals(names[i], MLKEMParameterSpec.fromName(names[i]).getName()); + } + } + + public void testKeyFactory() + throws Exception + { + KeyFactory kFact = KeyFactory.getInstance("ML-KEM", "BC"); + KeyPairGenerator kpGen512 = KeyPairGenerator.getInstance("ML-KEM-512"); + KeyPair kp512 = kpGen512.generateKeyPair(); + KeyPairGenerator kpGen768 = KeyPairGenerator.getInstance("ML-KEM-768"); + KeyPair kp768 = kpGen768.generateKeyPair(); + KeyPairGenerator kpGen1024 = KeyPairGenerator.getInstance("ML-KEM-1024"); + KeyPair kp1024 = kpGen1024.generateKeyPair(); + + tryKeyFact(KeyFactory.getInstance("ML-KEM-512", "BC"), kp512, kp768, "2.16.840.1.101.3.4.4.2"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_alg_ml_kem_512.toString(), "BC"), kp512, kp768, "2.16.840.1.101.3.4.4.2"); + tryKeyFact(KeyFactory.getInstance("ML-KEM-768", "BC"), kp768, kp512, "2.16.840.1.101.3.4.4.1"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_alg_ml_kem_768.toString(), "BC"), kp768, kp512, "2.16.840.1.101.3.4.4.1"); + tryKeyFact(KeyFactory.getInstance("ML-KEM-1024", "BC"), kp1024, kp768, "2.16.840.1.101.3.4.4.2"); + tryKeyFact(KeyFactory.getInstance(NISTObjectIdentifiers.id_alg_ml_kem_1024.toString(), "BC"), kp1024, kp768, "2.16.840.1.101.3.4.4.2"); + } + + private void tryKeyFact(KeyFactory kFact, KeyPair kpValid, KeyPair kpInvalid, String oid) + throws Exception + { + kFact.generatePrivate(new PKCS8EncodedKeySpec(kpValid.getPrivate().getEncoded())); + kFact.generatePublic(new X509EncodedKeySpec(kpValid.getPublic().getEncoded())); + + try + { + kFact.generatePrivate(new PKCS8EncodedKeySpec(kpInvalid.getPrivate().getEncoded())); + fail("no exception"); + } + catch (InvalidKeySpecException e) + { + assertEquals("incorrect algorithm OID for key: " + oid, e.getMessage()); + } + try + { + kFact.generatePublic(new X509EncodedKeySpec(kpInvalid.getPublic().getEncoded())); + fail("no exception"); + } + catch (InvalidKeySpecException e) + { + assertEquals("incorrect algorithm OID for key: " + oid, e.getMessage()); + } + } + + public void testDefaultPrivateKeyEncoding() + throws Exception + { + KeyPairGenerator kpGen512 = KeyPairGenerator.getInstance("ML-KEM-512", "BC"); + + byte[] seed = Hex.decode("000102030405060708090a0b0c0d0e0f" + + "100102030405060708090a0b0c0d0e0f" + + "200102030405060708090a0b0c0d0e0f" + + "300102030405060708090a0b0c0d0e0f"); + kpGen512.initialize(MLKEMParameterSpec.ml_kem_512, new FixedSecureRandom(seed)); + KeyPair kp512 = kpGen512.generateKeyPair(); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp512.getPrivate().getEncoded()); + ASN1Sequence seq = ASN1Sequence.getInstance(privInfo.getPrivateKey().getOctets()); + + assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(seq.getObjectAt(0)).getOctets(), seed)); + + assertTrue(Arrays.areEqual(ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets(), ((MLKEMPrivateKey)kp512.getPrivate()).getPrivateData())); + } + + public void testSeedPrivateKeyEncoding() + throws Exception + { + KeyPairGenerator kpGen512 = KeyPairGenerator.getInstance("ML-KEM-512", "BC"); + + byte[] seed = Hex.decode("000102030405060708090a0b0c0d0e0f" + + "100102030405060708090a0b0c0d0e0f" + + "200102030405060708090a0b0c0d0e0f" + + "300102030405060708090a0b0c0d0e0f"); + kpGen512.initialize(MLKEMParameterSpec.ml_kem_512, new FixedSecureRandom(seed)); + KeyPair kp512 = kpGen512.generateKeyPair(); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(((MLKEMPrivateKey)kp512.getPrivate()).getPrivateKey(true).getEncoded()); + + ASN1OctetString k = ASN1OctetString.getInstance((ASN1TaggedObject)privInfo.parsePrivateKey(), false); + + assertTrue(Arrays.areEqual(k.getOctets(), seed)); + } + + public void testExpandedPrivateKeyEncoding() + throws Exception + { + KeyPairGenerator kpGen512 = KeyPairGenerator.getInstance("ML-KEM-512", "BC"); + + byte[] seed = Hex.decode("000102030405060708090a0b0c0d0e0f" + + "100102030405060708090a0b0c0d0e0f" + + "200102030405060708090a0b0c0d0e0f" + + "300102030405060708090a0b0c0d0e0f"); + byte[] expanded = Base64.decode("WCF6H9yVm+nHHlpz1fOL8Oibz2GOuXSDQhwXrSnDraa2fYB0LxV12Tsp7FggB1xmvIg+GBXJoJcJ6APDuDCqE/RtW5eSZwKLI/cqeubNablS7SCQSORrZiNuVkoGgPikT9hzUDhvDhdE7tuD+cF1UfpECGZOFDFfaKeFufJlX/kcIAwFjgXOPqJrBiUd3BUsb2G81kxyJHfEODauV3p58dAWReW4Wfwzm8CP+OXMAsUiZTlHCzJxbaXFPwCBaokc/8XBd6FUOBLHAjxbVRKvuTQS8JEJLFTHvqYtehik66hEdNUJBfSpRGFalRFjvXp8acFXmluVTQsO6eoTL5pO0nZ1fhetf0RKgzeI07G0xIherqxln1dwj7VtM6WsW6WxZcFHkBQMWFiRUitxJ1QIbqY/1Po6uBEp/YYOPEoe7qMw2hxvadNEf7KiRPq6R+oxDMwnthex94O78ZNoDHiM5PdU4WKj8EkrySo49uS+d/YUnxxGZbSSY+uzTYY7D+w7zcapr0sgmmUIHtYEU6WxmCMFA8NmABySw0xOhJaDBsk5EWK1aZqkM+eqbhYfRwIpFvrKapAi86i6jAadcwm8ASRjmyZmRfCYkevG8kisVQg44TFbP6RYoXoFHzXI3BguJCmbGBS7YFSfwHcIiOybuJWQLqxIZZkPdzlGmnMr25uimbBxyzIB4Zw7HsZfGEGQ3xdAsCRhFskQw0XDHIVWZ9IZN/pofqUlNhqqeGCC6RaRkgDMdrLE8bBeB8WUt0SyXKgCZeXJBshKa3dhZeOq1yWNt5hB/rZKDgszqPmwv+hiZxURg6VUJPEoiXaAsbHBZKWROywm7WeK8ghdsyazhGFbJMdKhAOSYKBgWIBCcUBHZMLEhtm3gNLHdzGx4DtC4dGmJHxMRhFoH5cX/ARlO+RcKteNZTcyT+hlSIgyU/wBgxzBhIwsVmkMYiuPGnmqEAF0+LI79VqrTDJFmdBYGJsdShOV8Ey4JGulmoRN3oyOtvsPPpJ8Qfl0xgJLn6Ns87KcI/MUaXtilMpeYwxS1AwFnvJZGzDKh1GxTtKD87iTzErIgiV0AFojsEZ59AkvjGmFw1jPvhSIXsF900EMc8O2oWArKHIYzXWL2AmfDmmmjFxTW4Ic5xyQejkibiolbHhAb0RYYesI1ZmUnXCjyiBSz/CpgIyFIjqVXAOxGmy5XJdMobDJbhh0xnV3uytNGXuRiYqjnaQTzVEpbNUYXbAdVoFuHfwMKfy6eHIBXoLJFnpdLOEYnYireCYv1mrGYjWsH9MY4Ys17vvIcFSia/Rc+VtH9CJk2bqgEVqK2TsV6KgREaJgDBmj0BRp8ourO/YAFMslxLcLQDqrKtA4JhGcAzhsYjpzQlBXljSlqmFKWmjCIBRFrFaMG+xv76YBaqh+0aEQKOVT2JwNyADG3SonhoUDovo+J9UlaGljwmeaAQCouQZDCXELgreKpHOFaMK7RpQHNjtlv+FuV+k7WnudORs9Nde92Kw13SRSulmQtao1SHJf0VRcvuQu3eMzLLsjluElKqEpvDZX/Cg76XgEptYaEqlMQNSa6fh30bc+GhoyFRGx3zk3zvbGrtrEWiPIacCMeQKMmieN8apjragAiZsGdpMCsfxq1xAJraHB4cMGSix3ZOp8riKumiO4EQwDhtJGu4NXbLC459JkqaEP1HTA/jNpwiIRBsHE3dlOaFE7iJk+znrMXzcG+1fHAXhDatwPEizALupyhTxAiJsCWzxctKFbzouzbwcuXAKqJbldNdRsx+ESaugoN+QKLmEJOJlpjWKFIORE4daWXpoCz4WPw1ADCTiDQ3WzTPQn46tlgDDFwTx60eJk+CAn48Q+eYM3W6SDCtqLKYgUjLlJcakdKMmKJVdIL1A66gtH3jA/oJurjNGNaHK+ZNKDm9NxKrWQ9PmmBAiHsPKqIosLR4sZ6oANC4mtVHK3lZmYz9LI/ejIfLgd7aw1INBupOPPpGmrQqA4LcGgd0mMCVRLKxEqPBRuTDaLBAI8HdJUwsgwI3GrH1ZkAsNHBhmvUdSNjicplOoWHcNYi9U4FZkIifBjHUgGUNUhmw4Mkf3IfeYtJoLtjpYOIjQ3yFH8zzdEKBY74ILHT+BSWiakAyABAgMEBQYHCAkKCwwNDg8wAQIDBAUGBwgJCgsMDQ4P"); + + kpGen512.initialize(MLKEMParameterSpec.ml_kem_512, new FixedSecureRandom(seed)); + KeyPair kp512 = kpGen512.generateKeyPair(); + + PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(((MLKEMPrivateKey)kp512.getPrivate()).getPrivateKey(false).getEncoded()); + + ASN1OctetString k = ASN1OctetString.getInstance(privInfo.parsePrivateKey()); + + assertTrue(Arrays.areEqual(k.getOctets(), expanded)); + } + + public void testPrivateKeyRecoding() + throws Exception + { + // TODO: rebuild with newer encodings. +// byte[] mlkem512_sequence = Base64.decode("MIIGvgIBADALBglghkgBZQMEBAEEggaqMIIGpgRAAAECAwQFBgcICQoLDA0ODxABAgMEBQYHCAkKCwwNDg8gAQIDBAUGBwgJCgsMDQ4PMAECAwQFBgcICQoLDA0OD4GCBmBYIXof3JWb6cceWnPV84vw6JvPYY65dINCHBetKcOtprZ9gHQvFXXZOynsWCAHXGa8iD4YFcmglwnoA8O4MKoT9G1bl5JnAosj9yp65s1puVLtIJBI5GtmI25WSgaA+KRP2HNQOG8OF0Tu24P5wXVR+kQIZk4UMV9op4W58mVf+RwgDAWOBc4+omsGJR3cFSxvYbzWTHIkd8Q4Nq5Xennx0BZF5bhZ/DObwI/45cwCxSJlOUcLMnFtpcU/AIFqiRz/xcF3oVQ4EscCPFtVEq+5NBLwkQksVMe+pi16GKTrqER01QkF9KlEYVqVEWO9enxpwVeaW5VNCw7p6hMvmk7SdnV+F61/REqDN4jTsbTEiF6urGWfV3CPtW0zpaxbpbFlwUeQFAxYWJFSK3EnVAhupj/U+jq4ESn9hg48Sh7uozDaHG9p00R/sqJE+rpH6jEMzCe2F7H3g7vxk2gMeIzk91ThYqPwSSvJKjj25L539hSfHEZltJJj67NNhjsP7DvNxqmvSyCaZQge1gRTpbGYIwUDw2YAHJLDTE6EloMGyTkRYrVpmqQz56puFh9HAikW+spqkCLzqLqMBp1zCbwBJGObJmZF8JiR68bySKxVCDjhMVs/pFihegUfNcjcGC4kKZsYFLtgVJ/AdwiI7Ju4lZAurEhlmQ93OUaacyvbm6KZsHHLMgHhnDsexl8YQZDfF0CwJGEWyRDDRcMchVZn0hk3+mh+pSU2Gqp4YILpFpGSAMx2ssTxsF4HxZS3RLJcqAJl5ckGyEprd2Fl46rXJY23mEH+tkoOCzOo+bC/6GJnFRGDpVQk8SiJdoCxscFkpZE7LCbtZ4ryCF2zJrOEYVskx0qEA5JgoGBYgEJxQEdkwsSG2beA0sd3MbHgO0Lh0aYkfExGEWgflxf8BGU75Fwq141lNzJP6GVIiDJT/AGDHMGEjCxWaQxiK48aeaoQAXT4sjv1WqtMMkWZ0FgYmx1KE5XwTLgka6WahE3ejI62+w8+knxB+XTGAkufo2zzspwj8xRpe2KUyl5jDFLUDAWe8lkbMMqHUbFO0oPzuJPMSsiCJXQAWiOwRnn0CS+MaYXDWM++FIhewX3TQQxzw7ahYCsochjNdYvYCZ8OaaaMXFNbghznHJB6OSJuKiVseEBvRFhh6wjVmZSdcKPKIFLP8KmAjIUiOpVcA7EabLlcl0yhsMluGHTGdXe7K00Ze5GJiqOdpBPNUSls1RhdsB1WgW4d/Awp/Lp4cgFegskWel0s4RidiKt4Ji/WasZiNawf0xjhizXu+8hwVKJr9Fz5W0f0ImTZuqARWorZOxXoqBERomAMGaPQFGnyi6s79gAUyyXEtwtAOqsq0DgmEZwDOGxiOnNCUFeWNKWqYUpaaMIgFEWsVowb7G/vpgFqqH7RoRAo5VPYnA3IAMbdKieGhQOi+j4n1SVoaWPCZ5oBAKi5BkMJcQuCt4qkc4VowrtGlAc2O2W/4W5X6Ttae505Gz01173YrDXdJFK6WZC1qjVIcl/RVFy+5C7d4zMsuyOW4SUqoSm8Nlf8KDvpeASm1hoSqUxA1Jrp+HfRtz4aGjIVEbHfOTfO9sau2sRaI8hpwIx5AoyaJ43xqmOtqACJmwZ2kwKx/GrXEAmtocHhwwZKLHdk6nyuIq6aI7gRDAOG0ka7g1dssLjn0mSpoQ/UdMD+M2nCIhEGwcTd2U5oUTuImT7OesxfNwb7V8cBeENq3A8SLMAu6nKFPECImwJbPFy0oVvOi7NvBy5cAqoluV011GzH4RJq6Cg35AouYQk4mWmNYoUg5ETh1pZemgLPhY/DUAMJOINDdbNM9Cfjq2WAMMXBPHrR4mT4ICfjxD55gzdbpIMK2ospiBSMuUlxqR0oyYolV0gvUDrqC0feMD+gm6uM0Y1ocr5k0oOb03EqtZD0+aYECIew8qoiiwtHixnqgA0Lia1UcreVmZjP0sj96Mh8uB3trDUg0G6k48+kaatCoDgtwaB3SYwJVEsrESo8FG5MNosEAjwd0lTCyDAjcasfVmQCw0cGGa9R1I2OJymU6hYdw1iL1TgVmQiJ8GMdSAZQ1SGbDgyR/ch95i0mgu2Olg4iNDfIUfzPN0QoFjvggsdP4FJaJqQDIAECAwQFBgcICQoLDA0ODzABAgMEBQYHCAkKCwwNDg8="); + byte[] mlkem512_seed_only = Base64.decode("MFICAQAwCwYJYIZIAWUDBAQBBEAAAQIDBAUGBwgJCgsMDQ4PEAECAwQFBgcICQoLDA0ODyABAgMEBQYHCAkKCwwNDg8wAQIDBAUGBwgJCgsMDQ4P"); + byte[] mlkem512_wrap_seed_only = Base64.decode("MFQCAQAwCwYJYIZIAWUDBAQBBEIEQAABAgMEBQYHCAkKCwwNDg8QAQIDBAUGBwgJCgsMDQ4PIAECAwQFBgcICQoLDA0ODzABAgMEBQYHCAkKCwwNDg8="); +// byte[] mlKem512_expanded_only = Base64.decode("MIIGdAIBADALBglghkgBZQMEBAEEggZgWCF6H9yVm+nHHlpz1fOL8Oibz2GOuXSDQhwXrSnDraa2fYB0LxV12Tsp7FggB1xmvIg+GBXJoJcJ6APDuDCqE/RtW5eSZwKLI/cqeubNablS7SCQSORrZiNuVkoGgPikT9hzUDhvDhdE7tuD+cF1UfpECGZOFDFfaKeFufJlX/kcIAwFjgXOPqJrBiUd3BUsb2G81kxyJHfEODauV3p58dAWReW4Wfwzm8CP+OXMAsUiZTlHCzJxbaXFPwCBaokc/8XBd6FUOBLHAjxbVRKvuTQS8JEJLFTHvqYtehik66hEdNUJBfSpRGFalRFjvXp8acFXmluVTQsO6eoTL5pO0nZ1fhetf0RKgzeI07G0xIherqxln1dwj7VtM6WsW6WxZcFHkBQMWFiRUitxJ1QIbqY/1Po6uBEp/YYOPEoe7qMw2hxvadNEf7KiRPq6R+oxDMwnthex94O78ZNoDHiM5PdU4WKj8EkrySo49uS+d/YUnxxGZbSSY+uzTYY7D+w7zcapr0sgmmUIHtYEU6WxmCMFA8NmABySw0xOhJaDBsk5EWK1aZqkM+eqbhYfRwIpFvrKapAi86i6jAadcwm8ASRjmyZmRfCYkevG8kisVQg44TFbP6RYoXoFHzXI3BguJCmbGBS7YFSfwHcIiOybuJWQLqxIZZkPdzlGmnMr25uimbBxyzIB4Zw7HsZfGEGQ3xdAsCRhFskQw0XDHIVWZ9IZN/pofqUlNhqqeGCC6RaRkgDMdrLE8bBeB8WUt0SyXKgCZeXJBshKa3dhZeOq1yWNt5hB/rZKDgszqPmwv+hiZxURg6VUJPEoiXaAsbHBZKWROywm7WeK8ghdsyazhGFbJMdKhAOSYKBgWIBCcUBHZMLEhtm3gNLHdzGx4DtC4dGmJHxMRhFoH5cX/ARlO+RcKteNZTcyT+hlSIgyU/wBgxzBhIwsVmkMYiuPGnmqEAF0+LI79VqrTDJFmdBYGJsdShOV8Ey4JGulmoRN3oyOtvsPPpJ8Qfl0xgJLn6Ns87KcI/MUaXtilMpeYwxS1AwFnvJZGzDKh1GxTtKD87iTzErIgiV0AFojsEZ59AkvjGmFw1jPvhSIXsF900EMc8O2oWArKHIYzXWL2AmfDmmmjFxTW4Ic5xyQejkibiolbHhAb0RYYesI1ZmUnXCjyiBSz/CpgIyFIjqVXAOxGmy5XJdMobDJbhh0xnV3uytNGXuRiYqjnaQTzVEpbNUYXbAdVoFuHfwMKfy6eHIBXoLJFnpdLOEYnYireCYv1mrGYjWsH9MY4Ys17vvIcFSia/Rc+VtH9CJk2bqgEVqK2TsV6KgREaJgDBmj0BRp8ourO/YAFMslxLcLQDqrKtA4JhGcAzhsYjpzQlBXljSlqmFKWmjCIBRFrFaMG+xv76YBaqh+0aEQKOVT2JwNyADG3SonhoUDovo+J9UlaGljwmeaAQCouQZDCXELgreKpHOFaMK7RpQHNjtlv+FuV+k7WnudORs9Nde92Kw13SRSulmQtao1SHJf0VRcvuQu3eMzLLsjluElKqEpvDZX/Cg76XgEptYaEqlMQNSa6fh30bc+GhoyFRGx3zk3zvbGrtrEWiPIacCMeQKMmieN8apjragAiZsGdpMCsfxq1xAJraHB4cMGSix3ZOp8riKumiO4EQwDhtJGu4NXbLC459JkqaEP1HTA/jNpwiIRBsHE3dlOaFE7iJk+znrMXzcG+1fHAXhDatwPEizALupyhTxAiJsCWzxctKFbzouzbwcuXAKqJbldNdRsx+ESaugoN+QKLmEJOJlpjWKFIORE4daWXpoCz4WPw1ADCTiDQ3WzTPQn46tlgDDFwTx60eJk+CAn48Q+eYM3W6SDCtqLKYgUjLlJcakdKMmKJVdIL1A66gtH3jA/oJurjNGNaHK+ZNKDm9NxKrWQ9PmmBAiHsPKqIosLR4sZ6oANC4mtVHK3lZmYz9LI/ejIfLgd7aw1INBupOPPpGmrQqA4LcGgd0mMCVRLKxEqPBRuTDaLBAI8HdJUwsgwI3GrH1ZkAsNHBhmvUdSNjicplOoWHcNYi9U4FZkIifBjHUgGUNUhmw4Mkf3IfeYtJoLtjpYOIjQ3yFH8zzdEKBY74ILHT+BSWiakAyABAgMEBQYHCAkKCwwNDg8wAQIDBAUGBwgJCgsMDQ4P"); +// byte[] mlKem512_wrap_expanded_only = Base64.decode("MIIGeAIBADALBglghkgBZQMEBAEEggZkBIIGYFgheh/clZvpxx5ac9Xzi/Dom89hjrl0g0IcF60pw62mtn2AdC8Vddk7KexYIAdcZryIPhgVyaCXCegDw7gwqhP0bVuXkmcCiyP3KnrmzWm5Uu0gkEjka2YjblZKBoD4pE/Yc1A4bw4XRO7bg/nBdVH6RAhmThQxX2inhbnyZV/5HCAMBY4Fzj6iawYlHdwVLG9hvNZMciR3xDg2rld6efHQFkXluFn8M5vAj/jlzALFImU5RwsycW2lxT8AgWqJHP/FwXehVDgSxwI8W1USr7k0EvCRCSxUx76mLXoYpOuoRHTVCQX0qURhWpURY716fGnBV5pblU0LDunqEy+aTtJ2dX4XrX9ESoM3iNOxtMSIXq6sZZ9XcI+1bTOlrFulsWXBR5AUDFhYkVIrcSdUCG6mP9T6OrgRKf2GDjxKHu6jMNocb2nTRH+yokT6ukfqMQzMJ7YXsfeDu/GTaAx4jOT3VOFio/BJK8kqOPbkvnf2FJ8cRmW0kmPrs02GOw/sO83Gqa9LIJplCB7WBFOlsZgjBQPDZgAcksNMToSWgwbJORFitWmapDPnqm4WH0cCKRb6ymqQIvOouowGnXMJvAEkY5smZkXwmJHrxvJIrFUIOOExWz+kWKF6BR81yNwYLiQpmxgUu2BUn8B3CIjsm7iVkC6sSGWZD3c5RppzK9ubopmwccsyAeGcOx7GXxhBkN8XQLAkYRbJEMNFwxyFVmfSGTf6aH6lJTYaqnhggukWkZIAzHayxPGwXgfFlLdEslyoAmXlyQbISmt3YWXjqtcljbeYQf62Sg4LM6j5sL/oYmcVEYOlVCTxKIl2gLGxwWSlkTssJu1nivIIXbMms4RhWyTHSoQDkmCgYFiAQnFAR2TCxIbZt4DSx3cxseA7QuHRpiR8TEYRaB+XF/wEZTvkXCrXjWU3Mk/oZUiIMlP8AYMcwYSMLFZpDGIrjxp5qhABdPiyO/Vaq0wyRZnQWBibHUoTlfBMuCRrpZqETd6Mjrb7Dz6SfEH5dMYCS5+jbPOynCPzFGl7YpTKXmMMUtQMBZ7yWRswyodRsU7Sg/O4k8xKyIIldABaI7BGefQJL4xphcNYz74UiF7BfdNBDHPDtqFgKyhyGM11i9gJnw5ppoxcU1uCHOcckHo5Im4qJWx4QG9EWGHrCNWZlJ1wo8ogUs/wqYCMhSI6lVwDsRpsuVyXTKGwyW4YdMZ1d7srTRl7kYmKo52kE81RKWzVGF2wHVaBbh38DCn8unhyAV6CyRZ6XSzhGJ2Iq3gmL9ZqxmI1rB/TGOGLNe77yHBUomv0XPlbR/QiZNm6oBFaitk7FeioERGiYAwZo9AUafKLqzv2ABTLJcS3C0A6qyrQOCYRnAM4bGI6c0JQV5Y0paphSlpowiAURaxWjBvsb++mAWqoftGhECjlU9icDcgAxt0qJ4aFA6L6PifVJWhpY8JnmgEAqLkGQwlxC4K3iqRzhWjCu0aUBzY7Zb/hblfpO1p7nTkbPTXXvdisNd0kUrpZkLWqNUhyX9FUXL7kLt3jMyy7I5bhJSqhKbw2V/woO+l4BKbWGhKpTEDUmun4d9G3PhoaMhURsd85N872xq7axFojyGnAjHkCjJonjfGqY62oAImbBnaTArH8atcQCa2hweHDBkosd2TqfK4irpojuBEMA4bSRruDV2ywuOfSZKmhD9R0wP4zacIiEQbBxN3ZTmhRO4iZPs56zF83BvtXxwF4Q2rcDxIswC7qcoU8QIibAls8XLShW86Ls28HLlwCqiW5XTXUbMfhEmroKDfkCi5hCTiZaY1ihSDkROHWll6aAs+Fj8NQAwk4g0N1s0z0J+OrZYAwxcE8etHiZPggJ+PEPnmDN1ukgwraiymIFIy5SXGpHSjJiiVXSC9QOuoLR94wP6Cbq4zRjWhyvmTSg5vTcSq1kPT5pgQIh7DyqiKLC0eLGeqADQuJrVRyt5WZmM/SyP3oyHy4He2sNSDQbqTjz6Rpq0KgOC3BoHdJjAlUSysRKjwUbkw2iwQCPB3SVMLIMCNxqx9WZALDRwYZr1HUjY4nKZTqFh3DWIvVOBWZCInwYx1IBlDVIZsODJH9yH3mLSaC7Y6WDiI0N8hR/M83RCgWO+CCx0/gUlompAMgAQIDBAUGBwgJCgsMDQ4PMAECAwQFBgcICQoLDA0ODw=="); +// byte[] mlkem512_seed_with_pub_key = Base64.decode("MIIDdwIBATALBglghkgBZQMEBAEEQAABAgMEBQYHCAkKCwwNDg8QAQIDBAUGBwgJCgsMDQ4PIAECAwQFBgcICQoLDA0ODzABAgMEBQYHCAkKCwwNDg+BggMhAPOynCPzFGl7YpTKXmMMUtQMBZ7yWRswyodRsU7Sg/O4k8xKyIIldABaI7BGefQJL4xphcNYz74UiF7BfdNBDHPDtqFgKyhyGM11i9gJnw5ppoxcU1uCHOcckHo5Im4qJWx4QG9EWGHrCNWZlJ1wo8ogUs/wqYCMhSI6lVwDsRpsuVyXTKGwyW4YdMZ1d7srTRl7kYmKo52kE81RKWzVGF2wHVaBbh38DCn8unhyAV6CyRZ6XSzhGJ2Iq3gmL9ZqxmI1rB/TGOGLNe77yHBUomv0XPlbR/QiZNm6oBFaitk7FeioERGiYAwZo9AUafKLqzv2ABTLJcS3C0A6qyrQOCYRnAM4bGI6c0JQV5Y0paphSlpowiAURaxWjBvsb++mAWqoftGhECjlU9icDcgAxt0qJ4aFA6L6PifVJWhpY8JnmgEAqLkGQwlxC4K3iqRzhWjCu0aUBzY7Zb/hblfpO1p7nTkbPTXXvdisNd0kUrpZkLWqNUhyX9FUXL7kLt3jMyy7I5bhJSqhKbw2V/woO+l4BKbWGhKpTEDUmun4d9G3PhoaMhURsd85N872xq7axFojyGnAjHkCjJonjfGqY62oAImbBnaTArH8atcQCa2hweHDBkosd2TqfK4irpojuBEMA4bSRruDV2ywuOfSZKmhD9R0wP4zacIiEQbBxN3ZTmhRO4iZPs56zF83BvtXxwF4Q2rcDxIswC7qcoU8QIibAls8XLShW86Ls28HLlwCqiW5XTXUbMfhEmroKDfkCi5hCTiZaY1ihSDkROHWll6aAs+Fj8NQAwk4g0N1s0z0J+OrZYAwxcE8etHiZPggJ+PEPnmDN1ukgwraiymIFIy5SXGpHSjJiiVXSC9QOuoLR94wP6Cbq4zRjWhyvmTSg5vTcSq1kPT5pgQIh7DyqiKLC0eLGeqADQuJrVRyt5WZmM/SyP3oyHy4He2sNSDQbqTjz6Rpq0KgOC3BoHdJjAlUSysRKjwUbkw2iwQCPB3SVMLIMCNxqx9WZALDRwYZr1HUjY4nKZTqFh3DWIvVOBWZCInwYx1IBlDVIZsODJH9"); + + KeyFactory kFact = KeyFactory.getInstance("ML-KEM", "BC"); + +// checkEncodeRecode(kFact, mlkem512_sequence); + checkEncodeRecode(kFact, mlkem512_seed_only); + checkEncodeRecode(kFact, mlkem512_wrap_seed_only); +// checkEncodeRecode(kFact, mlKem512_expanded_only); +// checkEncodeRecode(kFact, mlKem512_wrap_expanded_only); +// checkEncodeRecode(kFact, mlkem512_seed_with_pub_key); + } + + private void checkEncodeRecode(KeyFactory kFact, byte[] encoding) + throws Exception + { + PrivateKey key = kFact.generatePrivate(new PKCS8EncodedKeySpec(encoding)); + + assertTrue(Arrays.areEqual(encoding, key.getEncoded())); + } + + public void testBasicKEMCamellia() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom()); + + kpg.generateKeyPair().getPrivate().getEncoded(); + performKEMScipher(kpg.generateKeyPair(), "ML-KEM", new KTSParameterSpec.Builder("Camellia", 128).withNoKdf().build()); + performKEMScipher(kpg.generateKeyPair(), "ML-KEM", new KTSParameterSpec.Builder("Camellia-KWP", 128).withNoKdf().build()); + } + + public void testBasicKEMSEED() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom()); + + performKEMScipher(kpg.generateKeyPair(), "ML-KEM", new KTSParameterSpec.Builder("SEED", 128).build()); + } + + public void testBasicKEMARIA() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom()); + + performKEMScipher(kpg.generateKeyPair(), "ML-KEM", new KTSParameterSpec.Builder("ARIA", 256).build()); + performKEMScipher(kpg.generateKeyPair(), "ML-KEM", new KTSParameterSpec.Builder("ARIA-KWP", 256).build()); + } + + private void performKEMScipher(KeyPair kp, String algorithm, KTSParameterSpec ktsParameterSpec) + throws Exception + { + Cipher w1 = Cipher.getInstance(algorithm, "BC"); + + byte[] keyBytes; + if (ktsParameterSpec.getKeyAlgorithmName().endsWith("KWP")) + { + keyBytes = Hex.decode("000102030405060708090a0b0c0d0e0faa"); + } + else + { + keyBytes = Hex.decode("000102030405060708090a0b0c0d0e0f"); + } + SecretKey key = new SecretKeySpec(keyBytes, "AES"); + + w1.init(Cipher.WRAP_MODE, kp.getPublic(), ktsParameterSpec); + + byte[] data = w1.wrap(key); + + Cipher w2 = Cipher.getInstance(algorithm, "BC"); + + w2.init(Cipher.UNWRAP_MODE, kp.getPrivate(), ktsParameterSpec); + + Key k = w2.unwrap(data, "AES", Cipher.SECRET_KEY); + + assertTrue(Arrays.areEqual(keyBytes, k.getEncoded())); + } + + public void testGenerateAES() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyGenerator keyGen = KeyGenerator.getInstance("ML-KEM", "BC"); + + keyGen.init(new KEMGenerateSpec(kp.getPublic(), "AES", 128), new SecureRandom()); + + SecretKeyWithEncapsulation secEnc1 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + assertEquals("AES", secEnc1.getAlgorithm()); + assertEquals(16, secEnc1.getEncoded().length); + + keyGen.init(new KEMExtractSpec(kp.getPrivate(), secEnc1.getEncapsulation(), "AES", 128)); + + SecretKeyWithEncapsulation secEnc2 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + assertEquals("AES", secEnc2.getAlgorithm()); + + assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded())); + } + + public void testGenerateAES256() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_1024, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyGenerator keyGen = KeyGenerator.getInstance("ML-KEM", "BC"); + + keyGen.init(new KEMGenerateSpec(kp.getPublic(), "AES"), new SecureRandom()); + + SecretKeyWithEncapsulation secEnc1 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + assertEquals("AES", secEnc1.getAlgorithm()); + assertEquals(32, secEnc1.getEncoded().length); + + keyGen.init(new KEMExtractSpec(kp.getPrivate(), secEnc1.getEncapsulation(), "AES")); + + SecretKeyWithEncapsulation secEnc2 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + assertEquals("AES", secEnc2.getAlgorithm()); + + assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded())); + } + + public void testRestrictedKeyPairGen() + throws Exception + { + doTestRestrictedKeyPairGen(MLKEMParameterSpec.ml_kem_512, MLKEMParameterSpec.ml_kem_1024); + doTestRestrictedKeyPairGen(MLKEMParameterSpec.ml_kem_768, MLKEMParameterSpec.ml_kem_1024); + doTestRestrictedKeyPairGen(MLKEMParameterSpec.ml_kem_1024, MLKEMParameterSpec.ml_kem_512); + } + + private void doTestRestrictedKeyPairGen(MLKEMParameterSpec spec, MLKEMParameterSpec altSpec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + assertEquals(spec.getName(), kpg.getAlgorithm()); + assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); + assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); + + kpg = KeyPairGenerator.getInstance(spec.getName(), "BC"); + + try + { + kpg.initialize(altSpec, new SecureRandom()); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("key pair generator locked to " + spec.getName(), e.getMessage()); + } + } + + public void testRestrictedKeyGen() + throws Exception + { + doTestRestrictedKeyGen(MLKEMParameterSpec.ml_kem_512, MLKEMParameterSpec.ml_kem_1024); + doTestRestrictedKeyGen(MLKEMParameterSpec.ml_kem_768, MLKEMParameterSpec.ml_kem_1024); + doTestRestrictedKeyGen(MLKEMParameterSpec.ml_kem_1024, MLKEMParameterSpec.ml_kem_512); + } + + private void doTestRestrictedKeyGen(MLKEMParameterSpec spec, MLKEMParameterSpec altSpec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + assertEquals(spec.getName(), kpg.getAlgorithm()); + assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); + assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); + + KeyGenerator keyGen = KeyGenerator.getInstance(spec.getName(), "BC"); + + assertEquals(spec.getName(), keyGen.getAlgorithm()); + + keyGen.init(new KEMGenerateSpec(kp.getPublic(), "AES"), new SecureRandom()); + + SecretKeyWithEncapsulation secEnc1 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + keyGen.init(new KEMExtractSpec(kp.getPrivate(), secEnc1.getEncapsulation(), "AES")); + + SecretKeyWithEncapsulation secEnc2 = (SecretKeyWithEncapsulation)keyGen.generateKey(); + + assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded())); + + kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + kpg.initialize(altSpec, new SecureRandom()); + + kp = kpg.generateKeyPair(); + + try + { + keyGen.init(new KEMExtractSpec(kp.getPrivate(), secEnc1.getEncapsulation(), "AES")); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("key generator locked to " + spec.getName(), e.getMessage()); + } + + try + { + keyGen.init(new KEMGenerateSpec(kp.getPublic(), "AES")); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("key generator locked to " + spec.getName(), e.getMessage()); + } + } + + public void testRestrictedCipher() + throws Exception + { + doTestRestrictedCipher(MLKEMParameterSpec.ml_kem_512, MLKEMParameterSpec.ml_kem_1024, new byte[16]); + doTestRestrictedCipher(MLKEMParameterSpec.ml_kem_768, MLKEMParameterSpec.ml_kem_1024, new byte[24]); + doTestRestrictedCipher(MLKEMParameterSpec.ml_kem_1024, MLKEMParameterSpec.ml_kem_512, new byte[32]); + } + + private void doTestRestrictedCipher(MLKEMParameterSpec spec, MLKEMParameterSpec altSpec, byte[] keyBytes) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + assertEquals(spec.getName(), kpg.getAlgorithm()); + assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); + assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); + + Cipher cipher = Cipher.getInstance(spec.getName(), "BC"); + + assertEquals(spec.getName(), cipher.getAlgorithm()); + + cipher.init(Cipher.WRAP_MODE, kp.getPublic(), new SecureRandom()); + + byte[] wrapBytes = cipher.wrap(new SecretKeySpec(keyBytes, "AES")); + + cipher.init(Cipher.UNWRAP_MODE, kp.getPrivate()); + + Key unwrapKey = cipher.unwrap(wrapBytes, "AES", Cipher.SECRET_KEY); + + assertTrue(Arrays.areEqual(keyBytes, unwrapKey.getEncoded())); + + kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + kpg.initialize(altSpec, new SecureRandom()); + + kp = kpg.generateKeyPair(); + + try + { + cipher.init(Cipher.UNWRAP_MODE, kp.getPrivate()); + fail("no exception"); + } + catch (InvalidKeyException e) + { + assertEquals("cipher locked to " + spec.getName(), e.getMessage()); + } + + try + { + cipher.init(Cipher.WRAP_MODE, kp.getPublic(), new SecureRandom()); + fail("no exception"); + } + catch (InvalidKeyException e) + { + assertEquals("cipher locked to " + spec.getName(), e.getMessage()); + } + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MainProvKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MainProvKeyPairGeneratorTest.java new file mode 100644 index 0000000000..0d7404a54d --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MainProvKeyPairGeneratorTest.java @@ -0,0 +1,97 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +public abstract class MainProvKeyPairGeneratorTest + extends FlexiTest +{ + + protected KeyPairGenerator kpg; + + protected KeyFactory kf; + + protected final void performKeyPairEncodingTest(KeyPair keyPair) + { + performKeyPairEncodingTest(null, keyPair); + } + + protected final void performKeyPairEncodingTest(String name, KeyPair keyPair) + { + try + { + PublicKey pubKey = keyPair.getPublic(); + PrivateKey privKey = keyPair.getPrivate(); + + byte[] encPubKey = pubKey.getEncoded(); + byte[] encPrivKey = privKey.getEncoded(); + + X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encPubKey); + PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encPrivKey); + + PublicKey decPubKey = kf.generatePublic(pubKeySpec); + PrivateKey decPrivKey = kf.generatePrivate(privKeySpec); + + assertEquals(pubKey, decPubKey); + assertEquals(pubKey.getAlgorithm(), decPubKey.getAlgorithm()); + assertEquals(pubKey.hashCode(), decPubKey.hashCode()); + + assertEquals(privKey, decPrivKey); + assertEquals(privKey.getAlgorithm(), decPrivKey.getAlgorithm()); + assertEquals(privKey.hashCode(), decPrivKey.hashCode()); + + if (name != null) + { + KeyFactory nkf = KeyFactory.getInstance(name, "BC"); + + decPubKey = nkf.generatePublic(pubKeySpec); + decPrivKey = nkf.generatePrivate(privKeySpec); + + assertEquals(pubKey, decPubKey); + assertEquals(pubKey.getAlgorithm(), decPubKey.getAlgorithm()); + assertEquals(pubKey.hashCode(), decPubKey.hashCode()); + + assertEquals(privKey, decPrivKey); + assertEquals(privKey.getAlgorithm(), decPrivKey.getAlgorithm()); + assertEquals(privKey.hashCode(), decPrivKey.hashCode()); + } + checkSerialisation(pubKey); + checkSerialisation(privKey); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e); + } + } + + private void checkSerialisation(Key key) + throws IOException, ClassNotFoundException + { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(key); + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + Key inKey = (Key)oIn.readObject(); + + assertEquals(key, inKey); + assertEquals(key.getAlgorithm(), inKey.getAlgorithm()); + assertEquals(key.hashCode(), inKey.hashCode()); + } + +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MayoKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MayoKeyPairGeneratorTest.java new file mode 100644 index 0000000000..454722219c --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MayoKeyPairGeneratorTest.java @@ -0,0 +1,63 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Security; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.jcajce.spec.MayoParameterSpec; + +public class MayoKeyPairGeneratorTest + extends KeyPairGeneratorTest +{ + public static void main(String[] args) + throws Exception + { + MayoKeyPairGeneratorTest test = new MayoKeyPairGeneratorTest(); + test.setUp(); + test.testKeyFactory(); + test.testKeyPairEncoding(); + } + + protected void setUp() + { + super.setUp(); + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public void testKeyFactory() + throws Exception + { + kf = KeyFactory.getInstance("Mayo", "BCPQC"); + KeyFactory kf1 = KeyFactory.getInstance("MAYO_1", "BCPQC"); + KeyFactory kf2 = KeyFactory.getInstance("MAYO_2", "BCPQC"); + KeyFactory kf3 = KeyFactory.getInstance("MAYO_3", "BCPQC"); + KeyFactory kf5 = KeyFactory.getInstance("MAYO_5", "BCPQC"); + } + + public void testKeyPairEncoding() + throws Exception + { + MayoParameterSpec[] specs = + new MayoParameterSpec[] + { + MayoParameterSpec.mayo1, + MayoParameterSpec.mayo2, + MayoParameterSpec.mayo3, + MayoParameterSpec.mayo5 + }; + kf = KeyFactory.getInstance("Mayo", "BCPQC"); + + kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + for (int i = 0; i != specs.length; i++) + { + kpg.initialize(specs[i], new SecureRandom()); + performKeyPairEncodingTest(specs[i].getName(), kpg.generateKeyPair()); + } + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MayoTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MayoTest.java new file mode 100644 index 0000000000..58d433f0c3 --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/MayoTest.java @@ -0,0 +1,276 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.InvalidKeyException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Security; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import junit.framework.TestCase; +import org.bouncycastle.pqc.jcajce.interfaces.MayoKey; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.pqc.jcajce.spec.MayoParameterSpec; +import org.bouncycastle.util.Strings; + +public class MayoTest + extends TestCase +{ + public static void main(String[] args) + throws Exception + { + MayoTest test = new MayoTest(); + test.setUp(); + test.testMayo3(); + test.testMayo5(); + test.testMayoRandomSig(); + test.testPrivateKeyRecovery(); + test.testPublicKeyRecovery(); + test.testRestrictedKeyPairGen(); + } + + byte[] msg = Strings.toByteArray("Hello World!"); + + public void setUp() + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + } + + public void testPrivateKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo1, new RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("Mayo", "BCPQC"); + + MayoKey privKey = (MayoKey)kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + assertEquals(kp.getPrivate(), privKey); + assertEquals(kp.getPrivate().getAlgorithm(), privKey.getAlgorithm()); + assertEquals(kp.getPrivate().hashCode(), privKey.hashCode()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(privKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + MayoKey privKey2 = (MayoKey)oIn.readObject(); + + assertEquals(privKey, privKey2); + assertEquals(privKey.getAlgorithm(), privKey2.getAlgorithm()); + assertEquals(privKey.hashCode(), privKey2.hashCode()); + } + + public void testPublicKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo2, new MayoTest.RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("Mayo_2", "BCPQC"); + + MayoKey pubKey = (MayoKey)kFact.generatePublic(new X509EncodedKeySpec(kp.getPublic().getEncoded())); + + assertEquals(kp.getPublic(), pubKey); + assertEquals(kp.getPublic().getAlgorithm(), pubKey.getAlgorithm()); + assertEquals(kp.getPublic().hashCode(), pubKey.hashCode()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(pubKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + MayoKey pubKey2 = (MayoKey)oIn.readObject(); + + assertEquals(pubKey, pubKey2); + assertEquals(pubKey.getAlgorithm(), pubKey2.getAlgorithm()); + assertEquals(pubKey.hashCode(), pubKey2.hashCode()); + } + + public void testMayo5() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo5, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("MAYO_5", "BCPQC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("MAYO_5", "BCPQC"); + + assertEquals("MAYO_5", Strings.toUpperCase(sig.getAlgorithm())); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo1, new SecureRandom()); + + kp = kpg.generateKeyPair(); + + try + { + sig.initVerify(kp.getPublic()); + fail("no exception"); + } + catch (InvalidKeyException e) + { + assertEquals("signature configured for MAYO_5", e.getMessage()); + } + } + + public void testMayo3() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo3, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("MAYO_3", "BCPQC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("MAYO_3", "BCPQC"); + + assertEquals("MAYO_3", Strings.toUpperCase(sig.getAlgorithm())); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo5, new SecureRandom()); + + kp = kpg.generateKeyPair(); + + try + { + sig.initVerify(kp.getPublic()); + fail("no exception"); + } + catch (InvalidKeyException e) + { + assertEquals("signature configured for MAYO_3", e.getMessage()); + } + } + + public void testRestrictedKeyPairGen() + throws Exception + { + doTestRestrictedKeyPairGen(MayoParameterSpec.mayo1); + doTestRestrictedKeyPairGen(MayoParameterSpec.mayo2); + doTestRestrictedKeyPairGen(MayoParameterSpec.mayo3); + doTestRestrictedKeyPairGen(MayoParameterSpec.mayo5); + } + + private void doTestRestrictedKeyPairGen(MayoParameterSpec spec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BCPQC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); + assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); + + //kpg = KeyPairGenerator.getInstance(spec.getName(), "BCPQC"); + +// try +// { +// kpg.initialize(altSpec, new SecureRandom()); +// fail("no exception"); +// } +// catch (InvalidAlgorithmParameterException e) +// { +// assertEquals("key pair generator locked to " + spec.getName(), e.getMessage()); +// } + } + + public void testMayoRandomSig() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Mayo", "BCPQC"); + + kpg.initialize(MayoParameterSpec.mayo2, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("Mayo", "BCPQC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("Mayo", "BCPQC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + private static class RiggedRandom + extends SecureRandom + { + public void nextBytes(byte[] bytes) + { + for (int i = 0; i != bytes.length; i++) + { + bytes[i] = (byte)(i & 0xff); + } + } + } + +} + diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/RainbowKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/RainbowKeyPairGeneratorTest.java deleted file mode 100644 index 44ad589782..0000000000 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/RainbowKeyPairGeneratorTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider.test; - -import java.security.KeyFactory; -import java.security.KeyPairGenerator; -import java.security.SecureRandom; - -import org.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; - -/** - * KeyFactory/KeyPairGenerator tests for Falcon with BCPQC provider. - */ -public class RainbowKeyPairGeneratorTest - extends KeyPairGeneratorTest -{ - protected void setUp() - { - super.setUp(); - } - - public void testKeyFactory() - throws Exception - { - kf = KeyFactory.getInstance("Rainbow", "BCPQC"); - } - - public void testKeyPairEncoding() - throws Exception - { - RainbowParameterSpec[] specs = - new RainbowParameterSpec[] - { - RainbowParameterSpec.rainbowIIIclassic, - RainbowParameterSpec.rainbowIIIcircumzenithal, - RainbowParameterSpec.rainbowIIIcompressed, - RainbowParameterSpec.rainbowVclassic, - RainbowParameterSpec.rainbowVcircumzenithal, - RainbowParameterSpec.rainbowVcompressed, - }; - kf = KeyFactory.getInstance("Rainbow", "BCPQC"); - - kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - - for (int i = 0; i != specs.length; i++) - { - kpg.initialize(specs[i], new SecureRandom()); - performKeyPairEncodingTest(kpg.generateKeyPair()); - } - } - -} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/RainbowTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/RainbowTest.java deleted file mode 100644 index a6fd39d1ab..0000000000 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/RainbowTest.java +++ /dev/null @@ -1,393 +0,0 @@ -package org.bouncycastle.pqc.jcajce.provider.test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SecureRandom; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import junit.framework.TestCase; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.pqc.jcajce.interfaces.RainbowKey; -import org.bouncycastle.pqc.jcajce.interfaces.RainbowPrivateKey; -import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; -import org.bouncycastle.pqc.jcajce.spec.RainbowParameterSpec; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Hex; - -public class RainbowTest - extends TestCase -{ - byte[] msg = Strings.toByteArray("Hello World!"); - - public void setUp() - { - if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) - { - Security.addProvider(new BouncyCastlePQCProvider()); - } - } - - public void testPrivateKeyRecovery() - throws Exception - { - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - - kpg.initialize(RainbowParameterSpec.rainbowIIIclassic, new RainbowTest.RiggedRandom()); - - KeyPair kp = kpg.generateKeyPair(); - - KeyFactory kFact = KeyFactory.getInstance("Rainbow", "BCPQC"); - - RainbowKey privKey = (RainbowKey)kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); - - assertEquals(kp.getPrivate(), privKey); - assertEquals(kp.getPrivate().getAlgorithm(), privKey.getAlgorithm()); - assertEquals(kp.getPrivate().hashCode(), privKey.hashCode()); - - assertEquals(((RainbowPrivateKey)kp.getPrivate()).getPublicKey(), ((RainbowPrivateKey)privKey).getPublicKey()); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ObjectOutputStream oOut = new ObjectOutputStream(bOut); - - oOut.writeObject(privKey); - - oOut.close(); - - ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); - - RainbowKey privKey2 = (RainbowKey)oIn.readObject(); - - assertEquals(privKey, privKey2); - assertEquals(privKey.getAlgorithm(), privKey2.getAlgorithm()); - assertEquals(privKey.hashCode(), privKey2.hashCode()); - - assertEquals(kp.getPublic(), ((RainbowPrivateKey)privKey2).getPublicKey()); - assertEquals(((RainbowPrivateKey)privKey).getPublicKey(), ((RainbowPrivateKey)privKey2).getPublicKey()); - } - - public void testPublicKeyRecovery() - throws Exception - { - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - - kpg.initialize(RainbowParameterSpec.rainbowVclassic, new RainbowTest.RiggedRandom()); - - KeyPair kp = kpg.generateKeyPair(); - - KeyFactory kFact = KeyFactory.getInstance("Rainbow", "BCPQC"); - - RainbowKey pubKey = (RainbowKey)kFact.generatePublic(new X509EncodedKeySpec(kp.getPublic().getEncoded())); - - assertEquals(kp.getPublic(), pubKey); - assertEquals(kp.getPublic().getAlgorithm(), pubKey.getAlgorithm()); - assertEquals(kp.getPublic().hashCode(), pubKey.hashCode()); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ObjectOutputStream oOut = new ObjectOutputStream(bOut); - - oOut.writeObject(pubKey); - - oOut.close(); - - ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); - - RainbowKey pubKey2 = (RainbowKey)oIn.readObject(); - - assertEquals(pubKey, pubKey2); - assertEquals(pubKey.getAlgorithm(), pubKey2.getAlgorithm()); - assertEquals(pubKey.hashCode(), pubKey2.hashCode()); - } - - public void testRainbowIIIclassic() - throws Exception - { - doConfSigTest("Rainbow-III-Classic", RainbowParameterSpec.rainbowIIIclassic, RainbowParameterSpec.rainbowVclassic); - } - - public void testRainbowIIIcircum() - throws Exception - { - doConfSigTest("Rainbow-III-Circumzenithal", RainbowParameterSpec.rainbowIIIcircumzenithal, RainbowParameterSpec.rainbowVclassic); - } - - public void testRainbowIIIcomp() - throws Exception - { - doConfSigTest("Rainbow-III-Compressed", RainbowParameterSpec.rainbowIIIcompressed, RainbowParameterSpec.rainbowVclassic); - } - - public void testRainbowVclassic() - throws Exception - { - doConfSigTest("Rainbow-V-Classic", RainbowParameterSpec.rainbowVclassic, RainbowParameterSpec.rainbowIIIclassic); - } - - public void testRainbowVcircum() - throws Exception - { - doConfSigTest("Rainbow-V-Circumzenithal", RainbowParameterSpec.rainbowVcircumzenithal, RainbowParameterSpec.rainbowIIIclassic); - } - - public void testRainbowVcompressed() - throws Exception - { - doConfSigTest("Rainbow-V-Compressed", RainbowParameterSpec.rainbowVcompressed, RainbowParameterSpec.rainbowIIIclassic); - } - - private void doConfSigTest(String algorithmName, AlgorithmParameterSpec algSpec, AlgorithmParameterSpec altSpec) - throws Exception - { - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - - kpg.initialize(algSpec, new SecureRandom()); - - KeyPair kp = kpg.generateKeyPair(); - - Signature sig = Signature.getInstance("Rainbow", "BCPQC"); - - sig.initSign(kp.getPrivate(), new SecureRandom()); - - sig.update(msg, 0, msg.length); - - byte[] s = sig.sign(); - - sig = Signature.getInstance(algorithmName, "BCPQC"); - - assertEquals(Strings.toUpperCase(algorithmName), Strings.toUpperCase(sig.getAlgorithm())); - - sig.initVerify(kp.getPublic()); - - sig.update(msg, 0, msg.length); - - assertTrue(sig.verify(s)); - - kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - - kpg.initialize(altSpec, new SecureRandom()); - - kp = kpg.generateKeyPair(); - - try - { - sig.initVerify(kp.getPublic()); - fail("no exception"); - } - catch (InvalidKeyException e) - { - assertEquals("signature configured for " + Strings.toUpperCase(algorithmName), e.getMessage()); - } - } - - public void testRestrictedKeyPairGen() - throws Exception - { - doTestRestrictedKeyPairGen(RainbowParameterSpec.rainbowIIIclassic, RainbowParameterSpec.rainbowVclassic); - doTestRestrictedKeyPairGen(RainbowParameterSpec.rainbowIIIcircumzenithal, RainbowParameterSpec.rainbowVclassic); - doTestRestrictedKeyPairGen(RainbowParameterSpec.rainbowIIIcompressed, RainbowParameterSpec.rainbowVclassic); - doTestRestrictedKeyPairGen(RainbowParameterSpec.rainbowVclassic, RainbowParameterSpec.rainbowIIIclassic); - doTestRestrictedKeyPairGen(RainbowParameterSpec.rainbowVcircumzenithal, RainbowParameterSpec.rainbowIIIclassic); - doTestRestrictedKeyPairGen(RainbowParameterSpec.rainbowVcompressed, RainbowParameterSpec.rainbowIIIclassic); - } - - private void doTestRestrictedKeyPairGen(RainbowParameterSpec spec, RainbowParameterSpec altSpec) - throws Exception - { - KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BCPQC"); - - kpg.initialize(spec, new SecureRandom()); - - KeyPair kp = kpg.generateKeyPair(); - - assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); - assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); - - kpg = KeyPairGenerator.getInstance(spec.getName(), "BCPQC"); - - try - { - kpg.initialize(altSpec, new SecureRandom()); - fail("no exception"); - } - catch (InvalidAlgorithmParameterException e) - { - assertEquals("key pair generator locked to " + spec.getName(), e.getMessage()); - } - } - - public void testRainbowRandomSig() - throws Exception - { - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - - kpg.initialize(RainbowParameterSpec.rainbowIIIcompressed, new SecureRandom()); - - KeyPair kp = kpg.generateKeyPair(); - - Signature sig = Signature.getInstance("Rainbow", "BCPQC"); - - sig.initSign(kp.getPrivate(), new SecureRandom()); - - sig.update(msg, 0, msg.length); - - byte[] s = sig.sign(); - - sig = Signature.getInstance("Rainbow", "BCPQC"); - - sig.initVerify(kp.getPublic()); - - sig.update(msg, 0, msg.length); - - assertTrue(sig.verify(s)); - } - - /** - * count = 0 - * seed = 061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1 - * No public key as it's a bit "big". - */ - public void testRainbowKATSigCompressedIII() - throws Exception - { - byte[] privK = Hex.decode("8626ED79D451140800E03B59B956F8210E556067407D13DC90FA9E8B872BFB8F7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2D"); - byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode(" 451F524FEF128EDBE93814C041D5EDD2C8A0226E05E13942B5B832C864A96184261745A5B530D09D51773C3E6F3C8297E3A8E6E4DBD23E56BDA10B5C3A491F7A5D9EA819D712FC6565429F965FD7264041E5F2007085DE29930B20B187BB9E5BC4BCAC01C35CABC97F5EC6476C42138C3D18A1DBD23BA22B31B21BDBE5421AC1B837A793123C80E2B5028A0763872E76E45F6AA9D675E2D667E6F68024D5EF1143D21713"); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); - - kpg.initialize(RainbowParameterSpec.rainbowIIIcompressed, katRandom); - - KeyPair kp = kpg.generateKeyPair(); - - PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); - - ASN1OctetString privEnc = ASN1OctetString.getInstance(privInfo.parsePrivateKey()); - - assertTrue(Arrays.areEqual(privK, privEnc.getOctets())); - - doKatTest(kp, msg, s, katRandom); - } - - public void testRainbowKATSigCompressedV() - throws Exception - { - byte[] privK = Hex.decode("8626ED79D451140800E03B59B956F8210E556067407D13DC90FA9E8B872BFB8F7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2D"); - byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode(" D1F97D1310F57AF3509F66307985B7F341234CE8F7516E4B61F9E53B1282CE66B9526321C66954E1753D1A9C8BA4012B9C5A211F0287C72705141F71A9AAEC350E81F6EC67ED10E1BD61DCDFA4AC87553563E0FEE31927E5877741D5DCDF03C44E50CF80BB3D15856AF49F2C68A7EDAC52FD2957F96A7113DCE51785EDF0AB8538C1EAAD694E8514CDC7872664412BCF9884C185BADE87781016826E32E08C1EC6275C6F8588A11FF6575D704505D4AB794D047BEC1104C00DAD3BCFC2DE42267B3552BD74090543C9478050169FCCFBC0E9BA11"); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); - - kpg.initialize(RainbowParameterSpec.rainbowVcompressed, katRandom); - - KeyPair kp = kpg.generateKeyPair(); - - PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded()); - - ASN1OctetString privEnc = ASN1OctetString.getInstance(privInfo.parsePrivateKey()); - - assertTrue(Arrays.areEqual(privK, privEnc.getOctets())); - - doKatTest(kp, msg, s, katRandom); - } - - public void testRainbowKATSigClassicIII() - throws Exception - { - byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode("6033C99A65042BE545EED707341BD14F73CA178F2A5B244A87E847DCAB29A9086676D7A7A4B35E3904A9EDD7B399B1BD104A19373A415029BCCD4C707B416EED683F13A9189EF0BDC151116CBF6D6A9D4BC019FAA58FD770B6F567A410C700B48C488A375C33866F3FEBB8DEDF239C64FF9A36F092E3D6192B9A0726B06672A540A892FA7BA47DBE7F3E66BF394ED328A107B8EDCEB39AD2E43C6EE441F39ECE871397AC"); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); - - kpg.initialize(RainbowParameterSpec.rainbowIIIclassic, katRandom); - - doKatTest(kpg.generateKeyPair(), msg, s, katRandom); - } - - public void testRainbowKATSigClassicV() - throws Exception - { - byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode("15040F890F2BF56F8B04B1D8B9BA21D303C490868A0A10C9FFC04A2AF9D1F3122D14F7C6D5E0B1D914CC23D763C061B2FD34DF8CB0D75F12111244241FA7A136C440C2D40782390FE5EF3C15ED5539285B437DA0447E361853E98982E1F16AA0506BABFFBBA8282BAA0A307C50EBA79596AD26EBECE897E7B4DE3B601A515C08775526522915ED03F08BAA23AFED4224C8E50ED67FBCCFAB62C58872CE880C850D3A03F21B2703C5C085FA410A5FCB3559E50D6BBC6A06FABA309962F2922E0D014C5EB074090543C9478050169FCCFBC0E9BA11"); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); - - kpg.initialize(RainbowParameterSpec.rainbowVclassic, katRandom); - - doKatTest(kpg.generateKeyPair(), msg, s, katRandom); - } - - public void testRainbowKATSigCircumIII() - throws Exception - { - byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode("451F524FEF128EDBE93814C041D5EDD2C8A0226E05E13942B5B832C864A96184261745A5B530D09D51773C3E6F3C8297E3A8E6E4DBD23E56BDA10B5C3A491F7A5D9EA819D712FC6565429F965FD7264041E5F2007085DE29930B20B187BB9E5BC4BCAC01C35CABC97F5EC6476C42138C3D18A1DBD23BA22B31B21BDBE5421AC1B837A793123C80E2B5028A0763872E76E45F6AA9D675E2D667E6F68024D5EF1143D21713"); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); - - kpg.initialize(RainbowParameterSpec.rainbowIIIcircumzenithal, katRandom); - - doKatTest(kpg.generateKeyPair(), msg, s, katRandom); - } - - public void testRainbowKATSigCircumV() - throws Exception - { - byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); - byte[] s = Hex.decode("D1F97D1310F57AF3509F66307985B7F341234CE8F7516E4B61F9E53B1282CE66B9526321C66954E1753D1A9C8BA4012B9C5A211F0287C72705141F71A9AAEC350E81F6EC67ED10E1BD61DCDFA4AC87553563E0FEE31927E5877741D5DCDF03C44E50CF80BB3D15856AF49F2C68A7EDAC52FD2957F96A7113DCE51785EDF0AB8538C1EAAD694E8514CDC7872664412BCF9884C185BADE87781016826E32E08C1EC6275C6F8588A11FF6575D704505D4AB794D047BEC1104C00DAD3BCFC2DE42267B3552BD74090543C9478050169FCCFBC0E9BA11"); - KeyPairGenerator kpg = KeyPairGenerator.getInstance("Rainbow", "BCPQC"); - SecureRandom katRandom = new NISTSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"), null); - - kpg.initialize(RainbowParameterSpec.rainbowVcircumzenithal, katRandom); - - doKatTest(kpg.generateKeyPair(), msg, s, katRandom); - } - - private static void doKatTest(KeyPair kp, byte[] msg, byte[] s, SecureRandom katRandom) - throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException - { - Signature sig = Signature.getInstance("Rainbow", "BCPQC"); - - sig.initSign(kp.getPrivate(), katRandom); - - sig.update(msg, 0, msg.length); - - byte[] genS = sig.sign(); - - assertTrue(Arrays.areEqual(s, genS)); - - sig = Signature.getInstance("Rainbow", "BCPQC"); - - sig.initVerify(kp.getPublic()); - - sig.update(msg, 0, msg.length); - - assertTrue(sig.verify(s)); - } - - private static class RiggedRandom - extends SecureRandom - { - public void nextBytes(byte[] bytes) - { - for (int i = 0; i != bytes.length; i++) - { - bytes[i] = (byte)(i & 0xff); - } - } - } -} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SLHDSAKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SLHDSAKeyPairGeneratorTest.java new file mode 100644 index 0000000000..cd3195acad --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SLHDSAKeyPairGeneratorTest.java @@ -0,0 +1,232 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.security.InvalidAlgorithmParameterException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Security; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.SLHDSAPrivateKey; +import org.bouncycastle.jcajce.interfaces.SLHDSAPublicKey; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; + + +/** + * KeyFactory/KeyPairGenerator tests for SLHDSA with the BC provider. + */ +public class SLHDSAKeyPairGeneratorTest + extends MainProvKeyPairGeneratorTest +{ + + protected void setUp() + { + super.setUp(); + Security.addProvider(new BouncyCastleProvider()); + } + + public void testKeyFactory() + throws Exception + { + kf = KeyFactory.getInstance("SLH-DSA", "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_sha2_128s.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_sha2_128f.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_sha2_192s.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_sha2_192f.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_sha2_256s.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_sha2_256f.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_shake_128s.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_shake_128f.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_shake_192s.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_shake_192f.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_shake_256s.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_slh_dsa_shake_256f.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256.getId(), "BC"); + kf = KeyFactory.getInstance(NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256.getId(), "BC"); + } + + public void testKeySpecs() + throws Exception + { + kf = KeyFactory.getInstance("SLH-DSA", "BC"); + kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + KeyPair kp = kpg.generateKeyPair(); + + PKCS8EncodedKeySpec privSpec = kf.getKeySpec(kp.getPrivate(), PKCS8EncodedKeySpec.class); + + assertTrue(Arrays.areEqual(kp.getPrivate().getEncoded(), privSpec.getEncoded())); + + X509EncodedKeySpec pubSpec = kf.getKeySpec(kp.getPublic(), X509EncodedKeySpec.class); + + assertTrue(Arrays.areEqual(kp.getPublic().getEncoded(), pubSpec.getEncoded())); + } + + public void testKeyPairEncoding() + throws Exception + { + kf = KeyFactory.getInstance("HASH-SLH-DSA", "BC"); + + SLHDSAParameterSpec[] params = + { + SLHDSAParameterSpec.slh_dsa_sha2_128s, + SLHDSAParameterSpec.slh_dsa_sha2_128f, + SLHDSAParameterSpec.slh_dsa_sha2_192s, + SLHDSAParameterSpec.slh_dsa_sha2_192f, + SLHDSAParameterSpec.slh_dsa_sha2_256s, + SLHDSAParameterSpec.slh_dsa_sha2_256f, + + SLHDSAParameterSpec.slh_dsa_shake_128s, + SLHDSAParameterSpec.slh_dsa_shake_128f, + SLHDSAParameterSpec.slh_dsa_shake_192s, + SLHDSAParameterSpec.slh_dsa_shake_192f, + SLHDSAParameterSpec.slh_dsa_shake_256s, + SLHDSAParameterSpec.slh_dsa_shake_256f, + + SLHDSAParameterSpec.slh_dsa_sha2_128s_with_sha256, + SLHDSAParameterSpec.slh_dsa_sha2_128f_with_sha256, + SLHDSAParameterSpec.slh_dsa_sha2_192s_with_sha512, + SLHDSAParameterSpec.slh_dsa_sha2_192f_with_sha512, + SLHDSAParameterSpec.slh_dsa_sha2_256s_with_sha512, + SLHDSAParameterSpec.slh_dsa_sha2_256f_with_sha512, + + SLHDSAParameterSpec.slh_dsa_shake_128s_with_shake128, + SLHDSAParameterSpec.slh_dsa_shake_128f_with_shake128, + SLHDSAParameterSpec.slh_dsa_shake_192s_with_shake256, + SLHDSAParameterSpec.slh_dsa_shake_192f_with_shake256, + SLHDSAParameterSpec.slh_dsa_shake_256s_with_shake256, + SLHDSAParameterSpec.slh_dsa_shake_256f_with_shake256, + }; + + // expected object identifiers + ASN1ObjectIdentifier[] oids = + { + NISTObjectIdentifiers.id_slh_dsa_sha2_128s, + NISTObjectIdentifiers.id_slh_dsa_sha2_128f, + NISTObjectIdentifiers.id_slh_dsa_sha2_192s, + NISTObjectIdentifiers.id_slh_dsa_sha2_192f, + NISTObjectIdentifiers.id_slh_dsa_sha2_256s, + NISTObjectIdentifiers.id_slh_dsa_sha2_256f, + NISTObjectIdentifiers.id_slh_dsa_shake_128s, + NISTObjectIdentifiers.id_slh_dsa_shake_128f, + NISTObjectIdentifiers.id_slh_dsa_shake_192s, + NISTObjectIdentifiers.id_slh_dsa_shake_192f, + NISTObjectIdentifiers.id_slh_dsa_shake_256s, + NISTObjectIdentifiers.id_slh_dsa_shake_256f, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256 + }; + + kpg = KeyPairGenerator.getInstance("HASH-SLH-DSA", "BC"); + + for (int i = 0; i != params.length; i++) + { + kpg.initialize(params[i], new SecureRandom()); + KeyPair keyPair = kpg.generateKeyPair(); + performKeyPairEncodingTest(keyPair); + performKeyPairEncodingTest(params[i].getName(), keyPair); + performKeyPairEncodingTest(oids[i].getId(), keyPair); + assertNotNull(((SLHDSAPrivateKey)keyPair.getPrivate()).getParameterSpec()); + assertNotNull(((SLHDSAPublicKey)keyPair.getPublic()).getParameterSpec()); + assertEquals(oids[i], SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()).getAlgorithm().getAlgorithm()); + assertTrue(oids[i].toString(), Arrays.areEqual(((SLHDSAPublicKey)keyPair.getPublic()).getPublicData(), ((SLHDSAPrivateKey)keyPair.getPrivate()).getPublicKey().getPublicData())); + } + + // + // a bit of a cheat as we just look for "getName()" on the parameter spec. + // + for (int i = 0; i != params.length; i++) + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(params[i].getName(), "BC"); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase(params[i].getName()))); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toUpperCase(params[i].getName()))); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase(params[i].getName())), new SecureRandom()); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toUpperCase(params[i].getName())), new SecureRandom()); + } + + try + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(params[0].getName(), "BC"); + kpg.initialize(new ECNamedCurveGenParameterSpec(Strings.toLowerCase("Not Valid"))); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + assertEquals("unknown parameter set name: NOT VALID", e.getMessage()); + } + } + + public void testCrossNaming() + throws Exception + { + ASN1ObjectIdentifier[] nistOids = new ASN1ObjectIdentifier[] + { + NISTObjectIdentifiers.id_slh_dsa_sha2_128s, + NISTObjectIdentifiers.id_slh_dsa_sha2_128f, + NISTObjectIdentifiers.id_slh_dsa_shake_128s, + NISTObjectIdentifiers.id_slh_dsa_shake_128f, + NISTObjectIdentifiers.id_slh_dsa_sha2_192s, + NISTObjectIdentifiers.id_slh_dsa_sha2_192f, + NISTObjectIdentifiers.id_slh_dsa_shake_192s, + NISTObjectIdentifiers.id_slh_dsa_shake_192f, + NISTObjectIdentifiers.id_slh_dsa_sha2_256s, + NISTObjectIdentifiers.id_slh_dsa_sha2_256f, + NISTObjectIdentifiers.id_slh_dsa_shake_256s, + NISTObjectIdentifiers.id_slh_dsa_shake_256f, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256 + }; + + for (int i = 0; i != nistOids.length; i++) + { + KeyPairGenerator ml_dsa_kp = KeyPairGenerator.getInstance(nistOids[i].getId(), "BC"); + Signature ml_dsa_sig = deriveSignatureFromKey(ml_dsa_kp.generateKeyPair().getPrivate()); + } + } + + private static Signature deriveSignatureFromKey(Key key) + throws Exception + { + return Signature.getInstance(key.getAlgorithm(), "BC"); + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SLHDSATest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SLHDSATest.java new file mode 100644 index 0000000000..e1247839dd --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SLHDSATest.java @@ -0,0 +1,662 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.AlgorithmParameters; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Security; +import java.security.Signature; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.jcajce.interfaces.SLHDSAKey; +import org.bouncycastle.jcajce.interfaces.SLHDSAPrivateKey; +import org.bouncycastle.jcajce.spec.ContextParameterSpec; +import org.bouncycastle.jcajce.spec.SLHDSAParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.crypto.slhdsa.SLHDSAParameters; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; + +/** + * Test cases for the use of SLH-DSA with the provider. + */ +public class SLHDSATest + extends TestCase +{ + // test vector courtesy the "Yawning Angel" GO implementation and the SUPERCOP reference implementation. + static private final byte[] msg = Strings.toByteArray("Cthulhu Fthagn --What a wonderful phrase!Cthulhu Fthagn --Say it and you're crazed!"); + + static private final String[] names = new String[] { + "SLH-DSA-SHA2-128F", + "SLH-DSA-SHA2-128S", + "SLH-DSA-SHA2-192F", + "SLH-DSA-SHA2-192S", + "SLH-DSA-SHA2-256F", + "SLH-DSA-SHA2-256S", + "SLH-DSA-SHAKE-128F", + "SLH-DSA-SHAKE-128S", + "SLH-DSA-SHAKE-192F", + "SLH-DSA-SHAKE-192S", + "SLH-DSA-SHAKE-256F", + "SLH-DSA-SHAKE-256S", + "SLH-DSA-SHA2-128F-WITH-SHA256", + "SLH-DSA-SHA2-128S-WITH-SHA256", + "SLH-DSA-SHA2-192F-WITH-SHA512", + "SLH-DSA-SHA2-192S-WITH-SHA512", + "SLH-DSA-SHA2-256F-WITH-SHA512", + "SLH-DSA-SHA2-256S-WITH-SHA512", + "SLH-DSA-SHAKE-128F-WITH-SHAKE128", + "SLH-DSA-SHAKE-128S-WITH-SHAKE128", + "SLH-DSA-SHAKE-192F-WITH-SHAKE256", + "SLH-DSA-SHAKE-192S-WITH-SHAKE256", + "SLH-DSA-SHAKE-256F-WITH-SHAKE256", + "SLH-DSA-SHAKE-256S-WITH-SHAKE256", + }; + + public void setUp() + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + Security.addProvider(new BouncyCastleProvider()); + } + + public void testParametersAndParamSpecs() + throws Exception + { + for (int i = 0; i != names.length; i++) + { + assertEquals(names[i], SLHDSAParameterSpec.fromName(names[i]).getName()); + } + + SLHDSAParameters slhdsaParameters[] = new SLHDSAParameters[] + { + SLHDSAParameters.sha2_128f, + SLHDSAParameters.sha2_128s, + SLHDSAParameters.sha2_192f, + SLHDSAParameters.sha2_192s, + SLHDSAParameters.sha2_256f, + SLHDSAParameters.sha2_256s, + SLHDSAParameters.shake_128f, + SLHDSAParameters.shake_128s, + SLHDSAParameters.shake_192f, + SLHDSAParameters.shake_192s, + SLHDSAParameters.shake_256f, + SLHDSAParameters.shake_256s, + SLHDSAParameters.sha2_128f_with_sha256, + SLHDSAParameters.sha2_128s_with_sha256, + SLHDSAParameters.sha2_192f_with_sha512, + SLHDSAParameters.sha2_192s_with_sha512, + SLHDSAParameters.sha2_256f_with_sha512, + SLHDSAParameters.sha2_256s_with_sha512, + SLHDSAParameters.shake_128f_with_shake128, + SLHDSAParameters.shake_128s_with_shake128, + SLHDSAParameters.shake_192f_with_shake256, + SLHDSAParameters.shake_192s_with_shake256, + SLHDSAParameters.shake_256f_with_shake256, + SLHDSAParameters.shake_256s_with_shake256 + }; + + for (int i = 0; i != names.length; i++) + { + assertEquals(names[i], SLHDSAParameterSpec.fromName(slhdsaParameters[i].getName()).getName()); + } + } + + public void testKeyFactory() + throws Exception + { + KeyPairGenerator kpGen44 = KeyPairGenerator.getInstance("ML-DSA-44"); + KeyPair kp44 = kpGen44.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("HASH-SLH-DSA", "BC"); + + ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[] { + NISTObjectIdentifiers.id_slh_dsa_sha2_128f, + NISTObjectIdentifiers.id_slh_dsa_sha2_128s, + NISTObjectIdentifiers.id_slh_dsa_sha2_192f, + NISTObjectIdentifiers.id_slh_dsa_sha2_192s, + NISTObjectIdentifiers.id_slh_dsa_sha2_256f, + NISTObjectIdentifiers.id_slh_dsa_sha2_256s, + NISTObjectIdentifiers.id_slh_dsa_shake_128f, + NISTObjectIdentifiers.id_slh_dsa_shake_128s, + NISTObjectIdentifiers.id_slh_dsa_shake_192f, + NISTObjectIdentifiers.id_slh_dsa_shake_192s, + NISTObjectIdentifiers.id_slh_dsa_shake_256f, + NISTObjectIdentifiers.id_slh_dsa_shake_256s, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128f_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_128s_with_sha256, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_192s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256f_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_sha2_256s_with_sha512, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128f_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_128s_with_shake128, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192f_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_192s_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256f_with_shake256, + NISTObjectIdentifiers.id_hash_slh_dsa_shake_256s_with_shake256, + }; + + for (int i = 0; i != names.length; i++) + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance(names[i]); + KeyPair kp = kpGen.generateKeyPair(); + + tryKeyFact(KeyFactory.getInstance(names[i], "BC"), kp, kp44, "2.16.840.1.101.3.4.3.17"); + tryKeyFact(KeyFactory.getInstance(oids[i].toString(), "BC"), kp, kp44, "2.16.840.1.101.3.4.3.17"); + } + } + + private void tryKeyFact(KeyFactory kFact, KeyPair kpValid, KeyPair kpInvalid, String oid) + throws Exception + { + kFact.generatePrivate(new PKCS8EncodedKeySpec(kpValid.getPrivate().getEncoded())); + kFact.generatePublic(new X509EncodedKeySpec(kpValid.getPublic().getEncoded())); + + try + { + kFact.generatePrivate(new PKCS8EncodedKeySpec(kpInvalid.getPrivate().getEncoded())); + fail("no exception"); + } + catch (InvalidKeySpecException e) + { + assertEquals("incorrect algorithm OID for key: " + oid, e.getMessage()); + } + try + { + kFact.generatePublic(new X509EncodedKeySpec(kpInvalid.getPublic().getEncoded())); + fail("no exception"); + } + catch (InvalidKeySpecException e) + { + assertEquals("incorrect algorithm OID for key: " + oid, e.getMessage()); + } + } + +// public void testSphincsDefaultKeyGen() +// throws Exception +// { +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); +// +// kpg.initialize(new SLHDSAKeyGenParameterSpec(), new RiggedRandom()); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// SLHDSAKey pub = (SLHDSAKey)kp.getPublic(); +// +// assertTrue(Arrays.areEqual(expSha2Pub, pub.getKeyData())); +// +// SLHDSAKey priv = (SLHDSAKey)kp.getPrivate(); +// +// assertTrue(Arrays.areEqual(expSha2Priv, priv.getKeyData())); +// +// KeyFactory keyFact = KeyFactory.getInstance("SLH-DSA", "BC"); +// +// SLHDSAKey pub2 = (SLHDSAKey)keyFact.generatePublic(new X509EncodedKeySpec(pub.getEncoded())); +// +// assertTrue(Arrays.areEqual(expSha2Pub, pub2.getKeyData())); +// +// SLHDSAKey priv2 = (SLHDSAKey)keyFact.generatePrivate(new PKCS8EncodedKeySpec(priv.getEncoded())); +// +// assertTrue(Arrays.areEqual(expSha2Priv, priv2.getKeyData())); +// } + + public void testPrivateKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, new RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("SLH-DSA", "BC"); + + SLHDSAKey privKey = (SLHDSAKey)kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(privKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + SLHDSAKey privKey2 = (SLHDSAKey)oIn.readObject(); + + assertEquals(privKey, privKey2); + + assertEquals(kp.getPublic(), ((SLHDSAPrivateKey)privKey2).getPublicKey()); + assertEquals(((SLHDSAPrivateKey)privKey).getPublicKey(), ((SLHDSAPrivateKey)privKey2).getPublicKey()); + } + + public void testPublicKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, new RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("SLH-DSA", "BC"); + + SLHDSAKey pubKey = (SLHDSAKey)kFact.generatePublic(new X509EncodedKeySpec(kp.getPublic().getEncoded())); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(pubKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + SLHDSAKey pubKey2 = (SLHDSAKey)oIn.readObject(); + + assertEquals(pubKey, pubKey2); + } + +// public void testSphincsDefaultSha2KeyGen() +// throws Exception +// { +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); +// +// kpg.initialize(new SLHDSAKeyGenParameterSpec(SLHDSAKeyGenParameterSpec.SHA512_256), new RiggedRandom()); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// SLHDSAKey pub = (SLHDSAKey)kp.getPublic(); +// +// assertTrue(Arrays.areEqual(expSha2Pub, pub.getKeyData())); +// +// SLHDSAKey priv = (SLHDSAKey)kp.getPrivate(); +// +// assertTrue(Arrays.areEqual(expSha2Priv, priv.getKeyData())); +// +// KeyFactory keyFact = KeyFactory.getInstance("SLH-DSA", "BC"); +// +// SLHDSAKey pub2 = (SLHDSAKey)keyFact.generatePublic(new X509EncodedKeySpec(pub.getEncoded())); +// +// assertTrue(Arrays.areEqual(expSha2Pub, pub2.getKeyData())); +// +// SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(pub2.getEncoded()); +// +// assertEquals(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_256), SLHDSAKeyParams.getInstance(pkInfo.getAlgorithm().getParameters()).getTreeDigest()); +// +// SLHDSAKey priv2 = (SLHDSAKey)keyFact.generatePrivate(new PKCS8EncodedKeySpec(priv.getEncoded())); +// +// assertTrue(Arrays.areEqual(expSha2Priv, priv2.getKeyData())); +// } +// +// public void testSphincsDefaultSha3KeyGen() +// throws Exception +// { +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); +// +// kpg.initialize(new SLHDSAKeyGenParameterSpec(SLHDSAKeyGenParameterSpec.SHA3_256), new RiggedRandom()); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// SLHDSAKey pub = (SLHDSAKey)kp.getPublic(); +// +// assertTrue(Arrays.areEqual(expSha3Pub, pub.getKeyData())); +// +// SLHDSAKey priv = (SLHDSAKey)kp.getPrivate(); +// +// assertTrue(Arrays.areEqual(expSha3Priv, priv.getKeyData())); +// +// KeyFactory keyFact = KeyFactory.getInstance("SLH-DSA", "BC"); +// +// SLHDSAKey pub2 = (SLHDSAKey)keyFact.generatePublic(new X509EncodedKeySpec(pub.getEncoded())); +// +// assertTrue(Arrays.areEqual(expSha3Pub, pub2.getKeyData())); +// +// SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(pub2.getEncoded()); +// +// assertEquals(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha3_256), SLHDSAKeyParams.getInstance(pkInfo.getAlgorithm().getParameters()).getTreeDigest()); +// +// SLHDSAKey priv2 = (SLHDSAKey)keyFact.generatePrivate(new PKCS8EncodedKeySpec(priv.getEncoded())); +// +// assertTrue(Arrays.areEqual(expSha3Priv, priv2.getKeyData())); +// } +// +// public void testSphincsSha2Signature() +// throws Exception +// { +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); +// +// kpg.initialize(new SLHDSAKeyGenParameterSpec(SLHDSAKeyGenParameterSpec.SHA512_256), new RiggedRandom()); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// Signature sig = Signature.getInstance("SHA512withSPHINCSPlus", "BC"); +// +// sig.initSign(kp.getPrivate()); +// +// sig.update(msg, 0, msg.length); +// +// byte[] s = sig.sign(); +// +// assertTrue(Arrays.areEqual(expSha2Sig, s)); +// } +// +// public void testSphincsSha3Signature() +// throws Exception +// { +// KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); +// +// kpg.initialize(new SLHDSAKeyGenParameterSpec(SLHDSAKeyGenParameterSpec.SHA3_256), new RiggedRandom()); +// +// KeyPair kp = kpg.generateKeyPair(); +// +// Signature sig = Signature.getInstance("SHA3-512withSPHINCSPlus", "BC"); +// +// sig.initSign(kp.getPrivate()); +// +// sig.update(msg, 0, msg.length); +// +// byte[] s = sig.sign(); +// +// assertTrue(Arrays.areEqual(expSha3Sig, s)); +// } +// + + + public void testSphincsRandomSigSHA2() + throws Exception + { + SecureRandom random = new FixedSecureRandom(Hex.decode("7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E4711E95F8A383854BA16A5DD3E25FF71D3" + + "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1")); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, random); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new FixedSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"))); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + byte[] expected = Hex.decode("7c65a4abed5a4926316228c52d815b0086c8fe9991254a563db365e340d056dabe5b45ce9e46f8c64fe65644d3874ccc9ce314b2d12d4903188c110fd21a6e548aa995f2c6508be8b60d620a906a0c3e394f31003ee12576d9847c508125058d1f030dd91c5da0026190f3b0f5d18051621c87c0334c644552ed94dfd8868a13ad90d67471f6ab3891a0a8a3a374500faf30f22c56bde568a89736d0a03203a23ca48135c86939f4e9e3ece6e3be79e18d33bed0b3ce7ee69922e08c0a7ecb1375ec93b0393b7dd4a3d64a8c030d3e7bf144666fbb67400fd38fb3b788460eed49439fb2093a01c21cdcef6f2ddfe299a3bd3d675949c3c04390a9f39c1a0f4e99e6c49cc8fa3728c0b9fdffddcf560b791c00e41a09c3baf99b192d519bb6e095045795ecaf4299bd286fdcb27045ab863888807361a7497f24e014618376041a49049fdb572b19d0da9ac4d35a7fb6a9d18cffe0f6edde17be904747fced7b670d7b0aa8f4706facd6e1fda80b08f62fe2033889bbe15e40995f71dac567b962927c16a08c1c2141e5d5eab881306754c7367849195538a8c05eef8bd1036962aa6a227cdc3772d3f9c142f7f74661c2daf6a094948765247a0c760851b731077496222121b5e7c852ab0021d37a4743242d96874d6a58ccfe07490415b482de7ab164dfb19056c93bca1c0260733f93ca7294e25c7bb117aa37101d705806ac8558d3ea9abf90a500081b77b657c515e2eca4b3058a3e9b63fa8b7a83d0be55828fa4f12e7cf663624224026ae8935f1b99b92128c5ef154080f66cd361c22d020dea778aa400011d212900a730e45039dbaf9f92ab4cb02aea28f1ea0ea456c399017b1a7ed410874aebdaa94cd8f54f16abd4b0193614c5b2f4d28bd3fac84e4881c1c92db162d9a441bbcf668b8acb050721ef22e79c7f9fe8675dc3501c7dfeb8f691d5ce390905d3bb0b523c1ba4694e0982669ec0a96aaf2b0f72df752dc627d71cecfc027e59d3ed440776831e2a8ea09436a504bd30c2b5bed18e4d5fe270bc5ec98e2ccec4f2f33b864f7912f45502b6aae2a9275e4049c7e872887a307cae2a0076b1c74cfbdc1ea8ba6947e683caaed96e84f451ef643e4d766e18ba6dd05e7ac46432957bc141deb48940261200444ad2e6b8b7fd5895c7a4e80b494bd1b648b145de29b718c7768f16dbfbb9dae1c6f991a57664aee425b12796d3739c18d532c9b3c37e8b634b16fff898aad91fa3b20853183dc6ecd535db1d953f421c2a195e781763f7c8117c6204b8f27d5ca74873c5755fdb96101b8a43e430207ff7d1a661bfac71f4261080df592a700f6c687b788230cabbd240f000fbeead9d5124dfaab331b709ab4165efc89a108fc5962a40989b8b413140196470e723ba6c45fa94dea7d4ed45c7fdbcbab9c3878493ee44ad35bbdbb77553ed2fd9e7a20dfa55f1875d232333935bd529eb1dd1d3a2f5f0b291c31d3231a719ec794059a89ecb2f12fd6bf8b227bcaabf0d43a9791f8f9190c31da568df59774be74178e08a80cd77ee6ed3024e3f530a4a32f2f36e2369b6a7e9d7411b2233e7a1e80e43b208324daa82bfea001311e00ebf9ce6631ab067e42a411597db903552261c289a619a459185a44a3cd26fd72d942df7a14434c0afc1a4bde8064315973d26c359c774bc3e4ca183c6f9b5c60c5a0566156ae9cea689e4ff1364b491d5b49a18712a468a2298994e006378bc9fc0eec56697b24dd0c4e2ca2d4bc52f3fa995df91b158ea726526700100067ec6a419571dc6a64bd5d526aad6f375891a04d8d81e2204bb3fdf7ce553aa90e07e02d3014bdc16b9a3d08f5d63880a36e13c30790ae3c7cfeb67061bce2138d1b9124a95b1f5c3c0f20aceeb7c311a03a0ae11574890dc998b54ec0145411c773340b96a5a6da30fd9ee7b56142414478e0a78f9defb187f8155e6632e13e272f8314621214e5d552dc4de3c8242d618919f000f0646a86ab494d9e0b840f13a457449e95e7803de4897b2545fccba471c44b8bbb760e84d173518672aadccccbe7e8cba8681e78067fe63bd83f26afc04fe93a00923fd73707682c377458bde04d4a8b4a0f350f6eac59c10c8ef739e4568c9044bd3d22182e881bbd8f727a45e1d7e666befe8c3640d325284c29bc22f3103ba468e9dbced0c9025a18248bd822d4652a756b6643b18590c6af2a3d77f72061d2ecefeeffb7fd0f770cd022922c72454d3bd4ceee3782901a5efcadd2b899a92a5099caf8ed66bf182d6457e3279811cb712cb269ae6a484626f27d86638c586da27fb6d5cd1fc2ecffe7603fefb346e76db89b9b714f3e0cfc3b5d7da68ab332371d3bad9dcdcdd294519374779b0fc0216f2a2c938403eea1a501906991c55233eeb63374273076a72f77144a06bb67cfa70babc7fe5f6739a9e808c7643bcad6f20da03f6071d7296d601a4142d2bb9f015c7adfde3765e011097e5ad4b29dbe47a50f24732370a1b471ed304e7d0eef3a2598e470e60d8d61af0f68b10a10543182abec726f27a452fdb4f669b02c908349e0da297a5af613f5e5d48ccd83ca4be57e6ff79ddf74b31ad8ae715abc8b1284e1caedce4928925301b538aedc0e38fcce10fc91968ba8a68302755b9f591bc179e3e31e5f820110328dcd58d46cfb71a1fc29b51f00dbc078fccfe00e6eeed39bb49a846e2f3674cf79b9b208d726ed0615a5498d8883bde48de23336a13935a38fb95a762ecf4ab53883dc434b4515e997a408494ea2f2abcda0fe24b4e9395de6cab707d924de8a3323de5057c8047f97ca27f9294aa319f760ba5f78a3c834e96bf89a3284cc584139503665a2813944fb3705aee1bb866cf5defa5b26c9d9169286fc56adf455f6c6838a2cf20358dcc081ae06079eed74b3fca1ff617e24fc2b8fbad7aad505ad1de9105bd59da2afe2cefceb4e7d7ba5cdcb3a43a40b06376ec8f7921e9b4abe571d2a62015107d107bc7f41b01a0eae20e9495b4b490cf9dd451201828e8ec4f9bd3840570b637adb24d979d361be7940fe570bfae66f0dcbabf1ae78fa516d106e2f980a74a39f10b1f00b1e96046eca047b471a212b26027b5b13853a2eded38d148e0d8c98be3aca48f0f581e9ae091830500217bd4809c5ca3d38f5939fafccd29aa875afc61fdcf96a1b8e207268693d8748068b9bfd73778f5338f772cf0287322cfff67f7a2f02f16fe0c5c0edfb0a4a10dbed23f62a6324c84cf06c3277c8dcbaae6dff3130d3af025a41e0fb06d954da1ed8ee8b551001b2ce6d5dd3593acb8fd641ad822ae8ee5fdb97fab411659dc6c99c8dab505637b497269c2f8be104db9f1e8ba3002866a2bbd8f6395e6652af64ec0153060f52602b280f64563483d41c8bfbd8057ebaae1c7d43deb5355ef4f4076c9d8460784eca581dc987758440624954704190d63e77ca6ae535b9c81a1dd84f3d8d45c574617d5af921ce78c10848477730d36c849603ac80100bbc27a245c38bf9d3c04df16b0e9fb4d7afb043273ca33e5d0ba9ab71036cfffc4fc94fe8957857aebeb1c7d13462b205463a598e88c28d2155eb7cd136e86b2fbb2d453d7466887601f912402861de0239740b61980bba4cfbd12acfd7c77c74bbab585d02230492f01090ce439bb4a62d87a11d55a99fb303ee314ebfe7ce91e7a0a7a09200f3e27b07c42ac239f97bbe30b67963f3eeb86293a134b7a78978e1599529a17049b377245db909e3b4daf464862a15e38ebdbf484513717d485abf438579dc03fb7317e1d75e12e290afbb946aeaadffb449fd6b06edc3024045d9aa98932b065ad4ac89a2ca247a08c7b1c6e6f5498b083af3125e68c30c1ffb471facf43138c290be05fb29342c350bf8c8d428004cce0fc132b1e39fba0cb7e2aaadf0adfc97652ad18ea7c8dcad8aed77c7db021a4fdcb95e24b41d4ebabfa264c1d3be58ad0d5256e423b39c61b6aab8be4868d4de14cd7cd57e4e19dad9b5563298a2b718c7b6e312ccfcc37b21dd491b9f61912f05fc991df9ba558b36234e50c760ebef42f976dd42420811759b5b4acb4ad02fcfcc52a9ebf8acc042653b68c34654fde992916ea63ab346839ca1a921404269c3403c6d45f6802616cefe9beaabc5c2b4b1409de4d64f262fbad635c5690e1d536d12f0eb8776cdeace37fa2af3d2ae9ca4628386c8fc457d239ae2b12bc7517d48bb4230141554a6eb709ebf628bc79297bdec16d72e3827ea1e0041b94795ea2915294f904d69a6538475a59274c62840394665cb9dbe1f004384d6864efb17caf2602f9a3dc1eaf3191286d0dc320e796cdc75197f99667d70036f23cdde384b10bc42b80f420b92a5b68c3df9eab25d2c1e42b57c2e831f80a177fdc10037f38c700cdd0b0f9300cc9e216e77046771b8f6f40030fa6d3ed244f7ded3c05904b5f9b194d2b51475988747ee2cfe277a9736ad7362e304653b21beddac32e30d9c99ef11a809af2ae602cd1c4ff44538b3e4a5dfffe03584824d6475da866a49b0e1b9b908f78928517125f64e2e5481071c5bcbb9eb55435f8523208021d67e80cc28a33393356bb11a14f0513cfb0a835cdccde3a10af0e38da32ec25ac50b4d728b994d7e1a9147ce32a470645380c6f447c04e1a1535cb0018fd25f4e886514e617564937012da42d868f6c0f4697a26457ecd7cbdeabf298964c67ab1594e42af19a28cc4405ac968da3cabd5a34a86199ab85dab34953882b5c20d7177b4807d036d303d6140e975908fe86b9b48a4c689627f6003a6a0aa753c41f5e55c9c99516c10ca47a6ca4d8de9d5e52688f6c1715f16e731c5843a2a7979ef5c3d5b94b2530aa8eab356c62d15f189c38bfa2ae4e6488d476d85cd00166a6d100f14f44d612dd4631bf1e2732dc3b547b2e8b2946f52124695287527730744e91a491f17be7ed0ed7c060e2f053ddd837167e4d70f67455528d48ca7eb225f75184ab4e5348d3268508c1ee7da39098beb8632c50e5c71f71e2e5e651caf07ddb237d8b74801369088732a263252493ac7ac9ad4f25123e7464f5057a3fc99b19905666c43083d3f5c9265277707f27fa604a2d5e84848cfd88773b7e6a3f78981b5e34b5bb5a8bb20eca04db5a2a5c01853083ef716ce5b5981c66f5b6254d545e709b347e98a913314d2aa1e427875ad90d8930afc14ec92dd95953d7883438f66ddb38bcef5bfebfedf8182323b9ba999a6454e568963526e3f390c26e570eb90510180acac7fad3884b4b8f2b50358bc576bf9f5789db0f4bb39c486dc500ca59b425512013c1d98c06adb29c3b15e0ac9cdfe701caba233e7b7f7f4fd2035c9d642aa5932b12b57cdfa1595363e5e3f785ae7cd2fea7dd5e29decef35a048dd97a8f1736341fd0706735c746a16a1fd92ef03ee2dd5278261572d254518e65569a1fe83752c71a2cef7875b21e115da82888cf37cdc893113877ee84d69661a2b7fc34973a8dc1245d10940f62f21e80b463f6fc75795f0353dfe94d70916ae6e9bab0fcf01680d13c9f2e57d427a31f7342c591b96ef13ffdc036fc3e6d75864e2c50a676638e9e9f69c4c7a16535f4a1b36fab3b58759d83c3a668c718f88a3296d320235f9ae65e7c5811dce32d5912f2111292cbde2b2c70e6619ad5177bb4829ad7c3a4a00412a1cb3033eb930abacc7ca1bbe9ee5b50a38dde54b2533010cfa39804807449904f76d650739dbaa0b08cb72b0c3c9b29d7ceb8d0a8cea47b126617c47ce9364a6a0a083fcf5ac152c0248cf78c576886d697433e4bf6b0fa77864982435b9628f78eb2678c80899f8d413aa72dd3f59a1d373b59d85024e339bd54adc84ecccface73813e7205c3a4079402a3608f24c8fcc788c071b9dadb1068b44c19219c20a3b33ddf5ad87b223be873379d765733d5c8a05f20804b7db1b4a10154e2361f8b24debc0dcb51f6e475f52224dd5ad497364084882043a04302fa4c24fa5c0a02fcf82ae455bafcd29747ba78f1660b40446dc188cf4655c852bf3b844ec40f0c9b2cfd81299ee699564a651d8ef00198ae7d36c833fea52b1054b5a693e76d1cd6190d71dc442c071b2617b9cfe5212ccf925cab46cccac6e3cad2de50f3fc787aabffc489532a46176b39c214b245e00c9333eaad119538a171916e01a94a4d7ba42251d4f3a51d5f2919a845458fe36573238c8c5aba5d6d5c18fc3bd0776ff88561325a916d2ec985628cc9ff1381e219a0c804f94fc8906ce073fe820c2520e39e4208c88721cacc1124d9787a54456b93eee9660c16d2adc283b4cde456c66060fc4f6c683a0e92b7d048400d539ceb55ad6e38296ff0aa7cf7e1f5bf88eeeec51cd82b1735299ffc59c3a807d809d9ba1ec57d5104d95c96e1d38df42997083e70f65bde2861f830559c9c4de92ca0f1acdea5bb1394024de73453ef70c54dc26e8dfbe42be49d4af77ff08c220b75a15fef3e5ccfc6af5da4c353aaa85326b49329eb7da7fcbc58a6db318b63a44501ae04978a45266d56fa36abf81dee1beaa8c244e80872841ac772a7b8b1695b0f42a090232a61886c9cb36dfc31485cbd4486d60d15914b67103945448e93fc24b2f640ade543f393c4f7a7fac43ba6d2238eb8bd5a010b623ef9e6f1559550d2e37957fbde3ef4952ec65e403a37ae1e91da9399d6751fbddfa0e98c44f6b279e47370fdaef3b99ac02d46beed2308efdd6e0f21d8020dfefb1c46bc2f164b707ecb74d5d8763e31f4631f0231752cff0fd90c4a9565b5c512497a5cecd799a234a9989b7f1e7e26d3c57b8bb595daee9319b97b98ae080a15ed88a7d9bb47a5c6d493cdfc51b6fe54cc8577a15782776cb2c895dac267746426ff0275703cea45202c76e4d0bcf5b378a459e25c078e055bb225fc0c17555b3e28d313a25d1ca1a24cea6e5c527e3b0312a99a56d5fa80610ca6cb2e294c41eb8aee4c18a572b8e600694691b67313d5594e0e4ed7e74dd6a95e2f5c66376d2e3ea5a484f7935966d7ebbfcc99a66ba7232691d212b2a1a52f9ba586a03832e13e1da4251dd2f78e5940aa3618c6814bf544d22e28782ca9f71622acc7b8ceb73bdf7b2e3a61a3ca0a8b3c07bcd371ec3c5537650f69fd8db5f862bbb7fa2789bcdc3181dafce8dfce88ab29b1c102fe1c9892c5a57170b4c472e3627c0e7660215f63e27c1a713a4a17485b103a14d4a1ad3d5ac3051479cf699f54bc6a5e47c9654260c5d210bb083c7a7a35b7ec9b4944037cf9befc70e440a7aff4f7d68048c7b8086574f7e3a9b7ac40e4bb7787d11c435ea5e698a4409486f7fa76e2852e6f5d32ceab5d3bc75532a92adeabf09fe54453c8313956ac94e016f140df72171a07e3870ca69a33945a3beec5773578d43a3c7f3ca92b403c8a2868436440638936f859eb855a25791b789f3af3586c7313082e4f2f73a4f31888e31ed32fa2bdb7c3613442918477902f3a9742d98abe453a354a45628597139251e86e44332d2f0059805dc33ccde0621e54a1dd53293924bec6401c1296c11fd03146ada01b7c8c9357d3aeed6e2607a588fe4ade46f1e4d37c9533f7a00cc4e29184322369ea2501338859441e1e93ee09cb7b42c42e2940697402d983fc1e7fa82f9054956b09b52660bb8596b3b017252de3c9846a5cc88eed042eb59308798ca7ea6876026b4efb5494bd3ec94cce5e5ec359d4ef0c6104e256dc4a840d030c6f5828de7397d16194fe5d6124e0c08064ef3f3e7dc1f035ef9a41e35912ba68eae57c7a47e44866ba91593c6280c3da79e8613586c121e803af786f938212e76dcde4156e763934b6710205cf2e89273a371248d2c444905777aa2163196e709daf5a5ac7670bbbda5ef6b70e71dcb3f36a8474f318cf41ea4a328401f305ed3e506974c9e9a66c3822fd355420a8d7b375ba42505b5ca09d6f53f6e0b6cd677f3700bfe5cd99dc606b1d5034000dbbec8f98dd23b36ea44fae92e0b3339dce3bcdd0f4f159ddbdce13caddfefdd3683ffcfdbe05fd8e6c7f87e5f726230fc6aa3c66b752628d5580ba828c79b6ab22fdbface25f913465b76cdb58668e60db1a1d7066f60789c08d6f7bbf5b50224ad8bf0f0c097f088520b265ad6973a8a43d740f4121bc335e89c3e4b8734840d7a76b961453a2142069ce0f025be0317cd7ee341e7162792168a9efa720a3d23a7ea7e06e3d6d72710f30f617324cebefc8d0266e2d7c6c72d6bbd741abf438092c4b2f6e03444c86dcdf257c15ee2c7149f3549fd1192d5d91891af390f828f2e13a089f48e124a2ad072265f51eb46d06786afdbffa70872c907b2d3781aedb35c7264b60ac7d36f89e26c9d824511f4d35857ae084688a596e8559c7fa58d6ec13d7907fdc1f9338a3530a3ee823404da4bcfd43af2f94583b3e862555e9045bd76f5e6449635379f2d7ee80c7603866a9d28a0f0066e58451eb931984513771065d675213d44e1459d8356351fbdd3bca856e7bf15fe56507df091d40dc204e1e7cbe5fe78a02183cee906a156eee17b14763173b8df6053389e825b72fa1138e246bcd753ecaa58c31221227e8d91abc65fdf436886da67078b41ee364e1800642c437d4e7aa3388847d36ab59aa6010547f5e1d8a42858a777b97c6ea621980862114f1691248f122a63315c13c0312d72227394a3cf380ed5673bb749e0f188e1d53a74c3e0e3f63740683d6922f5354fc42f53cc97d7d0459767737ab89b6857bb456edf86fd874c9485051dda317c7d69d59f134271496bf4a6f59d402c03701f94c593dd9b61c18ce8493a8606fe7e53d3fd22da8524a8fa7fe91aad2d1eaf8d38f7f9e71c122b5f19fc483f73b041d95671c2c1269b2a6f319c1f2b76cdaea1341f69cace60c78e01b0544879381e672fc868084063d5b521d69729986b282dd8da32a221c816b270e520291de331230dda01af303af4e65f2cb949431040dbdf81afc6d1a2acdf39b722c2506d85bef9d7f06f383feb81e5bffb2c12a50f2ab8c1d38c5045734e2f66f4bc2a3b4f5d745f1b80094a5487e2452428746e0f286d4c1610f1cd3c238365eaa69e32e8cbd67b11882b014e86cd9578ba129ed9a42c3878e2f223277d36875c8dbaac008498c2ed97bbb9a05406ca9d94fafef817ff487254941fae9d0e797d77b6f7cc14f1f91f37b4a395d8cfcc0e85773a563da922b905fd70cd994f887543bc6c35a0e8210e239137959ab8380a8f6ae259bd039032cea1efa68bf9c82efd42747a3c5eddd7bccbc0c96d69dbf12671d4ed7455939d4dabee64f11655c548650198caba28f0a618e240ba9e20adcbcdb97251485c0843e11860d3f9a117de40e7d30e764d8b5839a0da0e1024991702c700cdfef8d5af8563f457d0bf48a44a7f0e9d51ea13b8903bac1a3f3933690d2ceb99fd26a183ec5d6101c34c6894fc1b6bd1da0ffab09b0a8bbbf9c54cd2760d88650695386c33aa62b6913df7f814023a3b2e56aa4304ae05b7935f1203366df7acab75f2078c2bb5e6b01312e3ac5cfebb1054c272487134411408098f26c26fb5f181410c5115b997b82dfda05b0e6a9fa5ee6469791b0548984aea213b312cd9cf5cc64a6a3880574c64db1e93ec482252b618d2d3355d37b581d21fc99f3973e9a76fc7fea9c96d1f02ef751a756d23bb2c63778bf5d042b38f2b89522db9f7abb31948950256ab520e0d3b511d6907115aec631d3a797fbc125549109c055f89818ed4f3723db8c8ca0d8d6bf31ce9f3acbf11ca5905cf5cb1f237c661925297722048ff1b51e772c35f90edb3c05b51ca0f6446c7bf1a672bff344a9d538ad4896212448352a0cc1a0d365ef59f058f29a6bced30584c701508a93939dd01acc79e6119944084a4c1ac5581ae663a1b1748d3e34e8ed9f01a80a8a5d10eba4b8f789c1288e86bc660e56a16343881d9466ee869f50c93b9a11110083335b4e201fda9c537a9553048ed88e819494f9e8556eb8dff01a8b9dd6a8a4928861c69697bd1bf921249936ba7c629f202ead82365564dfd38541d3849e8ccfcbda35da37377e80a4196536049001d689ab09c8c183fdc3e8dd70eb25af0570a1a6311f1774db8c029130e78f7384872acc3733156bae2e8692543c45640d9a18905ac8b28eca38278da9564451c2f0173b4ac8071b69be625b794f9d8a4ef0ccfafedc17dd287107ebcca821761ec1d35934160522366a200ed633767128eeac83ba01e502aea183ab8e6f8f5173d5fe6d0faabf51942cc6fda2c5c3377b0c68dbc65151ffce6a09e52b4c1913fc63ea81154fbc6fe2eb99103c1bb5b7cd2b32e63b3788e71f273934c47cb7bd4f0b36550c2a5324e69b08a52a0268b4f6a254b6a33b2dca205b352fb38beeb32e5d7a27bc567b9d36188c6c0d56befe46828b01e6742067a933db93c952a960cc6bc4d8ed112be22619636a175aeae5162c0f662b6f513cd67931b44374022b8cd03c08276eab2cb171da315d77db1f38fbec7219660a4984adebd730c913a982aac5cbd9788c17ad5b6b8161d37e13a50fa1fb84076b5a6e2f4aef766f007113ce40a6652e2ee88d88b0039fe35405c5a343c4ab650128a0efe45e4216550de2187766c1b20138e31e38116e9fcb3c009c7d160ea3b78676083cc17835c049260c9c08b0d1ddc944c1b691ce7de01127011abb3478449627cb02e88f99541471218a2eaa179471d6c663618f1981b36f10a1b851aa29032f7891bf3bc1f4e3204e27a57366acf10aac8a3f48c6d12362337eb3c3b22c8a8db14ef8662ce5baca19a6a25ec56e71c8d4cd5222d3a5d4f1f6b1d48dcc769017e8d0eda431dda79cc9b120dbe3600ce95324dc3a6f02c39a31695e8aa8b91ba70e68bf1fe19f67a21cc92d241c8733da2cda68cd82d8736f7fb00177a4c8523875bd40600ad84e70559257c07bac8a7cfe62cf42f4053213d8166e49323a171e84580807dcfca4d94deee2b260b3c6a8db39de104aaf015ec3ba6fbefe6e6ff8484247d878fabda29d4ee15135d388654f7f467dcb45d4f3c4fdb33150a1b8c2a6b11e83ab03433c8bba39dd18116b58385766c5b0b9789cc0900b100bfd9a8b55c4bd22fb1edb800fc42cf0ac8e66eb4d00dbd655b582b01fc9e04dd687ea3d7ef77f8a0fa51a5a52861f10208bdc4501a075223a26d73a38592f581e918256fbba191fa7b323ec7777ee922a6b3890f5abbe262fd4d6b1ced136b1b90a8a831c10c9c0859b96f485c3b8584e0debd8a6f1bd465f95f3ce0570adb9e83059a8159628d314deb874cdb1288e97f68dff695577b60c0e31a48eb8edf6f2b36e97ae8cbf5798fff891f43bcd977b760bad6117a02ccdb4265ee9e7d433af1212ec5b1fec0798bc2a85702c03a80f398f72e42e3fe1ad008e891db37e9e40f10e0c68204c1541c1f9232d25b4a2dec8836cdb9b4df436de8d4de02b05391caf9eda959299a14f3d3c5f964d7b4ebe3b25b896a417f15fc4db4abc01e7bf32f511294319c907ff4ac46f6ec4079f0da894d7ac3fa9f02caea3f9fd96689de52f8d68694b42e7e0a87422b4ad6c148b059c7fa738e484d4f0f58154205a9903c7da97dee414a36426ef22033f72e1d7c6330cfe1372e79473a837dc4c54b2302f3a9179d5a356985ef6eab02a57b384d56389a95d175364e287eaa159cb1aaaf89e6f1c3a41a50fd245d58f5ab900f6e484d82bdab14d748d8bcf07c82925d369cf71491eb4ed699f4c6debc698fc67595e81cb7f480bf770be93df0a108598d272be9f0922a600c965cff0c044e3d6cf60cd782d47b0427d3dedb7d317f2fc988bfe9fcfa3d9232f415b014ab78d22cadfa7f9178573e5ec3f06885a68474afc40d044e46263cc066140f3a58cc9e5674d297ca1b9afc669ce1d00f081c5f7b830cd177f7fcae315cfba601f971ee9b78ab7729fa2f06e3a4cb87ebd70d172158b4b8c11096818697d3ab2110c04f6ca906789146ed495e3c119516b5f34c423ba4c1c271f288b08646e01912a7c873e8784767496dacefe1a91e28b83c2408ce8f303e4fc222991626f9f7de7484013aeea36df9cd8fd16cdd47b45fe7111de94d7d9638d1bc81ec321e833439eead1d358a61e86d070ae93cbb0e12a365985d4065b9175c2654ea66dc5a856cba6f7a36cbb7223868d1d15679c923f306114e2bd4685df2f41399ff87f252b6427594071a31204887e4764310c412f5e74a7337bece000eb22672a708e98bb7f1e5b8b5986b6252ac06b8dc3f5b0823d03241699bb49bb7182020b11888a660c2bfd3d8790879ca0a228da8d1f97586d743e98fc97199f65a0f85fa75411ededc9083272ec5b09040b525e0b1ecb6bceb038025c13e8406cc9587c80734bf7f654c23ef987a0bb5d9e1e43a3cfd97404117264900949a1034716ec90a3f983ba49fcd8f36003f36768c15e3523da2a9da1ca6eddf54da5397e3e7f02e19c1b973b9722e849625cbfef8eaac005b1928cc4ec2eef20cf7e97aae0107e7ffd94ec9014118e6f5760e1a92c5caf0c563e8dc4cc6647049dda50376e74a925a45e01311f72edabaca059c56f8c20841a45d1e84e849cfc21b393ef83ad760b53fb913cd6cb69a9d255b93ce699e2e7fba28e9759135cfaa7b56fbb721b9576d5829207309888c5363774689dba6df6df6b32a9ee4c582a86d3004c38ee18df2a92cd2bd2e17c097f4a152d4cca7ea5f388c53897d60e77a81095cf977ac1f1f959957e6c362dc108f456846790c5a109989387ed02075cd0941662bdba235ff8e0f0f1d517919622c70724af49dd78d4e59b1679d1f720ded6263e9fd6577cda41647a6de783373f825b8147296c12aeaa34355f9d380780ad1787ec9578bf2f4f5f432a9389eb9dc172766f2bd048c6026860b9135e5547ec0e5f294ac2ee4b03a68222fdbb8d39d6dfa3db7468c47caace1ddfe6f8dcf711a6def98439b82ea2aad697f3510d195da07f219abe10a5c2d9b49e057c5fc18b6cf7302ab4749d07bf5e7b4e355f41a1dbafd118ba7f7d37226f573e24f165f91de73c97db184ec186353e87d9c37957510245e522a92fef11512f620cf184a157a5beea1c4198c7aedd5db14ec49aaf7be8326e56f589beea005f3c63fe8652b8a14761c858a6e75e09eb5f3f063066039e65840c64b9d1898813639eb26185246d098d3c140d504ed99f076914bb03f3be33576fb5dcbe17e560ce4184e7e874f525f21055e933e10ba68a550f3fc233b93d5c842f9e14d2dfa51067f125eb16e99f62f0075f8f6d95c6b7601b58d3f0600714fa0d3dc0f480f5b265f3fda18dbf48110b3fc35fe0652ec3e70e9efaf16c807d793c40f977f4c52b705f450de5a26a3feea4e42714c16a7d399cc54585c4029eb7e33533c6bf4f65c08a8a33095a246024920c9505fcd4fff7235f281aef4ac50e4eb663d1d7751bd2910f09fa17d3e5d0f22829f9ed22ac715a26b508abd2a574d78405b5fbe582e5fa1198beb437e98c4dd96e46da8d99bdc8ad2b0fe3bd915eee567354a024cb632f1286d4b9d873d42d3439f52f8c9c1bc12a101e73e8f29b2c48e36cb19d23e2e9ec8fa60c98ecec823f69b95f1436e94513ae33f4c0e8a0a2999bc8283393379dc35522dda1dfa791285b79951b4c9299dfa99768fe7fd7cbad763cde44b384479dae32ede52da46e12ce5faeab2328d6402ac6354fc548e0fe655ca7ffdbfa2ce94586efd6eb1d5146090a3f79610da3558832e55766333a5f15f2eb8c33e4a352f2ce135c651d829799cec84fc44c28289b81549fdc311017ad5b37ac8388d81e9a3adb40c6910b629736e209cf7a7a87ba344353e9aebcd75577d86bf1b33f41d0e603bc9a26c803b5eea11fda2f6a4c5071001a3a865b85004b4a0d1383dfb979adfff52119df541d3c58738e7019afc60e251eb9767d4b886c9f4db147b2ee3ce9838045411a03e16240a986272618dc8ea67e5f6e1d460b7a532377552ec398a498e2385302533310f09ac49475bb77f30605ae07e1cdec9f9dc35a75ca1a4aec073ae1027dafc259a08a948e99442a335aa9ac54150bbf05caa3bccf95ee47cc8585e7932c8f0e9bc2c6880da04be7277a4f76a4b1b0b22764137527c48635eb141028d3d7991f6ac753bd1721f82d72bcc5bae307bd1eca27d85ba3ff9d38b7756d7e95b66f6b4ac445a387968bd45005f63c5056a018ba28530adf79c0f57a07983bc865b981f2a640e2520f5fdbafd8e147687e7b52ab1a2fe3ee86703ffd2c4359ef4274aae8defc08f13ac984b50f8eac0112bbdbf6481143fe4222140e7488e19b937617b68514f94c6af8e23a0ca161007baf6f2b7f905cdc89b4bc9e858112eade69a825919bb94f3d62cd00f599c5ffcc6af3023355272d2f89a1f849d76446397a672cc8ae7614b8b6ce246d09858308c92e970aeedbb1bf76d454cbee11bb916497fd1af193d21e7777274d2d61eceeea8b543c2394e5c8685af994d527a7f156421aa6b9f5dde5de1cd1d2be2acb5cd60fd04c580ee3efa13a7730d4d1aa939dbc3f3c8e91ca3a98155fcba960a92bd32281c2a20699245c64a9a7ff07d02ecca5bc13dde0de50fb440f3f9ef066ba458da231d680f5dec5ffe2322ebc9d8b624f93a4bc55000e318ea058ff97901bf4a1a3970ca9278f4404fb1b4148c4742b78a869bf045fab04552b88740969d6c2eebf0b4408216ff2f6ed2276e10c3f0c86ac321f80ff491b41b64710bf6959e57a45f3434e771e72011fa73e82246204e28e2fa090cfca50bd3125860fdb08246b542a4e22423633608fb56732ebdb5cbe7e0685b0e46dc0f2e22d90716426157e5258d4896f5b6241cdf73dedf472584fcede9887e81ecd5b47534720e4de2829996276033bbd6be864f93796e5a1a7893765f3140b30b65c7c1001abfe2832989ea7c3a454e8f8f05779dddda4966927c6191231421328949e127ac48fcd1d65b4d00dbf61007ba9e8508ed4e42b05f85b2ade88b1b8708a0eac356f58eb660a57c33528c1eb1202e3ef77d0cc1ae5e5fa751c8eb6acdac63fced5aaba252b15dee8a78645378202b690df8cfb5f8f3d5909503056b5c9177dfdf454c5890295abef08786cbb2842cc6ec0ee948f3206a652ad03e736b7f36996fb9bb6e904a66827626dd159a56a310c52f631b251ce8732db7fa9ef210b5119b3d0be995278199d88f60a3e7bfdc5448a5dcea4874a3e7cca4e30e12f88c1f33019b48b275c529a79c6c3c5060752e37e3469d1c62422d27a19deceb0f09bef08c58f816effef34bc8b2259ef16c8c4320e8770184c67878857b507d3b68e28774658fb7fc29116bd1e563b8e998e62d1103b4cec2e5d05f5fa383d888898641032d6ca3c51f72edc757b0e3905c36f200f4328c584d42d9c278b08e6513d73bd1413d24a0da913f0683459f67c880e7009ecc58b83712acff34fc655d8b447f7cc552644558b9771f205c6f14281d4ebbf088646fb0a8b8880d28ff9f80b41a8df261d55df4c317e93479a2b08ee8a06af152203fc99201839915d7032a03b29403043e65e0b5cf08937d99d8003b78d6367fd16f06f24b7ac6ee3f48ac489b76643978271a86dabb77c6c67fb555979197abca7cbc766792073457f20ebd1feeffd7f8a3ef217d3098ce9a2c4ca6f91b9a4685e22b5419e6caf033888e64cf6d2adcb02a9f7b1a4c9bd3742b46ecbdd32cb7a37061e11e2ec740834d00dea21fc59b2500bae4e51b00de7821902a917aa2acd37f59ea4e4a58a7996c27ffdf1955b9c71bbd83f8d5743de05f75c237a13851f9becb0dff1fb226ac4f3355a89faf79e73272948850a825ac090d61c576b727901f3c24338ba013ef3f562f3aa4fb6d4bf4bc164aef6a37caccb3b07d63524741703e82834860bd129ace09ef6809f2378a87ebda310bd2c2d56097bed5e75c60e06dd6487de90cd6fdabdfaa04c0e06c6bd45048c31fae645799e43377aaa0ebdeb77910ddc919f2ee3e3f13558b110a22b84a7fc77fec2affe81db4483b242ed515f804789eabb7cf1afde5a22dd63b79b339132595cde7c4402c6964ca777a4ddd3118cb1ad0567c1a08f5f4f2f67023fd2c3f2099ca50b60d5827d4d84821373271783b5619de60ca8bc4d8e69a8be5d3d0099d19fdbc20902a7576a501f2ec9766a3ce72d1af6ff0db3a18c282b5b4f268358a06008ddcebc0887350c6a43dbbc07f3d7d23fbe2b1604165f60c885f77c2339b3cd8eda11e2443ba5dc790a9d0f204c5924077100698a582e2d4470b474a3b771479bbca3a8317d655aa742c2e51e8572184e3140c4a98b64fd9ae1f00ad3b33490fe0092833e8aab9a2a6cef22f4570836f39037f616bb31c17d51707b13eaaaad39e63199aeebaf77b39614391c76268e899027e10b9bce003b5795ee89dd6f102056981004a0264577864715442dc712a6c9855c2e4f25ee59d3dae5e903436baa0cf170c963d9c8ba359e26385de615ac6c88f189f24b86269b5fbd8ce8d7dde66c6ee3de69cc9adf55d79b544e0e1d7154acda681ab5fcbde7c1b2c5247cd06c174544ddcac61bbfa43ddf469c523e900e4bb76fd5c5358b78ba8d786c32ace47c353f66dd5dc0459ba912ff1c659d15fd35dcc738c0a487d0ebc96bd890bf7023670ad56e0ce082e4f192273cccdee4097b8ca9a405b23c4fa6c7614b594778c8374b998494e37cfa8626e7a2fe26cde4e6ca9a375117176b795406ba01de08cf9cbdb96f4f825b843d30a9b3ee49372b42ac6c6f00c0a7ef760a8ad6437e789c1eaaf924e5e0135e7ddaf477ec7e2826aa7d58d0589b15aacfd17db6a9d1caac27a684f06c9dc7c31baffa8b2f98096814bc381d2dce1cc3d1db5afe02e43ed2fbaf6c1f9f03c5936681da066197c12315e6ae39bb2062e26f88ac2a47ae578a675986db8be4c75dc74b46354e5090696f8529a10595fe8be55e93b8d5d8a15a2a084b98efe05c7773918f6fbd753b057d60fdd55795f97e99d073f1f160ef00ca0ba44386d2b3237c1476a05a233f046085ba0db4b85b8fad248197607bfc309e123c9dcfd98483f1e79709be727f294feb2424c1eb5f3a2733b8ff07d8dde0832cd672da1c26abfb6f30d6190e26d1e995a94314be69e10bc7755debad7272af3d3eadafc969fb2bd05d929f58ffde6af686baf0bbc19ac70979254dea0cb7f33b732bad38de402a0eb55e094d15687be601f81f91c30d85ea8e909097cb07bae067ce08b44424d4af623abe97c9e1f9bfab5c045db5a01431ef4b1858bc0ddac9c297d59d1a35bbece0adb7834f934677206e7b80cd0518b540c5a2d7bac0fe919cf8af5e75133b950afd74cd4693461f936c80755d928c6179a10e2f49f64d08b26ac397a517b7e3ac872058b944de963f77c8f76ae3d1bf7fb7d5317390e4efd6978765b7d9cdbd440c3b72f746d6199cc69fb560420b273f71da931c0257247e9cc9e149289af96982ee9342b2a3af365f25d1301326b707c51c42f374ebac2baa22bf1fe7f6a2ab58e8fd1f919bed31694f27ddd5d05f15af86a66987ad43170dbb8d0ae16a9ba69c3d66a3661e22d04bbb005cd954baceb409e1546792a94c2061fdecca24ba84825be50f0b66c3e7b208245b58413c0accfdf11c932c1486e6c3ffd32a40fda28cd432015dc5f88e223a003e9da6fc3b4ab2e8e4fd673d012fc8574f91f61a3b2f1a3e1a44e97b059d615b6675c9d348ce9a2f60e2aadaa85f8e8e9eb932b9132d98730aae2105d7c582150464de42cd124d18e4b1d00dbe2d7b37e7481a0da06175e06dae95d2453b7f212f1ef4d39e788e9cd793870fdc8e1dc92a629e28310bb17671864f2685758b395ef59daaddf9166ae26a6b5ddbff5cf9d143595fb15eda80410806ef84473879724a47a98cb26ac2204d82374a14434593f891836b36508df8d33a451ca58bccbedf623cb6e1278c9ef87a7a059c72e1788c93ab5638b6fdd191a4fe24c2ae4b1c4478450fc3918783b722b5b635f5e62c181d104d7c6b24909e3dae64c0459117169a863ee5ac339d36704c3e1ba89f382f5a1862c216743656a4ba2991aff465d45c8491a9197f896c3b1bd9e983a26101e731774419a88f708d9850ae51bb873da89d90b3516ae8253d57f5e52c90849fd43daef8e22813aeccd2e3deda9c1f26e6bf9fe9ca71909b5b497295dd533cf5860f60b658d86d1d161ee433a78bfeafda9a0288825c67f5c114a24039ee9e75c02c1647eb1b5c8d55fb6da6a7a925c0cfa5c8cac6c6af9ee497f3d2d55f88fb65e06b9da1683667b2406accc3c0fcd661db01751b5dc9b9d02ea5243c263119b0c1da03c36d98dbb42f104f71c5526124573f63c4df07f50a813e12c33a255c1b3e79987606d79af390ac6ab48addcee62a89cf66192d09631c34892ee44251e1189c75ac6b4daeb9d5c7671733fd52a99ca0ea0b89dbbdd6125e250c0d8c5b777b7eb51a9547ef7c3d83060fdcb5939a510dd9299ee48c95044eca09588fa445372355ed14bd84311219448b3d8f575c94c3d9d91617effc0c23089a571257439f0bd51c73e2ae5f635ff7ae3b9446416612a614992c718bde4596806b75109109a1731e1ec416c6992a520622de9e14e756cb1cb5b4e98155994892045a462619d9a9f6e3ae4e2c506ebdb5eaec68a7927a72ed27bbd2b84281e00b12528855664793f41ee75fe1424d3fce2c3be4323c35fa1a76c546cafeee4863c5d59e2d45a707a3127588d0ed59eda47841865f87ecc6bef0af952de32c5f6f68f0c9ae3dd78eb0bb9662844444dec84ba295be742062ec1f602332022e2e77ff0d214caa4ffe3548944b83a7310cc882e360b110e7a76167d6a41ad356ff68f62c7912b1540d2cd35142518f5bb0b66aada4fdd524cb056db7fda0ea3e2b86139942993e6a8b01733c0f81f91a863c9da4e98830dc12eee9c19bf02ac8771668e56bf3d6de66bb8381a90c913e9797ecc444a554a2dbffdc34f01db79af40f2d81318dab7f3c7bf1965167333f62c63b8ba9ec61fda4c32c0f13eb8a1ac97e99d2bc65d4a44cb23e9251592136a2d451b1584da900dfafe68ad462c0b993fb907a68938033216b8afd2f17a1d26619cdbaf1187e64fe46e4356e0bde03c8ca6ae4cc1697723f1c199d367e588010dbdd34ad702c0dff21595fe71208fddc30d0752a425a1d95844e6ebb26ec85e648eff348393ea6308730b472974191fb78dfe2cb43edfcc6f2fc6e67f2521c917d9921811f702855e8ac85a4ccbb5ecc59b6394ac2148147a5a6c6c44e56adee6a1d11f3d607eceb235a58a6e44ccbca793ec354172d8b22cad3efcfde87ee14c5fc42e8702071ae9098e8c59967470600fd2a5e96a714fca8dd4f0a8ac7d7bd1bf1260f706d3d08296e2873d579052598e89ff2fb5cef1576012ae6697956e27e6209b9aa2921d03b42cbfd3adf120dd7dced9731bb8bb36bb58cf89b4c5819359716a2305e01489e573ee97d9da1bf28f8d3ab7c6288c843e2c5b2633e4b7b4416c41671e1c4c0bf96127395b88bb0bcd71021f233e40e7e689496c640b12a038e3b61eedad9ae7635bbd6447ae4eeec9a25ccaf7a203939d635807dc879dd0f2fab64a3000dee7dccfd2397e4450bccc2ead97a4dcd4d44127a267fbad574a6db0005ffd12da57fe4166bfe4d35bc95c3d4318bb5506711174bbdb80ea8fff2f3c416cdbdfc3e0d3554345569fee25ce55208940372b68c8dd990e54938b94cfd1383f3e6ccfcd2dcac807516d74d72417f78f2f2ab8f27b2f6a6293f12d8967338ad8a9abd8e5a227c74a61601f9c25d562169a0d8ab90622d2d69ac03a8bdded7ad09fc3368c02388eef90c4706e68063e4911f391aea74c980bb6a51c3cd4129f0fc32ec1560838dd9256633c29895c84f00e07e6007729758a16e90a58ae1707eb374016c4060e3603a64a659cdda4eb416d66e70f75b5d453f16d6e4f822a93687f4bd5a1f5899ceb4efe7b558180b2809a8cf39d8f365adf6938cd65a00e742292233375d6c68198ea03d5e810e5c706305fbdd47f8e3eddf6422abe130d9a2165028958c1278deda56aa9b0eb84e6fc5a775daef91a9aac09e9f1650056741d9b51366cbb0bf8282dccf4f7570f40a3f465f964d3dd9ac7ea2695a86bff7d6781d1debec4f71561b5af59a8e54e018c45668b5b09bce665b541d9daa5c028c5150e96004386ad3bb672d7679c6013a58239f1977a23cf82d3d2bf8b38551e6b31182baa46c3d86c02b1dc2397df88668c93d35f7e141718ceddb704a12eb280d34a9438ce02f316a20581ff20c17f6adcd2ff3127097614995575bd0f56b61342e3ea7ca2ee1ce3861a8428e5af8f5081a6d2fb6a7ad7b902226c75ced2e18cddee3d16dbac46ece06b727c9c4f57541ffae017fe98c527d8ea25e76b11bf3d0244c9e989e2d9f1487ffb6b06faed243bb7da672856e636a0680f956999d6784a62d50f635be493e6090f24e2479ad990571507c97a257e63bc675befb32d5da333783a6bbad07c545e469d7d71d6865d905bd34ca92ca4cd692fc99d7367aab0107933fe71afe059b36816622447c67dbd24eb3496d2210e593d7a6112cad2c5f240aced736109931d259357ad91d8d85a691c032971fddf454e70448875206a3bc321f3d65d2a4058680153685e1158298798d0755ab4a991ca225518fc4bc8cccda8a0ac2759280939b6a71202e78f2548291c301fe97936d7776e9c77ee3180d1ae1d9db26d35f0de35a5330991f1c67a49d96ffbda816d97d8877d1bd695db00c3546477c1f8124a592a2997da1cdfcc8d1162fb5d6b7298f7f47441e689a113ca231cbe8561898bd7ad7d0ac1206e811ec5aa7346c7a847e4f906c5b0c354d36564cf65f699ecfc45ff9be5493ea37909519d2d0d0dabd0600ed34bc8227cde2d2692bcfdfad32da5dcdaea77678cdab663784eb2997ba9b9936a5abb62f4b980fffc34055cd8fe659e4878e5b00c4e168f4f1bf6398d2d53228e9d8a03d9c3062d6adb90e9eb8f652e089401c0e05008f1b37e259e601adc267e9b61e2ed83162b3c32f49bb5e4d580e2ba9fb83627d4b8136c2d2320d41888e21db2b57e520063b6823bce7aa9312f120ded0a9d860939a7d911fb833a8b6dc0608ab711c9e35edae7f0662159ec8e3594cfc769c59c65ff7c0c9bc29f6287b3f3b100073fa02051f64948244c2662b2124bf181c12f7bacb7729c610889cf5119dd1b967a22da09e6733a0c07a9a1d294dcee5015285cff22de58fa992ea9125f7f7d2a49ff103679ac3efc3333913dff94a3963e92983446a3ad126d9cf199686b5e2a572580627d78a94f184563178daeed94e21945789e4599eee4e62d7d7088105ab44b52fb6ca528e39ecd3fa7128b2ee9791907ce26df56f54a0f02a19eab9c0037758aca9f23607823c13a8fa2454311481d2efc4eeaed02656064ca66e1ff48bf79b0add93d741a3c98dbea2d0e299705b6b9c7063d675ff046ed96caa545c69f76e2769a0abc30c61c10ceb932d761ad754db0e88edf2846ff2bd33200ba14ff644fa2d2a6667f583d4225a8a37bc5899c5d86e88786b2014fc0f50bd9a5eae1163c8f2fcb4e6f1968620e0e4512ca4b33b84ca6da636a796de851070c8f92c9d0e7fb09d3e444a6b8a464168d1277e45d3eb03e283ac9a7cf9af0bc42e93feb3da5f746a3ae0278b5e5df6c812e97f3078606f36e3f1e4042b0e8cee8ee249ec90a93de5983f9892475ddbe668a2b0f2dec65b34099c1cedcb364ce78e2d7efed9165efd1bcad5dd3e190d6a199870742f20668fb8e799d043ae49289a6fbd042f6efd8c1c735562fa60688973bdd2abe52265eb4007b202b0366f7a86f2aa0cfd1bd6ce518681a95f69f44a048900ad4043a1d7e2693336d728461905c5b32e6e644461abcd425d58ce9cd37861c5dc4a08d82e06327444e4b229be47a7250289fcc438defdc5e6b7d72914d42ae3c7a2024df3024038be020ea35b33b1e15fd01b06a4f9e4bf0c31424ec48bf6d763dba0cbdb7d9fc35a7a7e092dc27702c14c8944c584dd8c3a87646587f247ff37490279a9f9c34a08d922913a235cbe889b0b611e4863d19a0487d241930057ee538593474616973e36247013430f7aeb5f7f354ff5e7dfc0473c8028b6219760fca7147c5cdb6dd33c1618e08872029f5576c04ca3ab618e76ab93a479682066a47a3a079b1e68edf4e079d79a65d0639ef1b4b3d3f84d66776608cdaf59ebd4070bdeff845af4bb86e353de467ec02a08515b8d5437bd9dece05429b99f87a30bd68e86041d02568ad754a40800f64aa601fd21fde4df2943df8d97eaeaaa5213b1f0856397ac28b22022511e27de0c0485851983772dcbd9ffc799abe12f2df8edd2c9dac8f61d8e9aebc97ead5302861091117fa73cbf21f7703918e3ed36e6dc76e540fd4f7b08b22f033180dcf1f63b398c9e46cf0ec66597a4d3f4002eee929c1230ff6bcaa52dbac861b00cdee62c2e1e1adf12a2f9e6770e896acc614725ce72ce8205ed24282f9ea269714f2d43c750780754bf9be6e752015ce4a2a537127b6a889bd18c92a91ac174336a6342e8a4d20e44175db43db9216df547f86d9f2ba599575bb57725a5c172fac48db01f1b68eed86c7585d4efd0132d3f85e9f98e8ff15a23210dddcc18417e62a70fad860bf024b5cb6a2784774b75a3c146a3eb1a8c7929d3cbc69d2f5e7c285b9023177b617f9c43d54ecec6e21543b3b71487f21986f472886d316a24a5786aefa6484107a7388bd8a56746fdde8923f82a1a3263ca259ca1936b9bec7f6f1cb226266459c1f2c51d58a9342a7efb7efc01c7092fbc78a254803223e18a31018d33c69cc6a79652576d833242958f46e312bfbb97dcd1204d07b07c3384cf3d2d675f6acb5518c90a88dee145c6083a9d77a4f895763a5b2a9ac04101e8254d76b07453df781c45d0d5f4085146f635deb950ce3adee734dbd2064ef5b12aee30b948f2e7286fa20020c5801e841bbd5e6025ef55fb4069b2ae96097c9b18b1a3a68c6283b3c736fc96861b7bfd3e26cba71d4e81feba5f6920b48779c4a8e68e452cd6261682176acf177addff33b5111ce3b97757892751480f76c87b13d1e899e2630c18f038a932692ce79504ce10963fd66a29356196187641511f71fe025956c603759b8ed092bcfc21a67f19a2d36add048cc056b217d4d79a53b5ed622ef837b346af08f494b26fd51e8dbf0b1fab2dcbb76a637b42a4752196b67ce99f5e141dfa90225061db83d4c26e1211c7eeb66ab0a37c101ac5271198285cb32fe71e33f35b7070a37c41cea016cb8c8a933bc5d568cb25d0a5123d0b317d554672576d12f80fc9b3111158d50f13ae595aefab29795d7b9466a0922dca5b172a3581a7a3c17dfba447938fe6df63c57082fe151745306f398a657cd9604c84346899fb3f2f8751d52935e3b27f4ab325c5ca64d31ff1e40d98bbfcfe0a2fa933a345a0843bc8c1fa44f2712b7c3d89e11695769025da5cf5160551f8773690a415a2397519c042303394892ba30a72cbe5ed0b254c7814d018d3b857c27eb50aad6800ffca3e7688aed0bcafd5d888a5ea983dbcacbf7ea41b5513e77e9545f39c1aa1c6ca065dec8dfb730bdf801b71615f8327c13772d859f91e6c0d630daa3ae6a9d55513c2febf76f5307d7921fe82e9abb9c053d59fc06b1a99d368fc86b0b7ff53f9d7ca841d5a69f3e61ceab1669dd2a7595a1083163ac69c1d644a36f009bf80ea243d9527f92d70500aff6b0751e5f8068ae8843a9a79851442307d396e3ce98312f9dd5969c0d20baae956fd7582b188f6cd7a832fc7d4b361c5ea0171c9fa52e39513f07a010c3c08080d2fc61b24a99fcc4b4d1aed608c3fadf6420d1f167912b038058a4ea19333daff3cf2be62904ea25c2843beb5489a58e19f1efecf823682fc4e4bf22e8cd8dcd36fc5dc02f1e94e329d9b5338ea8c3b909ec6e5dc87c74ca0aea834a9d96738099bf7cd8063b650d57f23f15498c783de844de2cadbe6bf1e8b71e7939d6d0f7be2283af91358c9f926336c649d1\n"); + assertTrue(Hex.toHexString(s), Arrays.areEqual(expected, s)); + + sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + public void testSphincsRandomSigSHA2WithContext() + throws Exception + { + SecureRandom random = new FixedSecureRandom(Hex.decode("7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E4711E95F8A383854BA16A5DD3E25FF71D3" + + "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1")); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, random); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new FixedSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"))); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + AlgorithmParameters sp = sig.getParameters(); + + ContextParameterSpec sspec = sp.getParameterSpec(ContextParameterSpec.class); + + assertTrue(Arrays.areEqual(Strings.toByteArray("Hello, world!"), sspec.getContext())); + + byte[] expected = Hex.decode("f1559e4e1487a12d25c3925fb686b5d3ef4a1c5ea6e8f521b80c386fa64b7d269af3a3db0f320573fb83780ec5be1131072f84d87790dee5e1222f2d3423fff53d572f722d4903e60c611dc146271472da505bd67b1d25d46da89d70f36993ed9f4577f0d35ed5d01487161731ab5683c21bcac805085afb70d3d89296b83cd43b43d8f32cc59ae149c036e8872ee2e1f9cbbcedb484077784ac5da2939a6ec13f1018e0cc3e8f9056e1e8854c17eb766ce779577d2f48e621eb5597e86e92025df55273a26b3f3ccd1d01e0f73a90618b572f683947f16443a50caf79e27d06af57ed3eac838e89122895a63e8e95d58417989d4bcb4b9e582a61863536708da75730aa866ed349b6b653c4db3e5759e83f753c4cef2d6e98f4d576d5dcbf4db1e8efb6b6516cea3f8bdab41bfe1ebca6175afc0daeb13a66e08b1db9fce01c064279fa00d1a25de78d2270cda5a4c8adbd32c0e13f51f34909269d08f464a75f6f7b2d7ea3ee28e77c299511029e42f138cd035d65a85427fa1a41591b1b2e2dcb706adadd07bafc3a3c121a8258dc813e4ec79e09099fc73820c3d74a287d7084b91f70b6b71303f766bec82f42a26017230d640e25f4f58cf7a53ea32a62595966481360b792e7d65edb023b5d2cb1690fd2db6761ece28bc5fbf6a4320ffe2518880adfb42093e89c04d165a08128e4dafe748d6b2cf7c49922cfe2fead253a27be2a41b64e6031a41b4edbff8bb41b5ea0fda954bacf4cd762c7b24559fa1c937ff15b1538f11fb2c59e7de35be8864f84619a9a860e8d612b5e98d8eb33414bf215ce56a7a461611df4879f0d076b8f3804a2f0b4bc74552535eda817869086f5e32cd6681670850a9237c62a29e5f57ee1410029c3560c283015763c3ff514afc922a16e459d37e1b13636586e91026f755ce892a1af3f4e5f80bbcd6de89b0eabe566ceefa91f152f67b2a4f4d3bbd196f5843cbfaa3a70ba62ff133534844c7169c0adf4ee182ff0bae90035b1b177e76412f61fd5b91f72b1b86d2a9f65ee6d5b717a3d60f9040c65187fc56c55bc1c21de4b8581310c49646d581417a3960e90595ca836f9f3a2acbe6a1c1fb109fc03a1e881ca865c71e0dc39798169fe9e9e730e782d6802ea603abf07e97e20e7598be7d7d826ec8593dd111eed6313f03209dc22bb4152a96221848f23c8c50c839d9ab92e3187b18a06a5a76576a922e2aca6bb2b9b87ca7c0655f021f4d57f08303e075ab0044a7833e8e60e45f9922302cf1b7889b4213069f3708ad3f6f98718d6ea6b2a633ff0a403e2df7165e44963bdb608676f9a723efaea87df982c4ed2f214bd416a64d9b37a35029c26f3a667e8f64149c66957b72375cc4e5195d3095b410d51d753f1af99ff0afa982d830b5acb8bdb59631f93d0cceaecdd132699fecb20d171f4eb0f5854e82f83b731ab104cbb60562a96aa4ea166dd554c04b8b815ebee3490ede49ba186e206e22190fbddd96e2c1352d3c6a005abaffb734e45be63025cbfcd6e57bd184b5798ecea43f02af942e512ed5cf09ca3519cc61476f84ec67804fef3b05441859451344b3418663babb4f56e583ea2f9ff6a146c8d18fbb411ed5bf795e916cf54c6d038a72153c7b58b883a7784f4ca1593b81a30d00a35dcde29ff4bc537764a8363b886a856caf1bd2b3f3f7b53c5dffc6e1d5686c68f154e01cdc52262cde9ad301b7e8920267a5cc478aeb7800614bf270d9486f27c38b6e36561adffb5f1433f20a642ed7a75d4f41b8879599da1d108945ee8c805434628f03fc9b88ea252c0e62e72ab2385e347a6e045ae7af2ac4bc28fdb5a802aba7153f9adfc585308a9064f0912889a8fcf645a89aa7e96c47a9100e75b6714fd811be88cefe645fb054726080210e9f13d6ad8075c86f97026550ab46a9cdde7b1573352531d0a7d0298ad22b86e5609846aa80f0a8bbe5e894864f01ddbdb52940aedf9f8389ed5c9325145201f6b2780747233ad0e6e3f790789d6a8cff350fe3904a89925b44abfa1ab68db640d939e666b628968577e1c09114b9aa37cf3497a574596a4a281fdb49621412a5414d97fb651f6c42fc7ce13d46e825a1105cfb46a1ec54d064bb0ba18d8601173ac8f42b7f2a36a10493f32053078e9a3e628dc8f6499ccd41fb004a0340930a2f53fe448bbaa8503d1ba927f8f7fb01cae80b8406d5c6703fce77dac4e7500819b74b6b48646aefe33b61ea50a7d9f401571b78cf5dac71da3d6f92d7ff97de88c793b65181e81cfd765aa43b0b8053b91ed80c94f654c8bb7372bc9fa63ae89c60e3935fa9dd54c5a36fdd18f5b835d0614563c357549dd702920e185a3a8c7aa2fd991740c98462305e463d0040ab679f5d0a4cdcc4452dbc2a20b8adf16c6d1eacce566f6d94d91d0cc8a1f794ce24972c8045722e32b4519886b30062629261a4ae01f019f8220a727f05a4b467e6585aa13becebaf0d921b76aa777da366822b1dd969ea9dbaadd4698993d9154d2b4ed48eda8050f9938e2139d96b6c6d48e9a41dc5ff990f493bb457b0329533e78868cf67b9051af3d98ed7f5a7d636ab809ac00a7504a6b0703d3213ecba5ecd005d6a9095fbc5290ff23b50a19fab1445a3d5d805290543a9891bc751fd3bbd65aab0d84f763a149825df1624002c744d413e95214c34ef7d54d392a5dc0623edbafa9b763dcea5160623c3dcb584609b1d279a39c1ef316ee622c4da5858df1cab8b8d86ebc3ecc0e855c67a41892c523d720fbdfff38bc7e0baaad7701cc1461438d8ef8bfd43be14f4c14fdb7c41a73bbc61bf3f666f1d31164fcfcae4395e6cbe049b6d81dff7ae92cfd121e203891fbaf555f1fa74a066f445bb397ed09795fc1d22bdc63ac35ea9f7b4c18fab6948c77ca1e3edcf8fbb2a39afab9ec1330bbf81671a1663cdcfc1b65795c0b3211df3a31a623b131dd6535dfd46507305bb3b8d4e0cb1e3bd498e7dc161f218ab03d3eb1c62f995f2b5518f61837cdd424b52fcaa2e31be8d496a9bafbfdc7f46f4a31df7d541d58616fbaf7d4a7e3419c23d8e95a61907d03571b251f887e2b2270e867beecaffb85f46e0f426ffdb1e8390c668ca54564227c707a8c24ee9a28f43e5eda40a54afba9255892e1d05af2015fdc9849b6c41f10ec465966c94c6d8a73781cc0063fcc2cb2ea4a5e41a6468d7d05b09e9a472e3f798dc81e10acb04f567425f4b44b6bf841a58881050b07e0b1f36d1a9eb237c9b4796a172f26fc6c055f2d80dc0d1b7772a17449ddb6337c6f0fb532457cc5ecca8a23185bb211ef14cc23914355914aa61e65685c6e9a556fb75afba3b90a567041487559bcd77c204ddbcd48c1b59adc2d9d1e80446d6fdac6305744ff4cb2606ecc1bd91e5d63c5f90632074ed92033ee8f92f5d7823a12e5cd8a72a31237370be32db8ad90d29d611475c4e7274c89a886793915808e76c84cfe7b907c1963e900f67b1dac0d3d8349a3fa86b4237cb3e8d51dbfa07d0ffe939f0b6b2ab39725b7c216a135fd157c1087275eac9e41c8ab3b3435609e23372b1687a619a9fd76240ff2793864e6a0ce4a4ca824849311690761f45ab4682752edfc5640eebb0553bf41b396d807ca1687afe6e8c5284666b3a4d17a398db1eda0a4e7c28563c05e9ba45e20ba25bbd59e78ef66c2478bfc3ebeec30ad633ede7d78d6448bd85943295107c2f38b9713b18877cf7c3a13b4fd3ff14cf18e36a74b92d3c8ff5c885bcf1e250fcbc050e49ccab442c0ee09e43fd18efb1a90d1a65bcb691a6b4c797bd9434e71289dadc0c198960b8745758481420dbb083f86471095b594bf2baac473dbd3520fe419a393d38c417b1763e36be61edd23c34330389bea0a5f3dd8640bedad13cd7725ba9cffea713bef958f980dd75a73a21eae0421815daa5d7d1d0bc30471b59aacbb1576041da32eb27adf9a36c17ae82a813168bad7370c7112c09bda51f54ce1880143534dbae1842c631b0801345bc3245c53a736a58b354b2100206fc7fb6b6b14009593123a810a1cc66f6d8c50a408cc36f75851d43eef2a60ad5b3bfbb00209aa45d943433b6e28ab97b090bfc9d248af3d830923f7a81e4019a3dc985ff398591ec542b832eb161d5c53b2f1f2608d4856c5c397d52d38cf25ad332f358a18943365fd8e0df612e66aa00624e863b124acc1d6ed692a51560a9e079b01e64952cdb298826ddb4c60df04ea18bc69b88d2b15dc6a7beaa04668cca5889b8a17fb8c0346b2fc6c89592680ee749bda1fd0877fe1abbb19549d91cf0860e81407fe98e0079872afb8c2136fb406749a47bedabe0c021d51076fc41aa6c8b4af686a8ac5bf2bfcb5f67919e3ece65dc5274e7481758afb4863d4d89c7fa87aa9a45edad2e390cfbfc84d71014307a2ac50f77bbac07b084ecae42fd4adffd2be148485f90bd9ee220f24bf2a7906d0f0959d9b7d880d98bee3ebaa605bcb7dc3896509f9529f9d562636a80eb0fd7879b8a77d4777e480fc999e13bae18059d6646918a735f5632d0c952a230362ebe56638649d554200a5f1af6e96e17b2f56872aec56afc84d9cec1f67bbee700be38c304f4ec408d6f188dec2db46b279e3de96991f9d6bb5c9f545de518f5c851e46df7774ea5774bea43e43d982dd3a30187d442bb1d9f576365fc7ecf60b0ef2e05a431e3548b998400a8617a3d0415695afb5d69a8bb4230d99df05003a835ac2a8f14129e7d0b3adf7077d3c9f0f8c08d5b6cdd05f3eb97a0e3272b776df1a5e9344232e1de24c45f60d3d40aa3033c7de7f6c2bd247099373973988ae0b25dd859adbab153149028e407afe90a755bf391ce800dc232a6e7d3fa6bab1becc0616529b23dc955367140b64b9aa9b0d0446f1215a02c3edcc86293cff3ce3d514e0334596e63c6a4d75b662c21c04a0ca4d1198b64597eb4a366560d6107722ba1261560996e049fe07ecc8d82cebe932c13c5a8b12bbb2b83a1641245853c7d10676b81de86107c42cfca912aa6c9d530abdd638fe1f81574ab14e7d0c701fe6197806f9f04fe32646720829075c765bd03f1ad51409f2930aaba51a68c5c1c6689abb6b19910163e60e2b6044af86eece9e6d1f2afa2deabb0740303d7a06988f4396809c09acce4c1179dd5c8d58ee4c8e9406faa3a33f15045766274ebb5d6413286f30d928a09c0093603f7592d528a99527c6691693343c6580207c13d06234d38854fc0ae45d56cf4cd7b90e757a6b5b448887215e96de4c00408e2abe17706642280c5a62774e988ebd4be3a0fe406e4ede30e04d1b92db9051ef9376124256f6293c4674ad14a27cf6b7603d634d7c5d3819c1c4f7517a1871b3d12a37e34babe7f11b17f3052a1e6e163aaedc243b590c502f9008d636bee4765b0f5bf2bfaf9870ed02067c58fd9318ee87a04b81844a533766523091450236a3f9c84d6fed16eec3eac21552aee3ce1ca97132076ededc0ca91f189c0b9b64c16d46b4ec60f2caac94fbf9b0d44e0f8cc55f167b7dcd2e8305286cd9e2c00cbfa514333c673c3df7d0c79fd2f7adb8c818c3d5e8cd8acf74620d4da61034b167a5bdc8552e789fe9db25393e1e613b812253a79a0fc705c2b739cbc0b774109bfdc304ac7db1ad0da9c99e2f8ad2a44712e078d3a37af231fa11b028e06afb9c6bf56bf754f0ca0ac9ba9d7aaedc96664278ba2cdc446712a497b305e7db9bb68a22ccfe167c16d55a5e5ba9571a810445b568cf55820b51c7c45869601dfcfba86e2be78e865a97d635cde561909d3175b2855d3d7ddb705e51b196b23d34e7536ad1af68f01e61bb83f9001cfa18d1e58ad0f43c7508e01de737bce146b918e4d5a2130183aa80e81c0e00eb8797db6bbfa001884f8af0ff0f0cb1d802cf939f264643f12418ee9a8fb3069de9f2e110ca5287b202aa33fca024d4674b3b30d7677f6ddcb52a52749ec48e5a633c9e9025ef20c8b75b49c2e4c77a06d775553eda37125864f6f2a8c42d64f945172b713743129c263593942f313b5a6d11e25da446d80e80e96f73f82138f59d2be4a916d7cdfde85f78609df8221ebe9a8bf9a09135a7864da88063faa7e37d7fc800a4b54f1c217494ea2aaaec0039668e61bfe4bdee1874504d7ac986ca944c46620517579f829c8bf5fa79019037e2123e83388aafa64e2b1fcd7724fd86dcc7782dfe44658e34501567590a9a414f07949f20469937b1ac976e1531c18909f0ebfffc1b030ff16e35df95fdab0628bc94867e60bd38d4830953e5741967e8f3e37d9bee925a6d9aa3debf3754182b78ff2c214ab188db73e65ce23479f2102df754e5ebb52df864241de1dfa02cffc74ae9c12f7457da40fe55001b987cd1442378b9c95149dfb552d31c7761450fe06df4fba4532af89b60d73dad6c0cc0a986cd19f5295f9e132fcee2c753927316e92fb4025d3b7f19608ad41eb1fcdcd90ad969c026ab0c122d96b05a1d379d2eba859dae44a800d2832973cb597f064f7a20e27621865999ae6c95b6e1d3e93222d02bfbbef528626cdc47b17dccb110f4afc11e3234ad3caca0df4819661b4e6391d9eb2bfd712c40ea8ed4b58c63518fb39de29cbeaa5a6dd00b5a71b01b7801680a8b9724050be3f3e5224c0fc094a485aac3df84deb8458169966c477e5229efe950f78824f2e7a2104ab4d4343c51186e014f2c595b81a8b22abec62d54264d0f912cd6098551e5fa37e20b8eca99bc93789c2d5ae98899a32cd1607f4afc41853c368e1a92e5617dabe22bb75750dccdb87260dd6cc951bf3b308ecefcb9fdc9e2e935d417645dad4b9605c9da6bc7b6a0857a44cf130e9efe2c1c1f8b3ea57e5b9f62aea3b0141387b74212077869f745064e1328bcb1716d4daead60b98cdc690efd31738520ee5f140610032478d93ba584119a543d086a87491fc339c7e50ef60ad1e6e6d7306c5530ca114e5c8b3ddb96ef8bd67348d67538617414938fecf12041a719ad10f2b452837649dc723e80f686d7b31477b191918c02cefcb7173621b03cee14fc6afc4282e39d15dee8f3b94aa93898c6f19a053542860f00f70fd77007b7b7f5209a4ce8f01f19faf37265ab892b664bf1bd9704537958def07cf6f149951f94deb86df41583b7d98c79ac06f69a6d08c199a01293281f6a74c4ee716d66eba129f319d03ca381154a58522df667bba8d1269b67a3a3d30172e32a7af73fc2f7000121792b3fcb04a6ca12d066110f669dfad28aa01d8024762ae2618aee5a3bb7e273d018f5d1de43c40f0c64222f8bf82b8553eac91087d3a3baf3499e8515ed9e4a1ac07f7377233b6d4a868b96c2ac08df09808d07343322a8afc11428bb8aa83da2306702909702720983bb622f3f2a441630083690fa5f773a80d0136d75651f8dc8255fdad7d6405ec4a9fe73fe7fc23f0e40400f099b77e46e4c44809d73fea735784b4d425a1a05a82bef50b2bf1a1014df39a5aae7b92ca2b01ac5e6f1fd29f446e7a0f1d43355209702aaf2053009d86d9800471a4aa351c9047a13fc4d961e8e4ca5ed98004f1e58d55d35137954b0ba8103ff29e94615863f351f103b4da353db1227ecf69cb269a436425738841a975b80aebabe6d58e219962fca5c226e0936d73d5605fad9f110020f06643dd625a80f23d990471a7501838e0316ed81bf5a501acf8fdb5605356f02b51ef0cffcb46402efdb274645ec0ccf6146d21df5ff73a8fcda3e32ca1f58a8d3583392cae5bdd882075bacae4b5e4846f9c18472c22fe2b9a3ca1605d23da99ea4af9ed9cdd4aa7d345ea504c7237bbfad4b0960c68a5e1c01b983804dbc18b4041e60b4c07413303547a51bbef09bd4562d0a62ed7467f7d2cfa676b0d1bfd8da22d3c4cca5c557473fa960e19688b8328db25fb454cd489f0240ae9ac28202765f9f5b5081fd39346d4b93598d1b7c18604c10250637679e90488800acc2f11b4c26c9a2febeae60cdeff43f483f7aa0fb71f2139d3ed8acdea4cde8b2b6001d3b89b0b491d0615c0616adcace408b8c118ab839e0c3d315c4a9274e639861edf0e86600fb44904ec1090c45434a134d1c803b97bdf85aed678252f1275ce931a3b180ea0faf4655e7a94f5ebba21bd6e464c9ccee598549c71733ba1e2d1ff80f646d027b66c92c72fb3d7ea0698b34ae16b39bf0368990bb1655e6d4e4575835a2bb658bfdac0cea3df760edca4c10442bb093c93c422083f3d05f2d865ed32b83aec37eadd73ebe9e33280dec41908f57e293bbc3ea33747a64438915fc647a3bed7b473876899fdbd697a83a37a1a5c9a8940ecfad79da2dcd16b1ed3e0b8a8cc7772e506ef00417874faace4da4681cd0fcca8700cbcf1c9892fb8bbd73887ef5f99e3fdf8d8df60999836f9f875190a19f706cf6cd4c3752addcb39483dd0f89d968e4fbba6aa20a5c7a018124fea8042c749c617a34b2812edf5a4b1d1746650cf114d2e99c30c930f040ed015b4b4dc4985e87b8cb9f8e8736a5f789f75a824961d160260e5c1080997c7943506a3989825f665b1c21de41c17f52d16ac975a38d687d6a139a3e21b91c83eb160a88285a02e67ba4d3ce59e1ce664fe327636f30e2782b27d2cb48ee4de9154d6dc73504d7bb209d836ac410a08d032552cef4435be26dd5081a55fefa01d93bfdc214fb1dd36c9ffe6c02f81d53a51b59002451c69374b38d2857fec602a2d43c253450ad32ec520f438351ee4696209493623d3b374ea24f165a6cc42096333b895bc004250a5aa693a555dc65cffaaa313115c0d6bb90e864b0b94dde42b08b68fb803f5fa2048ab096a29f6823a62c9e322e5dc0138ca1198bf1ee0a961733b0d6820d86b015084ee62703443435ea28609c803ab6a8a63bdeec264ac1593bd489209aa8ec11f7b53eb3e27325229e8dc0fd0f26b636a1fdbdd0e014555855f79988caab28b06120dd875fb62a84f65f324f02461f36ebc0d2afe8855851149a1bc7d6fcc9cb2f12ebdc6557a106faa9b7d808da76f724c05abe47e0ab931019665f1e78cd7ea2746badc1763c73d0c0ecaffaa886d46b367de3eb25e716e089ca90833c64860b70c020d786693f1874f8e20f5bcbb2d0da9767751dc443d1bed1a187ab0091b4935203c23535c5863ccaca15362ef149d32a12fa22ca99af117e61f785d6c05d358fa27b6a7597b446a64f1fec2e7311fd2161d33d5011b6cac38684e2df82a3d2f15eb7e79b24ff60320b799720022a8ae1d89bb9c79d4733966b61fda4685efb06711e49c14471f6c33dc4259e654a8a766fe3e84fa41270dbe1415739555c720e41717de123a9f85febcc802c0e47e38d090186a8972f2de5c73d3f3bd12fe5885054a089e5c4d448a35a56ae7ca13696df44c1acaf9a48e043ca6e33c32a974f296bf7ebd75236df7e3c7248a0bd776f8da07be6dc4d26f962a3c4d6a8f0944c7c2a1d2d6e3f03b45ff2b65871de876a4d3d373987294fbb078fb91fa915d91452a255a9fc3e231ea39598c03576f42afe53502961e14c58a462bdb4649b1ae31d068378d57f0d0c048a0cab1c4cba2d2e9e244eb98ae8e694509a0f0bfbaa5fdaca43de00e41ab7e561df3c7e367960b6c918bf75631a27e186161d0116d713d41f41120e5786507e2e607e40551b70c294254effb226d51ad7bf01a2e6f1f4948b2aec4f1c0baf9b6c2cf567664d05e2973e76838a3dfbf5cf6d591361cb46e5b9929649788470a3b6ba3f0d6dd7729be07ff24c907acf6cd1cda0ef386121ba7486ae1fabe1d916a5f247c96cb9cfcb8c230cb87fe9d8571e3dfed32b8706f24c0b3ec61113c17f194d2ae485ec9249eda99f19749a9241f2654f43266f67e85913e96b6078fbe7ec49913f180f58c34112863bf17f915aa7603a8c09aa081a26ef72cd693d27673a46d2ef34a974c52e44231479b0450aaa920b3bbf683417981e5f3b8a48ae7abf82373ffbb601527472cdeaca5adc2aae628510843dfdc14253ce16d98ac6048fcd9acd9c75d0f9864c7a08ec29b76934ffa110d470c387a1e5d2797cb9b1232b455eb8f47f84337216aedc961cb55cc4672bc509f7e7fefdf6110e498ffca5952cb66ed2a41c6a1423d424afa2e3673e7b82408bb27b37549de7d02b35b3d8c8110b99b0a90c5e3e9c49b27375719f72cec646973df2e83aff95fdb0d033702cd15f7f84a4c4abd9719425714de5c7d6e6b6fe9e3d146c7b3dc778f1d38c18518ab0025e5f5e754f3b05bf69d6aad327155ef729d9cf2d6082a3f78c5e879f4501362fdb76072b5ce41eed6f1d4168bec842ee45fde38b048fee4bd570699da292b3e518a1913b6c0c57f2c3983342839df81610dc195c371695bd85f61b0d18588246fa5b64b922f738e0d2c0984a6340c3cd9df8367aee7a8ba8441d59e406f327ec11536611972e11b057c45378b05c4c75e0810d6def98b4dbb846c77b3e01f581e67f78e3f5810cbfae071a79aaa9b12a4ec50383647aa27bb2813462a5db426cb0323c80f0e1800e5db2d8af718ea934338fede0c59e14341da9146b2b2704ce7361a28599322b93e8a87c0f82cc2540d539e4cc043b29a1c2fecda6132cc26d810cfdd5293a120864a4542095e912517a5291d6d326c2d10801de17431e5ebe0725a5fae840c97ab76479fd3face97a4de7c18bf0a44f8e445ef308990db6a15250e1da784cf362c9c88fe1fa96120b48358ddeda30693d4f16dbbe02f6c8975c7e557b3d5dbcff0f03b594abf5446e5820ebf2477bb745ba896bf0fdb7afa580578cc092bd23e6c0d2a830c1f98210f5a5739c05df1a7d2b101f45b9df8b72344f0861cb5ef1d0adecfbc904b6f5b6eccef78bfdc4e9b177453e53cd7149a51bd1129d39de1efc965fef5783dfe14d288864577040ff0a08f22f214798220aa7778c586b19d3ea26627a4f253ec23d6aaa6386d847c02a6e6ae17a11986a3043cf9c9e865100e2351dfa81f67c0f0f30ddf47914d76666480e790f3cc6caf0e65a5232e24df0d32742463bd9bc7b5f66916cdc39187e197f5fd62c2b5e943897662d04434eb708c5b3fc68edde7fdf1e2a6b4e641684e40608fd04402886031077aa25a6199f0f32aeaf48556632c68e4e8c60693dd885378618097834e2d5cdd4c7f318fb5a7573d5bf1cafd575bb5e88fa1c5d59655930f6883e0782a60361450daac5bb0eb80c3fbe3b9b34958f54fc39f293e69707e75ba15019e4e6158386dc4cffbd21f4406edc947391aa9edd09ff40d2704c2e5dbc12b1a9fcf32ea7a0c0ad79bb725f56f2ed9649061998d1e1e292220d56dd4eccd17e3ec6aadb8b008479ff4ef4d887957f2e5aef0a743f054e82f7ebae7ddcbb7896d3773ba4ae3d92dcc3ebe108ce4f281d6bd28fffca2ed63248f1d8073f0a4445c0ededc133c374978872c25f7de544b9d84d41659a0eac532ae687d592140a2c6dee439103482d0a51fc94742c9865b2bfb2e33f7f4b8471cee3357e290b3fb6067d9ba014f253e0566e78476c7900b66da4c0c512b11e970dce31ba84cf07fed6e5b8d446b3f32d8b48f525e214808142529b4f130f03226492611f4b45d6ca2cbde213411e204f8ffa1ca1f4367d0b4c086801f68e7101ca14a256e134ea91d8080f54e21dbc58b38933cfb1f1736059a94cdf3f520b9f9afd4bf8bd761b4d3fdf888fac90a6dd0dae30a966ff8e9d68b33ab8026c93bfedbcc718444b69907b93d2ac380d1a21886b5aae41e104d1afcc964172e37c0920a0c966efa011e4e1a70f606af1677b606e8c6cf964c22727c94108ec7132a57dcf56ae942b987188ca6f0b97ec86614218545a85798f9c40556f45aa2f80dcfc9531a9e6bf8d454f53e4322107deacbc81ffda5c27f5bcf4741939d5c84bd33e446141c1e7b4a4cbbbc9ebceb7bf27ec85d6576e14aef75f144b7b30b314a5c7627464316d6059e3e8cd0307af2855c883a5c8426f2e966c30f23926b0fb0ec610efd34235f79e68d1d74d0789142f2e6bcb7126b104c311aaaa3c717f757b0bd6dbfbdfcd21e8ede44b34c8d50dc8345aa26519d289a8f5032c4ae4b1cd20d8735a6ca5c8a5fe1941b5b78cf1cba92e26abb689bb3d8c098f37a6d5294ecd68fc39e34acad3030e2b0eb42351a10a6b0b08143f79976420df33b99344032ed6bdd757703da35ab313a39ae92184e064ee296c73219518afa2efe7bd914123df948843a6749e2f709ca6fd811921ab12902be450d1b4b554750fc91269f50265d41b360ba6b6d3a2a3612d64bb8880fd6eee6f4d92ae0f1da7eefc5dc11ee2d85832e0e7564be46c0e6db8acae3107372f72f030f4014ceec64569340c22dfbc0571ee29f3d55f407fcd5b38c0806d875037353b31e05a8d0a0851f05c4b6e29df27cc90fdfad0300f38bcf264a75f9ebe7d03cb98dfd6b2657d856b53bfb71f9fb16d2def6fd14b86008031a122927a91fa9723d9820a8d13a00234cca08daa74d8f0cbc2979a51875c36c5b69d814866656231f445a3edb627ef3790f254861827052efbcd80d01f7ea66f00005b35c3fac3db470aff702ae8c95840c4d4ce9abfc607d7c336a4b010407437e6a27cdaae4cc36ef2efe54008648f397f813685cc2b49c944b8bc2b16f07e35fe8cceff32df56c22fffa41b678aaa89aa97dfc02a753913528a1b62d7a41d2378c93fb9f5ea47a4f25336048b1dd7e070a646a497790d71e23e3f950fa548f9fd15d624cbe7440c22bf7a541593ae32fe1825ba164a8da94626628a73e9b85140412666a1419a1ca71feaf537934c0f37f4ec570cd230d5a0c3421c8965887dc55fc44401e8eae27c0b50e498cebaaf3bfc70cb897813860cd958034506cc1a5c87d7b86a994aaf52f9059317762998b290d93fd0fbf83e2722fd1cf482efadcab0b9d64b6ad9dadfd9b40eabd4186bb9486a5711034b357fa85f503ec5ecc43c5473e115168f8bf751734b3108b5f262273f12536870a0181fa4dde486e60d29040f0644f4f0819d976440d90f46df6799818b6fb4cb8bdaa2c281869e385de59817eec2c2c6749d7a500d0ae93115e4c65c0641f4146c0db9857b2874f5f4a6ec11f426f6d9da69890fead09cac9d760403f3844449237a7958d60eb7ea30548160461df0b2ddfe0afb6e3d41c86e20f860dcd8da73296d1f042546f0bac9ebadbabce4fdd0d7828a932ea992455c4d2c89beef60741748504835b011cebafddddd799b772116de8a25b455f1bf6d13a705f9f1a96021474ffeab8bbc66eeb20e9d4da66f796db828c941195834cdc32f08007b18d2c8971bcd93dd906ba9d3d4335a1678c733fbd450b91349285d79a2d650c90410d9384618a93bf24d662135a3f68ed179c06adea7ba03418fb720b6f8be5ba9840c1ec71db2500025d52eaf1b210189a140cf1e4fe107eb35fe7a1080db23599de1329566388ac5ae7141d0c9ac9a3f2fe4ead32008996a0a68672dd1b6cac4ff0ac9eacbdf58b1c42b3361a191ec147f1fe2a036a6f347f85fcf23bbc247ca2a1c1e81ca55fdab054835403736e22ad89a53dda396d60e1b6dd78c91f1bee81aa96f9e623d81a51744db4a0f34e72e7090f3355d4154e5d06c9c87cb191b0ed74c681de0c3a418b38340598efa8b22c8959a6d787b30acd679b6e860b58cf9b00eafa469f1d1821f7f26f2ee70767736e8effe4040f0624462dd800a760ff917beac8c32da7c27396b04c2f59e88dafe28378c99f8cc466b1a3a183ed4d26f219d8f82840375f57c03b559387e3c9369bd19e8ec24b8d79850a116ef89a3f99406938992117ff71e1c3214e1f92e40e82168d98835f0a2eea0cddbad499a5309f3a71e08e0ce1f2d1594d41674a8740599aa6c86c7aed0ffe0c890c999a3645ddd3e03b99bec7a25dd523b91bd9dac618b615a03812b493ebf79897aeb65dd7f0b0df701df149587213a87034ccc293545db67e7cc6205a5ee1a945096c8772466b440ff7ff7c276211d4b9bf8be9cab4dbd29ad7e08e7bac07e795ed47cd24782cccf703148104d14102292aee5d9c65da1e69cdf9e9b9e351494d74355be5b7109f9afc819f0c437078fdba7423e8c842a1d010d2969605c3ec3f8fcbe10ac81d798ca3689e745302017e026f6efc8581b3f1349810c81ae56ce61fa5b7802d986900165b9d7b1957fff2549c66922d3f33b38fe533ce14d2cade68c4d9a7d552c2ac8a93b2bb7fb149a33b6a647717a23ad33f6a57103aa1ba55c887c86d2e47425d7c9595db825f4faa6b3b7a582a7ea3099e0809cb0228cc97e7dfce12018c75030cd23aee56b599aecbc7965b4b9ea0171c4b8cc6a283d1048dcfe336de85f7683831a7a48133587592901eaa0291d45d5902d368a175db51b9ff464a8dd5be8e646803a6ab444ae271f0657084cbf3abacb16d41aaa0b42ca7c9339758b6b321fffd8e85c5f76a8ce4c1c700ba5f38d0082740e9825c11c4c57c36191d4321a98ac8e13f9d2df9331b5767fe94fa10fb62de3a915f8b6b23fb3e5f1bb24dc495a55a2d2757675190173d995be1024463f60f9fb6dae736533e2180d1fd39d078835fd6d139f537e3e49e09e44db887a0a188760dbc3f6dcd03dccd0cb75d6bcb7d8515e2ae0723fcab2cfd964958f3fece1caf8b73d340ef0df2901a09d659b3e46bdcfc9f20ab9d7ecaf4b1ad38758368b50a67c38cb0d5b63906b0504afc0f317ef1b93875bc7fb63c9089d1112149c614fd913a6b3b41636156eed565afdf182870f947e1de8b0262b226e291eea6fd138a8d86abbc728b01ba926bfeb2242a16f6e4d8a5602b186aca54d9303b04c7122ce357dd3996d70209ddf8b7e29ac5cf7f6049645ba3f0543c5ea53023d108db18636ca7e1b4dab86c23ca652fd7f99d3414249f31bc180f5e7bcc0b1c00ef09c712671fd9a3f22a286da3279f36832cf211e1e43bef42ffa31bb1edda44d1b18bec2b8e3d74843bfca12ba16f08cbe0f89d8dd2f41965dbb98f5382cb1866239ab8903003463030f326cc03955ac68f0c681f1dd6831eb74b9d2e5f457fcf7e999f7312169a722c0a4d4376ba7a39aa30a68ea2f65ed5ce4e8cdeddfd4e97c3fb04ae76a62f286160df46ca9b6f02a1a66e9eec9201324b585fd6621cf809f6ce81476cabf37af095e17e9487ff197776e49944f7e5ee6813d8cd50cb73a6ecd6c5ed076aeb29156d9ddac15268144fd8bf235b895ce29cdab207c5de539604d06a7409524628e641fe4a3cd2ab2d7d7160ddcfd910b39c114cdddb942ccef7eb49903b94d0766355cdee0503c8b3f9f258639c6778d35a931170393f97fb4b12723e006e5262de3ca275df5e0add73e0abc4a408bdc287a3c380ca9dc0a86fc9020cbc1922c7e75269e5ff52e6e0c62eb9a3cf2135d74f57c8a17e5089f99be0359388f733a75353e60cf214034f8c8af3af5d0fc8f3b361b344c559d12e6d5cfb4a562eaad6afd6fa41bd5b7ea614486b3ab69c298f1637b923e2b2b47991ec2753493d6e6b6b818d05c7d3e539226979604b58b65d5a2a86bc407eb700e22697c9aad677b0497c49aed6390470855300137dd16d2f17737478eeab2a0b4da2c41776e2c3a9e95de0cc89ac9fff2de0125642999d2885241d26bb89267cee7eefe50fa8565a6b7963c479a34b7b190f7d575a6fab03b1a8638ff77d23d1188e8a6763f872a651aad715bbb7f4d7ef1ed9517e2c65e8bbf803b221f4118e38340d80a99cc0158527fbac3c394dfc9dc7a983fb12464a81cd126f2ebff3c3c21d22eb3f000719568d7c3d4ec1d6c7754cca8703d5cf3dd12392e154a7a39c709867e278db8537205e0249ce2da0a11a2ad5e94a3bceb1e2ca7970ab0a02008727bd43a2670927c8cfb01c16ad69fd237c42486f5d24c1f2137c454a9df94257a93cd680301fa78ab6c1ace88ebce8a78c01bb138d6fd77e835b0806165b9865ee6ee2cd7263e14ddf1e47ec56ef33c58e3d87ab5db3921023b56340d14b8f61a811d588734e4a572c292d6cc09a28aad5ef002333f945436001c750adccf8ec9bdf190213607ff79a1a2332ac6aca06d5e303b3bfb817ba53d7eb7f9058ddbe31748830e2803e90714e1b3605495da118d1a03f983cc7424c0997857782362de776ae221361263ca8c1f9cf84e11d1c7b348568e98f4eeada5efa2f9cdf7207e334204a923b07c01eba31d6c164593efb7cf2f7bf32a89286e4db615bf1d3853ce7d3e4e81b5df5130b329dd40bdb2cf78d07833d348ebd00767a75cde265c8f4c252d3a6934201809cf3e5c93dc96d8718f955a1773b1b96e8846921a9e39de819a8ceee05cc57a7733ea26c6a74950b235b676b6c8d76e076d99392cad610eaf9e6b5999ae89f8b0d4de32dec1a8e4e2da32c25160140eff8356eb3f8f6987aa96644916469f0bb14452528c5fee727135ef9a502829cb934d0360cf21b819e57f5a4fba7dddf41b682e389b057a2b769c6e08038fd8b134d05186251953dcc9719951f97892a554f66aa5126c8e56e2294037b00a226154c4d5a8c5b25ed11f0fe6616b82953738e3c36d89d24c7f9ca47686bc9fbf99aa0a9c7c2f1a760b06244c62bbd132fbd57e4e4703750a765dfca7c4c2bb62a4771f9a3f2cddf80e3315cca36b22edd9666c4ce84b06a63951166ee0b31a308d8ab9c5ed30bcad80a4c5e0a5b3934a1bdbdc9d31baa38c4ae1f08aaf93a5ae7bdbbef15985ae46ba64dba7e2e8429f768e85c1b5f474e6adf3d7865e67d088175e19dc4891e12fddcf109f4391149eba4182c8b40ce3168e72d8440ccefd028a3564228b5a8bf50ce0d0bdcb715714de7c03223b3fc5dab9028ad5c01f70ab462bc9e47a9e2c52109d74d4ced47a69bcc3fc804571b713d9acb2351b8bcdc8512c11d3a0b880a4958c8ed915fdb43e7c809548742f26f9536866e0965d15b4b4bb4be2129bd4e370f205d422a1f633db0c23aa4fb9c56cf912ce06f4550234354c95df76f41bf3609f86488f1905dceaf4440c4f95ef54c83609dbb40bb9f6f3bd8716785efd634a66d610b9888ede8cd668345ec19bc8be57942dfb1a3ad557317437149d792d33b09ba924ccb6501ac735febd81931b8b99e4dce293a739d4bd843cff676faba84d04e1854dc7ff87e51b4d41cc986caf683f235ab105895c7b9a502edc36d3ac8a38ca34f2a709b98ea08953a0eefd1667778b022b8276299d725f719f787a96381278bda1dffa5fd74787aaae8de3608bae7a460099e96beac67ebd42c4fc9df4079fc6ef0fb090748fc956619d4077cadb58684a268413d174ef08c37627073ae16a6fa2eee24f3f36b358bf77e69cd0eaf23876961fe8c28aa98e1817c7eafdec3271393eac3ece1e516d99413053c028aff6fdf41775e8731748d4558267df4c32b3b0237c7ec7da9601444ac2d9e59e8f0d614700fcd1884d693e67f609061258dffb58908344700daa7c5d9bd996d7e622fc29ca0647b083736f40f6106b83594970283950a0c26b83b0dd5d685a799f5b707c5884121b11af49aef8d49b7ae8515ee816b3c3477e1d646bd0419bed03065953883a06575c3ae5838bd8dc67cf27e43643a598f812caebd24c460040f5f4dc424a80f05c4d419c6e6df29a7fa07df64214aba35b13a4fe72e83b3db5e2800814a4f53cc355dd74afbc6ca93ec7e05b15fb62c5fef70b44f1c5fd9d3022119cbccca5de2e0644ee6dcc7bb6b481a2cd30881efa4613e44c202ce250b4e3db83803c2d69087f7f5139ad9c237c5dcd27e228181e4811b4f5da9aa049e43f900075133ab57c4a89c0a47111d81edf844da54454168ea076aad8258c8a323e49b73d703e57afdbe1a6ce2733faeb53b50200004f4cd66262ebde46847384978dda705c1cf8ef1283f908a4cc82f6c973009f88b8cfd7417b0369705116d8e6f30b98854c8f8918f488c2c932b09850825cd5ebc211bf2869d07d0c6d757c2483ab50eed00e6581e03c8d025b89632d9da3e19b50049af1116244447a79400c9310eedef3dcc131dc8ae54d66d4760de40dd3d91fd36a5fd95f985545e1449ae5431dbdcb167bbebae823e8c5b44fec3ea1860a94234e2cf88b675d1b4062e96eb20aa0d9f6a44d345e21d756cb26a9d18c7b98940aaa210981a6fb5e5442fe2e8ee1b8a8c3ed7056f2e1d501cff81c62a76ad4d9b84786be2339d19dd27d439977c69ef0b4eed5aada2af50467f2d40cf3764b1a098ba93ee0f19ab8979e865ff44c4cc93b882b66ab369202588a4e816b3ad7ff394b041c092460f1059b66ac51dc034c3089016ccc86747bc7cded584cbb1c3b839082ac99047df16e56a386f707538bb11696e5d5c619908bf0c25109f2e9d411bfaf99bd663f0bf7f1fc9e6c8cd5c5004c1e45816b9b096605bfad8c9206e9825197ef140dc67c729d9231bb80e6e3482f714255da15e0b762752c0b6e50259a539a2027c6d568276cc35cf51cbafff10e27f19d51328f69d3c03396eaa28f98b5eb4979f2bd752ccb485d8b5f89720bf13b71abc99250ab07586a307a12a5b04c0ed0e3c53bfcbc85e56b1bf4c7f7b3409c9d6ce42ac6b0fe9cc14df2f72791a67b91360e6f42c7a7a98ef78c9e696458d511a5f83018465f7d2a8a9f20c6d0c0c8aa9d81611f0a9db008014241bb61f03d3e87c3524a730fc5ea764c673a2b1d6c1acbb9a58f1a3c67ef333b90b8b3007e7c873cf4b9c109931b95c51968c8ee60872d068ce9413b4803616f88530433312124195761334923a46cae89a0d0daad9ecc9e55687bcdc90c2d2bcd35493ab07698d30f127e48c5df50a617cd278ee29564dca33783274d1680e408699a2479af1e98cd13f00480db7bd77168d7087efb6b1cc5fe462d386b72948a1b401febfb308ee8708132b04d7f793a24d4a994e8bd09963246d7956f0ccb3d662de65ca5526fb463831e1c763e5559deac90a0d9f33610726985e34448db39feb0bfb93fc5000f9a055a219e04dea6859be8d915abfca7f89ccca6a113e5e003007288be2c264117efb0b66dd4b4b78409e1c98f192137ec41f766c9f36a9e187300aef977e889d0434de2151f5a00019aeeb613b1382e776ea4b1f52721d0e4ef38c932bc77d7c9fb0aa7e1cf4ab777ad526f42707a7ea6543a1dbeaa286dca06bf7f335c869f0e26607187971d43318b39a47175bed924ba6d0d4aa7afc508ca0da2c79c2455df4018420e21857444e3ad6655fdd1ca4c1782f94f5e2c1153f2c593b5dde96b908b5817ebb18e0ca81dacd2e5edbef6ab32f79667010c3a96426b435cb294863e9378a8490b032415b0c646b316890f0bbd5fb275f76192162a342b954e2d660f92fe34b39e677dff87a5c2d9e9f8e0d892a57793b23d74072c0f24ba4c33167670e5b7865b64ad6aa25adaabdb17c931587170bf3134719e6448a5dab23214767af47a8396b4e5f0c9a162adb87d4863770e0d0f9c5e25907a23c8b4e7a68a6b7e25b902d5273aed699796e54fb323e37de635205d11a38253a8aba649cea7059b132b04a46d9c1df77aa6634025f818125dc1fe93f1f3ab225be96cde61393873a6d0176d914234d0a8282d61cdb874d9c4361182ac81acbb5d11ad91c1e165bf292ef4558fd37f42f0470c043ffbbd340bfedaac0c34cf4421cb74df0f4088fc3b329a893190532151e920a8685e6347b2da672f7b494cdc2754ba13f23a4a5686f3e95f9a34ba1420cc9f942a75fd168695d05ce85f36adc59dcc542f75c421501e447671be2cce3f95eb991e06076ece5e402c28932b52772d4f9cca926ea068b5fdcc3be0f3049c9f985cf3615f2b8f54604c705813c50f458681217c8b1d5a9be7d93954cc865af6b0e7a3a8da4ebe45dae33cd8173bbd73ed73869e2099dd29e6e0cd941ed6638acc944dad340111a86a6a08670f16fa20e4d4c212282c1161c34c81522abfafd66f20440e631d4860cec23e05bab69c8eab77e28974a96f56606013c0e1862b6c648f197c267f680761d02eb92bf493e4cab9c548cc6cd8d37eae203fed2c9e74d6cb6dd3b6d10f387be2abbce15c93df817ac1b7ebdd14113a838b5b5eb30ff57f2ef219b51f04c0abaab42c41a9fca7fa36e6b554a76ed9aeb52c1f62857fc9e2bcfd0b763b9505fa70e8632a35103ba086599fab7dd5b77153277b9edee015c5d37d146a853c49dc73600890b73905bf06d865fdeb37add163df3cf73ec8dc0f6243e5b05b09e89f2d041dd4a027798caf48a6bd39e316c1ce4c26bbf69ee7a7f0058b74104f9361596aa4ef5b2effb7b676d5b94968bb2af88f717e8f9a3840d5ad2b97ed90f1b813bfe070fe4de871699830157f5226768df149edfa86e8580df2d2a0dc136cd17c9d1e85cd9747538273539574354097cdb0e48a6ceeb225b5937fad5231e4d4957f84828cb553fda06d799272ad3f4bce89406ce060a7c2c4468cc5cca965c59086afd261db2f56b58021829a0186869dd7d27e303101c57963656673c26ee0a236e502fa41d52abf441a462b61d6897ce569c118a3531009c1e3a3a362f16f3b22afb29e7b52b511841c3fbb20758af81bd582df97f2cb116a343807acdf523319c96d4930b8cad500c257c3e45b60a0020e8f87df85cd1fe1f49ce9a3fade3ad138775286a83c98563c1e14a24037445e5c31104158064163cc478367b2591d1145dbb1019f54a282fcacdd22e9917050730b39db44da2544fce848ca65a52636847c0b45be46fb1ebda4de049388484330625afba603130802d534acff268dfc6a1c94ad780b5527df93ac4fbb03186c4c1428476b64f1ba319f985adfd602398fea4d37e6cba2c036947d306a1d98a7e433a6cf4bbd901d7ca29067980ab83276186120c09cfe03511bb87500361892160416e4f6bc131c35714f17c8bdebe8f2c21e85e5854d29a562e78186e67886e19ef28c5b6ec6adf36a6c3b240c79733613c3bead86f9f87958aee809e71b5c13206fb699275e54a3c06aea7a076bcd6f51797c7384be8452cd9fbf5319120d0e7d19bb814683722bb211a44797e7ed77860502fabb891900845291bf3eb7f0d3ed8ebbbc235b5fa2829e60e3c3b9bb9f062279acc4ec827f16536aff23b58d6d6dacfae40fda42cd1506f7bc744d69457682d1d0389de5b2e92bf70336964b5268989660c90f4c1991aa2dd0e84b0fbea19cea046b7cd4c91d0ea40e8e77f37755fb91285abc3ad987f6754cada54d6707ff580b709fc8cbb909a9e469fb7c301c439c74dc0ddfb89b4cf3710f02faa93e14c031fadf4cd60418e1baf26a83c0bb7fb666392ddfe33dac18387799d06e7356898efa41bcc041b5b24731e731dd67c564554c2c01951558da90d02cfaa75f8a949ca7cec6e880f287ab76bf0123c2d3eba5e26640a12bf72a8a114d61c0f5e16e1d21b86f560427577d497b0827e56bd45f1e86da4a0b1766ba34727dfeeacc8645c9d06cd3f55690c3fb7e49474e39bcee88de2205729d1e4d9b0bf8d8ee20c23b59473e77656a802df391e9eead21a169421dd14e161215c5966d6bc3450a808c5e054ee7099f231710247f32474a71b8c065108b1129efef5a53b160dea188965dbb3ad5a2216b50e0cfef96673366fc327f32a3e2065c2633aa815fb1e5b0d1b3ca9f9fc4b0f8cec1afec7798ae0fa3bb37041ad1f6a50564c562d93f2f7ec04410f7bba082da87409fc37c5dd166b5167e38c7886f7902afe8a7085809e3ffca59167e20f7aa799d4e90b7ddd561727a5d89e1fed86638c903bdb6a5dd17343b97815f810f6a4e7e72bdf6d0313b6c0fad758e1f0ce4c272c8e804c48f56ad11925c06cf79b9738b717a6d0ac0561da78ffc74928df5cfd767dfbe0277b3a062b169c1b609ca2abda359b1cbbb3e4059cfce7ba0f72b3f54c3de4eac3a5ebd73101fd71501ba6d1a3ca3c245be3b5c107c92cfa7549650d404bec822313fc2ca0652f2197c8a9f0e61a5270511bb36d065cc9c25d0ad53fe7090177eb3d77257f59d5b4580b7e27b9e00426cf78aaee62a3192f70016c7b3ef65834cd0aeffe3b806bc05408b5855fb45258986baa040f680dec18fea6027e7cf9ef9bc8e5dc481eb3d3d145c8c02c789e30d53189ff23c724b8511700ab0fd4e165e1c13e9840ccc073996245983b1a4214b0813eaa8b08ca0b964d38fd81d10ba3cf4ee1c42fd4a79104b413efc31bddd7c557fdc9604e710fa79e85be74f1acf3902aa82872ffbd97341c9ff889a692cce2b5b925651e8bbc11dce989653fa9dc05498db6253d6237765d3f5077f9ea11c598f932b01d2e00ad8d37642605be9e390696d7458287ea42ed95c88268849a62c35d9f37876b0084171e6898a9d338863cdc281b92a78e67776d1e57c1cabf81bd965464a21ad1288797a1d11bf043321fc7326ff3df51988a40860f2724b4029e3dc130072b050483b7e83e400340406b4e3af991e88fe710f0b26ee232a4ec8b41489a814f89395e455f653a76ec896dc465e506f3b22be78e384e32a69b590ac7caa6538030e409b3dc3274778bb1c269f9305c7293a87de90cdedd4e328e252606b48de5cafed77a4654afec5626aec00e671226f1b20d07483ab3f12797dc28a055d808900303b99ceab5904d453e4ff0976d5ad51dab6611755176c15c78f7144718e1994bea37c98772823bf4c446249d74bd260c01ba94523bc359476ced62ae38b507c01ec6106ee17c2ab8ad9dc08e6b7b416394744e5326018dca1dce9f39a03cf7550f70667a7597e2c6802f84d5bf1c83086215983aee4360bcb70c1ac6335a5b5189e86b11187da08fd9b64f769723a97646a72a5fc8a0029837d6ad1f37dad13c5d36021d902f605ff072435bd455776433052b4a4de8312a90958700630ebf60b3628f9fc7fb07a1dbd4240d5ad93716754d255862af51d08e74b9877106b06b3667f82426dd924bcb3a1c6f2fbd2db9d19a45eb14919b04b6226ed843631823844456ac712f396d2e719cadeee8161be95e054afa6874335a1a6e6f946c9e2c409057e2ba47478d7fd6d5fac03fa7aca4e53fba352c19025b56b9d28f8471c325a4d328dc66facb403a795917fdc8fd6b97d4a66e79423122806e64b6ac245784faa79ecbe8380ccb0d0d503394d356602061fda7795f0da35c05aa02db82d46dc3975359de91f837443e6e9b4b45050d17073f90ff046316e95e88be8ef9f7baa5328654677dc841c81d5ef202e3c625d5cdd23660300b9ba132610cdd3cb8d6fbe245f75a22ef9a8d571165d8ce48f350c04037f3979c1b6717f18fa5f1411f2c06f237055e6dfaf78e093ebe92bb0100557c7575a1504ec2d511c50379e2247ca96b14ee1566ebaaefb5d27cb47d072a2c5b58592396d1ced4eb1bc906899dda3e661fd1b01a7ed6e0def6c8b798a08fa0c5384c327408166d5c939f7fbac55b545632d222837280dced578bafd9c43b2f58f8e74749067215076c69f3881f34291f3f746884cbd512465609a81fe798ba83df27548c170a79fe7a34f7db33738097cda13b63f145ff874f5aa200f8961aa3c73b59077c64a6237241a11edab6500b4db90a375a2d78d90ec0c9626ae4ecfdcf27a5a9bdd1b3f927ce04134397d4f92380b40f1b133ac780328938cf39a2aa2bc013f3ebb829698dd2454b91f452d924492f307f68a98fa734d670648c65681a569bbe6ecda771ab449f35fc5120caabb1dbf165f98bc89b79e3d400ad05dffb27d295875eb6ede093e4143f54a9efe5a7371f66a727c7d5e80a98d416318df4d20b02725a280a4ac8905685984fe7b44174d72c3c53510ddb91853a2c1e18e3fef92a1c792e50b95ec86eacb822bb2b7350617472eaa901746a7fc7cbd0822b623935660773c50f9b5b2f68a48f547acb67edb01e479f72f6a4884b2f03c167ec2f7bf9ddff626e1fdb84c1fb71275d47ba5541d5410d9f7edcc2254e6d8528feabbc53fd57655d65ab1e97bc171a67c23a70e9dd7fe4ab658c17461951e84a53cdb23064f32ac6357f2c17d76e9da561d39cf7aa64551c11e26f2ca5cfbf2af6ff7079b9fbdb7bf872dcebbdda6ae0dec2d122823d9730a4864a36776951c3882"); + assertTrue(Hex.toHexString(s), Arrays.areEqual(expected, s)); + + sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + AlgorithmParameters vp = sig.getParameters(); + + ContextParameterSpec vspec = vp.getParameterSpec(ContextParameterSpec.class); + + assertTrue(Arrays.areEqual(Strings.toByteArray("Hello, world!"), vspec.getContext())); + } + + public void testSLHDSARandomSigSHA2() + throws Exception + { + SecureRandom random = new FixedSecureRandom(Hex.decode("7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E4711E95F8A383854BA16A5DD3E25FF71D3" + + "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1")); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, random); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new FixedSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"))); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + byte[] expected = Hex.decode("7c65a4abed5a4926316228c52d815b0086c8fe9991254a563db365e340d056dabe5b45ce9e46f8c64fe65644d3874ccc9ce314b2d12d4903188c110fd21a6e548aa995f2c6508be8b60d620a906a0c3e394f31003ee12576d9847c508125058d1f030dd91c5da0026190f3b0f5d18051621c87c0334c644552ed94dfd8868a13ad90d67471f6ab3891a0a8a3a374500faf30f22c56bde568a89736d0a03203a23ca48135c86939f4e9e3ece6e3be79e18d33bed0b3ce7ee69922e08c0a7ecb1375ec93b0393b7dd4a3d64a8c030d3e7bf144666fbb67400fd38fb3b788460eed49439fb2093a01c21cdcef6f2ddfe299a3bd3d675949c3c04390a9f39c1a0f4e99e6c49cc8fa3728c0b9fdffddcf560b791c00e41a09c3baf99b192d519bb6e095045795ecaf4299bd286fdcb27045ab863888807361a7497f24e014618376041a49049fdb572b19d0da9ac4d35a7fb6a9d18cffe0f6edde17be904747fced7b670d7b0aa8f4706facd6e1fda80b08f62fe2033889bbe15e40995f71dac567b962927c16a08c1c2141e5d5eab881306754c7367849195538a8c05eef8bd1036962aa6a227cdc3772d3f9c142f7f74661c2daf6a094948765247a0c760851b731077496222121b5e7c852ab0021d37a4743242d96874d6a58ccfe07490415b482de7ab164dfb19056c93bca1c0260733f93ca7294e25c7bb117aa37101d705806ac8558d3ea9abf90a500081b77b657c515e2eca4b3058a3e9b63fa8b7a83d0be55828fa4f12e7cf663624224026ae8935f1b99b92128c5ef154080f66cd361c22d020dea778aa400011d212900a730e45039dbaf9f92ab4cb02aea28f1ea0ea456c399017b1a7ed410874aebdaa94cd8f54f16abd4b0193614c5b2f4d28bd3fac84e4881c1c92db162d9a441bbcf668b8acb050721ef22e79c7f9fe8675dc3501c7dfeb8f691d5ce390905d3bb0b523c1ba4694e0982669ec0a96aaf2b0f72df752dc627d71cecfc027e59d3ed440776831e2a8ea09436a504bd30c2b5bed18e4d5fe270bc5ec98e2ccec4f2f33b864f7912f45502b6aae2a9275e4049c7e872887a307cae2a0076b1c74cfbdc1ea8ba6947e683caaed96e84f451ef643e4d766e18ba6dd05e7ac46432957bc141deb48940261200444ad2e6b8b7fd5895c7a4e80b494bd1b648b145de29b718c7768f16dbfbb9dae1c6f991a57664aee425b12796d3739c18d532c9b3c37e8b634b16fff898aad91fa3b20853183dc6ecd535db1d953f421c2a195e781763f7c8117c6204b8f27d5ca74873c5755fdb96101b8a43e430207ff7d1a661bfac71f4261080df592a700f6c687b788230cabbd240f000fbeead9d5124dfaab331b709ab4165efc89a108fc5962a40989b8b413140196470e723ba6c45fa94dea7d4ed45c7fdbcbab9c3878493ee44ad35bbdbb77553ed2fd9e7a20dfa55f1875d232333935bd529eb1dd1d3a2f5f0b291c31d3231a719ec794059a89ecb2f12fd6bf8b227bcaabf0d43a9791f8f9190c31da568df59774be74178e08a80cd77ee6ed3024e3f530a4a32f2f36e2369b6a7e9d7411b2233e7a1e80e43b208324daa82bfea001311e00ebf9ce6631ab067e42a411597db903552261c289a619a459185a44a3cd26fd72d942df7a14434c0afc1a4bde8064315973d26c359c774bc3e4ca183c6f9b5c60c5a0566156ae9cea689e4ff1364b491d5b49a18712a468a2298994e006378bc9fc0eec56697b24dd0c4e2ca2d4bc52f3fa995df91b158ea726526700100067ec6a419571dc6a64bd5d526aad6f375891a04d8d81e2204bb3fdf7ce553aa90e07e02d3014bdc16b9a3d08f5d63880a36e13c30790ae3c7cfeb67061bce2138d1b9124a95b1f5c3c0f20aceeb7c311a03a0ae11574890dc998b54ec0145411c773340b96a5a6da30fd9ee7b56142414478e0a78f9defb187f8155e6632e13e272f8314621214e5d552dc4de3c8242d618919f000f0646a86ab494d9e0b840f13a457449e95e7803de4897b2545fccba471c44b8bbb760e84d173518672aadccccbe7e8cba8681e78067fe63bd83f26afc04fe93a00923fd73707682c377458bde04d4a8b4a0f350f6eac59c10c8ef739e4568c9044bd3d22182e881bbd8f727a45e1d7e666befe8c3640d325284c29bc22f3103ba468e9dbced0c9025a18248bd822d4652a756b6643b18590c6af2a3d77f72061d2ecefeeffb7fd0f770cd022922c72454d3bd4ceee3782901a5efcadd2b899a92a5099caf8ed66bf182d6457e3279811cb712cb269ae6a484626f27d86638c586da27fb6d5cd1fc2ecffe7603fefb346e76db89b9b714f3e0cfc3b5d7da68ab332371d3bad9dcdcdd294519374779b0fc0216f2a2c938403eea1a501906991c55233eeb63374273076a72f77144a06bb67cfa70babc7fe5f6739a9e808c7643bcad6f20da03f6071d7296d601a4142d2bb9f015c7adfde3765e011097e5ad4b29dbe47a50f24732370a1b471ed304e7d0eef3a2598e470e60d8d61af0f68b10a10543182abec726f27a452fdb4f669b02c908349e0da297a5af613f5e5d48ccd83ca4be57e6ff79ddf74b31ad8ae715abc8b1284e1caedce4928925301b538aedc0e38fcce10fc91968ba8a68302755b9f591bc179e3e31e5f820110328dcd58d46cfb71a1fc29b51f00dbc078fccfe00e6eeed39bb49a846e2f3674cf79b9b208d726ed0615a5498d8883bde48de23336a13935a38fb95a762ecf4ab53883dc434b4515e997a408494ea2f2abcda0fe24b4e9395de6cab707d924de8a3323de5057c8047f97ca27f9294aa319f760ba5f78a3c834e96bf89a3284cc584139503665a2813944fb3705aee1bb866cf5defa5b26c9d9169286fc56adf455f6c6838a2cf20358dcc081ae06079eed74b3fca1ff617e24fc2b8fbad7aad505ad1de9105bd59da2afe2cefceb4e7d7ba5cdcb3a43a40b06376ec8f7921e9b4abe571d2a62015107d107bc7f41b01a0eae20e9495b4b490cf9dd451201828e8ec4f9bd3840570b637adb24d979d361be7940fe570bfae66f0dcbabf1ae78fa516d106e2f980a74a39f10b1f00b1e96046eca047b471a212b26027b5b13853a2eded38d148e0d8c98be3aca48f0f581e9ae091830500217bd4809c5ca3d38f5939fafccd29aa875afc61fdcf96a1b8e207268693d8748068b9bfd73778f5338f772cf0287322cfff67f7a2f02f16fe0c5c0edfb0a4a10dbed23f62a6324c84cf06c3277c8dcbaae6dff3130d3af025a41e0fb06d954da1ed8ee8b551001b2ce6d5dd3593acb8fd641ad822ae8ee5fdb97fab411659dc6c99c8dab505637b497269c2f8be104db9f1e8ba3002866a2bbd8f6395e6652af64ec0153060f52602b280f64563483d41c8bfbd8057ebaae1c7d43deb5355ef4f4076c9d8460784eca581dc987758440624954704190d63e77ca6ae535b9c81a1dd84f3d8d45c574617d5af921ce78c10848477730d36c849603ac80100bbc27a245c38bf9d3c04df16b0e9fb4d7afb043273ca33e5d0ba9ab71036cfffc4fc94fe8957857aebeb1c7d13462b205463a598e88c28d2155eb7cd136e86b2fbb2d453d7466887601f912402861de0239740b61980bba4cfbd12acfd7c77c74bbab585d02230492f01090ce439bb4a62d87a11d55a99fb303ee314ebfe7ce91e7a0a7a09200f3e27b07c42ac239f97bbe30b67963f3eeb86293a134b7a78978e1599529a17049b377245db909e3b4daf464862a15e38ebdbf484513717d485abf438579dc03fb7317e1d75e12e290afbb946aeaadffb449fd6b06edc3024045d9aa98932b065ad4ac89a2ca247a08c7b1c6e6f5498b083af3125e68c30c1ffb471facf43138c290be05fb29342c350bf8c8d428004cce0fc132b1e39fba0cb7e2aaadf0adfc97652ad18ea7c8dcad8aed77c7db021a4fdcb95e24b41d4ebabfa264c1d3be58ad0d5256e423b39c61b6aab8be4868d4de14cd7cd57e4e19dad9b5563298a2b718c7b6e312ccfcc37b21dd491b9f61912f05fc991df9ba558b36234e50c760ebef42f976dd42420811759b5b4acb4ad02fcfcc52a9ebf8acc042653b68c34654fde992916ea63ab346839ca1a921404269c3403c6d45f6802616cefe9beaabc5c2b4b1409de4d64f262fbad635c5690e1d536d12f0eb8776cdeace37fa2af3d2ae9ca4628386c8fc457d239ae2b12bc7517d48bb4230141554a6eb709ebf628bc79297bdec16d72e3827ea1e0041b94795ea2915294f904d69a6538475a59274c62840394665cb9dbe1f004384d6864efb17caf2602f9a3dc1eaf3191286d0dc320e796cdc75197f99667d70036f23cdde384b10bc42b80f420b92a5b68c3df9eab25d2c1e42b57c2e831f80a177fdc10037f38c700cdd0b0f9300cc9e216e77046771b8f6f40030fa6d3ed244f7ded3c05904b5f9b194d2b51475988747ee2cfe277a9736ad7362e304653b21beddac32e30d9c99ef11a809af2ae602cd1c4ff44538b3e4a5dfffe03584824d6475da866a49b0e1b9b908f78928517125f64e2e5481071c5bcbb9eb55435f8523208021d67e80cc28a33393356bb11a14f0513cfb0a835cdccde3a10af0e38da32ec25ac50b4d728b994d7e1a9147ce32a470645380c6f447c04e1a1535cb0018fd25f4e886514e617564937012da42d868f6c0f4697a26457ecd7cbdeabf298964c67ab1594e42af19a28cc4405ac968da3cabd5a34a86199ab85dab34953882b5c20d7177b4807d036d303d6140e975908fe86b9b48a4c689627f6003a6a0aa753c41f5e55c9c99516c10ca47a6ca4d8de9d5e52688f6c1715f16e731c5843a2a7979ef5c3d5b94b2530aa8eab356c62d15f189c38bfa2ae4e6488d476d85cd00166a6d100f14f44d612dd4631bf1e2732dc3b547b2e8b2946f52124695287527730744e91a491f17be7ed0ed7c060e2f053ddd837167e4d70f67455528d48ca7eb225f75184ab4e5348d3268508c1ee7da39098beb8632c50e5c71f71e2e5e651caf07ddb237d8b74801369088732a263252493ac7ac9ad4f25123e7464f5057a3fc99b19905666c43083d3f5c9265277707f27fa604a2d5e84848cfd88773b7e6a3f78981b5e34b5bb5a8bb20eca04db5a2a5c01853083ef716ce5b5981c66f5b6254d545e709b347e98a913314d2aa1e427875ad90d8930afc14ec92dd95953d7883438f66ddb38bcef5bfebfedf8182323b9ba999a6454e568963526e3f390c26e570eb90510180acac7fad3884b4b8f2b50358bc576bf9f5789db0f4bb39c486dc500ca59b425512013c1d98c06adb29c3b15e0ac9cdfe701caba233e7b7f7f4fd2035c9d642aa5932b12b57cdfa1595363e5e3f785ae7cd2fea7dd5e29decef35a048dd97a8f1736341fd0706735c746a16a1fd92ef03ee2dd5278261572d254518e65569a1fe83752c71a2cef7875b21e115da82888cf37cdc893113877ee84d69661a2b7fc34973a8dc1245d10940f62f21e80b463f6fc75795f0353dfe94d70916ae6e9bab0fcf01680d13c9f2e57d427a31f7342c591b96ef13ffdc036fc3e6d75864e2c50a676638e9e9f69c4c7a16535f4a1b36fab3b58759d83c3a668c718f88a3296d320235f9ae65e7c5811dce32d5912f2111292cbde2b2c70e6619ad5177bb4829ad7c3a4a00412a1cb3033eb930abacc7ca1bbe9ee5b50a38dde54b2533010cfa39804807449904f76d650739dbaa0b08cb72b0c3c9b29d7ceb8d0a8cea47b126617c47ce9364a6a0a083fcf5ac152c0248cf78c576886d697433e4bf6b0fa77864982435b9628f78eb2678c80899f8d413aa72dd3f59a1d373b59d85024e339bd54adc84ecccface73813e7205c3a4079402a3608f24c8fcc788c071b9dadb1068b44c19219c20a3b33ddf5ad87b223be873379d765733d5c8a05f20804b7db1b4a10154e2361f8b24debc0dcb51f6e475f52224dd5ad497364084882043a04302fa4c24fa5c0a02fcf82ae455bafcd29747ba78f1660b40446dc188cf4655c852bf3b844ec40f0c9b2cfd81299ee699564a651d8ef00198ae7d36c833fea52b1054b5a693e76d1cd6190d71dc442c071b2617b9cfe5212ccf925cab46cccac6e3cad2de50f3fc787aabffc489532a46176b39c214b245e00c9333eaad119538a171916e01a94a4d7ba42251d4f3a51d5f2919a845458fe36573238c8c5aba5d6d5c18fc3bd0776ff88561325a916d2ec985628cc9ff1381e219a0c804f94fc8906ce073fe820c2520e39e4208c88721cacc1124d9787a54456b93eee9660c16d2adc283b4cde456c66060fc4f6c683a0e92b7d048400d539ceb55ad6e38296ff0aa7cf7e1f5bf88eeeec51cd82b1735299ffc59c3a807d809d9ba1ec57d5104d95c96e1d38df42997083e70f65bde2861f830559c9c4de92ca0f1acdea5bb1394024de73453ef70c54dc26e8dfbe42be49d4af77ff08c220b75a15fef3e5ccfc6af5da4c353aaa85326b49329eb7da7fcbc58a6db318b63a44501ae04978a45266d56fa36abf81dee1beaa8c244e80872841ac772a7b8b1695b0f42a090232a61886c9cb36dfc31485cbd4486d60d15914b67103945448e93fc24b2f640ade543f393c4f7a7fac43ba6d2238eb8bd5a010b623ef9e6f1559550d2e37957fbde3ef4952ec65e403a37ae1e91da9399d6751fbddfa0e98c44f6b279e47370fdaef3b99ac02d46beed2308efdd6e0f21d8020dfefb1c46bc2f164b707ecb74d5d8763e31f4631f0231752cff0fd90c4a9565b5c512497a5cecd799a234a9989b7f1e7e26d3c57b8bb595daee9319b97b98ae080a15ed88a7d9bb47a5c6d493cdfc51b6fe54cc8577a15782776cb2c895dac267746426ff0275703cea45202c76e4d0bcf5b378a459e25c078e055bb225fc0c17555b3e28d313a25d1ca1a24cea6e5c527e3b0312a99a56d5fa80610ca6cb2e294c41eb8aee4c18a572b8e600694691b67313d5594e0e4ed7e74dd6a95e2f5c66376d2e3ea5a484f7935966d7ebbfcc99a66ba7232691d212b2a1a52f9ba586a03832e13e1da4251dd2f78e5940aa3618c6814bf544d22e28782ca9f71622acc7b8ceb73bdf7b2e3a61a3ca0a8b3c07bcd371ec3c5537650f69fd8db5f862bbb7fa2789bcdc3181dafce8dfce88ab29b1c102fe1c9892c5a57170b4c472e3627c0e7660215f63e27c1a713a4a17485b103a14d4a1ad3d5ac3051479cf699f54bc6a5e47c9654260c5d210bb083c7a7a35b7ec9b4944037cf9befc70e440a7aff4f7d68048c7b8086574f7e3a9b7ac40e4bb7787d11c435ea5e698a4409486f7fa76e2852e6f5d32ceab5d3bc75532a92adeabf09fe54453c8313956ac94e016f140df72171a07e3870ca69a33945a3beec5773578d43a3c7f3ca92b403c8a2868436440638936f859eb855a25791b789f3af3586c7313082e4f2f73a4f31888e31ed32fa2bdb7c3613442918477902f3a9742d98abe453a354a45628597139251e86e44332d2f0059805dc33ccde0621e54a1dd53293924bec6401c1296c11fd03146ada01b7c8c9357d3aeed6e2607a588fe4ade46f1e4d37c9533f7a00cc4e29184322369ea2501338859441e1e93ee09cb7b42c42e2940697402d983fc1e7fa82f9054956b09b52660bb8596b3b017252de3c9846a5cc88eed042eb59308798ca7ea6876026b4efb5494bd3ec94cce5e5ec359d4ef0c6104e256dc4a840d030c6f5828de7397d16194fe5d6124e0c08064ef3f3e7dc1f035ef9a41e35912ba68eae57c7a47e44866ba91593c6280c3da79e8613586c121e803af786f938212e76dcde4156e763934b6710205cf2e89273a371248d2c444905777aa2163196e709daf5a5ac7670bbbda5ef6b70e71dcb3f36a8474f318cf41ea4a328401f305ed3e506974c9e9a66c3822fd355420a8d7b375ba42505b5ca09d6f53f6e0b6cd677f3700bfe5cd99dc606b1d5034000dbbec8f98dd23b36ea44fae92e0b3339dce3bcdd0f4f159ddbdce13caddfefdd3683ffcfdbe05fd8e6c7f87e5f726230fc6aa3c66b752628d5580ba828c79b6ab22fdbface25f913465b76cdb58668e60db1a1d7066f60789c08d6f7bbf5b50224ad8bf0f0c097f088520b265ad6973a8a43d740f4121bc335e89c3e4b8734840d7a76b961453a2142069ce0f025be0317cd7ee341e7162792168a9efa720a3d23a7ea7e06e3d6d72710f30f617324cebefc8d0266e2d7c6c72d6bbd741abf438092c4b2f6e03444c86dcdf257c15ee2c7149f3549fd1192d5d91891af390f828f2e13a089f48e124a2ad072265f51eb46d06786afdbffa70872c907b2d3781aedb35c7264b60ac7d36f89e26c9d824511f4d35857ae084688a596e8559c7fa58d6ec13d7907fdc1f9338a3530a3ee823404da4bcfd43af2f94583b3e862555e9045bd76f5e6449635379f2d7ee80c7603866a9d28a0f0066e58451eb931984513771065d675213d44e1459d8356351fbdd3bca856e7bf15fe56507df091d40dc204e1e7cbe5fe78a02183cee906a156eee17b14763173b8df6053389e825b72fa1138e246bcd753ecaa58c31221227e8d91abc65fdf436886da67078b41ee364e1800642c437d4e7aa3388847d36ab59aa6010547f5e1d8a42858a777b97c6ea621980862114f1691248f122a63315c13c0312d72227394a3cf380ed5673bb749e0f188e1d53a74c3e0e3f63740683d6922f5354fc42f53cc97d7d0459767737ab89b6857bb456edf86fd874c9485051dda317c7d69d59f134271496bf4a6f59d402c03701f94c593dd9b61c18ce8493a8606fe7e53d3fd22da8524a8fa7fe91aad2d1eaf8d38f7f9e71c122b5f19fc483f73b041d95671c2c1269b2a6f319c1f2b76cdaea1341f69cace60c78e01b0544879381e672fc868084063d5b521d69729986b282dd8da32a221c816b270e520291de331230dda01af303af4e65f2cb949431040dbdf81afc6d1a2acdf39b722c2506d85bef9d7f06f383feb81e5bffb2c12a50f2ab8c1d38c5045734e2f66f4bc2a3b4f5d745f1b80094a5487e2452428746e0f286d4c1610f1cd3c238365eaa69e32e8cbd67b11882b014e86cd9578ba129ed9a42c3878e2f223277d36875c8dbaac008498c2ed97bbb9a05406ca9d94fafef817ff487254941fae9d0e797d77b6f7cc14f1f91f37b4a395d8cfcc0e85773a563da922b905fd70cd994f887543bc6c35a0e8210e239137959ab8380a8f6ae259bd039032cea1efa68bf9c82efd42747a3c5eddd7bccbc0c96d69dbf12671d4ed7455939d4dabee64f11655c548650198caba28f0a618e240ba9e20adcbcdb97251485c0843e11860d3f9a117de40e7d30e764d8b5839a0da0e1024991702c700cdfef8d5af8563f457d0bf48a44a7f0e9d51ea13b8903bac1a3f3933690d2ceb99fd26a183ec5d6101c34c6894fc1b6bd1da0ffab09b0a8bbbf9c54cd2760d88650695386c33aa62b6913df7f814023a3b2e56aa4304ae05b7935f1203366df7acab75f2078c2bb5e6b01312e3ac5cfebb1054c272487134411408098f26c26fb5f181410c5115b997b82dfda05b0e6a9fa5ee6469791b0548984aea213b312cd9cf5cc64a6a3880574c64db1e93ec482252b618d2d3355d37b581d21fc99f3973e9a76fc7fea9c96d1f02ef751a756d23bb2c63778bf5d042b38f2b89522db9f7abb31948950256ab520e0d3b511d6907115aec631d3a797fbc125549109c055f89818ed4f3723db8c8ca0d8d6bf31ce9f3acbf11ca5905cf5cb1f237c661925297722048ff1b51e772c35f90edb3c05b51ca0f6446c7bf1a672bff344a9d538ad4896212448352a0cc1a0d365ef59f058f29a6bced30584c701508a93939dd01acc79e6119944084a4c1ac5581ae663a1b1748d3e34e8ed9f01a80a8a5d10eba4b8f789c1288e86bc660e56a16343881d9466ee869f50c93b9a11110083335b4e201fda9c537a9553048ed88e819494f9e8556eb8dff01a8b9dd6a8a4928861c69697bd1bf921249936ba7c629f202ead82365564dfd38541d3849e8ccfcbda35da37377e80a4196536049001d689ab09c8c183fdc3e8dd70eb25af0570a1a6311f1774db8c029130e78f7384872acc3733156bae2e8692543c45640d9a18905ac8b28eca38278da9564451c2f0173b4ac8071b69be625b794f9d8a4ef0ccfafedc17dd287107ebcca821761ec1d35934160522366a200ed633767128eeac83ba01e502aea183ab8e6f8f5173d5fe6d0faabf51942cc6fda2c5c3377b0c68dbc65151ffce6a09e52b4c1913fc63ea81154fbc6fe2eb99103c1bb5b7cd2b32e63b3788e71f273934c47cb7bd4f0b36550c2a5324e69b08a52a0268b4f6a254b6a33b2dca205b352fb38beeb32e5d7a27bc567b9d36188c6c0d56befe46828b01e6742067a933db93c952a960cc6bc4d8ed112be22619636a175aeae5162c0f662b6f513cd67931b44374022b8cd03c08276eab2cb171da315d77db1f38fbec7219660a4984adebd730c913a982aac5cbd9788c17ad5b6b8161d37e13a50fa1fb84076b5a6e2f4aef766f007113ce40a6652e2ee88d88b0039fe35405c5a343c4ab650128a0efe45e4216550de2187766c1b20138e31e38116e9fcb3c009c7d160ea3b78676083cc17835c049260c9c08b0d1ddc944c1b691ce7de01127011abb3478449627cb02e88f99541471218a2eaa179471d6c663618f1981b36f10a1b851aa29032f7891bf3bc1f4e3204e27a57366acf10aac8a3f48c6d12362337eb3c3b22c8a8db14ef8662ce5baca19a6a25ec56e71c8d4cd5222d3a5d4f1f6b1d48dcc769017e8d0eda431dda79cc9b120dbe3600ce95324dc3a6f02c39a31695e8aa8b91ba70e68bf1fe19f67a21cc92d241c8733da2cda68cd82d8736f7fb00177a4c8523875bd40600ad84e70559257c07bac8a7cfe62cf42f4053213d8166e49323a171e84580807dcfca4d94deee2b260b3c6a8db39de104aaf015ec3ba6fbefe6e6ff8484247d878fabda29d4ee15135d388654f7f467dcb45d4f3c4fdb33150a1b8c2a6b11e83ab03433c8bba39dd18116b58385766c5b0b9789cc0900b100bfd9a8b55c4bd22fb1edb800fc42cf0ac8e66eb4d00dbd655b582b01fc9e04dd687ea3d7ef77f8a0fa51a5a52861f10208bdc4501a075223a26d73a38592f581e918256fbba191fa7b323ec7777ee922a6b3890f5abbe262fd4d6b1ced136b1b90a8a831c10c9c0859b96f485c3b8584e0debd8a6f1bd465f95f3ce0570adb9e83059a8159628d314deb874cdb1288e97f68dff695577b60c0e31a48eb8edf6f2b36e97ae8cbf5798fff891f43bcd977b760bad6117a02ccdb4265ee9e7d433af1212ec5b1fec0798bc2a85702c03a80f398f72e42e3fe1ad008e891db37e9e40f10e0c68204c1541c1f9232d25b4a2dec8836cdb9b4df436de8d4de02b05391caf9eda959299a14f3d3c5f964d7b4ebe3b25b896a417f15fc4db4abc01e7bf32f511294319c907ff4ac46f6ec4079f0da894d7ac3fa9f02caea3f9fd96689de52f8d68694b42e7e0a87422b4ad6c148b059c7fa738e484d4f0f58154205a9903c7da97dee414a36426ef22033f72e1d7c6330cfe1372e79473a837dc4c54b2302f3a9179d5a356985ef6eab02a57b384d56389a95d175364e287eaa159cb1aaaf89e6f1c3a41a50fd245d58f5ab900f6e484d82bdab14d748d8bcf07c82925d369cf71491eb4ed699f4c6debc698fc67595e81cb7f480bf770be93df0a108598d272be9f0922a600c965cff0c044e3d6cf60cd782d47b0427d3dedb7d317f2fc988bfe9fcfa3d9232f415b014ab78d22cadfa7f9178573e5ec3f06885a68474afc40d044e46263cc066140f3a58cc9e5674d297ca1b9afc669ce1d00f081c5f7b830cd177f7fcae315cfba601f971ee9b78ab7729fa2f06e3a4cb87ebd70d172158b4b8c11096818697d3ab2110c04f6ca906789146ed495e3c119516b5f34c423ba4c1c271f288b08646e01912a7c873e8784767496dacefe1a91e28b83c2408ce8f303e4fc222991626f9f7de7484013aeea36df9cd8fd16cdd47b45fe7111de94d7d9638d1bc81ec321e833439eead1d358a61e86d070ae93cbb0e12a365985d4065b9175c2654ea66dc5a856cba6f7a36cbb7223868d1d15679c923f306114e2bd4685df2f41399ff87f252b6427594071a31204887e4764310c412f5e74a7337bece000eb22672a708e98bb7f1e5b8b5986b6252ac06b8dc3f5b0823d03241699bb49bb7182020b11888a660c2bfd3d8790879ca0a228da8d1f97586d743e98fc97199f65a0f85fa75411ededc9083272ec5b09040b525e0b1ecb6bceb038025c13e8406cc9587c80734bf7f654c23ef987a0bb5d9e1e43a3cfd97404117264900949a1034716ec90a3f983ba49fcd8f36003f36768c15e3523da2a9da1ca6eddf54da5397e3e7f02e19c1b973b9722e849625cbfef8eaac005b1928cc4ec2eef20cf7e97aae0107e7ffd94ec9014118e6f5760e1a92c5caf0c563e8dc4cc6647049dda50376e74a925a45e01311f72edabaca059c56f8c20841a45d1e84e849cfc21b393ef83ad760b53fb913cd6cb69a9d255b93ce699e2e7fba28e9759135cfaa7b56fbb721b9576d5829207309888c5363774689dba6df6df6b32a9ee4c582a86d3004c38ee18df2a92cd2bd2e17c097f4a152d4cca7ea5f388c53897d60e77a81095cf977ac1f1f959957e6c362dc108f456846790c5a109989387ed02075cd0941662bdba235ff8e0f0f1d517919622c70724af49dd78d4e59b1679d1f720ded6263e9fd6577cda41647a6de783373f825b8147296c12aeaa34355f9d380780ad1787ec9578bf2f4f5f432a9389eb9dc172766f2bd048c6026860b9135e5547ec0e5f294ac2ee4b03a68222fdbb8d39d6dfa3db7468c47caace1ddfe6f8dcf711a6def98439b82ea2aad697f3510d195da07f219abe10a5c2d9b49e057c5fc18b6cf7302ab4749d07bf5e7b4e355f41a1dbafd118ba7f7d37226f573e24f165f91de73c97db184ec186353e87d9c37957510245e522a92fef11512f620cf184a157a5beea1c4198c7aedd5db14ec49aaf7be8326e56f589beea005f3c63fe8652b8a14761c858a6e75e09eb5f3f063066039e65840c64b9d1898813639eb26185246d098d3c140d504ed99f076914bb03f3be33576fb5dcbe17e560ce4184e7e874f525f21055e933e10ba68a550f3fc233b93d5c842f9e14d2dfa51067f125eb16e99f62f0075f8f6d95c6b7601b58d3f0600714fa0d3dc0f480f5b265f3fda18dbf48110b3fc35fe0652ec3e70e9efaf16c807d793c40f977f4c52b705f450de5a26a3feea4e42714c16a7d399cc54585c4029eb7e33533c6bf4f65c08a8a33095a246024920c9505fcd4fff7235f281aef4ac50e4eb663d1d7751bd2910f09fa17d3e5d0f22829f9ed22ac715a26b508abd2a574d78405b5fbe582e5fa1198beb437e98c4dd96e46da8d99bdc8ad2b0fe3bd915eee567354a024cb632f1286d4b9d873d42d3439f52f8c9c1bc12a101e73e8f29b2c48e36cb19d23e2e9ec8fa60c98ecec823f69b95f1436e94513ae33f4c0e8a0a2999bc8283393379dc35522dda1dfa791285b79951b4c9299dfa99768fe7fd7cbad763cde44b384479dae32ede52da46e12ce5faeab2328d6402ac6354fc548e0fe655ca7ffdbfa2ce94586efd6eb1d5146090a3f79610da3558832e55766333a5f15f2eb8c33e4a352f2ce135c651d829799cec84fc44c28289b81549fdc311017ad5b37ac8388d81e9a3adb40c6910b629736e209cf7a7a87ba344353e9aebcd75577d86bf1b33f41d0e603bc9a26c803b5eea11fda2f6a4c5071001a3a865b85004b4a0d1383dfb979adfff52119df541d3c58738e7019afc60e251eb9767d4b886c9f4db147b2ee3ce9838045411a03e16240a986272618dc8ea67e5f6e1d460b7a532377552ec398a498e2385302533310f09ac49475bb77f30605ae07e1cdec9f9dc35a75ca1a4aec073ae1027dafc259a08a948e99442a335aa9ac54150bbf05caa3bccf95ee47cc8585e7932c8f0e9bc2c6880da04be7277a4f76a4b1b0b22764137527c48635eb141028d3d7991f6ac753bd1721f82d72bcc5bae307bd1eca27d85ba3ff9d38b7756d7e95b66f6b4ac445a387968bd45005f63c5056a018ba28530adf79c0f57a07983bc865b981f2a640e2520f5fdbafd8e147687e7b52ab1a2fe3ee86703ffd2c4359ef4274aae8defc08f13ac984b50f8eac0112bbdbf6481143fe4222140e7488e19b937617b68514f94c6af8e23a0ca161007baf6f2b7f905cdc89b4bc9e858112eade69a825919bb94f3d62cd00f599c5ffcc6af3023355272d2f89a1f849d76446397a672cc8ae7614b8b6ce246d09858308c92e970aeedbb1bf76d454cbee11bb916497fd1af193d21e7777274d2d61eceeea8b543c2394e5c8685af994d527a7f156421aa6b9f5dde5de1cd1d2be2acb5cd60fd04c580ee3efa13a7730d4d1aa939dbc3f3c8e91ca3a98155fcba960a92bd32281c2a20699245c64a9a7ff07d02ecca5bc13dde0de50fb440f3f9ef066ba458da231d680f5dec5ffe2322ebc9d8b624f93a4bc55000e318ea058ff97901bf4a1a3970ca9278f4404fb1b4148c4742b78a869bf045fab04552b88740969d6c2eebf0b4408216ff2f6ed2276e10c3f0c86ac321f80ff491b41b64710bf6959e57a45f3434e771e72011fa73e82246204e28e2fa090cfca50bd3125860fdb08246b542a4e22423633608fb56732ebdb5cbe7e0685b0e46dc0f2e22d90716426157e5258d4896f5b6241cdf73dedf472584fcede9887e81ecd5b47534720e4de2829996276033bbd6be864f93796e5a1a7893765f3140b30b65c7c1001abfe2832989ea7c3a454e8f8f05779dddda4966927c6191231421328949e127ac48fcd1d65b4d00dbf61007ba9e8508ed4e42b05f85b2ade88b1b8708a0eac356f58eb660a57c33528c1eb1202e3ef77d0cc1ae5e5fa751c8eb6acdac63fced5aaba252b15dee8a78645378202b690df8cfb5f8f3d5909503056b5c9177dfdf454c5890295abef08786cbb2842cc6ec0ee948f3206a652ad03e736b7f36996fb9bb6e904a66827626dd159a56a310c52f631b251ce8732db7fa9ef210b5119b3d0be995278199d88f60a3e7bfdc5448a5dcea4874a3e7cca4e30e12f88c1f33019b48b275c529a79c6c3c5060752e37e3469d1c62422d27a19deceb0f09bef08c58f816effef34bc8b2259ef16c8c4320e8770184c67878857b507d3b68e28774658fb7fc29116bd1e563b8e998e62d1103b4cec2e5d05f5fa383d888898641032d6ca3c51f72edc757b0e3905c36f200f4328c584d42d9c278b08e6513d73bd1413d24a0da913f0683459f67c880e7009ecc58b83712acff34fc655d8b447f7cc552644558b9771f205c6f14281d4ebbf088646fb0a8b8880d28ff9f80b41a8df261d55df4c317e93479a2b08ee8a06af152203fc99201839915d7032a03b29403043e65e0b5cf08937d99d8003b78d6367fd16f06f24b7ac6ee3f48ac489b76643978271a86dabb77c6c67fb555979197abca7cbc766792073457f20ebd1feeffd7f8a3ef217d3098ce9a2c4ca6f91b9a4685e22b5419e6caf033888e64cf6d2adcb02a9f7b1a4c9bd3742b46ecbdd32cb7a37061e11e2ec740834d00dea21fc59b2500bae4e51b00de7821902a917aa2acd37f59ea4e4a58a7996c27ffdf1955b9c71bbd83f8d5743de05f75c237a13851f9becb0dff1fb226ac4f3355a89faf79e73272948850a825ac090d61c576b727901f3c24338ba013ef3f562f3aa4fb6d4bf4bc164aef6a37caccb3b07d63524741703e82834860bd129ace09ef6809f2378a87ebda310bd2c2d56097bed5e75c60e06dd6487de90cd6fdabdfaa04c0e06c6bd45048c31fae645799e43377aaa0ebdeb77910ddc919f2ee3e3f13558b110a22b84a7fc77fec2affe81db4483b242ed515f804789eabb7cf1afde5a22dd63b79b339132595cde7c4402c6964ca777a4ddd3118cb1ad0567c1a08f5f4f2f67023fd2c3f2099ca50b60d5827d4d84821373271783b5619de60ca8bc4d8e69a8be5d3d0099d19fdbc20902a7576a501f2ec9766a3ce72d1af6ff0db3a18c282b5b4f268358a06008ddcebc0887350c6a43dbbc07f3d7d23fbe2b1604165f60c885f77c2339b3cd8eda11e2443ba5dc790a9d0f204c5924077100698a582e2d4470b474a3b771479bbca3a8317d655aa742c2e51e8572184e3140c4a98b64fd9ae1f00ad3b33490fe0092833e8aab9a2a6cef22f4570836f39037f616bb31c17d51707b13eaaaad39e63199aeebaf77b39614391c76268e899027e10b9bce003b5795ee89dd6f102056981004a0264577864715442dc712a6c9855c2e4f25ee59d3dae5e903436baa0cf170c963d9c8ba359e26385de615ac6c88f189f24b86269b5fbd8ce8d7dde66c6ee3de69cc9adf55d79b544e0e1d7154acda681ab5fcbde7c1b2c5247cd06c174544ddcac61bbfa43ddf469c523e900e4bb76fd5c5358b78ba8d786c32ace47c353f66dd5dc0459ba912ff1c659d15fd35dcc738c0a487d0ebc96bd890bf7023670ad56e0ce082e4f192273cccdee4097b8ca9a405b23c4fa6c7614b594778c8374b998494e37cfa8626e7a2fe26cde4e6ca9a375117176b795406ba01de08cf9cbdb96f4f825b843d30a9b3ee49372b42ac6c6f00c0a7ef760a8ad6437e789c1eaaf924e5e0135e7ddaf477ec7e2826aa7d58d0589b15aacfd17db6a9d1caac27a684f06c9dc7c31baffa8b2f98096814bc381d2dce1cc3d1db5afe02e43ed2fbaf6c1f9f03c5936681da066197c12315e6ae39bb2062e26f88ac2a47ae578a675986db8be4c75dc74b46354e5090696f8529a10595fe8be55e93b8d5d8a15a2a084b98efe05c7773918f6fbd753b057d60fdd55795f97e99d073f1f160ef00ca0ba44386d2b3237c1476a05a233f046085ba0db4b85b8fad248197607bfc309e123c9dcfd98483f1e79709be727f294feb2424c1eb5f3a2733b8ff07d8dde0832cd672da1c26abfb6f30d6190e26d1e995a94314be69e10bc7755debad7272af3d3eadafc969fb2bd05d929f58ffde6af686baf0bbc19ac70979254dea0cb7f33b732bad38de402a0eb55e094d15687be601f81f91c30d85ea8e909097cb07bae067ce08b44424d4af623abe97c9e1f9bfab5c045db5a01431ef4b1858bc0ddac9c297d59d1a35bbece0adb7834f934677206e7b80cd0518b540c5a2d7bac0fe919cf8af5e75133b950afd74cd4693461f936c80755d928c6179a10e2f49f64d08b26ac397a517b7e3ac872058b944de963f77c8f76ae3d1bf7fb7d5317390e4efd6978765b7d9cdbd440c3b72f746d6199cc69fb560420b273f71da931c0257247e9cc9e149289af96982ee9342b2a3af365f25d1301326b707c51c42f374ebac2baa22bf1fe7f6a2ab58e8fd1f919bed31694f27ddd5d05f15af86a66987ad43170dbb8d0ae16a9ba69c3d66a3661e22d04bbb005cd954baceb409e1546792a94c2061fdecca24ba84825be50f0b66c3e7b208245b58413c0accfdf11c932c1486e6c3ffd32a40fda28cd432015dc5f88e223a003e9da6fc3b4ab2e8e4fd673d012fc8574f91f61a3b2f1a3e1a44e97b059d615b6675c9d348ce9a2f60e2aadaa85f8e8e9eb932b9132d98730aae2105d7c582150464de42cd124d18e4b1d00dbe2d7b37e7481a0da06175e06dae95d2453b7f212f1ef4d39e788e9cd793870fdc8e1dc92a629e28310bb17671864f2685758b395ef59daaddf9166ae26a6b5ddbff5cf9d143595fb15eda80410806ef84473879724a47a98cb26ac2204d82374a14434593f891836b36508df8d33a451ca58bccbedf623cb6e1278c9ef87a7a059c72e1788c93ab5638b6fdd191a4fe24c2ae4b1c4478450fc3918783b722b5b635f5e62c181d104d7c6b24909e3dae64c0459117169a863ee5ac339d36704c3e1ba89f382f5a1862c216743656a4ba2991aff465d45c8491a9197f896c3b1bd9e983a26101e731774419a88f708d9850ae51bb873da89d90b3516ae8253d57f5e52c90849fd43daef8e22813aeccd2e3deda9c1f26e6bf9fe9ca71909b5b497295dd533cf5860f60b658d86d1d161ee433a78bfeafda9a0288825c67f5c114a24039ee9e75c02c1647eb1b5c8d55fb6da6a7a925c0cfa5c8cac6c6af9ee497f3d2d55f88fb65e06b9da1683667b2406accc3c0fcd661db01751b5dc9b9d02ea5243c263119b0c1da03c36d98dbb42f104f71c5526124573f63c4df07f50a813e12c33a255c1b3e79987606d79af390ac6ab48addcee62a89cf66192d09631c34892ee44251e1189c75ac6b4daeb9d5c7671733fd52a99ca0ea0b89dbbdd6125e250c0d8c5b777b7eb51a9547ef7c3d83060fdcb5939a510dd9299ee48c95044eca09588fa445372355ed14bd84311219448b3d8f575c94c3d9d91617effc0c23089a571257439f0bd51c73e2ae5f635ff7ae3b9446416612a614992c718bde4596806b75109109a1731e1ec416c6992a520622de9e14e756cb1cb5b4e98155994892045a462619d9a9f6e3ae4e2c506ebdb5eaec68a7927a72ed27bbd2b84281e00b12528855664793f41ee75fe1424d3fce2c3be4323c35fa1a76c546cafeee4863c5d59e2d45a707a3127588d0ed59eda47841865f87ecc6bef0af952de32c5f6f68f0c9ae3dd78eb0bb9662844444dec84ba295be742062ec1f602332022e2e77ff0d214caa4ffe3548944b83a7310cc882e360b110e7a76167d6a41ad356ff68f62c7912b1540d2cd35142518f5bb0b66aada4fdd524cb056db7fda0ea3e2b86139942993e6a8b01733c0f81f91a863c9da4e98830dc12eee9c19bf02ac8771668e56bf3d6de66bb8381a90c913e9797ecc444a554a2dbffdc34f01db79af40f2d81318dab7f3c7bf1965167333f62c63b8ba9ec61fda4c32c0f13eb8a1ac97e99d2bc65d4a44cb23e9251592136a2d451b1584da900dfafe68ad462c0b993fb907a68938033216b8afd2f17a1d26619cdbaf1187e64fe46e4356e0bde03c8ca6ae4cc1697723f1c199d367e588010dbdd34ad702c0dff21595fe71208fddc30d0752a425a1d95844e6ebb26ec85e648eff348393ea6308730b472974191fb78dfe2cb43edfcc6f2fc6e67f2521c917d9921811f702855e8ac85a4ccbb5ecc59b6394ac2148147a5a6c6c44e56adee6a1d11f3d607eceb235a58a6e44ccbca793ec354172d8b22cad3efcfde87ee14c5fc42e8702071ae9098e8c59967470600fd2a5e96a714fca8dd4f0a8ac7d7bd1bf1260f706d3d08296e2873d579052598e89ff2fb5cef1576012ae6697956e27e6209b9aa2921d03b42cbfd3adf120dd7dced9731bb8bb36bb58cf89b4c5819359716a2305e01489e573ee97d9da1bf28f8d3ab7c6288c843e2c5b2633e4b7b4416c41671e1c4c0bf96127395b88bb0bcd71021f233e40e7e689496c640b12a038e3b61eedad9ae7635bbd6447ae4eeec9a25ccaf7a203939d635807dc879dd0f2fab64a3000dee7dccfd2397e4450bccc2ead97a4dcd4d44127a267fbad574a6db0005ffd12da57fe4166bfe4d35bc95c3d4318bb5506711174bbdb80ea8fff2f3c416cdbdfc3e0d3554345569fee25ce55208940372b68c8dd990e54938b94cfd1383f3e6ccfcd2dcac807516d74d72417f78f2f2ab8f27b2f6a6293f12d8967338ad8a9abd8e5a227c74a61601f9c25d562169a0d8ab90622d2d69ac03a8bdded7ad09fc3368c02388eef90c4706e68063e4911f391aea74c980bb6a51c3cd4129f0fc32ec1560838dd9256633c29895c84f00e07e6007729758a16e90a58ae1707eb374016c4060e3603a64a659cdda4eb416d66e70f75b5d453f16d6e4f822a93687f4bd5a1f5899ceb4efe7b558180b2809a8cf39d8f365adf6938cd65a00e742292233375d6c68198ea03d5e810e5c706305fbdd47f8e3eddf6422abe130d9a2165028958c1278deda56aa9b0eb84e6fc5a775daef91a9aac09e9f1650056741d9b51366cbb0bf8282dccf4f7570f40a3f465f964d3dd9ac7ea2695a86bff7d6781d1debec4f71561b5af59a8e54e018c45668b5b09bce665b541d9daa5c028c5150e96004386ad3bb672d7679c6013a58239f1977a23cf82d3d2bf8b38551e6b31182baa46c3d86c02b1dc2397df88668c93d35f7e141718ceddb704a12eb280d34a9438ce02f316a20581ff20c17f6adcd2ff3127097614995575bd0f56b61342e3ea7ca2ee1ce3861a8428e5af8f5081a6d2fb6a7ad7b902226c75ced2e18cddee3d16dbac46ece06b727c9c4f57541ffae017fe98c527d8ea25e76b11bf3d0244c9e989e2d9f1487ffb6b06faed243bb7da672856e636a0680f956999d6784a62d50f635be493e6090f24e2479ad990571507c97a257e63bc675befb32d5da333783a6bbad07c545e469d7d71d6865d905bd34ca92ca4cd692fc99d7367aab0107933fe71afe059b36816622447c67dbd24eb3496d2210e593d7a6112cad2c5f240aced736109931d259357ad91d8d85a691c032971fddf454e70448875206a3bc321f3d65d2a4058680153685e1158298798d0755ab4a991ca225518fc4bc8cccda8a0ac2759280939b6a71202e78f2548291c301fe97936d7776e9c77ee3180d1ae1d9db26d35f0de35a5330991f1c67a49d96ffbda816d97d8877d1bd695db00c3546477c1f8124a592a2997da1cdfcc8d1162fb5d6b7298f7f47441e689a113ca231cbe8561898bd7ad7d0ac1206e811ec5aa7346c7a847e4f906c5b0c354d36564cf65f699ecfc45ff9be5493ea37909519d2d0d0dabd0600ed34bc8227cde2d2692bcfdfad32da5dcdaea77678cdab663784eb2997ba9b9936a5abb62f4b980fffc34055cd8fe659e4878e5b00c4e168f4f1bf6398d2d53228e9d8a03d9c3062d6adb90e9eb8f652e089401c0e05008f1b37e259e601adc267e9b61e2ed83162b3c32f49bb5e4d580e2ba9fb83627d4b8136c2d2320d41888e21db2b57e520063b6823bce7aa9312f120ded0a9d860939a7d911fb833a8b6dc0608ab711c9e35edae7f0662159ec8e3594cfc769c59c65ff7c0c9bc29f6287b3f3b100073fa02051f64948244c2662b2124bf181c12f7bacb7729c610889cf5119dd1b967a22da09e6733a0c07a9a1d294dcee5015285cff22de58fa992ea9125f7f7d2a49ff103679ac3efc3333913dff94a3963e92983446a3ad126d9cf199686b5e2a572580627d78a94f184563178daeed94e21945789e4599eee4e62d7d7088105ab44b52fb6ca528e39ecd3fa7128b2ee9791907ce26df56f54a0f02a19eab9c0037758aca9f23607823c13a8fa2454311481d2efc4eeaed02656064ca66e1ff48bf79b0add93d741a3c98dbea2d0e299705b6b9c7063d675ff046ed96caa545c69f76e2769a0abc30c61c10ceb932d761ad754db0e88edf2846ff2bd33200ba14ff644fa2d2a6667f583d4225a8a37bc5899c5d86e88786b2014fc0f50bd9a5eae1163c8f2fcb4e6f1968620e0e4512ca4b33b84ca6da636a796de851070c8f92c9d0e7fb09d3e444a6b8a464168d1277e45d3eb03e283ac9a7cf9af0bc42e93feb3da5f746a3ae0278b5e5df6c812e97f3078606f36e3f1e4042b0e8cee8ee249ec90a93de5983f9892475ddbe668a2b0f2dec65b34099c1cedcb364ce78e2d7efed9165efd1bcad5dd3e190d6a199870742f20668fb8e799d043ae49289a6fbd042f6efd8c1c735562fa60688973bdd2abe52265eb4007b202b0366f7a86f2aa0cfd1bd6ce518681a95f69f44a048900ad4043a1d7e2693336d728461905c5b32e6e644461abcd425d58ce9cd37861c5dc4a08d82e06327444e4b229be47a7250289fcc438defdc5e6b7d72914d42ae3c7a2024df3024038be020ea35b33b1e15fd01b06a4f9e4bf0c31424ec48bf6d763dba0cbdb7d9fc35a7a7e092dc27702c14c8944c584dd8c3a87646587f247ff37490279a9f9c34a08d922913a235cbe889b0b611e4863d19a0487d241930057ee538593474616973e36247013430f7aeb5f7f354ff5e7dfc0473c8028b6219760fca7147c5cdb6dd33c1618e08872029f5576c04ca3ab618e76ab93a479682066a47a3a079b1e68edf4e079d79a65d0639ef1b4b3d3f84d66776608cdaf59ebd4070bdeff845af4bb86e353de467ec02a08515b8d5437bd9dece05429b99f87a30bd68e86041d02568ad754a40800f64aa601fd21fde4df2943df8d97eaeaaa5213b1f0856397ac28b22022511e27de0c0485851983772dcbd9ffc799abe12f2df8edd2c9dac8f61d8e9aebc97ead5302861091117fa73cbf21f7703918e3ed36e6dc76e540fd4f7b08b22f033180dcf1f63b398c9e46cf0ec66597a4d3f4002eee929c1230ff6bcaa52dbac861b00cdee62c2e1e1adf12a2f9e6770e896acc614725ce72ce8205ed24282f9ea269714f2d43c750780754bf9be6e752015ce4a2a537127b6a889bd18c92a91ac174336a6342e8a4d20e44175db43db9216df547f86d9f2ba599575bb57725a5c172fac48db01f1b68eed86c7585d4efd0132d3f85e9f98e8ff15a23210dddcc18417e62a70fad860bf024b5cb6a2784774b75a3c146a3eb1a8c7929d3cbc69d2f5e7c285b9023177b617f9c43d54ecec6e21543b3b71487f21986f472886d316a24a5786aefa6484107a7388bd8a56746fdde8923f82a1a3263ca259ca1936b9bec7f6f1cb226266459c1f2c51d58a9342a7efb7efc01c7092fbc78a254803223e18a31018d33c69cc6a79652576d833242958f46e312bfbb97dcd1204d07b07c3384cf3d2d675f6acb5518c90a88dee145c6083a9d77a4f895763a5b2a9ac04101e8254d76b07453df781c45d0d5f4085146f635deb950ce3adee734dbd2064ef5b12aee30b948f2e7286fa20020c5801e841bbd5e6025ef55fb4069b2ae96097c9b18b1a3a68c6283b3c736fc96861b7bfd3e26cba71d4e81feba5f6920b48779c4a8e68e452cd6261682176acf177addff33b5111ce3b97757892751480f76c87b13d1e899e2630c18f038a932692ce79504ce10963fd66a29356196187641511f71fe025956c603759b8ed092bcfc21a67f19a2d36add048cc056b217d4d79a53b5ed622ef837b346af08f494b26fd51e8dbf0b1fab2dcbb76a637b42a4752196b67ce99f5e141dfa90225061db83d4c26e1211c7eeb66ab0a37c101ac5271198285cb32fe71e33f35b7070a37c41cea016cb8c8a933bc5d568cb25d0a5123d0b317d554672576d12f80fc9b3111158d50f13ae595aefab29795d7b9466a0922dca5b172a3581a7a3c17dfba447938fe6df63c57082fe151745306f398a657cd9604c84346899fb3f2f8751d52935e3b27f4ab325c5ca64d31ff1e40d98bbfcfe0a2fa933a345a0843bc8c1fa44f2712b7c3d89e11695769025da5cf5160551f8773690a415a2397519c042303394892ba30a72cbe5ed0b254c7814d018d3b857c27eb50aad6800ffca3e7688aed0bcafd5d888a5ea983dbcacbf7ea41b5513e77e9545f39c1aa1c6ca065dec8dfb730bdf801b71615f8327c13772d859f91e6c0d630daa3ae6a9d55513c2febf76f5307d7921fe82e9abb9c053d59fc06b1a99d368fc86b0b7ff53f9d7ca841d5a69f3e61ceab1669dd2a7595a1083163ac69c1d644a36f009bf80ea243d9527f92d70500aff6b0751e5f8068ae8843a9a79851442307d396e3ce98312f9dd5969c0d20baae956fd7582b188f6cd7a832fc7d4b361c5ea0171c9fa52e39513f07a010c3c08080d2fc61b24a99fcc4b4d1aed608c3fadf6420d1f167912b038058a4ea19333daff3cf2be62904ea25c2843beb5489a58e19f1efecf823682fc4e4bf22e8cd8dcd36fc5dc02f1e94e329d9b5338ea8c3b909ec6e5dc87c74ca0aea834a9d96738099bf7cd8063b650d57f23f15498c783de844de2cadbe6bf1e8b71e7939d6d0f7be2283af91358c9f926336c649d1\n"); + assertTrue(Hex.toHexString(s), Arrays.areEqual(expected, s)); + + sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + public void testSLHDSARandomPrehashSigSHA2() + throws Exception + { + SecureRandom random = new FixedSecureRandom(Hex.decode("7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E4711E95F8A383854BA16A5DD3E25FF71D3" + + "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1")); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, random); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("HASH-SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new FixedSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"))); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + byte[] expected = Hex.decode("72a4799428388928769dbdb7dbbedb13af074fef161d92b7ce2f88c9e46a20b51511c8db0a9fbfe2100f34d6e150e55662992a2e3e5a7c735964dd23ebf1d3eada66a9d241741675d04cd5c780bab20c5c2c1956fef96dbd693d16ed10c416c2ec059d6473f74e7ae56e97cad4b9c4fcd97da8b6cc6962b82bfffbeff63c5d1103781cfe64fef3fa1df924c08e971028cedfd6e4d00da72566287aeb4b31d40e99d67f97e4592dbe3ccf37d2d9178e4598180d8dd16a9a033c320c0aa52ffe4ab224c1a71e0b85c117a781b082bdd42b6cb16e8256e0c1310879b989498300f4cf6cfda4a0ab4584a55926e80074994e1ae3da53951361d1a4eb2d19c8348481e759c172f195a36a87dcc6a7aec73884c425fec37ae54a0fb8e624a14c08efc4c4d19d981d0dc0fc8e3d4f70eed9bfd1935ca393d862678c94d3eedf19b6dafd68213923bb079cfa78be9e0ae57bcda8a4a374ebb8129d2cbe138c7569c15785160ca1ba46ad8c22cadd2092ad8889cf0d5775865c16beab09cd0c9f5bd2326a9e2560f0c910dbced2382d7d1b76a6db20c10354080015fc8f43ac4c174758fbd5d6c4514d496890b7f5971cc10d8c53875f2e594f7accd8b0970dff287c4d6ae582f9099cfd765ba52260cfd0ee1058e53296f006dfd0f651d3cb61426b94365041298a78715911b4128149b6078a56587f2ffceb3c80468d7e5e701e4f664751793dcc08027757bb0bc71cde085677394556aefaa3414bcfa30c3142ea1da8320e2840bc810bf6feb378a502ead4e6c5decdb184d0204839a13e0a75bbc73001a99026bf6ab2a76a5b61c9ae59397cb9e0e0c72565a45e000b0d542380db5fb416953dd224dd6dda4a10b6802e58711f7aa3f52acbdc087989f268f8faff587231206aaab34fadf678c5074ae7bd102b9cb7a702fa5e59c71e732bb3a94eb106f6ad00dbed23ac53d412bcc12dc6da48a4c8ca702929b70d1b3c72fa0ef5bb74a7d4e4b6e1d88cc5fd021e4ae565081db628a7a3c19aefb66f16e13c97347a88299438fae4ad4d468e5867dde36decf65a7b2d8503edde00e29a81c59fa7666ec570a0230fc72523e6337f29e9e32a8ca230a25a410461d4c83072c962e75a1aa06717d664055b361b985bfc5b44a724174d918d11378b8cb2e1f147d07e92ed740bac496d24889490d3323bca1d0b16e85e6e64c910051238118818d61bf57e6f7ee583490414160694d6cff2f36e8273f91de204067dab58ddcf63861483cdb42bb7288df5c0ace9c8687541468fa0f8e4227c1185b2cee47f5e9cb30243d120a586d7d2be69dd3bdad34d40591ad0d66f23c093d8ba6d602aced5fefe97a40f7fd3a4b7c9d573cd76fef2fbe91c7d9cb1501ea4ab4653751f594ef2fa25abdb7c8fb5f18b08a79d27253afc7d982aee4cb8b9d934e2f4c54721eed2209edc98322c0b2a037f4cf8f2dd770a49133c0b4d1286c992a3e90889860d2b7cfb86a56fad5acd0a88b303463f1092c99112f172179fb2cb8ca248b2566bfb3e9e6c248aeeef6f2960aa2cf19f90886bdece8ee79d5748fed875d6803f52dbf2439aecd9d57fc1ebcb2bda048489f22bd6ff1c030c7962c9f0f24fccd7c932b4ff04fdeed057eb10f056c10bb953131d7fdddd57a67a0636b91f3ab555979eaa1f147063ff96d941a8db4c6f3207aa99154d39738df179a5cf9ff3e04890f6db1d5539a133cd4fdb227776129bd0a66586ebabfb72b8711f2deca806e053dc48f85052ca53480df5d76f190ceb4c861906695179542e7676827409db96d5db18ed9b516a6d402e28769af8f370ae79eb3bd8ee49abddf1c73be955db0018095297ec8b1dbf362c060064d1ada557c9d5069e6a2e7fb3e4a254c3d19d34793cb37fc64a84ffb4074f97154144a3bd438757bec1875382cb8f267e35406f582adf401362dcfe0377d53afc703f2103c9a2ca8b679919cfe106c500b9956a6397901690e872cc3cc33e5ecb801025e66d5cff94a7cfefc346b8190a19359d00907b48e128297f62ba3724d8da7280ab5bd8f622c9774fca979aef429a83d960282223bcabb7126fecd6f9f40042e23dbf6839c6f8889923f548ecff4cd2c355ed925c3ca3a30c523ada85df9cbb1e2136167fb5729965e2ba28f56c3b3ee1892268f549421563386671bddfd79fed9f16b78b30c7bafb1f1c58d9b3ac9f2f4c0873fdbd29e66c95106b37da1ccc5db9fe1012793fc665fb61e9fbf4013293b34a5ebe1cc38d86c9d0efabfa4d37fcdb9fa634be8e73d978c234721cf1280e178c518f95a319f0eec550d4c1dc7eec48be2735cc3fbdb371944e3a7ad1c63b227728e20d36f9d99356e6cc8eeadcb6a5a1902712479c2caed16949c29c6b6b09cd4308e1243c0531a9f5f4e7df6a3d27e3804fb1eade52f61131b2662ca60d9554337288da028584c90d33ba54bd819f75555ffe8e52f3947cd9d3ccd564b4966ee41cf5c7e012f7c36da9b6899a9a65ad88028620568ee049128f43d75c7d25436c4d0d95d1e6a65b781d2607cd1f7096ccf786808e2aa01bc6351cd3d526d68e226ca78295b295bd57ea1dea943ca06d2009d749001c46f4bbe4006b9a9d2361acda0e1546019e652db6c687c7fc94b6d169924d8327e4bb50cd0abbd249bab3906f292659e869f988f0565df5798bbf13f0ac688b61da2253f44f588dba65e33f07fffbed7ff537a27db1370c20c6b136eea20b831048ebdb9552753f6f7df7e96ca6c3b3cd1cd202b9d465bb432d70564124742833545b52e8022e93efc05f8bf85b59408779b938bea0caade08f19ed6f2702adec5d9754e0b4035baf4c927420121bf9144fd1953c5c9a2f10b6760ceabfbf868b566eda0d4da954b0707bfea2a671362ff29866422357058f8d676051abf106911a0f728ea42f0808fc33804696cd545449e79a17785c1b0fcbc552cabb3a47eb62f63678f94ca4426736316baf19c206fd99e2336c3b6ce71ca381cba83354b3343ef28afe87983c6c5f4e17d28cd741284ef290767a224d2995023ebb30c50d7a2f24d780fbdc03651a166b7839a472d5e828002764b1768add4b170d978141b8ca2f06b594fe41bb887ecd599fea0dbd36d74ebb739f0c33c51116fa507ccd3acf415fead7eefde45c9359baeb18727e79961bb14e12b48d4573588607c88a608cb9f5883b6f795ab8668b10d202decf02d353ba14287c3fb8db66b44b0c4cf74ea09efdda6b7b7765011cac3f9b46fcdedd09bd0e83a0b61ca82dae52bbaeaf28303f6390759a876f67eb2cd9c625422d5f0527c3199457084a2b20388762f45f42b4ad0a5d0906839c9bd8f01098ddd439f083117066c76cc0006e38c349986ee828170587836149432bdad52c959b1082118ae6cdcdf72ead7ca04b6fba03feb9581f5418e3d01826073d46da8dcaaca85542a57f1a354c140c276e05acebd3e0a0d5b35a510664f431cb15586f496f5caa630336ce0f4f68bfcfd04bacd8ce0d9e9373de3cc07c0bba21a237bbf95030b422cb59732cce8eccd56ab533aa078762f4f76b74d94ef1b71d41dbf388095eb38f34016488cf568c3372dce84cac53caef7a5358d7d21d90007755e755bec2ce744405d253a41e51683d33eeed58d7f96db807040093064700fa298b9d92e86556ea263d7b1513c14b0b6558cfde6bba6db7c1576b6ef42db41ab279e197a039249adfa8c035b032f0c213c40f408883b21e55152c8e1bce8d779810251f2cde1b1aa955fcdcaf61a73d024972e6f9d9bc1f90b05e122e09e35ace70f1c89309a0f53b465a3d1dc14bc77a01a323ab53756ad864646d9cb128f54dbac67dad6cfbb9abb23beb7c2c97a7ede7de8ce5aadd97fcf5aa3b4bc8e7f51cce2fa1774155993ca7e95b5d9275c432163b59401df8a140e6ec5899847cf1fa486c53832d24765c3aae4836af8818f3dd91e23f57edd4b640283e0ea7b148570379634f46d60274c33ca586003ebbd7f051852722e38b10bfeccf9d2f45035997bc8b77657c801840b623c90e82da39b64fbdc940539ce5dcf1d6baea9cca0a730896f3d471558635106f1c8bc8d881042bd4cc772e9587b416fe2aaa8355d95f44342d8a7ecff2d94de3a3eb5726d21045bf2293f24159e7757dec895ce05de5932323708257a0a0b6230285126f779f8f793dfb7a325609ae993ef030b3b1bf32860313b8636a2ed42c86c79875c28f998b4a56f1a2b3554b82c60e2fedf499f28a009b17a10fe543980f0fa26b04361e080acdd2be6f538faf483ea870c37979ac8ccc2e1cfa13a36ba3df754236c60c77fba4592508b8b171a0f12589d8a91014dd3c15d4c494337c094bb4d19da70ada22e282ab2220c9740c9e360a44cb6729688c78d384f3beea925223a5e53ad2bca88451587adb8f74025a208640de93d12ceee8ea2b5e02a8609f08e4438923e04c962d0fa5fce38f9be6901dc48f8c0ff12095f27a416d365ad0cd79d01748ff4bf8230129265fa2fb845bd2b794375973c74a7b36c4ca8165faeea2147852580751804b11c0072eb305681411f9777462b76f6ad66522763952db367b3593376b2760564ce828cd6fb6079374a6feeaaa3132b99874110c2fb7582a55af37aafcb7bc30ee10d5376c19a4e41bcb03b571ada34e203d726610420705159e929443aaf86b6956abd938ed6f92879a9e55751f37737363be0781818ee4129fe98917b67b369c083eb829d7be5734a15d8241da90e9a6b1a903e412a6013743d6601838874cfc61a5123086a6cbb74e1084c09b02b370cbfb41a9657c267a1b96ef3542650adf6f89c4beaee88105d44790449e7921766f28d1614f9ae367f7b145a145df4545626ef7642bfd41539006f0febccafc3d78f9366fa4f8e6ab7623fd71fa8b2f429bcd44411046b1a259af3234015deb46c2affb0f171f7be8d93bd0e22790cd7f1f71a91788b4ade58b618461b9230827a7b786e4dd0c5161845cbe76e8eafa2d220818e8cedb8d7b331c6edfc8044948f55d3dff7c6683fb4c557e5d28f9bd89fa149e6b2fb6b97687ca8f3db1b54739833a155344eccbfbca5c9877d443c31c7b64057f527dcb025ac76ba663482f78430ffa561cb7daee7ea4c57fe2369e03289bc2f3cd00fea78afe92d12535a0da39c878741b139aaa3145b512a212076fb16d3b981d71c3468b5e423454e2dfe97379d1463a657473c75ab70802c5e74d32aaab5f484d426bb4c5e04cc7a90e3fc6032877ba7d1dfab929645a2ef3455597623b7070c1d1c0e911da3fb6d867cc039922951642f146c2edeb57642b8cba633c4c7307b63933c8cbba3287b10e3f19c154323b7e0bbce9dad800c272a345195d5b9aa1085d9ceb4748c9bd9af98ba46baa3793e7c11e41d7306eda0470340399cc5e420798ccd8c482b104dfa597f8f164e3596f9a0f453351b328ace8953c7d41d9dd7b1c8207eb3815b954cf98a7b5cb56eb0bdd00bb62c4fe4853b30ad580297cf5f6897607f69cc0a18348c00aa1942c4d255bdd451ec30d9138235eaf757bcc61ddac4b9098cf0f95fa3fca9d2a5c302907c708284cb1923d74f1d59e5d121dd4b35a38489be9ffe9490d5909d2343b1c5fdd373e9bca5cb4ae90963084b84736ddf4c45151dfbe6172ab5b9bd0b75acc98692c627395c43af4fe4f6d71c3ddbdc627bbfb93af98dc5afec9f0dfe57692edb63bdc8d3a8b553c6deb11a8c746e232a01c79abedd64cf5eb758a04ea39901487af5d91a96f902e3ea34cea70cc83b1fef260fbd1b0c2e2f07a933b8c3202974fd5250e77d160d43de98810546bd77626e2954b4c2c39d10592e8bc980ce338de74eca85572bbe0d7acd2cbcc00d6f1bba9fcdcd5ec42e0bdfa06a96e2b87954f3091bcddde09ab84278ac0bc7d8b484c311b09bec09618d2fb0e7cb8cc5470f6e8937da5e2138b473fac822ca395fbabb45e75ae48c2d5c815eaf29780ef8268d7456a17ecb05ad2ae264f8cba18d783f75f5f044ab6430647f7a12a3afbeeb034ac30940c0d22e8b5b5890e08e2932e667fac258e8e75b85b2c8e81eac0985bd75e2c3c69c1646bb503924acadb155d9fe0f22a202cbb18aa660d20aa1646757aa8192cddbcde86dbe53768023dae14ee3adf7d13e0e484935915b799deb0f4dad6b898d217afa64a4c24fbf351f96f95dd35a441d5497f8f9c404c13044f769d1a15d32099943211d8f952ac341840e37426082e0ef45050a484ac31ca6d9de7df4020a7c3d3028167ee321bd76504b4bdbdfda582e0698bdd056e6d242c944de11d922891f69ff4a835a3b0dde69c0fa2c03c31d3f02b145f151f40b466b89560c9d36e4d005dba3ad6c175052d6c0edeab9e9ae6bcea00a47e954f24726e1a16e42159f83b819c02af027fb7603d36d3e3469ac4db2905f22d7a6970e8a578928a38b9142e3bb4f21d1415ee4cac1ae263ebc15fe984c0b465ca9920aa1874460a3a69c07b9c1f9c190867b26c13b7acd305e53b20873d1c2a871ec472fe4fd9f1892c999d48ee7fb71052253ddcb6430edbd25e52ee414542b225ec74fe6a6982d12520073c161012aec6253f9e13161258900d1146be6364513cf19cbfedad5b92be163221fedfa2a7edf4f4b7d204f7dc3320fa2ac8543c60f8c24299f83f81e0533cf067d685e1e91b982eff8944f7ebd9f47075669a51d947c1bfdc6aeb6c23a5b9e7b25a3fe14f98f026a528183a61751f5fe0af4029c98688993a2d3f09885f89f45d5aff9901b20354229aa5dcb6b3dbf7c92bd1134d595f0a646a6e43e7ad60e468a580f3b9c9b1fb10d08de00b09606b7e7f4303c7e4a1f3f81a3f7dcf06c9ed9a67ed334d127c976e13dc8208543e50449a51364860b16066e9a818ec64c6a9f4c96d4da7a74ffdcd47c051d37d0c0efeb8ef4797892b3b6c73d0ee5b75b82a1fa3015ec364196efcf50646689630d2e2c22d10371ccfe5d16d68fc2554e0f6a476e39091447858b9da17d31159402808f652cfb198331d638353f3ed4a5cac668c6026184846adeb5e9e78b6c792e631f445a99857943e20f34898813f031eadb9bce1c05c4bd91353c61d20c027729a6a94794a387cceaec7c9a5d44ab2d8aaeb1345505cd2ce2b4f29b85345b5acfa8f67ae13e42e88af788f9d137abd13dfee0e9b370db1bd231e4316f9553514a1a6f414d4e865a4b5363979b743fe1e41a4664017c8715b9f51979b78d232d12088a5eb0abab89a444998618e9cd1beaa16f71c1916139a3ba497a166bd4095fbfa9a3c308ba3b218827077e57700945e5a2689484444cb354be82040113f9720109609494c4689be664a6e35663066500fad77638b43852f1d3df1682b235dc96ca18e3b135cf37f71d0da7b412752408f63089850b84e6c410dfba271c75d0d7bd5e4a9a1876a985a9d57365d3b7005c4f4c4182515d80e09266245227c0705d798023d6d160f7ab3373ccccaa2a84963cb6239479b8c3601b7f25432c96d8972b9ef039516aeae59a4bb7c58ba7c21c439f0c696f35a5e673f877eecf1979a8548b69351647e196e7bd6b1284bc63c6c85d4a7f40a49778bfaeea4dd3e5ec7896d26012f56c66bf26febb0a2bc451f1c87bb75f50c2a69bc13f760d87e54e8ab62b917ef6b5efc7de4b98ddccf53d984f4163efad04637559110ee6bef2cc96545d0e15c5b59a13cd217d2dc9964a0d8c9b36578baf19f4b06a97fd5bcede1ddc10c9e2955bcbcc6eb5e428a79c3c179c8d077933058406d433256e5af8ae6bf91d017933d72f07d661070af6239bbe996324f6be13e376f8390dcae4cecbd04c5ef1d5d478d5a2cf2da28e0f917e10134c31bfb555f91979eb52d637f4ada3895e303176e91c096d5f4d0175c0311bafb47e5ebd6fd6c985b4baa9c7193192bd5b0d1c9918260f6925349658e22b5131e76eafe769d5f9c7a993fede1eabff88455e2881d066092289ecdc1539012d74e9a779ad2068a3de66ae91921b51683f5a429d9a3b74d964ddc1e6cf89f87f4945cf8dd0a40aeee254592bb56d01ef27880084e62022f73d6218e3db5cdbbe8e263b8386e2112682e8f4f5abeb85d00adc8ecd2aca68183dba492facf3aca9d99f094c839c276e59dd171c9d739757a0c4458796968b00350ee869ff4c4eb4617c9f08c9281f7b860dfab10e259512163834263ef7c5fee091545b11463846e5e8c9eb61ee5325ad8f826c39dd4cd6d99f6632349e1a3b5f61f55ec6da6589fbdac678cb0fac1b59e0167718daa19d70f53687501a57e878bdb34143c6c0f60c5ad3f3c733bef05ae3db4c739730bffa3d0e1a636f6045742faa409bb120feb724c9ca7d9970f93075ba3d08845fefe0a0c9608e4804b9a7947dc96b73a981db5fbabcb11065b6e3bb8f8e86f46e8e9fbde3be3af075dce460067c61d8f2900754c19377bbd665ac9d5b479ae6ab2cac510f633c471c7b332bbeaf948c66c61b9002b1743c351a5ab1774ce05e6a3d83ac64d6867fead6409d75caaed8173d039dad33d39d5d6df6b7b7182669028accac0c345f4d3cb25bf6b8770080400a319bd59b205c61e226ee17caf61d1072c8c03db76ce62eccad476c9d46b4a458706062fee5b2a3224aad56b504c7dcb595e77f25a69bdb51d39cd7f8c47838f3e6de35fc1e4f95d50e0aded698010d4adf01f0d6e741bb437fce1f7530321c104f8983c59e6bf368c7051a4c52a2be813ee22d1c0555627cf1e28984c5fc684df7eef4b1cf71a336fe0f76931407790737f2660226dcecb200bd25b758b223a58b131cd8d8dea8befc510e02ef66c891ab94b80460f0f830cd7b93aeec505f373683723961b829e1789bb3ecc10650b8cd473949f2a0b4c155dca402f49c3716e2abb0b719aec4b97833dc908edfbc410f0984cc5357512c7627fe746fcc685654c029b5526f6242563922c4ba74bfdf34942f4edcf617021f6cbe5643e2aae94435d002b85a2d4bf3e83a2ca2876d796e3ee5c4da576dffb13de1fa6b34af8468747886991a2627772fd7671771f898e9f608d1bf754493c974084ff92df365e209da684bc4f619ca6dd17c6d2e7dc9b0f99519f1e185eadd672faa5f5cb4f5098547177dc4a1a21bd0772637a650b83637e80832be0f73533be7da7ceae4f15ff2c0e8da421a30c8aaa5d1fea84c6726af1fe2316526aff16919ece6881f116231236bb3d0cf572e0165048beb4b891b5f80cb45d89ba5d4b49c5875ba92536d94e3631a7a66e2ad3e192eff3ec26a5bc429130408409a3421af6fda7e7b00f69d16448eb4ed77cb45755966a86ce84e6e68956bc609252378a59439b9031d6584f3fbbe934ef1f434bb927efb59c94c2a5c2a05986bddcfc18fbb2158195870ef4979faa15231259eeb753e7553fa6f25581e030132133473c02f158855dd773365ee206ea2272e332a081ddc9e516c85184455d868d51091187519b2916a06b6f6cae3273f0acc27fad3fcb0021cead95815c217bca53b0159f5de3f8dd8c5bf60ec90a8c3bef4525bb379cfe35704ad8b7dd476a1c8cd1bd012c2c44283e15f8219dc183addf3d82506cde22caa25f176663129a8810e10a9fd8f67517fb01a0bf9dc0ba80d622d0be058d4abb98eda0030ea66cf266ab6d3543623af9643faf50405247a5ccd28bd73d1a16cd4364651f22110203f82b56f6e09ae90c7e617f2105ee4e7bfc97a6e9b3e7704548bc50ab18aa55d17a7d779b911f35e7990b89b9b4f4b2c0afca9cdb771a11c33bb41708ab6a2c2c6b994db47199c8761e7d3ddeeddc72d11de9298819d03da09979cb9f42597c60b443272e47807f726ea956da41233f5b13e1bd5abb807b7f4bd3a31406a4aa68aa4823ce09f6f5560be40bff2f91b90db7b01c630adcdccbcd865de37f23f85384641d5706541a3e3d2ad586aeb0b8cec6f072e0e8dae4fd42359f95200994ea440a643ac03d3db077b8d4cdd52e34733b1702bd46659e0e8f89277a2c21216b0833ac896fbff381f9295b04121598f701c202105e6f1a0a135be0762f049d2286a9f759c4e6790010db957b4a4454daf0514c61611c273cf804d8ce8c6102399749cd8121b305524d5e602476147552cc1bed2f5b6cb352fc0689ae798374258f163b4ee362bca0a7081f3ce4b8bcffd582e94ca7595b49748963a1396d460d837b25b6834c0d3e08f2f2aa68009ce1e0fc95e902cfaaed492d86e44c0c8e30ac70e9c293b5e21a95a367535b9681f87f6c3119c1d70a8847d4e7fd2f9ae92d2606d2c9f460bf6e6f7b90caad8f3bb60358f345564b5ad4e72f416d3b6f2620ecd8e702d842402a535c23cef1252fa6462b77ac2299ee8d333fc67c038f686258de46cfa21664266745ce0559b66de5ef915ccf39ca8ca37b0e26bfcec1a000ea7d660584e763cc168bdbbce1566fc23ae02f51e9ed199e394cfe1dcaddb28037d12c80b929b8e10fd967e501b12cfc4f62a2ab2bd2cb271b48311db33f1c7675ffdf04a8ab90ff78bc6b898083a49ce65654a28f73bd3ac6548c864e8abc0c3215e3fba56c6ec2dc3a41bb147446b111531cc8e749e62101775d1e4b60f69944a3d5d478f3fc3dd261086b1e120f7acb92471a55c8de095e0bf2f598475524429f931341a800f0b0e8460eb736bc3904926f32ddebcde70cfc79b41629b0242860661c4713485a0abbc9ec982aa3aafc9983136065ba12494356c62d46d4f0d4bc979ba8d6aa01ea4f1b3c81ec367340cbc10097a46d4121ad44261afb1cbfbb297003c94499fb373267e383fc1eaa2b213397aaae7b5ad97b1e69b814db4a504f017903029f3725cca6b561c30a804c988d965add274346dd52fcee0cbd9155e7a1df8cd21242d17ebe3b1b69eda1873a6fe55e7403df3b7d6990ff0030dcd165677fe7f67ff433920568c2fcbc6e3491820a8f085fef06e5bfa973d3aedcb2699cb3633eafa46e4f9819acb2b53f6a132f7806b998274bb909274c4114c69da0765be349eae1aa93d6ceeb9f39b2f4ce0dd57bcbc867cc089edfbe167eafcb0465c4927466a254a6d5878a3f7ff6a50b7dc5c06b02d6e50b1257b450b1b29a6b8fa3bf33efbc83c75d8a5ceb176e155cad9e2f5e5e9c76be15e0030efc35b89a6f81406bddab46029c99976706bfe02cc4ef6e9bb7e9ad09540f18b87c9ce33b7c38b81c4e6bf283cd8e0bdea43fc43523eac569e9616f3e2dab7192e4357331b89abde231d63edc7a6a14b57c7462bf81cc9dd81f68cd0a7eaa421787bc1f1fd08cf56868bbcb6c9152c1852c04816a888ed884f1cb9157c530c0f16e9f1dbb32e17aba30b47784fc3adb8d17d195e924e332552dc3b63e38b12ed778b4c67f43cc07fa09ba07252e3daa0f380d982cde3bd77cec5f7b3e380791260b04389ff4f76d498d76b2f3e1d9d9d54c6bf3ee2360b65182e31dce97314137c9b8ac15270482fb44f9fd9acbd93c7eee67969106416c2569e5c89d9995560729fb7a9c053c9aac09466307969e8d69b2a155d8a299aec31dd51ab19f8a468871fd99b2a584beebe5bfd7d3ce3021dba608404d1738b8c15351ae55a31ff4fb7801e09034305a393d633f7f917ffc22f2020de1d08b734b36f64b41467c705994c113b360da3ccfe5deaa1f14c57a9a5988cc50f1c1a2e94b8f9d4d06f3e43d97ff72545193bc12b832ea89adcb318f1489df260d53eb73b957a84fb010cf9d3a8a3c9a0f74894dfc44cf2bd61843b30f3c4534bad2fc895e325ed5fb1b788ca268d3bdad7771e0bc7adab685a4f8a8bda2dd79bb0fd6784b4ec2fea5b1f89e5adb921d6e5b2cb910381e2af36427f3dbc9a5542903e66979d56f5fb8722b86deffb73580d41fb20c3faa9a74add06c57322238263e45e039dfe79198ffba8457ee80eb96cedca462e09abde0709c73a4f800673f2c0bc22f64d63b6dd1b3d88323d4d54d0c1879bb7dcf8730a6a7cf6c29245ec57978f0fdd884a924e6e2c7d0a0134fd2de6fd4d54399f2374ca50c7bb587a7becd7f6193277c3afd036b448b707be43e34c8a93ab3a1813247d82d003f661d5d8584d35b696117195a1a5469d433d51dbf9c91657f2ed2fc3785ee448901cd1ffafccf07b20f5e0965ef99966035753e65d0880f25f15724ee0cb0493e63a891bfd67becdd7476506ffd35d4754e30ca4a6604bde4aead8de63a86893e53bcd2acfbbebcb2b71fa4a9fb7fa2f594ec11ef8044d9b7e532425bc5d819db1e2c70a510f2f87733c51164cb60ddeadadb7397499cd923cc00cf21b3db68d2d8e4eba00cdc7e2685fc453d4d5307e926823e0a845bb3a52ea9e33ccc691a16dc4bd69955780b388bd3050a941aae559ae467ab1c4fbb3243287eee6cf7e8f6cc50c09f6496e7c726fc36bc7d76fd6322d8c33913ea7dba43fd531c5237ba0ef782acb44a5df3f80909dff5ff386ff237fd0841f6fb6ed6eb401384147159e8ce1ba9298eadc646f3caef66274b4608c0ddeac901ba6f69d7c62beffe2f9e84f747f0ccad068bd34855ee34e4b4a06305aefad021dd25969e4325f3c500d5fd61ac37a7949b68992782fea1f05de246f87a3a1b8ca0cfc5b1d60e395066792e390d64fe4bcab9e532dec19011340e583f3f6f269d21740640b8c7f5bee4fcdde09150e7a757045a07c3acb98f14b0cba67dd3e8723f085da88a2f041ef1637a3b4ed330e421a2fc5e7b1ec7dc93286e3a94f01b099653700e6c1a85acbcbf34ece89d1e936e67215ec20ffd9a11f05ec8951b37836d76789ddf7910053309dc757b2951eee611abab500089376f960d3f4ae02e76b8db2ce01946c29c94060b6b799e7a1d49576848c1b56768562ef28c4a9d4c27b2806cbb86c2db136d8d7a92514359fe97389cd2a53313e4daf77c2bd731b88e6f8c17197c77dcca3cb7ab5dac3142a94faf0b945ba11f76a997e5e2007a4dcc9c5e9f1aa1bd3bacca2c61997bcf578a80133f25df4dec5d3872ed7254121ebc3b1ed60e19daac51efe8cc7c98fec4517ee121d029abf6a9c5a2f5a2fabf1b3dca3d2b9cacdd0219e3f4751a74cc40d2c71e17b7b938922b138b42a3f7a2480b30b41e7a565b5b1357ed5fdfdf2b81fbf3cd005352505d6ec953035d0329be868c99fe134acd4d9f0389808f528f4487514b644750935918dcc132346acef4e5658ab22136461ff5cbb16242948e240e5576729829c6c4442a3ba43d3cd6d5ec21615e12164df113e7d4c6c9b2beb8903c6a9308ce27710f4eaffa9c5f11d5736d2896164767dc4e8607f43f99f30e633613db20f4c8981e7d2b86c893a35a6a3c025a46b52bc99ecb1881f0a1826a5c5841df8e2cfb3259d2e9df02835af40e24c9024aca3b9c4f5ebe3d93fbc255d9f11a7566bbdfe74d5fca68ae2a5ddeb84424f11d2dce4de3767adf8e01069292ba74c771c3091579a26a0812539ab4904f26ab0e4a8255abba061da54e5ee0770cd81f6543532bfcee414507253a3b59e29b1c850aa6399ea264fbb59491327132309d64f1f1033e6a71265ccaa143fc870f559f7c90d1c96f5c81eabad2408f7804f4b6b1db91240e48613e7944a36b0080ed1e719542b304d4347250d9035f847354c72023503b17429c78f7c122c456bc87bec88dc637246ad2673338593deab2a331752acb84586fd02648d95e8fb855ac231cc65f8cd6fa5b002b5903ba08fdf54a99d509f5f87fb6f76d4dbd3985b33f0b684611835f06e73031f64728dd07ee504ecf9fa7e6962509be844a5f55687029ab3a0bafc83293ced1d4afeb1992b8c726432557f0e81fdad7f7e9007f46dc79a4a6a8a14d2a5d34104bd7482f0942a90b4248ec9e4fbd94949fdabd8c106e88280b9d636c851a7ce0b3adb803c18c1aa5b80b33ba415be0a8300269eef2d2a5ecd11f882826b50c2b5f52961d84f6284066f5174cb6e3c8909ebb9b9af5b41ad52e0cbe6caeb19f13dda2da24b9c2f96cc58f712f0b8f8965369812fd8797c7e3bf0dc5cd35edc9f725693427febd0b1d935d27c3c17fd6b1d2abc5a283635bc19ad7f55e8a89f82e360ef581c679e5287a4d5036a86aea5a4e9d879b5c68855b5e17613ecaeee7020b4eb3cc8e8ff41da8c9f2993329766a57959a303ce4f2977f6f5bc88dbb06a7dd496c9b158dba41b9fc1489d0dbccdac2f1e6f4ae8b7b8803cf0049f5d7d0db3ba6fefd629af420d08ce1c40b38ca61fb373f1428b991708c0518ed57d2387ab93e9b9832139969a62b12223c67f1fa7b2b125573c1590cd2606facda8a2529aaaa31eeb86f17fafd19341d6df0c3c43cfdf82301363a406f4fac97aa09183c86798972e72146beed63c0109538826a2c0e15e34b75eae9d4516b17d4f4decf8c18716eb5f9fea959b1dba279bce472d4c904c205d97c3b0b745b960997faa9459e50506a4524b23b72efebf0ffc2633e08aa9d3c12922eb549242050e5156e548f5bbd86359b2a946e0a187482722e513b74b8bd331bb97321f840ef95782788d814d4419876722feefb2579c81ef8077fd8ad4df0ca0ff50e49f05db6f5532065c37e1bdd4ed5d792c2deafe7f80ad5cdb6cecade3e60447635cc7becf43c2d4d9305a50bc41ee69c98000ed5a5032da849127bc3fba97f62a48018a20fae81bc07acc1f58424893b6e199a77622903d997924d10fe294d752aacdcc564fcb1b1a05bf9a3bcac366f872d9d3638b4c81f72d40fdeb90f99f3c2bee25219721847039bc65afb241f674a97516c3d23df9a73e3e399e10061f13479916013083fad13c52a2bfcf959f77b375e6fffa222bac0d2a3e854a529f1b9f0f163451df289c21d185d0af7783200724356b39e05529bc9b3452d85bd0593a2c7e5943870b3fa16c707a111ad71aa2e1a344dd6244ea4712dec463733c5a4a49bb0e84c5c8f29a22530f8c5c3eaa40a1445f226b592da3e2f949ce5be3581a272b7024d162312bfeb7b99b43cfbf67953f7ccce1abe9ea37f2a996a3d8d47708033dba9ad36d7e7e0f847153ed7be1ab24925f89227aeef0f5c7108ec702b94de37cc9a33df561909e027f5086a7afa598d74a04a698be513ef1e28b0e9260930aa40ca2352874e236654ad88dbee32251703fe9b7dcbb6837db64b3c38ffcd7a379c1fa8eaa26c0b4cb814476f15891ea2f87725509e3b4442ed9fe04444b6f6f48d34018a266006c619552a6bf78ae563be0c344668956aaee331d8004af10592c61c3f50c9fd78ce554707f078341c459fb56285ac07152bb4565e423c866d318b7108d41ab471a5d50d9ba65a81a53887e0f1e479d53faa6e8da9fb5d7df1d5645716db7abbfe294622870d8f90e52aa216f9029a82a1261132835afe679a0fdf080e1cee417dab10086ecbfb949c83bdb8b4289227739f0da869db6dae80f93012b8e36ed2b4e8285830baf45a06e5bd8c77f699e279fb274370838c2bf92b8f8145dbdab2bbd1b376b66f2b84a949664fe5dc75ee5fe60a2ee7330054a4dab1a83cad84baa3a19349329f126f36e10adc8935e7069ba145cfab3c073d3540c2e2230529dacb6e4fecdbdff74dc4de188573d42aef38a3fbbe6809e96e1d3812aa9ead7c71d56ff0780948beb1f1b5c7fbe7770abe64345b3781cb8cc8c6a5a65fb69728daa7a29af1e30c38afe10b6f9bc39bc686403d1bbdbe2ab633683f49dfad66e42252ad01f6393cb624ea867e7794bac38786e02bf71e76d651404394c63e41fe9f17dcbadeaa729677b38f203f7412ab2c0960b57ab622e419deae57fa8122215e69d8215a24bdc4db0f12d1514d3519a6a5adf7116f794735c919e3434f49ebb9e9a1686b11aa08c6cedf3f418b900988fc7cf96f38ccce2490ba64a2fd18b4fa9fa463e45f729e37a5c7632e7d3926925476b93d03d62f305605f9a3971715572e5dc63b66230a58cf13a0d99ccacab4e58ea65a815f771691048367ea38b53bc788b8b1074a049d37dcb56a762113af7c2d6f823012e3dc8faac43f970f2fbb286446f5f9d2b12022a463f28f1b55a4fba572287ea772b936311d7736ada345606afe3cfa0988a9d7e7680baff25cb9a8a2215bdbad757b2f0dd331607cdadbec79229fc83b762f7b7a14fbc245fee7dd4e3ae524f9da22b7b3b66b71b8863e48e057afa7aaebef3d1a1ef50e36c115493695fcaa727c13e42366f53830927c505775144bd8669cf06cc4771d49d593cf2088f0b28958c3771f92b7a7c8659e1631be898a798af28399870ac74e227686ae431a14ae4a229177a0622ff3d5f5e502c3bd88a93f087294c0d7f5d347d1be393c3de668a60b27859d71b5fb7b9349b50e2c4384b731ace3cd3bb2052c890565ce57eab06edcc4967e73b3d57fad127c128bb98d46aeec2f5d212fbfb14eae49e3a1c704546cc4324be899493b5426da4f65f599452b3ed39c95bd08882c9815c811ef0756479b505acae02d6c116ab409fef76631672cbbaae68cfaf39aa7e55af3213d1e8a914fd256d2d81557544fcda7a175ab49bf54aafbc670b8873c08103acc7dd597abfaad4283642c000e5c701d45ee349d6a5a445a7c132591114964a0d8c75dd9e4e7a8b3df54fa0523d0a0e22f2abeffec08f74c776695e3d971511fff1e697509f60e946d67cfaebc658978bb2713b17c0da56745b74f14ad5bedca73486e732c83b80f9e4552d0cff87d515a171314ab7f8bfc8435c0dbb682390be726f6c435614623fbbb1c8469ac082fdbb4be4f77336bbbe9eb7692c3b0f5ceaf33adef8e3e1efd4130dff0b6a15ac25832240f283119fb5bc803f012cbb3712a127ca1b9a2f81b1272b071fe82fa39113e3da50ed29ee13a49f7d689b5e52aa25787225f0fa6a32621b9b4b3beef42fdfc9a49fd6016d4a3c472a96b745c1240b097617b48ae4067a57112f1e8e29c841513b37ffaf6d2c80998589a815233b3fabecd0c491cc32d673d1cec21d423ad2997d00226a160ddc637bb70d5f3e55414927a12e79df36cae7e055da4f6ff8b8377263ffd47e08ae21f32a1475a66f024287f9a56393777bead5a714f02706207d5ed6a269231490b4f1b19035b904a9f981dc9e556cb41731be7390c8ebfc8681bca0abdf51d65c8b155d317fe1d8f43aca9c92171a71731d74db1d4fa958882bf7ca564d0582d2d56dd8b5379373b4aabab4abdb5a001b3f7b443d10a45b8b315ee14a13abde8410b5daecd84fc09c56c4dc0a27ec3a643ffed8bf23000831693408ff72d03135f53ddb7ec2a5366d1e5e2811681e6e3c8f1140794e0718b298ed9f46ed561d5be7030071ce32a5a94a4aee8b63407266be3bad57f4bac2691693d9181feb7576791e80e0342388db54726691da282674ab02c5a68f8df30d26404b3e3147f12cbe0f57f7f5cbea7297cfce06ef3b0883233b73becd5565dcb549063511fe7f7d0e6aee5efe70c0b7468ece7c6df996a24147b92621735e61c7e9d59bda3ffd50414e546204cfa0aedec5434c1c8001a4eec04e42d0e9155d792ae5050f4ac75bda604cb11cf6d3fc445390e83017118adfe4b4ed3460d482f7e31e7663819019d14c6c9d23725e6b41617bff7369ba0b4e75186e079d1a755500cef7d680741167a15441b998186ece1bd2aee4dfe9410b31c5d2e80e3204a84d811966c8886f329453656edb70cd36c0f924fa798990c51e8c681d750bd894bddf80352d7bb895e85b66c645694580a56ee978a6437b929c08155fdd7ae167d84d2daa01485211ad021376ef865421085e82270b7a5445529f86049bf017708186797a8470811d06789ba5fd9966493f7ba18bd42e79492eddfc4c63ddc72f1ca32543e33fb0e6910699d99d6991103efc4f0ff8b6663415093a0bd594ad179b574be4a33bc84b5ee6f66fd54733660729e548b00984496d7c24e16d8679644c877681a0a54b4b69d5fd72f819edba049780ef7a2b2e368c81d95a509b89a351f1518b2e561bb7c1df589952bf4faeb7b784db9afdae030f70ae1959d364b288e19fc8028d64ed0e4a7e61449d5e1a0ae926ee0e166f15ec59d3817d855f568b0f8ca45ebb1000b4f1364060ccde4bb6693da0dcf233264bfa4c9756f73e4cd1beafee1a89557f30eaf92febade1ce44b2f2878d9b463b4a2fde8bddf57cd7d4739d8d8d37b775b13e46d4477cc683a3acf30a8c83e5a6e997d467a7551df2decfb375a7698d6ae3d13470a108a895d7192388c41d5be45bcb9fdddc71b195303c74c0f0e5a31e2cb489503ac65494631a94f33fe0d1055f43ab06836d55afc0593480eba74814bd0fa8333e0fcaa3bcd4472c55464ba6cf136ff46a79d2187937a6f7b6e367b292480d81aa6febd845ce656bbf2f40b80f9c59b7115c89d83075738f858ee301536a245ec3bc94a62af287e321140663e25aa671d3354b81f67dd0ab840069404c908e2283c9a9b1e9594fc9c02de87f5ec8af9e5af8e872dcd37f8089fbcd168dab16e901d01abdce2b3d1a969745c46bc83ffd6ad4fe88b8420dbd708ac57c601a20d0008cfe2d45bb91f909e8d038382dff33da47313ba5fb628064d4a12d06e944043549c950db6213d0591bc69e3c28570f3e23ef273c65ceb095f4a73786af3679e0b7a4d0dc26f170c8ffc19cfc1b529137253cbe94a79f4189ff03198aa73034633c9c336444c528af53e4ea19840f45b622ee808ae9c027d3fa2372be2f4feb73347a30ab49d7dad56ac63fa3059a7ea4bffba30ea1a862b318aec1d54416776189bb114c6b1a71a118b304c21d8442d1740194b1778c0ae04b964e97e5dad877f0dee38d8a5a965c6e39c13d23a3215cfba36f34f4ae154cdd49711ba19c7963c562cc384b7c42ecdab814d66f9b90fcce048585afc6cdbe007501f19841daa3bcbfe77de83b308c4f875b667b4670b2e82ac908e7689c93b92e900de9745a4f30fae2fd8a1a4621bdcaf2aee794984619c09308fcc2636d3859d3352a8fa2ccda9d81404c32f70b94b0d7bf5f5484cc1f367f429f068fb0ce7565e17fb06a9f651978055d9f35d6ab5e4b15f1379aad5fae8bcc935d11a375718bfbd8e1afb741c420efb8e3a5caf69cc74e09b7e64c5f4d49580b34e66b623e2a348ab677f6646c97df6fbbdd64a450184e07c6d6d7073d27bf0a4520700e5ef539c4407ebae06ecb9c21c61a02c366ff5afc479e3d37c426d796853e7bf572d18977c1850897816ed3ed8a34619686961ccc3f0d40d338d4cc7436c3bc70547099a1d8c7208dfe7e12ae725becda0e7f03ea79e18b2ed1bfa08a14eda013f07e64db84e9dfd9df1028cb0c2280a6697edd79bb4a819aa9e6b5f07bf6eb5e3cae91a40338965112f75fbc3e7a9599de1fee4851c49aa057ccde7196d812d9834ad41e08b900cb170098b7c1b071f90080c644791b6df163d2ae1aa71fc69f2e00935ef22dacca759b667c87c15ab583a39c3706649a8c76efb473b1d98decf3e44eef6b893d12815b39574bded204c73af2fbb44f5a37d725c3c4581c7669d1221b2677d4571871db324840e0bead09962249d15f23c35607d3b6ad1985112b4fc7ab8ccce2eb5b0dd0f119c3b605674ce9fbe0263d970687a020ee9971219db6b81b656f5910e4043958b7bba3eab7e54ab7c356c5188edb4db968f18bc800f0e7270bce1cdcceaf03839fb1d49e581f6dab50c54fd16785c32566c934a2f257b6fe0189a5abd52fa1a475f5c2fed030ed20b47cc4d8f8b59a9411832e77dc8bfd45e1a117af2ba3e7e5457d4d280a339068c7ebb09c23f74074cbfee7cbfd745e27d380f7ffb8102628c440cc7531fea4aa11eb0f87348cdea6d756c855472cd7c840179ca8abfd456b9931e6e549ec5df72a97d21f242f03bca7dd064a80cf9c83d5889ac19b59aaad892c5de7ec139d981a26ba16122fa6413d63a301010160eedfe7909df2e4e974ac538991a75d90a9fd8f800e9c0dd64e96d3d0222336ae60da368ca40ab1a033a1abb6797ad70a2fd4b7237a28f89ce31f29704991d084fa886f876ea5c2930bcde729ac66b4db0219861fb82a5618f3af920353ed1608ff2ba39ecf0fef1235d42bd3f4566849b569055e76520704fa6bf534aa89e4a5af30662783963543f4db17dd14d950103b719e200e04294cdfc93c0b25c2bac8cf27a1ce9fa4247bfe28df2ac675a11e3efd216846fbe7fbd23efe13ba85edd8e2a90ac300449d4fe346d80710c7ae398a43ada2af153ad7ba4d71db48a918a9a4497509fdfec123395765302a842f04d9eb3ba5f0ee91b6c75381dd313a22f7ec9c1a52492923cbe6835b0a4a6e495bf70836d7e5a384a86bc493de5affe091d9aca65c90a95d7fe940637fc64bfc73abeca0df0f7a0947bcbad1bbd0b59577d44d54b9dd94fbb523f2c953be9d67465dd4a3825a73480b75c4862d74010267835283a298332235d7e41d5d689c115e2eb25a6969dcb04266a997f2bb1708c9432d81e05d712baeed92e3a3a3b9256f19d9d6241b8f30af99502257a95a8612b02f08afc1ca30bbfca06155b697971b674108e809d88b4e81a2293da7f1abe5f08eaade8eec2ad5683e8daf9b7261434c2294f2a679b3787ea4c9479e28767ddde7e49b2682932571eb1fc11200cc5dac75b8979c4a367b133cc476c6d6a534915e6fdfff05c4a7816fc80cc351ea638a3ab82f644f6e4b35d7860d6276ea4558ce4267445d60a886ecc4b2edb57b7ade4cc0047503bd8f13281398b3d5e4e2709b2d6356c5ea6ef76e516e8e9d095f363762cdfc4ff779c6d9c7cbea9241c1b5c661ac92615842b61349907120f9942ccd464bb3d112ee246a2f317563891d25c428783bfc2bf9e8cb2fa74d3d91058a63842e0488389ce6afa9acf37d688c42817ab446473737358978dca609cf02b637d717f816316750f92f9f20980628e040a5fcdaed9da5a09275441fd07ef16653afe234a6bb9b264cfe25d1e6073d0791e1177396486b1c0eb2115d2c0fe2b376d4be046c2ac660f65ec3a97db9945ffef4f7e16c2323a6bd5833619f12f0feb9c8e39ca97e0845bd24a3df958ccaf83309b58cb3d61c4245808718562abeefdafdc4ed61b5e1cf2f8a1212cf8625b5c8848dbb81147de16161bb59b82ed9386e0098dd381867844cb02bf87d049f7415e83c311bb77632c254cbb6464d5c4ece8ce099c8808143a7354455194563f9dbd434e80f7acc61fecca37b7efb9acd599e49a3da14e369ce650810343c1a6128a14270fad685cee7ac350b60fdfc57c0ef980d0c72b9c932152f257699577cd54e1af86db870905d835cbdea768fff3ab3d6960cdccdeaa5d413087523765c672a875efe864c6f68300910f9f997bb028ac1eb3a9eb910f625e406aa6e769be84656cd152ebd21f0896543bc7506a135fd91d83caa76975fe704c6cceb2ade991572bc0bee225d0807479000915fe4ea01ab3c5df3faaba3dafd351a94b388b6c3ad8056cbd7b316ba38f3f8be94c10db05258428de6eff07cc369e3a9e41f3fc4b09d9acdaf99986d730cfe9684326480d49ea02d3a5daf419351c4f4578f84cef24c077c127714e2fbf065652c79b0dde1b18720f2fb7e3b44946eb5529c424980596c2d259a2105e699dc97ae779de013fba64475b7eeb8349050fd453b1099744c956d46a9f5e968fd065f9eb8c5c57f1fdfe8f1f238084ba8e77c3061c95c81bb2f8121ed15edf3ed3c662be5e6d3ca5c82ae0a9926125dc937fc212e553ea6d01a2f18212ec1886c37eb40e5197b54b9d261b950bc4fdf917d145ed7ae7a0f8f4c5e9b05eb31c1636171671b79b9828d9880c356f6b4ab13bbca2c0c4d69e3a1f40ce26ce25ba466f88226f0ead16be9c21e3e5160b12cef3ed2d8d23ab23ac3f67929a6276a9a873c53f48589fb5289eb35341a268e63e204edb79f1e247c261d7ab89a38cff5f6caf918bb43666ddd53b4ad7f564071807e01c1cd518aeaa2abf114584018382ae608ddb0f582519e6e4ada7e13739f3001a9a2a8e8ef8e1b6ec9e757f7d97c721d9bc47debd1063e98635f2f873d8eae9e526dbb49dbaf9ac391080545e9eb9f3ded9b9c78f94c727bd039531cd16e84e28e0386ed0a29c056573b2169af7cfad3de53401544cc75e2e9e803cd2eea43da53f0a0dff2471b28c76c842c4d39e9d9c912aae7d8c5f8f995c98591f690904e16b298310f5c05aa85a2ff310385c5cfa7079aa25993ad9d8a95d7c38ed678be4909f368d91223b521e425c4d1645e80d770c1056017eeac70cb3fe47a48d888e0d6c683e988ad3f7e0f1823b64ea4e8e851b5d7c25d15483c4b1a16fd40b9984217769fa06d0b0165e72e472e3af0197ab1f3351eba8c0214109ac8e6d121405e1e1773eaad77a845af4d7a7edf068160f9b05ff5a386eda1e11c09a7fd645c0aa2516cc6f5670fca3c184aed0fe168f2c5368aa7028014b58ce1685159cf2dca170b8615f6f439a74fd6b7f24de9f3f5d0ddbdf8428178d27c3feb1c61f8ed4b3e0ec56cc2826078f47218cf9cf820f46df260f89db920b03a5bee7b32249b71de2eca568d941b0287fb768ca37f0214fcdf79e2cf07757d4c5c7296610ddbc480bcacbf5dcce15763502f81388f11a197d56c146a3da18229f7c2c4fbb6ae5ddc57c27d73ba231a447ff35926ed660beb499564464cf0bab66190ef2690bf54d0dc7f3db2b3d98e1c089993167b3b7a4c93467573f1e90c52a11fb191f162d1dc12147ce46ef0b254641dac8b5dfbc99867be34e212630ccffe045c7fc1136b5be84af5a3cd4ebc0263d1b3574c30c15c6538ea7bb090b9627ee122672f67e8063ace6bd1a020b130985b1cf4db9f91e61bea0d532fe967f1f41c111d25550bafd4da300ccbcc6f79dda6d96ccd183444f1fd11ab2cee6b0b3db8b2de73bb88b2b23082b4739079a7686b044526186da5a405d10edc0bb7e3636d295c3c4ba7f5855cc3bd34ed2d08ff50e685e7137a6fc4dad978ce6309dd635b25ab72bcc27b3eeaf8bdf7d9771b5176e3c4bc294981f9fc165bea43359d548b1a3a6af9bfe2098fab842753f23f83a2bb615f9fdf6eb7e1b3cd524061aa041190745873b11b4af962a27af9b1441c6e8451044688c758d9259d82e6ec1a3fe956507fd49c03d6f4c9158e2ef6affab3c4f4480b7d3a0bd633ee4fc8eb2ceb4c4c8f62ea5bd01eaee1eb9670841452a5b63729548ee3b15e9773659b6ee220759db69bee667b11c5c09e84926d948dbaefb690e37151f8f92448007f9a8978f23383ce0f763faa43f4c742262c1183e4c8e163d436124196cfab7429339832d2da538e9490d8b18dd33cd4df40dfdbb91f00c078b494a0a09a2c666d15b4458426ab8b0cd94a8a37c7461bd4fb0c0c0720fdf4081a89b8937a77ff366ba37d1d99da46668c9d81f737d71b67122cae3d6b0469f6da379f51aacb2bbf8b530005cd9f6d50de77f9bfb9b73877612bd1cb9a182087075b7edd2783aa54541658a97ba1228eb17e3150c0a9199b76c71d21cd069bb33717eb11b608b45bca0351bdb8b0242e266dacea3b108c8d4c7595b859e3642c1e9c06aa1cc4ebf480fd71c01b3c5a52c30e3e76815630702fa1a8cdc56f3776a38710871fc8114ee0a44351fa88c0ac3bc66e66a011c1d35e2486acc1fa58a7a3a03d2dcf7f1c2659135d45ca8c17c69d7461e30ff2dc823ad5a27af6177f4c9dd3bb9341c09b543e224a4dbd574ee845959a4d575cae935c0683921e64c8798054b7507fa5cfebf65b7298e28a4af2328057cc176096871eb246f35e1ca8be6feb440732c4a9b2a8d466691533a3c95b15754b9b79e405d8362fe76a26bc33b97db6b91be0328c3ee6d1702ded3ef48c659d3c56f9e5d5aaa3f5039636884ec89006e3a3b955719990468e926901eb632637921fbb4184f08d317cc97b2860e1ca90d151eb280d7735222771e109eb4db9aabded4b4e835920f9c08d608596c7516b328e623ba7d806359fadbed695d8f0188e5ff13fcf19ba4909a98be148a445a66b09fa0ddad5da5f997ebe01fb45ac7b19fa692e613d55e536e5a5657e73ee88db23ba023bed0146842db9cf4770f7a8075e3906ec0cee5a514737f7ac67c237f9eec57f94a78f92d122823d9730a4864a36776951c3882"); + assertTrue(Hex.toHexString(s), Arrays.areEqual(expected, s)); + + sig = Signature.getInstance("HASH-SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + public void testSLHDSARandomPrehashSigSHA2WithContext() + throws Exception + { + SecureRandom random = new FixedSecureRandom(Hex.decode("7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E4711E95F8A383854BA16A5DD3E25FF71D3" + + "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1")); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, random); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("HASH-SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new FixedSecureRandom(Hex.decode("061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1"))); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + byte[] expected = Hex.decode("1d01c0dd5a0ef67061d9cbd6d309281505774a7ae4425a07a60afa386a36ffdfbaabacacb2f2182e9cbe18ff58cf15231280305e78db23fe04861c9ffcee2b78318fa96d2708bf43e4192e3494f9468e350ddccb4efb0046bf2b2e861802f74e883bf045afb0cdca4b7bcb79161c287d7c33303bdef87cd0b1896ae3c512435f96ea3e48706d434db1b78efe07f465fffb3210c3baa4e19ee2e67b42a79f9660c0b1211285685bebeb3cfa5ba740b9f1089fddec19c50d318b5b98f66dda2d75a59f45c9382adeae63a65efc52e59c5d989dc6c9e9b3d47be6e12ad9123b7709142d46a4023995427d9692c302f3a4e9a1f4a68d2bc341154407bc85593f85ca36a2f2ffd2c6159f90865e9b1aa62eccb503821f93b097770d3942a89633fd5064ca74cf6b00a6c9db0d4d456b6520ca83153a101d0bba9361a73666ee4150ca07165313102fca6f7f529050c6a1c908e3022d40530990fa0aa13c70ed800139b142dcc56f333e40f1bb6ad1a4406530f53cf1ccbb99f90e1aa7fc2c3300dc53570ea4dc44f4ecfde2d95c0c280c03d45de13df444784b5755692d184e8c5bbd8de82dfc5578fe2055863e3f4b843fb1c0b52d5b1596f0ebf677dc2324722f2dafccd6d4892007bd0dda08b206f3ae5454a67dff0b0d532031c32576540c772f78640dcbdb51a421cf90ff1e9e28d80efd76943c559805b1a3adade7ff3b9b339b50d5c797da7814beac265b13a51849a82b8ba4c6034c29604f2d9c269d1dfdda9bef02e26d232d90493ab50207dcac81deb2fdaf8a0f378c8aef9945a8fb24b4bcd6049f78e3cf93d9cbc69ec731a8a7cdbf0a38f0aa88d62b18d7662419dc496ec53b44e7be7a92e47958c2280bd68f2abcc313d09cefb03a1ca6951052cb03f6b3dfbe10ecb0ecb3018aaf5fc7eef22b2b4ea2bb34697227ad9446e0a1191221edb2bc02ea2ea320ddc4060772d3ea9053610e3db6377d697b7b6033a61ab5980915aa976eadbc2c2a12860a8ee00a736ee28be98f0ce9ed9816511004020ed3ef0df82b2669bb06330fb14b08440696a876c28e3a285824eea7ec1a770da95c74ec30849b487070b3a603c398718edeb0a478537b2162b7799db93eafce5a7766b75d203f4e7b8a6ea589c12ae119d72682213541497d4cb45f7d3bbd4ad1dfaf1da56bb0ae5dbc36ff40eacc52c7db2d202f48cb5bd27f1bcf054503790482bcf6dc56bae235eb868f8684eb4afb3ab9c6a3582660403a3cd2f208ace5cd5cef297168a379ef7ca634361f212d6e962644b369e3b126e630537446c10967befc4951f076a343986b32ccd2462131e40d6d3660ea4f4199547c1158a31cfebcc6aa070dcd3350159379cd52abc4a492ddf3f006cc7d9f2d29bc1c45175eadd402a5b7d1644cc985e5ac908274be8ae8953495359f57768fbbcce457cf3fb9e6e80a60d9ff6f44b7b3fff1be793efb18d8f6c80e87234904402d1c30406eb8da51562e69d907a820c424a456c6466d81c8792a332db4a5f9b34d35c7017ca4cbb01d434c4db464c6395e170d12acd5a0783100623d0491aa2f7b78ed093bba39ab399dc89047ca09defc1ffb6188b48122633cf32c844d883bca0eb144b364906e6f4693285077ac43fefd8b2939b97d449906a8e59dd23d464084e539afb706db7d6e7b5f13b46d0bca9b0f896afb9eafddab2542cda2f98e9918b8db6bc93dadaa756a77f4273b8fe0c8777249ef345ed725fd4b59e4d12c2e0fcf689697055b4ac2f82863d8ecbdb4809e49ad5a10942c6b6f247433cb5e8a1899b793681773d403a1d21418efd09d31f04986396313b21c7f96b3b42dc7727a0f92f7c75befa4a132b26939e2ae91c68fcb5af5352d99482115fb5b1fad8a3afa8069f55bc6cf4e14aff423aa78b62d541cb68a1ca58822a6b0cce82de0f5a8710f540892849761b743a0b7fc271c488922dc256103076a09f26fbc00ca1b373eb5847dbeeaff499962c06d30c717f9a2e6584ef441c6501f81d9cb4be8fde9a0105b75cd7cf8c6adc34290b0b21007e27ec413e4facc3eb584ec60d152df0269be3e0f1156a3290490ad68a1043e73be01bf656b7515b3664c59423accab60bb856167a95a65820729e58c9479060f3c14e1b73f222f777097c9b065efaa962f6577e460570e3b2d29e68617986c2847671f0f6482021cd57f867a68fa8f2569f7e9033a292a896bdce5ac90360319bf69ee4d5ce9a6afc743b891516151654f29bb4775a0d400b469a7520d1bdbd084ff7acc6e5262fd3e45fdeffeb1248d8d094a5a5dfceb1d84432b5faeb967db0249d815308a40815db664920e2ebbfc06f6c3d7bae224bf787995730fabd38462b4246e4f6a68403566134c5dad0ea22feb8c34b0b8b8f1afcf45027e1f62a0fd225900f850b965299ced25938c2cdc853611c41b1612ad867cdb3dd2658276ba6aaf400871803d7a57241bef9317f000397d6cbf802b649dc4c82a716414ce8ba9a8788869c64aeb6c2cefbe1ff304c64596480c05be845ca01a07435f42907f9bb7739f86d10aec0041fd79f86353ee81e9f30c0bf640d32138f275bce8f9a49b77dd12fd6600155b8380684c84185df05db2ff282777eb5b29e6ec11ec3b244aba3f09f686637ec8971c6c914e4b8d7a5cad7a75a2db33cf5233db97e1b452880e938b09e6c682a1a449cac9cd3b9412eeca325c2cb23d8440bd7e5acd613d1079d6961d343df9216617670267ee3a78a09b0a84b18e5388df5e67b0eeb608e5f009176d043de9dadade473520fb89929de2da34e8165dea98c8bb9819d818150eaf6e8386ad86b22f8ccbdc6cf4d903d1b6ca7cd4eeef63bdb603859d5ce9fcb2df8a8f8e58e731ebdb8d6eb518585b1a3bef5fc7d980bfc30053a9ae0512914a3a90f8e16d8b14edcec070be1b8975e83f3e7cbaefd7d18de48cf0e51a7c480df1a3cc6a3408de93b9724a125dabba5dd91db6b5bc3a0ab638d509259d8dfefda122e37beb67f0073b8ad701e47e62bfa45c0ec7300e7833c1b965c09eda4eea6c5634bbf81d1e3801da856d6acf4387da4a22c4693ca6301a4f4809959c6b8837931b8f733ab8dd136c4c55903e59f64b9680d73ac4fad0121b71a0b22bcde2ae741404096612871103ec0cfaecf1a1e788f64d53f85875e519542b390b842fcd3b6487070b0b4e5092ee44794e77fee577834ac835ed223e80c969051f7c6b44bd99da138b4f9a7012fe3c0b0089395c8b50b1f6bbe0a0481408025428594c31d64a4262c90d49ecb4787585e9c1e386f1ff5f091720763b806614d100335888528617beb6035a800b91b2330e86268db91a6606359115cf4a61fb37dbb7fda644d8d88848a29d38d8cf984db8386b9f667dd96b6ff7727b4624368f8062105aa5da68e1ad467691cf8bd9aa7d4c83a63f7861637057c7a033a1c6e8315164b0deb9404b2db4b14c0d125d4199fa24b6fe6230b12b7cfbfb516f4f3de7a22dae501013b6cafeed0f0c58b76c87e7f10393a6513a2c298c901cf8f225a42362b611d7aaa55c1bef3cd9779ba400c4fef504bcd8b0b63304c1a8218b91c16f87d123dc691ef3cac349cb2c3d0b0207412d3192f7ebffdb5b3f2a0b9fd4c7315ac131b75b7dcee3a7d6a2bfa92dad5247edcb8e59e34206813821cc7020b74e5952382fe6d501169f0f5f4c0ee1518da0e0106bdee891f4c4f1873f4ff487750c0ba09b826acd49f3a0bb52f06511f5c718f8ccbf15a7eefc1984062da04d049bb70baf1ca720144d0803b515e60369a8e8b528ac1dce9e2063671b7b59e9eac4dd6b567bc76aeb04f48f8c881380408c22e89388a8397a4b91fae7adccb6d5948f87e1f307caa593ea712ec081b91da3d59171030e611bab9999c52c6fd9b61124124566c1262603551bfaad998390e7dd304f558c676af0be96f3be138fc3e5fd3afe594e848515454002c6c3a2cece6955e940923e21cade0a6d6e788a88c34468550ec95bd2fccc02f436994bec52a4c44aed40f50c28c47de270175c2ddb4c6757a33a35b917f79407f738ec78e709f0ce0f9b0606b41799489bd6e3a6d51449cee4c9f2188cf08197d18136178f2d83937afe44099531041859e778b363e2818ed2f18ab87c2c8ee47553703eb3fe3ed4524eb0921830b6e204c6c39dcd09b90387cfeecbc193b76ef9d195c8cfda3fbf84b55a5a3ded745f271d912de95a2ead29333f4a7b8b9bfa2f945fcee4374b0f1fdcd92f3b592c3212a936f754e5b4bc16adb87c409169da316543e731cc22b5cf5f6d087e605a07707b2b46d72373a467a54b3178e13a3339779551f4c5661cb3a8f3f439654192540232f47d0cc61245551031e52b51be89d8524338d7097508d9de624d27d6cf15efee3675994e5f218eed994fc09d4a58245d16499abc5e4e6e609bde2970f1501ef0ec82665c460c8667cb51b240fe8620ce5242b8a85d83aab762b57a528bbe3d0c8c8a2b0e59af61cfc1e3341a1e1710ecdf859772b357b9fd5c7ca06314b149d096c9132225837981d300f097d7d6924b814211ea763240d127d31657675c6c117bc71458b04230a40aab2b31c9eb7c480c64838721c2d666913ddccc3fa12a734a9e05649da1ffc8ade660efebf600c71a985e9a7bec006052857ed7af8b7f618f7bcadde425aeebd21d78ee43d6b233d9df8f40fcc49dcdc844aab922ea97bcc8db23009fb822c5145176e1f0d71c81e99e3441eb9d8554327b20580559b47a1dd1a59b037bfdf04153c46ba0ac5ea5e741444797cd947b2061d88e6e763a84db4dc25987a07798c121d2505560c4af1f0883fd44be621f329164874eda8606d5cde7ec51a8b6163107db9e05ffa32107260ac725311867deb1e62cb1abdaced0cb7d4f5f2748aa1e493cac4df6b7b0226fc0d785f5b3947a03fdaf85dd316286906b3a1efce033d086b280a2d1c71e8f9ff984f682a393828547e30dcace48ebdd9d3957a2adc40d0390d502bf7b9e4a6fc6a72c3601bddc4760c9644519647e1532d0dff21b5317718ec7d960ed9c69d0439c0d975262d3d7bc997a072c3a98be1d5963b0ff1d199a6f2b8585163f7c0522a967b79f68a109bb44ff6e67929d094583b1d81226412f8f67a1167a368173a87cced1dd4934b1fe4e5f0c4bfaa94d54d906387383d9f449ada9dac1154d5d4e248158dccae0c36936b2e0d3b6f384abe458141168b49d815ef6cdf1aca765bbdd4da25bee98cfcce7b732fc7be83919df86ba2330ebb426b847d25df44415798a7a9fc24324aa88a6108efbb63eeedacb267636b6f9152f19f8b05656514f4ce88a63e695e017bbaa4121a94ce0583cb6fcdddf1c8dca95099ab6d348a72f5c0a96006d8e12d343527a5001cd7800bc35d8efba3e8574a723caa643ef20dcc9b90e8b25ea145f6d744f822070490acddf4ce87e58e9bd79517643c3db12d1b2e93e26ab13906ba281dbb47f40fa395cee6c52712a020efed17e3cb32d050387b8403a953668ecbda4bc654a417f867040dce3dac2a526a1777736b5e9ecb75968287685449d0c5ee68cbe31751c203215e27bc8459bc63409d7af8de043f861c65387b3b46c22abcebaedbaa293634abaf0096adea37040a8122d7ecdd156307590e7a14bba5ec8215ba9e303a12bf6d2cf175013942f613158cc8e0fead29be85f363f0c393abe6dd35d9c028e331194fc964432fa3b826dcb427960be5a5b7591631dd3f5c9866d3deb2cb4c8267da91455bc0f19ca29badaf770460108030328fe7909363d442540963bca554e5aec5f663778471ac4e2350fd33f78725bfea40b2cff9deed4ffb72cb0fb416195eeb8e0e872397b709cea18294723ce82e56f390cd2ada2d3bdd7c554e22810aaed94ef65dcf86cc7b46406e371f9af03699d7a75e45a19bc08df5058c4077360cda247efb9a010ecd5c3fa947f3dd1231e3cd25044f95a8549443cf356ce9f22783e78ebb1e07f96ab5ddab325fe9e5b93f4e2b91de912326b2e138258ba06392de3f313f31786a281943b35732d7d286f209e192bc04ac437a0e51e7d2d75caadfb36290e7bd375449f06f32a63d3513fd6cda9b487e6915727e9a4c0724903b5d83c7c02b4a8cf1af5747edb72d1c5bd08891335a8e8738bc0d1db0316aad1e8c5dfe43f2f8376dd44ca902323d02b90944ec0e3d7533d30dd3dd8cd921819e41d429123e32422449758295bbcfcc89574753bf2592ff611cab5664e52d95cc0baff388f9ac2a96a020cd90bd83f1ccf6de4b476fc03185e85dbe5a673e5eb12af25f2d366502ab876ebdc0b7f5e10996d1042e4914adad2c510d900e9dbb6e14893f061d6934f6a1fd6a022571ed4d672831ab1c68c84d3997148c064e382172fba25c316b7965636a79e914e9ee1c312de6e6ac950791e2c454774d1da08ba76cb69884cc9f31e19096f3205265e569471b8ffa3d814bc8fa4a8c72796525f442560f631fdbd2ec2e86b15529f23a7e38db0513c042f98cf5582115d7c750721c480d0a8e8902db069a99b011808fb4cc80a8ccfa52097676a5629d0f19e8d38bab66ac8133f95c5f19e11c07cc042197104373363613b8c34aa1849fb823f668e697c1d9d59bc1c70edcbae8c4c4d4fe3f3287893079cc6eea1a82f42b36b8334439fde048b6bb7ae4558b4757e4c4b4f9a45c0ad76c6555a61445a3d5511cd0c5b5e5769d0242352946d44e0747f8fca074967545b1787572bab95c4383c4c2e4ac42b680add1e73f49f4151d23519cf1ca3d7825deedcfd007eea19e8c8df4a71ac483be225d532772cc57d13e1da38dd4b3824b2227fd2a55d7ebe7edaf8216023661fc6b98a7100a4cbb3ca1e281720bf2f6c43b967f145a0315963e93ef128495ef30bbc6ca66d2cd93daf80998228e101d1714ed99eefd63f4b34b178166b00411a1b0de8d0a6682274825523f4688cd844542e801d503c27b094b3cea18b619e2299c83a1289e6856c7fa74aa5b4b647c738ce7dfb732bc394974429e6b22865afad4dd387948346952f27847247e750b3979414414f37107b2750d491f699b501b4b894684ca8ed9f5d8d7b54ed4697ed0e47621c803702c5c73abf9372f10d09108907b2d8f7452e8e6c8cdec7c9b688a4af60a409b25e6df5cd2ba0529eaa10568c74e4139814512acfee8cd93f1fdf650485c749a3f6df4d8c206eb86addcd35b9a39347c1364e0ea53a7480ff6e0ceb6e3580af99e1aa609f6ba37b2055272861fd9daa8daa60c51621bd8f2417d92d10f531a12de5e427b326705f6cc19d705120342a0978712fdecc6bf5e4694011a56ce16c6fa6ac3527df355bab2f64945a6d13accccc7b0db48bf549dc0730670efe427c556ce5d31c035d0aaf21507c73ae8abe22483e54c2235ce31e1a37f7165d55a2e99f07961dfbb3ed26032f7cacab1b5253ca08c6193c0e528e4ad91c325da5e0decd478c1452d935065153aecbc09ea7a59f68946cefd4c79312bc8d1d5eceea7b2c334bbe12632b14bdaba930373815acfbd1faa764995463ce0e3ac1848b0f084db540c0bc52ee0fa9fe55471b9fdad37cc49a71298411dc97ee08651164daee3dd68fb22c308b29cc1cbc6aca225d4478feb488eebb4e845c06eec07c4ad69e7b9058abd6eaa749c4d0dda5d488a712df26b8ecb7cfc9928922171619c3509a84c0909c015ca7921f37bf04e6d5d567773226cfa7487edcd57fdf35981ffac2e5c0ca19c0d93e86e0695b70362121725babbda95724b78e1a17f45b58c9d3490815c3e72e64709a6a767820283bf00cbb5dbc322d7bb1252a7ccc1f7a074c374d13a8fe0a790aca974c880778733e83dabfa1a8e790922af264ce19b27861f66c6c860963d08d54903d7e68c5a558c060b00d431693f8619cada6c028356227395dc20fbf4b7478a338fbd1bdc33e1ab320eb4c3d5cd85650634b4147e50f7e3ab89b68485e9806c21408199445a6237bb29b2f9a939be2560605b9739d95c7e1c7044f1ecdbace3a95cc3fa1dfc8ac190eb5ba84afc71236f5f6be6c24d7d5d57ff8549285350d2439d61ffff4e691d7d06a6b040a9838caa0492c1321e14ba41e4bc57a94e78ea16dc6d3ec84d1aa9cffdd00cc9cd4479b77dd521405c08730437fbb6dc15c358dffa5230eccd27fb7da35b074ac7ee103fe4aa8ef80638bfe3b5575e4d79174d8a9074d056ac0f1e9cdf22f96b5db9f722ecb35a6ee313d934cbcf0ae3593be91a175924ba6ed8deac57826b20fdebe170b678117186a59b8df8aa6869e8801f5516ffcb1ef301f46f9b2e87137d5596670c1a237f55cb4918a1cd983b38c673fb3d44e8d36773f7d0a8b32ad7189f838dfdf08b2ad4163b49c9d40281ad7da15608f2ada2a9472c9e17c9bbe12ceeb85cb02c0f22e72de45864374600bfc45e305ed71df9632e32274c15a091f22c5853c2056a65ec9267cc3a38c610dda91639c793a3fd7dfdbb3704e321f9c2deb0bfd2d6a101ea4988fcb3dc5894cb087c6db3c80dc8b3ed4b7a11b0f258266f01a367c1688f17780290003be6055b93577c2b78c2bf65d7b2065da6fe716482cfe701310e27eeb9a823aa096a5ebf5555aeed9d4e353d852ca2cbb14c387f279c62d4f37046f66a88381db84e4e9a23edb606ee63af8aa5c9c9f0efb30feccc1af2ffb313788f394055b6e55e16c79fe58b326590468c2c19ab11b189a870aa84fe4f789b4d7588c9736f9e8807e14801dc78da526609d71ab0c54e89721c2adb2cf77e8af063793677a7b18cd062528866c5444f06936fc1fdb8449c493534fbc6454a4ada18406856697f2ad827436c522cedda31bfa0cf8bf34830224ccc0044ed478535ef8486ef422fef0ab0bfe7d818804b5de53c1b607e004150c22d02b31969dd1710ca7a57505c2c30b1319f5df7a6b0bfbdb890bdfb4a6e4dc08857506070bf322cd91cd8a0936eec9dd9874258e5d5134eb1c2292b888732bcc9a0509804040ebf9428a8270a0c0dd660d6707beddcc742a13295c94d6568f838b40d67b3d1b61c2cefce29d6ad0ee0a6ad08606389298b9281e7c8b896dbb1ad663595173761072a1b7301c0e90b32510d646cf9113440c10d1b31d42906a4a195b552e22b2ed69609f99fc24584456b27a4e16dad6278d585346d407c71d4cdb5a817ed8bec3bc4630798254950451700fb7bf9d73cf77d4d46c7459d44db4acbc8e831bd0f237771316dd01395e0f8acf97b6064ba58db686c71455eba65daceb17ced894b30f2f7873d246ec66d46bfeb286ff2fa90ad9a7319b260f5cd90fadb2979115d948a74add1fdc378716b1531c8223546930dcda091103c2f4546d0199db7a59a92eccb77cf674883776f88f284d71aaa033ad65599b1ff2a80eea27317b22615f888c036d797fe64942b5bfaf270432f22f0ef1caeef60c83f8774b568b3643d459c2a6390bea9497dc83624343fc7b7113a3e6b225d7b17723aaa0ee8de3d4e7a3ab1b285c35b3cc845057a51bbc43c08e7f6541f56c18942896835a6689cf50db3194cd834006eab74b8bd0341a2b064a92ceb623b820e92bd60165f07a46eadbdc8d8321e964f80831d74893454daac53f80c0986c7abc538543d202c44f31767d7d5508fc97617d8c21137202e79d6f0f5f29ae7f08a4104f3bac665446aa7ee6ba97740fb2ede6a13376fb1aa71e3f5b5536b0d86ea20d9cc3fa06dbcb366faae78a53f623cb3e3354ea76388a9166aeabb7ac378ccf11a1a7e1fef69b839e521f9d0d0728444121ef3b0157ebf8a8957f37efee69f807b4e4394812c62f2ede4dcd53902270c051831429315d53d3f5a877985c8c84b0adcaf0ed124968282821a0845adcb4fd6e51a053696bd83e9430b6e1af0fbdf029ac54dec0bde49ad9f03bdfe00a22edd73a789ac28b66b20864636223c24d89acf322036db8cd8004265eb196283f117ff555b2dcea4c4debe70acb3babd05b64c1d8d2402f12f407c43b0369982d8d887405d5a51651b4e527ea4591a970d51637064c2f2b6061f562be4ffec34a30f7b5cea32f90c6c678d9460b608cf003c6d7bb7a28e33ca8d54dbc6c1a25dd213514a9547d4cf777cd5140822861e54449f13e353783ffdf33ced92e3dc6d8cbf49e79d7bb0be0ed6959570794a88859c86bcd6ffde8a9f865cfec1dfebdaceb490579338988df8e54a57e21e26374d4e737ee14dc45a437956dc99011720d3377a19619c41ed33ceaf5a6c43d02c23c9c4d33deff38b954eb7014edf7c00ad4fc4b4c5350aaf8fc4d149922940998be02c6ae19902af72d5a7b2d8be54f1def690932d61378852c333c88625a3374f0aa61916f86e0e811bcef347146a902febeb955a30b3392f6e28622f9bdbd7b46f5888694391d91a2597ab4bf4483f15446cb5e5760b03cd57a31d2bb8b295791fad15316c10b2776cc2550efcbb1613bb2e93c9326839e627a0ded17e1e278007595343b0f580cfab6e0d69362d7e369c33648db87b545676352395facd69c8efaa98705d967f6dcc8f60b8106b99c4ec25f949fa9c8744d6b9ec2a6587c057c39628a0176bba0f87812df3b4783cdab7c82272bfc364d36877d36990a6b949e1e043cb27f8f2b9ccfedcaa22f5be4310fef12d5b81a8f2ce3ae19fee5aa5161d5e56ceab8380c31c2ce410e1d31bd51e2cd709da9fa3d60e00a7da5498d5bafeb9172c58a14ada3f767a50e8fd28b5edfc5ad4def25fe9bf706de7bfd66323a58bb154193e34de639c98f90ba6082f6d71ea650b318eec21b164d9523dd39d3cf258ec106fd3b494d31f087b2367c050ae9d70a53dab8dfd94b28aeab4b8897cfe7036236e2af9c61a274b620675b20779b19fa8f1f70b47573a5372b81c4c4f97ffe8ebd84d4f359c060705bec0c7630ef0d59fd982661c335bee3d70e86b93175984830a0590fef571566eb30d19ed6e436956c35f632ed25307ca59d3601a89f882a54e2d7f0539808509cb9a937d94fe5e9aeacba5761d2670be1c1f1e71f006591623fe4a81136ed7e98133d418a0563dc242b527f13301f0d4e313b8542879283d1e57cecfdfd4102f63a75d322ed0e66abb2df46ca236b8d3e3d48f8e9e81f6fc156bc7d91d4767edb642a61335fe365b2f60fafc49cf45ce0eb117123afca9cad78413431f3f189bcbbbb76a320fa706f4a7255957787c378d41e02166aecde8d71a172e1ad36b26b67c3f6139db83c7dfed82ee42bb8c7cd12d789a982697885a2f82282e970f6217a732ec98a2578da583d119e92cefe3cae1aa81e44a1b16700e61ef0090044956a01c23e3dccf087fa2c6288f36da400b1080ffaf04f52288dcac04e4bf14f0beb1cb57b0ddc027a4ace6606490f7bc846c6458fc752df64d2327aaf780618a80b2b04c13a5fe6d18a2feaa8669a770fae5f395450bcd1d2df215ebc73faa4cefe7583f9ff11f38435fd1bb2755c0f333409136b0aaddb726704f5cb7d80343005c1f677f2eb109536055b59745dd0ccbe364e53cf6b4399f78263d906ae7bcbdc8e56066c304e37b4dc58bc38ce70c3b74cf3793c19ff59dd6d57c9c34ef6da1664e6a2064d161c7c751b094bfb07be58d14540489cb64f1a6c1874a33f02101014ad701b77050f7d03d33bf4ee341808a1d79445180ae6db3d7749798cadda7889ec1964efe28f2625a9eb1472be5b8e2c58c14fd6e3ea6ea641320c93511777d74ee69ef38f6fbc83baeebd26ed723e7341614bb5713f59380201d309b22b4a4df3ff161575524b807b6ee2a6af5419196296934de8cdeb8b59ffed9fdbc6c6a01499e24cc803aa4508f1e99751d5681215de284c0090b4f66ff964a3fd6ef44e3f3e58963af3ecaf0ce7d326b77cd58ce123d92dc84f8d2ba02be290ac29e4d3bf9ea069f5be54d79157dcc1079a048e65397384e0bc04299d7ce207271d9507d736ccf6d7528d1618f43d58ed16c2f317409be23a7b40d16d895f1cda099e65ed4c3d6e9bd6411f7b4a3987038fbad05fb8b9679a5768bccc6ac4bd77605cf5dc05fb54d23b85c87dd89d2dfb1230cf3ba8606e7a01b0d3ec2d0a49813cbcd3936cdb9e172b50cf6a76f551d277924dc2880a1cd95b9fec1d75e1fcec357df5f26028c0cdc73268f91d4bc26a4a0437bde377fc088ebc1e29c00d3fec449c6f69e20a3230dc93523d73b040958f68cf172081efcfe03761d151e99d832dfcaf0e72d4435fc83481e47bfa09f6d0e73d4b889b51781263017896c6ff4a5aced91ec3df1c9ce468ed0285446e0f38c6738c42e44f9f0557f630a5f9c3c77d1d6c21577db55c1e5d642765d4bfc569ff148aa90028968c881fa9a45d961158a1f1d6f5d549318187cf99a51510ef76a7fed9810ef852994211a12478e84440d691116a41df70e10ebe65d731222d7a730f9198633b649eba8afe467ee1a972bf605eb228850b1024f014fab34033cfee7b6aa20106c43987a52f25c15f7de415c51681610bc6bc6c5803c115f11ec6a95307d27257d912dcb501291eb30991ff5efbf1752c47a3c1234ba4fc093cd00e270ad8e3dfaf7160fe78fc9f4ecb33ab4f82c1385b38b1734ae21d60cdcb16741418ffd49e25fc7477b04a5b3ffc026f024be77f6e82d763ee978984af738418ba310cf67a25b94342c48b12eef4fca0c96c3032a40fdd1c3495438177d081cbcab4db401e259ff7a9fcdd32fdde8be484d4fd717ca3ab39aec46895ff45a677653aad01a6454b822f5b729aa9bf35fedb73c51c345f389de4b57c71b79b672148ce5bbfbf001bf118560734b869aad3b62c399482c935f1415dcdd23ff4573f431736590fa95352459af33b8b7c3eace02e4e08e5e3560f3c9f7eea16572f187f7864c0937693ea369b6d0a52ffb746b430ef50b639baaf7e8c073638ebeefae315c65b10fa9912ac7a296f48a74107d9053c73227374f58e6d955a6dd86779c6c055dbad61659449018d7a4236fb320161cc459bc54ba9b753fb5a9dd6b976e862bab4b29c469c33a0dd70cd4012538cf054b010a843533b4cc4022f2d32740c7e495b55ea9254a4ea6656d45974ecbe6cf2c09934be72f2b14687d39503eb44ebb8966d363d0745c4ea1505e44d6234d6ec352a76837c95e350cf4826fd312316721719af95b381b38a227f7ed9a080e0030320fe55c28a7dded61de1369bc6949df4d127b0d1918380dbfeb6de68ba27d39e84c786f7a5369b16a6eb41ba1a71ba2dff0382b5941b1d27c5c4f653b34613786f255a9efc2533aaeaf4a047ade3e84032d35e6bb856656ebb9c24f8df48ac5285c6a8326311c4b17f54317f650f47c32695e072e408cd9e4708b1cf03bee2a850bd0a8081140aac8ef9300d766e2a2a4fa6864a8539d36107fc3b91fb63d982c8b99b924feb00432ca11f3d58dd27af83738bb0fa0ff9b0fe5ef43e0eecce30355f4553e8bf3e4eecfd0e1d13bcde61c97b6dee01b7b1e3d503f4183f2d9e8a63186136d90a78224bf5602c178f3b74e61a7a00d2c8702c6bfbdc4172e52ada0dabac29f9854cd4ea3e2399f42a572517c706c0b443f3e356bb463764e1538e6b381d76ea38af5effbf6f7c3dc8bab66d9e766cdfe883c85376a4dc32db84569077317752998ade145ec1dd6c73fba31b7702eaffddeef529ce7bf2d5d7515fdde59be496c650944179c11ad9d382aa1a0400ae1002b47853c14fd4a7d74671b35cbdd0db90475dcafd840748be12e573eaafb4f572446943b49234261116923973b84339d77f8b60eb294d147ccfa2c4d244c62a9d674b9bd0956ae65e397ef8422dee19122d5290064354e00cfaff7244affd7b3ec7e52a57fce7d4821838627a0799d0c9de043b28cc99a6aa3f187f6db854cab4d6ad63cb3ae681a6374b55ed6c48b653ba24d0a54656097207a39ca8a7f3451942ffe5d8bfc5cc2dd31c6896e33129fff8413f5f8e90dec5840bd2746473c789aa4d7f9f56478630b84ee34f11d9cfa8a2792e82dbbf576f07dc94acc5588f713037854705a32680bfdd2bfd7d4ba0c0dd9c7de601ff78e1d10ca7345f9b85c4ba3a820a8698220c1f17a0205c6fe7c2d9984e89717473d937b522b8a890f5260d39d1a751e4e0b48046f380135c50b80ad5d2ec2bfac592002feb14667b5439e3afac45c613ca98f94b3c7426122e39bfc3f073f5434f0c089b2a0cf4fa0acc9ba36ac97f763e9d8277c353a975b62dd0bcebea8244953931ab5ec3133dddf5668e7369b3d3cd4dcad026d239008f8a61a33ae6fb5566d4b67ae048419041cfadddac371b93a818ec4da74757976816b89e2a58124b7d06edeb964e5ee83f09fbc44d34faf71764a1f11f2f719a8521031a0435f7343d7cd330723c25790138f53e0897a9a15c456fb30de3bbcaad172e842236ba4df244451849fa3469b0b9473b3f0c67a0a18bc613411dac3c0e612250ea97a164e33ae745131d171fe51c102e7c8f57b39c4cc47ad5e43259c8cb6ee3822a02c0c73ba62c69443d41d2fdbfba866a5358a8777fa8efb5ea170863d56d21c93296588b1c341ca648bc38f08c2fff85bae38ecabce6a9d889f2569480d5fc0cae168091d78f329209b41f88646f40c297ace830b4254b2a5e2a00680d67a7279eee70a7ee40dac52829213274e80f1db7479e07d596cd16883c16ee4f6ee62af8d94c44989d5dfefe49ed5d5ca940d52719241e4cde78b52df15eba67d4d3528307ceb7e2cccacd43addf29f40870dab6590f00974caf3dbf8b6f6bfd598ecb146b27e2f8eb2f66e47406ed4c28f5d2f874e9d5328c3b3bff360f6d6415768f3d19d450adbb0668cedc548582306a8c621dc669d78b97920a15378bc789ab4d4a10cff4e17bf8f5cb4a97c65b3783d0481a60c43e2a51b346be20c9864c7a8399d33cc86ef09bb2284ee598f94a9c29d189f0ee37e6dd25b84806b16609df3809d15a9298258b6f076fdeca973d764ca4aeee35316d391d42e6c4da8dc5ccc5cd1a8bbaf36c2865f5b231a79fdcd3d35237c9f1afc98bb31dc466d1f8d732bf92583ab7e75413db2db90133ce860b46d4a29097764cee222fa3430b305300068af19b2d0ba0802c95d4cdbc62f835ec94fa62276326d58e8e7a9210ee7905552d1c1de304505994407adb2f90ecef1d44812dba70a2af915fb5d3768f6e36b306e102c1dfc0ddc004813ac844a3611744ff8ea36bab778ad7ffd02e683ebbd955495e5677d75604afad959e697af28ed0bedf19042605b38ff192df33ffce309672efaf2d9e3ceccd0508a529aa286e2187339bdd11fcd668b39a30adf6c4bece1b86c1674ab4ac6a87c923ca00408fd2ec01bc74b4688ed38a1447138f0dda60386fef9890fd7aaa71c47922d4ed979aad0f511c2c839beed8eecae5172d1fa5cdcf2d77c6fe24daad30816c20d6df5e94c2d64d22104549d4e8bbd2bd216b37a535a55f3ccb63848050521488786293783742c8909109c7b1d9b902d3c82534433ce06ee0c7a6d0a5f7649ac12be34afb8e66b15648e7d64c7beba6633352833c9214bbf82f8db5a04c04a3d524e927a6698c9d4008e440ef72b651bf509202b62ac85ad5f39f2ec27f9db4ef2f13f96b15db523df9465fc17b6b482ea2e0e4fd9c89e54f25e7cc24a08d39b3c762c1f62ada53db865e7590fe66115d3f60588e53682ff6586999ea74b8ffd5f0d3bc2d2139092311b0f67005cd89f9e97c145ac54e759bcf8a2536ffd1f77d3efee05b76d1ab83be6c1b796c191eb1a428f52759d96db1babafe3594df63a7068544352c6c91159c94e9e6d0dab767940a1f95777e4e564fbd7229e9f6e04bc0d32422dbdf542c73ac03fbe16583874861386be81bc6ddeca576371ee61d1971c3ce5af1926fb46f1acc58847f901c498b0201bd207fb87a089ad9f9095e0c5c5202c1acb6c256e387dcbacaa8dc2b87e3b24247ad0a82ae4d7e7d115757865261fe4b82fd527634066d255a93824bb0d82d390e56dca0df6e7f75d04f262b775df2070cc3b597c907f978b0cc01b4867840d27c5ec5bb05b2d2bd255909851114a8d56589b40a8e7ffb1d951f0b0a31f3d1db1379c7051209e4975340cf0bf89a20197f25f6e75ca1a9f40a22e3dfa945cb4c3b08a04c119656dfc389921353c0d087d9b85ec1ec513d2fbc23a7a056738b3a488dd07a9b008a400f0dfd6577da220da51347b31e539633e1d1c0faf8ba66c00c231261f62707f6b5b581c47697ae8e6ee47e14426356a10019e7fd4c6a33e0c2f466e77b63ad9f71d1a22a3445e7afb9d2c3b5cf0c30f7782016fe0be68a1fe0314f0d1be0a6e73e32ade565e3031fa59e081f20fdf7558f60ff943c8d5be06efc6bfd0bc84d5b6ff3c9f02b52eaa886c6404dea3125d1768ae98d42201f4f1a0a505c71e417d8587dd927c371ff93b8018d708d5f42ca552d091beb88d66c46a6e51670432b00d569ccfe4f9aae35ec0c5ba2c96162e54a455e110865a2578decea2a2a71cbfd12dc0e1390ae5eaa88dd8f706a9911ab75df87b47257c658fad57d4f9cc8d667b3d200a0d543854a57388fb20d0f607dfa0dd789c444d2ba5e693ddad36f96700a577e729ae1c4deb50bbb63eb0af0ea3ec81b76ec07e4425d4aabd366daccd048cdf7698e7910346fd79af8a58e82e3f50233f0271dd2627bac436a0874e36a1d438f3bd4fdd5bdd7e24d82f13e4acc1d4a62091fa0809293b3ba17349f99499eec04cd47d027069fe7d545c27e4d33d6e504fc268f196ae4b49920b3f606d9e0ed3375593ec2f7f34dae86938722ead2a795127f4321ecd8df4b31ccec7c2fb33136e42a9f1597e54c78d38cea120b770d68d2c3781b6fb782ba71de5f6bbd46f7ea07def80d6bdee9d078ec6250aa9def8b6c97288863b50ea3d4fc20a13d3d1c334297278e26d27c7f40ff80f9d728e578ee4ddf8b0b2090c91aecf84ae7e4735a227add085445ecb4f2d969db846d5e94fbae378e80381c6161697030b9caf7c4662e2fb3c8f26c6ccb946cc04c2c8a7994e585272df923b8035ecd7edc05fadf73b0376c3654735fb317acdd9672f17326739c644c17252da09470d3e61eff100835631201ab601a55602b98b46915e80a40c8b1819186f3970d2274675b5029b577e5ec754c0df5994645012c528f14830bc3a861b878dfae36386733a80c18c6db708200ab17ea810ce021b01336af88c841f04b8f93c903f8572d0b1fcb9c16c20b914b0f2e96903d0192517d859b33af59e3fc6445566cf30a93bb0ab06d2e2cfc2d3fbee796b5334f2d8d08ec8863b283da5553051f30d70d4e0533667e64b982461c62a1e1d74a09113d164786f5f2e482e498b6aa852454badf31751cd3f794d2ca9a009eb5fed4d29ea3a4ae9bff6abb251cd170f3da4222a8ef5950fcfba88b547d9d9b124f45dfd6c097e03345ed0bc5aad453a6e513e7985683383c795504b3e270a8c28586caffaad4be4abca948eda3b082010ce5ca8c5c4a927b5a31812d22adf59902ba8d61f1ad8c6a3a91269aa6652c3e2b6af77b149b4f562c682d269218badab713f598233badc0a521d9c180cd6437c7d3925e526d854d322526a33ff22609ddc144c7a2f49d505f5d95a6587c67cd9cdea10b7ac01f3d4212183023fef477deac5312bb583ae9ef13bbd370cfe193d4ce7e70932ccb997c261de37037c7e78531b7bd4574e8062e8125ab1e592b8573dd47ea0c0dea84cbef9a33d026208f399b0c23236e22c716a3db372cf4aa7b574fd07c2b592fd95da696d7a44abcaadab9f15226ccb14ba20beb84d7fa0cb78fc33447b889e6adfae2e84671939e5b52887dc8ed86280e8eb748d63e367297d1f24875d3fc8211e4bedcd357dfe42647df79ad3831af6bdb92cfbf53f74b802d9703e2a72dcb1946bd21d6cf45632fafcd8daf69058800782693f9ccde33a98fe6a3d850f75a853eec30145ddd9d09aeb85c2adfec1f2a371117550eb423344f1e539f42b470cdcd850b4a6ef7d05a7be13714adc2b2d99506856ed57ea956c255de2e89967ce5a368623c99e21c60b56180114f998323b60a963d5184fa78867a68d344686fe68152770f9c525a529f1fd8b0084908d202f593fb972612eaafbd75935b4ed931a71fcfcbd449cffbdf97c149239b40a41b59b1034e3e7072388dfbf5c4657ef528fcf81a497ec66035275f61bf86b0b4b8169a708bd520d3eb365df6b0251051b49ee3a697ac22726664801bb522a01400ca655136cb4da316040cecacf1ab44a66c37fe9fb2228a8a4ff779aab956f34ca211d4b117183b06170663073c5874871deeeb10759e6bf05ace9867a56241e4e5cc1dbfc112ff6694c8fdb9e76ad73ebfda95a2ec835d6e95f9af948e1007cd900bc292e094efba144e54e174631535c24a78b9fea3c7ce6f46427bb01e52abbc1964c5c236e7394866114fd2969f59d05a07beb52647aaeaab055752a92bfd30886ac98155687a75108612f93bb16e893b7d01ffe185057ac5acd19e7013badbe8841de4307fc4996c11e5ed32f1a6d27d9d601e430a8ce3e9ffa6933358796ea6c9a26ef32dfa159f8aee31ce51101c962e7bdd1cfc529496ceae665613c35e4996ef75f21746e4e78db07b3734395ce09425851d964bbafbf14910bf61ade6f9203a3aa418505239293871134ea19fcc019f7e9cb8cb4e0358aca9b3d880b7e063c1c824ca34fc4c45a017748b71217c9634e71ec6628c0e4e98c44be84bc394093b903175c777c6bfb2eb18d1466dcb76eb80c73a1c836b544fa7a431bef6db312ba5a53a194b2b7f363d064a719a627b33064d93c6e6e18bb1187559b2364ae1bc75de5af4989e786710e2441a4f6a49aedc0028756c5da223704e1626f02a9bb3381ead31443ebeedd7d7879e8125fcc204f2c9114efe881c29e3307b422f8620d007ba5361a9705a9ee7af5814585a940162dd7833f522866d286bab9e752dce74c70b244a335c29bce7ad7bf2d770488f9bcaf94c0be4a84022d2a59a3916ea66c552a7eecd8731ebcc064b217323c3c5e89a9c1cd233e2cb0b38ec27680ad6c9132fa249db6ada6cc47f86cf44ea31605b3dab3350d113ef1835212b3899a6a81b51214838ffbf5f5346b6876fdd4a4d2ce05441ccd6e8f09e1fa05e7d3061c83031e263c72066cbb62a599bfcbed9a8a6527a11ba48f7f46bda550ad012ccaa284c2ac54bde48a827d2adf2d1dd7f51ca47adada8308f962e4b26c900ffb5282dc5d403149888b8aca228d89aee757747d83ff1e111e0f23c4213732922b87c8d79131dc7b822490376b6b948d1ab46167f850357f411b25ba2ad49b2cded93c222151519fe1be40c755739241f16b36be4198ecb78249339b1ca6bb8f3f70451794718b608ad14af77c7e1cb5ed991252bd14dbbd0c79dea90f771cbae322640fa17bb3ed30a67b19a31268e0b1b5707f9323dad7a3a187e65fdf83db5f01beac5ad29d4f5605ab81050119e66729b241c07a7b58bd803472de1247e123b70e56eb5da9268cd408013a267b53b5f8dca72346822857c18ddb128445bf8f2a6729c581d79307607b555b66855c90c954e2e1729c3bbd6c9927d4ba9cab1e7568c556d22a264291e13987481f19856c6e4f53bed5be85c35428194d710790e560f66b3e6803737c33764d0a607d25df6f5d7b2b21ec7db7e169854dc5b93e7d17286522075e112db91adc865521d54904e13418933517c7cfd7c7529c82f92a24749dc2177569f4fba755d42727083277461b0873bc16b69fd8b0d34eefeb7071ef07c6d83ba96f7d72b85298c66fff16d7c7cdf0b372f6b0c36cad352e12c9da5066128eba4a33b28c93c39de5bc101a1abaf616bcbca13479986ef9303c5adc3533f715e3cb5bfcd7cbd79fda2254d0437742ca533ba0d507ed33da77751fae8c51c2e251dbc63a04dfe33fa323bf12c6ecc37d54dffac979c798b7aa77d4fa5ff11b55626a9b9272eb5aaa0d1b23f91ecb4b114c88e009a5a47c4992d52361250fcd17523c7ab429f22af633ce58b35265d918c61480c89c0803b2904d79c416b8c8902568edeea4b4252ae4a81a11b9d706d5ae313f7fb82b140f36e0c5ccf401b672074f34ac04bdf43dfbc0535717574d65266deb02ed27e29aeee8bec97cfe7b8b27dffb001bc246e844fa2a8e0eb77ee8d261c3f1596e0e65bef6c20823f27f83917e2a94c42ae487b76229dd004d07d844de344330b4bff3a1a4c03c8c0a2cf1bfb316bc69cb05a5e0a3ae2fd59f21b4f40531c2fd73b094e26599bc94cab622f3a2ea9019c3c5c19d8c4a4566b393a2f7e8856f0adc213dfe00393d1371e42334b84783901e339ae2e363d6d14db6e835f8cd7bb33974bf9ef0951ba47c8d74f289f83cbbad9a6c23b14293aaecb6396ac28c0f0e617f9f9d24659019de95bc66012797381d08654255b0404e8d5605df46cf9f81f3d3f3267335b9e98d2d2b94fe2136718101d51d033ddb897f33d756cb2cf8dedab7ee2a42d3b2fac2962b137d093ad6e9667718ba6481f56f35ef1094f92b7e489f3e9d1786171863c0c6775a8fb0d64cac9a51a788c81d14098ae9fb24d038bc046571d009222ec81b2f191d55a89de64080a70d67472fce51f39867f62d0a1ccff5da44df8f9a96cd02a9f18322f700a4a6317822174c6207723bb68d99964f0ce16d5c4426042516bf1a658c52e45fb482273871582e22e47ba1a610c8245d4d2f10947dafa3dee74422cba77b63f4e15e3020dc0251c549925b71a4969d4b4057a3cd67be5afc4040b74066bff9b7f0addd0fadf8670cb7b642ac3d2795aa70dba1dd8eb4a09aafc9f6690c9a688bb90eee613bdfa1d551096682ba47bc62227e9035015b66034a6f260cb10f63bfa0f50d22c4d7afea02e8f44a9d27b04fb2212f38db8352b1a3c41812891d7b507542b89810bd1268532a89f379b6da4df4d57e8ea24bb3d81e32f41567a93580db01c7ce9509c9571ba06edf5dd703ec7bc528f6e5b1ba58fb7267a150a7bcebaf443b65938108bb18b6931d2eb9cb54ce8fa7566120df149edd8944c33205897ef7794597a253d3d7febe5d04d777a2c56ebf6d897bf2077aa059d4b3ef032ceff63c60b3e0b39be0ffe41e816d2640d5f2a5e1956562f37dec3828af2e4d41eecadb3854913014631a7b1fcc183b6a71c5f45872500bf61077732cc75faf6b25a0077b9df7780343ca94455a3bc79e91c35baa5fefb00255c3c4b5ed8aa4ca63820039b9388b31f12843a148994acd0469062a4551bd5787485b82771fc8e32d46aededf9a7d1a99c24e6dad07db12e634391da74ff47678f710649eeff440640f63bf9bc9cd757c499190e61c85bc1f9f76db19869adedcf9ffa8639d6a1142d7d8339e216673be47e09975c108d4d5c4d04801cea28c5d69df2c68f796a150364304ef254ce7d601fa02f76e89c8412f64a5ad1cbec1a5e94b978b082e7d1380f41abe4a57bf8b7f8f4c90b98cf7fe246e2a9bf1d611819e553965e2b37251a324e7c7dfbdc87f37d1020c6c7fccc53286a318f191cc55d4f0bb96200d49f9e06987eb313490862f3c25b3e8471b79fa789f16e9ffd7bf48a46089ba1185a39bc09253ae75febdc78778e939835d1c98f11e769de9611c561384aa349595be60066fc9bdb3efc246bffdecd0e9ead588fb56bafd919647ae36f198ba98e7e730c1618fd139d35960901903747f6a036131b9861ee568cd942a6ad0558ce5a304cf71b1dee1522ae945616418b3f13df65ffc5213583ca2bdfbe92bab29e44f55fbff0fba7246dab9bf9bb3f90b2d4ee68d52631899d75c1c923fadace91ac5ac38384bfaea72528c13f67d3fc76c5cbc1331a4ee3af15b0f62a989816f5e4821a21699f0c1281946c4e30d1884a06f4120ca449296722e9e5b218d50861d490579c25a106e9262418d0d67a070b2314373eaceaff9992fefdbead46f26b22d5bbb22dfb67929b345a618c1c236076b9bbeb247a1e9d53732ca196989ed267316d017e4d1c6aeeb7750d5ae72c59158761f85b3f84697ce1f90dc53ed63f4f6b38137269ee01903e8035ad09fd79530251a2cae0078e20ecb14dc5a5c73e050a94a4c89dd229856a8bf750a646a09f99cbe2f62105a9d4fcf0590c7d60c87afee850a80b940e2a92ac1276fac2857093c5f99b80c942b72b4d10ec8c28c6d0415d1f6e672746aab7e36ef817e08303b59731a9ad8844ea5458907ac7dbedd5ef9419335a41c45013392dfefc2cc093a932f71725d2506c5fdf77e6438e3525a631e81fcd667e9053047197e9906b413ef57d27c786ea75415113c3bf40538d86ad233748fdf65e6ad970925c9661c796e40e9d86a343522511b7879aadbb19e7329d979f6b071c8249ffc59e3069b7bed2569a04f919c8b65ce8fc16bea035ad09dca37b0932d7728ba5da0d726f334007798d208e14627b218e0ab33bd2ad5917df9873b0d27de4ba083a7ac8a16e22fbe46f1b6fffa8f1267e59f8821789a4ca870ca4881f565d7a8421529ceb4245908437bd46efd5a7449dabd725b87c8216dbe950d7b3681bb66d939404a5d26bdd39f8f56a5160fe2bb6787c63e8bec78acf65485d489bb3077c3ab703bb0a7f197242cf8d373266196f1626b5f95a330d594f18f47ccb044b40ad308ca4f6bf822b9f680026b574086219d903812556dbb268c1dda6859e6ee6ebcd6617f9ef6fcfe61c9c184b92f2067256ddca8f12d6845f8b0363ddc52d9c1a18208001db50436250557bb86ee04da7539b85553bd418d9c6ec7ba41cf6799adf6171dff0301c1e388b77c61ad821aa35f7ed9a25d92fa641a14ebc0f650b9f040ab625e47c45d2635be778134e6545dd02394451b67f2933893fb1e283770fcb2228946b42d5316fd1f5d6e2e19d843dbcd5b18b7dfb7bd71daa8268c9ce2a817e7affd30350087d59833f1e92e81f038868f0a1edeb0a8bce21a1c8ef5f86bc7914f4663789b6e70cf36c73ab6e271c5d990af23480a9fa252a290fd39cfc287d7c12045ee168d7ce9f29c099c3ed9c17e00c49924d887948cc837da4ab5c62dcb4c150a6b3c6e37ab8220fa9498afa19d429893164f81ef2def745d4948a24b6376bb1f7176d926db11401c1c001fa0ff64e0720fc546f4a4205e492804f02fb257be12e9121fac62497f573616485f49623b56ec5df8e3a01ec413c03fb11d4484ad27d4f21943f7418d6c70a236df22a726833941436f47cc67520008e895fb4e174dd4f56eebaad332f1097c762a1655f0e18a4d648f923e237ac7d827c4cca5b9558d61903bd27145faa7483a1b5631784fd2c895ae6ce073d6135947be95b725971443a0fe7d784a3dce7d253eb9fea3a2ce005bf50ea1bef7a3ee7480209a7a39d452d3f0bf126f81a96a6944c15e34d24a59771eac153b2cdee83a38b122ea17e6ef638a7e25dbb9a3f4191a310391a76e722cbf22dc432b3836d50c363be836c4ab6d312784d0fd6ebac37add46a5dda909c60473418f4fd67e7cd3460720fe1e85e79ec70706f444030b55084f5159257c6f2abe935ffabcde5d5640b2a0b6113a3df1ba038f985d95e9617d77cc81f8756638bd5441265a074f2475919b5af205b456addfe3ede90342f0fb4d5c488cab28585409bb37257630e561030aa7c51f4358796a347442c1557eb90e3a952a1bf1300e5ddbec47b8ae17d356bc0eaf652ffe9706cfcfc1028c183d524c9a7a6e073a6ad2c1257a57d673b34458f52b9a9a39eb734ec7e29c1c70242125cf479d4c09f3befcec2060d9f470f5b365d7c3b84a8961165dd120f354f1d5f87011b04f67b9b536938883ac2d3dcc0bee5ac2a04dd75eab3eb1a0f0683289242a3e103b0aba3052282cd986ed4262a3663e4f7a46d5c7a946d57b0428b947aa119da04d955ea0897f3e437e02ba24f7f362c0f1655dcb1566f4853de17951977f1e7bb09a992ccca2fb35b6023bda55a18f686330fc38ef15063eb671ca1e88b00e359eb9fb4e49572eb6d3cd9fdea030206313344e15126c81c28f5a29c9f546633280aea0b67f9974e00609f6171f7079b9fbdb7bf872dcebbdda6ae0dec2d122823d9730a4864a36776951c3882"); + assertTrue(Hex.toHexString(s), Arrays.areEqual(expected, s)); + + sig = Signature.getInstance("HASH-SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.setParameter(new ContextParameterSpec(Strings.toByteArray("Hello, world!"))); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + // TODO + /* + public void testSphincsDeterministicSigSHA2() + throws Exception + { + SecureRandom random = new FixedSecureRandom(Hex.decode("7C9935A0B07694AA0C6D10E4DB6B1ADD2FD81A25CCB148032DCD739936737F2DB505D7CFAD1B497499323C8686325E4711E95F8A383854BA16A5DD3E25FF71D3" + + "061550234D158C5EC95595FE04EF7A25767F2E24CC2BC479D09D86DC9ABCFDE7056A8C266F9EF97ED08541DBD2E1FFA1")); + byte[] msg = Hex.decode("D81C4D8D734FCBFBEADE3D3F8A039FAA2A2C9957E835AD55B22E75BF57BB556AC8"); + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_sha2_128f, random); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + byte[] expected = Hex.decode("e8a1883716841afecbd6f9bd8648bbf86ab3badcb227b624633d51913eb337e07b68834818c993532f90581ff8e26477449fc5f0fb37c9d8462bee7d3f5825316afbd4c9a2a266d71d7f8ba4db064c665e02e7aa0d1ba9bac5d0ac0934db69fa09fc85234a701887cfc0af912c7b5d3186c0489e593fff2e9b5c79a0a77ac312aac4049d29ad57db8e86cec1c1264e819c5083bd03b4ac44b94be97756e2e4b491947a2103b371c1b54940bba71cbb7f9bbcc8eb90dac25795d1148fdbdc3cacef7945bf9744c966cb73cde15b98721440d2fce6294e77c39bb2cc37738bb2c2ec45a8d64a7fdda31c2a5f38e9cf17afe942470f1227e05b907ada0564ff9cc0e1154b1459f4a4b21485d901582c2cabd443635262c6a899e774e27d7428d980c77e2d42c15bf9f45b702462dce170042b696598fa8a850beed7517f717cb48fc98c8634296e3b8572284717fa5248eaca46c8b20670c31347b919d6569d351e4ba30595a5adbf887c8e971aed2dcceb4593ad18db1e5f9226ae82366e5c99c44e22ea292912d00aa6c53670bf6ed0e969c56a95015b8c5e0641885b4ceaf45bd2d90d5b93f5b0f63a8798a572935e2300319aa40e6435441b611149750638e3894e66e7c3ffc6a4f1cb37456a7c82b05e2b6d16f8365f05391f25539b835159ba9b775e85abda82d16d6b7b626f76bd2e98cb31b82ba8f18f0309c41677c2b4f5e822f255dffe17d21e7ecd421cecdb7e6a3f88e4d76fa0eeb3d7e9677c0c983223d029a025a147399ce72a13572edb7d2689b361993a06492df19fc5391a1e6e89d4d81cb5c3eaf1396941f9a51b8897cdf725ae8669f2b4b9435277ba13899a8f1805b77fddf5bd6b2d6dddf02a185d10f3196c571ab246bb8e3e1fc97b0b0b4e1c3e2186f6839b615c210613c4c3c7fd922d1907fedf6631bf3d1ca99914ad5c9fd34ca51ae4093e2a925c6a967b2c2e8c97fdf73d8dc3c6fb36ae587e50e0b31455f618811162c30ecbe1e2528d325a8c75afb13cceff548863c535bb6f72779fc150b74d33b4f98f7dca144fa554318cf48863fdaf16c73ab14e5c00580ff227803b1c8c383713bffb6144ae7b02f0cc1113fe2f57b72b93edc1e0c363ad4745e5a96bc61b2ebfe5fe1fe6008e734fa9382c0b818834e22611433ca213cf090c5af84a318cdfd038d8cf6936479d5b35dacc30be7b92e13920c0f80e5a6365ffa3b0c35ee637a4e861817b10b6c6b8f6532124c45289ddd027365e86e76b57ac42b6c15abff1b0426d1456299f9585b16aa0301d333837e751db28c0e3ef942d577655b70219353954384b649dbb4cfd8754d80250fe9ed859ab8d51e6c663ab32bc6c5972620214f3e08b3275829e1e97a19e2795ee39a43e56c1adab144951ef5b1cc1512eb250625d7bc18165a20e588f03075a524c0cac05c5da810632680e05516815c5b32262eb5b3b54851477edd61ce14d3238c3d02f4518d809887a49d148e84cdf7e50e0c06d82b41e152a5151a576c69fbc812c327d440b41edb75c02ab444ebc7da11143e440cfbda9c6c7916264b95692029e4c1bcbe56c55bcb2af6530131147de4a1b384b46179bce044dc104a3131ade59e4a1556e665d6ae0ba1bfcb433215d6b9d5be7b023045b0b49490685808b1a545577abc9abfd069aacd33863c2f5d0daf41b4c5af5224803f248356ca7c1269315c1bc4cf8256cda2e1dd2b1f227b7032ac29acf80732120ea3f9aa07945b602810e8aeafccea49d32e5050f248f72f3fc839962ae0e1443b46b586fbb48a2aae82cca180d580312f918ed208a2b6a493cd63b881a75e321a5622bf47314877bcdc9474019b5c64152e003d857b9eac87b3ea6c8f378592078326a4cb16d66caae17694b306ec4965f85a064175763ac9d4b457be3609188ccbeea07087f5051c66b5ca51fd88fb91a1dcc3f93ebb7840645283595fd3c4148bd62e8dcf0c5da4b89492222106228717ec8b473f7505defcf6da41c8e31965c76a067604da9f031f0b34235d7ef587748ba03cac0f104ebd1d29a44e0ac96c85359550a115aed8a8f15536032b6fbf4ac8239eb94391b2f66d7f001114457a938e5877f0eae1ad36ff6a853d96ebd8d5e44391e83a940fe538dfe2caaebcf7b6110cf4e51617f3619480c3396d7c9d2af597e113acdd794cf81de24a21285f4ca9bf56df99e02587bf89674e7db2a1a06cbc217940fda6248befcb93a3f947234e59ab6b03333932c015dba3c88092f362d0baac5c5b9f2d9d5a829dd3ad4644e0cde89d4d8df4d547187d66179f7b350112c4c004e6afc97fc97793530be06c13737386ba92b13cce0c0b6cb6b0aa0d82000d674d1998f05b271643ba85f7da6304dbb6f530d2c80c40c3e2f925b87d32603e377b3a9ac486e0f0186c191f4648fbb8e230f192185498e3e09e82d321a9a6058c553419e21c3ddbf147c2ed88f99398a7eba4db3a7ea39b45693285c4d6d6c8a1eb8e7bc0ed937838afd59d003d69623f6cc6740f2a7b1808073fc7638960d649256026d9b714d903719ac7959405eed2a22e4a9d72e33ab6f0aa5d07be4783b4ddf36af1b4d4c78585cfce80738b9c1225660f5e16d9de5c9ac285d24db80c9680525d419b626435fafebbb683c9b36bdc1cfc185cfe87b6ae93a14e3d63db6688f300154f288484c07c97d82f438fb9281afe6254170ea6d8037108d8984e88872f1c9072eaa46ed6ba426282ddf6365f010323e176e11309a3d80be22f8aba5cf93dbff8658665a9d2e3b428e05218d9da73aa0324f9500732920cb278bce651e21816c61376d1cf6d2899f02423b33be6a8217c217dc42b1f97abf8f63ebfc367b4fbf0f158a32cb2aac06616446a9773f6501692cbbab803074b5c026cb3b8ab7f48d6e5818e668198cc958b8acfd6469e8b835aca0e5bfa5a8f301ffdea73c8693f6c656cfa411e7efab0842da13aa7132db26176c792fd1a99c79551ab99482be3674bd2e37fcd8e0701f2a9cc801b56e717c8186cae04287fc741296e97c5563c4b64e7d36b76cfb41ff3ef32c5c88a4dc09ff91a215d157fcae725f7da8801e72086e3f063529eac6a11d4845c1eb0bd5845801cf9cc35deb27d7bdbb67055f641b9f4bfaacc0af6124853cee6cc3a858c1b102fde6da1d245390d6a6db8492b1142fc09b90d8c985ddd2a82e9e79355a070eccdcf125ba45a2543d473cab41cd9ec464b77fd57c54dd5b346f954b1c2acd37841f29f9b7dfa767fd029bddfbd0cd3aa285540a3943c6d1018f4cf87fd7c17fbbc65016d5668d2b90e01f3176218160ef5241caaf3bbd747c81da560d1debe3dc258197740839f93ca6eb41e7e635340e9de07aac1b24c5f48182d0bdee3672097d2ae48960224038c8fd710845d0927f647dbe09062c586842d31e1018950a3e16ea5d209402367badae58d2344d169cdc05f5a47f86903d18902ef3bed7d3deea961bc2e8e7019d77005ff88be637ed0977354b26ca98a7c0dd436af45341626540e050d7f4f03b703f254e32bd9a3d2f93997052732773c2274cd1a26da956105c5fa59dbfb002efbc28d3cca08f91f0fa76289a1f68decc6f943cad337f710e26e8287ced6a35b3c4a5b2598162fe2412cc2d44b49948f383403c23ec22c585e95f91063202da0755205bb592fbd345e10bf1b545187a7c14aa88106bfc37bc05dafa17f0e2bb8edc2179b3093bb1cd955beb621d2e222b39af3cc1ed26c7067012b4fdea539c983e1481b70dea56506a3ad912257cd7cd58da4cacfd4370a0dd292c319f23ee3ead9695bfe91c7e83bd846bc186b1703061a9d4a69eb961ba06415d4dfaf2cfe839337a6efa0e6b4f4a23c700f678e517a64e8a0c1eb28c6044440f203d9eac89c8b7d406a076bcabdce36195119001022e640155df8ef46241ea50204df095b96deeb70c2306cea56794e9729b3fe27e114a95344ad4d033175decb92e0ac3a88a16e5ba32f8c94853764fc7aeb16591cd3cdeb84b24ef6827a341355e7efe0ef360991a20e6ae77a04d66bee1da160f14ceeadabb7844e3baec99a057202d80f41c01c6f59d6affe7497b137f93e377e3b9f6df995df70480098c46a85e5b9d9b3fb7d4b7c6f4c72e1ea8fc442f92d4d74b41ce026aa5ecfac54ca2b4f45995799330082e0b558f18c5e31e698c67f2e82dca0ed3540f8493f8176b9163633481d4a444ce792b1b5b7c1f390853aad64979678de457086d7b7a0c0230ee0d0c269322812d5e7dc8e6e1e03dc0c977e81a6ac37b328af654ab070c6b073e3d0194046e9e91898e8459b90faba6e0c5a14a764d919db650c798aaf27ef1ef87a62b3b5d0b69a5abd7ea8e12e19a74754deadbcd82867ee271340c0687e7091091585e1163da7ac9655c91a62da7850478d2283fb6946306834f2e56025d863044b564818de7b43a7d895bc3b260f4d8c55fdcb09d8d01d11631e7409e3dffa027be768340e5a1a71c518396906b1ae32b44b08f6c0b54ca53c7e73375713656815e503a799205ef9b6753d177794c753ec2a067421a13272d09131fe37d212c19790d707c327146823e7442b56bca450f3de89888637e0dc249c2e42c6d6d47a6a49a27dad3aa5b543a0130d7d34f6310bbf8aca6e514be50e2cadc80a7133545d56bfe06a017191e5dd5ed598ba52bee9752896c65fcd4bcb9de79f7a89d781dd47601df7445e23104f2d7f9341d6c1e833247b1f5b56721255d2616e6edf75aee159735f15a70a170dcced4f0d029800b6462fe50379eec7119530650b4606ddd7721e568e52a934ea14565168c45cc0b4e540149badcdc1f70e3079f2adfc8ffa44333c88c5e875e64377780a23573a6f009d8f8d8bd3a2ec814f9a5636f19dedd93b0ab1f70a4b6666520d7b060925c95c2725ee065f52fd09b2f3b2b89201de0174ec755680cbba3e5828298a054bcdefa112aa739c554f847069ec6f4bc30c099c67eb930a68d20a01e5c68d12b9f1b1f3c557fc9ddbe6083aaa884880c95721c85ab22cbb5980bba49c708edeac69a95f7e0e70c9a75fe011411a1ee730f2f6699ae74708608ce6f33435efa0b31379f6c8bc2494dbe7145eb70f6d4d46f8d7827071c49d55c487f9fbfe1a56a7db761cf3d314205a18866b872aa8b9f4b68a930dca64e8fc294b6d59eefe25cfc1008689c78a1e90bca877ce9f46aa05f81e66a415092ef9bafff8d4732b12976b925bd83439e547e3df349eaac385d674bb2672e23290e5db0784ebabb24bed7831e9965c2db3dc8db4ca4c3525b3b132439fd0de7fd1480e2e697c2165e1a27b646898c1af610276c6f58fbc84104a345783be38749ae3f968c980e368b6c7943fcd5a3fdff44f4a44ee55cfd7f94d0eac235dad9296e979f32d5ee4fd624aaca794bf5cc30584e505382b852b880f6aff7da68d4c7970dab6d5510036bb453a7462d7cef59fa78d03de0ba69b266685dc2f17ce8e8a6c23e465175b352c977eacd5fc611d55a03dbb46a831e5016ea28329373d40cba6414193641f75e27a5099676670634008678c3b5d1f14e688a1196b08e4dd855611e56fb74146876ee12b6d7992dc34bfaf68462322e0f169e61b127c00b9c8817cdb59bc675387f671e913d64662128134932a50d8cb6f49a13646fcb10e2c3f1c8c517c5296d1285660549d1bc0ade7c03354749ea811002a9cf526100e264a6f9506c563211e56a811d8ee8eb8e2e917512d9bd38c0c1f51c6968cdb10b9d526d19f4762636bfd9353f904cee43d28b31f6a65266f46e0af9e7882aeed238450a985b493bcaceaf8eef545c93eb6b7a264dc278fd621c338f7dceddd29f68c20625619374410db7d45563e2d90341c475a5df5a5f8dccf3c648072e205adba8327eb36b9d2f0e7dc5ae59933063ef105538974bd47f11379566342c07461f6fce54bd2ddae8004824e93eb63cbe950663d88c31b9cf20e4abfdc1892405b4879cb32ce9c6eee7f93da5e7955d4c04b04cd13bb4ff3f13ee1ced444b80c92bd18d8c122f43020bb423a15142932bf522d9df402a29087bca975a852865ae27a9989a5921ad4345cb4a64f7e9f6aedb0217604a11b3eab8b4adaf2b9f527fc108b3a6d94bf6d0ecc63a237a70489041d1d499316396d67b5b8c73f6e6b91d0a6af32914fbfd860087ef4d14ca4553cea4781cb9b075e47a9fac71c38779892c87a21ebd942a596be33fa3f8473e869d99213782866fe8ad4a79d4d2dcee9abdd53de125a179af9bda9a8b8fa9092ea6ef17b6260da9099ffb1cda671fcc364ad5e40bb4028115be8833c9c6ee381e64c20d1ef056cb5132a04dbebadf2e62f8c545808f685f8f08e817558f27ac120970d6fb1250ae469d33f181ce62aa6a150fec671bc669427151da2e8de1f010c572a000172ca2a140ffd253a48c612c413eac55e9087817b42a468e929e116f4e33a63df26934e2478e806a583493c985f75c4edac0280317bfdb572f1ae1452aa26f3076e7e48fc91a253d689dfa76bb46b199abbfd6c5533da987747dbe90a4c9a8ca664661d8f09df9a2b6648e2b7185f459084f35a3d56f773da2bfc70b1d7ab0ddea709362afb0435c6e6f6a58d0cc42da9a884d76123b6df031accef92a77b67a906abe90abd54ffd358bd9aa977f926a71bc46a5d9b13ee0e4b761771ca5538601cbc7204463f3bc3821e06738acd83cbaf7571abbf032e9607ab7be96baee4ba563932f172ddee5d6adfa4c01b21439e8fa80101847ae4cf5ba289d46fd65545a45fb7f4186e02cf9a0aa2841bacd3c463d6f23ac88514c9039987671fdb263621b4ce663c7838dea4568905a5f1fa3ee4d82f222579ce278e145785c5403bcb37825d3f787ed3f4a657c7d06a77c31afdd33f4042d6baffa3898da308a9a2f367203bf5e6afa82a6d5c428cd8b8bfbf98a505cdd24282867d89d7dcc7ff7f56cfbfe6ed07ebb3fa36ce68ff1cbd2141a656a7e62ddd90e5fe72308c5a2a3a5f198bed49e4b7d373ae4920ea0ba52b3c9d8bd9fa45a655bbad9ebfc64f06a759a79d97f0693f73d25700a7aa7dad283b88c9d62d07951642561911f11e1c7bd760c9a021cbab298b0bddbccf828a2d203a10e36b7dc7d5f40df67c226a9a423f8e42a62a3e91b3ce9524e0bf9d2d18e07e1d0fcfb8c67693168871de6b5e683c0dcf46e95ce63b5887d2538f76078121a5cf124f2f0c06226387fe22be207b8b966b59f12a702bfbd6b00ba9b6d9ce2beec702e262af32ecdbf54811850c51ce03544087d7b0a292a87e0ae406e772bcfb02c84c513e05836ce62116a2e21920bd219d49d0d888156577204b6222e1b017a9bf5f6d57f43011ec2631a6323ee0238e89d0cb2b20b504c485f8a2a001e79d3ef7f56b71e8fd30add6013dddd984a2b5ceed885afd9b59bc639fb2dbc5903acb55bb2612e4bb7606f5431d864a12770f0cda1ab87a9323a40a8db68214aad3a00e3fcbf12d2327e33c658f629edb36355de41e91bc9ab3f4ae43dc43c7f457a28f51eb1e27a34db532a4a869242848dc23399572f4a02d07a52c58e8829d1c1a6e2cd123707240e1abf62f737ece64cfca027b31ff67d9dd567d4ca309f18a91d27a40fd2a4c1bb9297ac329222675d533d048d27909acd0d562589c137d6c0b4534ed1488eebc2e823eaecc1de95f120d2fa5292257c6c0e00b4352fe3da2880d08b7e4594770d2d0c8c5f2ffbc349b7555739226e5fc3c1f1e4effe5072f1fd8a6eb1bedfa334dfd7c6bed3580f5209773d7c1c133d26b758b7132436810f27f497b7470ea735fec626eb95b9d301ce012c8f61aa4db918c38baf9d52c67c0b2add59693bfed42a4e0263a7edcf473a481ee870260f3e8b22a42a820be4b65e797b801a86e2693a3d9364f687aff0a7177a6a3d35c535239585688255a2e378de152b88133be4a0524ad6ab72b539006e21f67cbe460ac56fb696174b87cff050b2c577b59c0c4b1677e5e325ea0b7d89d68a2438d9a2dcdfd898b05327bc8a8fb9c7df586c7659ed64de3032bce462832304726aa0f842cc12a4872172bbb364b5cb7e5d24eeb2d332d15bfafa591c9616363d945f14ff46c6b98ccbdc8e949a5647312fee2b8fdcf3ecbff2d7e259ef14d5beaa0cafdc81d8434afa394ca66769d230811330f7b1f68b6be89ac987a45904fc4e853134d5d3a6a140fb56a5e8decc3c37d98cfe3a9b43928f2e01efe9518a6bb7749dca1d7ae8089ee2e3861151c260c5a484e2f563c518bdffe45b2488cdd8e9e965aeab01bf894192b5987f1e96e18f75266e21e72c5a728ed2995a1605b33e8ecb21a9d56d25938730d6936c701a49a155eecb39075e4da05849c67dae2f2ad40962837ccd03743cc331e1b09dbba32ccffd77895201999664638a2b035fb346d2a65b3236253874cf6fd250666f68fa517328abf9014dc8545736eefbe2649140510f9e669b2e28bed80f2618898bd2eeffa0fb5e7f962f685d42a7f694255a33335842dd5f7f48969252a35edf0f8e6920ae85fd2836f89d358c3e451ef5c843c071230a2fe30ec1efac1e58fb506267a50043fe6b9b0aedaae9208520d7285bffa2857d0c7d276e9b7523a1c22b8889c5295b5a539387d6738b996964071e25841edee21f1884ef73fe4c1fafa393dbeb0a6bcb56598762c554ac650797c90fccf5973fca168c3a9ccf0570a791c80be4840039083318589138f566ed5a0222e4af8ff3a3569e4dd5914644208b2289e790f15e5b4c3daf9d4033b4e1c77c878fee8493e5b0f6f4a4ff5657922c0642a7fef854e5a1620af30d8804abc4315cffb8e271991353556fd2e957c235e028c2afbf0a2c35a998cfe3c87f1e9bf0da9bfa73a67e5a6f3ab73c9ffd554c82fe52b742a25587d43fe6675915f2e509a7f0c6566196f4c5aae24bd495579026328a85f668f685466fdf7f76a8becd25b2cbbac3efb8306b2691451414407ee41fa1471055a2ab02f5ec99b2c612d0d1cd16f1af866e773d6aec53ed2dda0fb6bb140b766c0b3a0f8e6012b7d67554e7c7a1876f51d0cffbee1fc1a11d46257bfca462c7a9c17a4f872476b9aebe991846fcd10c431beba46f02cb0376a632c4b6e8b10cae1eff3d96224886c1d885a8c46d9dc80e6a5edcde5d436b902cb0565be77baad995411199151f5ea61ac1d7ca5014fc2ebc01a8cb9d1e7662dd93f253eee23f474bf3a25285c4e992a0f77e7c707a412d50e5a04f49f1069a9b810f2ddc9ec9f468c389279b75bddc6beaeaacee970c768a05e1ca667a796cc4a5acf756401959738079b0578a61a80c1329ab59bdd2bc62fa98178b3acb2972d47539d7b97bdae13a81be76eac592537d096902a248eddcc8200030df3f9a2963ae7c8a3a86e83595940810a619b063d9bc6fc0cb75035e988acac64480f5a1a31a787855d8a83013919a793d4de679a6810208aae6835ba9aae843e6cde97ec57296398ec3c128891f3c7e44f3fe0c9779350f66f55ec3be94f9eed53dc6ebfbe53ed427cc44089a70100e605f554f9410bbbf77adbad858ce214f06ab334228b8f894fb7a9b2e3b4b53baa67fd4311fb910c424cdc486e6739cd432a711f570699a903c52a7071c2948a5c6c9d125abadccd242e24c2871e83d7c048dd2da6a476466a9ec31a35a652c06be1eaea5b6820e87f880d9b2faf5c2a7e60355e4a941e1b748fba735d0e75dfec06c6a9f2e57f12171ec9d6c69c0fbe3c6808324175ab324efaba125a22cecb55d7be793e6799d6a8c2a64774ecf894b09ee626146d46ee5b6875e74459751e16b62a4feabc675d887910cea345bdd470fca4229237d4ff79b7673a974bac5da0cd2f3df6ecd0c21ea039acb0cfc74472a7a97a2116d3250f183d0e427228a9602fe6d39497b02713c61e478b5c1dc68aa0d1e0294d7a5bd9bf4b8182d2cbaa1b9455c2cd2ee1120c83166d6f2dddf1311f40168fbad45b1c7afab59b95077540e64b638c159dda711a35e0bcfbcdc89f8ee8da56d7dfa2e23f39e8dfca2033783a3380c031deef512177f7128400ca8f49d8cdcac9ee38a5f86b8ff90664418509fee67e383bfbb478d7434ff7a6f50f6b4a279be9ab33b7270658f129e4f56526f32b38887eeeb13e2b068bca0914e730397ce5003d181f777b45744bc43fd05141178878e2f2705017b4616d23ea244d54aadc74c4d8ef3cbca173964a50521b13cf235c4348930f1c7d17552bf9f89c988f977ed6078fbda9f23d81e117404fac83961b7d23a91c7de2a5aeaeedc8ebaee2f0f76d9327e81a1f23fddc05cc577e4c0dbfed207bea589963c00c96ad79f2360d470e3304ad86d203e1c24738973b46bf04609f1f744dd1975c0c7f7f4e7a337bffbe7c9e83fba1c69c6e18287f3afa2d3996ffc1bd5193ce2b52444fdcdb0b19f701297d88d0fa29962cec5d2ef399feafe95db1f5e8c3c645ae63750de0406d519710dbeaaeef4139aa1b9687f4cf3ff77cf42acc00833bded8e853cfe5ffb8a369800b227fdeaaf6f54c182aa21d1398b29016cc7d468424beef0f5babde8ec7b1b7259b0fa178d98a5e2e2a6f100fc9b2dcc4ee5ea49b240bac283c9e4657eaee6a3f266b7f091d30e96666c14f1285a8671d02656a3e5583d4a4850da032e27bc13845a807b36a974593b1d232bc7742f3f20d1111781746deb4ea6ac95653a1acdf4f649bc060044d3224147133b44bd88fb13caebc41b36f7e48ec97b21e405ec941b270960837be1d49179664567d1ee2342cef5f9e4a559c7b27aa5aeb094a60845308aaa9c2afe5fd4cb808a44e4b6211111a69b40862e530247320863b7fd37fa77e69f05e05a8c43b51d3dbbaf3c715e5c348abfcfc5673f8c21a8126c762325ae3cffae51ffd43cee880f480006b7ef63e3a9ac33e6389466ef1a0b0e67e47537db6bf0f4950f735df6cd81ac960084df5f17d827ab400c074f8fc09bc5353bdd8cd17c6dec09842e7fdfe283f7f33133b33b704da89184ac05b9f98f0b64a5a437647107438cbacb161b6ec97814f56928e800ae519efd7129bfbcbcd4b305a9c703ec4c2b7fc685030e741f951e182da0e0297f99b28a1adec735e4a8b571e79035b78513b6ec12d815323fda7ed61353c52d490186450359c7fda3b45258bf276ee655cebb8bb23b20067bb914cfa50510832e93be450dfb9b7938d3e9888632938ba8d52760169055359373a558a7e2db3e3f7d31476c638a263c48b02f73131c737be93f29b9d9612b6d91434a26e6bce2b536a16d866985ad835a995781cb72680b8a5ab806da807bc77b9ab0f5cc39e845e2be7599db544dccf61c214b998469e8e7e568db4d171b66eddcecfcbc74535753a1b430c91c64e4ef97fbb70bc2468173d0362940a1379d90b358806eb49c2632398b2572b3d821cb12c0fc32c68106d6357b26ea2cce6c6fa8e1a17bda0fa64820c450752483cd066900f36ecbfc34b100799756296d7e46e48c5c48d38cdf333b98a8c7aa1adc2b02b58a0189f2cd046a18d1778192d98cd9510b40fb35350361fc4c3e917ac19c372f196e52c976c083ed500b4238f636fe21b9f3c362bd2556b16e45f67de52aa2e8f08d92bc19fd18a0030591df154df34ef121eac4ab0cba5b5fe8920c4c3f3a63a20f439ea9dcda4ec0d7601fe8849aff4f5d4d5552cab4c73b34d41543551fe1008032d101fe1d94ab4943256471f4bd06eff1f9593afab9fa8cd534d88258936cc593785464f4546b268f6adfd878911497d035a60a0e6c68b5884d76bb4898ad59c41160321b83d40a364cb427699c201ad78852a22eaaef3d5ceaf9de365018b271e16abf0ff5819345ed4764b70b88decf41c15dd243d81cc599a2fef2a3befb2949f2ab244fbcd412432ad3600eb5d92d116ba618f8730a477debcb3280d8b1dc04bed8b360ec7bb47b9cae89d25e702db37c5b583fd72c3f0c08a1495f75f15982a9931fca16b5b1ef1868c50a855116e6e0f49495ef82705f3a3c8d834d1725f0f0506060c2cc37e148f78f020fc701424fe46a5159e3a73dc834433d244568bbae114f475e5e60c13f47e9e14db1d21d451d2c5f39c39af0b60651d059a899af0181ba0b4c7fd5a7e1416adfb9f5381b24ce947b7d09a27a264acf7f0fa28d9db6f6f277d86e94ed96a4a53cbd3a7fe099d7177c2d6ec783314e08947f6811d60f069a1e65663b93f9aba00dd7de119c550181262340a88b316c191cff1c7b43d936a466c0226a5968c2e84ca61faf9a32cb3170fb8d105d25b3952395426d28531797154875af2cd089f7505dfa742c83a9fd15ea57427767df5db894e58f7e026eb4d126067eca69c7c2440d9e12486c63957013961c24359f94f5c1dc239bf532998ca339b3f0053961fa7b71c3c2a614d4b8a821b5e1a5544c4d079e71a43a7965c34e981a1c5460b25b6831979883e48f76c7ed34c844406cf5268936c01c3faf13a235b72444b9d7a701fa9a495231fcd8b8ed89ff2993e7a0241f8ff77e71badc7f0c471024a240f4824da0ace63db199ded2e6f3953c43cec3f5d60394f546eeac40331aa3f466af470311bff164fc90b00995228cda7e239b354a10269904304436ffc6f42c17e9b9ffe9a946c205fc0add8103e12e342b4542062ca0083c286a0be8ad469885fa7171c5526e2baa153c8cb43d33e9b1db7c635827ecd26041aa632829acbe53c38f63462e4d7a308f299efd555294be0894ecebd3a11d4242e1aef59cf77768197b77282aa0dd81d9085f87daf6bba680e40aa252629e2668d87eaf38be0e5399c95eccf3af5ef5b6b9d9da27251b8375343aba5406c6ae8f78d2311828bac89fad2291433cd2ee74ffb81fee1a3170ed32305ee77b1ecd22c7dc6b7b5b400d42917275058a2be78bcd1d79a661aee6ade1ce17fb1cbdbafbe2dffd3884dd87e14e36fd4a27a5c64d4f970541a75af417dadc969e6bb5f29415070e1078071472b5e043361e5747809bcb83af5cc5bb17b03ec564ed1349b563563233760c4553b0ce46a6adde8b4f1cbcf0cc33ccf6d8ec8551144992a0f530b012ec11e28de9a3564096637e590d549b8264c3aa1284270a9310496fea8d53024853bf30801c657fc2439f0446b3de62e556754805a5618eb99e3ff6acc52c898900a565139dc593c4b2a37fa9e212b646d9f4c7fbb204c2401ea0d838a806dc26c067a390f202bd3446cfda0a569c1cbd99be00c125ff13e330bf7b67f8e489c2191d73a74d3cdebf0bbc20ceb4c024bed7069d261cf7418fd07d305b03dec683dea3e3ad4f1ef8df8073f720be0761ba4c6473ae3e8344f76e7e7530258aae63b0b183b0d364ff7b53d35bb0182f8cb56bd550a5148737a1e7520cdfa5b11f0caa70390ad04d0e98664d47af518d6972fd4f803e5b395a68a3e08df1ae70e0aec356075f616c8a60502d45fdd6444ac5ed5d37d2f6083caf91fc5d9851e636ceb095169d44bb865387a60ff46a277ab2f9f6d8160f09d051bb581c3daafd79cc8d2d307335a7505573d2ef74d0f66ab4a432488c215b6b72faa1b672c5805f0e3265583947fea3f20e6b1f10b4dd717c0ce3088fafebc16d48ad74ee4cf5e059164700d3f50df68f2fb8d8b932918ec820c0de00eda4caf332a1139924cb9549c265339495fa248164c422fd6a31337a78320c8c31193101a9ef7202fe0ce9d30521ac08f0f71b3fe100625ff22cf651ee9494101ffa3b4e8c8c360bf03ce35a6c00e3a0a7f024f9757b4914cead8b17a52669fc31bb92efae1513aaa3c109916ea7c025298036cbc91c69b7a53d5774c1c28c9356e33caf4a5d6e9809bc11de2b3bb3f0d2573f8c28c8320b8a397ee9e384dbcad1d8a99d70cadc1c337d6c9c2207fed9f62963c46c866c79fdd4abaee40b62ab54b942dc2da4cd87dc404b742eaec64ccd087d2b60e06b1396765390f6f8c254bba3b0d5bc015100a67319fd198fb2850586b63d2d2b728d47aef097893178195064925954678bf2d7e5e31bc10ab8a315a0289c8152e7ce3051df782d81b7c49e4f171f1de5255b87d4801b0842318f60dda27545eb0c8797f77eec5a064d166da02f04faf7d809219fdb082abb41e0a59eb0c8eb4e7f2a260aebe453c59fb18794fe1bf21eb9eb330740081873e0d674f026d261f82b8262c2979a6c8b17a7cedc89a737f7a5a43e68f513a9c0cb084fb4723d230864186c8e465db6eff89efabc81c7b511453503847d69efcd625afee62118c8172fac335c0218adaa22e0b6b7a205e1cb0ec4dd27c769fd626eda9952cc2887c3e4e7c2586977e7145bd175ca45ad507a6ddfeffda0555ebe142cffc93ff70623f8fde34f24c6f9d654671bd784bb31fd0dc11da9bfe4577408527ec385d71ea1d3b739101083594e4e63f4156eb6c37541555344073f25e39cdc7a39c5a659f560c9ceab686cfea58fb62a1fa4c7aa3a35d91d4ff284706054615d0782bbb6dfb3b07a5fc80df69f1292556f2ff044d1728be0a4604118386c199a19d467bcf118b5b07b4a52181c73d6bda19f8952683c56b61fcf096067f00e47cd106626aa6e3806a80ceeb33acdd8ae7390252c815629473d79abfa9368e0c6c546624a60b011715b87fb8d5cc9a1f028f1079ade65b35291bb0b1fa5f02b6072a40a78275e2ec4784e41d16fd83357ab084935f6d7896788ce7cba108896c0e865b303fed152a8ec3c664f4b135739a671d3a8335b1960a1727d451c85f0e5562fa021088eb45a7f694371d16c21f7b136b9642e817cad5135901de9122756bb776eac02b894d04e198ae881e0af62b79dab09db20311c83e69852ee7b5c13a546714dbceb221b0440af333c3c4344f4fc324c301a60d1f183e7330f110ed3596e253fa8c693063f5f9599faa778b1afbe68eb2f832af2a6acb250d7236e956d0fd56eded2ee11caa420a2687fdf82a74785366aa22e916d75ad1597ea3d2f9a0c5b6d07a4d557a931022bbdd36b4bbc75e97c3fda081facc8cc0782f902771166d34c8ea91147d1c7b7ec857881fdd5425581f1d027ffd2108ee15a9b81196b29059a5791850f6f330b47bc5c7180db701fa81da7030cfda8e60f12a69172bac1651b7392a0927b93b28b42b5d2e9d590e736bfad55993d97cb1b79a1f519591e2c528bfbd0e5504189719b9cf4f7b0d155734cd43800daf07357d653f73370a02618bae488201846aacb31565b5b23e7aa818e70b5ece5dfe1cbeb945e449f3d425065925505e62a8bd5ea20f21667ba834d8cc52026857cf176677a658c7db9e27b0e0e0c479031960b9b3f6d06026e2d87c60c7135bfd63b9dcb2c00e46e5f042393ba7ff958ee8fa72c2c9e9594bb2fa9162c38688dd77c3ff7695303ce3fc79953453e2e2c7fe02628e53c52036297c0c2ac5f4630919bd359bb69225eca419c6a6c89c071d6716c6ec0093fc65712c2e7dd0be6ef7c7417aaecc60f83088b64bc0f247d038e921cf6fd1e47a59da17d62ed646fcc502aceed35870eebcf10881cf0ff712c302bb4e7eeca684b49fc90de7e12bd211ce2e0421d698c59ac3984d71d9b02164fe9cbe95966c4da5f8c4800fdccb6bc09e4056af229619ab9ab723ef6592c6bbf83fcc20dabf9f49511c4311a1a97cacfc030604334583e6f5ab08654ab43d9392722f40a41dfbd6035a5edc25fbe72ec02ac6775795a1fefa99c18948f548be1a636ebd24b697b0a59c00071b73a90511911d27c0b00926a79902d859a40d7f0a77488dcf5af259e818d05d186b0474a4425ec3abeadbe310922acf1ec22a615874764511bf80d16bbedfcf837323283c84971f9bcdcac612942fd12dbd1beb8f6b658da42f50863366552738016491073e24ec7ed6f429706ae4b90816471af4031be4e492c8c2a08ff1680e3d3d934f2e0a3e42cdf7214e3ef59af7b39842988a1f4cad45ad0ad419d0382f766560b861959132e76806ed08d5322da000d39845feaf455bc306af95a7684eea71b4ac31a972220ea22f029977030314b9a4b21f8c402b0bf2f41da5bd721179d7672ae77f48f9f682ffdf5bab3588cf8a49d31c002b7adb4434cfc5a05488ef8f26ac80dc153fabd6cebe61a04c2428aa04e037c977441b1bb93ed431c914ade76b0c08cc887e3d590f1e2a50308fa3c54b22d92f9b8ac39d485cb84eb6ffa0a51718693f58aad932695e169b7e41a4f4ce021362241472d13e2ef0c569110fa5f0d05f244e3e6f9b8a706817fa592b2f9117e8c2defa18ebfd1563cbe348c4f8de0a16e7acd71735a657f75ff196605d4ea3fbb120e954701c8c59e0bfeeee38f7312307ebcee061b4226d3eda9aad6eb31d460a0d3552e156f3e86489dff4a03791be54a6925ee5b07d0545896106bc847bdd561146ef646aa91b879f0de706c740bfdb5d1c3a732b640731436a62c431187e775b4880a0b2275a312a894779212407be25031e403d9f36cbfe07418dff4dd9fa6379d110416697ee0c114d113c6f99e04cc37286c3d6851c5ccf781250e5d3049d93d1917723751d8672639f0bb854f87564af445ac5cb47a1fd35864b6ae446eb1e4806a6f3bc9e4ca4bd191cf9d4b56530735b16254b920afa2415329f673bf921e849f0aa7b8c51f0e5b40756d04c19a1eff8b622965ecacf183bb07b2b4572630f97f6eadda879bc0fffbbc4bff7ed1e5aca9a847de2129a3c935c278af6c29eebcf58a1e6cf093aa44aca35c1bafa6e2a361218b000ff4a2a49c65e64c12344d94c5040d1e737f8bd78bf015ecbfea6ce19574837c5471dd660e673dbd703eae068521ac27f570786a952e37d4ef425607ad60fe45b09a228f18ee664d04652ee2cbb488d42a0c9faaf50f867afa41f1b68aa9d7967f15adda81deb18c00f29ea8a5e0775381cf931f58caacb54a7ac41db043747a218927fbebff95aa1520e136f366088a0c006a2fe6b61070626e0c083ede8c423acfdd70d0de04927a5d2f481d4cbd2485c5bc7aa22f6fe226be46be4a9dfa6d10253675bf0760f3131a11e169dcc62f4338fdc35ce0280f23483c2ccd2ed854b3666f6e8c02ca15be940edcb11e996a84a61db5b0f68fc6703a0aed9866396e26895aae65bde6d50f573ba0a6e45a6671bea93700223b866360ec5baeef69294666acacd89acf029fd7e66b37d0d1fdd9aa0a69a827c6506edd8e48a771cbd698b868de3d4d4440348f97a0ab76709d57139a1da8f1b9543252bb8778eb2f5be0ed17756e4ae806e341741dc992dd2f06608eadeb4cd819ac791f0d30901e622bafee36b5409c091193e4c0f5a5db5c516cfd9e40496cf91773e6d87817f639f8d47385df3a43a2bef3705c25f636414f9c2887a782bd786b7b1cde6793907b15eed4e9486c991f21e3a02f7d48dd9366ff8760d95a46751cf1d32c2e72515f36e0d98ad9a5f81a70c06d5c4560868c6d1990def3b94475b76664381f722fdabe739066c58370aa03a28aa5bd00432177b74d70f4cb53ab7f3a5459e99e1b430d1dd547c273214dbed7c3cdc673a0f5b924a860cce78aa1e8cca714b5f28471368e2fb5f41d2e72e6967e20adbcd5006dd31f644b4439ecfd62541f69d5c9810ca00df676a284d4646923f76dd4846d7f289d29cf3dd9770cc4fc2a2fda158264538584aabd66d28f71018252892b545992ddcdf4a40fa2f3a909abfe0da2e722178d70e83ccd21477581af360c93d33531b095951804c15f2dbb80d48a9db7ea9900edef9651f758c97683eaee8e61c0c88d30c4969920aa732c57f8c5a1aa2834b9f9c3285267dc4e56a381633d466a64b2085abfa052b13d812a6873efe6f2544650186fea789d6924599bc06046f151931d7b6b614b836a1246b8ae7ce4614563ecb68cf9a57cd3731f89e1a73951a2ace26289a366529a987592d18d4d326fd0a9f289a6a9517d4e33de1736ea2f9c5e2c52493378bfd5b4fb643eb17fa154728e29ddc1b2d6fea380205692aac60d3916ec163777a6fbf2fb8cdf840e09f910e29c85727812a62dc3a3a39afdc2ea167a5449e12c2ce1371a32d57ce5802cda1f28254f0d9c544080622df00e2c094011ea97e34edd702de6a84c1b156da47667699b63ada7d58c202fbc2f540c8d4fbf8cdc95f9b102257fac1f2f8ce5bfd2f50e99f7282d2463208c08b106782a1ebd4a135ae1afcb54319972689303d6a524307e29114a50cdb2f8c94fb0f204f637a16fea8261ae51ac33b3b1ab498213636b9c7f855b9a46308ffa1f8b6c8b25a2b6065920f9a20833f9c097b8f48dae00ff898d7d462e55dab5aa07f9d1396504b8e42eecec392fca1f64c30305e02602f5b454c4a562bb17aab60970d440d913b8db0aae3383e1f3f013d7019e3e9d69147810546b1dc6fd68c9f47ac3c4a67972b854055f4706ae4861e584aa855d42e4b5dfd61fd9d6673beb5801d2e31bd7dd78091d474d7ade651dbe5ea208360be3ef1aeebd9e38681768c0783193d1c4474f913a2b4c395ed725ba539a6d6a0ad31015248c84805bf0cd35449653e8801a6a397f228d385e8cc8da401fbc8c111de9dde1257c0cae82220202870abc1a1112b807287b06d08f9d33ff02e81a19fd66f02ce48b71524b5a5177f80b3674105d56234bf717bf682f63943f9a6464638053561b78db54aeb6525035b39a01e610249af2c0b5f2b3b799f14f8c0ee76b66f09ac685ed9ba4678268441d14a22a4a65fd3d7d72816af4d842bdcef9bd20ecbbb42c6b6fd6668bcb0cc8c99fe5a30ae7ee5c850bec2d6296f91c2c1976fa55a4c9cbdaaebdc8f718475951affbe88c3af773953001c08ae069e1cf40bb9799f569954b33c3f4330c74652f088ab669c8b7cd93c5557be761764be9e85b0f07439d28b8e9977586922dfe4c287bdc4122fbe6378923c86bc586fb547b1012f92b2a75047f7a48f88e1730408bf53a6b6ea2c905d1807916be1e0288294cc466ee73f909ead23f31ef36b61e5df581f382c81aabc761f45547288621d16ba21e52c14b92c93e276c22f2b4ce5106928cdd0cdeb67dcdf8ef98db1a701e9f196a2cf3353a27bdcfd5ea32f8cb53795c40beaec2e33bb3ceeb980688709a6f875a2ea891367aa7b1d5b5de2f90d717d2efea3a3ab71777d1f4c7d758487f2114f5ad4062b31b08fefd3edda89982138e4185ed9f4cdd122761389e06bd4eabf217d4197b3fa1a0691a96f7b1ea33624e528132c104b25f0440236ee38df45c1581a68d1fb44e1bf29c3a191cc95ecc2fe09c38c78bba281cf51d51f06a22ea1cd6476b077c6deca2c278606fe8d6efd65dcf9fcbb7e984d75e69ee6e1989427c510034fd4501f75ffbaaf813bbbeb148dd1019d45e2e6ad33a22304f9cbcc54b78c8c3ce958f8a75a2a777f092dbe3b88344f84d93dc9bbec0aa9287a9859c740dd4dd7bf28e5222cabd4a525260a94996ab21d70c4c82ae42d7c802dc9e7377be23b15e5c13872b0a49ce3894c60bd1aa235fcff8d4af6fb85656376a5fd0409fc4b33419f9a4f70462baa3534bb8ed68b8ca471adf0e11d5ba51d4b614b678231e3036fbd5c632d956298ea9fe845727486896056d0c03ccdd1c9e8a9a60473db4e6face0c4edd3d0353fc588e24e6b428050f18974d8c85c7cbe95dab305b6720dc14c21b1550743e335263c756399ff8091f48da7cdfd9e1fe4790cb337e8db7640f2916fb910bce94e76c9dba93ce0c72c297c340c76da7895a75729b2e103646d91170978de2abb1544927d473113947c2fc1e048cc08bde0fe3e5e0afb144fde4fb7328545b05b100e432ed26d16e435fe4d6c0a4413a8041614569ccaf741e8d3e4eac01490c890fa924792a080750f582a538afcb5851be494f8bfb0649287fd01b5fe10f7402ec63899c67ba5c2d377683425d4b079b62e13e6debe7d6cfaf1f7e8f6def16902a725e89840eeef41fb54d74e97777a31e5275cbe2c6b49428cc11c34a334f967c3be7c8228b77029e494a7f30f0f774f9d7b3ac9cbb0792e5af1b1cc7bf8250b879a558fe1dcf0e47f9eed867580bed13bf0880693a1eac8eefa43ad554f64f8c07aebb280f71112a168c320b4a2cb757c2f0aba3f7168c4dc1ad9a95a959ebee8c4057eb6a67df2d80a815291ab340fe4e1c7edc4ea32ef97eddc3a1806d4da1edc07ab7362a215be04c47d9d204f644ac4463a9aca3b6620cae9842a2c4140c724fd7f73ea8a7adb19143907af6e3850a5851334062cace2722124fa72935979ddda0aaf71b3d0cb11b3ef12e955e87ce03bef2f686354b8023b45933787146beb2844f6bbb3e4e6278270b700e73b3b2c4513a9e8de1fbc15ca0f7b76f5386acddeb400452b6fe7e60d109ddf62a3404b1b3738de303d0e824796e1737c35e1077af37d5f8d915c8ab71a16635c60e18d76b3c9280d876a34fb0973b87ffc3d4761075e1f30a2be34621baf1c73cdffc7f965e590a63ad34897c27047df2140c976b62c7cc9f02fcefd07d9c0ce7ddeee9cc6dd7b20245a7a08268e2246044e84474969e1eb63930f495750917bc0975a0c65feb4d5a1d87a2ea7e1508cb2436f319adccc4618bf5bc1885d0e1fd3f254d5779037ecca9649879f1236cfd843bc832c2a7c2d79e6775fffa67da8bb582e400b36a5b95a7efd3bc6d33dacc0e2588c713fdb46c87095b629294efa9f197784766cbc697b84c874ff109705f2c0b6c2570b3d90f5b85d84a5e1ab2a037136d187e37a7cb33b406b3011fa3897e649ee63ab76022db7dd2d0eb1b7ae97088b19634ff9970bc1cedd6d20f5c67772e8096c634a7dade70f5f92710e41ee9d8dc3515d7d1d73a8a6190e1db33e2066bd26a9e828a1b8f90f7ff12a2f23627f75fea4164c19ec1ac04b942e6f2013bfe2c2e43c2b57f3b21024429b468c6d1a1dff7540614abd4bc82d5d9b059bde8b1031f96cda606fe9e94136b4290bd046c5e2818ecda86bb7e1fef74caebae4d090b6a58e12edfe52362a681dc64e378ab008550c883fa84b062b778fe2db472f32ca3fb2f74df7be06ef0a85f2fa019260c5cc1e66d7fe6d6962bf8762e9149a689749f3b871e88e5a8d4a61490dc8c701dc8ca3e920067613e907f5c736d68c792672895b47e9e797d0253bec32b9d5a79e0a433e1601d5e5072b7660b5ebed7e67bc95a6223176625290382192efaff0436ff1c704e9f76e1c64d83fed9472197a6bc000bcc24d02e5400efee09bc5881aee9bc801826cde13fc6d22a0a9dbfe4cb171c9528a0240b8ded6f922c77de1360939fa0bbe4fb82c3105f22c90040958b1cfad71423aa7fc3624e0d22a4e9da57e3dc09950a599266fa71c0841f80764e96a096e1ce4ad161c0cb5348bb5248513b4740748d10b423b9cbc95cbe6ae43040a5eed2ae2cfc7eb34081595ab6b2dd1fd7480089ee2e8fbcd06c6dc43a3243c9c4450f05c28559df8c0fc41cadb644854825662d1475c00dcec00818b746a286dc12acc5175a04d0ab685b48c76b40bd0790afa606be65e6c7df5e027f8bbd6979f00a08cb985b68a64f1604e6386715a4aa242d8176e43f6d8147dd64377a4f44d24fa3ed06323746207d95bf6323b61b42f4903d32f6235a77f98c25ce6ebe8d5f8b76d689267ecffe9c32b7dde34c7f43da41ce215456f1423572b78b116af081226c54eb0fcd8272890ea4ff1ccf91614c309cace805da498eb7b538f2f5e08d99f46d1f57981c5d8488301fd00d11f484e13c00bab448bdace012d2951db621aea02e2a1efd5638931f55faaa0c62e9a3d25ee26ef6a57ff22836b331e9d4d9179d5297972891bcdfeb695e9d296e61798456f9c7ace85c8e767211c5b586eaa114c74dcbcaaf8acc932707f42c775032e1f771428bb60c6fbca0e34e17a20ff52f4616516c60ff59a0b81f9908faae30985bb3126f98fd57aefe7e5b62098f47f35be80891ce4f9c4c6991b817128e3917b91d6fddb764b19e9e705c9fc3b45d1bb4fd4e0e06aabb40ca9f276f618e98856fa6eefb1646070e7504247df6dace32b472aa7dc41e633f086ab7d4ff34874c544d07d5679e7a8ac5f36672cf59ccadcf0c002e9f9322ca34a1691690a06b2f6dc2dd5d1b705490c8bd3acadea5d4e7dde44bfde584a62bfc85ad067be0e3a733e27ce017cac0230bfa5c53bf423dbd2f02ef0b95678a215afdd0480d0f1d7a1c709398e3448eb7b7c77c33570dfe545a81c6984c1bf19584953641daa62be86c17ae3b0c39daa12e0ddc5c40998f64abea505af6ac562d79d5f33cc19954348b0ed03028e71f6ee00962b0a3cbfc3ed78e92b58da538e8d4f65699a96bc41987f1b13aeaeb6fabab6b9bc9bb9e30ebb96a7a5817b73061d368a356f3d332e77da5e0f16d5f4fd981c132ca92cf6f6ad0f6ddbbb8f20912c4cb8a806e3386f39b7c5f668763366d01a4d69b5b0516b1b8b0930e7211cc060ef0d0de91e49656ffa28cb3ba42f4c2a31892eb91effff5f607b3bbcbc61733e8eff2680547ba75f37d4a7a6fd49019dabd5844aa2077dc5783919beb2c0a1f2601eaacc0ef67d61a70a8c9c248de2af03294e86f555ec59ac8c86d78a35c450ee80d7bab2b72761412cb54250b27aa3dd40b23532ecb3a14fd7fb6d0ab584a3677f6b1a373a1400100439edb5e011c9595daaa69fbccbdd1621f8ea08f21d4ba9dec01f2b75b6579f5010bf6538de8240a266eefd7e2fc9f2096c23465b5d545627737f162f8c5691c0eb07fe59879d55fad9174ada4043b9ccca80e2c9919d005e339f71802c6e64107e5d939921989642da4e3a24ee3d58ef82e99a54a4d4b2c732d114a823d6edafede047b8877713abd0a37da3086c64abd0cfbb2914d41fbcb6c33daf9405e371dca44f9b085bd7ce80ce5dc10847111cb72a6fa0ddc4d4f5fa7284c4becc389936cddbd759338701adaddcdc68be01cff14f472d30aea3189ae4dce09afbdc6d41405e16dce2f667bfba5600d7cbdec3d4d30041544dd461fa876c085c15de206ea8a00b90f89b5b010622d246b63a11dd57780c09e6e66288141e5191c9aa4d3887989cf2960b5f7d7d0a00b4fafe80691e335e8836cafefb784c05c4c13542d47123df54b71503998f750520e6226690a6d0e933adad8555f519c8e08d4835ff8826d9e975ced67b2084b5f20c5e2e2de0f32bd0cb3bc760174c9e3d383a4d45af9505d2c1cd4ea892cb0190d0ec47f1269623937425aa3725366ac712f7e30358de56b757912fbab0e73dd0d5672f0e23ae501930c7cd82b10dcd41815ce7135b8013e8a5ef854dca11b7c984d9da15547820604df6d0e30b896da0ab8329306220a4d095c610566196961f840733f872dec575ae58c11cf507248d3a5a017bef3c939bd05b789a41fa6d0ee0e41b72e62aedefd033cceae2e13404eaf2f3ba109c6cdb10cfa8b4e6a78ac3ee7978a273c999bca8a58930f4914044ba6605638ef5dff33b6b4b1fc7cd76ce502060affcb5232760f8aecf01825c14e3d1c0332b98a01747965b8e62c1cba3a865754aeeffc1a3fe38683a0ae89f7320b1ba314f1bc5dc2b47b094ba9242e7473245e6feb8e5fa63699f320c755e4b81f8fdc22d277d62d50bf1ac0a33047b7ef43c9eaad8376e3049b7a772cd5a21fa3a1358efa46857699cdf4e26ca3541f8a508b9f4baead07e9b8522081461f3a965547dbb7a43cd53f804419bb9ecccd7e0be09f69b07d320d52db53be1be2f6b4dc4ff8b7665681e9ba4cc8b6ac989bac9002a15913d0600e7100cd086494fb0d44da52a13627adb6089d8634288b08e9843ce090e79c37a286d9facda1126adc9bcac24faf62650f793407c36bb71a4e26526c7c84521aef3a7c702773ec2e4d9648a2269d86002a11325dd8eebabd321a4f6478cb670b8fc5b1ec5346b58e57915a776dd1830854a81f2716b089a336d3c4c9bde6337c9ebb94f269d9990028c04fb12ca59c2eb490470e33534d8efb250b518d7e2b23d515a716905e8e5200343adb21ee504195f282c913534a76452a49c76b8f5c33a8a174f5052dc3db943565e6fccbc36e7951a1063c8410a454b7fad8e54a021340062d2fdf94981dd6d88995014a11a7dbe244b401ff88d6f780ae1c0945d4fd88c2c3426296bc2c80"); + assertTrue(Hex.toHexString(s), Arrays.areEqual(expected, s)); + + sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + */ + public void testSLHDSARandomSigSHAKE() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_shake_256f, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + public void testSLHDSARandomPrehashSigSHAKE() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("HASH-SLH-DSA", "BC"); + + kpg.initialize(SLHDSAParameterSpec.slh_dsa_shake_256f_with_shake256, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("HASH-SLH-DSA", "BC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("HASH-SLH-DSA", "BC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + private static class RiggedRandom + extends SecureRandom + { + public void nextBytes(byte[] bytes) + { + for (int i = 0; i != bytes.length; i++) + { + bytes[i] = (byte)(i & 0xff); + } + } + } +} + diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SnovaTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SnovaTest.java new file mode 100644 index 0000000000..4dd563ca1f --- /dev/null +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SnovaTest.java @@ -0,0 +1,318 @@ +package org.bouncycastle.pqc.jcajce.provider.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.InvalidKeyException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Security; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import junit.framework.TestCase; +import org.bouncycastle.pqc.jcajce.interfaces.SnovaKey; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.pqc.jcajce.spec.SnovaParameterSpec; +import org.bouncycastle.util.Strings; + +public class SnovaTest + extends TestCase +{ + public static void main(String[] args) + throws Exception + { + SnovaTest test = new SnovaTest(); + test.setUp(); + test.testPrivateKeyRecovery(); + test.testPublicKeyRecovery(); + test.testRestrictedKeyPairGen(); + test.testSnovaRandomSig(); + test.testSnovaSign(); + } + + byte[] msg = Strings.toByteArray("Hello World!"); + + public void setUp() + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + } + + public void testPrivateKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Snova", "BCPQC"); + + kpg.initialize(SnovaParameterSpec.SNOVA_24_5_4_ESK, new RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance("Snova", "BCPQC"); + + SnovaKey privKey = (SnovaKey)kFact.generatePrivate(new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded())); + + assertEquals(kp.getPrivate(), privKey); + assertEquals(kp.getPrivate().getAlgorithm(), privKey.getAlgorithm()); + assertEquals(kp.getPrivate().hashCode(), privKey.hashCode()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(privKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + SnovaKey privKey2 = (SnovaKey)oIn.readObject(); + + assertEquals(privKey, privKey2); + assertEquals(privKey.getAlgorithm(), privKey2.getAlgorithm()); + assertEquals(privKey.hashCode(), privKey2.hashCode()); + } + + public void testPublicKeyRecovery() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Snova", "BCPQC"); + + kpg.initialize(SnovaParameterSpec.SNOVA_25_8_3_ESK, new SnovaTest.RiggedRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + KeyFactory kFact = KeyFactory.getInstance(SnovaParameterSpec.SNOVA_25_8_3_ESK.getName(), "BCPQC"); + + SnovaKey pubKey = (SnovaKey)kFact.generatePublic(new X509EncodedKeySpec(kp.getPublic().getEncoded())); + + assertEquals(kp.getPublic(), pubKey); + assertEquals(kp.getPublic().getAlgorithm(), pubKey.getAlgorithm()); + assertEquals(kp.getPublic().hashCode(), pubKey.hashCode()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(bOut); + + oOut.writeObject(pubKey); + + oOut.close(); + + ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); + + SnovaKey pubKey2 = (SnovaKey)oIn.readObject(); + + assertEquals(pubKey, pubKey2); + assertEquals(pubKey.getAlgorithm(), pubKey2.getAlgorithm()); + assertEquals(pubKey.hashCode(), pubKey2.hashCode()); + } + + public void testSnovaSign() + throws Exception + { + testSnova(SnovaParameterSpec.SNOVA_24_5_4_ESK, SnovaParameterSpec.SNOVA_24_5_4_SSK); + testSnova(SnovaParameterSpec.SNOVA_24_5_4_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_24_5_4_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_24_5_4_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_24_5_5_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_24_5_5_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_25_8_3_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_25_8_3_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_25_8_3_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_25_8_3_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_29_6_5_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_29_6_5_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_29_6_5_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_29_6_5_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_8_4_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_8_4_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_8_4_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_8_4_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_17_2_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_17_2_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_17_2_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_37_17_2_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_49_11_3_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_49_11_3_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_49_11_3_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_49_11_3_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_56_25_2_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_56_25_2_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_56_25_2_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_56_25_2_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_60_10_4_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_60_10_4_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_60_10_4_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_60_10_4_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_66_15_3_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_66_15_3_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_66_15_3_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_66_15_3_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_75_33_2_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_75_33_2_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_75_33_2_SHAKE_ESK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + testSnova(SnovaParameterSpec.SNOVA_75_33_2_SHAKE_SSK, SnovaParameterSpec.SNOVA_24_5_4_ESK); + } + + private void testSnova(SnovaParameterSpec spec, SnovaParameterSpec wrongSpec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Snova", "BCPQC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance(spec.getName(), "BCPQC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance(spec.getName(), "BCPQC"); + + assertEquals(spec.getName(), Strings.toUpperCase(sig.getAlgorithm())); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + + kpg = KeyPairGenerator.getInstance("Snova", "BCPQC"); + + kpg.initialize(wrongSpec, new SecureRandom()); + + kp = kpg.generateKeyPair(); + + try + { + sig.initVerify(kp.getPublic()); + fail("no exception"); + } + catch (InvalidKeyException e) + { + assertEquals("signature configured for " + spec.getName(), e.getMessage()); + } + } + + public void testRestrictedKeyPairGen() + throws Exception + { + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_4_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_4_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_4_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_4_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_5_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_5_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_25_8_3_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_25_8_3_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_25_8_3_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_25_8_3_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_29_6_5_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_29_6_5_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_29_6_5_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_29_6_5_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_8_4_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_8_4_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_8_4_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_8_4_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_17_2_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_17_2_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_17_2_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_37_17_2_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_49_11_3_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_49_11_3_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_49_11_3_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_49_11_3_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_56_25_2_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_56_25_2_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_56_25_2_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_56_25_2_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_60_10_4_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_60_10_4_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_60_10_4_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_60_10_4_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_66_15_3_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_66_15_3_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_66_15_3_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_66_15_3_SHAKE_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_75_33_2_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_75_33_2_SSK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_75_33_2_SHAKE_ESK); + doTestRestrictedKeyPairGen(SnovaParameterSpec.SNOVA_75_33_2_SHAKE_SSK); + } + + private void doTestRestrictedKeyPairGen(SnovaParameterSpec spec) + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(spec.getName(), "BCPQC"); + + kpg.initialize(spec, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + assertEquals(spec.getName(), kp.getPublic().getAlgorithm()); + assertEquals(spec.getName(), kp.getPrivate().getAlgorithm()); + + //kpg = KeyPairGenerator.getInstance(spec.getName(), "BCPQC"); + +// try +// { +// kpg.initialize(altSpec, new SecureRandom()); +// fail("no exception"); +// } +// catch (InvalidAlgorithmParameterException e) +// { +// assertEquals("key pair generator locked to " + spec.getName(), e.getMessage()); +// } + } + + public void testSnovaRandomSig() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("Snova", "BCPQC"); + + kpg.initialize(SnovaParameterSpec.SNOVA_24_5_5_SHAKE_SSK, new SecureRandom()); + + KeyPair kp = kpg.generateKeyPair(); + + Signature sig = Signature.getInstance("Snova", "BCPQC"); + + sig.initSign(kp.getPrivate(), new SecureRandom()); + + sig.update(msg, 0, msg.length); + + byte[] s = sig.sign(); + + sig = Signature.getInstance("Snova", "BCPQC"); + + sig.initVerify(kp.getPublic()); + + sig.update(msg, 0, msg.length); + + assertTrue(sig.verify(s)); + } + + private static class RiggedRandom + extends SecureRandom + { + public void nextBytes(byte[] bytes) + { + for (int i = 0; i != bytes.length; i++) + { + bytes[i] = (byte)(i & 0xff); + } + } + } +} diff --git a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SphincsPlusKeyPairGeneratorTest.java b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SphincsPlusKeyPairGeneratorTest.java index d08a5f5b3b..8add2a930b 100644 --- a/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SphincsPlusKeyPairGeneratorTest.java +++ b/prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/SphincsPlusKeyPairGeneratorTest.java @@ -31,7 +31,7 @@ public void testKeyFactory() { kf = KeyFactory.getInstance("SPHINCSPlus", "BCPQC"); kf = KeyFactory.getInstance(BCObjectIdentifiers.sphincsPlus.getId(), "BCPQC"); - kf = KeyFactory.getInstance(BCObjectIdentifiers.sphincsPlus_sha2_128s_r3.getId(), "BCPQC"); + kf = KeyFactory.getInstance(BCObjectIdentifiers.sphincsPlus_sha2_128f_r3.getId(), "BCPQC"); kf = KeyFactory.getInstance(BCObjectIdentifiers.sphincsPlus_shake_128s_r3.getId(), "BCPQC"); kf = KeyFactory.getInstance(BCObjectIdentifiers.sphincsPlus_shake_128f_r3.getId(), "BCPQC"); diff --git a/prov/src/test/java/org/bouncycastle/test/JVMVersionTest.java b/prov/src/test/java/org/bouncycastle/test/JVMVersionTest.java index 15d3eee323..46b985be48 100644 --- a/prov/src/test/java/org/bouncycastle/test/JVMVersionTest.java +++ b/prov/src/test/java/org/bouncycastle/test/JVMVersionTest.java @@ -5,18 +5,19 @@ /** * This test asserts the java version running the tests starts with * a property value passed in as part of test invocation. - * + *

      * -Dtest.java.version.prefix must match the start of System.getProperty("java.version") * So: - * if -Dtest.java.version.prefix=17 and System.getProperty("java.version") = 17.0.4.1 - * Then this test will pass. + * if -Dtest.java.version.prefix=17 and System.getProperty("java.version") = 17.0.4.1 + * Then this test will pass. */ public class JVMVersionTest extends TestCase { private static final String expectedVersionPropName = "test.java.version.prefix"; - - public void testAssertExpectedJVM() { + + public void testAssertExpectedJVM() + { // // This project produces a multi-release jar, and we need to test it on different jvm versions @@ -30,13 +31,18 @@ public void testAssertExpectedJVM() { // String version = System.getProperty("java.version"); - assertNotNull(String.format("property %s is not set, see comment in test for reason why.",expectedVersionPropName),System.getProperty(expectedVersionPropName)); - + assertNotNull(String.format("property %s is not set, see comment in test for reason why.", expectedVersionPropName), System.getProperty(expectedVersionPropName)); String expectedPrefix = System.getProperty(expectedVersionPropName); - TestCase.assertTrue(String.format("JVM Version: '%s' did not start with '%s' see comment in test",version,expectedPrefix), version.startsWith(expectedPrefix)); + if ("any".equals(expectedPrefix)) + { + TestCase.assertTrue(true); + return; + } + + TestCase.assertTrue(String.format("JVM Version: '%s' did not start with '%s' see comment in test", version, expectedPrefix), version.startsWith(expectedPrefix)); } diff --git a/prov/src/test/jdk1.1/org/bouncycastle/jce/provider/test/RSATest.java b/prov/src/test/jdk1.1/org/bouncycastle/jce/provider/test/RSATest.java index e756f401a5..16e36be2d9 100644 --- a/prov/src/test/jdk1.1/org/bouncycastle/jce/provider/test/RSATest.java +++ b/prov/src/test/jdk1.1/org/bouncycastle/jce/provider/test/RSATest.java @@ -12,6 +12,7 @@ import javax.crypto.Cipher; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; @@ -50,27 +51,6 @@ public void nextBytes( } } - private boolean arrayEquals( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - private RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); @@ -115,7 +95,7 @@ public TestResult perform() byte[] out = c.doFinal(input); - if (!arrayEquals(out, output[0])) + if (!Arrays.areEqual(out, output[0])) { return new SimpleTestResult(false, "NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out))); } @@ -124,7 +104,7 @@ public TestResult perform() out = c.doFinal(out); - if (!arrayEquals(out, input)) + if (!Arrays.areEqual(out, input)) { return new SimpleTestResult(false, "NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out))); } @@ -138,7 +118,7 @@ public TestResult perform() out = c.doFinal(input); - if (!arrayEquals(out, output[1])) + if (!Arrays.areEqual(out, output[1])) { return new SimpleTestResult(false, "PKCS1 test failed on encrypt expected " + new String(Hex.encode(output[1])) + " got " + new String(Hex.encode(out))); } @@ -147,7 +127,7 @@ public TestResult perform() out = c.doFinal(out); - if (!arrayEquals(out, input)) + if (!Arrays.areEqual(out, input)) { return new SimpleTestResult(false, "PKCS1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out))); } @@ -161,7 +141,7 @@ public TestResult perform() out = c.doFinal(input); - if (!arrayEquals(out, output[2])) + if (!Arrays.areEqual(out, output[2])) { return new SimpleTestResult(false, "OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out))); } @@ -170,7 +150,7 @@ public TestResult perform() out = c.doFinal(out); - if (!arrayEquals(out, input)) + if (!Arrays.areEqual(out, input)) { return new SimpleTestResult(false, "OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out))); } diff --git a/prov/src/test/jdk1.15/org/bouncycastle/jcajce/provider/test/EdDSA15Test.java b/prov/src/test/jdk1.15/org/bouncycastle/jcajce/provider/test/EdDSA15Test.java index 179449a97f..d321fd11d4 100644 --- a/prov/src/test/jdk1.15/org/bouncycastle/jcajce/provider/test/EdDSA15Test.java +++ b/prov/src/test/jdk1.15/org/bouncycastle/jcajce/provider/test/EdDSA15Test.java @@ -6,23 +6,28 @@ import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.interfaces.EdECKey; import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.EdECPrivateKeySpec; +import java.security.spec.EdECPublicKeySpec; import java.security.spec.NamedParameterSpec; import java.util.Base64; -import org.bouncycastle.jcajce.interfaces.EdDSAPrivateKey; -import org.bouncycastle.jcajce.spec.RawEncodedKeySpec; -import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - +import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.bouncycastle.jcajce.interfaces.EdDSAPrivateKey; +import org.bouncycastle.jcajce.spec.EdDSAParameterSpec; +import org.bouncycastle.jcajce.spec.RawEncodedKeySpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; public class EdDSA15Test extends TestCase @@ -149,6 +154,51 @@ private void implTestInterop(String algorithm) implTestInteropCase(kpSunEC, sigSunEC, sigBC); // implTestInteropCase(kpSunEC, sigSunEC, sigSunEC); } + + KeyFactory sunKeyFact = KeyFactory.getInstance(algorithm, "SunEC"); + KeyFactory bcKeyFact = KeyFactory.getInstance(algorithm, bc); + KeyPair kpSunEC = kpGenSunEC.generateKeyPair(); + + EdECPublicKeySpec pubSpec = sunKeyFact.getKeySpec(kpSunEC.getPublic(), EdECPublicKeySpec.class); + PublicKey pubKey = bcKeyFact.generatePublic(pubSpec); + + EdECPrivateKeySpec privSpec = sunKeyFact.getKeySpec(kpSunEC.getPrivate(), EdECPrivateKeySpec.class); + PrivateKey privKey = bcKeyFact.generatePrivate(privSpec); + + sigBC.initSign(kpSunEC.getPrivate()); + + sigBC.update(Strings.toByteArray("Hello, world!")); + + byte[] sig = sigBC.sign(); + + sigBC.initVerify(pubKey); + + sigBC.update(Strings.toByteArray("Hello, world!")); + + Assert.assertTrue(sigBC.verify(sig)); + + sigBC.initSign(privKey); + + sigBC.update(Strings.toByteArray("Hello, world!")); + + sig = sigBC.sign(); + + sigBC.initVerify(pubKey); + + sigBC.update(Strings.toByteArray("Hello, world!")); + + Assert.assertTrue(sigBC.verify(sig)); + + EdECPrivateKeySpec bcPrivSpec = bcKeyFact.getKeySpec(privKey, EdECPrivateKeySpec.class); + + Assert.assertEquals(privSpec.getParams().getName(), bcPrivSpec.getParams().getName()); + Assert.assertTrue(Arrays.areEqual(privSpec.getBytes(), bcPrivSpec.getBytes())); + + EdECPublicKeySpec bcPubSpec = bcKeyFact.getKeySpec(pubKey, EdECPublicKeySpec.class); + + Assert.assertEquals(pubSpec.getParams().getName(), bcPubSpec.getParams().getName()); + Assert.assertEquals(pubSpec.getPoint().isXOdd(), bcPubSpec.getPoint().isXOdd()); + Assert.assertEquals(pubSpec.getPoint().getY(), bcPubSpec.getPoint().getY()); } private void implTestInteropCase(KeyPair kp, Signature signer, Signature verifier) diff --git a/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/PSSTest.java b/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/PSSTest.java index bd1dc32f35..f0d567501a 100644 --- a/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/PSSTest.java +++ b/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/PSSTest.java @@ -11,6 +11,7 @@ import java.security.spec.RSAPublicKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; @@ -38,27 +39,6 @@ public void nextBytes( } } - private boolean arrayEquals( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - private RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); @@ -98,7 +78,7 @@ public TestResult perform() s.update(msg1a); byte[] sig = s.sign(); - if (!arrayEquals(sig1a, sig)) + if (!Arrays.areEqual(sig1a, sig)) { return new SimpleTestResult(false, "PSS Sign test expected " + new String(Hex.encode(sig1a)) + " got " + new String(Hex.encode(sig))); } @@ -118,7 +98,7 @@ public TestResult perform() s.update(msg1a); sig = s.sign(); - if (!arrayEquals(sig1b, sig)) + if (!Arrays.areEqual(sig1b, sig)) { return new SimpleTestResult(false, "PSS Sign test expected " + new String(Hex.encode(sig1b)) + " got " + new String(Hex.encode(sig))); } diff --git a/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/DHTest.java b/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/DHTest.java index 19c30d6cef..b394a1572a 100644 --- a/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/DHTest.java +++ b/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/DHTest.java @@ -26,6 +26,7 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; @@ -252,7 +253,7 @@ private TestResult testRandom( // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); - if (!arrayEquals(encodeParams, encodeParams_2)) + if (!Arrays.areEqual(encodeParams, encodeParams_2)) { return new SimpleTestResult(false, this.getName() + ": encode/decode parameters failed"); } @@ -474,27 +475,6 @@ private TestResult testExceptions() return new SimpleTestResult(true, this.getName() + ": Okay"); } - - private boolean arrayEquals( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - public TestResult perform() { diff --git a/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/PSSTest.java b/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/PSSTest.java index 3cba08eb79..672a6b9760 100644 --- a/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/PSSTest.java +++ b/prov/src/test/jdk1.4/org/bouncycastle/jce/provider/test/PSSTest.java @@ -15,6 +15,7 @@ import java.security.spec.RSAPublicKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; @@ -41,27 +42,6 @@ public void nextBytes( } } - private boolean arrayEquals( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - - private RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); @@ -103,7 +83,7 @@ public TestResult perform() s.update(msg1a); byte[] sig = s.sign(); - if (!arrayEquals(sig1a, sig)) + if (!Arrays.areEqual(sig1a, sig)) { return new SimpleTestResult(false, "PSS Sign test expected " + new String(Hex.encode(sig1a)) + " got " + new String(Hex.encode(sig))); } @@ -129,7 +109,7 @@ public TestResult perform() } AlgorithmParameters pss = s.getParameters(); - if (!arrayEquals(pss.getEncoded(), new byte[] { 0x30, 0x00 })) + if (!Arrays.areEqual(pss.getEncoded(), new byte[] { 0x30, 0x00 })) { return new SimpleTestResult(false, "failed default encoding test."); } @@ -142,7 +122,7 @@ public TestResult perform() pss = s.getParameters(); - if (!arrayEquals(sig1b, sig)) + if (!Arrays.areEqual(sig1b, sig)) { return new SimpleTestResult(false, "PSS Sign test expected " + new String(Hex.encode(sig1b)) + " got " + new String(Hex.encode(sig))); } @@ -171,7 +151,7 @@ public TestResult perform() pss = s.getParameters(); - if (!arrayEquals(sig1c, sig)) + if (!Arrays.areEqual(sig1c, sig)) { return new SimpleTestResult(false, "PSS Sign test expected " + new String(Hex.encode(sig1c)) + " got " + new String(Hex.encode(sig))); } diff --git a/prov/src/test/jdk1.5/org/bouncycastle/jce/provider/test/PBETest.java b/prov/src/test/jdk1.5/org/bouncycastle/jce/provider/test/PBETest.java new file mode 100644 index 0000000000..48c8d38399 --- /dev/null +++ b/prov/src/test/jdk1.5/org/bouncycastle/jce/provider/test/PBETest.java @@ -0,0 +1,824 @@ +package org.bouncycastle.jce.provider.test; + +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.SecureRandom; +import java.security.Security; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.InvalidParameterSpecException; +import java.security.spec.KeySpec; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.PBEParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.PBEParametersGenerator; +import org.bouncycastle.crypto.digests.SHA1Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator; +import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.jcajce.PKCS12Key; +import org.bouncycastle.jcajce.PKCS12KeyWithParameters; +import org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Strings; +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.FixedSecureRandom; +import org.bouncycastle.util.test.SimpleTest; + +/** + * test out the various PBE modes, making sure the JCE implementations + * are compatible with the light weight ones. + */ +public class PBETest + extends SimpleTest +{ + private static class OpenSSLTest + extends SimpleTest + { + char[] password; + String baseAlgorithm; + String algorithm; + int keySize; + int ivSize; + + OpenSSLTest( + String baseAlgorithm, + String algorithm, + int keySize, + int ivSize) + { + this.password = algorithm.toCharArray(); + this.baseAlgorithm = baseAlgorithm; + this.algorithm = algorithm; + this.keySize = keySize; + this.ivSize = ivSize; + } + + public String getName() + { + return "OpenSSLPBE"; + } + + public void performTest() + throws Exception + { + byte[] salt = new byte[16]; + int iCount = 100; + + for (int i = 0; i != salt.length; i++) + { + salt[i] = (byte)i; + } + + OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator(); + + pGen.init( + PBEParametersGenerator.PKCS5PasswordToBytes(password), + salt, + iCount); + + ParametersWithIV params = (ParametersWithIV)pGen.generateDerivedParameters(keySize, ivSize); + + SecretKeySpec encKey = new SecretKeySpec(((KeyParameter)params.getParameters()).getKey(), baseAlgorithm); + + Cipher c; + + if (baseAlgorithm.equals("RC4")) + { + c = Cipher.getInstance(baseAlgorithm, "BC"); + + c.init(Cipher.ENCRYPT_MODE, encKey); + } + else + { + c = Cipher.getInstance(baseAlgorithm + "/CBC/PKCS7Padding", "BC"); + + c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV())); + } + + byte[] enc = c.doFinal(salt); + + c = Cipher.getInstance(algorithm, "BC"); + + PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount); + SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "BC"); + + c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec)); + + byte[] dec = c.doFinal(enc); + + if (!Arrays.areEqual(salt, dec)) + { + fail("" + algorithm + "failed encryption/decryption test"); + } + } + } + + private static class PKCS12Test + extends SimpleTest + { + char[] password; + String baseAlgorithm; + String algorithm; + Digest digest; + int keySize; + int ivSize; + + PKCS12Test( + String baseAlgorithm, + String algorithm, + Digest digest, + int keySize, + int ivSize) + { + this.password = algorithm.toCharArray(); + this.baseAlgorithm = baseAlgorithm; + this.algorithm = algorithm; + this.digest = digest; + this.keySize = keySize; + this.ivSize = ivSize; + } + + public String getName() + { + return "PKCS12PBE"; + } + + public void performTest() + throws Exception + { + byte[] salt = new byte[digest.getDigestSize()]; + int iCount = 100; + + digest.doFinal(salt, 0); + + PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest); + + pGen.init( + PBEParametersGenerator.PKCS12PasswordToBytes(password), + salt, + iCount); + + ParametersWithIV params = (ParametersWithIV)pGen.generateDerivedParameters(keySize, ivSize); + + SecretKeySpec encKey = new SecretKeySpec(((KeyParameter)params.getParameters()).getKey(), baseAlgorithm); + + Cipher c; + + if (baseAlgorithm.equals("RC4")) + { + c = Cipher.getInstance(baseAlgorithm, "BC"); + + c.init(Cipher.ENCRYPT_MODE, encKey); + } + else + { + c = Cipher.getInstance(baseAlgorithm + "/CBC/PKCS7Padding", "BC"); + + c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV())); + } + + byte[] enc = c.doFinal(salt); + + c = Cipher.getInstance(algorithm, "BC"); + + PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount); + SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "BC"); + + c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec)); + + byte[] dec = c.doFinal(enc); + + if (!Arrays.areEqual(salt, dec)) + { + fail("" + algorithm + "failed encryption/decryption test"); + } + + // + // get the parameters + // + AlgorithmParameters param = checkParameters(c, salt, iCount); + + // + // try using parameters + // + c = Cipher.getInstance(algorithm, "BC"); + + keySpec = new PBEKeySpec(password); + + c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec), param); + + checkParameters(c, salt, iCount); + + dec = c.doFinal(enc); + + if (!Arrays.areEqual(salt, dec)) + { + fail("" + algorithm + "failed encryption/decryption test"); + } + + // + // try using PBESpec + // + c = Cipher.getInstance(algorithm, "BC"); + + keySpec = new PBEKeySpec(password); + + c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec), param.getParameterSpec(PBEParameterSpec.class)); + + checkParameters(c, salt, iCount); + + dec = c.doFinal(enc); + + if (!Arrays.areEqual(salt, dec)) + { + fail("" + algorithm + "failed encryption/decryption test"); + } + } + + private AlgorithmParameters checkParameters(Cipher c, byte[] salt, int iCount) + throws InvalidParameterSpecException + { + AlgorithmParameters param = c.getParameters(); + PBEParameterSpec spec = (PBEParameterSpec)param.getParameterSpec(PBEParameterSpec.class); + + if (!Arrays.areEqual(salt, spec.getSalt())) + { + fail("" + algorithm + "failed salt test"); + } + + if (iCount != spec.getIterationCount()) + { + fail("" + algorithm + "failed count test"); + } + return param; + } + } + + private PKCS12Test[] pkcs12Tests = { + new PKCS12Test("DESede", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC", new SHA1Digest(), 192, 64), + new PKCS12Test("DESede", "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", new SHA1Digest(), 128, 64), + new PKCS12Test("RC4", "PBEWITHSHAAND128BITRC4", new SHA1Digest(), 128, 0), + new PKCS12Test("RC4", "PBEWITHSHAAND40BITRC4", new SHA1Digest(), 40, 0), + new PKCS12Test("RC2", "PBEWITHSHAAND128BITRC2-CBC", new SHA1Digest(), 128, 64), + new PKCS12Test("RC2", "PBEWITHSHAAND40BITRC2-CBC", new SHA1Digest(), 40, 64), + new PKCS12Test("AES", "PBEWithSHA1And128BitAES-CBC-BC", new SHA1Digest(), 128, 128), + new PKCS12Test("AES", "PBEWithSHA1And192BitAES-CBC-BC", new SHA1Digest(), 192, 128), + new PKCS12Test("AES", "PBEWithSHA1And256BitAES-CBC-BC", new SHA1Digest(), 256, 128), + new PKCS12Test("AES", "PBEWithSHA256And128BitAES-CBC-BC", new SHA256Digest(), 128, 128), + new PKCS12Test("AES", "PBEWithSHA256And192BitAES-CBC-BC", new SHA256Digest(), 192, 128), + new PKCS12Test("AES", "PBEWithSHA256And256BitAES-CBC-BC", new SHA256Digest(), 256, 128), + new PKCS12Test("Twofish","PBEWithSHAAndTwofish-CBC", new SHA1Digest(), 256, 128), + new PKCS12Test("IDEA", "PBEWithSHAAndIDEA-CBC", new SHA1Digest(), 128, 64), + new PKCS12Test("AES", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc.getId(), new SHA1Digest(), 128, 128), + new PKCS12Test("AES", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc.getId(), new SHA1Digest(), 192, 128), + new PKCS12Test("AES", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc.getId(), new SHA1Digest(), 256, 128), + new PKCS12Test("AES", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc.getId(), new SHA256Digest(), 128, 128), + new PKCS12Test("AES", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc.getId(), new SHA256Digest(), 192, 128), + new PKCS12Test("AES", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.getId(), new SHA256Digest(), 256, 128), + }; + + private OpenSSLTest openSSLTests[] = { + new OpenSSLTest("AES", "PBEWITHMD5AND128BITAES-CBC-OPENSSL", 128, 128), + new OpenSSLTest("AES", "PBEWITHMD5AND192BITAES-CBC-OPENSSL", 192, 128), + new OpenSSLTest("AES", "PBEWITHMD5AND256BITAES-CBC-OPENSSL", 256, 128) + }; + + static byte[] message = Hex.decode("4869205468657265"); + + private byte[] hMac1 = Hex.decode("bcc42174ccb04f425d9a5c8c4a95d6fd7c372911"); + private byte[] hMac2 = Hex.decode("cb1d8bdb6aca9e3fa8980d6eb41ab28a7eb2cfd6"); + private byte[] hMac3 = Hex.decode("514aa173a302c770689269aac08eb8698e5879ac"); + private byte[] hMac4 = Hex.decode("d24b4eb0e5bd611d4ca88bd6428d14ee2e004c7e"); + + private Cipher makePBECipherUsingParam( + String algorithm, + int mode, + char[] password, + byte[] salt, + int iterationCount) + throws Exception + { + PBEKeySpec pbeSpec = new PBEKeySpec(password); + SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, "BC"); + PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount); + + Cipher cipher = Cipher.getInstance(algorithm, "BC"); + + cipher.init(mode, keyFact.generateSecret(pbeSpec), defParams); + + return cipher; + } + + private Cipher makePBECipherWithoutParam( + String algorithm, + int mode, + char[] password, + byte[] salt, + int iterationCount) + throws Exception + { + PBEKeySpec pbeSpec = new PBEKeySpec(password, salt, iterationCount); + SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, "BC"); + + Cipher cipher = Cipher.getInstance(algorithm, "BC"); + + cipher.init(mode, keyFact.generateSecret(pbeSpec)); + + return cipher; + } + + public void testPBEHMac( + String hmacName, + byte[] output) + { + SecretKey key; + byte[] out; + Mac mac; + + try + { + SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName, "BC"); + + key = fact.generateSecret(new PBEKeySpec("hello".toCharArray())); + + mac = Mac.getInstance(hmacName, "BC"); + } + catch (Exception e) + { + fail("Failed - exception " + e.toString(), e); + return; + } + + try + { + mac.init(key, new PBEParameterSpec(new byte[20], 100)); + } + catch (Exception e) + { + fail("Failed - exception " + e.toString(), e); + return; + } + + mac.reset(); + + mac.update(message, 0, message.length); + + out = mac.doFinal(); + + if (!Arrays.areEqual(out, output)) + { + fail("Failed - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(out))); + } + } + + public void testPKCS12HMac( + String hmacName, + byte[] output) + { + SecretKey key; + byte[] out; + Mac mac; + + try + { + mac = Mac.getInstance(hmacName, "BC"); + } + catch (Exception e) + { + fail("Failed - exception " + e.toString(), e); + return; + } + + try + { + mac.init(new PKCS12Key("hello".toCharArray()), new PBEParameterSpec(new byte[20], 100)); + } + catch (Exception e) + { + fail("Failed - exception " + e.toString(), e); + return; + } + + mac.reset(); + + mac.update(message, 0, message.length); + + out = mac.doFinal(); + + if (!Arrays.areEqual(out, output)) + { + fail("Failed - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(out))); + } + } + + public void testPBEonSecretKeyHmac( + String hmacName, + byte[] output) + { + SecretKey key; + byte[] out; + Mac mac; + + try + { + SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName, "BC"); + + key = fact.generateSecret(new PBEKeySpec("hello".toCharArray(), new byte[20], 100, 160)); + } + catch (Exception e) + { + fail("Failed - exception " + e.toString(), e); + return; + } + + try + { + mac = Mac.getInstance("HMAC-SHA1", "BC"); + + mac.init(key); + } + catch (Exception e) + { + fail("Failed - exception " + e.toString(), e); + return; + } + + mac.reset(); + + mac.update(message, 0, message.length); + + out = mac.doFinal(); + + if (!Arrays.areEqual(out, output)) + { + fail("Failed - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(out))); + } + } + + private void testCipherNameWithWrap(String name, String simpleName) + throws Exception + { + KeyGenerator kg = KeyGenerator.getInstance("AES"); + kg.init(new SecureRandom()); + SecretKey key = kg.generateKey(); + + byte[] salt = { + (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, + (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 + }; + char[] password = { 'p','a','s','s','w','o','r','d' }; + + PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); + PBEKeySpec pbeKeySpec = new PBEKeySpec(password); + SecretKeyFactory keyFac = + SecretKeyFactory.getInstance(name); + SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); + Cipher pbeEncryptCipher = Cipher.getInstance(name, "BC"); + + pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec); + + byte[] symKeyBytes = pbeEncryptCipher.wrap(key); + + Cipher simpleCipher = Cipher.getInstance(simpleName, "BC"); + + simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec); + + SecretKey unwrappedKey = (SecretKey)simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY); + + if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) + { + fail("key mismatch on unwrapping"); + } + } + + public void testNullSalt() + throws Exception + { + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHSHAAND128BITAES-CBC-BC"); + Key key = skf.generateSecret(new PBEKeySpec("secret".toCharArray())); + + Cipher cipher = Cipher.getInstance("PBEWITHSHAAND128BITAES-CBC-BC"); + + try + { + cipher.init(Cipher.ENCRYPT_MODE, key, (AlgorithmParameterSpec)null); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + isTrue("wrong message", "PBEKey requires parameters to specify salt".equals(e.getMessage())); + } + } + + + public void performTest() + throws Exception + { + byte[] input = Hex.decode("1234567890abcdefabcdef1234567890fedbca098765"); + + // + // DES + // + Cipher cEnc = Cipher.getInstance("DES/CBC/PKCS7Padding", "BC"); + + cEnc.init(Cipher.ENCRYPT_MODE, + new SecretKeySpec(Hex.decode("30e69252758e5346"), "DES"), + new IvParameterSpec(Hex.decode("7c1c1ab9c454a688"))); + + byte[] out = cEnc.doFinal(input); + + char[] password = { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' }; + + Cipher cDec = makePBECipherUsingParam( + "PBEWithSHA1AndDES", + Cipher.DECRYPT_MODE, + password, + Hex.decode("7d60435f02e9e0ae"), + 2048); + + byte[] in = cDec.doFinal(out); + + if (!Arrays.areEqual(input, in)) + { + fail("DES failed"); + } + + cDec = makePBECipherWithoutParam( + "PBEWithSHA1AndDES", + Cipher.DECRYPT_MODE, + password, + Hex.decode("7d60435f02e9e0ae"), + 2048); + + in = cDec.doFinal(out); + + if (!Arrays.areEqual(input, in)) + { + fail("DES failed without param"); + } + + // + // DESede + // + cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC"); + + cEnc.init(Cipher.ENCRYPT_MODE, + new SecretKeySpec(Hex.decode("732f2d33c801732b7206756cbd44f9c1c103ddd97c7cbe8e"), "DES"), + new IvParameterSpec(Hex.decode("b07bf522c8d608b8"))); + + out = cEnc.doFinal(input); + + cDec = makePBECipherUsingParam( + "PBEWithSHAAnd3-KeyTripleDES-CBC", + Cipher.DECRYPT_MODE, + password, + Hex.decode("7d60435f02e9e0ae"), + 2048); + + in = cDec.doFinal(out); + + if (!Arrays.areEqual(input, in)) + { + fail("DESede failed"); + } + + // + // 40Bit RC2 + // + cEnc = Cipher.getInstance("RC2/CBC/PKCS7Padding", "BC"); + + cEnc.init(Cipher.ENCRYPT_MODE, + new SecretKeySpec(Hex.decode("732f2d33c8"), "RC2"), + new IvParameterSpec(Hex.decode("b07bf522c8d608b8"))); + + out = cEnc.doFinal(input); + + cDec = makePBECipherUsingParam( + "PBEWithSHAAnd40BitRC2-CBC", + Cipher.DECRYPT_MODE, + password, + Hex.decode("7d60435f02e9e0ae"), + 2048); + + in = cDec.doFinal(out); + + if (!Arrays.areEqual(input, in)) + { + fail("RC2 failed"); + } + + // + // 128bit RC4 + // + cEnc = Cipher.getInstance("RC4", "BC"); + + cEnc.init(Cipher.ENCRYPT_MODE, + new SecretKeySpec(Hex.decode("732f2d33c801732b7206756cbd44f9c1"), "RC4")); + + out = cEnc.doFinal(input); + + cDec = makePBECipherUsingParam( + "PBEWithSHAAnd128BitRC4", + Cipher.DECRYPT_MODE, + password, + Hex.decode("7d60435f02e9e0ae"), + 2048); + + in = cDec.doFinal(out); + + if (!Arrays.areEqual(input, in)) + { + fail("RC4 failed"); + } + + cDec = makePBECipherWithoutParam( + "PBEWithSHAAnd128BitRC4", + Cipher.DECRYPT_MODE, + password, + Hex.decode("7d60435f02e9e0ae"), + 2048); + + in = cDec.doFinal(out); + + if (!Arrays.areEqual(input, in)) + { + fail("RC4 failed without param"); + } + + for (int i = 0; i != pkcs12Tests.length; i++) + { + pkcs12Tests[i].perform(); + } + + for (int i = 0; i != openSSLTests.length; i++) + { + openSSLTests[i].perform(); + } + + testPKCS12Interop(); + + testPBEHMac("PBEWithHMacSHA1", hMac1); + testPBEHMac("PBEWithHMacRIPEMD160", hMac2); + + testPBEonSecretKeyHmac("PBKDF2WithHmacSHA1", hMac3); + testPBEonSecretKeyHmac("PBKDF2WithHMacSM3", hMac4); + + testCipherNameWithWrap("PBEWITHSHA256AND128BITAES-CBC-BC", "AES/CBC/PKCS5Padding"); + testCipherNameWithWrap("PBEWITHSHAAND40BITRC4", "RC4"); + testCipherNameWithWrap("PBEWITHSHAAND128BITRC4", "RC4"); + + checkPBE("PBKDF2WithHmacSHA1", true, "f14687fc31a66e2f7cc01d0a65f687961bd27e20", "6f6579193d6433a3e4600b243bb390674f04a615"); + + testPKCS12HMac("HMacSHA1", Hex.decode("bcc42174ccb04f425d9a5c8c4a95d6fd7c372911")); + testPKCS12HMac("HMacSHA256", Hex.decode("e1ae77e2d1dcc56a8befa3867ea3ff8c2163b01885504379412e525b120bf9ce")); + testPKCS12HMac("HMacSHA384", Hex.decode("1256a861351db2082f2ba827ca72cede54ee851f533962bba1fd97b500b6d6eb42aa4a51920aca0c817955feaf52d7f8")); + testPKCS12HMac("HMacSHA512", Hex.decode("9090898971914cb2e65eb1b083f1cad1ce9a9d386f963a2e2ede965fbce0a7121526b5f8aed83f81db60b97ced0bc4b0c27cf23407028cc2f289957f607cec98")); + testPKCS12HMac("HMacRIPEMD160", Hex.decode("cb1d8bdb6aca9e3fa8980d6eb41ab28a7eb2cfd6")); + + try + { + Mac mac = Mac.getInstance("HMacRIPEMD256", "BC"); + + mac.init(new PKCS12Key("hello".toCharArray()), new PBEParameterSpec(new byte[20], 100)); + fail("no exception"); + } + catch (InvalidAlgorithmParameterException e) + { + isTrue("wrong exception", "no PKCS12 mapping for HMAC: RIPEMD256/HMAC".equals(e.getMessage())); + } + + testMixedKeyTypes(); + testNullSalt(); + } + + private void testPKCS12Interop() + throws Exception + { + final String algorithm = "PBEWithSHA256And192BitAES-CBC-BC"; + + final PBEKeySpec keySpec = new PBEKeySpec("foo123".toCharArray(), Hex.decode("01020304050607080910"), 1024); + final SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "BC"); + + BCPBEKey bcpbeKey = (BCPBEKey)fact.generateSecret(keySpec); + + Cipher c1 = Cipher.getInstance(algorithm, "BC"); + + c1.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters("foo123".toCharArray(), Hex.decode("01020304050607080910"), 1024)); + + Cipher c2 = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); + + c2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(bcpbeKey.getEncoded(), "AES"), new IvParameterSpec(((ParametersWithIV)bcpbeKey.getParam()).getIV())); + + if (!Arrays.areEqual(Hex.decode("deadbeef"), c2.doFinal(c1.doFinal(Hex.decode("deadbeef"))))) + { + fail("new key failed"); + } + + c1.init(Cipher.ENCRYPT_MODE, bcpbeKey); + + if (!Arrays.areEqual(Hex.decode("deadbeef"), c2.doFinal(c1.doFinal(Hex.decode("deadbeef"))))) + { + fail("old key failed"); + } + } + + private void checkPBE(String baseAlg, boolean defIsUTF8, String utf8, String eightBit) + throws Exception + { + byte[] utf8K = Hex.decode(utf8); + byte[] ascK = Hex.decode(eightBit); + + SecretKeyFactory f = SecretKeyFactory.getInstance(baseAlg, "BC"); + KeySpec ks1 = new PBEKeySpec("\u0141\u0142".toCharArray(), new byte[20], 4096, 160); + if (!Arrays.areEqual((defIsUTF8) ? utf8K : ascK, f.generateSecret(ks1).getEncoded())) + { + fail(baseAlg + " wrong PBKDF2 k1 key generated, got : " + new String(Hex.encode(f.generateSecret(ks1).getEncoded()))); + } + + KeySpec ks2 = new PBEKeySpec("\u0041\u0042".toCharArray(), new byte[20], 4096, 160); + if (!Arrays.areEqual(ascK, f.generateSecret(ks2).getEncoded())) + { + fail(baseAlg + " wrong PBKDF2 k2 key generated"); + } + f = SecretKeyFactory.getInstance(baseAlg + "AndUTF8", "BC"); + ks1 = new PBEKeySpec("\u0141\u0142".toCharArray(), new byte[20], 4096, 160); + if (!Arrays.areEqual(utf8K, f.generateSecret(ks1).getEncoded())) + { + fail(baseAlg + " wrong PBKDF2 k1 utf8 key generated"); + } + + ks2 = new PBEKeySpec("\u0041\u0042".toCharArray(), new byte[20], 4096, 160); + if (!Arrays.areEqual(ascK, f.generateSecret(ks2).getEncoded())) + { + fail(baseAlg + " wrong PBKDF2 k2 utf8 key generated"); + } + f = SecretKeyFactory.getInstance(baseAlg + "And8BIT", "BC"); + ks1 = new PBEKeySpec("\u0141\u0142".toCharArray(), new byte[20], 4096, 160); + if (!Arrays.areEqual(ascK, f.generateSecret(ks1).getEncoded())) + { + fail(baseAlg + " wrong PBKDF2 k1 8bit key generated"); + } + + ks2 = new PBEKeySpec("\u0041\u0042".toCharArray(), new byte[20], 4096, 160); + if (!Arrays.areEqual(ascK, f.generateSecret(ks2).getEncoded())) + { + fail(baseAlg + " wrong PBKDF2 k2 8bit key generated"); + } + } + + // for regression testing only - don't try this at home. + public void testMixedKeyTypes() + throws Exception + { + String provider = "BC"; + SecretKeyFactory skf = + SecretKeyFactory.getInstance("PBKDF2WITHHMACSHA1", provider); + // note: the salt would be regarded as too short and the iteration count too small! + PBEKeySpec pbeks = new PBEKeySpec("password".toCharArray(), Strings.toByteArray("salt"), 100, 128); + SecretKey secretKey = skf.generateSecret(pbeks); + PBEParameterSpec paramSpec = new PBEParameterSpec(pbeks.getSalt(), pbeks.getIterationCount()); + + // in this case pbeSpec picked up from internal class representing key + Cipher cipher = + Cipher.getInstance("PBEWITHSHAAND128BITAES-CBC-BC", provider); + + try + { + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + fail("no exception"); + } + catch (InvalidKeyException e) + { + isTrue("wrong exception", "Algorithm requires a PBE key suitable for PKCS12".equals(e.getMessage())); + } + } + + public String getName() + { + return "PBETest"; + } + + + public static void main( + String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new PBETest()); + } +} diff --git a/prov/src/test/jdk1.5/org/bouncycastle/jce/provider/test/RegressionTest.java b/prov/src/test/jdk1.5/org/bouncycastle/jce/provider/test/RegressionTest.java new file mode 100644 index 0000000000..ed0954e26b --- /dev/null +++ b/prov/src/test/jdk1.5/org/bouncycastle/jce/provider/test/RegressionTest.java @@ -0,0 +1,115 @@ +package org.bouncycastle.jce.provider.test; + +import java.security.Security; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.test.SimpleTest; +import org.bouncycastle.util.test.Test; + +public class RegressionTest +{ + public static Test[] tests = { + new AEADTest(), + new AESSICTest(), + new AESTest(), + new AlgorithmParametersTest(), + new ARIATest(), + new BCFKSStoreTest(), + new BlockCipherTest(), + new CamelliaTest(), + new CertLocaleTest(), + new CertPathBuilderTest(), + new CertPathTest(), + new CertPathValidatorTest(), + new CertStoreTest(), + new CertTest(), + new CertUniqueIDTest(), + new ChaCha20Poly1305Test(), + new CipherStreamTest(), + new CipherStreamTest2(), + new CMacTest(), + new CRL5Test(), + new DESedeTest(), + new DetDSATest(), + new DHIESTest(), + new DHTest(), + new DigestTest(), + new DoFinalTest(), + new DRBGTest(), + new DSATest(), + new DSTU4145Test(), + new DSTU7624Test(), + new ECDSA5Test(), + new ECEncodingTest(), + new ECIESTest(), + new ECIESVectorTest(), + new ECNRTest(), + new EdECTest(), + new ElGamalTest(), + new EncryptedPrivateKeyInfoTest(), + new FIPSDESTest(), + new GMacTest(), + new GOST28147Test(), + new GOST3410KeyPairTest(), + new GOST3410Test(), + new GOST3412Test(), + new HMacTest(), + new IESTest(), + new ImplicitlyCaTest(), + new KeccakTest(), + new KeyStoreTest(), + new MacTest(), + new MQVTest(), + new MultiCertStoreTest(), + new NamedCurveTest(), + new NetscapeCertRequestTest(), + new NISTCertPathTest(), + new NoekeonTest(), + new OCBTest(), + new OpenSSHSpecTests(), + new PBETest(), + new PKCS10CertRequestTest(), + new PKCS12StorePBETest(), + new PKCS12StoreTest(), + new PKIXNameConstraintsTest(), + new PKIXPolicyMappingTest(), + new PKIXTest(), + new Poly1305Test(), + new PQCDHTest(), + new PSSTest(), + new RSATest(), + new SealedTest(), + new SEEDTest(), + new SerialisationTest(), + new Shacal2Test(), + new SigNameTest(), + new SignatureTest(), + new SigTest(), + new SipHash128Test(), + new SipHashTest(), + new SkeinTest(), + new SlotTwoTest(), + new SM2CipherTest(), + new SM2SignatureTest(), + new SM4Test(), + new ThreefishTest(), + new TLSKDFTest(), + new WrapTest(), + new X509CertificatePairTest(), + new X509StreamParserTest(), + new XIESTest(), + new XOFTest(), + new ZucTest(), + }; + + public static void main(String[] args) + { + System.setProperty("org.bouncycastle.bks.enable_v1", "true"); + + Security.addProvider(new BouncyCastleProvider()); + + System.out.println("Testing " + Security.getProvider("BC").getInfo() + " version: " + Security.getProvider("BC").getVersion()); + + SimpleTest.runTests(tests); + } +} diff --git a/prov/src/test/jdk1.5/org/bouncycastle/test/JVMVersionTest.java b/prov/src/test/jdk1.5/org/bouncycastle/test/JVMVersionTest.java index 06e26c6851..ca7db6a612 100644 --- a/prov/src/test/jdk1.5/org/bouncycastle/test/JVMVersionTest.java +++ b/prov/src/test/jdk1.5/org/bouncycastle/test/JVMVersionTest.java @@ -12,7 +12,7 @@ * if -Dtest.java.version.prefix=17 and System.getProperty("java.version") = 17.0.4.1 * Then this test will pass. */ -public class JVMVersionTestProv extends TestCase +public class JVMVersionTest extends TestCase { private static final String expectedVersionPropName = "test.java.version.prefix"; diff --git a/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/AllTests21.java b/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/AllTests21.java index 237f78986d..c89ddf6bb1 100644 --- a/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/AllTests21.java +++ b/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/AllTests21.java @@ -11,7 +11,6 @@ public class AllTests21 { public static void main(String[] args) { - PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); } @@ -20,6 +19,8 @@ public static Test suite() TestSuite suite = new TestSuite("JDK21 Provider Tests"); suite.addTestSuite(NTRUKEMTest.class); suite.addTestSuite(SNTRUPrimeKEMTest.class); + suite.addTestSuite(MLKEMTest.class); + suite.addTestSuite(HQCTest.class); return suite; } } diff --git a/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/HQCTest.java b/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/HQCTest.java new file mode 100644 index 0000000000..42f9cefda3 --- /dev/null +++ b/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/HQCTest.java @@ -0,0 +1,174 @@ +package org.bouncycastle.jcacje.provider.test; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; + +import javax.crypto.KEM; +import javax.crypto.SecretKey; + +import org.bouncycastle.jcajce.spec.KEMParameterSpec; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.pqc.jcajce.spec.HQCParameterSpec; +import org.bouncycastle.util.Arrays; + +import junit.framework.TestCase; + +public class HQCTest + extends TestCase +{ + public static void main(String[] args) + throws Exception + { + HQCTest test = new HQCTest(); + test.setUp(); + test.testKEM(); + } + + public void setUp() + { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + } + + public void testKEM() + throws Exception + { + // Receiver side + KeyPairGenerator g = KeyPairGenerator.getInstance("HQC", "BCPQC"); + + g.initialize(HQCParameterSpec.hqc192, new SecureRandom()); + + KeyPair kp = g.generateKeyPair(); + PublicKey pkR = kp.getPublic(); + + // Sender side + KEM kemS = KEM.getInstance("HQC"); + KTSParameterSpec ktsSpec = null; + KEM.Encapsulator e = kemS.newEncapsulator(pkR, ktsSpec, null); + KEM.Encapsulated enc = e.encapsulate(); + SecretKey secS = enc.key(); + byte[] em = enc.encapsulation(); + byte[] params = enc.params(); + + // Receiver side + KEM kemR = KEM.getInstance("HQC"); + KEM.Decapsulator d = kemR.newDecapsulator(kp.getPrivate(), ktsSpec); + SecretKey secR = d.decapsulate(em); + + // secS and secR will be identical + assertEquals(secS.getAlgorithm(), secR.getAlgorithm()); + assertTrue(Arrays.areEqual(secS.getEncoded(), secR.getEncoded())); + } + + public void testBasicKEMAES() + throws Exception + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); + kpg.initialize(HQCParameterSpec.hqc192, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("AES")); + performKEM(kpg.generateKeyPair(), 0, 16, "AES", new KEMParameterSpec("AES")); + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("AES-KWP")); + + try + { + performKEM(kpg.generateKeyPair(), 0, 16, "AES-KWP", new KEMParameterSpec("AES")); + fail(); + } + catch (Exception ex) + { + } + + kpg.initialize(HQCParameterSpec.hqc256, new SecureRandom()); + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("AES")); + + } + + public void testBasicKEMCamellia() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); + kpg.initialize(HQCParameterSpec.hqc128, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KTSParameterSpec.Builder("Camellia", 256).build()); + performKEM(kpg.generateKeyPair(), new KTSParameterSpec.Builder("Camellia-KWP", 256).build()); + } + + public void testBasicKEMSEED() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); + kpg.initialize(HQCParameterSpec.hqc192, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KTSParameterSpec.Builder("SEED", 128).build()); + } + + public void testBasicKEMARIA() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("HQC", "BCPQC"); + kpg.initialize(HQCParameterSpec.hqc192, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("ARIA")); + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("ARIA-KWP")); + } + + private void performKEM(KeyPair kp, int from, int to, String algorithm, KTSParameterSpec ktsParameterSpec) + throws Exception + { + PublicKey pkR = kp.getPublic(); + + // Sender side + KEM kemS = KEM.getInstance("HQC"); + KEM.Encapsulator e = kemS.newEncapsulator(pkR, ktsParameterSpec, null); + KEM.Encapsulated enc = e.encapsulate(from, to, algorithm); + SecretKey secS = enc.key(); + byte[] em = enc.encapsulation(); + + // Receiver side + KEM kemR = KEM.getInstance("HQC"); + KEM.Decapsulator d = kemR.newDecapsulator(kp.getPrivate(), ktsParameterSpec); + SecretKey secR = d.decapsulate(em, from, to, algorithm); + + // secS and secR will be identical + assertEquals(secS.getAlgorithm(), secR.getAlgorithm()); + assertTrue(Arrays.areEqual(secS.getEncoded(), secR.getEncoded())); + } + + private void performKEM(KeyPair kp, KTSParameterSpec ktsParameterSpec) + throws Exception + { + PublicKey pkR = kp.getPublic(); + + // Sender side + KEM kemS = KEM.getInstance("HQC"); + KEM.Encapsulator e = kemS.newEncapsulator(pkR, ktsParameterSpec, null); + KEM.Encapsulated enc = e.encapsulate(); + SecretKey secS = enc.key(); + byte[] em = enc.encapsulation(); + + // Receiver side + KEM kemR = KEM.getInstance("HQC"); + KEM.Decapsulator d = kemR.newDecapsulator(kp.getPrivate(), ktsParameterSpec); + SecretKey secR = d.decapsulate(em); + + // secS and secR will be identical + assertEquals(secS.getAlgorithm(), secR.getAlgorithm()); + assertTrue(Arrays.areEqual(secS.getEncoded(), secR.getEncoded())); + } +} diff --git a/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/MLKEMTest.java b/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/MLKEMTest.java new file mode 100644 index 0000000000..d2dfd9d8d8 --- /dev/null +++ b/prov/src/test/jdk21/org/bouncycastle/jcacje/provider/test/MLKEMTest.java @@ -0,0 +1,163 @@ +package org.bouncycastle.jcacje.provider.test; + +import junit.framework.TestCase; +import org.bouncycastle.jcajce.spec.KEMParameterSpec; +import org.bouncycastle.jcajce.spec.KTSParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; +import org.bouncycastle.util.Arrays; + +import javax.crypto.KEM; +import javax.crypto.SecretKey; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; + + +public class MLKEMTest + extends TestCase +{ + public void setUp() + { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public void testKEM() + throws Exception + { + // Receiver side + KeyPairGenerator g = KeyPairGenerator.getInstance("ML-KEM", "BC"); + + g.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom()); + + KeyPair kp = g.generateKeyPair(); + PublicKey pkR = kp.getPublic(); + + // Sender side + KEM kemS = KEM.getInstance("ML-KEM"); + KTSParameterSpec ktsSpec = null; + KEM.Encapsulator e = kemS.newEncapsulator(pkR, ktsSpec, null); + KEM.Encapsulated enc = e.encapsulate(); + SecretKey secS = enc.key(); + byte[] em = enc.encapsulation(); + byte[] params = enc.params(); + + // Receiver side + KEM kemR = KEM.getInstance("ML-KEM"); + KEM.Decapsulator d = kemR.newDecapsulator(kp.getPrivate(), ktsSpec); + SecretKey secR = d.decapsulate(em); + + // secS and secR will be identical + assertEquals(secS.getAlgorithm(), secR.getAlgorithm()); + assertTrue(Arrays.areEqual(secS.getEncoded(), secR.getEncoded())); + } + + public void testBasicKEMAES() + throws Exception + { + if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) + { + Security.addProvider(new BouncyCastlePQCProvider()); + } + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("AES")); + performKEM(kpg.generateKeyPair(),0, 16, "AES", new KEMParameterSpec("AES")); + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("AES-KWP")); + + try + { + performKEM(kpg.generateKeyPair(),0, 16, "AES-KWP", new KEMParameterSpec("AES")); + fail(); + } + catch (Exception ex) + { + } + + kpg.initialize(MLKEMParameterSpec.ml_kem_1024, new SecureRandom()); + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("AES")); + + + + } + + public void testBasicKEMCamellia() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KTSParameterSpec.Builder("Camellia", 256).build()); + performKEM(kpg.generateKeyPair(), new KTSParameterSpec.Builder("Camellia-KWP", 256).build()); + } + + public void testBasicKEMSEED() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KTSParameterSpec.Builder("SEED", 128).build()); + } + + public void testBasicKEMARIA() + throws Exception + { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM", "BC"); + kpg.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom()); + + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("ARIA")); + performKEM(kpg.generateKeyPair(), new KEMParameterSpec("ARIA-KWP")); + } + + private void performKEM(KeyPair kp, int from, int to, String algorithm, KTSParameterSpec ktsParameterSpec) + throws Exception + { + PublicKey pkR = kp.getPublic(); + + // Sender side + KEM kemS = KEM.getInstance("ML-KEM"); + KEM.Encapsulator e = kemS.newEncapsulator(pkR, ktsParameterSpec, null); + KEM.Encapsulated enc = e.encapsulate(from, to, algorithm); + SecretKey secS = enc.key(); + byte[] em = enc.encapsulation(); + + // Receiver side + KEM kemR = KEM.getInstance("ML-KEM"); + KEM.Decapsulator d = kemR.newDecapsulator(kp.getPrivate(), ktsParameterSpec); + SecretKey secR = d.decapsulate(em, from, to, algorithm); + + // secS and secR will be identical + assertEquals(secS.getAlgorithm(), secR.getAlgorithm()); + assertTrue(Arrays.areEqual(secS.getEncoded(), secR.getEncoded())); + } + + private void performKEM(KeyPair kp, KTSParameterSpec ktsParameterSpec) + throws Exception + { + PublicKey pkR = kp.getPublic(); + + // Sender side + KEM kemS = KEM.getInstance("ML-KEM"); + KEM.Encapsulator e = kemS.newEncapsulator(pkR, ktsParameterSpec, null); + KEM.Encapsulated enc = e.encapsulate(); + SecretKey secS = enc.key(); + byte[] em = enc.encapsulation(); + + // Receiver side + KEM kemR = KEM.getInstance("ML-KEM"); + KEM.Decapsulator d = kemR.newDecapsulator(kp.getPrivate(), ktsParameterSpec); + SecretKey secR = d.decapsulate(em); + + // secS and secR will be identical + assertEquals(secS.getAlgorithm(), secR.getAlgorithm()); + assertTrue(Arrays.areEqual(secS.getEncoded(), secR.getEncoded())); + } +} diff --git a/run_mtt.sh b/run_mtt.sh new file mode 100755 index 0000000000..ed60f4fd54 --- /dev/null +++ b/run_mtt.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +set -e + +export script_loc=$( cd -- "$( dirname -- "$0" )" &> /dev/null && pwd ) +version=$(fgrep version "$script_loc/gradle.properties" | sed -e "s/version=//") + +echo "" +echo "Module dependency testing" +echo "" + +# +# This is an internal tool used to verify that classes needed by one module +# are correctly exported by another module. +# + +levels=( "9" "11" "17" "21" ) + +for level in "${levels[@]}" +do +echo "---------------------------------------------------------------------" +echo "Start ${level}" + +( + echo "With Jakarta mail.." + modtest \ + -scan "${script_loc}/jmail/build/libs/bcjmail-jdk18on-${version}.jar" \ + -scan "${script_loc}/mls/build/libs/bcmls-jdk18on-${version}.jar" \ + -scan "${script_loc}/pg/build/libs/bcpg-jdk18on-${version}.jar" \ + -scan "${script_loc}/pkix/build/libs/bcpkix-jdk18on-${version}.jar" \ + -scan "${script_loc}/prov/build/libs/bcprov-jdk18on-${version}.jar" \ + -scan "${script_loc}/tls/build/libs/bctls-jdk18on-${version}.jar" \ + -scan "${script_loc}/util/build/libs/bcutil-jdk18on-${version}.jar" \ + -include "^org\.bouncycastle\..*" \ + -ignore "^java\..*" \ + -ignore "^javax\..*" \ + -ignore "^jakarta\..*" \ + -ignore "^io\.grpc\..*" \ + -ignore "^com\.google\..*" \ + -ignore "^com\.sun\..*" \ + -jvmlevel ${level} +) + +( # mail + echo "With Java mail.." + modtest \ + -scan "${script_loc}/mail/build/libs/bcmail-jdk18on-${version}.jar" \ + -scan "${script_loc}/mls/build/libs/bcmls-jdk18on-${version}.jar" \ + -scan "${script_loc}/pg/build/libs/bcpg-jdk18on-${version}.jar" \ + -scan "${script_loc}/pkix/build/libs/bcpkix-jdk18on-${version}.jar" \ + -scan "${script_loc}/prov/build/libs/bcprov-jdk18on-${version}.jar" \ + -scan "${script_loc}/tls/build/libs/bctls-jdk18on-${version}.jar" \ + -scan "${script_loc}/util/build/libs/bcutil-jdk18on-${version}.jar" \ + -include "^org\.bouncycastle\..*" \ + -ignore "^java\..*" \ + -ignore "^javax\..*" \ + -ignore "^jakarta\..*" \ + -ignore "^io\.grpc\..*" \ + -ignore "^com\.google\..*" \ + -ignore "^com\.sun\..*" \ + -jvmlevel ${level} +) + echo "End java ${level}" + echo "" +done \ No newline at end of file diff --git a/scripts/jdk1.1ed.sh b/scripts/jdk1.1ed.sh index f3ea90bb3d..775c4db3df 100644 --- a/scripts/jdk1.1ed.sh +++ b/scripts/jdk1.1ed.sh @@ -186,7 +186,8 @@ done for f in org/bouncycastle/pqc/crypto/*/*.java org/bouncycastle/pqc/crypto/*/*/*.java do ed $f <<%% -g/ final /s/final// +g/private final /s/final// +g/ final /s/final// w q %% @@ -721,3 +722,8 @@ w q % +ed org/bouncycastle/cms/PKIXRecipientId.java <<% +g/protected.*final.*;/s/final// +w +q +% diff --git a/scripts/jdk1.2ed.sh b/scripts/jdk1.2ed.sh index 2cf02fd733..c33336a23c 100644 --- a/scripts/jdk1.2ed.sh +++ b/scripts/jdk1.2ed.sh @@ -1,7 +1,7 @@ # # JDK 1.2 edits -for i in org/bouncycastle/pqc/jcajce/provider/*/*.java org/bouncycastle/pqc/*/*/*.java org/bouncycastle/pqc/*/*/*/*.java org/bouncycastle/crypto/digests/*.java org/bouncycastle/cert/cmp/*.java org/bouncycastle/crypto/engines/*.java org/bouncycastle/openpgp/operator/*.java org/bouncycastle/openpgp/operator/jcajce/*.java org/bouncycastle/openpgp/operator/bc/*.java org/bouncycastle/openpgp/*.java org/bouncycastle/bcpg/*.java org/bouncycastle/openpgp/test/*.java org/bouncycastle/bcpg/sig/* org/bouncycastle/cms/* org/bouncycastle/pkcs/* org/bouncycastle/gpg/* +for i in org/bouncycastle/pqc/jcajce/provider/*/*.java org/bouncycastle/pqc/*/*/*.java org/bouncycastle/pqc/*/*/*/*.java org/bouncycastle/crypto/digests/*.java org/bouncycastle/cert/cmp/*.java org/bouncycastle/crypto/engines/*.java org/bouncycastle/openpgp/operator/*.java org/bouncycastle/openpgp/operator/jcajce/*.java org/bouncycastle/openpgp/operator/bc/*.java org/bouncycastle/openpgp/*.java org/bouncycastle/bcpg/*.java org/bouncycastle/openpgp/test/*.java org/bouncycastle/bcpg/test/*.java org/bouncycastle/bcpg/sig/* org/bouncycastle/cms/* org/bouncycastle/pkcs/* org/bouncycastle/gpg/* org/bouncycastle/test/*.java org/bouncycastle/jcajce/provider/asymmetric/*.java org/bouncycastle/jcajce/provider/asymmetric/*/*.java do ed $i <<%% g/ .Override/d @@ -10,6 +10,7 @@ g/ .Deprecated/d g/ .Deprecated/d g/ .FunctionalInterface/d g/ .FunctionalInterface/d +g/StringBuilder/s//StringBuffer/g w q %% @@ -51,6 +52,18 @@ w q % +ed org/bouncycastle/jcajce/spec/KEMGenerateSpec.java <<% +g/private final/s/final// +w +q +% + +ed org/bouncycastle/jcajce/spec/KEMExtractSpec.java <<% +g/private final/s/final// +w +q +% + ed org/bouncycastle/asn1/cmc/CertificationRequest.java <<% g/private final/s/final// w diff --git a/tls/build.gradle b/tls/build.gradle index b012f3d14d..c413bd6221 100644 --- a/tls/build.gradle +++ b/tls/build.gradle @@ -22,15 +22,15 @@ sourceSets { java { compileClasspath += main.output + test.output runtimeClasspath += test.output - srcDir(files("src/test/jdk1.11", "src/test/java")) + srcDir(files("src/test/jdk1.11")) } } - test17 { + test15 { java { compileClasspath += main.output + test.output runtimeClasspath += test.output - srcDir(files("src/test/jdk1.11","src/test/jdk1.15", "src/test/java")) + srcDir(files("src/test/jdk1.15")) } } @@ -38,19 +38,18 @@ sourceSets { java { compileClasspath += main.output + test.output runtimeClasspath += test.output - srcDir(files("src/test/jdk1.11","src/test/jdk1.15","src/test/jdk21", "src/test/java")) + srcDir(files("src/test/jdk21")) } } } dependencies { - implementation project(':core') + implementation project(':prov') implementation project(':util') implementation project(':pkix') - java9Implementation project(':core') java9Implementation project(':prov') java9Implementation project(':util') java9Implementation project(':pkix') @@ -59,72 +58,63 @@ dependencies { } test11Implementation group: 'junit', name: 'junit', version: '4.13.2' - test17Implementation group: 'junit', name: 'junit', version: '4.13.2' + test15Implementation group: 'junit', name: 'junit', version: '4.13.2' test21Implementation group: 'junit', name: 'junit', version: '4.13.2' - test11Implementation project(':core') test11Implementation project(':prov') test11Implementation project(':util') test11Implementation project(':pkix') - test17Implementation project(':core') - test17Implementation project(':prov') - test17Implementation project(':util') - test17Implementation project(':pkix') + test15Implementation project(':prov') + test15Implementation project(':util') + test15Implementation project(':pkix') - test21Implementation project(':core') test21Implementation project(':prov') test21Implementation project(':util') test21Implementation project(':pkix') } + +evaluationDependsOn(":prov") +evaluationDependsOn(":util") +evaluationDependsOn(":pkix") + compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + options.release = 8 } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 9 - targetCompatibility = 9 + + options.release = 9 + + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" + def util_jar="${project(":util").jar.outputs.files.getFiles().getAt(0)}" + def pkix_jar="${project(":pkix").jar.outputs.files.getFiles().getAt(0)}" + + options.compilerArgs += [ - '--module-path', "${bc_prov}${File.pathSeparator}${bc_util}${File.pathSeparator}${bc_pkix}" + '--module-path', "${prov_jar}${File.pathSeparator}${util_jar}${File.pathSeparator}${pkix_jar}" ] options.sourcepath = files(['src/main/java', 'src/main/jdk1.9']) } compileTest11Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 11 - targetCompatibility = 11 + + options.release = 11 options.sourcepath = files(['src/test/java', 'src/test/jdk1.11']) } -compileTest17Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - sourceCompatibility = 17 - targetCompatibility = 17 +compileTest15Java { + options.release = 15 options.sourcepath = files(['src/test/java', 'src/test/jdk1.15']) } compileTest21Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(21) - } - sourceCompatibility = 21 - targetCompatibility = 21 + + options.release = 21 options.sourcepath = files(['src/test/java', 'src/test/jdk21']) } @@ -145,12 +135,14 @@ jar { into('META-INF/versions/9') { from sourceSets.java9.output } + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bctls') manifest.attributes('Bundle-SymbolicName': 'bctls') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': 'org.bouncycastle.{jsse|tls}.*') - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.{jsse|tls}.*,org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "org.bouncycastle.{jsse|tls}.*;version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!org.bouncycastle.{jsse|tls}.*,org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") } @@ -166,13 +158,54 @@ artifacts { archives sourcesJar } -test { - jvmArgs = ['-Dtest.java.version.prefix=1.8'] +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bctls-$vmrange" + from components.java + + artifact(javadocJar) + artifact(sourcesJar) + } + + } } -task test11(type: Test) { + +task test8(type: Test) { + onlyIf {System.getenv("BC_JDK8") != null} + testClassesDirs = sourceSets.test.output.classesDirs + classpath = sourceSets.test.runtimeClasspath + files(jar.archiveFile) + + forkEvery = 1; + maxParallelForks = 8; + + systemProperty 'bc.test.data.home', bcTestDataHome + maxHeapSize = "1536m" + testLogging.showStandardStreams = false + + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(8) + } + + jvmArgs = ['-Dtest.java.version.prefix=1.8'] + + + finalizedBy jacocoTestReport + + filter { + includeTestsMatching "AllTest*" + if (project.hasProperty('excludeTests')) { + excludeTestsMatching "${excludeTests}" + } + } +} + +task test11(type: Test) { + onlyIf {System.getenv("BC_JDK11") != null} dependsOn(jar) testClassesDirs = sourceSets.test11.output.classesDirs @@ -183,13 +216,13 @@ task test11(type: Test) { systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(11) } - jvmArgs = ['-Dtest.java.version.prefix=11.'] + jvmArgs = ['-Dtest.java.version.prefix=11'] finalizedBy jacocoTestReport @@ -202,27 +235,27 @@ task test11(type: Test) { } } -task test17(type: Test) { +task test15(type: Test) { // This is testing the 1.15 code base - + onlyIf {System.getenv("BC_JDK17") != null} dependsOn jar - testClassesDirs = sourceSets.test17.output.classesDirs - classpath = sourceSets.test17.runtimeClasspath + files(jar.archiveFile) + testClassesDirs = sourceSets.test15.output.classesDirs + classpath = sourceSets.test15.runtimeClasspath + files(jar.archiveFile) forkEvery = 1; maxParallelForks = 8; systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(17) } - jvmArgs = ['-Dtest.java.version.prefix=17.'] + jvmArgs = ['-Dtest.java.version.prefix=17'] finalizedBy jacocoTestReport @@ -238,7 +271,7 @@ task test17(type: Test) { task test21(type: Test) { // This is testing the 21 code base - + onlyIf {System.getenv("BC_JDK21") != null} dependsOn jar testClassesDirs = sourceSets.test21.output.classesDirs @@ -249,7 +282,7 @@ task test21(type: Test) { systemProperty 'bc.test.data.home', bcTestDataHome maxHeapSize = "1536m" - testLogging.showStandardStreams = true + testLogging.showStandardStreams = false javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) @@ -267,3 +300,27 @@ task test21(type: Test) { } } } + +if (System.getenv("BC_JDK8") != null) { + System.out.println("${project.name}: Adding test8 as dependency for test task because BC_JDK8 is defined") + test.dependsOn("test8") +} + +if (System.getenv("BC_JDK11") != null) { + System.out.println("${project.name}: Adding test11 as dependency for test task because BC_JDK11 is defined") + test.dependsOn("test11") +} + +if (System.getenv("BC_JDK17") != null) { + System.out.println("${project.name}: Adding test15 as dependency for test task because BC_JDK17 is defined") + test.dependsOn("test15") +} + +if (System.getenv("BC_JDK21") != null) { + System.out.println("${project.name}: Adding test21 as dependency for test task because BC_JDK21 is defined") + test.dependsOn("test21") +} + + + +compileJava9Java.dependsOn([":prov:jar", ":util:jar",":pkix:jar"]) \ No newline at end of file diff --git a/tls/src/main/java/org/bouncycastle/jsse/BCSSLParameters.java b/tls/src/main/java/org/bouncycastle/jsse/BCSSLParameters.java index c37d9a3161..11992286e0 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/BCSSLParameters.java +++ b/tls/src/main/java/org/bouncycastle/jsse/BCSSLParameters.java @@ -37,10 +37,12 @@ private static List copyList(Collection list) private List serverNames; private List sniMatchers; private boolean useCipherSuitesOrder; + private boolean useNamedGroupsOrder; private boolean enableRetransmissions = true; private int maximumPacketSize = 0; private String[] applicationProtocols = TlsUtils.EMPTY_STRINGS; private String[] signatureSchemes = null; + private String[] signatureSchemesCert = null; private String[] namedGroups = null; public BCSSLParameters() @@ -188,6 +190,16 @@ public void setUseCipherSuitesOrder(boolean useCipherSuitesOrder) this.useCipherSuitesOrder = useCipherSuitesOrder; } + public boolean getUseNamedGroupsOrder() + { + return useNamedGroupsOrder; + } + + public void setUseNamedGroupsOrder(boolean useNamedGroupsOrder) + { + this.useNamedGroupsOrder = useNamedGroupsOrder; + } + public boolean getEnableRetransmissions() { return enableRetransmissions; @@ -261,6 +273,30 @@ public void setSignatureSchemes(String[] signatureSchemes) this.signatureSchemes = check; } + public String[] getSignatureSchemesCert() + { + return TlsUtils.clone(signatureSchemesCert); + } + + public void setSignatureSchemesCert(String[] signatureSchemesCert) + { + String[] check = null; + + if (signatureSchemesCert != null) + { + check = TlsUtils.clone(signatureSchemesCert); + for (String entry : check) + { + if (TlsUtils.isNullOrEmpty(entry)) + { + throw new IllegalArgumentException("'signatureSchemesCert' entries cannot be null or empty strings"); + } + } + } + + this.signatureSchemesCert = check; + } + public String[] getNamedGroups() { return TlsUtils.clone(namedGroups); diff --git a/tls/src/main/java/org/bouncycastle/jsse/package-info.java b/tls/src/main/java/org/bouncycastle/jsse/package-info.java new file mode 100644 index 0000000000..d315b65a8e --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/jsse/package-info.java @@ -0,0 +1,4 @@ +/** + * BC specific classes and interfaces for use with the BCJSSE JSSE provider. + */ +package org.bouncycastle.jsse; diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/BouncyCastleJsseProvider.java b/tls/src/main/java/org/bouncycastle/jsse/provider/BouncyCastleJsseProvider.java index 0ac640de80..b466a3c397 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/BouncyCastleJsseProvider.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/BouncyCastleJsseProvider.java @@ -26,13 +26,14 @@ public class BouncyCastleJsseProvider private static final String JSSE_CONFIG_PROPERTY = "org.bouncycastle.jsse.config"; - private static final double PROVIDER_VERSION = 1.0019; - private static final String PROVIDER_INFO = "Bouncy Castle JSSE Provider Version 1.0.19"; + private static final double PROVIDER_VERSION = 1.0021; + private static final String PROVIDER_INFO = "Bouncy Castle JSSE Provider Version 1.0.21"; private final Map serviceMap = new ConcurrentHashMap(); private final Map creatorMap = new HashMap(); - private final boolean isInFipsMode; + private final boolean configFipsMode; + private final JcaTlsCryptoProvider configCryptoProvider; public BouncyCastleJsseProvider() { @@ -43,7 +44,10 @@ public BouncyCastleJsseProvider(boolean fipsMode) { super(PROVIDER_NAME, PROVIDER_VERSION, PROVIDER_INFO); - this.isInFipsMode = configure(fipsMode, new JcaTlsCryptoProvider()); + this.configFipsMode = fipsMode; + this.configCryptoProvider = new JcaTlsCryptoProvider(); + + configure(); } public BouncyCastleJsseProvider(Provider provider) @@ -55,7 +59,10 @@ public BouncyCastleJsseProvider(boolean fipsMode, Provider provider) { super(PROVIDER_NAME, PROVIDER_VERSION, PROVIDER_INFO); - this.isInFipsMode = configure(fipsMode, new JcaTlsCryptoProvider().setProvider(provider)); + this.configFipsMode = fipsMode; + this.configCryptoProvider = new JcaTlsCryptoProvider().setProvider(provider); + + configure(); } public BouncyCastleJsseProvider(String config) @@ -66,6 +73,7 @@ public BouncyCastleJsseProvider(String config) boolean fipsMode = false; String cryptoName = config; + String altCryptoName = null; int colonPos = config.indexOf(':'); if (colonPos >= 0) @@ -74,27 +82,44 @@ public BouncyCastleJsseProvider(String config) String second = config.substring(colonPos + 1).trim(); fipsMode = first.equalsIgnoreCase("fips"); - cryptoName = second; + config = second; + } + + int commaPos = config.indexOf(','); + if (commaPos >= 0) + { + cryptoName = config.substring(0, commaPos).trim(); + altCryptoName = config.substring(commaPos + 1).trim(); + } + else + { + cryptoName = config; } JcaTlsCryptoProvider cryptoProvider; try { - cryptoProvider = createCryptoProvider(cryptoName); + cryptoProvider = createCryptoProvider(cryptoName, altCryptoName); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("unable to set up JcaTlsCryptoProvider: " + e.getMessage(), e); } - this.isInFipsMode = configure(fipsMode, cryptoProvider); + this.configFipsMode = fipsMode; + this.configCryptoProvider = cryptoProvider; + + configure(); } - public BouncyCastleJsseProvider(boolean fipsMode, JcaTlsCryptoProvider tlsCryptoProvider) + public BouncyCastleJsseProvider(boolean fipsMode, JcaTlsCryptoProvider cryptoProvider) { super(PROVIDER_NAME, PROVIDER_VERSION, PROVIDER_INFO); - this.isInFipsMode = configure(fipsMode, tlsCryptoProvider); + this.configFipsMode = fipsMode; + this.configCryptoProvider = cryptoProvider; + + configure(); } // for Java 11 @@ -103,7 +128,7 @@ public Provider configure(String configArg) return new BouncyCastleJsseProvider(configArg); } - private JcaTlsCryptoProvider createCryptoProvider(String cryptoName) + private JcaTlsCryptoProvider createCryptoProvider(String cryptoName, String altCryptoName) throws GeneralSecurityException { if (cryptoName.equalsIgnoreCase("default")) @@ -114,9 +139,18 @@ private JcaTlsCryptoProvider createCryptoProvider(String cryptoName) Provider provider = Security.getProvider(cryptoName); if (provider != null) { - return new JcaTlsCryptoProvider().setProvider(provider); + JcaTlsCryptoProvider cryptoProvider = new JcaTlsCryptoProvider().setProvider(provider); + + if (altCryptoName != null) + { + // this has to be done by name as a PKCS#11 login may be required. + cryptoProvider.setAlternateProvider(altCryptoName); + } + + return cryptoProvider; } + // TODO: should we support alt name here? try { Class cryptoProviderClass = Class.forName(cryptoName); @@ -150,8 +184,11 @@ private JcaTlsCryptoProvider createCryptoProvider(String cryptoName) } } - private boolean configure(final boolean fipsMode, final JcaTlsCryptoProvider cryptoProvider) + private void configure() { + final boolean fipsMode = configFipsMode; + final JcaTlsCryptoProvider cryptoProvider = configCryptoProvider; + // TODO[jsse]: should X.509 be an alias. addAlgorithmImplementation("KeyManagerFactory.X.509", "org.bouncycastle.jsse.provider.KeyManagerFactory", new EngineCreator() { @@ -218,15 +255,14 @@ public Object createInstance(Object constructorParameter) addAlgorithmImplementation("SSLContext.DEFAULT", "org.bouncycastle.jsse.provider.SSLContext.Default", new EngineCreator() { - public Object createInstance(Object constructorParameter) throws GeneralSecurityException + public Object createInstance(Object constructorParameter) + throws GeneralSecurityException { return new DefaultSSLContextSpi(fipsMode, cryptoProvider); } }); addAlias("Alg.Alias.SSLContext.SSL", "TLS"); addAlias("Alg.Alias.SSLContext.SSLV3", "TLSV1"); - - return fipsMode; } void addAttribute(String key, String attributeName, String attributeValue) @@ -267,7 +303,7 @@ public final Provider.Service getService(String type, String algorithm) { String upperCaseAlgName = Strings.toUpperCase(algorithm); String serviceKey = type + "." + upperCaseAlgName; - + BcJsseService service = serviceMap.get(serviceKey); if (service == null) @@ -331,7 +367,7 @@ public synchronized final Set getServices() Set serviceSet = super.getServices(); Set bcServiceSet = new HashSet(); - for (Provider.Service service: serviceSet) + for (Provider.Service service : serviceSet) { bcServiceSet.add(getService(service.getType(), service.getAlgorithm())); } @@ -372,7 +408,7 @@ private static List specifyClientProtocols(String... protocols) public boolean isFipsMode() { - return isInFipsMode; + return configFipsMode; } private static class BcJsseService @@ -391,7 +427,7 @@ private static class BcJsseService * @param attributes Map of attributes or null if this implementation * has no attributes * @throws NullPointerException if provider, type, algorithm, or - * className is null + * className is null */ public BcJsseService(Provider provider, String type, String algorithm, String className, List aliases, Map attributes, EngineCreator creator) { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ContextData.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ContextData.java index bda556fe0c..11eab8b6b9 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ContextData.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ContextData.java @@ -1,36 +1,199 @@ package org.bouncycastle.jsse.provider; +import java.util.ArrayList; +import java.util.Comparator; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import java.util.Vector; import org.bouncycastle.jsse.BCX509ExtendedKeyManager; import org.bouncycastle.jsse.BCX509ExtendedTrustManager; +import org.bouncycastle.jsse.java.security.BCAlgorithmConstraints; +import org.bouncycastle.jsse.java.security.BCCryptoPrimitive; import org.bouncycastle.tls.ProtocolVersion; import org.bouncycastle.tls.SignatureAndHashAlgorithm; +import org.bouncycastle.tls.TlsUtils; import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto; final class ContextData { - private final ProvSSLContextSpi context; + private static final Set TLS_CRYPTO_PRIMITIVES_BC = JsseUtils.KEY_AGREEMENT_CRYPTO_PRIMITIVES_BC; + + private final boolean fipsMode; private final JcaTlsCrypto crypto; private final BCX509ExtendedKeyManager x509KeyManager; private final BCX509ExtendedTrustManager x509TrustManager; + private final Map supportedCipherSuites; + private final Map supportedProtocols; + private final String[] defaultCipherSuitesClient; + private final String[] defaultCipherSuitesServer; + private final String[] defaultProtocolsClient; + private final String[] defaultProtocolsServer; private final ProvSSLSessionContext clientSessionContext; private final ProvSSLSessionContext serverSessionContext; private final NamedGroupInfo.PerContext namedGroups; private final SignatureSchemeInfo.PerContext signatureSchemes; - ContextData(ProvSSLContextSpi context, JcaTlsCrypto crypto, BCX509ExtendedKeyManager x509KeyManager, - BCX509ExtendedTrustManager x509TrustManager) + ContextData(boolean fipsMode, JcaTlsCrypto crypto, BCX509ExtendedKeyManager x509KeyManager, + BCX509ExtendedTrustManager x509TrustManager, Map supportedCipherSuites, + Map supportedProtocols, String[] defaultCipherSuitesClient, + String[] defaultCipherSuitesServer, String[] defaultProtocolsClient, String[] defaultProtocolsServer) { - this.context = context; + this.fipsMode = fipsMode; this.crypto = crypto; this.x509KeyManager = x509KeyManager; this.x509TrustManager = x509TrustManager; + this.supportedCipherSuites = supportedCipherSuites; + this.supportedProtocols = supportedProtocols; + this.defaultCipherSuitesClient = defaultCipherSuitesClient; + this.defaultCipherSuitesServer = defaultCipherSuitesServer; + this.defaultProtocolsClient = defaultProtocolsClient; + this.defaultProtocolsServer = defaultProtocolsServer; this.clientSessionContext = new ProvSSLSessionContext(this); this.serverSessionContext = new ProvSSLSessionContext(this); - this.namedGroups = NamedGroupInfo.createPerContext(context.isFips(), crypto); - this.signatureSchemes = SignatureSchemeInfo.createPerContext(context.isFips(), crypto, namedGroups); + this.namedGroups = NamedGroupInfo.createPerContext(fipsMode, crypto); + this.signatureSchemes = SignatureSchemeInfo.createPerContext(fipsMode, crypto, namedGroups); + } + + int[] getActiveCipherSuites(JcaTlsCrypto crypto, ProvSSLParameters sslParameters, + ProtocolVersion[] activeProtocolVersions) + { + String[] enabledCipherSuites = sslParameters.getCipherSuitesArray(); + BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints(); + + ProtocolVersion latest = ProtocolVersion.getLatestTLS(activeProtocolVersions); + ProtocolVersion earliest = ProtocolVersion.getEarliestTLS(activeProtocolVersions); + + boolean post13Active = TlsUtils.isTLSv13(latest); + boolean pre13Active = !TlsUtils.isTLSv13(earliest); + + int[] candidates = new int[enabledCipherSuites.length]; + + int count = 0; + for (String enabledCipherSuite : enabledCipherSuites) + { + CipherSuiteInfo candidate = supportedCipherSuites.get(enabledCipherSuite); + if (null == candidate) + { + continue; + } + if (candidate.isTLSv13()) + { + if (!post13Active) + { + continue; + } + } + else + { + if (!pre13Active) + { + continue; + } + } + if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledCipherSuite, null)) + { + continue; + } + + /* + * TODO[jsse] SunJSSE also checks that the cipher suite is usable for at least one of + * the active protocol versions. Also, if the cipher suite involves a key exchange, + * there must be at least one suitable NamedGroup available. + */ + + candidates[count++] = candidate.getCipherSuite(); + } + + /* + * TODO Move cipher suite management into CipherSuiteInfo (PerConnection/PerContext pattern + * like NamedGroupInfo) to avoid unnecessary repetition of these sorts of checks. + */ + int[] result = TlsUtils.getSupportedCipherSuites(crypto, candidates, 0, count); + + if (result.length < 1) + { + // TODO[jsse] Refactor so that this can be an SSLHandshakeException? + throw new IllegalStateException("No usable cipher suites enabled"); + } + + return result; + } + + ProtocolVersion[] getActiveProtocolVersions(ProvSSLParameters sslParameters) + { +// String[] enabledCipherSuites = sslParameters.getCipherSuitesArray(); + String[] enabledProtocols = sslParameters.getProtocolsArray(); + BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints(); + + SortedSet result = new TreeSet(new Comparator() + { + public int compare(ProtocolVersion o1, ProtocolVersion o2) + { + return o1.isLaterVersionOf(o2) ? -1 : o2.isLaterVersionOf(o1) ? 1 : 0; + } + }); + + for (String enabledProtocol : enabledProtocols) + { + ProtocolVersion candidate = supportedProtocols.get(enabledProtocol); + if (null == candidate) + { + continue; + } + if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledProtocol, null)) + { + continue; + } + + /* + * TODO[jsse] SunJSSE also checks that there is at least one "activatable" cipher suite + * that could be used for this protocol version. + */ + + result.add(candidate); + } + + if (result.isEmpty()) + { + // TODO[jsse] Refactor so that this can be an SSLHandshakeException? + throw new IllegalStateException("No usable protocols enabled"); + } + + return result.toArray(new ProtocolVersion[result.size()]); + } + + ProvSSLSessionContext getClientSessionContext() + { + return clientSessionContext; + } + + JcaTlsCrypto getCrypto() + { + return crypto; + } + + String[] getDefaultCipherSuites(boolean isClient) + { + return implGetDefaultCipherSuites(isClient).clone(); + } + + String[] getDefaultProtocols(boolean isClient) + { + return implGetDefaultProtocols(isClient).clone(); + } + + ProvSSLParameters getDefaultSSLParameters(boolean isClient) + { + return new ProvSSLParameters(this, implGetDefaultCipherSuites(isClient), implGetDefaultProtocols(isClient)); + } + + ProvSSLParameters getSupportedSSLParameters(boolean isClient) + { + return new ProvSSLParameters(this, getSupportedCipherSuites(), getSupportedProtocols()); } NamedGroupInfo.PerConnection getNamedGroupsClient(ProvSSLParameters sslParameters, @@ -45,6 +208,11 @@ NamedGroupInfo.PerConnection getNamedGroupsServer(ProvSSLParameters sslParameter return NamedGroupInfo.createPerConnectionServer(namedGroups, sslParameters, negotiatedVersion); } + ProvSSLSessionContext getServerSessionContext() + { + return serverSessionContext; + } + SignatureSchemeInfo.PerConnection getSignatureSchemesClient(ProvSSLParameters sslParameters, ProtocolVersion[] activeProtocolVersions, NamedGroupInfo.PerConnection namedGroups) { @@ -59,29 +227,44 @@ SignatureSchemeInfo.PerConnection getSignatureSchemesServer(ProvSSLParameters ss namedGroups); } - ProvSSLContextSpi getContext() + List getSignatureSchemes(Vector sigAndHashAlgs) { - return context; + return SignatureSchemeInfo.getSignatureSchemes(signatureSchemes, sigAndHashAlgs); } - JcaTlsCrypto getCrypto() + String[] getSupportedCipherSuites() { - return crypto; + return JsseUtils.getKeysArray(supportedCipherSuites); } - ProvSSLSessionContext getClientSessionContext() + String[] getSupportedCipherSuites(String[] cipherSuites) { - return clientSessionContext; - } + if (null == cipherSuites) + { + throw new NullPointerException("'cipherSuites' cannot be null"); + } - ProvSSLSessionContext getServerSessionContext() - { - return serverSessionContext; + ArrayList result = new ArrayList(cipherSuites.length); + for (String cipherSuite : cipherSuites) + { + if (TlsUtils.isNullOrEmpty(cipherSuite)) + { + throw new IllegalArgumentException("'cipherSuites' cannot contain null or empty string elements"); + } + + if (supportedCipherSuites.containsKey(cipherSuite)) + { + result.add(cipherSuite); + } + } + + // NOTE: This method must always return a copy, so no fast path when all supported + return JsseUtils.getArray(result); } - List getSignatureSchemes(Vector sigAndHashAlgs) + String[] getSupportedProtocols() { - return SignatureSchemeInfo.getSignatureSchemes(signatureSchemes, sigAndHashAlgs); + return JsseUtils.getKeysArray(supportedProtocols); } BCX509ExtendedKeyManager getX509KeyManager() @@ -93,4 +276,75 @@ BCX509ExtendedTrustManager getX509TrustManager() { return x509TrustManager; } + + boolean isFipsMode() + { + return fipsMode; + } + + boolean isSupportedProtocols(String[] protocols) + { + if (protocols == null) + { + return false; + } + for (String protocol : protocols) + { + if (protocol == null || !supportedProtocols.containsKey(protocol)) + { + return false; + } + } + return true; + } + + void updateDefaultSSLParameters(ProvSSLParameters sslParameters, boolean isClient) + { + if (sslParameters.getCipherSuitesArray() == implGetDefaultCipherSuites(!isClient)) + { + sslParameters.setCipherSuitesArray(implGetDefaultCipherSuites(isClient)); + } + if (sslParameters.getProtocolsArray() == implGetDefaultProtocols(!isClient)) + { + sslParameters.setProtocolsArray(implGetDefaultProtocols(isClient)); + } + } + + String validateNegotiatedCipherSuite(ProvSSLParameters sslParameters, int cipherSuite) + { + // NOTE: The redundancy among these various checks is intentional + String name = ProvSSLContextSpi.getCipherSuiteName(cipherSuite); + if (null == name + || !JsseUtils.contains(sslParameters.getCipherSuitesArray(), name) + || !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null) + || !supportedCipherSuites.containsKey(name)) + { + throw new IllegalStateException("SSL connection negotiated unsupported ciphersuite: " + cipherSuite); + } + return name; + } + + String validateNegotiatedProtocol(ProvSSLParameters sslParameters, ProtocolVersion protocol) + { + // NOTE: The redundancy among these various checks is intentional + String name = ProvSSLContextSpi.getProtocolVersionName(protocol); + if (null == name + || !JsseUtils.contains(sslParameters.getProtocolsArray(), name) + || !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null) + || !supportedProtocols.containsKey(name)) + { + throw new IllegalStateException("SSL connection negotiated unsupported protocol: " + protocol); + } + return name; + } + + private String[] implGetDefaultCipherSuites(boolean isClient) + { + return isClient ? defaultCipherSuitesClient : defaultCipherSuitesServer; + } + + private String[] implGetDefaultProtocols(boolean isClient) + { + return isClient ? defaultProtocolsClient : defaultProtocolsServer; + } } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/DefaultSSLContextSpi.java b/tls/src/main/java/org/bouncycastle/jsse/provider/DefaultSSLContextSpi.java index 235a89d10d..0a61878776 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/DefaultSSLContextSpi.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/DefaultSSLContextSpi.java @@ -106,9 +106,9 @@ static ProvSSLContextSpi getDefaultInstance() throws Exception return LazyInstance.instance; } - DefaultSSLContextSpi(boolean isInFipsMode, JcaTlsCryptoProvider cryptoProvider) throws KeyManagementException + DefaultSSLContextSpi(boolean fipsMode, JcaTlsCryptoProvider cryptoProvider) throws KeyManagementException { - super(isInFipsMode, cryptoProvider, null); + super(fipsMode, cryptoProvider, null); if (null != LazyManagers.initException) { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/DisabledAlgorithmConstraints.java b/tls/src/main/java/org/bouncycastle/jsse/provider/DisabledAlgorithmConstraints.java index ffc92a4ed1..8a4f35da72 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/DisabledAlgorithmConstraints.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/DisabledAlgorithmConstraints.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Set; import java.util.StringTokenizer; +import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.SecretKey; @@ -53,8 +54,8 @@ static DisabledAlgorithmConstraints create(AlgorithmDecomposer decomposer, Strin } } - return new DisabledAlgorithmConstraints(decomposer, Collections.unmodifiableSet(disabledAlgorithms), - Collections.unmodifiableMap(constraintsMap)); + return new DisabledAlgorithmConstraints(decomposer, propertyName, + Collections.unmodifiableSet(disabledAlgorithms), Collections.unmodifiableMap(constraintsMap)); } private static boolean addConstraint(Set disabledAlgorithms, Map> constraintsMap, @@ -151,27 +152,16 @@ private static String getConstraintsAlgorithm(String algorithm, AlgorithmParamet return null; } - private static String getConstraintsAlgorithm(Key key) - { - if (null != key) - { - String keyAlgorithm = JsseUtils.getKeyAlgorithm(key); - if (null != keyAlgorithm) - { - return getCanonicalAlgorithm(keyAlgorithm); - } - } - return null; - } - + private final String logHeader; private final Set disabledAlgorithms; private final Map> constraintsMap; - private DisabledAlgorithmConstraints(AlgorithmDecomposer decomposer, Set disabledAlgorithms, - Map> constraintsMap) + private DisabledAlgorithmConstraints(AlgorithmDecomposer decomposer, String propertyName, + Set disabledAlgorithms, Map> constraintsMap) { super(decomposer); + this.logHeader = "[" + propertyName + "]"; this.disabledAlgorithms = disabledAlgorithms; this.constraintsMap = constraintsMap; } @@ -181,20 +171,7 @@ public final boolean permits(Set primitives, String algorithm checkPrimitives(primitives); checkAlgorithmName(algorithm); - if (containsAnyPartIgnoreCase(disabledAlgorithms, algorithm)) - { - return false; - } - - for (Constraint constraint : getConstraints(getConstraintsAlgorithm(algorithm, parameters))) - { - if (!constraint.permits(parameters)) - { - return false; - } - } - - return true; + return implPermitsAlgorithm(primitives, algorithm, parameters); } public final boolean permits(Set primitives, Key key) @@ -216,23 +193,32 @@ private boolean checkConstraints(Set primitives, String algor checkPrimitives(primitives); checkKey(key); - if (JsseUtils.isNameSpecified(algorithm) - && !permits(primitives, algorithm, parameters)) + String keyAlgorithm = JsseUtils.getKeyAlgorithm(key); + checkAlgorithmName(keyAlgorithm); + + if (JsseUtils.isNameSpecified(algorithm) && + !implPermitsAlgorithm(primitives, algorithm, parameters)) { return false; } - if (!permits(primitives, JsseUtils.getKeyAlgorithm(key), null)) + if (!implPermitsKeyAlgorithm(primitives, keyAlgorithm)) { return false; } // TODO[jsse] SunJSSE also checks the named curve for EC keys - for (Constraint constraint : getConstraints(getConstraintsAlgorithm(key))) + String constraintsAlgorithm = getCanonicalAlgorithm(keyAlgorithm); + for (Constraint constraint : getConstraints(constraintsAlgorithm)) { if (!constraint.permits(key)) { + if (LOG.isLoggable(Level.FINEST)) + { + LOG.finest(logHeader + " constraints for '" + constraintsAlgorithm + "' do not permit given '" + + keyAlgorithm + "' key"); + } return false; } } @@ -253,6 +239,49 @@ private List getConstraints(String algorithm) return Collections. emptyList(); } + private boolean implPermitsAlgorithm(Set primitives, String algorithm, + AlgorithmParameters parameters) + { + if (containsAnyPartIgnoreCase(disabledAlgorithms, algorithm)) + { + if (LOG.isLoggable(Level.FINEST)) + { + LOG.finest(logHeader + " disabled algorithm '" + algorithm + "'"); + } + return false; + } + + String constraintsAlgorithm = getConstraintsAlgorithm(algorithm, parameters); + for (Constraint constraint : getConstraints(constraintsAlgorithm)) + { + if (!constraint.permits(parameters)) + { + if (LOG.isLoggable(Level.FINEST)) + { + LOG.finest(logHeader + " constraints for '" + constraintsAlgorithm + + "' do not permit algorithm '" + algorithm + "' for given parameters"); + } + return false; + } + } + + return true; + } + + private boolean implPermitsKeyAlgorithm(Set primitives, String keyAlgorithm) + { + if (containsAnyPartIgnoreCase(disabledAlgorithms, keyAlgorithm)) + { + if (LOG.isLoggable(Level.FINEST)) + { + LOG.finest(logHeader + " disabled key algorithm '" + keyAlgorithm + "'"); + } + return false; + } + + return true; + } + private static enum BinOp { EQ("=="), GE(">="), GT(">"), LE("<="), LT("<"), NE("!="); diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_5.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_5.java index 6a626774cf..0be25c5846 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_5.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_5.java @@ -22,16 +22,16 @@ public BCX509ExtendedTrustManager unwrap() return x509TrustManager; } - public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - x509TrustManager.checkClientTrusted(x509Certificates, authType); + x509TrustManager.checkClientTrusted(chain, authType); } - public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - x509TrustManager.checkServerTrusted(x509Certificates, authType); + x509TrustManager.checkServerTrusted(chain, authType); } public X509Certificate[] getAcceptedIssuers() diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_7.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_7.java index 843403d059..4e735aacc7 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_7.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ExportX509TrustManager_7.java @@ -25,40 +25,44 @@ public BCX509ExtendedTrustManager unwrap() return x509TrustManager; } - public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - x509TrustManager.checkClientTrusted(x509Certificates, authType); + x509TrustManager.checkClientTrusted(chain, authType); } - public void checkClientTrusted(X509Certificate[] x509Certificates, String authType, Socket socket) + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { - x509TrustManager.checkClientTrusted(x509Certificates, authType, socket); + x509TrustManager.checkClientTrusted(chain, authType, socket); } - public void checkClientTrusted(X509Certificate[] x509Certificates, String authType, SSLEngine engine) + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { - x509TrustManager.checkClientTrusted(x509Certificates, authType, engine); + x509TrustManager.checkClientTrusted(chain, authType, engine); } - public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - x509TrustManager.checkServerTrusted(x509Certificates, authType); + x509TrustManager.checkServerTrusted(chain, authType); } - public void checkServerTrusted(X509Certificate[] x509Certificates, String authType, Socket socket) + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { - x509TrustManager.checkServerTrusted(x509Certificates, authType, socket); + x509TrustManager.checkServerTrusted(chain, authType, socket); } - public void checkServerTrusted(X509Certificate[] x509Certificates, String authType, SSLEngine engine) + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { - x509TrustManager.checkServerTrusted(x509Certificates, authType, engine); + x509TrustManager.checkServerTrusted(chain, authType, engine); } public X509Certificate[] getAcceptedIssuers() diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/FipsUtils.java b/tls/src/main/java/org/bouncycastle/jsse/provider/FipsUtils.java index 26cb817a9d..86cfb3a70c 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/FipsUtils.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/FipsUtils.java @@ -10,20 +10,14 @@ abstract class FipsUtils { - /* - * This can only be set to true if the underlying provider is able to assert it is compliant with FIPS IG - * A.5 (when GCM is used in TLS 1.2) and a mechanism has been integrated into this API accordingly to - * ensure that is the case. - */ - private static final boolean provAllowGCMCiphersIn12 = false; - private static final boolean provAllowRSAKeyExchange = PropertyUtils .getBooleanSystemProperty("org.bouncycastle.jsse.fips.allowRSAKeyExchange", false); - private static final Set FIPS_SUPPORTED_CIPHERSUITES = createFipsSupportedCipherSuites(); - private static final Set FIPS_SUPPORTED_PROTOCOLS = createFipsSupportedProtocols(); + private static final Set FIPS_CIPHERSUITES = createFipsCipherSuites(false); + private static final Set FIPS_CIPHERSUITES_GCM12 = createFipsCipherSuites(true); + private static final Set FIPS_PROTOCOLS = createProtocols(); - private static Set createFipsSupportedCipherSuites() + private static Set createFipsCipherSuites(boolean includeGCM12) { /* * Cipher suite list current as of NIST SP 800-52 Revision 2. @@ -88,7 +82,7 @@ private static Set createFipsSupportedCipherSuites() cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"); cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"); - if (provAllowGCMCiphersIn12) + if (includeGCM12) { // cs.add("TLS_DH_DSS_WITH_AES_128_GCM_SHA256"); // cs.add("TLS_DH_DSS_WITH_AES_256_GCM_SHA384"); @@ -126,7 +120,7 @@ private static Set createFipsSupportedCipherSuites() cs.add("TLS_RSA_WITH_AES_256_CCM"); cs.add("TLS_RSA_WITH_AES_256_CCM_8"); - if (provAllowGCMCiphersIn12) + if (includeGCM12) { cs.add("TLS_RSA_WITH_AES_128_GCM_SHA256"); cs.add("TLS_RSA_WITH_AES_256_GCM_SHA384"); @@ -136,7 +130,7 @@ private static Set createFipsSupportedCipherSuites() return Collections.unmodifiableSet(cs); } - private static Set createFipsSupportedProtocols() + private static Set createProtocols() { final Set ps = new HashSet(); @@ -148,9 +142,14 @@ private static Set createFipsSupportedProtocols() return Collections.unmodifiableSet(ps); } - static boolean isFipsCipherSuite(String cipherSuite) + private static Set getFipsCipherSuites(boolean includeGCM12) + { + return includeGCM12 ? FIPS_CIPHERSUITES_GCM12 : FIPS_CIPHERSUITES; + } + + static boolean isFipsCipherSuite(String cipherSuite, boolean includeGCM12) { - return cipherSuite != null && FIPS_SUPPORTED_CIPHERSUITES.contains(cipherSuite); + return cipherSuite != null && getFipsCipherSuites(includeGCM12).contains(cipherSuite); } static boolean isFipsNamedGroup(int namedGroup) @@ -180,7 +179,7 @@ static boolean isFipsNamedGroup(int namedGroup) static boolean isFipsProtocol(String protocol) { - return protocol != null && FIPS_SUPPORTED_PROTOCOLS.contains(protocol); + return protocol != null && FIPS_PROTOCOLS.contains(protocol); } static boolean isFipsSignatureScheme(int signatureScheme) @@ -215,13 +214,13 @@ static boolean isFipsSignatureScheme(int signatureScheme) } } - static void removeNonFipsCipherSuites(Collection cipherSuites) + static void removeNonFipsCipherSuites(Collection cipherSuites, boolean includeGCM12) { - cipherSuites.retainAll(FIPS_SUPPORTED_CIPHERSUITES); + cipherSuites.retainAll(getFipsCipherSuites(includeGCM12)); } static void removeNonFipsProtocols(Collection protocols) { - protocols.retainAll(FIPS_SUPPORTED_PROTOCOLS); + protocols.retainAll(FIPS_PROTOCOLS); } } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_5.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_5.java index 9afe57f2f7..00f8cbaa6b 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_5.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_5.java @@ -154,7 +154,7 @@ public boolean isFipsMode() SSLSessionContext sessionContext = getSessionContext(); if (sessionContext instanceof ProvSSLSessionContext) { - return ((ProvSSLSessionContext)sessionContext).getSSLContext().isFips(); + return ((ProvSSLSessionContext)sessionContext).getContextData().isFipsMode(); } return false; diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_7.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_7.java index 545b90ba67..069349a0f9 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_7.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportSSLSession_7.java @@ -155,7 +155,7 @@ public boolean isFipsMode() SSLSessionContext sessionContext = getSessionContext(); if (sessionContext instanceof ProvSSLSessionContext) { - return ((ProvSSLSessionContext)sessionContext).getSSLContext().isFips(); + return ((ProvSSLSessionContext)sessionContext).getContextData().isFipsMode(); } return false; diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_5.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_5.java index 65d3436561..2ef5726974 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_5.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_5.java @@ -21,13 +21,13 @@ class ImportX509TrustManager_5 extends BCX509ExtendedTrustManager implements ImportX509TrustManager { - final boolean isInFipsMode; + final boolean fipsMode; final JcaJceHelper helper; final X509TrustManager x509TrustManager; - ImportX509TrustManager_5(boolean isInFipsMode, JcaJceHelper helper, X509TrustManager x509TrustManager) + ImportX509TrustManager_5(boolean fipsMode, JcaJceHelper helper, X509TrustManager x509TrustManager) { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; this.x509TrustManager = x509TrustManager; } @@ -44,6 +44,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) checkAdditionalTrust(chain, authType, null, false); } + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { @@ -51,6 +52,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType, Socket checkAdditionalTrust(chain, authType, TransportData.from(socket), false); } + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { @@ -65,6 +67,7 @@ public void checkServerTrusted(X509Certificate[] chain, String authType) checkAdditionalTrust(chain, authType, null, true); } + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { @@ -72,6 +75,7 @@ public void checkServerTrusted(X509Certificate[] chain, String authType, Socket checkAdditionalTrust(chain, authType, TransportData.from(socket), true); } + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { @@ -103,7 +107,7 @@ private void checkAlgorithmConstraints(X509Certificate[] chain, String authType, try { - ProvAlgorithmChecker.checkChain(isInFipsMode, helper, algorithmConstraints, trustedCerts, chain, ekuOID, kuBit); + ProvAlgorithmChecker.checkChain(fipsMode, helper, algorithmConstraints, trustedCerts, chain, ekuOID, kuBit); } catch (GeneralSecurityException e) { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_7.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_7.java index 8d6daba417..916cb4a7c3 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_7.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ImportX509TrustManager_7.java @@ -32,12 +32,14 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) x509TrustManager.checkClientTrusted(chain, authType); } + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { x509TrustManager.checkClientTrusted(chain, authType, socket); } + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { @@ -50,12 +52,14 @@ public void checkServerTrusted(X509Certificate[] chain, String authType) x509TrustManager.checkServerTrusted(chain, authType); } + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { x509TrustManager.checkServerTrusted(chain, authType, socket); } + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/JsseUtils.java b/tls/src/main/java/org/bouncycastle/jsse/provider/JsseUtils.java index b552d997b3..37935697e7 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/JsseUtils.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/JsseUtils.java @@ -14,6 +14,7 @@ import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.Vector; @@ -111,7 +112,7 @@ static boolean allowLegacyResumption() return provTlsAllowLegacyResumption; } - static void appendCipherSuiteDetail(StringBuilder sb, ProvSSLContextSpi context, int cipherSuite) + static void appendCipherSuiteDetail(StringBuilder sb, int cipherSuite) { // TODO Efficiency: precalculate "cipherSuiteID" and make context.getCipherSuiteName faster @@ -134,6 +135,16 @@ static void appendCipherSuiteDetail(StringBuilder sb, ProvSSLContextSpi context, } } + static String[] getArray(Collection c) + { + return c.toArray(new String[c.size()]); + } + + static String[] getKeysArray(Map m) + { + return getArray(m.keySet()); + } + static String getPeerID(String root, ProvTlsManager manager) { long connectionID = ProvSSLConnection.allocateConnectionID(); @@ -156,16 +167,17 @@ static String getPeerReport(ProvTlsManager manager) return peerHost + ":" + peerPortStr; } - static String getSignatureAlgorithmsReport(String title, List signatureSchemes) + static String getSignatureAlgorithmsReport(String title, Iterable signatureSchemes) { - String[] names = SignatureSchemeInfo.getJcaSignatureAlgorithmsBC(signatureSchemes); - StringBuilder sb = new StringBuilder(title); sb.append(':'); - for (String name : names) + if (signatureSchemes != null) { - sb.append(' '); - sb.append(name); + for (SignatureSchemeInfo signatureScheme : signatureSchemes) + { + sb.append(' '); + sb.append(signatureScheme.getJcaSignatureAlgorithmBC()); + } } return sb.toString(); } @@ -925,6 +937,19 @@ private static String stripOuterChars(String s, char openChar, char closeChar) return s; } + static String stripTrailingDot(String s) + { + if (s != null && s.endsWith(".")) + { + int sLast = s.length() - 1; + if (sLast >= 0 && s.charAt(sLast) == '.') + { + return s.substring(0, sLast); + } + } + return s; + } + static boolean useCompatibilityMode() { return provTlsUseCompatibilityMode; diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/NamedGroupInfo.java b/tls/src/main/java/org/bouncycastle/jsse/provider/NamedGroupInfo.java index 18611a9294..f17581677a 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/NamedGroupInfo.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/NamedGroupInfo.java @@ -1,6 +1,7 @@ package org.bouncycastle.jsse.provider; import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; @@ -20,6 +21,7 @@ import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; +import org.bouncycastle.util.Properties; class NamedGroupInfo { @@ -78,14 +80,21 @@ private enum All OQS_mlkem512(NamedGroup.OQS_mlkem512, "ML-KEM"), OQS_mlkem768(NamedGroup.OQS_mlkem768, "ML-KEM"), OQS_mlkem1024(NamedGroup.OQS_mlkem1024, "ML-KEM"), - DRAFT_mlkem768(NamedGroup.DRAFT_mlkem768, "ML-KEM"), - DRAFT_mlkem1024(NamedGroup.DRAFT_mlkem1024, "ML-KEM"); + MLKEM512(NamedGroup.MLKEM512, "ML-KEM"), + MLKEM768(NamedGroup.MLKEM768, "ML-KEM"), + MLKEM1024(NamedGroup.MLKEM1024, "ML-KEM"), + + SecP256r1MLKEM768(NamedGroup.SecP256r1MLKEM768, "EC", "ML-KEM"), + X25519MLKEM768(NamedGroup.X25519MLKEM768, "ML-KEM", "XDH"), + SecP384r1MLKEM1024(NamedGroup.SecP384r1MLKEM1024, "EC", "ML-KEM"); private final int namedGroup; private final String name; private final String text; - private final String jcaAlgorithm; - private final String jcaGroup; + private final String jcaAlgorithm1; + private final String jcaAlgorithm2; + private final String jcaGroup1; + private final String jcaGroup2; private final boolean char2; private final boolean supportedPost13; private final boolean supportedPre13; @@ -94,17 +103,45 @@ private enum All private All(int namedGroup, String jcaAlgorithm) { + if (NamedGroup.refersToASpecificHybrid(namedGroup)) + { + throw new IllegalArgumentException("Non-hybrid constructor only"); + } + this.namedGroup = namedGroup; this.name = NamedGroup.getName(namedGroup); this.text = NamedGroup.getText(namedGroup); - this.jcaAlgorithm = jcaAlgorithm; - this.jcaGroup = NamedGroup.getStandardName(namedGroup); + this.jcaAlgorithm1 = jcaAlgorithm; + this.jcaAlgorithm2 = null; + this.jcaGroup1 = NamedGroup.getStandardName(namedGroup); + this.jcaGroup2 = null; this.supportedPost13 = NamedGroup.canBeNegotiated(namedGroup, ProtocolVersion.TLSv13); this.supportedPre13 = NamedGroup.canBeNegotiated(namedGroup, ProtocolVersion.TLSv12); this.char2 = NamedGroup.isChar2Curve(namedGroup); this.bitsECDH = NamedGroup.getCurveBits(namedGroup); this.bitsFFDHE = NamedGroup.getFiniteFieldBits(namedGroup); } + + private All(int namedGroup, String jcaAlgorithm1, String jcaAlgorithm2) + { + if (!NamedGroup.refersToASpecificHybrid(namedGroup)) + { + throw new IllegalArgumentException("Hybrid constructor only"); + } + + this.namedGroup = namedGroup; + this.name = NamedGroup.getName(namedGroup); + this.text = NamedGroup.getText(namedGroup); + this.jcaAlgorithm1 = jcaAlgorithm1; + this.jcaAlgorithm2 = jcaAlgorithm2; + this.jcaGroup1 = NamedGroup.getStandardName(NamedGroup.getHybridFirst(namedGroup)); + this.jcaGroup2 = NamedGroup.getStandardName(NamedGroup.getHybridSecond(namedGroup)); + this.supportedPost13 = NamedGroup.canBeNegotiated(namedGroup, ProtocolVersion.TLSv13); + this.supportedPre13 = NamedGroup.canBeNegotiated(namedGroup, ProtocolVersion.TLSv12); + this.char2 = false; + this.bitsECDH = -1; + this.bitsFFDHE = -1; + } } private static final int[] CANDIDATES_DEFAULT = { @@ -119,6 +156,7 @@ private All(int namedGroup, String jcaAlgorithm) NamedGroup.ffdhe2048, NamedGroup.ffdhe3072, NamedGroup.ffdhe4096, + NamedGroup.X25519MLKEM768, }; static class PerConnection @@ -165,6 +203,28 @@ static class PerContext } } + static class DefaultedResult + { + private final int result; + private final boolean defaulted; + + DefaultedResult(int result, boolean defaulted) + { + this.result = result; + this.defaulted = defaulted; + } + + int getResult() + { + return result; + } + + boolean isDefaulted() + { + return defaulted; + } + } + static PerConnection createPerConnectionClient(PerContext perContext, ProvSSLParameters sslParameters, ProtocolVersion[] activeProtocolVersions) { @@ -227,7 +287,7 @@ static PerContext createPerContext(boolean isFipsContext, JcaTlsCrypto crypto) return new PerContext(index, candidates); } - static int getMaximumBitsServerECDH(PerConnection perConnection) + static DefaultedResult getMaximumBitsServerECDH(PerConnection perConnection) { int maxBits = 0; List peer = perConnection.getPeer(); @@ -257,10 +317,10 @@ static int getMaximumBitsServerECDH(PerConnection perConnection) maxBits = Math.max(maxBits, namedGroupInfo.getBitsECDH()); } } - return maxBits; + return new DefaultedResult(maxBits, peer == null); } - static int getMaximumBitsServerFFDHE(PerConnection perConnection) + static DefaultedResult getMaximumBitsServerFFDHE(PerConnection perConnection) { int maxBits = 0; boolean anyPeerFF = false; @@ -294,7 +354,7 @@ static int getMaximumBitsServerFFDHE(PerConnection perConnection) maxBits = Math.max(maxBits, namedGroupInfo.getBitsFFDHE()); } } - return maxBits; + return new DefaultedResult(maxBits, !anyPeerFF); } static NamedGroupInfo getNamedGroup(PerContext perContext, int namedGroup) @@ -329,7 +389,7 @@ static boolean hasLocal(PerConnection perConnection, int namedGroup) return perConnection.local.containsKey(namedGroup); } - static int selectServerECDH(PerConnection perConnection, int minimumBitsECDH) + static DefaultedResult selectServerECDH(PerConnection perConnection, int minimumBitsECDH) { List peer = perConnection.getPeer(); if (peer != null) @@ -341,7 +401,7 @@ static int selectServerECDH(PerConnection perConnection, int minimumBitsECDH) int namedGroup = namedGroupInfo.getNamedGroup(); if (perConnection.local.containsKey(namedGroup)) { - return namedGroup; + return new DefaultedResult(namedGroup, false); } } } @@ -357,14 +417,14 @@ static int selectServerECDH(PerConnection perConnection, int minimumBitsECDH) { if (namedGroupInfo.getBitsECDH() >= minimumBitsECDH) { - return namedGroupInfo.getNamedGroup(); + return new DefaultedResult(namedGroupInfo.getNamedGroup(), true); } } } - return -1; + return new DefaultedResult(-1, peer == null); } - static int selectServerFFDHE(PerConnection perConnection, int minimumBitsFFDHE) + static DefaultedResult selectServerFFDHE(PerConnection perConnection, int minimumBitsFFDHE) { boolean anyPeerFF = false; List peer = perConnection.getPeer(); @@ -379,7 +439,7 @@ static int selectServerFFDHE(PerConnection perConnection, int minimumBitsFFDHE) { if (perConnection.local.containsKey(namedGroup)) { - return namedGroup; + return new DefaultedResult(namedGroup, false); } } } @@ -395,11 +455,11 @@ static int selectServerFFDHE(PerConnection perConnection, int minimumBitsFFDHE) { if (namedGroupInfo.getBitsFFDHE() >= minimumBitsFFDHE) { - return namedGroupInfo.getNamedGroup(); + return new DefaultedResult(namedGroupInfo.getNamedGroup(), true); } } } - return -1; + return new DefaultedResult(-1, !anyPeerFF); } private static void addNamedGroup(boolean isFipsContext, JcaTlsCrypto crypto, boolean disableChar2, @@ -415,23 +475,37 @@ private static void addNamedGroup(boolean isFipsContext, JcaTlsCrypto crypto, bo boolean disable = (disableChar2 && all.char2) || (disableFFDHE && all.bitsFFDHE > 0); - boolean enabled = !disable && (null != all.jcaGroup) && crypto.hasNamedGroup(namedGroup); + boolean enabled = !disable && (null != all.jcaGroup1) && (null == all.jcaAlgorithm2 || null != all.jcaGroup2) + && TlsUtils.isSupportedNamedGroup(crypto, namedGroup); + + AlgorithmParameters algorithmParameters1 = null; + AlgorithmParameters algorithmParameters2 = null; - AlgorithmParameters algorithmParameters = null; if (enabled) { - // TODO[jsse] Consider also fetching 'jcaAlgorithm' + // TODO[jsse] Consider also fetching 'jcaAlgorithm1', 'jcaAlgorithm2' + try { - algorithmParameters = crypto.getNamedGroupAlgorithmParameters(namedGroup); + if (NamedGroup.refersToASpecificHybrid(namedGroup)) + { + algorithmParameters1 = getAlgorithmParameters(crypto, NamedGroup.getHybridFirst(namedGroup)); + algorithmParameters2 = getAlgorithmParameters(crypto, NamedGroup.getHybridSecond(namedGroup)); + } + else + { + algorithmParameters1 = getAlgorithmParameters(crypto, namedGroup); + } } catch (Exception e) { enabled = false; + algorithmParameters1 = null; + algorithmParameters2 = null; } } - NamedGroupInfo namedGroupInfo = new NamedGroupInfo(all, algorithmParameters, enabled); + NamedGroupInfo namedGroupInfo = new NamedGroupInfo(all, algorithmParameters1, algorithmParameters2, enabled); if (null != ng.put(namedGroup, namedGroupInfo)) { @@ -495,7 +569,7 @@ private static Map createIndex(boolean isFipsContext, J final boolean disableChar2 = PropertyUtils.getBooleanSystemProperty("org.bouncycastle.jsse.ec.disableChar2", false) || - PropertyUtils.getBooleanSystemProperty("org.bouncycastle.ec.disable_f2m", false); + Properties.isOverrideSet("org.bouncycastle.ec.disable_f2m"); final boolean disableFFDHE = !PropertyUtils.getBooleanSystemProperty("jsse.enableFFDHE", true); @@ -507,6 +581,12 @@ private static Map createIndex(boolean isFipsContext, J return ng; } + private static AlgorithmParameters getAlgorithmParameters(JcaTlsCrypto crypto, int namedGroup) + throws GeneralSecurityException + { + return crypto.getNamedGroupAlgorithmParameters(namedGroup); + } + private static int getNamedGroupByName(String name) { for (All all : All.values()) @@ -565,13 +645,16 @@ private static boolean hasAnyECDSA(Map local) } private final All all; - private final AlgorithmParameters algorithmParameters; + private final AlgorithmParameters algorithmParameters1; + private final AlgorithmParameters algorithmParameters2; private final boolean enabled; - NamedGroupInfo(All all, AlgorithmParameters algorithmParameters, boolean enabled) + NamedGroupInfo(All all, AlgorithmParameters algorithmParameters1, AlgorithmParameters algorithmParameters2, + boolean enabled) { this.all = all; - this.algorithmParameters = algorithmParameters; + this.algorithmParameters1 = algorithmParameters1; + this.algorithmParameters2 = algorithmParameters2; this.enabled = enabled; } @@ -585,16 +668,6 @@ int getBitsFFDHE() return all.bitsFFDHE; } - String getJcaAlgorithm() - { - return all.jcaAlgorithm; - } - - String getJcaGroup() - { - return all.jcaGroup; - } - int getNamedGroup() { return all.namedGroup; @@ -632,7 +705,21 @@ private boolean isPermittedBy(BCAlgorithmConstraints algorithmConstraints) { Set primitives = JsseUtils.KEY_AGREEMENT_CRYPTO_PRIMITIVES_BC; - return algorithmConstraints.permits(primitives, getJcaGroup(), null) - && algorithmConstraints.permits(primitives, getJcaAlgorithm(), algorithmParameters); + if (!algorithmConstraints.permits(primitives, all.jcaGroup1, null) || + !algorithmConstraints.permits(primitives, all.jcaAlgorithm1, algorithmParameters1)) + { + return false; + } + + if (all.jcaAlgorithm2 != null) + { + if (!algorithmConstraints.permits(primitives, all.jcaGroup2, null) || + !algorithmConstraints.permits(primitives, all.jcaAlgorithm2, algorithmParameters2)) + { + return false; + } + } + + return true; } } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/OldCertUtil.java b/tls/src/main/java/org/bouncycastle/jsse/provider/OldCertUtil.java index 4eea1a5b62..51811ac437 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/OldCertUtil.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/OldCertUtil.java @@ -25,7 +25,7 @@ class OldCertUtil static javax.security.cert.X509Certificate[] getPeerCertificateChain(BCExtendedSSLSession sslSession) throws SSLPeerUnverifiedException { - boolean isFips = sslSession.isFipsMode(); + boolean fipsMode = sslSession.isFipsMode(); Certificate[] peerCertificates = sslSession.getPeerCertificates(); javax.security.cert.X509Certificate[] result = new javax.security.cert.X509Certificate[peerCertificates.length]; @@ -39,7 +39,7 @@ static javax.security.cert.X509Certificate[] getPeerCertificateChain(BCExtendedS if (peerCertificate instanceof X509Certificate) { X509Certificate peerX509Certificate = (X509Certificate)peerCertificate; - if (isFips) + if (fipsMode) { result[count++] = new X509CertificateWrapper(peerX509Certificate); } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmChecker.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmChecker.java index 0c89593210..8a46a9ff11 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmChecker.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmChecker.java @@ -85,13 +85,13 @@ private static Set createSigAlgNoParams() return Collections.unmodifiableSet(noParams); } - private final boolean isInFipsMode; + private final boolean fipsMode; private final JcaJceHelper helper; private final BCAlgorithmConstraints algorithmConstraints; private X509Certificate issuerCert; - ProvAlgorithmChecker(boolean isInFipsMode, JcaJceHelper helper, BCAlgorithmConstraints algorithmConstraints) + ProvAlgorithmChecker(boolean fipsMode, JcaJceHelper helper, BCAlgorithmConstraints algorithmConstraints) { if (null == helper) { @@ -102,7 +102,7 @@ private static Set createSigAlgNoParams() throw new NullPointerException("'algorithmConstraints' cannot be null"); } - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; this.algorithmConstraints = algorithmConstraints; @@ -149,7 +149,7 @@ public void check(Certificate cert, Collection unresolvedCritExts) throw X509Certificate subjectCert = (X509Certificate)cert; - if (isInFipsMode && !isValidFIPSPublicKey(subjectCert.getPublicKey())) + if (fipsMode && !isValidFIPSPublicKey(subjectCert.getPublicKey())) { throw new CertPathValidatorException("non-FIPS public key found"); } @@ -182,7 +182,7 @@ static void checkCertPathExtras(JcaJceHelper helper, BCAlgorithmConstraints algo checkEndEntity(helper, algorithmConstraints, eeCert, ekuOID, kuBit); } - static void checkChain(boolean isInFipsMode, JcaJceHelper helper, BCAlgorithmConstraints algorithmConstraints, + static void checkChain(boolean fipsMode, JcaJceHelper helper, BCAlgorithmConstraints algorithmConstraints, Set trustedCerts, X509Certificate[] chain, KeyPurposeId ekuOID, int kuBit) throws CertPathValidatorException { @@ -206,7 +206,7 @@ static void checkChain(boolean isInFipsMode, JcaJceHelper helper, BCAlgorithmCon checkIssued(helper, algorithmConstraints, chain[taPos - 1]); } - ProvAlgorithmChecker algorithmChecker = new ProvAlgorithmChecker(isInFipsMode, helper, algorithmConstraints); + ProvAlgorithmChecker algorithmChecker = new ProvAlgorithmChecker(fipsMode, helper, algorithmConstraints); algorithmChecker.init(false); for (int i = taPos - 1; i >= 0; --i) diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmConstraints.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmConstraints.java index 7a9cb10664..f473c930db 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmConstraints.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvAlgorithmConstraints.java @@ -82,6 +82,10 @@ public boolean permits(Set primitives, String algorithm, Algo if (null != configAlgorithmConstraints && !configAlgorithmConstraints.permits(primitives, algorithm, parameters)) { + if (LOG.isLoggable(Level.FINEST)) + { + LOG.finest("Configured algorithm constraints do not permit '" + algorithm + "' with given parameters"); + } return false; } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvKeyManagerFactorySpi.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvKeyManagerFactorySpi.java index 1d52494563..146ffcb9d8 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvKeyManagerFactorySpi.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvKeyManagerFactorySpi.java @@ -90,14 +90,14 @@ else if (null != ksPathProp) return new KeyStoreConfig(ks, ksPassword); } - protected final boolean isInFipsMode; + protected final boolean fipsMode; protected final JcaJceHelper helper; protected BCX509ExtendedKeyManager x509KeyManager; - ProvKeyManagerFactorySpi(boolean isInFipsMode, JcaJceHelper helper) + ProvKeyManagerFactorySpi(boolean fipsMode, JcaJceHelper helper) { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; } @@ -117,7 +117,7 @@ protected void engineInit(KeyStore ks, char[] ksPassword) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { // NOTE: When key store is null, we do not try to load defaults - this.x509KeyManager = new ProvX509KeyManagerSimple(isInFipsMode, helper, ks, ksPassword); + this.x509KeyManager = new ProvX509KeyManagerSimple(fipsMode, helper, ks, ksPassword); } @Override @@ -127,7 +127,7 @@ protected void engineInit(ManagerFactoryParameters managerFactoryParameters) if (managerFactoryParameters instanceof KeyStoreBuilderParameters) { List builders = ((KeyStoreBuilderParameters)managerFactoryParameters).getParameters(); - this.x509KeyManager = new ProvX509KeyManager(isInFipsMode, helper, builders); + this.x509KeyManager = new ProvX509KeyManager(fipsMode, helper, builders); } else { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java index 923e68afa4..829fe367df 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java @@ -4,16 +4,12 @@ import java.security.KeyStore; import java.security.SecureRandom; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.SortedSet; import java.util.TreeMap; -import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; @@ -33,8 +29,6 @@ import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jsse.BCX509ExtendedKeyManager; import org.bouncycastle.jsse.BCX509ExtendedTrustManager; -import org.bouncycastle.jsse.java.security.BCAlgorithmConstraints; -import org.bouncycastle.jsse.java.security.BCCryptoPrimitive; import org.bouncycastle.tls.CipherSuite; import org.bouncycastle.tls.ProtocolVersion; import org.bouncycastle.tls.TlsDHUtils; @@ -53,21 +47,26 @@ class ProvSSLContextSpi private static final String PROPERTY_CLIENT_PROTOCOLS = "jdk.tls.client.protocols"; private static final String PROPERTY_SERVER_PROTOCOLS = "jdk.tls.server.protocols"; - private static final Set TLS_CRYPTO_PRIMITIVES_BC = JsseUtils.KEY_AGREEMENT_CRYPTO_PRIMITIVES_BC; - /* * TODO[jsse] Should separate this into "understood" cipher suite int<->String maps * and a Set of supported cipher suite values, so we can cover TLS_NULL_WITH_NULL_NULL and * the SCSV values. */ private static final Map SUPPORTED_CIPHERSUITE_MAP = createSupportedCipherSuiteMap(); - private static final Map SUPPORTED_CIPHERSUITE_MAP_FIPS = createSupportedCipherSuiteMapFips(SUPPORTED_CIPHERSUITE_MAP); + private static final Map SUPPORTED_CIPHERSUITE_MAP_FIPS = + createSupportedCipherSuiteMapFips(SUPPORTED_CIPHERSUITE_MAP, false); + private static final Map SUPPORTED_CIPHERSUITE_MAP_FIPS_GCM12 = + createSupportedCipherSuiteMapFips(SUPPORTED_CIPHERSUITE_MAP, true); private static final Map SUPPORTED_PROTOCOL_MAP = createSupportedProtocolMap(); private static final Map SUPPORTED_PROTOCOL_MAP_FIPS = createSupportedProtocolMapFips(SUPPORTED_PROTOCOL_MAP); - private static final List DEFAULT_CIPHERSUITE_LIST = createDefaultCipherSuiteList(SUPPORTED_CIPHERSUITE_MAP.keySet()); - private static final List DEFAULT_CIPHERSUITE_LIST_FIPS = createDefaultCipherSuiteListFips(DEFAULT_CIPHERSUITE_LIST); + private static final List DEFAULT_CIPHERSUITE_LIST = + createDefaultCipherSuiteList(SUPPORTED_CIPHERSUITE_MAP.keySet()); + private static final List DEFAULT_CIPHERSUITE_LIST_FIPS = + createDefaultCipherSuiteListFips(DEFAULT_CIPHERSUITE_LIST, false); + private static final List DEFAULT_CIPHERSUITE_LIST_FIPS_GCM12 = + createDefaultCipherSuiteListFips(DEFAULT_CIPHERSUITE_LIST, true); private static final List DEFAULT_PROTOCOL_LIST = createDefaultProtocolList(SUPPORTED_PROTOCOL_MAP.keySet()); private static final List DEFAULT_PROTOCOL_LIST_FIPS = createDefaultProtocolListFips(DEFAULT_PROTOCOL_LIST); @@ -140,10 +139,11 @@ private static List createDefaultCipherSuiteList(Set supportedCi return Collections.unmodifiableList(cs); } - private static List createDefaultCipherSuiteListFips(List defaultCipherSuiteList) + private static List createDefaultCipherSuiteListFips(List defaultCipherSuiteList, + boolean includeGCM12) { ArrayList cs = new ArrayList(defaultCipherSuiteList); - FipsUtils.removeNonFipsCipherSuites(cs); + FipsUtils.removeNonFipsCipherSuites(cs, includeGCM12); cs.trimToSize(); return Collections.unmodifiableList(cs); } @@ -312,10 +312,10 @@ private static Map createSupportedCipherSuiteMap() } private static Map createSupportedCipherSuiteMapFips( - Map supportedCipherSuiteMap) + Map supportedCipherSuiteMap, boolean includeGCM12) { final Map cs = new LinkedHashMap(supportedCipherSuiteMap); - FipsUtils.removeNonFipsCipherSuites(cs.keySet()); + FipsUtils.removeNonFipsCipherSuites(cs.keySet(), includeGCM12); return Collections.unmodifiableMap(cs); } @@ -358,7 +358,8 @@ private static String[] getDefaultEnabledCipherSuites(Map { continue; } - if (!ProvAlgorithmConstraints.DEFAULT_TLS_ONLY.permits(TLS_CRYPTO_PRIMITIVES_BC, candidate, null)) + if (!ProvAlgorithmConstraints.DEFAULT_TLS_ONLY.permits(JsseUtils.KEY_AGREEMENT_CRYPTO_PRIMITIVES_BC, + candidate, null)) { continue; } @@ -491,16 +493,6 @@ private static List getJdkTlsProtocols(String protocolsPropertyName, Lis return result; } - private static String[] getArray(Collection c) - { - return c.toArray(new String[c.size()]); - } - - private static String[] getKeysArray(Map m) - { - return getArray(m.keySet()); - } - static CipherSuiteInfo getCipherSuiteInfo(String cipherSuiteName) { return SUPPORTED_CIPHERSUITE_MAP.get(cipherSuiteName); @@ -568,263 +560,17 @@ static String getProtocolVersionName(ProtocolVersion protocolVersion) return "NONE"; } - protected final boolean isInFipsMode; + protected final boolean fipsMode; protected final JcaTlsCryptoProvider cryptoProvider; - - protected final Map supportedCipherSuites; - protected final Map supportedProtocols; - protected final String[] defaultCipherSuitesClient; - protected final String[] defaultCipherSuitesServer; - protected final String[] defaultProtocolsClient; - protected final String[] defaultProtocolsServer; + protected final List specifiedProtocolsClient; private ContextData contextData = null; - ProvSSLContextSpi(boolean isInFipsMode, JcaTlsCryptoProvider cryptoProvider, List specifiedProtocolsClient) + ProvSSLContextSpi(boolean fipsMode, JcaTlsCryptoProvider cryptoProvider, List specifiedProtocolsClient) { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.cryptoProvider = cryptoProvider; - - this.supportedCipherSuites = isInFipsMode ? SUPPORTED_CIPHERSUITE_MAP_FIPS : SUPPORTED_CIPHERSUITE_MAP; - this.supportedProtocols = isInFipsMode ? SUPPORTED_PROTOCOL_MAP_FIPS : SUPPORTED_PROTOCOL_MAP; - - List defaultCipherSuiteList = isInFipsMode ? DEFAULT_CIPHERSUITE_LIST_FIPS : DEFAULT_CIPHERSUITE_LIST; - List defaultProtocolList = isInFipsMode ? DEFAULT_PROTOCOL_LIST_FIPS : DEFAULT_PROTOCOL_LIST; - - this.defaultCipherSuitesClient = getDefaultEnabledCipherSuitesClient(supportedCipherSuites, - defaultCipherSuiteList); - this.defaultCipherSuitesServer = getDefaultEnabledCipherSuitesServer(supportedCipherSuites, - defaultCipherSuiteList); - - this.defaultProtocolsClient = getDefaultEnabledProtocolsClient(supportedProtocols, defaultProtocolList, - specifiedProtocolsClient); - this.defaultProtocolsServer = getDefaultEnabledProtocolsServer(supportedProtocols, defaultProtocolList); - } - - int[] getActiveCipherSuites(JcaTlsCrypto crypto, ProvSSLParameters sslParameters, - ProtocolVersion[] activeProtocolVersions) - { - String[] enabledCipherSuites = sslParameters.getCipherSuitesArray(); - BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints(); - - ProtocolVersion latest = ProtocolVersion.getLatestTLS(activeProtocolVersions); - ProtocolVersion earliest = ProtocolVersion.getEarliestTLS(activeProtocolVersions); - - boolean post13Active = TlsUtils.isTLSv13(latest); - boolean pre13Active = !TlsUtils.isTLSv13(earliest); - - int[] candidates = new int[enabledCipherSuites.length]; - - int count = 0; - for (String enabledCipherSuite : enabledCipherSuites) - { - CipherSuiteInfo candidate = supportedCipherSuites.get(enabledCipherSuite); - if (null == candidate) - { - continue; - } - if (candidate.isTLSv13()) - { - if (!post13Active) - { - continue; - } - } - else - { - if (!pre13Active) - { - continue; - } - } - if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledCipherSuite, null)) - { - continue; - } - - /* - * TODO[jsse] SunJSSE also checks that the cipher suite is usable for at least one of - * the active protocol versions. Also, if the cipher suite involves a key exchange, - * there must be at least one suitable NamedGroup available. - */ - - candidates[count++] = candidate.getCipherSuite(); - } - - /* - * TODO Move cipher suite management into CipherSuiteInfo (PerConnection/PerContext pattern - * like NamedGroupInfo) to avoid unnecessary repetition of these sorts of checks. - */ - int[] result = TlsUtils.getSupportedCipherSuites(crypto, candidates, 0, count); - - if (result.length < 1) - { - // TODO[jsse] Refactor so that this can be an SSLHandshakeException? - throw new IllegalStateException("No usable cipher suites enabled"); - } - - return result; - } - - ProtocolVersion[] getActiveProtocolVersions(ProvSSLParameters sslParameters) - { -// String[] enabledCipherSuites = sslParameters.getCipherSuitesArray(); - String[] enabledProtocols = sslParameters.getProtocolsArray(); - BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints(); - - SortedSet result = new TreeSet(new Comparator() - { - public int compare(ProtocolVersion o1, ProtocolVersion o2) - { - return o1.isLaterVersionOf(o2) ? -1 : o2.isLaterVersionOf(o1) ? 1 : 0; - } - }); - - for (String enabledProtocol : enabledProtocols) - { - ProtocolVersion candidate = supportedProtocols.get(enabledProtocol); - if (null == candidate) - { - continue; - } - if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledProtocol, null)) - { - continue; - } - - /* - * TODO[jsse] SunJSSE also checks that there is at least one "activatable" cipher suite - * that could be used for this protocol version. - */ - - result.add(candidate); - } - - if (result.isEmpty()) - { - // TODO[jsse] Refactor so that this can be an SSLHandshakeException? - throw new IllegalStateException("No usable protocols enabled"); - } - - return result.toArray(new ProtocolVersion[result.size()]); - } - - String[] getDefaultCipherSuites(boolean isClient) - { - return implGetDefaultCipherSuites(isClient).clone(); - } - - String[] getDefaultProtocols(boolean isClient) - { - return implGetDefaultProtocols(isClient).clone(); - } - - ProvSSLParameters getDefaultSSLParameters(boolean isClient) - { - return new ProvSSLParameters(this, implGetDefaultCipherSuites(isClient), implGetDefaultProtocols(isClient)); - } - - String[] getSupportedCipherSuites() - { - return getKeysArray(supportedCipherSuites); - } - - String[] getSupportedCipherSuites(String[] cipherSuites) - { - if (null == cipherSuites) - { - throw new NullPointerException("'cipherSuites' cannot be null"); - } - - ArrayList result = new ArrayList(cipherSuites.length); - for (String cipherSuite : cipherSuites) - { - if (TlsUtils.isNullOrEmpty(cipherSuite)) - { - throw new IllegalArgumentException("'cipherSuites' cannot contain null or empty string elements"); - } - - if (supportedCipherSuites.containsKey(cipherSuite)) - { - result.add(cipherSuite); - } - } - - // NOTE: This method must always return a copy, so no fast path when all supported - return getArray(result); - } - - String[] getSupportedProtocols() - { - return getKeysArray(supportedProtocols); - } - - ProvSSLParameters getSupportedSSLParameters(boolean isClient) - { - return new ProvSSLParameters(this, getSupportedCipherSuites(), getSupportedProtocols()); - } - - boolean isFips() - { - return isInFipsMode; - } - - boolean isSupportedProtocols(String[] protocols) - { - if (protocols == null) - { - return false; - } - for (String protocol : protocols) - { - if (protocol == null || !supportedProtocols.containsKey(protocol)) - { - return false; - } - } - return true; - } - - void updateDefaultSSLParameters(ProvSSLParameters sslParameters, boolean isClient) - { - if (sslParameters.getCipherSuitesArray() == implGetDefaultCipherSuites(!isClient)) - { - sslParameters.setCipherSuitesArray(implGetDefaultCipherSuites(isClient)); - } - if (sslParameters.getProtocolsArray() == implGetDefaultProtocols(!isClient)) - { - sslParameters.setProtocolsArray(implGetDefaultProtocols(isClient)); - } - } - - String validateNegotiatedCipherSuite(ProvSSLParameters sslParameters, int cipherSuite) - { - // NOTE: The redundancy among these various checks is intentional - String name = getCipherSuiteName(cipherSuite); - if (null == name - || !JsseUtils.contains(sslParameters.getCipherSuitesArray(), name) - || !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null) - || !supportedCipherSuites.containsKey(name) - || (isInFipsMode && !FipsUtils.isFipsCipherSuite(name))) - { - throw new IllegalStateException("SSL connection negotiated unsupported ciphersuite: " + cipherSuite); - } - return name; - } - - String validateNegotiatedProtocol(ProvSSLParameters sslParameters, ProtocolVersion protocol) - { - // NOTE: The redundancy among these various checks is intentional - String name = getProtocolVersionName(protocol); - if (null == name - || !JsseUtils.contains(sslParameters.getProtocolsArray(), name) - || !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null) - || !supportedProtocols.containsKey(name) - || (isInFipsMode && !FipsUtils.isFipsProtocol(name))) - { - throw new IllegalStateException("SSL connection negotiated unsupported protocol: " + protocol); - } - return name; + this.specifiedProtocolsClient = specifiedProtocolsClient; } @Override @@ -866,21 +612,15 @@ protected SSLSocketFactory engineGetSocketFactory() // An SSLContextSpi method from JDK 6 protected SSLParameters engineGetDefaultSSLParameters() { - // Fail if uninitialized - getContextData(); - // Implicitly for a client socket - return SSLParametersUtil.getSSLParameters(getDefaultSSLParameters(true)); + return SSLParametersUtil.getSSLParameters(getContextData().getDefaultSSLParameters(true)); } // An SSLContextSpi method from JDK 6 protected SSLParameters engineGetSupportedSSLParameters() { - // Fail if uninitialized - getContextData(); - // Implicitly for a client socket - return SSLParametersUtil.getSSLParameters(getSupportedSSLParameters(true)); + return SSLParametersUtil.getSSLParameters(getContextData().getSupportedSSLParameters(true)); } @Override @@ -897,7 +637,35 @@ protected synchronized void engineInit(KeyManager[] kms, TrustManager[] tms, Sec // Trigger (possibly expensive) RNG initialization here to avoid timeout in an actual handshake crypto.getSecureRandom().nextInt(); - this.contextData = new ContextData(this, crypto, x509KeyManager, x509TrustManager); + boolean includeGCM12 = crypto.getFipsGCMNonceGeneratorFactory() != null; + + Map supportedCipherSuites = + !fipsMode ? SUPPORTED_CIPHERSUITE_MAP + : !includeGCM12 ? SUPPORTED_CIPHERSUITE_MAP_FIPS + : SUPPORTED_CIPHERSUITE_MAP_FIPS_GCM12; + + Map supportedProtocols = + fipsMode ? SUPPORTED_PROTOCOL_MAP_FIPS : SUPPORTED_PROTOCOL_MAP; + + List defaultCipherSuiteList = + !fipsMode ? DEFAULT_CIPHERSUITE_LIST + : !includeGCM12 ? DEFAULT_CIPHERSUITE_LIST_FIPS + : DEFAULT_CIPHERSUITE_LIST_FIPS_GCM12; + + String[] defaultCipherSuitesClient = getDefaultEnabledCipherSuitesClient(supportedCipherSuites, + defaultCipherSuiteList); + String[] defaultCipherSuitesServer = getDefaultEnabledCipherSuitesServer(supportedCipherSuites, + defaultCipherSuiteList); + + List defaultProtocolList = fipsMode ? DEFAULT_PROTOCOL_LIST_FIPS : DEFAULT_PROTOCOL_LIST; + + String[] defaultProtocolsClient = getDefaultEnabledProtocolsClient(supportedProtocols, defaultProtocolList, + specifiedProtocolsClient); + String[] defaultProtocolsServer = getDefaultEnabledProtocolsServer(supportedProtocols, defaultProtocolList); + + this.contextData = new ContextData(fipsMode, crypto, x509KeyManager, x509TrustManager, supportedCipherSuites, + supportedProtocols, defaultCipherSuitesClient, defaultCipherSuitesServer, defaultProtocolsClient, + defaultProtocolsServer); } protected synchronized ContextData getContextData() @@ -952,20 +720,10 @@ protected BCX509ExtendedTrustManager selectX509TrustManager(JcaJceHelper helper, { if (tm instanceof X509TrustManager) { - return X509TrustManagerUtil.importX509TrustManager(isInFipsMode, helper, (X509TrustManager)tm); + return X509TrustManagerUtil.importX509TrustManager(fipsMode, helper, (X509TrustManager)tm); } } } return DummyX509TrustManager.INSTANCE; } - - private String[] implGetDefaultCipherSuites(boolean isClient) - { - return isClient ? defaultCipherSuitesClient : defaultCipherSuitesServer; - } - - private String[] implGetDefaultProtocols(boolean isClient) - { - return isClient ? defaultProtocolsClient : defaultProtocolsServer; - } } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLEngine.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLEngine.java index d01ea87007..4d27cf8f36 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLEngine.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLEngine.java @@ -71,7 +71,7 @@ protected ProvSSLEngine(ContextData contextData, String peerHost, int peerPort) super(peerHost, peerPort); this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); } public ContextData getContextData() @@ -319,13 +319,13 @@ public synchronized SSLParameters getSSLParameters() @Override public synchronized String[] getSupportedCipherSuites() { - return contextData.getContext().getSupportedCipherSuites(); + return contextData.getSupportedCipherSuites(); } @Override public synchronized String[] getSupportedProtocols() { - return contextData.getContext().getSupportedProtocols(); + return contextData.getSupportedProtocols(); } public int getTransportID() @@ -425,7 +425,7 @@ public synchronized void setUseClientMode(boolean useClientMode) if (this.useClientMode != useClientMode) { - contextData.getContext().updateDefaultSSLParameters(sslParameters, useClientMode); + contextData.updateDefaultSSLParameters(sslParameters, useClientMode); this.useClientMode = useClientMode; } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLParameters.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLParameters.java index b95ecf1991..7e8fb1621b 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLParameters.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLParameters.java @@ -29,7 +29,7 @@ private static List copyList(Collection list) return Collections.unmodifiableList(new ArrayList(list)); } - private final ProvSSLContextSpi context; + private final ContextData contextData; private String[] cipherSuites; private String[] protocols; @@ -39,20 +39,22 @@ private static List copyList(Collection list) private BCAlgorithmConstraints algorithmConstraints = ProvAlgorithmConstraints.DEFAULT; private List sniServerNames; private List sniMatchers; - private boolean useCipherSuitesOrder = true; + private boolean useCipherSuitesOrder = false; + private boolean useNamedGroupsOrder = false; private boolean enableRetransmissions = true; private int maximumPacketSize = 0; private String[] applicationProtocols = TlsUtils.EMPTY_STRINGS; private String[] signatureSchemes = null; + private String[] signatureSchemesCert = null; private String[] namedGroups = null; private BCApplicationProtocolSelector engineAPSelector; private BCApplicationProtocolSelector socketAPSelector; private ProvSSLSession sessionToResume; - ProvSSLParameters(ProvSSLContextSpi context, String[] cipherSuites, String[] protocols) + ProvSSLParameters(ContextData contextData, String[] cipherSuites, String[] protocols) { - this.context = context; + this.contextData = contextData; this.cipherSuites = cipherSuites; this.protocols = protocols; @@ -60,7 +62,7 @@ private static List copyList(Collection list) ProvSSLParameters copy() { - ProvSSLParameters p = new ProvSSLParameters(context, cipherSuites, protocols); + ProvSSLParameters p = new ProvSSLParameters(contextData, cipherSuites, protocols); p.wantClientAuth = wantClientAuth; p.needClientAuth = needClientAuth; p.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; @@ -68,10 +70,12 @@ ProvSSLParameters copy() p.sniServerNames = sniServerNames; p.sniMatchers = sniMatchers; p.useCipherSuitesOrder = useCipherSuitesOrder; + p.useNamedGroupsOrder = useNamedGroupsOrder; p.enableRetransmissions = enableRetransmissions; p.maximumPacketSize = maximumPacketSize; p.applicationProtocols = applicationProtocols; p.signatureSchemes = signatureSchemes; + p.signatureSchemesCert = signatureSchemesCert; p.namedGroups = namedGroups; p.engineAPSelector = engineAPSelector; p.socketAPSelector = socketAPSelector; @@ -104,7 +108,7 @@ String[] getCipherSuitesArray() public void setCipherSuites(String[] cipherSuites) { - this.cipherSuites = context.getSupportedCipherSuites(cipherSuites); + this.cipherSuites = contextData.getSupportedCipherSuites(cipherSuites); } void setCipherSuitesArray(String[] cipherSuites) @@ -126,7 +130,7 @@ String[] getProtocolsArray() public void setProtocols(String[] protocols) { - if (!context.isSupportedProtocols(protocols)) + if (!contextData.isSupportedProtocols(protocols)) { throw new IllegalArgumentException("'protocols' cannot be null, or contain unsupported protocols"); } @@ -212,6 +216,16 @@ public void setUseCipherSuitesOrder(boolean useCipherSuitesOrder) this.useCipherSuitesOrder = useCipherSuitesOrder; } + public boolean getUseNamedGroupsOrder() + { + return useNamedGroupsOrder; + } + + public void setUseNamedGroupsOrder(boolean useNamedGroupsOrder) + { + this.useNamedGroupsOrder = useNamedGroupsOrder; + } + public boolean getEnableRetransmissions() { return enableRetransmissions; @@ -257,6 +271,16 @@ public void setSignatureSchemes(String[] signatureSchemes) this.signatureSchemes = TlsUtils.clone(signatureSchemes); } + public String[] getSignatureSchemesCert() + { + return TlsUtils.clone(signatureSchemesCert); + } + + public void setSignatureSchemesCert(String[] signatureSchemesCert) + { + this.signatureSchemesCert = TlsUtils.clone(signatureSchemesCert); + } + public String[] getNamedGroups() { return TlsUtils.clone(namedGroups); diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocket.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocket.java index 5c6d68c7b8..507ae084fd 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocket.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocket.java @@ -22,7 +22,7 @@ protected ProvSSLServerSocket(ContextData contextData) super(); this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); } protected ProvSSLServerSocket(ContextData contextData, int port) @@ -31,7 +31,7 @@ protected ProvSSLServerSocket(ContextData contextData, int port) super(port); this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); } protected ProvSSLServerSocket(ContextData contextData, int port, int backlog) @@ -40,7 +40,7 @@ protected ProvSSLServerSocket(ContextData contextData, int port, int backlog) super(port, backlog); this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); } protected ProvSSLServerSocket(ContextData contextData, int port, int backlog, InetAddress address) @@ -49,7 +49,7 @@ protected ProvSSLServerSocket(ContextData contextData, int port, int backlog, In super(port, backlog, address); this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); } @Override @@ -97,13 +97,13 @@ public synchronized SSLParameters getSSLParameters() @Override public synchronized String[] getSupportedCipherSuites() { - return contextData.getContext().getSupportedCipherSuites(); + return contextData.getSupportedCipherSuites(); } @Override public synchronized String[] getSupportedProtocols() { - return contextData.getContext().getSupportedProtocols(); + return contextData.getSupportedProtocols(); } @Override @@ -153,7 +153,7 @@ public synchronized void setUseClientMode(boolean useClientMode) { if (this.useClientMode != useClientMode) { - contextData.getContext().updateDefaultSSLParameters(sslParameters, useClientMode); + contextData.updateDefaultSSLParameters(sslParameters, useClientMode); this.useClientMode = useClientMode; } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocketFactory.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocketFactory.java index a223ba933d..68b1757d68 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocketFactory.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLServerSocketFactory.java @@ -45,12 +45,12 @@ public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddr @Override public String[] getDefaultCipherSuites() { - return contextData.getContext().getDefaultCipherSuites(false); + return contextData.getDefaultCipherSuites(false); } @Override public String[] getSupportedCipherSuites() { - return contextData.getContext().getSupportedCipherSuites(); + return contextData.getSupportedCipherSuites(); } } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionBase.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionBase.java index 4b63da824a..a0ca7f1010 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionBase.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionBase.java @@ -30,7 +30,7 @@ abstract class ProvSSLSessionBase protected final Map valueMap = Collections.synchronizedMap(new HashMap()); protected final AtomicReference sslSessionContext; - protected final boolean isFips; + protected final boolean fipsMode; protected final JcaTlsCrypto crypto; protected final String peerHost; protected final int peerPort; @@ -41,8 +41,8 @@ abstract class ProvSSLSessionBase ProvSSLSessionBase(ProvSSLSessionContext sslSessionContext, String peerHost, int peerPort) { this.sslSessionContext = new AtomicReference(sslSessionContext); - this.isFips = (null == sslSessionContext) ? false : sslSessionContext.getSSLContext().isFips(); - this.crypto = (null == sslSessionContext) ? null : sslSessionContext.getCrypto(); + this.fipsMode = (null == sslSessionContext) ? false : sslSessionContext.getContextData().isFipsMode(); + this.crypto = (null == sslSessionContext) ? null : sslSessionContext.getContextData().getCrypto(); this.peerHost = peerHost; this.peerPort = peerPort; this.creationTime = System.currentTimeMillis(); @@ -266,7 +266,7 @@ final void invalidatedBySessionContext() public boolean isFipsMode() { - return isFips; + return fipsMode; } public boolean isValid() diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionContext.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionContext.java index 249cd18c6d..da88a753a6 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionContext.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSessionContext.java @@ -18,7 +18,6 @@ import org.bouncycastle.tls.SessionID; import org.bouncycastle.tls.TlsSession; import org.bouncycastle.tls.TlsUtils; -import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto; class ProvSSLSessionContext implements SSLSessionContext @@ -55,14 +54,9 @@ protected boolean removeEldestEntry(Map.Entry eldest) this.contextData = contextData; } - ProvSSLContextSpi getSSLContext() + ContextData getContextData() { - return contextData.getContext(); - } - - JcaTlsCrypto getCrypto() - { - return contextData.getCrypto(); + return contextData; } synchronized ProvSSLSession getSessionImpl(byte[] sessionID) diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketDirect.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketDirect.java index 245b1eb461..889ab1b60b 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketDirect.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketDirect.java @@ -66,14 +66,14 @@ class ProvSSLSocketDirect protected ProvSSLSocketDirect(ContextData contextData) { this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); } protected ProvSSLSocketDirect(ContextData contextData, InetAddress address, int port, InetAddress clientAddress, int clientPort) throws IOException { this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); implBind(clientAddress, clientPort); implConnect(address, port); @@ -82,7 +82,7 @@ protected ProvSSLSocketDirect(ContextData contextData, InetAddress address, int protected ProvSSLSocketDirect(ContextData contextData, InetAddress address, int port) throws IOException { this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); implConnect(address, port); } @@ -91,7 +91,7 @@ protected ProvSSLSocketDirect(ContextData contextData, String host, int port, In throws IOException, UnknownHostException { this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); this.peerHost = host; implBind(clientAddress, clientPort); @@ -101,7 +101,7 @@ protected ProvSSLSocketDirect(ContextData contextData, String host, int port, In protected ProvSSLSocketDirect(ContextData contextData, String host, int port) throws IOException, UnknownHostException { this.contextData = contextData; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); this.peerHost = host; implConnect(host, port); @@ -275,13 +275,13 @@ public synchronized SSLParameters getSSLParameters() @Override public synchronized String[] getSupportedCipherSuites() { - return contextData.getContext().getSupportedCipherSuites(); + return contextData.getSupportedCipherSuites(); } @Override public synchronized String[] getSupportedProtocols() { - return contextData.getContext().getSupportedProtocols(); + return contextData.getSupportedProtocols(); } public int getTransportID() @@ -374,7 +374,7 @@ public synchronized void setUseClientMode(boolean useClientMode) if (this.useClientMode != useClientMode) { - contextData.getContext().updateDefaultSSLParameters(sslParameters, useClientMode); + contextData.updateDefaultSSLParameters(sslParameters, useClientMode); this.useClientMode = useClientMode; } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketFactory.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketFactory.java index 5519dc20ee..1f0f061ba0 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketFactory.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketFactory.java @@ -52,7 +52,7 @@ public Socket createSocket(String host, int port, InetAddress localHost, int loc return SSLSocketUtil.create(contextData, host, port, localHost, localPort); } - @Override + // No @Override for 1.8 method public Socket createSocket(Socket s, InputStream consumed, boolean autoClose) throws IOException { return SSLSocketUtil.create(contextData, s, consumed, autoClose); @@ -67,12 +67,12 @@ public Socket createSocket(Socket s, String host, int port, boolean autoClose) t @Override public String[] getDefaultCipherSuites() { - return contextData.getContext().getDefaultCipherSuites(true); + return contextData.getDefaultCipherSuites(true); } @Override public String[] getSupportedCipherSuites() { - return contextData.getContext().getSupportedCipherSuites(); + return contextData.getSupportedCipherSuites(); } } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketWrap.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketWrap.java index 59fabd7bb4..e793543054 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketWrap.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketWrap.java @@ -78,7 +78,7 @@ protected ProvSSLSocketWrap(ContextData contextData, Socket s, InputStream consu this.consumed = consumed; this.autoClose = autoClose; this.useClientMode = false; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); notifyConnected(); } @@ -92,7 +92,7 @@ protected ProvSSLSocketWrap(ContextData contextData, Socket s, String host, int this.peerHost = host; this.autoClose = autoClose; this.useClientMode = true; - this.sslParameters = contextData.getContext().getDefaultSSLParameters(useClientMode); + this.sslParameters = contextData.getDefaultSSLParameters(useClientMode); notifyConnected(); } @@ -358,13 +358,13 @@ public synchronized SSLParameters getSSLParameters() @Override public synchronized String[] getSupportedCipherSuites() { - return contextData.getContext().getSupportedCipherSuites(); + return contextData.getSupportedCipherSuites(); } @Override public synchronized String[] getSupportedProtocols() { - return contextData.getContext().getSupportedProtocols(); + return contextData.getSupportedProtocols(); } @Override @@ -553,7 +553,7 @@ public synchronized void setUseClientMode(boolean useClientMode) if (this.useClientMode != useClientMode) { - contextData.getContext().updateDefaultSSLParameters(sslParameters, useClientMode); + contextData.updateDefaultSSLParameters(sslParameters, useClientMode); this.useClientMode = useClientMode; } diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsClient.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsClient.java index eb5d60eb4f..7fbcfd8d33 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsClient.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsClient.java @@ -174,7 +174,11 @@ protected Vector getSNIServerNames() List sniServerNames = sslParameters.getServerNames(); if (null == sniServerNames) { - String peerHostSNI = manager.getPeerHostSNI(); + /* + * A fully qualified domain name (FQDN) may contain a trailing dot. We remove it for the + * purpose of SNI and endpoint ID checks (e.g. SNIHostName doesn't permit it). + */ + String peerHostSNI = JsseUtils.stripTrailingDot(manager.getPeerHostSNI()); /* * TODO[jsse] Consider removing the restriction that the name must contain a '.' @@ -210,8 +214,7 @@ protected Vector getSNIServerNames() @Override protected int[] getSupportedCipherSuites() { - return manager.getContextData().getContext().getActiveCipherSuites(getCrypto(), sslParameters, - getProtocolVersions()); + return manager.getContextData().getActiveCipherSuites(getCrypto(), sslParameters, getProtocolVersions()); } @Override @@ -237,7 +240,7 @@ protected Vector getSupportedSignatureAlgorithmsCert( @Override protected ProtocolVersion[] getSupportedVersions() { - return manager.getContextData().getContext().getActiveProtocolVersions(sslParameters); + return manager.getContextData().getActiveProtocolVersions(sslParameters); } @Override @@ -478,9 +481,9 @@ public void notifyConnectionClosed() { super.notifyConnectionClosed(); - if (LOG.isLoggable(Level.INFO)) + if (LOG.isLoggable(Level.FINE)) { - LOG.info(clientID + " disconnected from " + JsseUtils.getPeerReport(manager)); + LOG.fine(clientID + " disconnected from " + JsseUtils.getPeerReport(manager)); } } @@ -489,9 +492,9 @@ public void notifyHandshakeBeginning() throws IOException { super.notifyHandshakeBeginning(); - if (LOG.isLoggable(Level.INFO)) + if (LOG.isLoggable(Level.FINE)) { - LOG.info(clientID + " opening connection to " + JsseUtils.getPeerReport(manager)); + LOG.fine(clientID + " opening connection to " + JsseUtils.getPeerReport(manager)); } ContextData contextData = manager.getContextData(); @@ -510,9 +513,9 @@ public synchronized void notifyHandshakeComplete() throws IOException this.handshakeComplete = true; - if (LOG.isLoggable(Level.INFO)) + if (LOG.isLoggable(Level.FINE)) { - LOG.info(clientID + " established connection with " + JsseUtils.getPeerReport(manager)); + LOG.fine(clientID + " established connection with " + JsseUtils.getPeerReport(manager)); } TlsSession connectionTlsSession = context.getSession(); @@ -552,8 +555,9 @@ public void notifySecureRenegotiation(boolean secureRenegotiation) throws IOExce @Override public void notifySelectedCipherSuite(int selectedCipherSuite) { - String selectedCipherSuiteName = manager.getContextData().getContext() - .validateNegotiatedCipherSuite(sslParameters, selectedCipherSuite); + final ContextData contextData = manager.getContextData(); + + String selectedCipherSuiteName = contextData.validateNegotiatedCipherSuite(sslParameters, selectedCipherSuite); if (LOG.isLoggable(Level.FINE)) { @@ -566,7 +570,7 @@ public void notifySelectedCipherSuite(int selectedCipherSuite) @Override public void notifyServerVersion(ProtocolVersion serverVersion) throws IOException { - String serverVersionName = manager.getContextData().getContext().validateNegotiatedProtocol(sslParameters, + String serverVersionName = manager.getContextData().validateNegotiatedProtocol(sslParameters, serverVersion); if (LOG.isLoggable(Level.FINE)) diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsServer.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsServer.java index f39a51b78a..c43076da5d 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsServer.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTlsServer.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashMap; @@ -30,6 +31,7 @@ import org.bouncycastle.tls.ClientCertificateType; import org.bouncycastle.tls.DefaultTlsServer; import org.bouncycastle.tls.KeyExchangeAlgorithm; +import org.bouncycastle.tls.NamedGroup; import org.bouncycastle.tls.ProtocolName; import org.bouncycastle.tls.ProtocolVersion; import org.bouncycastle.tls.SecurityParameters; @@ -45,6 +47,7 @@ import org.bouncycastle.tls.TlsUtils; import org.bouncycastle.tls.TrustedAuthority; import org.bouncycastle.tls.crypto.DHGroup; +import org.bouncycastle.tls.crypto.TlsDHConfig; import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; @@ -60,11 +63,6 @@ class ProvTlsServer // TODO[jsse] Integrate this into NamedGroupInfo private static final int provEphemeralDHKeySize = PropertyUtils.getIntegerSystemProperty("jdk.tls.ephemeralDHKeySize", 2048, 1024, 8192); - /* - * TODO[jsse] Does this selection override the restriction from 'jdk.tls.ephemeralDHKeySize'? - * TODO[fips] Probably should be ignored in fips mode? - */ - @SuppressWarnings("unused") private static final DHGroup[] provServerDefaultDHEParameters = getDefaultDHEParameters(); private static final boolean provServerEnableCA = PropertyUtils @@ -99,7 +97,7 @@ private static DHGroup[] getDefaultDHEParameters() return null; } - ArrayList result = new ArrayList(); + ArrayList dhGroups = new ArrayList(); int outerComma = -1; do { @@ -133,7 +131,7 @@ private static DHGroup[] getDefaultDHEParameters() DHGroup dhGroup = TlsDHUtils.getStandardGroupForDHParameters(p, g); if (null != dhGroup) { - result.add(dhGroup); + dhGroups.add(dhGroup); } else if (!p.isProbablePrime(120)) { @@ -142,7 +140,7 @@ else if (!p.isProbablePrime(120)) } else { - result.add(new DHGroup(p, null, g, 0)); + dhGroups.add(new DHGroup(p, null, g, 0)); } } catch (Exception e) @@ -153,7 +151,15 @@ else if (!p.isProbablePrime(120)) outerComma = closeBrace + 1; if (outerComma >= limit) { - return result.toArray(new DHGroup[result.size()]); + DHGroup[] result = dhGroups.toArray(new DHGroup[dhGroups.size()]); + java.util.Arrays.sort(result, new Comparator() + { + public int compare(DHGroup a, DHGroup b) + { + return a.getP().bitLength() - b.getP().bitLength(); + } + }); + return result; } } while (',' == input.charAt(outerComma)); @@ -238,16 +244,13 @@ protected String getDetailMessageNoCipherSuite() sb.append(" found no selectable cipher suite among the "); sb.append(offered.length); sb.append(" offered: "); - - ProvSSLContextSpi context = manager.getContextData().getContext(); - sb.append('['); - JsseUtils.appendCipherSuiteDetail(sb, context, offered[0]); + JsseUtils.appendCipherSuiteDetail(sb, offered[0]); for (int i = 1; i < offered.length; ++i) { sb.append(", "); - JsseUtils.appendCipherSuiteDetail(sb, context, offered[i]); + JsseUtils.appendCipherSuiteDetail(sb, offered[i]); } sb.append(']'); @@ -259,13 +262,29 @@ protected String getDetailMessageNoCipherSuite() @Override protected int getMaximumNegotiableCurveBits() { - return NamedGroupInfo.getMaximumBitsServerECDH(jsseSecurityParameters.namedGroups); + NamedGroupInfo.DefaultedResult maxBitsResult = NamedGroupInfo.getMaximumBitsServerECDH( + jsseSecurityParameters.namedGroups); + + int maxBits = maxBitsResult.getResult(); + + return maxBits; } @Override protected int getMaximumNegotiableFiniteFieldBits() { - int maxBits = NamedGroupInfo.getMaximumBitsServerFFDHE(jsseSecurityParameters.namedGroups); + NamedGroupInfo.DefaultedResult maxBitsResult = NamedGroupInfo.getMaximumBitsServerFFDHE( + jsseSecurityParameters.namedGroups); + + int maxBits = maxBitsResult.getResult(); + + if (maxBitsResult.isDefaulted() && + !TlsUtils.isNullOrEmpty(provServerDefaultDHEParameters) && + !manager.getContextData().isFipsMode()) + { + DHGroup largest = provServerDefaultDHEParameters[provServerDefaultDHEParameters.length - 1]; + maxBits = Math.max(maxBits, largest.getP().bitLength()); + } return maxBits >= provEphemeralDHKeySize ? maxBits : 0; } @@ -279,14 +298,13 @@ protected Vector getProtocolNames() @Override protected int[] getSupportedCipherSuites() { - return manager.getContextData().getContext().getActiveCipherSuites(getCrypto(), sslParameters, - getProtocolVersions()); + return manager.getContextData().getActiveCipherSuites(getCrypto(), sslParameters, getProtocolVersions()); } @Override protected ProtocolVersion[] getSupportedVersions() { - return manager.getContextData().getContext().getActiveProtocolVersions(sslParameters); + return manager.getContextData().getActiveProtocolVersions(sslParameters); } @Override @@ -295,6 +313,12 @@ protected boolean preferLocalCipherSuites() return sslParameters.getUseCipherSuitesOrder(); } + @Override + public boolean preferLocalSupportedGroups() + { + return sslParameters.getUseNamedGroupsOrder(); + } + @Override protected boolean selectCipherSuite(int cipherSuite) throws IOException { @@ -325,11 +349,41 @@ protected boolean selectCipherSuite(int cipherSuite) throws IOException } @Override - protected int selectDH(int minimumFiniteFieldBits) + public TlsDHConfig getDHConfig() throws IOException { + int minimumFiniteFieldBits = TlsDHUtils.getMinimumFiniteFieldBits(selectedCipherSuite); minimumFiniteFieldBits = Math.max(minimumFiniteFieldBits, provEphemeralDHKeySize); - return NamedGroupInfo.selectServerFFDHE(jsseSecurityParameters.namedGroups, minimumFiniteFieldBits); + NamedGroupInfo.DefaultedResult namedGroupResult = NamedGroupInfo.selectServerFFDHE( + jsseSecurityParameters.namedGroups, minimumFiniteFieldBits); + + int namedGroup = namedGroupResult.getResult(); + + if (namedGroupResult.isDefaulted() && + !TlsUtils.isNullOrEmpty(provServerDefaultDHEParameters) && + !manager.getContextData().isFipsMode()) + { + for (DHGroup dhGroup : provServerDefaultDHEParameters) + { + int bits = dhGroup.getP().bitLength(); + if (bits >= minimumFiniteFieldBits) + { + if (namedGroup < 0 || bits <= NamedGroup.getFiniteFieldBits(namedGroup)) + { + return new TlsDHConfig(dhGroup); + } + break; + } + } + } + + return TlsDHUtils.createNamedDHConfig(context, namedGroup); + } + + @Override + protected int selectDH(int minimumFiniteFieldBits) + { + throw new UnsupportedOperationException(); } @Override @@ -341,7 +395,7 @@ protected int selectDHDefault(int minimumFiniteFieldBits) @Override protected int selectECDH(int minimumCurveBits) { - return NamedGroupInfo.selectServerECDH(jsseSecurityParameters.namedGroups, minimumCurveBits); + return NamedGroupInfo.selectServerECDH(jsseSecurityParameters.namedGroups, minimumCurveBits).getResult(); } @Override @@ -619,8 +673,7 @@ public int getSelectedCipherSuite() throws IOException keyManagerMissCache = null; - String selectedCipherSuiteName = contextData.getContext().validateNegotiatedCipherSuite(sslParameters, - selectedCipherSuite); + String selectedCipherSuiteName = contextData.validateNegotiatedCipherSuite(sslParameters, selectedCipherSuite); if (LOG.isLoggable(Level.FINE)) { @@ -765,7 +818,7 @@ public ProtocolVersion getServerVersion() throws IOException { ProtocolVersion serverVersion = super.getServerVersion(); - String serverVersionName = manager.getContextData().getContext().validateNegotiatedProtocol(sslParameters, + String serverVersionName = manager.getContextData().validateNegotiatedProtocol(sslParameters, serverVersion); if (LOG.isLoggable(Level.FINE)) diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTrustManagerFactorySpi.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTrustManagerFactorySpi.java index 2958631e67..3db3930295 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTrustManagerFactorySpi.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvTrustManagerFactorySpi.java @@ -129,14 +129,14 @@ else if (null != tsPathProp) return ks; } - protected final boolean isInFipsMode; + protected final boolean fipsMode; protected final JcaJceHelper helper; protected ProvX509TrustManager x509TrustManager; - ProvTrustManagerFactorySpi(boolean isInFipsMode, JcaJceHelper helper) + ProvTrustManagerFactorySpi(boolean fipsMode, JcaJceHelper helper) { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; } @@ -187,7 +187,7 @@ protected void engineInit(KeyStore ks) try { - this.x509TrustManager = new ProvX509TrustManager(isInFipsMode, helper, trustAnchors); + this.x509TrustManager = new ProvX509TrustManager(fipsMode, helper, trustAnchors); } catch (InvalidAlgorithmParameterException e) { @@ -207,7 +207,7 @@ protected void engineInit(ManagerFactoryParameters spec) throw new InvalidAlgorithmParameterException("parameters must inherit from PKIXParameters"); } - this.x509TrustManager = new ProvX509TrustManager(isInFipsMode, helper, (PKIXParameters)certPathParameters); + this.x509TrustManager = new ProvX509TrustManager(fipsMode, helper, (PKIXParameters)certPathParameters); } else if (null == spec) { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509KeyManager.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509KeyManager.java index 269dfff1f1..23ec3438aa 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509KeyManager.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509KeyManager.java @@ -56,7 +56,7 @@ class ProvX509KeyManager private final AtomicLong versions = new AtomicLong(); - private final boolean isInFipsMode; + private final boolean fipsMode; private final JcaJceHelper helper; private final List builders; @@ -215,9 +215,9 @@ private static String[] getKeyTypesLegacyServer(int... keyExchangeAlgorithms) return keyTypes; } - ProvX509KeyManager(boolean isInFipsMode, JcaJceHelper helper, List builders) + ProvX509KeyManager(boolean fipsMode, JcaJceHelper helper, List builders) { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; this.builders = builders; } @@ -510,7 +510,7 @@ private Match getPotentialMatch(int builderIndex, KeyStore.Builder builder, KeyS forServer, chain); if (keyTypeIndex >= 0) { - MatchQuality quality = getKeyTypeQuality(isInFipsMode, helper, keyTypes, algorithmConstraints, + MatchQuality quality = getKeyTypeQuality(fipsMode, helper, keyTypes, algorithmConstraints, forServer, atDate, requestedHostName, chain, keyTypeIndex); if (MatchQuality.NONE != quality) { @@ -587,7 +587,7 @@ private KeyStore.PrivateKeyEntry loadPrivateKeyEntry(String alias) return null; } - static MatchQuality getKeyTypeQuality(boolean isInFipsMode, JcaJceHelper helper, List keyTypes, + static MatchQuality getKeyTypeQuality(boolean fipsMode, JcaJceHelper helper, List keyTypes, BCAlgorithmConstraints algorithmConstraints, boolean forServer, Date atDate, String requestedHostName, X509Certificate[] chain, int keyTypeIndex) { @@ -595,7 +595,7 @@ static MatchQuality getKeyTypeQuality(boolean isInFipsMode, JcaJceHelper helper, LOG.finer("EE cert potentially usable for key type: " + keyType); - if (!isSuitableChain(isInFipsMode, helper, chain, algorithmConstraints, forServer)) + if (!isSuitableChain(fipsMode, helper, chain, algorithmConstraints, forServer)) { LOG.finer("Unsuitable chain for key type: " + keyType); return MatchQuality.NONE; @@ -795,7 +795,7 @@ private static int getSuitableKeyTypeForEECert(X509Certificate eeCert, List credentials; @@ -73,10 +73,10 @@ private static Map loadCredentials(KeyStore ks, char[] passw return Collections.unmodifiableMap(credentials); } - ProvX509KeyManagerSimple(boolean isInFipsMode, JcaJceHelper helper, KeyStore ks, char[] password) + ProvX509KeyManagerSimple(boolean fipsMode, JcaJceHelper helper, KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; this.credentials = loadCredentials(ks, password); } @@ -287,7 +287,7 @@ private Match getPotentialMatch(Credential credential, List keyTypes, in algorithmConstraints, forServer, chain); if (keyTypeIndex >= 0) { - MatchQuality quality = ProvX509KeyManager.getKeyTypeQuality(isInFipsMode, helper, keyTypes, + MatchQuality quality = ProvX509KeyManager.getKeyTypeQuality(fipsMode, helper, keyTypes, algorithmConstraints, forServer, atDate, requestedHostName, chain, keyTypeIndex); if (MatchQuality.NONE != quality) { diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509TrustManager.java b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509TrustManager.java index 1cf596950f..e7de360341 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509TrustManager.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/ProvX509TrustManager.java @@ -84,16 +84,16 @@ private static Map createKeyUsagesServer() return Collections.unmodifiableMap(keyUsages); } - private final boolean isInFipsMode; + private final boolean fipsMode; private final JcaJceHelper helper; private final Set trustedCerts; private final PKIXBuilderParameters pkixParametersTemplate; private final X509TrustManager exportX509TrustManager; - ProvX509TrustManager(boolean isInFipsMode, JcaJceHelper helper, Set trustAnchors) + ProvX509TrustManager(boolean fipsMode, JcaJceHelper helper, Set trustAnchors) throws InvalidAlgorithmParameterException { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; this.trustedCerts = getTrustedCerts(trustAnchors); @@ -111,10 +111,10 @@ private static Map createKeyUsagesServer() this.exportX509TrustManager = X509TrustManagerUtil.exportX509TrustManager(this); } - ProvX509TrustManager(boolean isInFipsMode, JcaJceHelper helper, PKIXParameters baseParameters) + ProvX509TrustManager(boolean fipsMode, JcaJceHelper helper, PKIXParameters baseParameters) throws InvalidAlgorithmParameterException { - this.isInFipsMode = isInFipsMode; + this.fipsMode = fipsMode; this.helper = helper; this.trustedCerts = getTrustedCerts(baseParameters.getTrustAnchors()); @@ -157,12 +157,14 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) checkTrusted(chain, authType, null, false); } + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkTrusted(chain, authType, TransportData.from(socket), false); } + @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { @@ -175,12 +177,14 @@ public void checkServerTrusted(X509Certificate[] chain, String authType) checkTrusted(chain, authType, null, true); } + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkTrusted(chain, authType, TransportData.from(socket), true); } + @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { @@ -232,7 +236,7 @@ private X509Certificate[] buildCertPath(X509Certificate[] chain, BCAlgorithmCons } PKIXBuilderParameters pkixParameters = (PKIXBuilderParameters)pkixParametersTemplate.clone(); - pkixParameters.addCertPathChecker(new ProvAlgorithmChecker(isInFipsMode, helper, algorithmConstraints)); + pkixParameters.addCertPathChecker(new ProvAlgorithmChecker(fipsMode, helper, algorithmConstraints)); pkixParameters.addCertStore(certStore); pkixParameters.setTargetCertConstraints( createTargetCertConstraints(eeCert, pkixParameters.getTargetCertConstraints())); @@ -423,6 +427,13 @@ private static void checkEndpointID(X509Certificate certificate, String endpoint BCExtendedSSLSession sslSession) throws CertificateException { String peerHost = sslSession.getPeerHost(); + + /* + * A fully qualified domain name (FQDN) may contain a trailing dot. We remove it for the purpose of + * SNI and endpoint ID checks (e.g. SNIHostName doesn't permit it). + */ + peerHost = JsseUtils.stripTrailingDot(peerHost); + if (checkServerTrusted) { BCSNIHostName sniHostName = JsseUtils.getSNIHostName(sslSession.getRequestedServerNames()); diff --git a/tls/src/main/java/org/bouncycastle/jsse/provider/SignatureSchemeInfo.java b/tls/src/main/java/org/bouncycastle/jsse/provider/SignatureSchemeInfo.java index ae80e14d8e..e56f8bc677 100644 --- a/tls/src/main/java/org/bouncycastle/jsse/provider/SignatureSchemeInfo.java +++ b/tls/src/main/java/org/bouncycastle/jsse/provider/SignatureSchemeInfo.java @@ -37,6 +37,9 @@ class SignatureSchemeInfo private static final String PROPERTY_CLIENT_SIGNATURE_SCHEMES = "jdk.tls.client.SignatureSchemes"; private static final String PROPERTY_SERVER_SIGNATURE_SCHEMES = "jdk.tls.server.SignatureSchemes"; + private static final String PROPERTY_CLIENT_SIGNATURE_SCHEMES_CERT = "org.bouncycastle.jsse.client.SignatureSchemesCert"; + private static final String PROPERTY_SERVER_SIGNATURE_SCHEMES_CERT = "org.bouncycastle.jsse.server.SignatureSchemesCert"; + // NOTE: Not all of these are necessarily enabled/supported; it will be checked at runtime private enum All { @@ -68,6 +71,11 @@ private enum All sm2sig_sm3(SignatureScheme.sm2sig_sm3, "SM3withSM2", "EC"), + // TODO[tls] Need mechanism for restricting signature schemes to TLS 1.3+ before adding +// DRAFT_mldsa44(SignatureScheme.DRAFT_mldsa44, "ML-DSA-44", "ML-DSA-44"), +// DRAFT_mldsa65(SignatureScheme.DRAFT_mldsa65, "ML-DSA-65", "ML-DSA-65"), +// DRAFT_mldsa87(SignatureScheme.DRAFT_mldsa87, "ML-DSA-87", "ML-DSA-87"), + /* * Legacy/Historical: mostly not supported in 1.3, except ecdsa_sha1 and rsa_pkcs1_sha1 are * still permitted as a last resort for certs. @@ -148,23 +156,22 @@ static class PerConnection private final AtomicReference> peerSigSchemes; private final AtomicReference> peerSigSchemesCert; - PerConnection(List localSigSchemes) + PerConnection(List localSigSchemes, List localSigSchemesCert) { - // TODO[tls13] No JSSE API to configure localSigSchemesCert?) this.localSigSchemes = localSigSchemes; - this.localSigSchemesCert = null; + this.localSigSchemesCert = localSigSchemesCert; this.peerSigSchemes = new AtomicReference>(); this.peerSigSchemesCert = new AtomicReference>(); } String[] getLocalJcaSignatureAlgorithms() { - return getJcaSignatureAlgorithms(getLocalJcaSigSchemesCert()); + return getJcaSignatureAlgorithms(getLocalSigSchemesCert()); } String[] getLocalJcaSignatureAlgorithmsBC() { - return getJcaSignatureAlgorithmsBC(getLocalJcaSigSchemesCert()); + return getJcaSignatureAlgorithmsBC(getLocalSigSchemesCert()); } Vector getLocalSignatureAndHashAlgorithms() @@ -177,21 +184,38 @@ Vector getLocalSignatureAndHashAlgorithmsCert() return getSignatureAndHashAlgorithms(localSigSchemesCert); } + List getLocalSigSchemes() + { + return localSigSchemes; + } + + List getLocalSigSchemesCert() + { + return localSigSchemesCert != null ? localSigSchemesCert : getLocalSigSchemes(); + } + String[] getPeerJcaSignatureAlgorithms() { - return getJcaSignatureAlgorithms(getPeerJcaSigSchemesCert()); + return getJcaSignatureAlgorithms(getPeerSigSchemesCert()); } String[] getPeerJcaSignatureAlgorithmsBC() { - return getJcaSignatureAlgorithmsBC(getPeerJcaSigSchemesCert()); + return getJcaSignatureAlgorithmsBC(getPeerSigSchemesCert()); } - Iterable getPeerSigSchemes() + List getPeerSigSchemes() { return peerSigSchemes.get(); } + List getPeerSigSchemesCert() + { + List sigSchemesCert = peerSigSchemesCert.get(); + + return sigSchemesCert != null ? sigSchemesCert : getPeerSigSchemes(); + } + boolean hasLocalSignatureScheme(SignatureSchemeInfo signatureSchemeInfo) { return localSigSchemes.contains(signatureSchemeInfo); @@ -202,30 +226,22 @@ void notifyPeerData(List sigSchemes, List getLocalJcaSigSchemesCert() - { - return localSigSchemesCert == null ? localSigSchemes : localSigSchemesCert; - } - - private List getPeerJcaSigSchemesCert() - { - List sigSchemesCert = peerSigSchemesCert.get(); - - return sigSchemesCert == null ? peerSigSchemes.get() : sigSchemesCert; - } } static class PerContext { private final Map index; private final int[] candidatesClient, candidatesServer; + private final int[] candidatesCertClient, candidatesCertServer; - PerContext(Map index, int[] candidatesClient, int[] candidatesServer) + PerContext(Map index, int[] candidatesClient, int[] candidatesServer, + int[] candidatesCertClient, int[] candidatesCertServer) { this.index = index; this.candidatesClient = candidatesClient; this.candidatesServer = candidatesServer; + this.candidatesCertClient = candidatesCertClient; + this.candidatesCertServer = candidatesCertServer; } } @@ -235,7 +251,7 @@ static PerConnection createPerConnectionClient(PerContext perContext, ProvSSLPar ProtocolVersion latest = ProtocolVersion.getLatestTLS(activeProtocolVersions); if (!TlsUtils.isSignatureAlgorithmsExtensionAllowed(latest)) { - return new PerConnection(null); + return new PerConnection(null, null); } ProtocolVersion earliest = ProtocolVersion.getEarliestTLS(activeProtocolVersions); @@ -248,7 +264,7 @@ static PerConnection createPerConnectionServer(PerContext perContext, ProvSSLPar { if (!TlsUtils.isSignatureAlgorithmsExtensionAllowed(negotiatedVersion)) { - return new PerConnection(null); + return new PerConnection(null, null); } return createPerConnection(perContext, true, sslParameters, negotiatedVersion, negotiatedVersion, namedGroups); @@ -257,78 +273,129 @@ static PerConnection createPerConnectionServer(PerContext perContext, ProvSSLPar private static PerConnection createPerConnection(PerContext perContext, boolean isServer, ProvSSLParameters sslParameters, ProtocolVersion earliest, ProtocolVersion latest, NamedGroupInfo.PerConnection namedGroups) { - String[] signatureSchemes = sslParameters.getSignatureSchemes(); - int[] candidates; - if (signatureSchemes == null) { - candidates = isServer ? perContext.candidatesServer : perContext.candidatesClient; + String[] signatureSchemes = sslParameters.getSignatureSchemes(); + + if (signatureSchemes == null) + { + candidates = isServer ? perContext.candidatesServer : perContext.candidatesClient; + + if (candidates == null) + { + candidates = CANDIDATES_DEFAULT; + } + } + else + { + candidates = createCandidates(perContext.index, signatureSchemes, "SSLParameters.signatureSchemes"); + } } - else + + int[] candidatesCert; { - candidates = createCandidates(perContext.index, signatureSchemes, "SSLParameters.signatureSchemes"); + String[] signatureSchemesCert = sslParameters.getSignatureSchemesCert(); + + if (signatureSchemesCert == null) + { + candidatesCert = isServer ? perContext.candidatesCertServer : perContext.candidatesCertClient; + } + else + { + candidatesCert = createCandidates(perContext.index, signatureSchemesCert, + "SSLParameters.signatureSchemesCert"); + } } BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints(); boolean post13Active = TlsUtils.isTLSv13(latest); boolean pre13Active = !TlsUtils.isTLSv13(earliest); - int count = candidates.length; - ArrayList localSigSchemes = new ArrayList(count); - for (int i = 0; i < count; ++i) + ArrayList localSigSchemes; { - Integer candidate = Integers.valueOf(candidates[i]); - SignatureSchemeInfo signatureSchemeInfo = perContext.index.get(candidate); + int count = candidates.length; + localSigSchemes = new ArrayList(count); + for (int i = 0; i < count; ++i) + { + Integer candidate = Integers.valueOf(candidates[i]); + SignatureSchemeInfo signatureSchemeInfo = perContext.index.get(candidate); + + if (null != signatureSchemeInfo + && signatureSchemeInfo.isActiveCerts(algorithmConstraints, post13Active, pre13Active, namedGroups)) + { + localSigSchemes.add(signatureSchemeInfo); + } + } + localSigSchemes.trimToSize(); + } - if (null != signatureSchemeInfo - && signatureSchemeInfo.isActiveCerts(algorithmConstraints, post13Active, pre13Active, namedGroups)) + ArrayList localSigSchemesCert = null; + if (candidatesCert != null) + { + int count = candidatesCert.length; + localSigSchemesCert = new ArrayList(count); + for (int i = 0; i < count; ++i) { - localSigSchemes.add(signatureSchemeInfo); + Integer candidate = Integers.valueOf(candidatesCert[i]); + SignatureSchemeInfo signatureSchemeInfo = perContext.index.get(candidate); + + if (null != signatureSchemeInfo + && signatureSchemeInfo.isActiveCerts(algorithmConstraints, post13Active, pre13Active, namedGroups)) + { + localSigSchemesCert.add(signatureSchemeInfo); + } } + localSigSchemesCert.trimToSize(); } - localSigSchemes.trimToSize(); - return new PerConnection(localSigSchemes); + + return new PerConnection(localSigSchemes, localSigSchemesCert); } static PerContext createPerContext(boolean isFipsContext, JcaTlsCrypto crypto, NamedGroupInfo.PerContext namedGroups) { Map index = createIndex(isFipsContext, crypto, namedGroups); + int[] candidatesClient = createCandidatesFromProperty(index, PROPERTY_CLIENT_SIGNATURE_SCHEMES); int[] candidatesServer = createCandidatesFromProperty(index, PROPERTY_SERVER_SIGNATURE_SCHEMES); - return new PerContext(index, candidatesClient, candidatesServer); + int[] candidatesCertClient = createCandidatesFromProperty(index, PROPERTY_CLIENT_SIGNATURE_SCHEMES_CERT); + int[] candidatesCertServer = createCandidatesFromProperty(index, PROPERTY_SERVER_SIGNATURE_SCHEMES_CERT); + + return new PerContext(index, candidatesClient, candidatesServer, candidatesCertClient, candidatesCertServer); } - static String[] getJcaSignatureAlgorithms(Collection infos) + private static String[] getJcaSignatureAlgorithms(Collection infos) { if (null == infos) { return TlsUtils.EMPTY_STRINGS; } - ArrayList result = new ArrayList(); + String[] result = new String[infos.size()]; + int resultPos = 0; for (SignatureSchemeInfo info : infos) { // TODO The two kinds of PSS signature scheme can give duplicates here - result.add(info.getJcaSignatureAlgorithm()); + result[resultPos++] = info.getJcaSignatureAlgorithm(); } - return result.toArray(TlsUtils.EMPTY_STRINGS); + return result; } - static String[] getJcaSignatureAlgorithmsBC(Collection infos) + private static String[] getJcaSignatureAlgorithmsBC(Collection infos) { if (null == infos) { return TlsUtils.EMPTY_STRINGS; } - ArrayList result = new ArrayList(); + String[] result = new String[infos.size()]; + int resultPos = 0; for (SignatureSchemeInfo info : infos) { - result.add(info.getJcaSignatureAlgorithmBC()); + result[resultPos++] = info.getJcaSignatureAlgorithmBC(); } - return result.toArray(TlsUtils.EMPTY_STRINGS); + return result; } static SignatureAndHashAlgorithm getSignatureAndHashAlgorithm(int signatureScheme) @@ -341,7 +408,8 @@ static SignatureAndHashAlgorithm getSignatureAndHashAlgorithm(int signatureSchem return SignatureScheme.getSignatureAndHashAlgorithm(signatureScheme); } - static Vector getSignatureAndHashAlgorithms(List signatureSchemeInfos) + private static Vector getSignatureAndHashAlgorithms( + Collection signatureSchemeInfos) { // TODO[tls13] Actually should return empty for empty? if (null == signatureSchemeInfos || signatureSchemeInfos.isEmpty()) @@ -455,7 +523,7 @@ private static int[] createCandidatesFromProperty(Map V call(Callable callable) throws Exception @Override protected Socket configureSocket(Socket s) { - if (url != null && s instanceof BCSSLSocket) + if (host != null && s instanceof BCSSLSocket) { BCSSLSocket ssl = (BCSSLSocket)s; - String host = url.getHost(); - if (host != null) - { - LOG.fine("Setting host on socket: " + host); + LOG.fine("Setting host on socket: " + host); - ssl.setHost(host); - } + ssl.setHost(host); } return s; } diff --git a/tls/src/main/java/org/bouncycastle/tls/AbstractTlsServer.java b/tls/src/main/java/org/bouncycastle/tls/AbstractTlsServer.java index 76869c0265..e04ffa5179 100644 --- a/tls/src/main/java/org/bouncycastle/tls/AbstractTlsServer.java +++ b/tls/src/main/java/org/bouncycastle/tls/AbstractTlsServer.java @@ -78,6 +78,16 @@ protected String getDetailMessageNoCipherSuite() return "No selectable cipher suite"; } + protected int getMaximumDefaultCurveBits() + { + return NamedGroup.getCurveBits(NamedGroup.secp521r1); + } + + protected int getMaximumDefaultFiniteFieldBits() + { + return NamedGroup.getFiniteFieldBits(NamedGroup.ffdhe8192); + } + protected int getMaximumNegotiableCurveBits() { int maxBits = 0; @@ -96,7 +106,7 @@ protected int getMaximumNegotiableCurveBits() * extensions. In this case, the server is free to choose any one of the elliptic curves or point * formats [...]. */ - maxBits = NamedGroup.getMaximumCurveBits(); + maxBits = getMaximumDefaultCurveBits(); } return maxBits; } @@ -121,7 +131,7 @@ protected int getMaximumNegotiableFiniteFieldBits() * entirely or contains no FFDHE groups (i.e., no codepoints between 256 and 511, inclusive), then * the server [...] MAY select an FFDHE cipher suite and offer an FFDHE group of its choice [...]. */ - maxBits = NamedGroup.getMaximumFiniteFieldBits(); + maxBits = getMaximumDefaultFiniteFieldBits(); } return maxBits; } @@ -145,6 +155,11 @@ protected boolean preferLocalCipherSuites() return false; } + public boolean preferLocalSupportedGroups() + { + return false; + } + protected boolean selectCipherSuite(int cipherSuite) throws IOException { this.selectedCipherSuite = cipherSuite; @@ -153,22 +168,32 @@ protected boolean selectCipherSuite(int cipherSuite) throws IOException protected int selectDH(int minimumFiniteFieldBits) { + boolean anyPeerFF = false; int[] clientSupportedGroups = context.getSecurityParametersHandshake().getClientSupportedGroups(); - if (clientSupportedGroups == null) - { - return selectDHDefault(minimumFiniteFieldBits); - } - - // Try to find a supported named group of the required size from the client's list. - for (int i = 0; i < clientSupportedGroups.length; ++i) + if (clientSupportedGroups != null) { - int namedGroup = clientSupportedGroups[i]; - if (NamedGroup.getFiniteFieldBits(namedGroup) >= minimumFiniteFieldBits) + // Try to find a supported named group of the required size from the client's list. + for (int i = 0; i < clientSupportedGroups.length; ++i) { - return namedGroup; + int namedGroup = clientSupportedGroups[i]; + anyPeerFF |= NamedGroup.isFiniteField(namedGroup); + + if (NamedGroup.getFiniteFieldBits(namedGroup) >= minimumFiniteFieldBits) + { + // This default server implementation supports all NamedGroup finite fields + return namedGroup; + } } } - + if (!anyPeerFF) + { + /* + * RFC 7919 4. If [...] the Supported Groups extension is either absent from the ClientHello + * entirely or contains no FFDHE groups (i.e., no codepoints between 256 and 511, inclusive), then + * the server [...] MAY select an FFDHE cipher suite and offer an FFDHE group of its choice [...]. + */ + return selectDHDefault(minimumFiniteFieldBits); + } return -1; } @@ -187,6 +212,11 @@ protected int selectECDH(int minimumCurveBits) int[] clientSupportedGroups = context.getSecurityParametersHandshake().getClientSupportedGroups(); if (clientSupportedGroups == null) { + /* + * RFC 4492 4. A client that proposes ECC cipher suites may choose not to include these + * extensions. In this case, the server is free to choose any one of the elliptic curves or point + * formats [...]. + */ return selectECDHDefault(minimumCurveBits); } @@ -196,6 +226,7 @@ protected int selectECDH(int minimumCurveBits) int namedGroup = clientSupportedGroups[i]; if (NamedGroup.getCurveBits(namedGroup) >= minimumCurveBits) { + // This default server implementation supports all NamedGroup curves return namedGroup; } } diff --git a/tls/src/main/java/org/bouncycastle/tls/CipherSuite.java b/tls/src/main/java/org/bouncycastle/tls/CipherSuite.java index c4938e1562..42b1e38de7 100644 --- a/tls/src/main/java/org/bouncycastle/tls/CipherSuite.java +++ b/tls/src/main/java/org/bouncycastle/tls/CipherSuite.java @@ -452,7 +452,7 @@ public static boolean isSCSV(int cipherSuite) public static final int TLS_SM4_CCM_SM3 = 0x00C7; /* - * draft-smyshlyaev-tls12-gost-suites-10 + * RFC 9189 */ public static final int TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC = 0xC100; public static final int TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC = 0xC101; diff --git a/tls/src/main/java/org/bouncycastle/tls/ClientCertificateType.java b/tls/src/main/java/org/bouncycastle/tls/ClientCertificateType.java index 125142984b..b4130b7978 100644 --- a/tls/src/main/java/org/bouncycastle/tls/ClientCertificateType.java +++ b/tls/src/main/java/org/bouncycastle/tls/ClientCertificateType.java @@ -21,7 +21,7 @@ public class ClientCertificateType public static final short ecdsa_fixed_ecdh = 66; /* - * draft-smyshlyaev-tls12-gost-suites-10 + * RFC 9189 */ public static final short gost_sign256 = 67; public static final short gost_sign512 = 68; diff --git a/tls/src/main/java/org/bouncycastle/tls/DTLSClientProtocol.java b/tls/src/main/java/org/bouncycastle/tls/DTLSClientProtocol.java index 44c4015973..a0e7d45123 100644 --- a/tls/src/main/java/org/bouncycastle/tls/DTLSClientProtocol.java +++ b/tls/src/main/java/org/bouncycastle/tls/DTLSClientProtocol.java @@ -420,10 +420,11 @@ protected byte[] generateClientHello(ClientHandshakeState state) TlsSession sessionToResume = offeringDTLSv12Minus ? client.getSessionToResume() : null; - boolean fallback = client.isFallback(); - + // NOTE: Client is free to modify the cipher suites up until getSessionToResume state.offeredCipherSuites = client.getCipherSuites(); + boolean fallback = client.isFallback(); + state.clientExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(client.getClientExtensions()); final boolean shouldUseEMS = client.shouldUseExtendedMasterSecret(); @@ -620,13 +621,10 @@ protected boolean establishSession(ClientHandshakeState state, TlsSession sessio return false; } - boolean isEMS = sessionParameters.isExtendedMasterSecret(); - if (!TlsUtils.isExtendedMasterSecretOptional(sessionVersion)) + if (!sessionParameters.isExtendedMasterSecret() && + !TlsUtils.isExtendedMasterSecretOptional(sessionVersion)) { - if (!isEMS) - { - return false; - } + return false; } TlsCrypto crypto = state.clientContext.getCrypto(); diff --git a/tls/src/main/java/org/bouncycastle/tls/DTLSServerProtocol.java b/tls/src/main/java/org/bouncycastle/tls/DTLSServerProtocol.java index 21a067c3f0..bda746305b 100644 --- a/tls/src/main/java/org/bouncycastle/tls/DTLSServerProtocol.java +++ b/tls/src/main/java/org/bouncycastle/tls/DTLSServerProtocol.java @@ -751,13 +751,10 @@ protected boolean establishSession(ServerHandshakeState state, TlsSession sessio return false; } - boolean isEMS = sessionParameters.isExtendedMasterSecret(); - if (!TlsUtils.isExtendedMasterSecretOptional(sessionVersion)) + if (!sessionParameters.isExtendedMasterSecret() && + !TlsUtils.isExtendedMasterSecretOptional(sessionVersion)) { - if (!isEMS) - { - return false; - } + return false; } TlsCrypto crypto = state.serverContext.getCrypto(); diff --git a/tls/src/main/java/org/bouncycastle/tls/EncryptionAlgorithm.java b/tls/src/main/java/org/bouncycastle/tls/EncryptionAlgorithm.java index 1af112ca9e..a1e44979ab 100644 --- a/tls/src/main/java/org/bouncycastle/tls/EncryptionAlgorithm.java +++ b/tls/src/main/java/org/bouncycastle/tls/EncryptionAlgorithm.java @@ -77,4 +77,11 @@ public class EncryptionAlgorithm * GMT 0024-2014 */ public static final int SM4_CBC = 28; + + /* + * RFC 9189 + */ + public static final int KUZNYECHIK_CTR_OMAC = 29; + public static final int MAGMA_CTR_OMAC = 30; + public static final int _28147_CNT_IMIT = 31; } diff --git a/tls/src/main/java/org/bouncycastle/tls/HandshakeType.java b/tls/src/main/java/org/bouncycastle/tls/HandshakeType.java index b87f24c9ce..8901144bf7 100644 --- a/tls/src/main/java/org/bouncycastle/tls/HandshakeType.java +++ b/tls/src/main/java/org/bouncycastle/tls/HandshakeType.java @@ -42,11 +42,27 @@ public class HandshakeType public static final short key_update = 24; public static final short message_hash = 254; + /* + * RFC 8870 + */ + public static final short ekt_key = 26; + /* * RFC 8879 */ public static final short compressed_certificate = 25; + /* + * RFC 9147 + */ + public static final short request_connection_id = 9; + public static final short new_connection_id = 10; + + /* + * RFC 9261 + */ + public static final short client_certificate_request = 17; + public static String getName(short handshakeType) { switch (handshakeType) @@ -91,8 +107,16 @@ public static String getName(short handshakeType) return "key_update"; case message_hash: return "message_hash"; + case ekt_key: + return "ekt_key"; case compressed_certificate: return "compressed_certificate"; + case request_connection_id: + return "request_connection_id"; + case new_connection_id: + return "new_connection_id"; + case client_certificate_request: + return "client_certificate_request"; default: return "UNKNOWN"; } @@ -127,7 +151,11 @@ public static boolean isRecognized(short handshakeType) case encrypted_extensions: case key_update: case message_hash: + case ekt_key: case compressed_certificate: + case request_connection_id: + case new_connection_id: + case client_certificate_request: return true; default: return false; diff --git a/tls/src/main/java/org/bouncycastle/tls/KeyExchangeAlgorithm.java b/tls/src/main/java/org/bouncycastle/tls/KeyExchangeAlgorithm.java index 619577f0cb..7329ae843e 100644 --- a/tls/src/main/java/org/bouncycastle/tls/KeyExchangeAlgorithm.java +++ b/tls/src/main/java/org/bouncycastle/tls/KeyExchangeAlgorithm.java @@ -59,6 +59,11 @@ public class KeyExchangeAlgorithm */ public static final int SM2 = 25; + /* + * RFC 9189 + */ + public static final int GOSTR341112_256 = 26; + public static boolean isAnonymous(int keyExchangeAlgorithm) { switch (keyExchangeAlgorithm) diff --git a/tls/src/main/java/org/bouncycastle/tls/NamedGroup.java b/tls/src/main/java/org/bouncycastle/tls/NamedGroup.java index 2e4bf4d510..d8338c2929 100644 --- a/tls/src/main/java/org/bouncycastle/tls/NamedGroup.java +++ b/tls/src/main/java/org/bouncycastle/tls/NamedGroup.java @@ -61,7 +61,7 @@ public class NamedGroup public static final int brainpoolP512r1tls13 = 33; /* - * draft-smyshlyaev-tls12-gost-suites-10 + * RFC 9189 */ public static final int GC256A = 34; public static final int GC256B = 35; @@ -102,23 +102,29 @@ public class NamedGroup public static final int arbitrary_explicit_prime_curves = 0xFF01; public static final int arbitrary_explicit_char2_curves = 0xFF02; - /** Experimental API (unstable): unofficial value from Open Quantum Safe project. */ + /** @deprecated Experimental API (unstable): unofficial value from Open Quantum Safe project. */ public static final int OQS_mlkem512 = 0x0247; - /** Experimental API (unstable): unofficial value from Open Quantum Safe project. */ + /** @deprecated Experimental API (unstable): unofficial value from Open Quantum Safe project. */ public static final int OQS_mlkem768 = 0x0248; - /** Experimental API (unstable): unofficial value from Open Quantum Safe project. */ + /** @deprecated Experimental API (unstable): unofficial value from Open Quantum Safe project. */ public static final int OQS_mlkem1024 = 0x0249; /* - * draft-connolly-tls-mlkem-key-agreement-01 + * draft-connolly-tls-mlkem-key-agreement-05 */ - /** Experimental API (unstable): draft value requested in draft-connolly-tls-mlkem-key-agreement. */ - public static final int DRAFT_mlkem768 = 0x0768; - /** Experimental API (unstable): draft value requested in draft-connolly-tls-mlkem-key-agreement. */ - public static final int DRAFT_mlkem1024 = 0x1024; + public static final int MLKEM512 = 0x0200; + public static final int MLKEM768 = 0x0201; + public static final int MLKEM1024 = 0x0202; + + /* + * draft-ietf-tls-ecdhe-mlkem-00 + */ + public static final int SecP256r1MLKEM768 = 0x11EB; + public static final int X25519MLKEM768 = 0x11EC; + public static final int SecP384r1MLKEM1024 = 0x11ED; /* Names of the actual underlying elliptic curves (not necessarily matching the NamedGroup names). */ - private static final String[] CURVE_NAMES = new String[] { "sect163k1", "sect163r1", "sect163r2", "sect193r1", + private static final String[] CURVE_NAMES = new String[]{ "sect163k1", "sect163r1", "sect163r2", "sect193r1", "sect193r2", "sect233k1", "sect233r1", "sect239k1", "sect283k1", "sect283r1", "sect409k1", "sect409r1", "sect571k1", "sect571r1", "secp160k1", "secp160r1", "secp160r2", "secp192k1", "secp192r1", "secp224k1", "secp224r1", "secp256k1", "secp256r1", "secp384r1", "secp521r1", "brainpoolP256r1", "brainpoolP384r1", @@ -127,7 +133,7 @@ public class NamedGroup "GostR3410-2001-CryptoPro-C", "Tc26-Gost-3410-12-512-paramSetA", "Tc26-Gost-3410-12-512-paramSetB", "Tc26-Gost-3410-12-512-paramSetC", "sm2p256v1" }; - private static final String[] FINITE_FIELD_NAMES = new String[] { "ffdhe2048", "ffdhe3072", "ffdhe4096", + private static final String[] FINITE_FIELD_NAMES = new String[]{ "ffdhe2048", "ffdhe3072", "ffdhe4096", "ffdhe6144", "ffdhe8192" }; public static boolean canBeNegotiated(int namedGroup, ProtocolVersion version) @@ -164,7 +170,7 @@ public static boolean canBeNegotiated(int namedGroup, ProtocolVersion version) } } - if (refersToASpecificKem(namedGroup)) + if (refersToASpecificHybrid(namedGroup) || refersToASpecificKem(namedGroup)) { return isTLSv13; } @@ -298,17 +304,78 @@ public static String getFiniteFieldName(int namedGroup) return null; } + public static int getHybridFirst(int namedGroup) + { + switch (namedGroup) + { + case SecP256r1MLKEM768: + return secp256r1; + case X25519MLKEM768: + return MLKEM768; + case SecP384r1MLKEM1024: + return secp384r1; + default: + return -1; + } + } + + public static int getHybridSecond(int namedGroup) + { + switch (namedGroup) + { + case SecP256r1MLKEM768: + return MLKEM768; + case X25519MLKEM768: + return x25519; + case SecP384r1MLKEM1024: + return MLKEM1024; + default: + return -1; + } + } + + // TODO Temporary until crypto implementations become more self-documenting around lengths + static int getHybridSplitClientShare(int namedGroup) + { + switch (namedGroup) + { + case secp256r1: + return 65; + case secp384r1: + return 97; + case MLKEM768: + return 1184; + } + return -1; + } + + // TODO Temporary until crypto implementations become more self-documenting around lengths + static int getHybridSplitServerShare(int namedGroup) + { + switch (namedGroup) + { + case secp256r1: + return 65; + case secp384r1: + return 97; + case MLKEM768: + return 1088; + } + return -1; + } + public static String getKemName(int namedGroup) { switch (namedGroup) { case OQS_mlkem512: + case MLKEM512: return "ML-KEM-512"; case OQS_mlkem768: - case DRAFT_mlkem768: + case MLKEM768: return "ML-KEM-768"; case OQS_mlkem1024: - case DRAFT_mlkem1024: + case MLKEM1024: return "ML-KEM-1024"; default: return null; @@ -376,10 +443,18 @@ public static String getName(int namedGroup) return "OQS_mlkem768"; case OQS_mlkem1024: return "OQS_mlkem1024"; - case DRAFT_mlkem768: - return "DRAFT_mlkem768"; - case DRAFT_mlkem1024: - return "DRAFT_mlkem1024"; + case MLKEM512: + return "MLKEM512"; + case MLKEM768: + return "MLKEM768"; + case MLKEM1024: + return "MLKEM1024"; + case SecP256r1MLKEM768: + return "SecP256r1MLKEM768"; + case X25519MLKEM768: + return "X25519MLKEM768"; + case SecP384r1MLKEM1024: + return "SecP384r1MLKEM1024"; case arbitrary_explicit_prime_curves: return "arbitrary_explicit_prime_curves"; case arbitrary_explicit_char2_curves: @@ -487,9 +562,23 @@ public static boolean refersToASpecificGroup(int namedGroup) { return refersToASpecificCurve(namedGroup) || refersToASpecificFiniteField(namedGroup) + || refersToASpecificHybrid(namedGroup) || refersToASpecificKem(namedGroup); } + public static boolean refersToASpecificHybrid(int namedGroup) + { + switch (namedGroup) + { + case SecP256r1MLKEM768: + case X25519MLKEM768: + case SecP384r1MLKEM1024: + return true; + default: + return false; + } + } + public static boolean refersToASpecificKem(int namedGroup) { switch (namedGroup) @@ -497,8 +586,9 @@ public static boolean refersToASpecificKem(int namedGroup) case OQS_mlkem512: case OQS_mlkem768: case OQS_mlkem1024: - case DRAFT_mlkem768: - case DRAFT_mlkem1024: + case MLKEM512: + case MLKEM768: + case MLKEM1024: return true; default: return false; diff --git a/tls/src/main/java/org/bouncycastle/tls/PRFAlgorithm.java b/tls/src/main/java/org/bouncycastle/tls/PRFAlgorithm.java index 0b7c1cf97c..360ab7a75b 100644 --- a/tls/src/main/java/org/bouncycastle/tls/PRFAlgorithm.java +++ b/tls/src/main/java/org/bouncycastle/tls/PRFAlgorithm.java @@ -16,6 +16,7 @@ public class PRFAlgorithm public static final int tls13_hkdf_sha384 = 5; // public static final int tls13_hkdf_sha512 = 6; public static final int tls13_hkdf_sm3 = 7; + public static final int tls_prf_gostr3411_2012_256 = 8; public static String getName(int prfAlgorithm) { @@ -35,6 +36,8 @@ public static String getName(int prfAlgorithm) return "tls13_hkdf_sha384"; case tls13_hkdf_sm3: return "tls13_hkdf_sm3"; + case tls_prf_gostr3411_2012_256: + return "tls_prf_gostr3411_2012_256"; default: return "UNKNOWN"; } diff --git a/tls/src/main/java/org/bouncycastle/tls/SignatureAlgorithm.java b/tls/src/main/java/org/bouncycastle/tls/SignatureAlgorithm.java index 889b1d9145..4acfab6d38 100644 --- a/tls/src/main/java/org/bouncycastle/tls/SignatureAlgorithm.java +++ b/tls/src/main/java/org/bouncycastle/tls/SignatureAlgorithm.java @@ -35,7 +35,7 @@ public class SignatureAlgorithm public static final short ecdsa_brainpoolP512r1tls13_sha512 = 28; /* - * draft-smyshlyaev-tls12-gost-suites-10 + * RFC 9189 */ public static final short gostr34102012_256 = 64; public static final short gostr34102012_512 = 65; diff --git a/tls/src/main/java/org/bouncycastle/tls/SignatureScheme.java b/tls/src/main/java/org/bouncycastle/tls/SignatureScheme.java index 2a980300fc..4d2479921b 100644 --- a/tls/src/main/java/org/bouncycastle/tls/SignatureScheme.java +++ b/tls/src/main/java/org/bouncycastle/tls/SignatureScheme.java @@ -45,6 +45,13 @@ public class SignatureScheme public static final int sm2sig_sm3 = 0x0708; + /* + * draft-tls-westerbaan-mldsa-00 + */ + public static final int DRAFT_mldsa44 = 0x0904; + public static final int DRAFT_mldsa65 = 0x0905; + public static final int DRAFT_mldsa87 = 0x0906; + /* * RFC 8446 reserved for private use (0xFE00..0xFFFF) */ @@ -70,6 +77,9 @@ public static int getCryptoHashAlgorithm(int signatureScheme) { case ed25519: case ed448: + case DRAFT_mldsa44: + case DRAFT_mldsa65: + case DRAFT_mldsa87: return -1; case ecdsa_brainpoolP256r1tls13_sha256: case rsa_pss_pss_sha256: @@ -146,6 +156,12 @@ public static String getName(int signatureScheme) return "ecdsa_brainpoolP512r1tls13_sha512"; case sm2sig_sm3: return "sm2sig_sm3"; + case DRAFT_mldsa44: + return "DRAFT_mldsa44"; + case DRAFT_mldsa65: + return "DRAFT_mldsa65"; + case DRAFT_mldsa87: + return "DRAFT_mldsa87"; default: return "UNKNOWN"; } @@ -238,6 +254,19 @@ public static boolean isECDSA(int signatureScheme) } } + public static boolean isMLDSA(int signatureScheme) + { + switch (signatureScheme) + { + case DRAFT_mldsa44: + case DRAFT_mldsa65: + case DRAFT_mldsa87: + return true; + default: + return false; + } + } + public static boolean isRSAPSS(int signatureScheme) { switch (signatureScheme) diff --git a/tls/src/main/java/org/bouncycastle/tls/SimulatedTlsSRPIdentityManager.java b/tls/src/main/java/org/bouncycastle/tls/SimulatedTlsSRPIdentityManager.java index e0293b1948..b157a913ec 100644 --- a/tls/src/main/java/org/bouncycastle/tls/SimulatedTlsSRPIdentityManager.java +++ b/tls/src/main/java/org/bouncycastle/tls/SimulatedTlsSRPIdentityManager.java @@ -36,7 +36,7 @@ public static SimulatedTlsSRPIdentityManager getRFC5054Default(TlsCrypto crypto, TlsSRPConfig srpConfig = new TlsSRPConfig(); - srpConfig.setExplicitNG(new BigInteger[] { group.getN(), group.getG() }); + srpConfig.setExplicitNG(new BigInteger[]{ group.getN(), group.getG() }); return new SimulatedTlsSRPIdentityManager(group, crypto.createSRP6VerifierGenerator(srpConfig), mac); } diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsClientProtocol.java b/tls/src/main/java/org/bouncycastle/tls/TlsClientProtocol.java index 2813ebbed6..e01366d485 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsClientProtocol.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsClientProtocol.java @@ -840,7 +840,7 @@ protected void process13HelloRetryRequest(ServerHello helloRetryRequest) final Hashtable extensions = helloRetryRequest.getExtensions(); if (null == extensions) { - throw new TlsFatalAlert(AlertDescription.illegal_parameter); + throw new TlsFatalAlert(AlertDescription.illegal_parameter, "no extensions found"); } TlsUtils.checkExtensionData13(extensions, HandshakeType.hello_retry_request, AlertDescription.illegal_parameter); @@ -855,15 +855,17 @@ protected void process13HelloRetryRequest(ServerHello helloRetryRequest) while (e.hasMoreElements()) { Integer extType = (Integer)e.nextElement(); + int extensionType = extType.intValue(); - if (ExtensionType.cookie == extType.intValue()) + if (ExtensionType.cookie == extensionType) { continue; } if (null == TlsUtils.getExtensionData(clientExtensions, extType)) { - throw new TlsFatalAlert(AlertDescription.unsupported_extension); + throw new TlsFatalAlert(AlertDescription.unsupported_extension, + "received unrequested extension response: " + ExtensionType.getText(extensionType)); } } } @@ -871,14 +873,19 @@ protected void process13HelloRetryRequest(ServerHello helloRetryRequest) final ProtocolVersion server_version = TlsExtensionsUtils.getSupportedVersionsExtensionServer(extensions); if (null == server_version) { - throw new TlsFatalAlert(AlertDescription.missing_extension); + throw new TlsFatalAlert(AlertDescription.missing_extension, + "missing extension response: " + ExtensionType.getText(ExtensionType.supported_versions)); } if (!ProtocolVersion.TLSv13.isEqualOrEarlierVersionOf(server_version) || - !ProtocolVersion.contains(tlsClientContext.getClientSupportedVersions(), server_version) || - !TlsUtils.isValidVersionForCipherSuite(cipherSuite, server_version)) + !ProtocolVersion.contains(tlsClientContext.getClientSupportedVersions(), server_version)) { - throw new TlsFatalAlert(AlertDescription.illegal_parameter); + throw new TlsFatalAlert(AlertDescription.illegal_parameter, "invalid version selected: " + server_version); + } + + if (!TlsUtils.isValidVersionForCipherSuite(cipherSuite, server_version)) + { + throw new TlsFatalAlert(AlertDescription.illegal_parameter, "invalid cipher suite for selected version"); } if (null != clientBinders) @@ -891,6 +898,20 @@ protected void process13HelloRetryRequest(ServerHello helloRetryRequest) } } + final int selected_group = TlsExtensionsUtils.getKeyShareHelloRetryRequest(extensions); + + /* + * TODO[tls:psk_ke] + * + * RFC 8446 4.2.8. Servers [..] MUST NOT send a KeyShareEntry when using the "psk_ke" + * PskKeyExchangeMode. + */ + if (selected_group < 0) + { + throw new TlsFatalAlert(AlertDescription.missing_extension, + "missing extension response: " + ExtensionType.getText(ExtensionType.key_share)); + } + /* * RFC 8446 4.2.8. Upon receipt of this [Key Share] extension in a HelloRetryRequest, the * client MUST verify that (1) the selected_group field corresponds to a group which was @@ -899,12 +920,10 @@ protected void process13HelloRetryRequest(ServerHello helloRetryRequest) * extension in the original ClientHello. If either of these checks fails, then the client * MUST abort the handshake with an "illegal_parameter" alert. */ - final int selected_group = TlsExtensionsUtils.getKeyShareHelloRetryRequest(extensions); - if (!TlsUtils.isValidKeyShareSelection(server_version, securityParameters.getClientSupportedGroups(), clientAgreements, selected_group)) { - throw new TlsFatalAlert(AlertDescription.illegal_parameter); + throw new TlsFatalAlert(AlertDescription.illegal_parameter, "invalid key_share selected"); } final byte[] cookie = TlsExtensionsUtils.getCookieExtension(extensions); @@ -1236,7 +1255,8 @@ protected void processServerHello(ServerHello serverHello) */ if (null == TlsUtils.getExtensionData(this.clientExtensions, extType)) { - throw new TlsFatalAlert(AlertDescription.unsupported_extension); + throw new TlsFatalAlert(AlertDescription.unsupported_extension, + "Unrequested extension in ServerHello: " + ExtensionType.getText(extType.intValue())); } /* @@ -1788,10 +1808,11 @@ protected void sendClientHello() TlsSession sessionToResume = offeringTLSv12Minus ? tlsClient.getSessionToResume() : null; - boolean fallback = tlsClient.isFallback(); - + // NOTE: Client is free to modify the cipher suites up until getSessionToResume int[] offeredCipherSuites = tlsClient.getCipherSuites(); + boolean fallback = tlsClient.isFallback(); + this.clientExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(tlsClient.getClientExtensions()); final boolean shouldUseEMS = tlsClient.shouldUseExtendedMasterSecret(); diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsDHUtils.java b/tls/src/main/java/org/bouncycastle/tls/TlsDHUtils.java index ba7dce9721..eb840ac4de 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsDHUtils.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsDHUtils.java @@ -101,7 +101,7 @@ public static int getNamedGroupForDHParameters(BigInteger p, BigInteger g) public static DHGroup getStandardGroupForDHParameters(BigInteger p, BigInteger g) { - DHGroup[] standardGroups = new DHGroup[] { DHStandardGroups.rfc7919_ffdhe2048, + DHGroup[] standardGroups = new DHGroup[]{ DHStandardGroups.rfc7919_ffdhe2048, DHStandardGroups.rfc7919_ffdhe3072, DHStandardGroups.rfc7919_ffdhe4096, DHStandardGroups.rfc7919_ffdhe6144, DHStandardGroups.rfc7919_ffdhe8192, DHStandardGroups.rfc3526_1536, DHStandardGroups.rfc3526_2048, DHStandardGroups.rfc3526_3072, DHStandardGroups.rfc3526_4096, DHStandardGroups.rfc3526_6144, diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsECCUtils.java b/tls/src/main/java/org/bouncycastle/tls/TlsECCUtils.java index 0a03ed9dba..95ed67a83c 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsECCUtils.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsECCUtils.java @@ -40,6 +40,7 @@ public static boolean isECCCipherSuite(int cipherSuite) case KeyExchangeAlgorithm.ECDHE_ECDSA: case KeyExchangeAlgorithm.ECDHE_PSK: case KeyExchangeAlgorithm.ECDHE_RSA: + case KeyExchangeAlgorithm.GOSTR341112_256: return true; default: diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsExtensionsUtils.java b/tls/src/main/java/org/bouncycastle/tls/TlsExtensionsUtils.java index a44904459e..072f721ca7 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsExtensionsUtils.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsExtensionsUtils.java @@ -250,6 +250,11 @@ public static void addSupportedGroupsExtension(Hashtable extensions, Vector name extensions.put(EXT_supported_groups, createSupportedGroupsExtension(namedGroups)); } + public static void addSupportedGroupsExtension(Hashtable extensions, int[] namedGroups) throws IOException + { + extensions.put(EXT_supported_groups, createSupportedGroupsExtension(namedGroups)); + } + public static void addSupportedPointFormatsExtension(Hashtable extensions, short[] ecPointFormats) throws IOException { @@ -934,6 +939,16 @@ public static byte[] createSupportedGroupsExtension(Vector namedGroups) throws I return TlsUtils.encodeUint16ArrayWithUint16Length(values); } + public static byte[] createSupportedGroupsExtension(int[] namedGroups) throws IOException + { + if (TlsUtils.isNullOrEmpty(namedGroups)) + { + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + return TlsUtils.encodeUint16ArrayWithUint16Length(namedGroups); + } + public static byte[] createSupportedPointFormatsExtension(short[] ecPointFormats) throws IOException { if (ecPointFormats == null || !Arrays.contains(ecPointFormats, ECPointFormat.uncompressed)) diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsProtocol.java b/tls/src/main/java/org/bouncycastle/tls/TlsProtocol.java index 7e3aa41183..ce2630bb8c 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsProtocol.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsProtocol.java @@ -1582,17 +1582,9 @@ protected boolean establishSession(TlsSession sessionToResume) return false; } - boolean isEMS = sessionParameters.isExtendedMasterSecret(); - if (sessionVersion.isSSL()) + if (!TlsUtils.isExtendedMasterSecretOptional(sessionVersion)) { - if (isEMS) - { - return false; - } - } - else if (!TlsUtils.isExtendedMasterSecretOptional(sessionVersion)) - { - if (!isEMS) + if (sessionParameters.isExtendedMasterSecret() == sessionVersion.isSSL()) { return false; } diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsServer.java b/tls/src/main/java/org/bouncycastle/tls/TlsServer.java index ee78dfbde5..8f092eeaf2 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsServer.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsServer.java @@ -13,6 +13,8 @@ public interface TlsServer extends TlsPeer { + boolean preferLocalSupportedGroups(); + void init(TlsServerContext context); /** diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsServerProtocol.java b/tls/src/main/java/org/bouncycastle/tls/TlsServerProtocol.java index 3ace602565..3c94732a8c 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsServerProtocol.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsServerProtocol.java @@ -10,9 +10,6 @@ import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsCrypto; -import org.bouncycastle.tls.crypto.TlsDHConfig; -import org.bouncycastle.tls.crypto.TlsECConfig; -import org.bouncycastle.tls.crypto.TlsKemConfig; import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.util.Arrays; @@ -219,7 +216,7 @@ protected ServerHello generate13ServerHello(ClientHello clientHello, HandshakeMe } this.retryCookie = null; - clientShare = TlsUtils.selectKeyShare(clientShares, retryGroup); + clientShare = TlsUtils.getRetryKeyShare(clientShares, retryGroup); if (null == clientShare) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); @@ -296,39 +293,25 @@ protected ServerHello generate13ServerHello(ClientHello clientHello, HandshakeMe int[] clientSupportedGroups = securityParameters.getClientSupportedGroups(); int[] serverSupportedGroups = securityParameters.getServerSupportedGroups(); + boolean useServerOrder = tlsServer.preferLocalSupportedGroups(); - clientShare = TlsUtils.selectKeyShare(crypto, serverVersion, clientShares, clientSupportedGroups, - serverSupportedGroups); + int selectedGroup = TlsUtils.selectKeyShareGroup(crypto, serverVersion, clientSupportedGroups, + serverSupportedGroups, useServerOrder); + if (selectedGroup < 0) + { + throw new TlsFatalAlert(AlertDescription.handshake_failure); + } + + clientShare = TlsUtils.findEarlyKeyShare(clientShares, selectedGroup); if (null == clientShare) { - this.retryGroup = TlsUtils.selectKeyShareGroup(crypto, serverVersion, clientSupportedGroups, - serverSupportedGroups); - if (retryGroup < 0) - { - throw new TlsFatalAlert(AlertDescription.handshake_failure); - } + this.retryGroup = selectedGroup; this.retryCookie = tlsServerContext.getNonceGenerator().generateNonce(16); return generate13HelloRetryRequest(clientHello); } - - if (clientShare.getNamedGroup() != serverSupportedGroups[0]) - { - /* - * TODO[tls13] RFC 8446 4.2.7. As of TLS 1.3, servers are permitted to send the - * "supported_groups" extension to the client. Clients MUST NOT act upon any - * information found in "supported_groups" prior to successful completion of the - * handshake but MAY use the information learned from a successfully completed - * handshake to change what groups they use in their "key_share" extension in - * subsequent connections. If the server has a group it prefers to the ones in the - * "key_share" extension but is still willing to accept the ClientHello, it SHOULD - * send "supported_groups" to update the client's view of its preferences; this - * extension SHOULD contain all groups the server supports, regardless of whether - * they are currently supported by the client. - */ - } } @@ -337,6 +320,25 @@ protected ServerHello generate13ServerHello(ClientHello clientHello, HandshakeMe tlsServer.getServerExtensionsForConnection(serverEncryptedExtensions); + /* + * RFC 8446 4.2.7. As of TLS 1.3, servers are permitted to send the "supported_groups" extension to + * the client. [..] If the server has a group it prefers to the ones in the "key_share" extension + * but is still willing to accept the ClientHello, it SHOULD send "supported_groups" to update the + * client's view of its preferences; this extension SHOULD contain all groups the server supports, + * regardless of whether they are currently supported by the client. + */ + if (!afterHelloRetryRequest) + { + int[] serverSupportedGroups = securityParameters.getServerSupportedGroups(); + + if (!TlsUtils.isNullOrEmpty(serverSupportedGroups) && + clientShare.getNamedGroup() != serverSupportedGroups[0] && + !serverEncryptedExtensions.containsKey(TlsExtensionsUtils.EXT_supported_groups)) + { + TlsExtensionsUtils.addSupportedGroupsExtension(serverEncryptedExtensions, serverSupportedGroups); + } + } + ProtocolVersion serverLegacyVersion = ProtocolVersion.TLSv12; TlsExtensionsUtils.addSupportedVersionsExtensionServer(serverHelloExtensions, serverVersion); @@ -396,21 +398,9 @@ protected ServerHello generate13ServerHello(ClientHello clientHello, HandshakeMe TlsSecret sharedSecret; { int namedGroup = clientShare.getNamedGroup(); - - TlsAgreement agreement; - if (NamedGroup.refersToAnECDHCurve(namedGroup)) - { - agreement = crypto.createECDomain(new TlsECConfig(namedGroup)).createECDH(); - } - else if (NamedGroup.refersToASpecificFiniteField(namedGroup)) - { - agreement = crypto.createDHDomain(new TlsDHConfig(namedGroup, true)).createDH(); - } - else if (NamedGroup.refersToASpecificKem(namedGroup)) - { - agreement = crypto.createKemDomain(new TlsKemConfig(namedGroup, true)).createKem(); - } - else + + TlsAgreement agreement = TlsUtils.createKeyShare(crypto, namedGroup, true); + if (agreement == null) { throw new TlsFatalAlert(AlertDescription.internal_error); } diff --git a/tls/src/main/java/org/bouncycastle/tls/TlsUtils.java b/tls/src/main/java/org/bouncycastle/tls/TlsUtils.java index 80a33fd617..18567b730e 100644 --- a/tls/src/main/java/org/bouncycastle/tls/TlsUtils.java +++ b/tls/src/main/java/org/bouncycastle/tls/TlsUtils.java @@ -40,6 +40,7 @@ import org.bouncycastle.tls.crypto.TlsEncryptor; import org.bouncycastle.tls.crypto.TlsHash; import org.bouncycastle.tls.crypto.TlsHashOutputStream; +import org.bouncycastle.tls.crypto.TlsHybridAgreement; import org.bouncycastle.tls.crypto.TlsKemConfig; import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.tls.crypto.TlsStreamSigner; @@ -1149,7 +1150,7 @@ public static void addIfSupported(Vector supportedAlgs, TlsCrypto crypto, Signat public static void addIfSupported(Vector supportedGroups, TlsCrypto crypto, int namedGroup) { - if (crypto.hasNamedGroup(namedGroup)) + if (isSupportedNamedGroup(crypto, namedGroup)) { supportedGroups.addElement(Integers.valueOf(namedGroup)); } @@ -2219,6 +2220,17 @@ static int getPRFAlgorithm(SecurityParameters securityParameters, int cipherSuit throw new TlsFatalAlert(AlertDescription.illegal_parameter); } + case CipherSuite.TLS_GOSTR341112_256_WITH_28147_CNT_IMIT: + case CipherSuite.TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC: + case CipherSuite.TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC: + { + if (isTLSv12Exactly) + { + return PRFAlgorithm.tls_prf_gostr3411_2012_256; + } + throw new TlsFatalAlert(AlertDescription.illegal_parameter); + } + case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: @@ -2707,6 +2719,9 @@ public static int getEncryptionAlgorithm(int cipherSuite) { switch (cipherSuite) { + case CipherSuite.TLS_GOSTR341112_256_WITH_28147_CNT_IMIT: + return EncryptionAlgorithm._28147_CNT_IMIT; + case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: @@ -3007,6 +3022,12 @@ public static int getEncryptionAlgorithm(int cipherSuite) case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256: return EncryptionAlgorithm.CHACHA20_POLY1305; + case CipherSuite.TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC: + return EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC; + + case CipherSuite.TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC: + return EncryptionAlgorithm.MAGMA_CTR_OMAC; + case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA: @@ -3085,6 +3106,9 @@ public static int getEncryptionAlgorithmType(int encryptionAlgorithm) case EncryptionAlgorithm.SM4_CBC: return CipherType.block; + case EncryptionAlgorithm._28147_CNT_IMIT: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.NULL: case EncryptionAlgorithm.RC4_40: case EncryptionAlgorithm.RC4_128: @@ -3332,6 +3356,11 @@ public static int getKeyExchangeAlgorithm(int cipherSuite) case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA: return KeyExchangeAlgorithm.ECDHE_RSA; + case CipherSuite.TLS_GOSTR341112_256_WITH_28147_CNT_IMIT: + case CipherSuite.TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC: + case CipherSuite.TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC: + return KeyExchangeAlgorithm.GOSTR341112_256; + case CipherSuite.TLS_AES_128_CCM_8_SHA256: case CipherSuite.TLS_AES_128_CCM_SHA256: case CipherSuite.TLS_AES_128_GCM_SHA256: @@ -3905,6 +3934,9 @@ public static ProtocolVersion getMinimumVersion(int cipherSuite) case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: + case CipherSuite.TLS_GOSTR341112_256_WITH_28147_CNT_IMIT: + case CipherSuite.TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC: + case CipherSuite.TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: @@ -4090,8 +4122,6 @@ static boolean isValidKeyShareSelection(ProtocolVersion negotiatedVersion, int[] static boolean isValidSignatureAlgorithmForServerKeyExchange(short signatureAlgorithm, int keyExchangeAlgorithm) { - // TODO[tls13] - switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DHE_RSA: @@ -4129,6 +4159,7 @@ static boolean isValidSignatureAlgorithmForServerKeyExchange(short signatureAlgo case KeyExchangeAlgorithm.NULL: return SignatureAlgorithm.anonymous != signatureAlgorithm; + case KeyExchangeAlgorithm.GOSTR341112_256: default: return false; } @@ -4411,11 +4442,25 @@ public static boolean isSupportedKeyExchange(TlsCrypto crypto, int keyExchangeAl return crypto.hasSRPAuthentication() && hasAnyRSASigAlgs(crypto); + // TODO[RFC 9189] + case KeyExchangeAlgorithm.GOSTR341112_256: + default: return false; } } + public static boolean isSupportedNamedGroup(TlsCrypto crypto, int namedGroup) + { + if (!NamedGroup.refersToASpecificHybrid(namedGroup)) + { + return crypto.hasNamedGroup(namedGroup); + } + + return crypto.hasNamedGroup(NamedGroup.getHybridFirst(namedGroup)) + && crypto.hasNamedGroup(NamedGroup.getHybridSecond(namedGroup)); + } + static boolean hasAnyRSASigAlgs(TlsCrypto crypto) { return crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa) @@ -4732,7 +4777,8 @@ static void checkTlsFeatures(Certificate serverCertificate, Hashtable clientExte { if (!(tlsFeaturesSeq.getObjectAt(i) instanceof ASN1Integer)) { - throw new TlsFatalAlert(AlertDescription.bad_certificate); + throw new TlsFatalAlert(AlertDescription.bad_certificate, + "Server certificate has invalid TLS Features extension"); } } @@ -4746,7 +4792,8 @@ static void checkTlsFeatures(Certificate serverCertificate, Hashtable clientExte Integer extensionType = Integers.valueOf(tlsExtension.intValue()); if (clientExtensions.containsKey(extensionType) && !serverExtensions.containsKey(extensionType)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "Server extensions missing TLS Feature " + extensionType); } } } @@ -5281,7 +5328,7 @@ static Hashtable addKeyShareToClientHello(TlsClientContext clientContext, TlsCli Hashtable clientAgreements = new Hashtable(3); Vector clientShares = new Vector(2); - collectKeyShares(clientContext, supportedGroups, keyShareGroups, clientAgreements, clientShares); + collectKeyShares(clientContext.getCrypto(), supportedGroups, keyShareGroups, clientAgreements, clientShares); // TODO[tls13-psk] When clientShares empty, consider not adding extension if pre_shared_key in use TlsExtensionsUtils.addKeyShareClientHello(clientExtensions, clientShares); @@ -5297,7 +5344,7 @@ static Hashtable addKeyShareToClientHelloRetry(TlsClientContext clientContext, H Hashtable clientAgreements = new Hashtable(1, 1.0f); Vector clientShares = new Vector(1); - collectKeyShares(clientContext, supportedGroups, keyShareGroups, clientAgreements, clientShares); + collectKeyShares(clientContext.getCrypto(), supportedGroups, keyShareGroups, clientAgreements, clientShares); TlsExtensionsUtils.addKeyShareClientHello(clientExtensions, clientShares); @@ -5310,10 +5357,9 @@ static Hashtable addKeyShareToClientHelloRetry(TlsClientContext clientContext, H return clientAgreements; } - private static void collectKeyShares(TlsClientContext clientContext, int[] supportedGroups, Vector keyShareGroups, + private static void collectKeyShares(TlsCrypto crypto, int[] supportedGroups, Vector keyShareGroups, Hashtable clientAgreements, Vector clientShares) throws IOException { - TlsCrypto crypto = clientContext.getCrypto(); if (isNullOrEmpty(supportedGroups)) { return; @@ -5328,48 +5374,98 @@ private static void collectKeyShares(TlsClientContext clientContext, int[] suppo int supportedGroup = supportedGroups[i]; Integer supportedGroupElement = Integers.valueOf(supportedGroup); - if (!keyShareGroups.contains(supportedGroupElement) - || clientAgreements.containsKey(supportedGroupElement) - || !crypto.hasNamedGroup(supportedGroup)) + if (!keyShareGroups.contains(supportedGroupElement) || + clientAgreements.containsKey(supportedGroupElement)) { continue; } - TlsAgreement agreement = null; - if (NamedGroup.refersToAnECDHCurve(supportedGroup)) + TlsAgreement agreement = createKeyShare(crypto, supportedGroup, false); + if (agreement != null) + { + byte[] key_exchange = agreement.generateEphemeral(); + KeyShareEntry clientShare = new KeyShareEntry(supportedGroup, key_exchange); + + clientShares.addElement(clientShare); + clientAgreements.put(supportedGroupElement, agreement); + } + } + } + + static TlsAgreement createKeyShare(TlsCrypto crypto, int keyShareGroup, boolean isServer) + { + if (!NamedGroup.refersToASpecificHybrid(keyShareGroup)) + { + return createKeyShareSimple(crypto, keyShareGroup, isServer); + } + + int hybridFirst = NamedGroup.getHybridFirst(keyShareGroup); + TlsAgreement firstAgreement = createKeyShareSimple(crypto, hybridFirst, isServer); + if (firstAgreement == null) + { + return null; + } + + int hybridSecond = NamedGroup.getHybridSecond(keyShareGroup); + TlsAgreement secondAgreement = createKeyShareSimple(crypto, hybridSecond, isServer); + if (secondAgreement == null) + { + return null; + } + + int peerValueSplit = isServer + ? NamedGroup.getHybridSplitClientShare(hybridFirst) + : NamedGroup.getHybridSplitServerShare(hybridFirst); + + return new TlsHybridAgreement(crypto, firstAgreement, secondAgreement, peerValueSplit); + } + + private static TlsAgreement createKeyShareSimple(TlsCrypto crypto, int keyShareGroup, boolean isServer) + { + if (crypto.hasNamedGroup(keyShareGroup)) + { + if (NamedGroup.refersToAnECDHCurve(keyShareGroup)) { if (crypto.hasECDHAgreement()) { - agreement = crypto.createECDomain(new TlsECConfig(supportedGroup)).createECDH(); + return crypto.createECDomain(new TlsECConfig(keyShareGroup)).createECDH(); } } - else if (NamedGroup.refersToASpecificFiniteField(supportedGroup)) + else if (NamedGroup.refersToASpecificFiniteField(keyShareGroup)) { if (crypto.hasDHAgreement()) { - agreement = crypto.createDHDomain(new TlsDHConfig(supportedGroup, true)).createDH(); + return crypto.createDHDomain(new TlsDHConfig(keyShareGroup, true)).createDH(); } } - else if (NamedGroup.refersToASpecificKem(supportedGroup)) + else if (NamedGroup.refersToASpecificKem(keyShareGroup)) { if (crypto.hasKemAgreement()) { - agreement = crypto.createKemDomain(new TlsKemConfig(supportedGroup, false)).createKem(); + return crypto.createKemDomain(new TlsKemConfig(keyShareGroup, isServer)).createKem(); } } + } + return null; + } - if (null != agreement) + static KeyShareEntry findEarlyKeyShare(Vector clientShares, int keyShareGroup) + { + if (null != clientShares) + { + for (int i = 0; i < clientShares.size(); ++i) { - byte[] key_exchange = agreement.generateEphemeral(); - KeyShareEntry clientShare = new KeyShareEntry(supportedGroup, key_exchange); - - clientShares.addElement(clientShare); - clientAgreements.put(supportedGroupElement, agreement); + KeyShareEntry clientShare = (KeyShareEntry)clientShares.elementAt(i); + if (null != clientShare && clientShare.getNamedGroup() == keyShareGroup) + { + return clientShare; + } } } + return null; } - static KeyShareEntry selectKeyShare(Vector clientShares, int keyShareGroup) + static KeyShareEntry getRetryKeyShare(Vector clientShares, int keyShareGroup) { if (null != clientShares && 1 == clientShares.size()) { @@ -5382,81 +5478,58 @@ static KeyShareEntry selectKeyShare(Vector clientShares, int keyShareGroup) return null; } - static KeyShareEntry selectKeyShare(TlsCrypto crypto, ProtocolVersion negotiatedVersion, Vector clientShares, - int[] clientSupportedGroups, int[] serverSupportedGroups) + static int selectKeyShareGroup(TlsCrypto crypto, ProtocolVersion negotiatedVersion, + int[] clientSupportedGroups, int[] serverSupportedGroups, boolean useServerOrder) { - if (null != clientShares && !isNullOrEmpty(clientSupportedGroups) && !isNullOrEmpty(serverSupportedGroups)) + if (!isNullOrEmpty(clientSupportedGroups) && !isNullOrEmpty(serverSupportedGroups)) { - for (int i = 0; i < clientShares.size(); ++i) - { - KeyShareEntry clientShare = (KeyShareEntry)clientShares.elementAt(i); - - int group = clientShare.getNamedGroup(); - - if (!NamedGroup.canBeNegotiated(group, negotiatedVersion)) - { - continue; - } - - if (!Arrays.contains(serverSupportedGroups, group) || - !Arrays.contains(clientSupportedGroups, group)) - { - continue; - } + int[] ordered = useServerOrder ? serverSupportedGroups : clientSupportedGroups; + int[] unordered = useServerOrder ? clientSupportedGroups : serverSupportedGroups; - if (!crypto.hasNamedGroup(group)) - { - continue; - } + for (int i = 0; i < ordered.length; ++i) + { + int candidate = ordered[i]; - if ((NamedGroup.refersToAnECDHCurve(group) && !crypto.hasECDHAgreement()) || - (NamedGroup.refersToASpecificFiniteField(group) && !crypto.hasDHAgreement()) || - (NamedGroup.refersToASpecificKem(group) && !crypto.hasKemAgreement())) + if (Arrays.contains(unordered, candidate) && + NamedGroup.canBeNegotiated(candidate, negotiatedVersion) && + supportsKeyShareGroup(crypto, candidate)) { - continue; + return candidate; } - - return clientShare; } } - return null; + return -1; } - static int selectKeyShareGroup(TlsCrypto crypto, ProtocolVersion negotiatedVersion, - int[] clientSupportedGroups, int[] serverSupportedGroups) + private static boolean supportsKeyShareGroup(TlsCrypto crypto, int keyShareGroup) { - if (!isNullOrEmpty(clientSupportedGroups) && !isNullOrEmpty(serverSupportedGroups)) + if (!NamedGroup.refersToASpecificHybrid(keyShareGroup)) { - for (int i = 0; i < clientSupportedGroups.length; ++i) - { - int group = clientSupportedGroups[i]; - - if (!NamedGroup.canBeNegotiated(group, negotiatedVersion)) - { - continue; - } - - if (!Arrays.contains(serverSupportedGroups, group)) - { - continue; - } - - if (!crypto.hasNamedGroup(group)) - { - continue; - } + return supportsKeyShareGroupSimple(crypto, keyShareGroup); + } - if ((NamedGroup.refersToAnECDHCurve(group) && !crypto.hasECDHAgreement()) || - (NamedGroup.refersToASpecificFiniteField(group) && !crypto.hasDHAgreement()) || - (NamedGroup.refersToASpecificKem(group) && !crypto.hasKemAgreement())) - { - continue; - } + return supportsKeyShareGroupSimple(crypto, NamedGroup.getHybridFirst(keyShareGroup)) + && supportsKeyShareGroupSimple(crypto, NamedGroup.getHybridSecond(keyShareGroup)); + } - return group; + private static boolean supportsKeyShareGroupSimple(TlsCrypto crypto, int keyShareGroup) + { + if (crypto.hasNamedGroup(keyShareGroup)) + { + if (NamedGroup.refersToAnECDHCurve(keyShareGroup)) + { + return crypto.hasECDHAgreement(); + } + else if (NamedGroup.refersToASpecificFiniteField(keyShareGroup)) + { + return crypto.hasDHAgreement(); + } + else if (NamedGroup.refersToASpecificKem(keyShareGroup)) + { + return crypto.hasKemAgreement(); } } - return -1; + return false; } static byte[] readEncryptedPMS(TlsContext context, InputStream input) throws IOException @@ -5620,9 +5693,32 @@ static void negotiatedCipherSuite(SecurityParameters securityParameters, int cip { securityParameters.verifyDataLength = securityParameters.getPRFHashLength(); } + else if (negotiatedVersion.isSSL()) + { + securityParameters.verifyDataLength = 36; + } else { - securityParameters.verifyDataLength = negotiatedVersion.isSSL() ? 36 : 12; + /* + * RFC 9189 4.2.6. The verify_data_length value is equal to 32 for the CTR_OMAC cipher + * suites and is equal to 12 for the CNT_IMIT cipher suite. + */ + switch (cipherSuite) + { + case CipherSuite.TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC: + case CipherSuite.TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC: + { + securityParameters.verifyDataLength = 32; + break; + } + + case CipherSuite.TLS_GOSTR341112_256_WITH_28147_CNT_IMIT: + default: + { + securityParameters.verifyDataLength = 12; + break; + } + } } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/CryptoHashAlgorithm.java b/tls/src/main/java/org/bouncycastle/tls/crypto/CryptoHashAlgorithm.java index b0ce733b4a..1beb7e1de8 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/CryptoHashAlgorithm.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/CryptoHashAlgorithm.java @@ -9,4 +9,5 @@ public abstract class CryptoHashAlgorithm public static final int sha384 = 5; public static final int sha512 = 6; public static final int sm3 = 7; + public static final int gostr3411_2012_256 = 8; } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCrypto.java b/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCrypto.java index a154e64238..46b41a1d23 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCrypto.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCrypto.java @@ -69,13 +69,6 @@ public interface TlsCrypto */ boolean hasECDHAgreement(); - /** - * Return true if this TlsCrypto can support KEM key agreement. - * - * @return true if this instance can support KEM key agreement, false otherwise. - */ - boolean hasKemAgreement(); - /** * Return true if this TlsCrypto can support the passed in block/stream encryption algorithm. * @@ -92,6 +85,13 @@ public interface TlsCrypto */ boolean hasHKDFAlgorithm(int cryptoHashAlgorithm); + /** + * Return true if this TlsCrypto can support KEM key agreement. + * + * @return true if this instance can support KEM key agreement, false otherwise. + */ + boolean hasKemAgreement(); + /** * Return true if this TlsCrypto can support the passed in MAC algorithm. * @@ -146,6 +146,8 @@ public interface TlsCrypto */ boolean hasSRPAuthentication(); + TlsSecret createHybridSecret(TlsSecret s1, TlsSecret s2); + /** * Create a TlsSecret object based on provided data. * diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCryptoUtils.java b/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCryptoUtils.java index 3b716fdcec..8b51aa6910 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCryptoUtils.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/TlsCryptoUtils.java @@ -5,6 +5,7 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.HashAlgorithm; @@ -74,6 +75,8 @@ public static int getHashForPRF(int prfAlgorithm) return CryptoHashAlgorithm.sha384; case PRFAlgorithm.tls13_hkdf_sm3: return CryptoHashAlgorithm.sm3; + case PRFAlgorithm.tls_prf_gostr3411_2012_256: + return CryptoHashAlgorithm.gostr3411_2012_256; default: throw new IllegalArgumentException("unknown PRFAlgorithm: " + PRFAlgorithm.getText(prfAlgorithm)); } @@ -88,6 +91,7 @@ public static int getHashInternalSize(int cryptoHashAlgorithm) case CryptoHashAlgorithm.sha224: case CryptoHashAlgorithm.sha256: case CryptoHashAlgorithm.sm3: + case CryptoHashAlgorithm.gostr3411_2012_256: return 64; case CryptoHashAlgorithm.sha384: case CryptoHashAlgorithm.sha512: @@ -109,6 +113,7 @@ public static int getHashOutputSize(int cryptoHashAlgorithm) return 28; case CryptoHashAlgorithm.sha256: case CryptoHashAlgorithm.sm3: + case CryptoHashAlgorithm.gostr3411_2012_256: return 32; case CryptoHashAlgorithm.sha384: return 48; @@ -138,6 +143,8 @@ public static ASN1ObjectIdentifier getOIDForHash(int cryptoHashAlgorithm) // TODO[RFC 8998] // case CryptoHashAlgorithm.sm3: // return GMObjectIdentifiers.sm3; + case CryptoHashAlgorithm.gostr3411_2012_256: + return RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256; default: throw new IllegalArgumentException(); } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/TlsHybridAgreement.java b/tls/src/main/java/org/bouncycastle/tls/crypto/TlsHybridAgreement.java new file mode 100644 index 0000000000..88d06b0395 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/TlsHybridAgreement.java @@ -0,0 +1,48 @@ +package org.bouncycastle.tls.crypto; + +import java.io.IOException; + +import org.bouncycastle.util.Arrays; + +public class TlsHybridAgreement + implements TlsAgreement +{ + private final TlsCrypto crypto; + private final TlsAgreement firstAgreement; + private final TlsAgreement secondAgreement; + private final int peerValueSplit; + + public TlsHybridAgreement(TlsCrypto crypto, TlsAgreement firstAgreement, TlsAgreement secondAgreement, + int peerValueSplit) + { + this.crypto = crypto; + this.firstAgreement = firstAgreement; + this.secondAgreement = secondAgreement; + this.peerValueSplit = peerValueSplit; + } + + public byte[] generateEphemeral() throws IOException + { + byte[] firstEphemeral = firstAgreement.generateEphemeral(); + byte[] secondEphemeral = secondAgreement.generateEphemeral(); + return Arrays.concatenate(firstEphemeral, secondEphemeral); + } + + public void receivePeerValue(byte[] peerValue) throws IOException + { + if (peerValue.length < peerValueSplit) + { + throw new IllegalArgumentException("'peerValue' is too short"); + } + + this.firstAgreement.receivePeerValue(Arrays.copyOfRange(peerValue, 0, peerValueSplit)); + this.secondAgreement.receivePeerValue(Arrays.copyOfRange(peerValue, peerValueSplit, peerValue.length)); + } + + public TlsSecret calculateSecret() throws IOException + { + TlsSecret firstSecret = firstAgreement.calculateSecret(); + TlsSecret secondSecret = secondAgreement.calculateSecret(); + return crypto.createHybridSecret(firstSecret, secondSecret); + } +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/AEADNonceGenerator.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/AEADNonceGenerator.java new file mode 100644 index 0000000000..3da87c5132 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/AEADNonceGenerator.java @@ -0,0 +1,8 @@ +package org.bouncycastle.tls.crypto.impl; + +import java.io.IOException; + +public interface AEADNonceGenerator +{ + public void generateNonce(byte[] nonce) throws IOException; +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/AEADNonceGeneratorFactory.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/AEADNonceGeneratorFactory.java new file mode 100644 index 0000000000..130c3d39a6 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/AEADNonceGeneratorFactory.java @@ -0,0 +1,6 @@ +package org.bouncycastle.tls.crypto.impl; + +public interface AEADNonceGeneratorFactory +{ + AEADNonceGenerator create(byte[] baseNonce, int counterSizeInBits); +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/PQCUtil.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/PQCUtil.java new file mode 100644 index 0000000000..0f8d51bd4a --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/PQCUtil.java @@ -0,0 +1,48 @@ +package org.bouncycastle.tls.crypto.impl; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAParameters; +import org.bouncycastle.tls.SignatureScheme; + +public class PQCUtil +{ + public static ASN1ObjectIdentifier getMLDSAObjectidentifier(int signatureScheme) + { + switch (signatureScheme) + { + case SignatureScheme.DRAFT_mldsa44: + return NISTObjectIdentifiers.id_ml_dsa_44; + case SignatureScheme.DRAFT_mldsa65: + return NISTObjectIdentifiers.id_ml_dsa_65; + case SignatureScheme.DRAFT_mldsa87: + return NISTObjectIdentifiers.id_ml_dsa_87; + default: + throw new IllegalArgumentException(); + } + } + + public static int getMLDSASignatureScheme(MLDSAParameters parameters) + { + if (MLDSAParameters.ml_dsa_44 == parameters) + { + return SignatureScheme.DRAFT_mldsa44; + } + if (MLDSAParameters.ml_dsa_65 == parameters) + { + return SignatureScheme.DRAFT_mldsa65; + } + if (MLDSAParameters.ml_dsa_87 == parameters) + { + return SignatureScheme.DRAFT_mldsa87; + } + throw new IllegalArgumentException(); + } + + public static boolean supportsMLDSA(AlgorithmIdentifier pubKeyAlgID, ASN1ObjectIdentifier mlDsaAlgOid) + { + return pubKeyAlgID.getAlgorithm().equals(mlDsaAlgOid) + && pubKeyAlgID.getParameters() == null; + } +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/TlsAEADCipher.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/TlsAEADCipher.java index d7910ccd5c..8ac3ccec6b 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/TlsAEADCipher.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/TlsAEADCipher.java @@ -30,6 +30,8 @@ public final class TlsAEADCipher private static final int NONCE_RFC7905 = 2; private static final long SEQUENCE_NUMBER_PLACEHOLDER = -1L; + private static final byte[] EPOCH_1 = { 0x00, 0x01 }; + private final TlsCryptoParameters cryptoParams; private final int keySize; private final int macSize; @@ -43,9 +45,18 @@ public final class TlsAEADCipher private final boolean isTLSv13; private final int nonceMode; + private final AEADNonceGenerator nonceGenerator; + + /** @deprecated Use version with extra 'nonceGeneratorFactory' parameter */ + public TlsAEADCipher(TlsCryptoParameters cryptoParams, TlsAEADCipherImpl encryptCipher, + TlsAEADCipherImpl decryptCipher, int keySize, int macSize, int aeadType) throws IOException + { + this(cryptoParams, encryptCipher, decryptCipher, keySize, macSize, aeadType, null); + } - public TlsAEADCipher(TlsCryptoParameters cryptoParams, TlsAEADCipherImpl encryptCipher, TlsAEADCipherImpl decryptCipher, - int keySize, int macSize, int aeadType) throws IOException + public TlsAEADCipher(TlsCryptoParameters cryptoParams, TlsAEADCipherImpl encryptCipher, + TlsAEADCipherImpl decryptCipher, int keySize, int macSize, int aeadType, + AEADNonceGeneratorFactory nonceGeneratorFactory) throws IOException { final SecurityParameters securityParameters = cryptoParams.getSecurityParametersHandshake(); final ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion(); @@ -91,6 +102,7 @@ public TlsAEADCipher(TlsCryptoParameters cryptoParams, TlsAEADCipherImpl encrypt final boolean isServer = cryptoParams.isServer(); if (isTLSv13) { + nonceGenerator = null; rekeyCipher(securityParameters, decryptCipher, decryptNonce, !isServer); rekeyCipher(securityParameters, encryptCipher, encryptNonce, isServer); return; @@ -121,6 +133,28 @@ public TlsAEADCipher(TlsCryptoParameters cryptoParams, TlsAEADCipherImpl encrypt { throw new TlsFatalAlert(AlertDescription.internal_error); } + + if (AEAD_GCM == aeadType && nonceGeneratorFactory != null) + { + int nonceLength = fixed_iv_length + record_iv_length; + byte[] baseNonce = Arrays.copyOf(encryptNonce, nonceLength); + int counterSizeInBits; + if (negotiatedVersion.isDTLS()) + { + counterSizeInBits = (record_iv_length - 2) * 8; // 48 + baseNonce[baseNonce.length - 8] ^= EPOCH_1[0]; + baseNonce[baseNonce.length - 7] ^= EPOCH_1[1]; + } + else + { + counterSizeInBits = record_iv_length * 8; // 64 + } + nonceGenerator = nonceGeneratorFactory.create(baseNonce, counterSizeInBits); + } + else + { + nonceGenerator = null; + } } public int getCiphertextDecodeLimit(int plaintextLimit) @@ -156,22 +190,29 @@ public TlsEncodeResult encodePlaintext(long seqNo, short contentType, ProtocolVe { byte[] nonce = new byte[encryptNonce.length + record_iv_length]; - switch (nonceMode) + if (null != nonceGenerator) { - case NONCE_RFC5288: - System.arraycopy(encryptNonce, 0, nonce, 0, encryptNonce.length); - // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number. - TlsUtils.writeUint64(seqNo, nonce, encryptNonce.length); - break; - case NONCE_RFC7905: - TlsUtils.writeUint64(seqNo, nonce, nonce.length - 8); - for (int i = 0; i < encryptNonce.length; ++i) + nonceGenerator.generateNonce(nonce); + } + else + { + switch (nonceMode) { - nonce[i] ^= encryptNonce[i]; + case NONCE_RFC5288: + System.arraycopy(encryptNonce, 0, nonce, 0, encryptNonce.length); + // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number. + TlsUtils.writeUint64(seqNo, nonce, encryptNonce.length); + break; + case NONCE_RFC7905: + TlsUtils.writeUint64(seqNo, nonce, nonce.length - 8); + for (int i = 0; i < encryptNonce.length; ++i) + { + nonce[i] ^= encryptNonce[i]; + } + break; + default: + throw new TlsFatalAlert(AlertDescription.internal_error); } - break; - default: - throw new TlsFatalAlert(AlertDescription.internal_error); } // TODO[tls13, cid] If we support adding padding to (D)TLSInnerPlaintext, this will need review diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.java index a0b84a1fa1..b5f50f99db 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.java @@ -1,13 +1,12 @@ package org.bouncycastle.tls.crypto.impl.bc; -import java.io.IOException; - import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; import org.bouncycastle.crypto.params.Ed448PrivateKeyParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; import org.bouncycastle.tls.Certificate; import org.bouncycastle.tls.DefaultTlsCredentialedSigner; import org.bouncycastle.tls.SignatureAndHashAlgorithm; @@ -21,20 +20,9 @@ public class BcDefaultTlsCredentialedSigner extends DefaultTlsCredentialedSigner { - private static BcTlsCertificate getEndEntity(BcTlsCrypto crypto, Certificate certificate) throws IOException - { - if (certificate == null || certificate.isEmpty()) - { - throw new IllegalArgumentException("No certificate"); - } - - return BcTlsCertificate.convert(crypto, certificate.getCertificateAt(0)); - } - private static TlsSigner makeSigner(BcTlsCrypto crypto, AsymmetricKeyParameter privateKey, Certificate certificate, SignatureAndHashAlgorithm signatureAndHashAlgorithm) { - TlsSigner signer; if (privateKey instanceof RSAKeyParameters) { RSAKeyParameters privKeyRSA = (RSAKeyParameters)privateKey; @@ -48,21 +36,11 @@ private static TlsSigner makeSigner(BcTlsCrypto crypto, AsymmetricKeyParameter p } } - RSAKeyParameters pubKeyRSA; - try - { - pubKeyRSA = getEndEntity(crypto, certificate).getPubKeyRSA(); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - - signer = new BcTlsRSASigner(crypto, privKeyRSA, pubKeyRSA); + return new BcTlsRSASigner(crypto, privKeyRSA); } else if (privateKey instanceof DSAPrivateKeyParameters) { - signer = new BcTlsDSASigner(crypto, (DSAPrivateKeyParameters)privateKey); + return new BcTlsDSASigner(crypto, (DSAPrivateKeyParameters)privateKey); } else if (privateKey instanceof ECPrivateKeyParameters) { @@ -85,22 +63,34 @@ else if (privateKey instanceof ECPrivateKeyParameters) } } - signer = new BcTlsECDSASigner(crypto, privKeyEC); + return new BcTlsECDSASigner(crypto, privKeyEC); } else if (privateKey instanceof Ed25519PrivateKeyParameters) { - signer = new BcTlsEd25519Signer(crypto, (Ed25519PrivateKeyParameters)privateKey); + return new BcTlsEd25519Signer(crypto, (Ed25519PrivateKeyParameters)privateKey); } else if (privateKey instanceof Ed448PrivateKeyParameters) { - signer = new BcTlsEd448Signer(crypto, (Ed448PrivateKeyParameters)privateKey); + return new BcTlsEd448Signer(crypto, (Ed448PrivateKeyParameters)privateKey); + } + else if (privateKey instanceof MLDSAPrivateKeyParameters) + { + if (signatureAndHashAlgorithm != null) + { + TlsSigner signer = BcTlsMLDSASigner.create(crypto, (MLDSAPrivateKeyParameters)privateKey, + SignatureScheme.from(signatureAndHashAlgorithm)); + if (signer != null) + { + return signer; + } + } + + throw new IllegalArgumentException("ML-DSA private key of wrong type for signature algorithm"); } else { throw new IllegalArgumentException("'privateKey' type not supported: " + privateKey.getClass().getName()); } - - return signer; } public BcDefaultTlsCredentialedSigner(TlsCryptoParameters cryptoParams, BcTlsCrypto crypto, diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCertificate.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCertificate.java index cfcf90d5b9..77c3f0c536 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCertificate.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCertificate.java @@ -102,7 +102,7 @@ public ASN1Encodable getSigAlgParams() return certificate.getSignatureAlgorithm().getParameters(); } - protected boolean supportsKeyUsage(int keyUsageBits) + protected boolean supportsKeyUsage(int keyUsageBit) { Extensions exts = certificate.getTBSCertificate().getExtensions(); if (exts != null) @@ -111,7 +111,7 @@ protected boolean supportsKeyUsage(int keyUsageBits) if (ku != null) { int bits = ku.getBytes()[0] & 0xff; - if ((bits & keyUsageBits) != keyUsageBits) + if ((bits & keyUsageBit) != keyUsageBit) { return false; } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCrypto.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCrypto.java index 5cf7cd07d9..0b9d6cda35 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCrypto.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsCrypto.java @@ -10,6 +10,7 @@ import org.bouncycastle.crypto.agreement.srp.SRP6Client; import org.bouncycastle.crypto.agreement.srp.SRP6Server; import org.bouncycastle.crypto.agreement.srp.SRP6VerifierGenerator; +import org.bouncycastle.crypto.digests.GOST3411_2012_256Digest; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; @@ -184,9 +185,12 @@ public TlsCipher createCipher(TlsCryptoParameters cryptoParams, int encryptionAl // NOTE: Ignores macAlgorithm return createCipher_SM4_GCM(cryptoParams); + case EncryptionAlgorithm._28147_CNT_IMIT: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.RC4_40: @@ -265,6 +269,7 @@ public boolean hasCryptoHashAlgorithm(int cryptoHashAlgorithm) case CryptoHashAlgorithm.sha384: case CryptoHashAlgorithm.sha512: case CryptoHashAlgorithm.sm3: + case CryptoHashAlgorithm.gostr3411_2012_256: return true; default: @@ -289,7 +294,7 @@ public boolean hasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm) case CryptoSignatureAlgorithm.rsa_pss_pss_sha512: return true; - // TODO[draft-smyshlyaev-tls12-gost-suites-10] + // TODO[RFC 9189] case CryptoSignatureAlgorithm.gostr34102012_256: case CryptoSignatureAlgorithm.gostr34102012_512: @@ -311,11 +316,6 @@ public boolean hasECDHAgreement() return true; } - public boolean hasKemAgreement() - { - return true; - } - public boolean hasEncryptionAlgorithm(int encryptionAlgorithm) { switch (encryptionAlgorithm) @@ -345,9 +345,12 @@ public boolean hasEncryptionAlgorithm(int encryptionAlgorithm) case EncryptionAlgorithm.SM4_GCM: return true; + case EncryptionAlgorithm._28147_CNT_IMIT: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.RC4_40: @@ -371,6 +374,11 @@ public boolean hasHKDFAlgorithm(int cryptoHashAlgorithm) } } + public boolean hasKemAgreement() + { + return true; + } + public boolean hasMacAlgorithm(int macAlgorithm) { switch (macAlgorithm) @@ -389,7 +397,9 @@ public boolean hasMacAlgorithm(int macAlgorithm) public boolean hasNamedGroup(int namedGroup) { - return NamedGroup.refersToASpecificGroup(namedGroup); + return NamedGroup.refersToASpecificCurve(namedGroup) + || NamedGroup.refersToASpecificFiniteField(namedGroup) + || NamedGroup.refersToASpecificKem(namedGroup); } public boolean hasRSAEncryption() @@ -417,11 +427,13 @@ public boolean hasSignatureAlgorithm(short signatureAlgorithm) case SignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512: return true; - // TODO[draft-smyshlyaev-tls12-gost-suites-10] + // TODO[RFC 9189] case SignatureAlgorithm.gostr34102012_256: case SignatureAlgorithm.gostr34102012_512: + // TODO[RFC 8998] // case SignatureAlgorithm.sm2: + default: return false; } @@ -445,6 +457,10 @@ public boolean hasSignatureScheme(int signatureScheme) switch (signatureScheme) { case SignatureScheme.sm2sig_sm3: + // TODO[tls] Test coverage before adding + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: return false; default: { @@ -466,6 +482,11 @@ public boolean hasSRPAuthentication() return true; } + public TlsSecret createHybridSecret(TlsSecret s1, TlsSecret s2) + { + return adoptLocalSecret(Arrays.concatenate(s1.extract(), s2.extract())); + } + public TlsSecret createSecret(byte[] data) { try @@ -508,6 +529,8 @@ public Digest cloneDigest(int cryptoHashAlgorithm, Digest digest) return new SHA512Digest((SHA512Digest)digest); case CryptoHashAlgorithm.sm3: return new SM3Digest((SM3Digest)digest); + case CryptoHashAlgorithm.gostr3411_2012_256: + return new GOST3411_2012_256Digest((GOST3411_2012_256Digest)digest); default: throw new IllegalArgumentException("invalid CryptoHashAlgorithm: " + cryptoHashAlgorithm); } @@ -531,6 +554,8 @@ public Digest createDigest(int cryptoHashAlgorithm) return new SHA512Digest(); case CryptoHashAlgorithm.sm3: return new SM3Digest(); + case CryptoHashAlgorithm.gostr3411_2012_256: + return new GOST3411_2012_256Digest(); default: throw new IllegalArgumentException("invalid CryptoHashAlgorithm: " + cryptoHashAlgorithm); } @@ -580,7 +605,7 @@ protected BlockCipher createCBCBlockCipher(int encryptionAlgorithm) protected TlsCipher createChaCha20Poly1305(TlsCryptoParameters cryptoParams) throws IOException { return new TlsAEADCipher(cryptoParams, new BcChaCha20Poly1305(true), new BcChaCha20Poly1305(false), 32, 16, - TlsAEADCipher.AEAD_CHACHA20_POLY1305); + TlsAEADCipher.AEAD_CHACHA20_POLY1305, null); } protected TlsAEADCipher createCipher_AES_CCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -589,7 +614,8 @@ protected TlsAEADCipher createCipher_AES_CCM(TlsCryptoParameters cryptoParams, i BcTlsAEADCipherImpl encrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_AES_CCM(), true); BcTlsAEADCipherImpl decrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_AES_CCM(), false); - return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_CCM); + return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_CCM, + null); } protected TlsAEADCipher createCipher_AES_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -598,7 +624,7 @@ protected TlsAEADCipher createCipher_AES_GCM(TlsCryptoParameters cryptoParams, i BcTlsAEADCipherImpl encrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_AES_GCM(), true); BcTlsAEADCipherImpl decrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_AES_GCM(), false); - return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_GCM); + return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_GCM, null); } protected TlsAEADCipher createCipher_ARIA_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -607,7 +633,7 @@ protected TlsAEADCipher createCipher_ARIA_GCM(TlsCryptoParameters cryptoParams, BcTlsAEADCipherImpl encrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_ARIA_GCM(), true); BcTlsAEADCipherImpl decrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_ARIA_GCM(), false); - return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_GCM); + return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_GCM, null); } protected TlsAEADCipher createCipher_Camellia_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -616,7 +642,7 @@ protected TlsAEADCipher createCipher_Camellia_GCM(TlsCryptoParameters cryptoPara BcTlsAEADCipherImpl encrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_Camellia_GCM(), true); BcTlsAEADCipherImpl decrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_Camellia_GCM(), false); - return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_GCM); + return new TlsAEADCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAEADCipher.AEAD_GCM, null); } protected TlsCipher createCipher_CBC(TlsCryptoParameters cryptoParams, int encryptionAlgorithm, int cipherKeySize, @@ -637,7 +663,7 @@ protected TlsAEADCipher createCipher_SM4_CCM(TlsCryptoParameters cryptoParams) BcTlsAEADCipherImpl encrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_SM4_CCM(), true); BcTlsAEADCipherImpl decrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_SM4_CCM(), false); - return new TlsAEADCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAEADCipher.AEAD_CCM); + return new TlsAEADCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAEADCipher.AEAD_CCM, null); } protected TlsAEADCipher createCipher_SM4_GCM(TlsCryptoParameters cryptoParams) @@ -646,7 +672,7 @@ protected TlsAEADCipher createCipher_SM4_GCM(TlsCryptoParameters cryptoParams) BcTlsAEADCipherImpl encrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_SM4_GCM(), true); BcTlsAEADCipherImpl decrypt = new BcTlsAEADCipherImpl(createAEADBlockCipher_SM4_GCM(), false); - return new TlsAEADCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAEADCipher.AEAD_GCM); + return new TlsAEADCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAEADCipher.AEAD_GCM, null); } protected TlsNullCipher createNullCipher(TlsCryptoParameters cryptoParams, int macAlgorithm) diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsDHDomain.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsDHDomain.java index 9a66fa2e97..34567de251 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsDHDomain.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsDHDomain.java @@ -57,20 +57,20 @@ public static DHParameters getDomainParameters(TlsDHConfig dhConfig) return new DHParameters(dhGroup.getP(), dhGroup.getG(), dhGroup.getQ(), dhGroup.getL()); } - protected BcTlsCrypto crypto; - protected TlsDHConfig config; - protected DHParameters domainParameters; + protected final BcTlsCrypto crypto; + protected final DHParameters domainParameters; + protected final boolean isPadded; public BcTlsDHDomain(BcTlsCrypto crypto, TlsDHConfig dhConfig) { this.crypto = crypto; - this.config = dhConfig; this.domainParameters = getDomainParameters(dhConfig); + this.isPadded = dhConfig.isPadded(); } public BcTlsSecret calculateDHAgreement(DHPrivateKeyParameters privateKey, DHPublicKeyParameters publicKey) { - return calculateDHAgreement(crypto, privateKey, publicKey, config.isPadded()); + return calculateDHAgreement(crypto, privateKey, publicKey, isPadded); } public TlsAgreement createDH() @@ -80,7 +80,7 @@ public TlsAgreement createDH() public BigInteger decodeParameter(byte[] encoding) throws IOException { - if (config.isPadded() && getValueLength(domainParameters) != encoding.length) + if (isPadded && getValueLength(domainParameters) != encoding.length) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } @@ -109,7 +109,7 @@ public DHPublicKeyParameters decodePublicKey(byte[] encoding) throws IOException public byte[] encodeParameter(BigInteger x) { - return encodeValue(domainParameters, config.isPadded(), x); + return encodeValue(domainParameters, isPadded, x); } public byte[] encodePublicKey(DHPublicKeyParameters publicKey) diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsECDomain.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsECDomain.java index 0562963d06..2aab2663fb 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsECDomain.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsECDomain.java @@ -45,7 +45,13 @@ public static BcTlsSecret calculateECDHAgreement(BcTlsCrypto crypto, ECPrivateKe public static ECDomainParameters getDomainParameters(TlsECConfig ecConfig) { - return getDomainParameters(ecConfig.getNamedGroup()); + ECDomainParameters parameters = getDomainParameters(ecConfig.getNamedGroup()); + if (parameters == null) + { + throw new IllegalArgumentException("No EC configuration provided"); + } + + return parameters; } public static ECDomainParameters getDomainParameters(int namedGroup) @@ -73,13 +79,11 @@ public static ECDomainParameters getDomainParameters(int namedGroup) } protected final BcTlsCrypto crypto; - protected final TlsECConfig config; protected final ECDomainParameters domainParameters; public BcTlsECDomain(BcTlsCrypto crypto, TlsECConfig ecConfig) { this.crypto = crypto; - this.config = ecConfig; this.domainParameters = getDomainParameters(ecConfig); } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd25519Signer.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd25519Signer.java index cdf6ec4fcc..de3df46357 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd25519Signer.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd25519Signer.java @@ -1,7 +1,5 @@ package org.bouncycastle.tls.crypto.impl.bc; -import java.io.IOException; - import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; import org.bouncycastle.crypto.signers.Ed25519Signer; import org.bouncycastle.tls.SignatureAndHashAlgorithm; @@ -16,11 +14,6 @@ public BcTlsEd25519Signer(BcTlsCrypto crypto, Ed25519PrivateKeyParameters privat super(crypto, privateKey); } - public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) throws IOException - { - throw new UnsupportedOperationException(); - } - public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) { if (algorithm == null || SignatureScheme.from(algorithm) != SignatureScheme.ed25519) diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd448Signer.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd448Signer.java index a6decb17cc..e7810861ce 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd448Signer.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsEd448Signer.java @@ -1,7 +1,5 @@ package org.bouncycastle.tls.crypto.impl.bc; -import java.io.IOException; - import org.bouncycastle.crypto.params.Ed448PrivateKeyParameters; import org.bouncycastle.crypto.signers.Ed448Signer; import org.bouncycastle.tls.SignatureAndHashAlgorithm; @@ -17,11 +15,6 @@ public BcTlsEd448Signer(BcTlsCrypto crypto, Ed448PrivateKeyParameters privateKey super(crypto, privateKey); } - public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) throws IOException - { - throw new UnsupportedOperationException(); - } - public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) { if (algorithm == null || SignatureScheme.from(algorithm) != SignatureScheme.ed448) diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLDSASigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLDSASigner.java new file mode 100644 index 0000000000..09e3de2c1b --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLDSASigner.java @@ -0,0 +1,45 @@ +package org.bouncycastle.tls.crypto.impl.bc; + +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSASigner; +import org.bouncycastle.tls.SignatureAndHashAlgorithm; +import org.bouncycastle.tls.SignatureScheme; +import org.bouncycastle.tls.crypto.TlsStreamSigner; +import org.bouncycastle.tls.crypto.impl.PQCUtil; + +public class BcTlsMLDSASigner + extends BcTlsSigner +{ + public static BcTlsMLDSASigner create(BcTlsCrypto crypto, MLDSAPrivateKeyParameters privateKey, int signatureScheme) + { + if (signatureScheme != PQCUtil.getMLDSASignatureScheme(privateKey.getParameters())) + { + return null; + } + + return new BcTlsMLDSASigner(crypto, privateKey, signatureScheme); + } + + private final int signatureScheme; + + private BcTlsMLDSASigner(BcTlsCrypto crypto, MLDSAPrivateKeyParameters privateKey, int signatureScheme) + { + super(crypto, privateKey); + + this.signatureScheme = signatureScheme; + } + + public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) + { + if (algorithm == null || SignatureScheme.from(algorithm) != signatureScheme) + { + throw new IllegalStateException("Invalid algorithm: " + algorithm); + } + + MLDSASigner signer = new MLDSASigner(); + signer.init(true, new ParametersWithRandom(privateKey, crypto.getSecureRandom())); + + return new BcTlsStreamSigner(signer); + } +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKem.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKem.java index 4d15220971..897536f380 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKem.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKem.java @@ -4,8 +4,8 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.SecretWithEncapsulation; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsSecret; @@ -13,8 +13,8 @@ public class BcTlsMLKem implements TlsAgreement { protected final BcTlsMLKemDomain domain; - protected KyberPrivateKeyParameters privateKey; - protected KyberPublicKeyParameters publicKey; + protected MLKEMPrivateKeyParameters privateKey; + protected MLKEMPublicKeyParameters publicKey; protected TlsSecret secret; public BcTlsMLKem(BcTlsMLKemDomain domain) @@ -34,8 +34,8 @@ public byte[] generateEphemeral() throws IOException else { AsymmetricCipherKeyPair kp = domain.generateKeyPair(); - this.privateKey = (KyberPrivateKeyParameters)kp.getPrivate(); - return domain.encodePublicKey((KyberPublicKeyParameters)kp.getPublic()); + this.privateKey = (MLKEMPrivateKeyParameters)kp.getPrivate(); + return domain.encodePublicKey((MLKEMPublicKeyParameters)kp.getPublic()); } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKemDomain.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKemDomain.java index 2025e70b1a..bda0607a85 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKemDomain.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsMLKemDomain.java @@ -2,13 +2,13 @@ import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.SecretWithEncapsulation; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyPairGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMExtractor; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyGenerationParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMKeyPairGenerator; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; import org.bouncycastle.tls.NamedGroup; import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsKemConfig; @@ -16,31 +16,32 @@ public class BcTlsMLKemDomain implements TlsKemDomain { - protected static KyberParameters getKyberParameters(int namedGroup) + public static MLKEMParameters getDomainParameters(TlsKemConfig kemConfig) { - switch (namedGroup) + switch (kemConfig.getNamedGroup()) { case NamedGroup.OQS_mlkem512: - return KyberParameters.kyber512; + case NamedGroup.MLKEM512: + return MLKEMParameters.ml_kem_512; case NamedGroup.OQS_mlkem768: - case NamedGroup.DRAFT_mlkem768: - return KyberParameters.kyber768; + case NamedGroup.MLKEM768: + return MLKEMParameters.ml_kem_768; case NamedGroup.OQS_mlkem1024: - case NamedGroup.DRAFT_mlkem1024: - return KyberParameters.kyber1024; + case NamedGroup.MLKEM1024: + return MLKEMParameters.ml_kem_1024; default: - return null; + throw new IllegalArgumentException("No ML-KEM configuration provided"); } } protected final BcTlsCrypto crypto; - protected final KyberParameters kyberParameters; + protected final MLKEMParameters domainParameters; protected final boolean isServer; public BcTlsMLKemDomain(BcTlsCrypto crypto, TlsKemConfig kemConfig) { this.crypto = crypto; - this.kyberParameters = getKyberParameters(kemConfig.getNamedGroup()); + this.domainParameters = getDomainParameters(kemConfig); this.isServer = kemConfig.isServer(); } @@ -54,33 +55,33 @@ public TlsAgreement createKem() return new BcTlsMLKem(this); } - public BcTlsSecret decapsulate(KyberPrivateKeyParameters privateKey, byte[] ciphertext) + public BcTlsSecret decapsulate(MLKEMPrivateKeyParameters privateKey, byte[] ciphertext) { - KyberKEMExtractor kemExtract = new KyberKEMExtractor(privateKey); + MLKEMExtractor kemExtract = new MLKEMExtractor(privateKey); byte[] secret = kemExtract.extractSecret(ciphertext); return adoptLocalSecret(secret); } - public KyberPublicKeyParameters decodePublicKey(byte[] encoding) + public MLKEMPublicKeyParameters decodePublicKey(byte[] encoding) { - return new KyberPublicKeyParameters(kyberParameters, encoding); + return new MLKEMPublicKeyParameters(domainParameters, encoding); } - public SecretWithEncapsulation encapsulate(KyberPublicKeyParameters publicKey) + public SecretWithEncapsulation encapsulate(MLKEMPublicKeyParameters publicKey) { - KyberKEMGenerator kemGen = new KyberKEMGenerator(crypto.getSecureRandom()); + MLKEMGenerator kemGen = new MLKEMGenerator(crypto.getSecureRandom()); return kemGen.generateEncapsulated(publicKey); } - public byte[] encodePublicKey(KyberPublicKeyParameters publicKey) + public byte[] encodePublicKey(MLKEMPublicKeyParameters publicKey) { return publicKey.getEncoded(); } public AsymmetricCipherKeyPair generateKeyPair() { - KyberKeyPairGenerator keyPairGenerator = new KyberKeyPairGenerator(); - keyPairGenerator.init(new KyberKeyGenerationParameters(crypto.getSecureRandom(), kyberParameters)); + MLKEMKeyPairGenerator keyPairGenerator = new MLKEMKeyPairGenerator(); + keyPairGenerator.init(new MLKEMKeyGenerationParameters(crypto.getSecureRandom(), domainParameters)); return keyPairGenerator.generateKeyPair(); } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRSASigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRSASigner.java index 61b5a956e4..76d66811e1 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRSASigner.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRSASigner.java @@ -24,13 +24,17 @@ public class BcTlsRSASigner extends BcTlsSigner { - private final RSAKeyParameters publicKey; - + /** + * @deprecated Use constructor without 'publicKey' parameter. + */ public BcTlsRSASigner(BcTlsCrypto crypto, RSAKeyParameters privateKey, RSAKeyParameters publicKey) { - super(crypto, privateKey); + this(crypto, privateKey); + } - this.publicKey = publicKey; + public BcTlsRSASigner(BcTlsCrypto crypto, RSAKeyParameters privateKey) + { + super(crypto, privateKey); } public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) throws IOException @@ -63,21 +67,11 @@ public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] h signer.update(hash, 0, hash.length); try { - byte[] signature = signer.generateSignature(); - - signer.init(false, publicKey); - signer.update(hash, 0, hash.length); - - if (signer.verifySignature(signature)) - { - return signature; - } + return signer.generateSignature(); } catch (CryptoException e) { throw new TlsFatalAlert(AlertDescription.internal_error, e); } - - throw new TlsFatalAlert(AlertDescription.internal_error); } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRawKeyCertificate.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRawKeyCertificate.java index de5efc2203..ed9342dded 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRawKeyCertificate.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsRawKeyCertificate.java @@ -26,6 +26,8 @@ import org.bouncycastle.crypto.signers.PSSSigner; import org.bouncycastle.crypto.signers.RSADigestSigner; import org.bouncycastle.crypto.util.PublicKeyFactory; +import org.bouncycastle.pqc.crypto.mldsa.MLDSAPublicKeyParameters; +import org.bouncycastle.pqc.crypto.mldsa.MLDSASigner; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.HashAlgorithm; import org.bouncycastle.tls.SignatureAlgorithm; @@ -39,6 +41,7 @@ import org.bouncycastle.tls.crypto.TlsEncryptor; import org.bouncycastle.tls.crypto.TlsVerifier; import org.bouncycastle.tls.crypto.impl.LegacyTls13Verifier; +import org.bouncycastle.tls.crypto.impl.PQCUtil; import org.bouncycastle.tls.crypto.impl.RSAUtil; /** @@ -91,7 +94,7 @@ public TlsEncryptor createEncryptor(int tlsCertificateRole) throws IOException // } } - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } public TlsVerifier createVerifier(short signatureAlgorithm) throws IOException @@ -141,8 +144,12 @@ public TlsVerifier createVerifier(short signatureAlgorithm) throws IOException return new BcTlsRSAPSSVerifier(crypto, getPubKeyRSA(), signatureScheme); } + // TODO[RFC 9189] + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } } @@ -243,8 +250,23 @@ public Tls13Verifier createVerifier(int signatureScheme) throws IOException // return new BcTls13Verifier(verifier); // } + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: + { + ASN1ObjectIdentifier mlDsaAlgOid = PQCUtil.getMLDSAObjectidentifier(signatureScheme); + validateMLDSA(mlDsaAlgOid); + + MLDSAPublicKeyParameters publicKey = getPubKeyMLDSA(); + + MLDSASigner verifier = new MLDSASigner(); + verifier.init(false, publicKey); + + return new BcTls13Verifier(verifier); + } + default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } } @@ -331,7 +353,7 @@ public DHPublicKeyParameters getPubKeyDH() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not DH", e); } } @@ -343,7 +365,7 @@ public DSAPublicKeyParameters getPubKeyDSS() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not DSS", e); } } @@ -355,7 +377,7 @@ public ECPublicKeyParameters getPubKeyEC() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not EC", e); } } @@ -367,7 +389,7 @@ public Ed25519PublicKeyParameters getPubKeyEd25519() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not Ed25519", e); } } @@ -379,7 +401,19 @@ public Ed448PublicKeyParameters getPubKeyEd448() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not Ed448", e); + } + } + + public MLDSAPublicKeyParameters getPubKeyMLDSA() throws IOException + { + try + { + return (MLDSAPublicKeyParameters)getPublicKey(); + } + catch (ClassCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not ML-DSA", e); } } @@ -391,7 +425,7 @@ public RSAKeyParameters getPubKeyRSA() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not RSA", e); } } @@ -424,7 +458,7 @@ public TlsCertificate checkUsageInRole(int tlsCertificateRole) throws IOExceptio } } - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } protected AsymmetricKeyParameter getPublicKey() throws IOException @@ -439,11 +473,17 @@ protected AsymmetricKeyParameter getPublicKey() throws IOException } } - protected boolean supportsKeyUsage(int keyUsageBits) + protected boolean supportsKeyUsage(int keyUsageBit) { return true; } + protected boolean supportsMLDSA(ASN1ObjectIdentifier mlDsaAlgOid) + { + AlgorithmIdentifier pubKeyAlgID = keyInfo.getAlgorithm(); + return PQCUtil.supportsMLDSA(pubKeyAlgID, mlDsaAlgOid); + } + protected boolean supportsRSA_PKCS1() { AlgorithmIdentifier pubKeyAlgID = keyInfo.getAlgorithm(); @@ -504,17 +544,43 @@ protected boolean supportsSignatureAlgorithm(short signatureAlgorithm, int keyUs return supportsRSA_PSS_PSS(signatureAlgorithm) && publicKey instanceof RSAKeyParameters; + // TODO[RFC 9189] + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: return false; } } - public void validateKeyUsage(int keyUsageBits) + public void validateKeyUsage(int keyUsageBit) + throws IOException + { + if (!supportsKeyUsage(keyUsageBit)) + { + switch (keyUsageBit) + { + case KeyUsage.digitalSignature: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow digital signatures"); + case KeyUsage.keyAgreement: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow key agreement"); + case KeyUsage.keyEncipherment: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow key encipherment"); + default: + throw new TlsFatalAlert(AlertDescription.internal_error); + } + } + } + + protected void validateMLDSA(ASN1ObjectIdentifier mlDsaAlgOid) throws IOException { - if (!supportsKeyUsage(keyUsageBits)) + if (!supportsMLDSA(mlDsaAlgOid)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "No support for ML-DSA signature scheme"); } } @@ -523,7 +589,7 @@ protected void validateRSA_PKCS1() { if (!supportsRSA_PKCS1()) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "No support for rsa_pkcs1 signature schemes"); } } @@ -532,7 +598,8 @@ protected void validateRSA_PSS_PSS(short signatureAlgorithm) { if (!supportsRSA_PSS_PSS(signatureAlgorithm)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "No support for rsa_pss_pss signature schemes"); } } @@ -541,7 +608,8 @@ protected void validateRSA_PSS_RSAE() { if (!supportsRSA_PSS_RSAE()) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "No support for rsa_pss_rsae signature schemes"); } } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSM2Signer.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSM2Signer.java index 6d964a4902..e7203411e9 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSM2Signer.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSM2Signer.java @@ -1,7 +1,5 @@ package org.bouncycastle.tls.crypto.impl.bc; -import java.io.IOException; - import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ParametersWithID; import org.bouncycastle.crypto.params.ParametersWithRandom; @@ -22,11 +20,6 @@ public BcTlsSM2Signer(BcTlsCrypto crypto, ECPrivateKeyParameters privateKey, byt this.identifier = Arrays.clone(identifier); } - public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) throws IOException - { - throw new UnsupportedOperationException(); - } - public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) { if (algorithm == null diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSigner.java index 8b76ab7730..1c20f74445 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSigner.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcTlsSigner.java @@ -1,5 +1,7 @@ package org.bouncycastle.tls.crypto.impl.bc; +import java.io.IOException; + import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.tls.SignatureAndHashAlgorithm; import org.bouncycastle.tls.crypto.TlsSigner; @@ -30,6 +32,11 @@ protected BcTlsSigner(BcTlsCrypto crypto, AsymmetricKeyParameter privateKey) this.privateKey = privateKey; } + public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) throws IOException + { + throw new UnsupportedOperationException(); + } + public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) { return null; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcVerifyingStreamSigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcVerifyingStreamSigner.java deleted file mode 100644 index 1c13238930..0000000000 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcVerifyingStreamSigner.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bouncycastle.tls.crypto.impl.bc; - -import java.io.IOException; -import java.io.OutputStream; - -import org.bouncycastle.crypto.CryptoException; -import org.bouncycastle.crypto.Signer; -import org.bouncycastle.crypto.io.SignerOutputStream; -import org.bouncycastle.tls.AlertDescription; -import org.bouncycastle.tls.TlsFatalAlert; -import org.bouncycastle.tls.crypto.TlsStreamSigner; -import org.bouncycastle.util.io.TeeOutputStream; - -class BcVerifyingStreamSigner - implements TlsStreamSigner -{ - private final Signer signer; - private final Signer verifier; - private final TeeOutputStream output; - - BcVerifyingStreamSigner(Signer signer, Signer verifier) - { - OutputStream outputSigner = new SignerOutputStream(signer); - OutputStream outputVerifier = new SignerOutputStream(verifier); - - this.signer = signer; - this.verifier = verifier; - this.output = new TeeOutputStream(outputSigner, outputVerifier); - } - - public OutputStream getOutputStream() throws IOException - { - return output; - } - - public byte[] getSignature() throws IOException - { - try - { - byte[] signature = signer.generateSignature(); - if (verifier.verifySignature(signature)) - { - return signature; - } - } - catch (CryptoException e) - { - throw new TlsFatalAlert(AlertDescription.internal_error, e); - } - - throw new TlsFatalAlert(AlertDescription.internal_error); - } -} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX25519.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX25519.java index e2928c878e..fa382ebfa8 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX25519.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX25519.java @@ -25,10 +25,10 @@ public BcX25519(BcTlsCrypto crypto) public byte[] generateEphemeral() throws IOException { - crypto.getSecureRandom().nextBytes(privateKey); + X25519.generatePrivateKey(crypto.getSecureRandom(), privateKey); byte[] publicKey = new byte[X25519.POINT_SIZE]; - X25519.scalarMultBase(privateKey, 0, publicKey, 0); + X25519.generatePublicKey(privateKey, 0, publicKey, 0); return publicKey; } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX448.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX448.java index ec3bd1d617..85e2cf5082 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX448.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/BcX448.java @@ -25,10 +25,10 @@ public BcX448(BcTlsCrypto crypto) public byte[] generateEphemeral() throws IOException { - crypto.getSecureRandom().nextBytes(privateKey); + X448.generatePrivateKey(crypto.getSecureRandom(), privateKey); byte[] publicKey = new byte[X448.POINT_SIZE]; - X448.scalarMultBase(privateKey, 0, publicKey, 0); + X448.generatePublicKey(privateKey, 0, publicKey, 0); return publicKey; } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/package-info.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/package-info.java new file mode 100644 index 0000000000..33d43706c4 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/bc/package-info.java @@ -0,0 +1,4 @@ +/** + * Service classes written to support the APIs using the BC light-weight API. + */ +package org.bouncycastle.tls.crypto.impl.bc; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/GCMFipsUtil.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/GCMFipsUtil.java new file mode 100644 index 0000000000..6ad19c81ff --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/GCMFipsUtil.java @@ -0,0 +1,11 @@ +package org.bouncycastle.tls.crypto.impl.jcajce; + +import org.bouncycastle.tls.crypto.impl.AEADNonceGeneratorFactory; + +class GCMFipsUtil +{ + static AEADNonceGeneratorFactory getDefaultFipsGCMNonceGeneratorFactory() + { + return null; + } +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaDefaultTlsCredentialedSigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaDefaultTlsCredentialedSigner.java index abb8dd177c..bea3fed4a2 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaDefaultTlsCredentialedSigner.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaDefaultTlsCredentialedSigner.java @@ -1,8 +1,6 @@ package org.bouncycastle.tls.crypto.impl.jcajce; -import java.io.IOException; import java.security.PrivateKey; -import java.security.PublicKey; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.RSAPrivateKey; @@ -19,16 +17,6 @@ public class JcaDefaultTlsCredentialedSigner extends DefaultTlsCredentialedSigner { - private static JcaTlsCertificate getEndEntity(JcaTlsCrypto crypto, Certificate certificate) throws IOException - { - if (certificate == null || certificate.isEmpty()) - { - throw new IllegalArgumentException("No certificate"); - } - - return JcaTlsCertificate.convert(crypto, certificate.getCertificateAt(0)); - } - private static TlsSigner makeSigner(JcaTlsCrypto crypto, PrivateKey privateKey, Certificate certificate, SignatureAndHashAlgorithm signatureAndHashAlgorithm) { @@ -50,17 +38,7 @@ private static TlsSigner makeSigner(JcaTlsCrypto crypto, PrivateKey privateKey, } } - PublicKey publicKey; - try - { - publicKey = getEndEntity(crypto, certificate).getPubKeyRSA(); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - - signer = new JcaTlsRSASigner(crypto, privateKey, publicKey); + signer = new JcaTlsRSASigner(crypto, privateKey); } else if (privateKey instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(algorithm)) diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java index dedd63c8fb..9f14399762 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java @@ -21,6 +21,7 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Certificate; +import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.tls.AlertDescription; @@ -132,7 +133,7 @@ public TlsEncryptor createEncryptor(int tlsCertificateRole) throws IOException // } } - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } public TlsVerifier createVerifier(short signatureAlgorithm) throws IOException @@ -182,8 +183,12 @@ public TlsVerifier createVerifier(short signatureAlgorithm) throws IOException return new JcaTlsRSAPSSVerifier(crypto, getPubKeyRSA(), signatureScheme); } + // TODO[RFC 9189] + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } } @@ -269,8 +274,12 @@ public Tls13Verifier createVerifier(int signatureScheme) throws IOException // TODO[RFC 8998] // case SignatureScheme.sm2sig_sm3: + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: + default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } } @@ -325,7 +334,7 @@ DHPublicKey getPubKeyDH() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not DH", e); } } @@ -337,7 +346,7 @@ DSAPublicKey getPubKeyDSS() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not DSS", e); } } @@ -349,7 +358,7 @@ ECPublicKey getPubKeyEC() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not EC", e); } } @@ -361,7 +370,7 @@ PublicKey getPubKeyEd25519() throws IOException // Oracle provider (Java 15+) returns the key as an EdDSA one if (!("EdDSA".equals(publicKey.getAlgorithm()) && publicKey.toString().indexOf("Ed25519") >= 0)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not Ed25519"); } } return publicKey; @@ -375,7 +384,7 @@ PublicKey getPubKeyEd448() throws IOException // Oracle provider (Java 15+) returns the key as an EdDSA one if (!("EdDSA".equals(publicKey.getAlgorithm()) && publicKey.toString().indexOf("Ed448") >= 0)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not Ed448"); } } return publicKey; @@ -383,6 +392,7 @@ PublicKey getPubKeyEd448() throws IOException PublicKey getPubKeyRSA() throws IOException { + // TODO[tls] How to reliably check that this is an RSA key? return getPublicKey(); } @@ -466,7 +476,7 @@ public TlsCertificate checkUsageInRole(int tlsCertificateRole) throws IOExceptio } } - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } protected boolean implSupportsSignatureAlgorithm(short signatureAlgorithm) throws IOException @@ -506,6 +516,10 @@ protected boolean implSupportsSignatureAlgorithm(short signatureAlgorithm) throw return supportsRSA_PSS_PSS(signatureAlgorithm) && publicKey instanceof RSAPublicKey; + // TODO[RFC 9189] + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: return false; } @@ -566,7 +580,20 @@ protected void validateKeyUsageBit(int keyUsageBit) { if (!supportsKeyUsageBit(keyUsageBit)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + switch (keyUsageBit) + { + case KeyUsage.digitalSignature: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow digital signatures"); + case KeyUsage.keyAgreement: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow key agreement"); + case KeyUsage.keyEncipherment: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow key encipherment"); + default: + throw new TlsFatalAlert(AlertDescription.internal_error); + } } } @@ -575,7 +602,7 @@ protected void validateRSA_PKCS1() { if (!supportsRSA_PKCS1()) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "No support for rsa_pkcs1 signature schemes"); } } @@ -584,7 +611,8 @@ protected void validateRSA_PSS_PSS(short signatureAlgorithm) { if (!supportsRSA_PSS_PSS(signatureAlgorithm)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "No support for rsa_pss_pss signature schemes"); } } @@ -593,7 +621,8 @@ protected void validateRSA_PSS_RSAE() { if (!supportsRSA_PSS_RSAE()) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "No support for rsa_pss_rsae signature schemes"); } } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java index 5c39e1a115..08ba8595e3 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java @@ -58,6 +58,8 @@ import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.tls.crypto.TlsStreamSigner; import org.bouncycastle.tls.crypto.TlsStreamVerifier; +import org.bouncycastle.tls.crypto.impl.AEADNonceGenerator; +import org.bouncycastle.tls.crypto.impl.AEADNonceGeneratorFactory; import org.bouncycastle.tls.crypto.impl.AbstractTlsCrypto; import org.bouncycastle.tls.crypto.impl.TlsAEADCipher; import org.bouncycastle.tls.crypto.impl.TlsAEADCipherImpl; @@ -75,14 +77,15 @@ /** * Class for providing cryptographic services for TLS based on implementations in the JCA/JCE. *

      - * This class provides default implementations for everything. If you need to customise it, extend the class - * and override the appropriate methods. + * This class provides default implementations for everything. If you need to customise it, extend the class + * and override the appropriate methods. *

      */ public class JcaTlsCrypto extends AbstractTlsCrypto { private final JcaJceHelper helper; + private final JcaJceHelper altHelper; private final SecureRandom entropySource; private final SecureRandom nonceEntropySource; @@ -93,13 +96,28 @@ public class JcaTlsCrypto /** * Base constructor. * - * @param helper a JCA/JCE helper configured for the class's default provider. - * @param entropySource primary entropy source, used for key generation. + * @param helper a JCA/JCE helper configured for the class's default provider. + * @param entropySource primary entropy source, used for key generation. * @param nonceEntropySource secondary entropy source, used for nonce and IV generation. */ protected JcaTlsCrypto(JcaJceHelper helper, SecureRandom entropySource, SecureRandom nonceEntropySource) + { + this(helper, null, entropySource, nonceEntropySource); + } + + /** + * Base constructor. + * + * @param helper a JCA/JCE helper configured for the class's default provider. + * @param altHelper a JCA/JCE helper configured for the class's secondary provider (tried for private keys). + * @param entropySource primary entropy source, used for key generation. + * @param nonceEntropySource secondary entropy source, used for nonce and IV generation. + */ + protected JcaTlsCrypto(JcaJceHelper helper, JcaJceHelper altHelper, SecureRandom entropySource, + SecureRandom nonceEntropySource) { this.helper = helper; + this.altHelper = altHelper; this.entropySource = entropySource; this.nonceEntropySource = nonceEntropySource; } @@ -109,7 +127,8 @@ JceTlsSecret adoptLocalSecret(byte[] data) return new JceTlsSecret(this, data); } - Cipher createRSAEncryptionCipher() throws GeneralSecurityException + Cipher createRSAEncryptionCipher() + throws GeneralSecurityException { try { @@ -237,9 +256,12 @@ public TlsCipher createCipher(TlsCryptoParameters cryptoParams, int encryptionAl // NOTE: Ignores macAlgorithm return createCipher_SM4_GCM(cryptoParams); + case EncryptionAlgorithm._28147_CNT_IMIT: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.RC4_40: @@ -321,7 +343,7 @@ public TlsSRP6Client createSRP6Client(TlsSRPConfig srpConfig) final SRP6Client srpClient = new SRP6Client(); BigInteger[] ng = srpConfig.getExplicitNG(); - SRP6Group srpGroup= new SRP6Group(ng[0], ng[1]); + SRP6Group srpGroup = new SRP6Group(ng[0], ng[1]); srpClient.init(srpGroup, createHash(CryptoHashAlgorithm.sha1), this.getSecureRandom()); return new TlsSRP6Client() @@ -350,7 +372,7 @@ public TlsSRP6Server createSRP6Server(TlsSRPConfig srpConfig, BigInteger srpVeri { final SRP6Server srpServer = new SRP6Server(); BigInteger[] ng = srpConfig.getExplicitNG(); - SRP6Group srpGroup= new SRP6Group(ng[0], ng[1]); + SRP6Group srpGroup = new SRP6Group(ng[0], ng[1]); srpServer.init(srpGroup, srpVerifier, createHash(CryptoHashAlgorithm.sha1), this.getSecureRandom()); return new TlsSRP6Server() { @@ -408,27 +430,25 @@ String getHMACAlgorithmName(int cryptoHashAlgorithm) return "HmacSHA512"; case CryptoHashAlgorithm.sm3: return "HmacSM3"; + case CryptoHashAlgorithm.gostr3411_2012_256: + return "HmacGOST3411-2012-256"; default: throw new IllegalArgumentException("invalid CryptoHashAlgorithm: " + cryptoHashAlgorithm); } } - public AlgorithmParameters getNamedGroupAlgorithmParameters(int namedGroup) throws GeneralSecurityException + public AlgorithmParameters getNamedGroupAlgorithmParameters(int namedGroup) + throws GeneralSecurityException { if (NamedGroup.refersToAnXDHCurve(namedGroup)) { - switch (namedGroup) - { /* - * TODO Return AlgorithmParameters to check against disabled algorithms - * + * TODO Return AlgorithmParameters to check against disabled algorithms? + * * NOTE: The JDK doesn't even support AlgorithmParameters for XDH, so SunJSSE also winds * up using null AlgorithmParameters when checking algorithm constraints. */ - case NamedGroup.x25519: - case NamedGroup.x448: - return null; - } + return null; } else if (NamedGroup.refersToAnECDSACurve(namedGroup)) { @@ -440,18 +460,12 @@ else if (NamedGroup.refersToASpecificFiniteField(namedGroup)) } else if (NamedGroup.refersToASpecificKem(namedGroup)) { - switch (namedGroup) - { /* - * TODO[tls-kem] Return AlgorithmParameters to check against disabled algorithms? + * TODO Return AlgorithmParameters to check against disabled algorithms? + * + * NOTE: See what the JDK/SunJSSE implementation does. */ - case NamedGroup.OQS_mlkem512: - case NamedGroup.OQS_mlkem768: - case NamedGroup.OQS_mlkem1024: - case NamedGroup.DRAFT_mlkem768: - case NamedGroup.DRAFT_mlkem1024: - return null; - } + return null; } throw new IllegalArgumentException("NamedGroup not supported: " + NamedGroup.getText(namedGroup)); @@ -555,7 +569,7 @@ public boolean hasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm) case CryptoSignatureAlgorithm.rsa_pss_pss_sha512: return true; - // TODO[draft-smyshlyaev-tls12-gost-suites-10] + // TODO[RFC 9189] case CryptoSignatureAlgorithm.gostr34102012_256: case CryptoSignatureAlgorithm.gostr34102012_512: @@ -576,11 +590,6 @@ public boolean hasECDHAgreement() { return true; } - - public boolean hasKemAgreement() - { - return true; - } public boolean hasEncryptionAlgorithm(int encryptionAlgorithm) { @@ -630,6 +639,11 @@ public boolean hasHKDFAlgorithm(int cryptoHashAlgorithm) } } + public boolean hasKemAgreement() + { + return true; + } + public boolean hasMacAlgorithm(int macAlgorithm) { switch (macAlgorithm) @@ -737,11 +751,13 @@ public boolean hasSignatureAlgorithm(short signatureAlgorithm) case SignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512: return true; - // TODO[draft-smyshlyaev-tls12-gost-suites-10] + // TODO[RFC 9189] case SignatureAlgorithm.gostr34102012_256: case SignatureAlgorithm.gostr34102012_512: + // TODO[RFC 8998] // case SignatureAlgorithm.sm2: + default: return false; } @@ -768,12 +784,16 @@ public boolean hasSignatureScheme(int signatureScheme) switch (signatureScheme) { case SignatureScheme.sm2sig_sm3: + // TODO[tls] Implement before adding + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: return false; default: { short signature = SignatureScheme.getSignatureAlgorithm(signatureScheme); - switch(SignatureScheme.getCryptoHashAlgorithm(signatureScheme)) + switch (SignatureScheme.getCryptoHashAlgorithm(signatureScheme)) { case CryptoHashAlgorithm.md5: return SignatureAlgorithm.rsa == signature && hasSignatureAlgorithm(signature); @@ -792,6 +812,11 @@ public boolean hasSRPAuthentication() return true; } + public TlsSecret createHybridSecret(TlsSecret s1, TlsSecret s2) + { + return adoptLocalSecret(Arrays.concatenate(s1.extract(), s2.extract())); + } + public TlsSecret createSecret(byte[] data) { try @@ -845,7 +870,7 @@ public TlsECDomain createECDomain(TlsECConfig ecConfig) return new JceTlsECDomain(this, ecConfig); } } - + public TlsKemDomain createKemDomain(TlsKemConfig kemConfig) { return new JceTlsMLKemDomain(this, kemConfig); @@ -883,8 +908,7 @@ protected TlsAEADCipherImpl createAEADCipher(String cipherName, String algorithm * @throws GeneralSecurityException in case of failure. */ protected TlsBlockCipherImpl createBlockCipher(String cipherName, String algorithm, int keySize, - boolean isEncrypting) - throws GeneralSecurityException + boolean isEncrypting) throws GeneralSecurityException { return new JceBlockCipherImpl(this, helper.createCipher(cipherName), algorithm, keySize, isEncrypting); } @@ -900,8 +924,7 @@ protected TlsBlockCipherImpl createBlockCipher(String cipherName, String algorit * @throws GeneralSecurityException in case of failure. */ protected TlsBlockCipherImpl createBlockCipherWithCBCImplicitIV(String cipherName, String algorithm, int keySize, - boolean isEncrypting) - throws GeneralSecurityException + boolean isEncrypting) throws GeneralSecurityException { return new JceBlockCipherWithCBCImplicitIVImpl(this, helper.createCipher(cipherName), algorithm, isEncrypting); } @@ -924,7 +947,7 @@ protected TlsHash createHash(String digestName) * * @param macAlgorithm the name of the algorithm supporting the MAC. * @return a null cipher suite implementation. - * @throws IOException in case of failure. + * @throws IOException in case of failure. * @throws GeneralSecurityException in case of a specific failure in the JCA/JCE layer. */ protected TlsNullCipher createNullCipher(TlsCryptoParameters cryptoParams, int macAlgorithm) @@ -945,51 +968,89 @@ protected TlsStreamSigner createStreamSigner(SignatureAndHashAlgorithm algorithm protected TlsStreamSigner createStreamSigner(String algorithmName, AlgorithmParameterSpec parameter, PrivateKey privateKey, boolean needsRandom) throws IOException { + SecureRandom random = needsRandom ? getSecureRandom() : null; + try { - SecureRandom random = needsRandom ? getSecureRandom() : null; - - JcaJceHelper helper = getHelper(); - try { - if (null != parameter) + return createStreamSigner(getHelper(), algorithmName, parameter, privateKey, random); + } + catch (InvalidKeyException e) + { + JcaJceHelper altHelper = getAltHelper(); + if (altHelper == null) { - Signature dummySigner = helper.createSignature(algorithmName); - dummySigner.initSign(privateKey, random); - helper = new ProviderJcaJceHelper(dummySigner.getProvider()); + throw e; } - Signature signer = helper.createSignature(algorithmName); - if (null != parameter) - { - signer.setParameter(parameter); - } - signer.initSign(privateKey, random); - return new JcaTlsStreamSigner(signer); + return createStreamSigner(altHelper, algorithmName, parameter, privateKey, random); } - catch (InvalidKeyException e) + } + catch (GeneralSecurityException e) + { + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } + } + + protected TlsStreamSigner createStreamSigner(JcaJceHelper helper, String algorithmName, + AlgorithmParameterSpec parameter, PrivateKey privateKey, SecureRandom random) throws GeneralSecurityException + { + try + { + if (null != parameter) { - String upperAlg = Strings.toUpperCase(algorithmName); - if (upperAlg.endsWith("MGF1")) + Signature dummySigner; + try { - // ANDMGF1 has vanished from the Sun PKCS11 provider. - algorithmName = upperAlg.replace("ANDMGF1", "SSA-PSS"); - return createStreamSigner(algorithmName, parameter, privateKey, needsRandom); + dummySigner = helper.createSignature(algorithmName); } - else + catch (NoSuchAlgorithmException e) { - throw e; + // more PKCS#11 mischief + String upperAlg = Strings.toUpperCase(algorithmName); + if (upperAlg.endsWith("ANDMGF1")) + { + // ANDMGF1 has vanished from the Sun PKCS11 provider. + algorithmName = upperAlg.replace("ANDMGF1", "SSA-PSS"); + dummySigner = helper.createSignature(algorithmName); + } + else + { + throw e; + } } + + dummySigner.initSign(privateKey, random); + helper = new ProviderJcaJceHelper(dummySigner.getProvider()); } + + Signature signer = helper.createSignature(algorithmName); + if (null != parameter) + { + signer.setParameter(parameter); + } + signer.initSign(privateKey, random); + return new JcaTlsStreamSigner(signer); } - catch (GeneralSecurityException e) + catch (InvalidKeyException e) { - throw new TlsFatalAlert(AlertDescription.internal_error, e); + String upperAlg = Strings.toUpperCase(algorithmName); + if (upperAlg.endsWith("ANDMGF1")) + { + // ANDMGF1 has vanished from the Sun PKCS11 provider. + algorithmName = upperAlg.replace("ANDMGF1", "SSA-PSS"); + return createStreamSigner(helper, algorithmName, parameter, privateKey, random); + } + else + { + throw e; + } } } - protected TlsStreamVerifier createStreamVerifier(DigitallySigned digitallySigned, PublicKey publicKey) throws IOException + protected TlsStreamVerifier createStreamVerifier(DigitallySigned digitallySigned, PublicKey publicKey) + throws IOException { String algorithmName = JcaUtils.getJcaAlgorithmName(digitallySigned.getAlgorithm()); @@ -1050,39 +1111,6 @@ protected Tls13Verifier createTls13Verifier(String algorithmName, AlgorithmParam } } - protected TlsStreamSigner createVerifyingStreamSigner(SignatureAndHashAlgorithm algorithm, PrivateKey privateKey, - boolean needsRandom, PublicKey publicKey) throws IOException - { - String algorithmName = JcaUtils.getJcaAlgorithmName(algorithm); - - return createVerifyingStreamSigner(algorithmName, null, privateKey, needsRandom, publicKey); - } - - protected TlsStreamSigner createVerifyingStreamSigner(String algorithmName, AlgorithmParameterSpec parameter, - PrivateKey privateKey, boolean needsRandom, PublicKey publicKey) throws IOException - { - try - { - Signature signer = getHelper().createSignature(algorithmName); - Signature verifier = getHelper().createSignature(algorithmName); - - if (null != parameter) - { - signer.setParameter(parameter); - verifier.setParameter(parameter); - } - - signer.initSign(privateKey, needsRandom ? getSecureRandom() : null); - verifier.initVerify(publicKey); - - return new JcaVerifyingStreamSigner(signer, verifier); - } - catch (GeneralSecurityException e) - { - throw new TlsFatalAlert(AlertDescription.internal_error, e); - } - } - protected Boolean isSupportedEncryptionAlgorithm(int encryptionAlgorithm) { switch (encryptionAlgorithm) @@ -1132,9 +1160,12 @@ protected Boolean isSupportedEncryptionAlgorithm(int encryptionAlgorithm) case EncryptionAlgorithm.SM4_GCM: return isUsableCipher("SM4/GCM/NoPadding", 128); + case EncryptionAlgorithm._28147_CNT_IMIT: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.RC4_40: @@ -1177,8 +1208,7 @@ protected Boolean isSupportedNamedGroup(int namedGroup) } else if (NamedGroup.refersToASpecificKem(namedGroup)) { - // TODO[tls-kem] When implemented via provider, need to check for support dynamically - return Boolean.TRUE; + return Boolean.valueOf(KemUtil.isKemSupported(this, NamedGroup.getKemName(namedGroup))); } else if (NamedGroup.refersToAnECDSACurve(namedGroup)) { @@ -1229,6 +1259,11 @@ public JcaJceHelper getHelper() return helper; } + public JcaJceHelper getAltHelper() + { + return altHelper; + } + protected TlsBlockCipherImpl createCBCBlockCipherImpl(TlsCryptoParameters cryptoParams, String algorithm, int cipherKeySize, boolean forEncryption) throws GeneralSecurityException { @@ -1248,7 +1283,7 @@ private TlsCipher createChaCha20Poly1305(TlsCryptoParameters cryptoParams) throws IOException, GeneralSecurityException { return new TlsAEADCipher(cryptoParams, new JceChaCha20Poly1305(this, helper, true), - new JceChaCha20Poly1305(this, helper, false), 32, 16, TlsAEADCipher.AEAD_CHACHA20_POLY1305); + new JceChaCha20Poly1305(this, helper, false), 32, 16, TlsAEADCipher.AEAD_CHACHA20_POLY1305, null); } private TlsAEADCipher createCipher_AES_CCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1256,7 +1291,7 @@ private TlsAEADCipher createCipher_AES_CCM(TlsCryptoParameters cryptoParams, int { return new TlsAEADCipher(cryptoParams, createAEADCipher("AES/CCM/NoPadding", "AES", cipherKeySize, true), createAEADCipher("AES/CCM/NoPadding", "AES", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_CCM); + TlsAEADCipher.AEAD_CCM, null); } private TlsAEADCipher createCipher_AES_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1264,7 +1299,7 @@ private TlsAEADCipher createCipher_AES_GCM(TlsCryptoParameters cryptoParams, int { return new TlsAEADCipher(cryptoParams, createAEADCipher("AES/GCM/NoPadding", "AES", cipherKeySize, true), createAEADCipher("AES/GCM/NoPadding", "AES", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); } private TlsAEADCipher createCipher_ARIA_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1272,7 +1307,7 @@ private TlsAEADCipher createCipher_ARIA_GCM(TlsCryptoParameters cryptoParams, in { return new TlsAEADCipher(cryptoParams, createAEADCipher("ARIA/GCM/NoPadding", "ARIA", cipherKeySize, true), createAEADCipher("ARIA/GCM/NoPadding", "ARIA", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); } private TlsAEADCipher createCipher_Camellia_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1281,7 +1316,7 @@ private TlsAEADCipher createCipher_Camellia_GCM(TlsCryptoParameters cryptoParams return new TlsAEADCipher(cryptoParams, createAEADCipher("Camellia/GCM/NoPadding", "Camellia", cipherKeySize, true), createAEADCipher("Camellia/GCM/NoPadding", "Camellia", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); } protected TlsCipher createCipher_CBC(TlsCryptoParameters cryptoParams, String algorithm, int cipherKeySize, @@ -1302,7 +1337,7 @@ private TlsAEADCipher createCipher_SM4_CCM(TlsCryptoParameters cryptoParams) int cipherKeySize = 16, macSize = 16; return new TlsAEADCipher(cryptoParams, createAEADCipher("SM4/CCM/NoPadding", "SM4", cipherKeySize, true), createAEADCipher("SM4/CCM/NoPadding", "SM4", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_CCM); + TlsAEADCipher.AEAD_CCM, null); } private TlsAEADCipher createCipher_SM4_GCM(TlsCryptoParameters cryptoParams) @@ -1311,7 +1346,27 @@ private TlsAEADCipher createCipher_SM4_GCM(TlsCryptoParameters cryptoParams) int cipherKeySize = 16, macSize = 16; return new TlsAEADCipher(cryptoParams, createAEADCipher("SM4/GCM/NoPadding", "SM4", cipherKeySize, true), createAEADCipher("SM4/GCM/NoPadding", "SM4", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); + } + + /** + * Optionally return an {@link AEADNonceGeneratorFactory} that creates {@link AEADNonceGenerator} + * instances suitable for generating TLS 1.2 GCM nonces in a FIPS approved way (or null). It is not needed + * or intended to be used in a non-FIPS context. + *

      + * Clients of this {@link JcaTlsCrypto} instance MAY assume from a non-null return value that the + * resulting {@link AEADNonceGenerator} implementation(s) are FIPS compliant; implementations that violate + * this assumption risk FIPS compliance failures. + *

      + * In particular, when BCJSSE is configured in FIPS mode, GCM cipher suites are enabled for TLS 1.2 if + * (and only if) a call to this method returns a non-null value. This can be achieved by configuring + * BCJSSE with a user-defined {@link JcaTlsCryptoProvider} subclass, which in turn creates instances of a + * {@link JcaTlsCrypto} subclass, with this method overridden to return a suitable + * {@link AEADNonceGeneratorFactory}. + */ + public AEADNonceGeneratorFactory getFipsGCMNonceGeneratorFactory() + { + return GCMFipsUtil.getDefaultFipsGCMNonceGeneratorFactory(); } String getDigestName(int cryptoHashAlgorithm) @@ -1332,6 +1387,8 @@ String getDigestName(int cryptoHashAlgorithm) return "SHA-512"; case CryptoHashAlgorithm.sm3: return "SM3"; + case CryptoHashAlgorithm.gostr3411_2012_256: + return "GOST3411-2012-256"; default: throw new IllegalArgumentException("invalid CryptoHashAlgorithm: " + cryptoHashAlgorithm); } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCryptoProvider.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCryptoProvider.java index 8368e8682c..9b5d81f364 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCryptoProvider.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCryptoProvider.java @@ -20,6 +20,7 @@ public class JcaTlsCryptoProvider implements TlsCryptoProvider { private JcaJceHelper helper = new DefaultJcaJceHelper(); + private JcaJceHelper altHelper = null; public JcaTlsCryptoProvider() { @@ -34,6 +35,21 @@ public JcaTlsCryptoProvider() public JcaTlsCryptoProvider setProvider(Provider provider) { this.helper = new ProviderJcaJceHelper(provider); + this.altHelper = null; + + return this; + } + + /** + * Set the alternate provider of cryptographic services for any JcaTlsCrypto we build (usually points to a + * HSM). + * + * @param provider the provider class to source cryptographic services from. + * @return the current builder instance. + */ + public JcaTlsCryptoProvider setAlternateProvider(Provider provider) + { + this.altHelper = new ProviderJcaJceHelper(provider); return this; } @@ -47,6 +63,20 @@ public JcaTlsCryptoProvider setProvider(Provider provider) public JcaTlsCryptoProvider setProvider(String providerName) { this.helper = new NamedJcaJceHelper(providerName); + this.altHelper = null; + + return this; + } + + /** + * Set the provider of cryptographic services for any JcaTlsCrypto we build by name (usually refers to a HSM). + * + * @param providerName the name of the provider class to source cryptographic services from. + * @return the current builder instance. + */ + public JcaTlsCryptoProvider setAlternateProvider(String providerName) + { + this.altHelper = new NamedJcaJceHelper(providerName); return this; } @@ -92,7 +122,7 @@ public JcaTlsCrypto create(SecureRandom random) */ public JcaTlsCrypto create(SecureRandom keyRandom, SecureRandom nonceRandom) { - return new JcaTlsCrypto(getHelper(), keyRandom, nonceRandom); + return new JcaTlsCrypto(getHelper(), getAltHelper(), keyRandom, nonceRandom); } public JcaJceHelper getHelper() @@ -100,6 +130,11 @@ public JcaJceHelper getHelper() return helper; } + public JcaJceHelper getAltHelper() + { + return altHelper; + } + @SuppressWarnings("serial") private static class NonceEntropySource extends SecureRandom diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsECDSA13Signer.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsECDSA13Signer.java index 6e97fd5b16..804a8932dc 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsECDSA13Signer.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsECDSA13Signer.java @@ -2,9 +2,12 @@ import java.io.IOException; import java.security.GeneralSecurityException; +import java.security.InvalidKeyException; import java.security.PrivateKey; +import java.security.SecureRandom; import java.security.Signature; +import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.SignatureAndHashAlgorithm; import org.bouncycastle.tls.SignatureScheme; @@ -50,12 +53,25 @@ public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] h throw new IllegalStateException("Invalid algorithm: " + algorithm); } + SecureRandom random = crypto.getSecureRandom(); + try { - Signature signer = crypto.getHelper().createSignature("NoneWithECDSA"); - signer.initSign(privateKey, crypto.getSecureRandom()); - signer.update(hash, 0, hash.length); - return signer.sign(); + try + { + return implGenerateRawSignature(crypto.getHelper(), privateKey, random, hash); + } + catch (InvalidKeyException e) + { + // try with PKCS#11 (usually) alternative provider + JcaJceHelper altHelper = crypto.getAltHelper(); + if (altHelper == null) + { + throw e; + } + + return implGenerateRawSignature(altHelper, privateKey, random, hash); + } } catch (GeneralSecurityException e) { @@ -68,4 +84,13 @@ public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) { return null; } + + private static byte[] implGenerateRawSignature(JcaJceHelper helper, PrivateKey privateKey, SecureRandom random, + byte[] hash) throws GeneralSecurityException + { + Signature signer = helper.createSignature("NoneWithECDSA"); + signer.initSign(privateKey, random); + signer.update(hash, 0, hash.length); + return signer.sign(); + } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsRSASigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsRSASigner.java index 82226429ef..584bf44f14 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsRSASigner.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsRSASigner.java @@ -25,11 +25,18 @@ public class JcaTlsRSASigner { private final JcaTlsCrypto crypto; private final PrivateKey privateKey; - private final PublicKey publicKey; private Signature rawSigner = null; + /** + * @deprecated Use constructor without 'publicKey' parameter. + */ public JcaTlsRSASigner(JcaTlsCrypto crypto, PrivateKey privateKey, PublicKey publicKey) + { + this(crypto, privateKey); + } + + public JcaTlsRSASigner(JcaTlsCrypto crypto, PrivateKey privateKey) { if (null == crypto) { @@ -42,7 +49,6 @@ public JcaTlsRSASigner(JcaTlsCrypto crypto, PrivateKey privateKey, PublicKey pub this.crypto = crypto; this.privateKey = privateKey; - this.publicKey = publicKey; } public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) throws IOException @@ -78,15 +84,7 @@ public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] h signer.update(input, 0, input.length); - byte[] signature = signer.sign(); - - signer.initVerify(publicKey); - signer.update(input, 0, input.length); - - if (signer.verify(signature)) - { - return signature; - } + return signer.sign(); } catch (GeneralSecurityException e) { @@ -96,8 +94,6 @@ public byte[] generateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] h { this.rawSigner = null; } - - throw new TlsFatalAlert(AlertDescription.internal_error); } public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) throws IOException @@ -110,7 +106,7 @@ public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) thro && JcaUtils.isSunMSCAPIProviderActive() && isSunMSCAPIRawSigner()) { - return crypto.createVerifyingStreamSigner(algorithm, privateKey, true, publicKey); + return crypto.createStreamSigner(algorithm, privateKey, true); } return null; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaVerifyingStreamSigner.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaVerifyingStreamSigner.java deleted file mode 100644 index cb8a57d840..0000000000 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaVerifyingStreamSigner.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bouncycastle.tls.crypto.impl.jcajce; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.Signature; -import java.security.SignatureException; - -import org.bouncycastle.jcajce.io.OutputStreamFactory; -import org.bouncycastle.tls.AlertDescription; -import org.bouncycastle.tls.TlsFatalAlert; -import org.bouncycastle.tls.crypto.TlsStreamSigner; -import org.bouncycastle.util.io.TeeOutputStream; - -class JcaVerifyingStreamSigner - implements TlsStreamSigner -{ - private final Signature signer; - private final Signature verifier; - private final OutputStream output; - - JcaVerifyingStreamSigner(Signature signer, Signature verifier) - { - OutputStream outputSigner = OutputStreamFactory.createStream(signer); - OutputStream outputVerifier = OutputStreamFactory.createStream(verifier); - - this.signer = signer; - this.verifier = verifier; - this.output = new TeeOutputStream(outputSigner, outputVerifier); - } - - public OutputStream getOutputStream() throws IOException - { - return output; - } - - public byte[] getSignature() throws IOException - { - try - { - byte[] signature = signer.sign(); - if (verifier.verify(signature)) - { - return signature; - } - } - catch (SignatureException e) - { - throw new TlsFatalAlert(AlertDescription.internal_error, e); - } - - throw new TlsFatalAlert(AlertDescription.internal_error); - } -} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsDHDomain.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsDHDomain.java index 578f3d486d..b7e1d96f1a 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsDHDomain.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsDHDomain.java @@ -71,8 +71,8 @@ public static JceTlsSecret calculateDHAgreement(JcaTlsCrypto crypto, DHPrivateKe } protected final JcaTlsCrypto crypto; - protected final TlsDHConfig dhConfig; protected final DHParameterSpec dhSpec; + protected final boolean isPadded; public JceTlsDHDomain(JcaTlsCrypto crypto, TlsDHConfig dhConfig) { @@ -83,8 +83,8 @@ public JceTlsDHDomain(JcaTlsCrypto crypto, TlsDHConfig dhConfig) if (null != spec) { this.crypto = crypto; - this.dhConfig = dhConfig; this.dhSpec = spec; + this.isPadded = dhConfig.isPadded(); return; } } @@ -95,7 +95,7 @@ public JceTlsDHDomain(JcaTlsCrypto crypto, TlsDHConfig dhConfig) public JceTlsSecret calculateDHAgreement(DHPrivateKey privateKey, DHPublicKey publicKey) throws IOException { - return calculateDHAgreement(crypto, privateKey, publicKey, dhConfig.isPadded()); + return calculateDHAgreement(crypto, privateKey, publicKey, isPadded); } public TlsAgreement createDH() @@ -105,7 +105,7 @@ public TlsAgreement createDH() public BigInteger decodeParameter(byte[] encoding) throws IOException { - if (dhConfig.isPadded() && getValueLength(dhSpec) != encoding.length) + if (isPadded && getValueLength(dhSpec) != encoding.length) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } @@ -140,7 +140,7 @@ public DHPublicKey decodePublicKey(byte[] encoding) throws IOException public byte[] encodeParameter(BigInteger x) throws IOException { - return encodeValue(dhSpec, dhConfig.isPadded(), x); + return encodeValue(dhSpec, isPadded, x); } public byte[] encodePublicKey(DHPublicKey publicKey) throws IOException diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsECDomain.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsECDomain.java index 8c332cbf04..084a1a658f 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsECDomain.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsECDomain.java @@ -29,7 +29,6 @@ public class JceTlsECDomain implements TlsECDomain { protected final JcaTlsCrypto crypto; - protected final TlsECConfig ecConfig; protected final ECParameterSpec ecSpec; protected final ECCurve ecCurve; @@ -42,7 +41,6 @@ public JceTlsECDomain(JcaTlsCrypto crypto, TlsECConfig ecConfig) if (null != spec) { this.crypto = crypto; - this.ecConfig = ecConfig; this.ecSpec = spec; this.ecCurve = ECUtil.convertCurve(spec.getCurve(), spec.getOrder(), spec.getCofactor()); return; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKem.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKem.java index 3a318e4f51..325eaf82a1 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKem.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKem.java @@ -1,11 +1,11 @@ package org.bouncycastle.tls.crypto.impl.jcajce; import java.io.IOException; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.PublicKey; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.SecretWithEncapsulation; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsSecret; @@ -13,8 +13,8 @@ public class JceTlsMLKem implements TlsAgreement { protected final JceTlsMLKemDomain domain; - protected KyberPrivateKeyParameters privateKey; - protected KyberPublicKeyParameters publicKey; + protected PrivateKey privateKey; + protected PublicKey publicKey; protected TlsSecret secret; public JceTlsMLKem(JceTlsMLKemDomain domain) @@ -26,16 +26,16 @@ public byte[] generateEphemeral() throws IOException { if (domain.isServer()) { - SecretWithEncapsulation encap = domain.encapsulate(publicKey); + SecretKeyWithEncapsulation encap = domain.encapsulate(publicKey); this.publicKey = null; - this.secret = domain.adoptLocalSecret(encap.getSecret()); + this.secret = domain.adoptLocalSecret(encap.getEncoded()); return encap.getEncapsulation(); } else { - AsymmetricCipherKeyPair kp = domain.generateKeyPair(); - this.privateKey = (KyberPrivateKeyParameters)kp.getPrivate(); - return domain.encodePublicKey((KyberPublicKeyParameters)kp.getPublic()); + KeyPair kp = domain.generateKeyPair(); + this.privateKey = kp.getPrivate(); + return KemUtil.encodePublicKey(kp.getPublic()); } } diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKemDomain.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKemDomain.java index 7a67176231..f85528070b 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKemDomain.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JceTlsMLKemDomain.java @@ -1,14 +1,18 @@ package org.bouncycastle.tls.crypto.impl.jcajce; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.SecretWithEncapsulation; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMExtractor; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKEMGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyGenerationParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberKeyPairGenerator; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPrivateKeyParameters; -import org.bouncycastle.pqc.crypto.crystals.kyber.KyberPublicKeyParameters; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.KeyGenerator; + +import org.bouncycastle.jcajce.SecretKeyWithEncapsulation; +import org.bouncycastle.jcajce.spec.KEMExtractSpec; +import org.bouncycastle.jcajce.spec.KEMGenerateSpec; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; import org.bouncycastle.tls.NamedGroup; import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsKemConfig; @@ -16,31 +20,14 @@ public class JceTlsMLKemDomain implements TlsKemDomain { - protected static KyberParameters getKyberParameters(int namedGroup) - { - switch (namedGroup) - { - case NamedGroup.OQS_mlkem512: - return KyberParameters.kyber512; - case NamedGroup.OQS_mlkem768: - case NamedGroup.DRAFT_mlkem768: - return KyberParameters.kyber768; - case NamedGroup.OQS_mlkem1024: - case NamedGroup.DRAFT_mlkem1024: - return KyberParameters.kyber1024; - default: - return null; - } - } - protected final JcaTlsCrypto crypto; - protected final KyberParameters kyberParameters; + protected final String kemName; protected final boolean isServer; public JceTlsMLKemDomain(JcaTlsCrypto crypto, TlsKemConfig kemConfig) { this.crypto = crypto; - this.kyberParameters = getKyberParameters(kemConfig.getNamedGroup()); + this.kemName = NamedGroup.getKemName(kemConfig.getNamedGroup()); this.isServer = kemConfig.isServer(); } @@ -54,34 +41,64 @@ public TlsAgreement createKem() return new JceTlsMLKem(this); } - public JceTlsSecret decapsulate(KyberPrivateKeyParameters privateKey, byte[] ciphertext) + public JceTlsSecret decapsulate(PrivateKey privateKey, byte[] ciphertext) { - KyberKEMExtractor kemExtract = new KyberKEMExtractor(privateKey); - byte[] secret = kemExtract.extractSecret(ciphertext); - return adoptLocalSecret(secret); + try + { + KeyGenerator keyGenerator = crypto.getHelper().createKeyGenerator(kemName); + keyGenerator.init(new KEMExtractSpec.Builder(privateKey, ciphertext, "DEF", 256).withNoKdf().build()); + SecretKeyWithEncapsulation secEnc = (SecretKeyWithEncapsulation)keyGenerator.generateKey(); + return adoptLocalSecret(secEnc.getEncoded()); + } + catch (Exception e) + { + throw Exceptions.illegalArgumentException("invalid key: " + e.getMessage(), e); + } } - public KyberPublicKeyParameters decodePublicKey(byte[] encoding) + public PublicKey decodePublicKey(byte[] encoding) + throws IOException { - return new KyberPublicKeyParameters(kyberParameters, encoding); + return KemUtil.decodePublicKey(crypto, kemName, encoding); } - public SecretWithEncapsulation encapsulate(KyberPublicKeyParameters publicKey) + public SecretKeyWithEncapsulation encapsulate(PublicKey publicKey) { - KyberKEMGenerator kemGen = new KyberKEMGenerator(crypto.getSecureRandom()); - return kemGen.generateEncapsulated(publicKey); + try + { + KeyGenerator keyGenerator = crypto.getHelper().createKeyGenerator(kemName); + keyGenerator.init(new KEMGenerateSpec.Builder(publicKey, "DEF", 256).withNoKdf().build()); + return (SecretKeyWithEncapsulation)keyGenerator.generateKey(); + } + catch (Exception e) + { + throw Exceptions.illegalArgumentException("invalid key: " + e.getMessage(), e); + } } - public byte[] encodePublicKey(KyberPublicKeyParameters publicKey) + public byte[] encodePublicKey(PublicKey publicKey) + throws IOException { - return publicKey.getEncoded(); + return KemUtil.encodePublicKey(publicKey); } - public AsymmetricCipherKeyPair generateKeyPair() + public KeyPair generateKeyPair() { - KyberKeyPairGenerator keyPairGenerator = new KyberKeyPairGenerator(); - keyPairGenerator.init(new KyberKeyGenerationParameters(crypto.getSecureRandom(), kyberParameters)); - return keyPairGenerator.generateKeyPair(); + try + { + // TODO How to pass only the SecureRandom to initialize if we use the full name in the getInstance? +// KeyPairGenerator keyPairGenerator = KemUtil.getKeyPairGenerator(crypto, kemName); +// keyPairGenerator.initialize((AlgorithmParameterSpec)null, crypto.getSecureRandom()); +// return keyPairGenerator.generateKeyPair(); + + KeyPairGenerator keyPairGenerator = crypto.getHelper().createKeyPairGenerator("ML-KEM"); + keyPairGenerator.initialize(MLKEMParameterSpec.fromName(kemName), crypto.getSecureRandom()); + return keyPairGenerator.generateKeyPair(); + } + catch (GeneralSecurityException e) + { + throw Exceptions.illegalStateException("unable to create key pair: " + e.getMessage(), e); + } } public boolean isServer() diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/KemUtil.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/KemUtil.java new file mode 100644 index 0000000000..d543f96b74 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/KemUtil.java @@ -0,0 +1,166 @@ +package org.bouncycastle.tls.crypto.impl.jcajce; + +import java.io.IOException; +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.PublicKey; +import java.security.spec.EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import javax.crypto.KeyGenerator; + +import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jcajce.interfaces.MLKEMPublicKey; +import org.bouncycastle.jcajce.spec.MLKEMParameterSpec; +import org.bouncycastle.jcajce.spec.MLKEMPublicKeySpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.tls.AlertDescription; +import org.bouncycastle.tls.TlsFatalAlert; + +class KemUtil +{ + static PublicKey decodePublicKey(JcaTlsCrypto crypto, String kemName, byte[] encoding) throws TlsFatalAlert + { + try + { + KeyFactory kf = crypto.getHelper().createKeyFactory(kemName); + + // More efficient BC-specific method + if (kf.getProvider() instanceof BouncyCastleProvider) + { + try + { + // TODO Add RawEncodedKeySpec support to BC? + + MLKEMParameterSpec params = MLKEMParameterSpec.fromName(kemName); + MLKEMPublicKeySpec keySpec = new MLKEMPublicKeySpec(params, encoding); + return kf.generatePublic(keySpec); + } + catch (Exception e) + { + // Fallback to X.509 + } + } + + EncodedKeySpec keySpec = createX509EncodedKeySpec(getAlgorithmOID(kemName), encoding); + return kf.generatePublic(keySpec); + } + catch (Exception e) + { + throw new TlsFatalAlert(AlertDescription.illegal_parameter, e); + } + } + + static byte[] encodePublicKey(PublicKey publicKey) throws TlsFatalAlert + { + // More efficient BC-specific method + if (publicKey instanceof MLKEMPublicKey) + { + return ((MLKEMPublicKey)publicKey).getPublicData(); + } + + if (!"X.509".equals(publicKey.getFormat())) + { + throw new TlsFatalAlert(AlertDescription.internal_error, "Public key format unrecognized"); + } + + try + { + SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); + return spki.getPublicKeyData().getOctets(); + } + catch (Exception e) + { + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } + } + + static KeyFactory getKeyFactory(JcaTlsCrypto crypto, String kemName) + + { + try + { + return crypto.getHelper().createKeyFactory(kemName); + } + catch (AssertionError e) + { + } + catch (Exception e) + { + } + + return null; + } + + static KeyGenerator getKeyGenerator(JcaTlsCrypto crypto, String kemName) + { + try + { + return crypto.getHelper().createKeyGenerator(kemName); + } + catch (AssertionError e) + { + } + catch (Exception e) + { + } + + return null; + } + + static KeyPairGenerator getKeyPairGenerator(JcaTlsCrypto crypto, String kemName) + { + try + { + KeyPairGenerator keyPairGenerator = crypto.getHelper().createKeyPairGenerator("ML-KEM"); + keyPairGenerator.initialize(MLKEMParameterSpec.fromName(kemName), crypto.getSecureRandom()); + return keyPairGenerator; + } + catch (AssertionError e) + { + } + catch (Exception e) + { + } + + return null; + } + + static boolean isKemSupported(JcaTlsCrypto crypto, String kemName) + { + return kemName != null + && getKeyFactory(crypto, kemName) != null + && getKeyGenerator(crypto, kemName) != null + && getKeyPairGenerator(crypto, kemName) != null; + } + + private static X509EncodedKeySpec createX509EncodedKeySpec(ASN1ObjectIdentifier oid, byte[] encoding) + throws IOException + { + AlgorithmIdentifier algID = new AlgorithmIdentifier(oid); + SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algID, encoding); + return new X509EncodedKeySpec(spki.getEncoded(ASN1Encoding.DER)); + } + + private static ASN1ObjectIdentifier getAlgorithmOID(String kemName) + { + if ("ML-KEM-512".equalsIgnoreCase(kemName)) + { + return NISTObjectIdentifiers.id_alg_ml_kem_512; + } + if ("ML-KEM-768".equalsIgnoreCase(kemName)) + { + return NISTObjectIdentifiers.id_alg_ml_kem_768; + } + if ("ML-KEM-1024".equalsIgnoreCase(kemName)) + { + return NISTObjectIdentifiers.id_alg_ml_kem_1024; + } + + throw new IllegalArgumentException("unknown kem name " + kemName); + } +} diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/package-info.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/package-info.java new file mode 100644 index 0000000000..0fc50e0718 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/package-info.java @@ -0,0 +1,4 @@ +/** + * Service classes written to support the APIs using the JCA and the JCE. + */ +package org.bouncycastle.tls.crypto.impl.jcajce; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/SRP6Util.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/SRP6Util.java index 866b82ec93..0b4d52de0c 100644 --- a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/SRP6Util.java +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/SRP6Util.java @@ -8,7 +8,7 @@ class SRP6Util { - private static final byte[] colon = new byte[] { (byte)':' }; + private static final byte[] COLON = new byte[]{ (byte)':' }; private static BigInteger ZERO = BigInteger.valueOf(0); private static BigInteger ONE = BigInteger.valueOf(1); @@ -26,7 +26,7 @@ public static BigInteger calculateU(TlsHash digest, BigInteger N, BigInteger A, public static BigInteger calculateX(TlsHash digest, BigInteger N, byte[] salt, byte[] identity, byte[] password) { digest.update(identity, 0, identity.length); - digest.update(colon, 0, 1); + digest.update(COLON, 0, 1); digest.update(password, 0, password.length); byte[] output = digest.calculateHash(); diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/package-info.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/package-info.java new file mode 100644 index 0000000000..bd01a69b82 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/srp/package-info.java @@ -0,0 +1,4 @@ +/** + * Service classes written to support SRP-6a using the JCA and the JCE. + */ +package org.bouncycastle.tls.crypto.impl.jcajce.srp; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/impl/package-info.java b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/package-info.java new file mode 100644 index 0000000000..2dcdef8656 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/impl/package-info.java @@ -0,0 +1,4 @@ +/** + * Common classes used to support the JCA/JCE and BC light weight services. + */ +package org.bouncycastle.tls.crypto.impl; diff --git a/tls/src/main/java/org/bouncycastle/tls/crypto/package-info.java b/tls/src/main/java/org/bouncycastle/tls/crypto/package-info.java new file mode 100644 index 0000000000..13e0807532 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/crypto/package-info.java @@ -0,0 +1,4 @@ +/** + * Definitions for the cryptography service layer supporting the APIs. + */ +package org.bouncycastle.tls.crypto; diff --git a/tls/src/main/java/org/bouncycastle/tls/package-info.java b/tls/src/main/java/org/bouncycastle/tls/package-info.java new file mode 100644 index 0000000000..c1c2c894e2 --- /dev/null +++ b/tls/src/main/java/org/bouncycastle/tls/package-info.java @@ -0,0 +1,4 @@ +/** + * A low-level TLS/DTLS API. + */ +package org.bouncycastle.tls; diff --git a/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java b/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java index 99638a65f5..227a6d4c8b 100644 --- a/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java +++ b/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCertificate.java @@ -21,6 +21,7 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Certificate; +import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.tls.AlertDescription; @@ -132,7 +133,7 @@ public TlsEncryptor createEncryptor(int tlsCertificateRole) throws IOException // } } - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } public TlsVerifier createVerifier(short signatureAlgorithm) throws IOException @@ -182,8 +183,12 @@ public TlsVerifier createVerifier(short signatureAlgorithm) throws IOException return new JcaTlsRSAPSSVerifier(crypto, getPubKeyRSA(), signatureScheme); } + // TODO[RFC 9189] + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } } @@ -269,8 +274,12 @@ public Tls13Verifier createVerifier(int signatureScheme) throws IOException // TODO[RFC 8998] // case SignatureScheme.sm2sig_sm3: + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: + default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } } @@ -325,7 +334,7 @@ DHPublicKey getPubKeyDH() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not DH", e); } } @@ -337,7 +346,7 @@ DSAPublicKey getPubKeyDSS() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not DSS", e); } } @@ -349,7 +358,7 @@ ECPublicKey getPubKeyEC() throws IOException } catch (ClassCastException e) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not EC", e); } } @@ -361,7 +370,7 @@ PublicKey getPubKeyEd25519() throws IOException // Oracle provider (Java 15+) returns the key as an EdDSA one if (!("EdDSA".equals(publicKey.getAlgorithm()) && publicKey.toString().indexOf("Ed25519") >= 0)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not Ed25519"); } } return publicKey; @@ -375,7 +384,7 @@ PublicKey getPubKeyEd448() throws IOException // Oracle provider (Java 15+) returns the key as an EdDSA one if (!("EdDSA".equals(publicKey.getAlgorithm()) && publicKey.toString().indexOf("Ed448") >= 0)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "Public key not Ed448"); } } return publicKey; @@ -383,6 +392,7 @@ PublicKey getPubKeyEd448() throws IOException PublicKey getPubKeyRSA() throws IOException { + // TODO[tls] How to reliably check that this is an RSA key? return getPublicKey(); } @@ -466,7 +476,7 @@ public TlsCertificate checkUsageInRole(int tlsCertificateRole) throws IOExceptio } } - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.internal_error); } protected boolean implSupportsSignatureAlgorithm(short signatureAlgorithm) throws IOException @@ -506,6 +516,10 @@ protected boolean implSupportsSignatureAlgorithm(short signatureAlgorithm) throw return supportsRSA_PSS_PSS(signatureAlgorithm) && publicKey instanceof RSAPublicKey; + // TODO[RFC 9189] + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: return false; } @@ -566,7 +580,20 @@ protected void validateKeyUsageBit(int keyUsageBit) { if (!supportsKeyUsageBit(keyUsageBit)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + switch (keyUsageBit) + { + case KeyUsage.digitalSignature: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow digital signatures"); + case KeyUsage.keyAgreement: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow key agreement"); + case KeyUsage.keyEncipherment: + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "KeyUsage does not allow key encipherment"); + default: + throw new TlsFatalAlert(AlertDescription.internal_error); + } } } @@ -575,7 +602,7 @@ protected void validateRSA_PKCS1() { if (!supportsRSA_PKCS1()) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, "No support for rsa_pkcs1 signature schemes"); } } @@ -584,7 +611,8 @@ protected void validateRSA_PSS_PSS(short signatureAlgorithm) { if (!supportsRSA_PSS_PSS(signatureAlgorithm)) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "No support for rsa_pss_pss signature schemes"); } } @@ -593,7 +621,8 @@ protected void validateRSA_PSS_RSAE() { if (!supportsRSA_PSS_RSAE()) { - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + throw new TlsFatalAlert(AlertDescription.certificate_unknown, + "No support for rsa_pss_rsae signature schemes"); } } } diff --git a/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java b/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java index 637be94e92..255f9743c0 100644 --- a/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java +++ b/tls/src/main/jdk1.4/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java @@ -4,6 +4,7 @@ import java.math.BigInteger; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; +import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; @@ -57,6 +58,8 @@ import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.tls.crypto.TlsStreamSigner; import org.bouncycastle.tls.crypto.TlsStreamVerifier; +import org.bouncycastle.tls.crypto.impl.AEADNonceGenerator; +import org.bouncycastle.tls.crypto.impl.AEADNonceGeneratorFactory; import org.bouncycastle.tls.crypto.impl.AbstractTlsCrypto; import org.bouncycastle.tls.crypto.impl.TlsAEADCipher; import org.bouncycastle.tls.crypto.impl.TlsAEADCipherImpl; @@ -69,18 +72,20 @@ import org.bouncycastle.tls.crypto.impl.jcajce.srp.SRP6VerifierGenerator; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; +import org.bouncycastle.util.Strings; /** * Class for providing cryptographic services for TLS based on implementations in the JCA/JCE. *

      - * This class provides default implementations for everything. If you need to customise it, extend the class - * and override the appropriate methods. + * This class provides default implementations for everything. If you need to customise it, extend the class + * and override the appropriate methods. *

      */ public class JcaTlsCrypto extends AbstractTlsCrypto { private final JcaJceHelper helper; + private final JcaJceHelper altHelper; private final SecureRandom entropySource; private final SecureRandom nonceEntropySource; @@ -91,13 +96,28 @@ public class JcaTlsCrypto /** * Base constructor. * - * @param helper a JCA/JCE helper configured for the class's default provider. - * @param entropySource primary entropy source, used for key generation. + * @param helper a JCA/JCE helper configured for the class's default provider. + * @param entropySource primary entropy source, used for key generation. * @param nonceEntropySource secondary entropy source, used for nonce and IV generation. */ protected JcaTlsCrypto(JcaJceHelper helper, SecureRandom entropySource, SecureRandom nonceEntropySource) + { + this(helper, null, entropySource, nonceEntropySource); + } + + /** + * Base constructor. + * + * @param helper a JCA/JCE helper configured for the class's default provider. + * @param altHelper a JCA/JCE helper configured for the class's secondary provider (tried for private keys). + * @param entropySource primary entropy source, used for key generation. + * @param nonceEntropySource secondary entropy source, used for nonce and IV generation. + */ + protected JcaTlsCrypto(JcaJceHelper helper, JcaJceHelper altHelper, SecureRandom entropySource, + SecureRandom nonceEntropySource) { this.helper = helper; + this.altHelper = altHelper; this.entropySource = entropySource; this.nonceEntropySource = nonceEntropySource; } @@ -107,7 +127,8 @@ JceTlsSecret adoptLocalSecret(byte[] data) return new JceTlsSecret(this, data); } - Cipher createRSAEncryptionCipher() throws GeneralSecurityException + Cipher createRSAEncryptionCipher() + throws GeneralSecurityException { try { @@ -235,9 +256,12 @@ public TlsCipher createCipher(TlsCryptoParameters cryptoParams, int encryptionAl // NOTE: Ignores macAlgorithm return createCipher_SM4_GCM(cryptoParams); + case EncryptionAlgorithm._28147_CNT_IMIT: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.RC4_40: @@ -319,7 +343,7 @@ public TlsSRP6Client createSRP6Client(TlsSRPConfig srpConfig) final SRP6Client srpClient = new SRP6Client(); BigInteger[] ng = srpConfig.getExplicitNG(); - SRP6Group srpGroup= new SRP6Group(ng[0], ng[1]); + SRP6Group srpGroup = new SRP6Group(ng[0], ng[1]); srpClient.init(srpGroup, createHash(CryptoHashAlgorithm.sha1), this.getSecureRandom()); return new TlsSRP6Client() @@ -348,7 +372,7 @@ public TlsSRP6Server createSRP6Server(TlsSRPConfig srpConfig, BigInteger srpVeri { final SRP6Server srpServer = new SRP6Server(); BigInteger[] ng = srpConfig.getExplicitNG(); - SRP6Group srpGroup= new SRP6Group(ng[0], ng[1]); + SRP6Group srpGroup = new SRP6Group(ng[0], ng[1]); srpServer.init(srpGroup, srpVerifier, createHash(CryptoHashAlgorithm.sha1), this.getSecureRandom()); return new TlsSRP6Server() { @@ -406,12 +430,15 @@ String getHMACAlgorithmName(int cryptoHashAlgorithm) return "HmacSHA512"; case CryptoHashAlgorithm.sm3: return "HmacSM3"; + case CryptoHashAlgorithm.gostr3411_2012_256: + return "HmacGOST3411-2012-256"; default: throw new IllegalArgumentException("invalid CryptoHashAlgorithm: " + cryptoHashAlgorithm); } } - public AlgorithmParameters getNamedGroupAlgorithmParameters(int namedGroup) throws GeneralSecurityException + public AlgorithmParameters getNamedGroupAlgorithmParameters(int namedGroup) + throws GeneralSecurityException { if (NamedGroup.refersToAnXDHCurve(namedGroup)) { @@ -419,7 +446,7 @@ public AlgorithmParameters getNamedGroupAlgorithmParameters(int namedGroup) thro { /* * TODO Return AlgorithmParameters to check against disabled algorithms - * + * * NOTE: The JDK doesn't even support AlgorithmParameters for XDH, so SunJSSE also winds * up using null AlgorithmParameters when checking algorithm constraints. */ @@ -436,6 +463,15 @@ else if (NamedGroup.refersToASpecificFiniteField(namedGroup)) { return DHUtil.getAlgorithmParameters(this, TlsDHUtils.getNamedDHGroup(namedGroup)); } + else if (NamedGroup.refersToASpecificKem(namedGroup)) + { + /* + * TODO Return AlgorithmParameters to check against disabled algorithms? + * + * NOTE: See what the JDK/SunJSSE implementation does. + */ + return null; + } throw new IllegalArgumentException("NamedGroup not supported: " + NamedGroup.getText(namedGroup)); } @@ -538,7 +574,7 @@ public boolean hasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm) case CryptoSignatureAlgorithm.rsa_pss_pss_sha512: return true; - // TODO[draft-smyshlyaev-tls12-gost-suites-10] + // TODO[RFC 9189] case CryptoSignatureAlgorithm.gostr34102012_256: case CryptoSignatureAlgorithm.gostr34102012_512: @@ -560,11 +596,6 @@ public boolean hasECDHAgreement() return true; } - public boolean hasKemAgreement() - { - return true; - } - public boolean hasEncryptionAlgorithm(int encryptionAlgorithm) { final Integer key = Integers.valueOf(encryptionAlgorithm); @@ -613,6 +644,11 @@ public boolean hasHKDFAlgorithm(int cryptoHashAlgorithm) } } + public boolean hasKemAgreement() + { + return true; + } + public boolean hasMacAlgorithm(int macAlgorithm) { switch (macAlgorithm) @@ -720,11 +756,13 @@ public boolean hasSignatureAlgorithm(short signatureAlgorithm) case SignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512: return true; - // TODO[draft-smyshlyaev-tls12-gost-suites-10] + // TODO[RFC 9189] case SignatureAlgorithm.gostr34102012_256: case SignatureAlgorithm.gostr34102012_512: + // TODO[RFC 8998] // case SignatureAlgorithm.sm2: + default: return false; } @@ -751,12 +789,16 @@ public boolean hasSignatureScheme(int signatureScheme) switch (signatureScheme) { case SignatureScheme.sm2sig_sm3: + // TODO[tls] Implement before adding + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: return false; default: { short signature = SignatureScheme.getSignatureAlgorithm(signatureScheme); - switch(SignatureScheme.getCryptoHashAlgorithm(signatureScheme)) + switch (SignatureScheme.getCryptoHashAlgorithm(signatureScheme)) { case CryptoHashAlgorithm.md5: return SignatureAlgorithm.rsa == signature && hasSignatureAlgorithm(signature); @@ -775,6 +817,11 @@ public boolean hasSRPAuthentication() return true; } + public TlsSecret createHybridSecret(TlsSecret s1, TlsSecret s2) + { + return adoptLocalSecret(Arrays.concatenate(s1.extract(), s2.extract())); + } + public TlsSecret createSecret(byte[] data) { try @@ -833,7 +880,7 @@ public TlsKemDomain createKemDomain(TlsKemConfig kemConfig) { return new JceTlsMLKemDomain(this, kemConfig); } - + public TlsSecret hkdfInit(int cryptoHashAlgorithm) { return adoptLocalSecret(new byte[TlsCryptoUtils.getHashOutputSize(cryptoHashAlgorithm)]); @@ -866,8 +913,7 @@ protected TlsAEADCipherImpl createAEADCipher(String cipherName, String algorithm * @throws GeneralSecurityException in case of failure. */ protected TlsBlockCipherImpl createBlockCipher(String cipherName, String algorithm, int keySize, - boolean isEncrypting) - throws GeneralSecurityException + boolean isEncrypting) throws GeneralSecurityException { return new JceBlockCipherImpl(this, helper.createCipher(cipherName), algorithm, keySize, isEncrypting); } @@ -883,8 +929,7 @@ protected TlsBlockCipherImpl createBlockCipher(String cipherName, String algorit * @throws GeneralSecurityException in case of failure. */ protected TlsBlockCipherImpl createBlockCipherWithCBCImplicitIV(String cipherName, String algorithm, int keySize, - boolean isEncrypting) - throws GeneralSecurityException + boolean isEncrypting) throws GeneralSecurityException { return new JceBlockCipherWithCBCImplicitIVImpl(this, helper.createCipher(cipherName), algorithm, isEncrypting); } @@ -899,7 +944,7 @@ protected TlsBlockCipherImpl createBlockCipherWithCBCImplicitIV(String cipherNam protected TlsHash createHash(String digestName) throws GeneralSecurityException { - return new JcaTlsHash(helper.createMessageDigest(digestName)); + return new JcaTlsHash(helper.createDigest(digestName)); } /** @@ -907,7 +952,7 @@ protected TlsHash createHash(String digestName) * * @param macAlgorithm the name of the algorithm supporting the MAC. * @return a null cipher suite implementation. - * @throws IOException in case of failure. + * @throws IOException in case of failure. * @throws GeneralSecurityException in case of a specific failure in the JCA/JCE layer. */ protected TlsNullCipher createNullCipher(TlsCryptoParameters cryptoParams, int macAlgorithm) @@ -928,14 +973,59 @@ protected TlsStreamSigner createStreamSigner(SignatureAndHashAlgorithm algorithm protected TlsStreamSigner createStreamSigner(String algorithmName, AlgorithmParameterSpec parameter, PrivateKey privateKey, boolean needsRandom) throws IOException { + SecureRandom random = needsRandom ? getSecureRandom() : null; + try { - SecureRandom random = needsRandom ? getSecureRandom() : null; + try + { + return createStreamSigner(getHelper(), algorithmName, parameter, privateKey, random); + } + catch (InvalidKeyException e) + { + JcaJceHelper altHelper = getAltHelper(); + if (altHelper == null) + { + throw e; + } + + return createStreamSigner(altHelper, algorithmName, parameter, privateKey, random); + } + } + catch (GeneralSecurityException e) + { + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } + } - JcaJceHelper helper = getHelper(); + protected TlsStreamSigner createStreamSigner(JcaJceHelper helper, String algorithmName, + AlgorithmParameterSpec parameter, PrivateKey privateKey, SecureRandom random) throws GeneralSecurityException + { + try + { if (null != parameter) { - Signature dummySigner = helper.createSignature(algorithmName); + Signature dummySigner; + try + { + dummySigner = helper.createSignature(algorithmName); + } + catch (NoSuchAlgorithmException e) + { +// // more PKCS#11 mischief +// String upperAlg = Strings.toUpperCase(algorithmName); +// if (upperAlg.endsWith("ANDMGF1")) +// { +// // ANDMGF1 has vanished from the Sun PKCS11 provider. +// algorithmName = upperAlg.replace("ANDMGF1", "SSA-PSS"); +// dummySigner = helper.createSignature(algorithmName); +// } +// else +// { + throw e; +// } + } + dummySigner.initSign(privateKey, random); helper = new ProviderJcaJceHelper(dummySigner.getProvider()); } @@ -948,13 +1038,29 @@ protected TlsStreamSigner createStreamSigner(String algorithmName, AlgorithmPara signer.initSign(privateKey, random); return new JcaTlsStreamSigner(signer); } - catch (GeneralSecurityException e) + catch (InvalidKeyException e) { - throw new TlsFatalAlert(AlertDescription.internal_error, e); + // not a concern in 1.4 it's all over if we get here. +// String upperAlg = Strings.toUpperCase(algorithmName); +// if (upperAlg.endsWith("ANDMGF1")) +// { +// String upperAlg = Strings.toUpperCase(algorithmName); +// if (upperAlg.endsWith("MGF1")) +// { +// // ANDMGF1 has vanished from the Sun PKCS11 provider. +// algorithmName = upperAlg.replace("ANDMGF1", "SSA-PSS"); +// return createStreamSigner(algorithmName, parameter, privateKey, needsRandom); +// } +// else +// { + throw e; +// } +// } } } - protected TlsStreamVerifier createStreamVerifier(DigitallySigned digitallySigned, PublicKey publicKey) throws IOException + protected TlsStreamVerifier createStreamVerifier(DigitallySigned digitallySigned, PublicKey publicKey) + throws IOException { String algorithmName = JcaUtils.getJcaAlgorithmName(digitallySigned.getAlgorithm()); @@ -1015,39 +1121,6 @@ protected Tls13Verifier createTls13Verifier(String algorithmName, AlgorithmParam } } - protected TlsStreamSigner createVerifyingStreamSigner(SignatureAndHashAlgorithm algorithm, PrivateKey privateKey, - boolean needsRandom, PublicKey publicKey) throws IOException - { - String algorithmName = JcaUtils.getJcaAlgorithmName(algorithm); - - return createVerifyingStreamSigner(algorithmName, null, privateKey, needsRandom, publicKey); - } - - protected TlsStreamSigner createVerifyingStreamSigner(String algorithmName, AlgorithmParameterSpec parameter, - PrivateKey privateKey, boolean needsRandom, PublicKey publicKey) throws IOException - { - try - { - Signature signer = getHelper().createSignature(algorithmName); - Signature verifier = getHelper().createSignature(algorithmName); - - if (null != parameter) - { - signer.setParameter(parameter); - verifier.setParameter(parameter); - } - - signer.initSign(privateKey, needsRandom ? getSecureRandom() : null); - verifier.initVerify(publicKey); - - return new JcaVerifyingStreamSigner(signer, verifier); - } - catch (GeneralSecurityException e) - { - throw new TlsFatalAlert(AlertDescription.internal_error, e); - } - } - protected Boolean isSupportedEncryptionAlgorithm(int encryptionAlgorithm) { switch (encryptionAlgorithm) @@ -1097,9 +1170,12 @@ protected Boolean isSupportedEncryptionAlgorithm(int encryptionAlgorithm) case EncryptionAlgorithm.SM4_GCM: return Boolean.valueOf(isUsableCipher("SM4/GCM/NoPadding", 128)); + case EncryptionAlgorithm._28147_CNT_IMIT: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.KUZNYECHIK_CTR_OMAC: + case EncryptionAlgorithm.MAGMA_CTR_OMAC: case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.RC4_40: @@ -1140,6 +1216,10 @@ protected Boolean isSupportedNamedGroup(int namedGroup) } } } + else if (NamedGroup.refersToASpecificKem(namedGroup)) + { + return Boolean.valueOf(KemUtil.isKemSupported(this, NamedGroup.getKemName(namedGroup))); + } else if (NamedGroup.refersToAnECDSACurve(namedGroup)) { return Boolean.valueOf(ECUtil.isCurveSupported(this, NamedGroup.getCurveName(namedGroup))); @@ -1191,6 +1271,11 @@ public JcaJceHelper getHelper() return helper; } + public JcaJceHelper getAltHelper() + { + return altHelper; + } + protected TlsBlockCipherImpl createCBCBlockCipherImpl(TlsCryptoParameters cryptoParams, String algorithm, int cipherKeySize, boolean forEncryption) throws GeneralSecurityException { @@ -1210,7 +1295,7 @@ private TlsCipher createChaCha20Poly1305(TlsCryptoParameters cryptoParams) throws IOException, GeneralSecurityException { return new TlsAEADCipher(cryptoParams, new JceChaCha20Poly1305(this, helper, true), - new JceChaCha20Poly1305(this, helper, false), 32, 16, TlsAEADCipher.AEAD_CHACHA20_POLY1305); + new JceChaCha20Poly1305(this, helper, false), 32, 16, TlsAEADCipher.AEAD_CHACHA20_POLY1305, null); } private TlsAEADCipher createCipher_AES_CCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1218,7 +1303,7 @@ private TlsAEADCipher createCipher_AES_CCM(TlsCryptoParameters cryptoParams, int { return new TlsAEADCipher(cryptoParams, createAEADCipher("AES/CCM/NoPadding", "AES", cipherKeySize, true), createAEADCipher("AES/CCM/NoPadding", "AES", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_CCM); + TlsAEADCipher.AEAD_CCM, null); } private TlsAEADCipher createCipher_AES_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1226,7 +1311,7 @@ private TlsAEADCipher createCipher_AES_GCM(TlsCryptoParameters cryptoParams, int { return new TlsAEADCipher(cryptoParams, createAEADCipher("AES/GCM/NoPadding", "AES", cipherKeySize, true), createAEADCipher("AES/GCM/NoPadding", "AES", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); } private TlsAEADCipher createCipher_ARIA_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1234,7 +1319,7 @@ private TlsAEADCipher createCipher_ARIA_GCM(TlsCryptoParameters cryptoParams, in { return new TlsAEADCipher(cryptoParams, createAEADCipher("ARIA/GCM/NoPadding", "ARIA", cipherKeySize, true), createAEADCipher("ARIA/GCM/NoPadding", "ARIA", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); } private TlsAEADCipher createCipher_Camellia_GCM(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) @@ -1243,7 +1328,7 @@ private TlsAEADCipher createCipher_Camellia_GCM(TlsCryptoParameters cryptoParams return new TlsAEADCipher(cryptoParams, createAEADCipher("Camellia/GCM/NoPadding", "Camellia", cipherKeySize, true), createAEADCipher("Camellia/GCM/NoPadding", "Camellia", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); } protected TlsCipher createCipher_CBC(TlsCryptoParameters cryptoParams, String algorithm, int cipherKeySize, @@ -1264,7 +1349,7 @@ private TlsAEADCipher createCipher_SM4_CCM(TlsCryptoParameters cryptoParams) int cipherKeySize = 16, macSize = 16; return new TlsAEADCipher(cryptoParams, createAEADCipher("SM4/CCM/NoPadding", "SM4", cipherKeySize, true), createAEADCipher("SM4/CCM/NoPadding", "SM4", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_CCM); + TlsAEADCipher.AEAD_CCM, null); } private TlsAEADCipher createCipher_SM4_GCM(TlsCryptoParameters cryptoParams) @@ -1273,7 +1358,27 @@ private TlsAEADCipher createCipher_SM4_GCM(TlsCryptoParameters cryptoParams) int cipherKeySize = 16, macSize = 16; return new TlsAEADCipher(cryptoParams, createAEADCipher("SM4/GCM/NoPadding", "SM4", cipherKeySize, true), createAEADCipher("SM4/GCM/NoPadding", "SM4", cipherKeySize, false), cipherKeySize, macSize, - TlsAEADCipher.AEAD_GCM); + TlsAEADCipher.AEAD_GCM, getFipsGCMNonceGeneratorFactory()); + } + + /** + * Optionally return an {@link AEADNonceGeneratorFactory} that creates {@link AEADNonceGenerator} + * instances suitable for generating TLS 1.2 GCM nonces in a FIPS approved way (or null). It is not needed + * or intended to be used in a non-FIPS context. + *

      + * Clients of this {@link JcaTlsCrypto} instance MAY assume from a non-null return value that the + * resulting {@link AEADNonceGenerator} implementation(s) are FIPS compliant; implementations that violate + * this assumption risk FIPS compliance failures. + *

      + * In particular, when BCJSSE is configured in FIPS mode, GCM cipher suites are enabled for TLS 1.2 if + * (and only if) a call to this method returns a non-null value. This can be achieved by configuring + * BCJSSE with a user-defined {@link JcaTlsCryptoProvider} subclass, which in turn creates instances of a + * {@link JcaTlsCrypto} subclass, with this method overridden to return a suitable + * {@link AEADNonceGeneratorFactory}. + */ + public AEADNonceGeneratorFactory getFipsGCMNonceGeneratorFactory() + { + return GCMFipsUtil.getDefaultFipsGCMNonceGeneratorFactory(); } String getDigestName(int cryptoHashAlgorithm) @@ -1294,6 +1399,8 @@ String getDigestName(int cryptoHashAlgorithm) return "SHA-512"; case CryptoHashAlgorithm.sm3: return "SM3"; + case CryptoHashAlgorithm.gostr3411_2012_256: + return "GOST3411-2012-256"; default: throw new IllegalArgumentException("invalid CryptoHashAlgorithm: " + cryptoHashAlgorithm); } diff --git a/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/SSLParametersUtil.java b/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/SSLParametersUtil.java index c58183f2e5..39d5abfa89 100644 --- a/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/SSLParametersUtil.java +++ b/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/SSLParametersUtil.java @@ -79,10 +79,12 @@ static BCSSLParameters getParameters(ProvSSLParameters prov) ssl.setServerNames(prov.getServerNames()); ssl.setSNIMatchers(prov.getSNIMatchers()); ssl.setUseCipherSuitesOrder(prov.getUseCipherSuitesOrder()); + ssl.setUseNamedGroupsOrder(prov.getUseNamedGroupsOrder()); ssl.setApplicationProtocols(prov.getApplicationProtocols()); ssl.setEnableRetransmissions(prov.getEnableRetransmissions()); ssl.setMaximumPacketSize(prov.getMaximumPacketSize()); ssl.setSignatureSchemes(prov.getSignatureSchemes()); + ssl.setSignatureSchemesCert(prov.getSignatureSchemesCert()); ssl.setNamedGroups(prov.getNamedGroups()); return ssl; @@ -177,6 +179,18 @@ static SSLParameters getSSLParameters(ProvSSLParameters prov) set(ssl, setNamedGroups, prov.getNamedGroups()); } + // Unsupported as of JDK 21 + +// if (null != setUseNamedGroupsOrder) +// { +// set(ssl, setUseNamedGroupsOrder, prov.getUseNamedGroupsOrder()); +// } + +// if (null != setSignatureSchemesCert) +// { +// set(ssl, setSignatureSchemesCert, prov.getSignatureSchemesCert()); +// } + return ssl; } @@ -276,6 +290,18 @@ static BCSSLParameters importSSLParameters(SSLParameters ssl) bc.setNamedGroups((String[])get(ssl, getNamedGroups)); } + // Unsupported as of JDK 21 + +// if (null != getUseNamedGroupsOrder) +// { +// bc.setUseNamedGroupsOrder((Boolean)get(ssl, getUseNamedGroupsOrder)); +// } + +// if (null != getSignatureSchemesCert) +// { +// bc.setSignatureSchemesCert((String[])get(ssl, getSignatureSchemesCert)); +// } + return bc; } @@ -329,6 +355,8 @@ static void setParameters(ProvSSLParameters prov, BCSSLParameters ssl) prov.setUseCipherSuitesOrder(ssl.getUseCipherSuitesOrder()); + prov.setUseNamedGroupsOrder(ssl.getUseNamedGroupsOrder()); + String[] applicationProtocols = ssl.getApplicationProtocols(); if (null != applicationProtocols) { @@ -342,6 +370,8 @@ static void setParameters(ProvSSLParameters prov, BCSSLParameters ssl) prov.setSignatureSchemes(ssl.getSignatureSchemes()); prov.setNamedGroups(ssl.getNamedGroups()); + + prov.setSignatureSchemesCert(ssl.getSignatureSchemesCert()); } static void setSSLParameters(ProvSSLParameters prov, SSLParameters ssl) @@ -449,6 +479,18 @@ static void setSSLParameters(ProvSSLParameters prov, SSLParameters ssl) { prov.setNamedGroups((String[])get(ssl, getNamedGroups)); } + + // Unsupported as of JDK 21 + +// if (null != getUseNamedGroupsOrder) +// { +// prov.setUseNamedGroupsOrder((Boolean)get(ssl, getUseNamedGroupsOrder)); +// } + +// if (null != getSignatureSchemesCert) +// { +// prov.setSignatureSchemesCert((String[])get(ssl, getSignatureSchemesCert)); +// } } private static Object get(Object obj, Method method) diff --git a/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java b/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java index 59177e11ac..2f8bdca961 100644 --- a/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java +++ b/tls/src/main/jdk1.5/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java @@ -88,7 +88,7 @@ static X509TrustManager exportX509TrustManager(BCX509ExtendedTrustManager x509Tr return new ExportX509TrustManager_5(x509TrustManager); } - static BCX509ExtendedTrustManager importX509TrustManager(boolean isInFipsMode, JcaJceHelper helper, + static BCX509ExtendedTrustManager importX509TrustManager(boolean fipsMode, JcaJceHelper helper, X509TrustManager x509TrustManager) { LOG.fine("Importing X509TrustManager implementation: " + x509TrustManager.getClass().getName()); @@ -114,6 +114,6 @@ static BCX509ExtendedTrustManager importX509TrustManager(boolean isInFipsMode, J } } - return new ImportX509TrustManager_5(isInFipsMode, helper, x509TrustManager); + return new ImportX509TrustManager_5(fipsMode, helper, x509TrustManager); } } diff --git a/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/SSLParametersUtil.java b/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/SSLParametersUtil.java index f33f3b4e39..e6da475798 100644 --- a/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/SSLParametersUtil.java +++ b/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/SSLParametersUtil.java @@ -50,10 +50,12 @@ static BCSSLParameters getParameters(ProvSSLParameters prov) ssl.setServerNames(prov.getServerNames()); ssl.setSNIMatchers(prov.getSNIMatchers()); ssl.setUseCipherSuitesOrder(prov.getUseCipherSuitesOrder()); + ssl.setUseNamedGroupsOrder(prov.getUseNamedGroupsOrder()); ssl.setApplicationProtocols(prov.getApplicationProtocols()); ssl.setEnableRetransmissions(prov.getEnableRetransmissions()); ssl.setMaximumPacketSize(prov.getMaximumPacketSize()); ssl.setSignatureSchemes(prov.getSignatureSchemes()); + ssl.setSignatureSchemesCert(prov.getSignatureSchemesCert()); ssl.setNamedGroups(prov.getNamedGroups()); return ssl; @@ -129,6 +131,18 @@ static SSLParameters getSSLParameters(ProvSSLParameters prov) set(ssl, setNamedGroups, prov.getNamedGroups()); } + // Unsupported as of JDK 21 + +// if (null != setUseNamedGroupsOrder) +// { +// set(ssl, setUseNamedGroupsOrder, prov.getUseNamedGroupsOrder()); +// } + +// if (null != setSignatureSchemesCert) +// { +// set(ssl, setSignatureSchemesCert, prov.getSignatureSchemesCert()); +// } + return ssl; } @@ -214,6 +228,18 @@ static BCSSLParameters importSSLParameters(SSLParameters ssl) bc.setNamedGroups((String[])get(ssl, getNamedGroups)); } + // Unsupported as of JDK 21 + +// if (null != getUseNamedGroupsOrder) +// { +// bc.setUseNamedGroupsOrder((Boolean)get(ssl, getUseNamedGroupsOrder)); +// } + +// if (null != getSignatureSchemesCert) +// { +// bc.setSignatureSchemesCert((String[])get(ssl, getSignatureSchemesCert)); +// } + return bc; } @@ -267,6 +293,8 @@ static void setParameters(ProvSSLParameters prov, BCSSLParameters ssl) prov.setUseCipherSuitesOrder(ssl.getUseCipherSuitesOrder()); + prov.setUseNamedGroupsOrder(ssl.getUseNamedGroupsOrder()); + String[] applicationProtocols = ssl.getApplicationProtocols(); if (null != applicationProtocols) { @@ -280,6 +308,8 @@ static void setParameters(ProvSSLParameters prov, BCSSLParameters ssl) prov.setSignatureSchemes(ssl.getSignatureSchemes()); prov.setNamedGroups(ssl.getNamedGroups()); + + prov.setSignatureSchemesCert(ssl.getSignatureSchemesCert()); } static void setSSLParameters(ProvSSLParameters prov, SSLParameters ssl) @@ -373,6 +403,18 @@ static void setSSLParameters(ProvSSLParameters prov, SSLParameters ssl) { prov.setNamedGroups((String[])get(ssl, getNamedGroups)); } + + // Unsupported as of JDK 21 + +// if (null != getUseNamedGroupsOrder) +// { +// prov.setUseNamedGroupsOrder((Boolean)get(ssl, getUseNamedGroupsOrder)); +// } + +// if (null != getSignatureSchemesCert) +// { +// prov.setSignatureSchemesCert((String[])get(ssl, getSignatureSchemesCert)); +// } } private static Object get(Object obj, Method method) diff --git a/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java b/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java index ffa574c89c..571312dc16 100644 --- a/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java +++ b/tls/src/main/jdk1.9/org/bouncycastle/jsse/provider/X509TrustManagerUtil.java @@ -22,7 +22,8 @@ static X509TrustManager exportX509TrustManager(BCX509ExtendedTrustManager x509Tr return new ExportX509TrustManager_7(x509TrustManager); } - static BCX509ExtendedTrustManager importX509TrustManager(boolean isInFipsMode, JcaJceHelper helper, X509TrustManager x509TrustManager) + static BCX509ExtendedTrustManager importX509TrustManager(boolean fipsMode, JcaJceHelper helper, + X509TrustManager x509TrustManager) { LOG.fine("Importing X509TrustManager implementation: " + x509TrustManager.getClass().getName()); @@ -41,6 +42,6 @@ static BCX509ExtendedTrustManager importX509TrustManager(boolean isInFipsMode, J return new ImportX509TrustManager_7((X509ExtendedTrustManager)x509TrustManager); } - return new ImportX509TrustManager_5(isInFipsMode, helper, x509TrustManager); + return new ImportX509TrustManager_5(fipsMode, helper, x509TrustManager); } } diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/BasicTlsTest.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/BasicTlsTest.java index 03f5bf58a7..94e140721d 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/BasicTlsTest.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/BasicTlsTest.java @@ -24,7 +24,7 @@ public class BasicTlsTest protected void setUp() { ProviderUtils.setupLowPriority(false); -// System.setProperty("jdk.tls.namedGroups", "kyber768"); +// System.setProperty("jdk.tls.namedGroups", "MLKEM768"); } private static final String HOST = "localhost"; diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestCase.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestCase.java index 528d8d8141..458d0dd109 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestCase.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestCase.java @@ -44,14 +44,6 @@ public CipherSuitesEngineTestCase(CipherSuitesTestConfig config) this.config = config; } - protected void setUp() - { - if (config != null) - { - ProviderUtils.setupHighPriority(config.fips); - } - } - public void testDummy() { // Avoid "No tests found" warning from junit diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestSuite.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestSuite.java index 5026e01a17..e67985c24b 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestSuite.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesEngineTestSuite.java @@ -9,6 +9,7 @@ import org.junit.Assert; +import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; @@ -23,7 +24,9 @@ public CipherSuitesEngineTestSuite() public static Test suite() throws Exception { - return createSuite(new CipherSuitesEngineTestSuite(), null, false, new CipherSuitesFilter() + ProviderUtils.setupHighPriority(false); + + TestSuite suite = createSuite(new CipherSuitesEngineTestSuite(), null, false, new CipherSuitesFilter() { public boolean isIgnored(String cipherSuite) { @@ -40,14 +43,20 @@ public boolean isPermitted(String cipherSuite) return true; } }); + + return new TestSetup(suite) + { + @Override + protected void setUp() throws Exception + { + ProviderUtils.setupHighPriority(false); + } + }; } - static Test createSuite(TestSuite testSuite, String category, boolean fips, CipherSuitesFilter filter) + static TestSuite createSuite(TestSuite testSuite, String category, boolean fips, CipherSuitesFilter filter) throws Exception { - // TODO Consider configuring BCJSSE with explicit crypto provider (maybe only when in fips mode?) - ProviderUtils.setupHighPriority(fips); - char[] serverPassword = "serverPassword".toCharArray(); KeyPair caKeyPairDSA = TestUtils.generateDSAKeyPair(); @@ -126,7 +135,6 @@ static Test createSuite(TestSuite testSuite, String category, boolean fips, Ciph config.category = category; config.cipherSuite = cipherSuite; config.clientTrustStore = ts; - config.fips = fips; config.protocol = protocol; config.serverKeyStore = ks; config.serverPassword = serverPassword; diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestCase.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestCase.java index 61d1badd58..8fc7ec87e0 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestCase.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestCase.java @@ -47,14 +47,6 @@ public CipherSuitesTestCase(CipherSuitesTestConfig config) this.config = config; } - protected void setUp() - { - if (config != null) - { - ProviderUtils.setupHighPriority(config.fips); - } - } - public void testDummy() { // Avoid "No tests found" warning from junit diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestConfig.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestConfig.java index 6d15796bcd..19843b32e9 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestConfig.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestConfig.java @@ -7,7 +7,6 @@ public class CipherSuitesTestConfig public String category = null; public String cipherSuite = null; public KeyStore clientTrustStore = null; - public boolean fips = false; public String protocol = null; public KeyStore serverKeyStore = null; public char[] serverPassword = null; diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestSuite.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestSuite.java index 4c38503051..a9393f884b 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestSuite.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/CipherSuitesTestSuite.java @@ -7,6 +7,7 @@ import javax.net.ssl.SSLContext; +import junit.extensions.TestSetup; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestSuite; @@ -22,7 +23,9 @@ public CipherSuitesTestSuite() public static Test suite() throws Exception { - return createSuite(new CipherSuitesTestSuite(), null, false, new CipherSuitesFilter() + ProviderUtils.setupHighPriority(false); + + TestSuite suite = createSuite(new CipherSuitesTestSuite(), null, false, new CipherSuitesFilter() { public boolean isIgnored(String cipherSuite) { @@ -39,14 +42,20 @@ public boolean isPermitted(String cipherSuite) return true; } }); + + return new TestSetup(suite) + { + @Override + protected void setUp() throws Exception + { + ProviderUtils.setupHighPriority(false); + } + }; } - static Test createSuite(TestSuite testSuite, String category, boolean fips, CipherSuitesFilter filter) + static TestSuite createSuite(TestSuite testSuite, String category, boolean fips, CipherSuitesFilter filter) throws Exception { - // TODO Consider configuring BCJSSE with explicit crypto provider (maybe only when in fips mode?) - ProviderUtils.setupHighPriority(fips); - char[] serverPassword = "serverPassword".toCharArray(); KeyPair caKeyPairDSA = TestUtils.generateDSAKeyPair(); @@ -125,7 +134,6 @@ static Test createSuite(TestSuite testSuite, String category, boolean fips, Ciph config.category = category; config.cipherSuite = cipherSuite; config.clientTrustStore = ts; - config.fips = fips; config.protocol = protocol; config.serverKeyStore = ks; config.serverPassword = serverPassword; diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/ECDSACredentialsTest.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/ECDSACredentialsTest.java index 912bbb5068..0babed3829 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/ECDSACredentialsTest.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/ECDSACredentialsTest.java @@ -126,10 +126,10 @@ private void implTestECDSACredentials(int port, String protocol, int namedGroup) X509Certificate caCert = TestUtils.generateRootCert(caKeyPair); KeyStore serverKs = createKeyStore(); - serverKs.setKeyEntry("server", caKeyPair.getPrivate(), keyPass, new X509Certificate[] { caCert }); + serverKs.setKeyEntry("server", caKeyPair.getPrivate(), keyPass, new X509Certificate[]{ caCert }); KeyStore clientKs = createKeyStore(); - clientKs.setKeyEntry("client", caKeyPair.getPrivate(), keyPass, new X509Certificate[] { caCert }); + clientKs.setKeyEntry("client", caKeyPair.getPrivate(), keyPass, new X509Certificate[]{ caCert }); TestProtocolUtil.runClientAndServer(new ECDSAServer(port, protocol, serverKs, keyPass, caCert), new ECDSAClient(port, protocol, clientKs, keyPass, caCert)); diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/EdDSACredentialsTest.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/EdDSACredentialsTest.java index a5bb4a4281..8e4c265257 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/EdDSACredentialsTest.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/EdDSACredentialsTest.java @@ -28,10 +28,10 @@ protected void setUp() } private static final String HOST = "localhost"; - private static final int PORT_NO_12_ED25519 = 9020; - private static final int PORT_NO_12_ED448 = 9021; - private static final int PORT_NO_13_ED25519 = 9022; - private static final int PORT_NO_13_ED448 = 9023; + private static final int PORT_NO_12_ED25519 = 9050; + private static final int PORT_NO_12_ED448 = 9051; + private static final int PORT_NO_13_ED25519 = 9052; + private static final int PORT_NO_13_ED448 = 9053; static class EdDSAClient implements TestProtocolUtil.BlockingCallable diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesEngineTestSuite.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesEngineTestSuite.java index 251a829fab..dc623dfd61 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesEngineTestSuite.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesEngineTestSuite.java @@ -1,5 +1,6 @@ package org.bouncycastle.jsse.provider.test; +import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; @@ -14,7 +15,10 @@ public FipsCipherSuitesEngineTestSuite() public static Test suite() throws Exception { - return CipherSuitesEngineTestSuite.createSuite(new FipsCipherSuitesEngineTestSuite(), "FIPS", true, new CipherSuitesFilter() + FipsTestUtils.setupFipsSuite(); + + TestSuite suite = CipherSuitesEngineTestSuite.createSuite(new FipsCipherSuitesEngineTestSuite(), "FIPS", true, + new CipherSuitesFilter() { public boolean isIgnored(String cipherSuite) { @@ -23,8 +27,25 @@ public boolean isIgnored(String cipherSuite) public boolean isPermitted(String cipherSuite) { - return FipsCipherSuitesTestSuite.isFipsSupportedCipherSuite(cipherSuite); + return FipsTestUtils.isFipsCipherSuite(cipherSuite); } }); + + FipsTestUtils.teardownFipsSuite(); + + return new TestSetup(suite) + { + @Override + protected void setUp() throws Exception + { + FipsTestUtils.setupFipsSuite(); + } + + @Override + protected void tearDown() throws Exception + { + FipsTestUtils.teardownFipsSuite(); + } + }; } } diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesTestSuite.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesTestSuite.java index 9988443e5d..830bd6c10b 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesTestSuite.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsCipherSuitesTestSuite.java @@ -1,138 +1,12 @@ package org.bouncycastle.jsse.provider.test; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - +import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; public class FipsCipherSuitesTestSuite extends TestSuite { - private static final boolean provAllowGCMCiphersIn12 = false; - private static final boolean provAllowRSAKeyExchange = true; - - private static final Set FIPS_SUPPORTED_CIPHERSUITES = createFipsSupportedCipherSuites(); - - private static Set createFipsSupportedCipherSuites() - { - /* - * Cipher suite list current as of NIST SP 800-52 Revision 2. - * - * Static (EC)DH cipher suites commented out since not supported by BCJSSE. - * - * PSK cipher suites from Appendix C left out completely since the BCJSSE provider does not - * currently support _any_ PSK key exchange methods. - */ - final Set cs = new HashSet(); - - cs.add("TLS_AES_128_CCM_8_SHA256"); - cs.add("TLS_AES_128_CCM_SHA256"); - cs.add("TLS_AES_128_GCM_SHA256"); - cs.add("TLS_AES_256_GCM_SHA384"); - -// cs.add("TLS_DH_DSS_WITH_AES_128_CBC_SHA"); -// cs.add("TLS_DH_DSS_WITH_AES_128_CBC_SHA256"); -// cs.add("TLS_DH_DSS_WITH_AES_256_CBC_SHA"); -// cs.add("TLS_DH_DSS_WITH_AES_256_CBC_SHA256"); - -// cs.add("TLS_DH_RSA_WITH_AES_128_CBC_SHA"); -// cs.add("TLS_DH_RSA_WITH_AES_128_CBC_SHA256"); -// cs.add("TLS_DH_RSA_WITH_AES_256_CBC_SHA"); -// cs.add("TLS_DH_RSA_WITH_AES_256_CBC_SHA256"); - - cs.add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA"); - cs.add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"); - cs.add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA"); - cs.add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"); - - cs.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"); - cs.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"); - cs.add("TLS_DHE_RSA_WITH_AES_128_CCM"); - cs.add("TLS_DHE_RSA_WITH_AES_128_CCM_8"); - cs.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"); - cs.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"); - cs.add("TLS_DHE_RSA_WITH_AES_256_CCM"); - cs.add("TLS_DHE_RSA_WITH_AES_256_CCM_8"); - -// cs.add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"); -// cs.add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"); -// cs.add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"); -// cs.add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"); - -// cs.add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"); -// cs.add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"); -// cs.add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"); -// cs.add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"); - - cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CCM"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CCM"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"); - - cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"); - cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"); - cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"); - cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"); - - if (provAllowGCMCiphersIn12) - { -// cs.add("TLS_DH_DSS_WITH_AES_128_GCM_SHA256"); -// cs.add("TLS_DH_DSS_WITH_AES_256_GCM_SHA384"); - -// cs.add("TLS_DH_RSA_WITH_AES_128_GCM_SHA256"); -// cs.add("TLS_DH_RSA_WITH_AES_256_GCM_SHA384"); - - cs.add("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"); - cs.add("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"); - - cs.add("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"); - cs.add("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"); - -// cs.add("TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"); -// cs.add("TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"); - -// cs.add("TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"); -// cs.add("TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"); - - cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); - cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"); - - cs.add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); - cs.add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"); - } - - if (provAllowRSAKeyExchange) - { - cs.add("TLS_RSA_WITH_AES_128_CBC_SHA"); - cs.add("TLS_RSA_WITH_AES_128_CBC_SHA256"); - cs.add("TLS_RSA_WITH_AES_128_CCM"); - cs.add("TLS_RSA_WITH_AES_128_CCM_8"); - cs.add("TLS_RSA_WITH_AES_256_CBC_SHA"); - cs.add("TLS_RSA_WITH_AES_256_CBC_SHA256"); - cs.add("TLS_RSA_WITH_AES_256_CCM"); - cs.add("TLS_RSA_WITH_AES_256_CCM_8"); - - if (provAllowGCMCiphersIn12) - { - cs.add("TLS_RSA_WITH_AES_128_GCM_SHA256"); - cs.add("TLS_RSA_WITH_AES_256_GCM_SHA384"); - } - } - - return Collections.unmodifiableSet(cs); - } - - static boolean isFipsSupportedCipherSuite(String cipherSuite) - { - return FIPS_SUPPORTED_CIPHERSUITES.contains(cipherSuite); - } - public FipsCipherSuitesTestSuite() { super("FIPS CipherSuites"); @@ -141,7 +15,10 @@ public FipsCipherSuitesTestSuite() public static Test suite() throws Exception { - return CipherSuitesTestSuite.createSuite(new FipsCipherSuitesTestSuite(), "FIPS", true, new CipherSuitesFilter() + FipsTestUtils.setupFipsSuite(); + + TestSuite suite = CipherSuitesTestSuite.createSuite(new FipsCipherSuitesTestSuite(), "FIPS", true, + new CipherSuitesFilter() { public boolean isIgnored(String cipherSuite) { @@ -150,8 +27,25 @@ public boolean isIgnored(String cipherSuite) public boolean isPermitted(String cipherSuite) { - return isFipsSupportedCipherSuite(cipherSuite); + return FipsTestUtils.isFipsCipherSuite(cipherSuite); } }); + + FipsTestUtils.teardownFipsSuite(); + + return new TestSetup(suite) + { + @Override + protected void setUp() throws Exception + { + FipsTestUtils.setupFipsSuite(); + } + + @Override + protected void tearDown() throws Exception + { + FipsTestUtils.teardownFipsSuite(); + } + }; } } diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsJcaTlsCrypto.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsJcaTlsCrypto.java new file mode 100644 index 0000000000..a7b1a4fef4 --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsJcaTlsCrypto.java @@ -0,0 +1,28 @@ +package org.bouncycastle.jsse.provider.test; + +import java.security.SecureRandom; + +import org.bouncycastle.jcajce.util.JcaJceHelper; +import org.bouncycastle.tls.crypto.impl.AEADNonceGeneratorFactory; +import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto; +import org.bouncycastle.tls.test.TestAEADGeneratorFactory; + +public class FipsJcaTlsCrypto extends JcaTlsCrypto +{ + public FipsJcaTlsCrypto(JcaJceHelper helper, SecureRandom entropySource, SecureRandom nonceEntropySource) + { + super(helper, entropySource, nonceEntropySource); + } + + public FipsJcaTlsCrypto(JcaJceHelper helper, JcaJceHelper altHelper, SecureRandom entropySource, + SecureRandom nonceEntropySource) + { + super(helper, altHelper, entropySource, nonceEntropySource); + } + + @Override + public AEADNonceGeneratorFactory getFipsGCMNonceGeneratorFactory() + { + return FipsTestUtils.enableGCMCiphersIn12 ? TestAEADGeneratorFactory.INSTANCE : null; + } +} diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsJcaTlsCryptoProvider.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsJcaTlsCryptoProvider.java new file mode 100644 index 0000000000..4781f119db --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsJcaTlsCryptoProvider.java @@ -0,0 +1,15 @@ +package org.bouncycastle.jsse.provider.test; + +import java.security.SecureRandom; + +import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto; +import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider; + +public class FipsJcaTlsCryptoProvider extends JcaTlsCryptoProvider +{ + @Override + public JcaTlsCrypto create(SecureRandom keyRandom, SecureRandom nonceRandom) + { + return new FipsJcaTlsCrypto(getHelper(), getAltHelper(), keyRandom, nonceRandom); + } +} diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsTestUtils.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsTestUtils.java new file mode 100644 index 0000000000..8953788a6d --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/FipsTestUtils.java @@ -0,0 +1,175 @@ +package org.bouncycastle.jsse.provider.test; + +import java.security.Provider; +import java.security.Security; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +abstract class FipsTestUtils +{ + /** + * In FIPS mode, GCM cipher suites (for TLS 1.2) are enabled if and only if the JcaTlsCrypto instance + * returns a non-null value from getFipsGCMNonceGeneratorFactory. This flag allows to enable/disable that + * support for the FIPS tests in this package. + */ + static final boolean enableGCMCiphersIn12 = true; + + static final boolean provAllowRSAKeyExchange = + "true".equalsIgnoreCase(System.getProperty("org.bouncycastle.jsse.fips.allowRSAKeyExchange")); + + private static final Set FIPS_CIPHERSUITES = createFipsCipherSuites(enableGCMCiphersIn12); + + private static Set createFipsCipherSuites(boolean includeGCM12) + { + /* + * Cipher suite list current as of NIST SP 800-52 Revision 2. + * + * Static (EC)DH cipher suites commented out since not supported by BCJSSE. + * + * PSK cipher suites from Appendix C left out completely since the BCJSSE provider does not + * currently support _any_ PSK key exchange methods. + */ + final Set cs = new HashSet(); + + cs.add("TLS_AES_128_CCM_8_SHA256"); + cs.add("TLS_AES_128_CCM_SHA256"); + cs.add("TLS_AES_128_GCM_SHA256"); + cs.add("TLS_AES_256_GCM_SHA384"); + +// cs.add("TLS_DH_DSS_WITH_AES_128_CBC_SHA"); +// cs.add("TLS_DH_DSS_WITH_AES_128_CBC_SHA256"); +// cs.add("TLS_DH_DSS_WITH_AES_256_CBC_SHA"); +// cs.add("TLS_DH_DSS_WITH_AES_256_CBC_SHA256"); + +// cs.add("TLS_DH_RSA_WITH_AES_128_CBC_SHA"); +// cs.add("TLS_DH_RSA_WITH_AES_128_CBC_SHA256"); +// cs.add("TLS_DH_RSA_WITH_AES_256_CBC_SHA"); +// cs.add("TLS_DH_RSA_WITH_AES_256_CBC_SHA256"); + + cs.add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA"); + cs.add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"); + cs.add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA"); + cs.add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"); + + cs.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"); + cs.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"); + cs.add("TLS_DHE_RSA_WITH_AES_128_CCM"); + cs.add("TLS_DHE_RSA_WITH_AES_128_CCM_8"); + cs.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"); + cs.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"); + cs.add("TLS_DHE_RSA_WITH_AES_256_CCM"); + cs.add("TLS_DHE_RSA_WITH_AES_256_CCM_8"); + +// cs.add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"); +// cs.add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"); +// cs.add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"); +// cs.add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"); + +// cs.add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"); +// cs.add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"); +// cs.add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"); +// cs.add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"); + + cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CCM"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CCM"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"); + + cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"); + cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"); + cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"); + cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"); + + if (includeGCM12) + { +// cs.add("TLS_DH_DSS_WITH_AES_128_GCM_SHA256"); +// cs.add("TLS_DH_DSS_WITH_AES_256_GCM_SHA384"); + +// cs.add("TLS_DH_RSA_WITH_AES_128_GCM_SHA256"); +// cs.add("TLS_DH_RSA_WITH_AES_256_GCM_SHA384"); + + cs.add("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"); + cs.add("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"); + + cs.add("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"); + cs.add("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"); + +// cs.add("TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"); +// cs.add("TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"); + +// cs.add("TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"); +// cs.add("TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"); + + cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); + cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"); + + cs.add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); + cs.add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"); + } + + if (FipsTestUtils.provAllowRSAKeyExchange) + { + cs.add("TLS_RSA_WITH_AES_128_CBC_SHA"); + cs.add("TLS_RSA_WITH_AES_128_CBC_SHA256"); + cs.add("TLS_RSA_WITH_AES_128_CCM"); + cs.add("TLS_RSA_WITH_AES_128_CCM_8"); + cs.add("TLS_RSA_WITH_AES_256_CBC_SHA"); + cs.add("TLS_RSA_WITH_AES_256_CBC_SHA256"); + cs.add("TLS_RSA_WITH_AES_256_CCM"); + cs.add("TLS_RSA_WITH_AES_256_CCM_8"); + + if (includeGCM12) + { + cs.add("TLS_RSA_WITH_AES_128_GCM_SHA256"); + cs.add("TLS_RSA_WITH_AES_256_GCM_SHA384"); + } + } + + return Collections.unmodifiableSet(cs); + } + + static boolean isFipsCipherSuite(String cipherSuite) + { + return FIPS_CIPHERSUITES.contains(cipherSuite); + } + + static void setupFipsSuite() + { + if (!enableGCMCiphersIn12) + { + ProviderUtils.setupHighPriority(true); + return; + } + + Provider bc = ProviderUtils.getProviderBC(); + + if (bc == null) + { + bc = ProviderUtils.createProviderBC(); + } + else + { + ProviderUtils.removeProviderBC(); + } + + ProviderUtils.removeProviderBCJSSE(); + + Provider bcjsse = ProviderUtils.createProviderBCJSSE(true, new FipsJcaTlsCryptoProvider().setProvider(bc)); + + Security.insertProviderAt(bc, 1); + Security.insertProviderAt(bcjsse, 2); + } + + static void teardownFipsSuite() + { + if (enableGCMCiphersIn12) + { + ProviderUtils.removeProviderBCJSSE(); + } + } +} diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/KeyManagerFactoryTest.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/KeyManagerFactoryTest.java index 2e23a369be..3da5f13b4f 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/KeyManagerFactoryTest.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/KeyManagerFactoryTest.java @@ -199,7 +199,7 @@ private KeyStore getEcKeyStore(boolean agreement) ks.load(null, PASSWORD); - ks.setKeyEntry("test", ePair.getPrivate(), PASSWORD, new Certificate[] { eCert, iCert }); + ks.setKeyEntry("test", ePair.getPrivate(), PASSWORD, new Certificate[]{ eCert, iCert }); ks.setCertificateEntry("root", rCert); @@ -230,7 +230,7 @@ private KeyStore getRsaKeyStore(boolean encryption) ks.load(null, PASSWORD); - ks.setKeyEntry("test", ePair.getPrivate(), PASSWORD, new Certificate[] { eCert, iCert }); + ks.setKeyEntry("test", ePair.getPrivate(), PASSWORD, new Certificate[]{ eCert, iCert }); ks.setCertificateEntry("root", rCert); @@ -248,14 +248,14 @@ private void implTestKeyManager(BCX509ExtendedKeyManager manager, String keyType BCX509Key key = manager.chooseServerKeyBC(new String[]{ keyType }, null, null); assertNotNull(key); - alias = manager.chooseServerAlias(keyType, new Principal[] { new X500Principal("CN=TLS Test") }, null); + alias = manager.chooseServerAlias(keyType, new Principal[]{ new X500Principal("CN=TLS Test") }, null); assertNull(alias); - key = manager.chooseServerKeyBC(new String[]{ keyType }, new Principal[] { new X500Principal("CN=TLS Test") }, + key = manager.chooseServerKeyBC(new String[]{ keyType }, new Principal[]{ new X500Principal("CN=TLS Test") }, null); assertNull(key); - alias = manager.chooseServerAlias(keyType, new Principal[] { new X500Principal("CN=TLS Test CA") }, null); + alias = manager.chooseServerAlias(keyType, new Principal[]{ new X500Principal("CN=TLS Test CA") }, null); assertNotNull(alias); assertNotNull(manager.getCertificateChain(alias)); assertNotNull(manager.getPrivateKey(alias)); diff --git a/tls/src/test/java/org/bouncycastle/jsse/provider/test/ProviderUtils.java b/tls/src/test/java/org/bouncycastle/jsse/provider/test/ProviderUtils.java index b71881e8eb..d9242d792b 100644 --- a/tls/src/test/java/org/bouncycastle/jsse/provider/test/ProviderUtils.java +++ b/tls/src/test/java/org/bouncycastle/jsse/provider/test/ProviderUtils.java @@ -24,9 +24,7 @@ static Provider createProviderBCJSSE() static Provider createProviderBCJSSE(boolean fips) { - // TODO Use new constructor when available -// return new BouncyCastleJsseProvider(fips); - return new BouncyCastleJsseProvider(fips, new JcaTlsCryptoProvider()); + return new BouncyCastleJsseProvider(fips); } static Provider createProviderBCJSSE(Provider bc) @@ -44,6 +42,11 @@ static Provider createProviderBCJSSE(String config) return new BouncyCastleJsseProvider(config); } + static Provider createProviderBCJSSE(boolean fips, JcaTlsCryptoProvider cryptoProvider) + { + return new BouncyCastleJsseProvider(fips, cryptoProvider); + } + static Provider getProviderBC() { return Security.getProvider(PROVIDER_NAME_BC); diff --git a/tls/src/test/java/org/bouncycastle/test/JVMVersionTest.java b/tls/src/test/java/org/bouncycastle/test/JVMVersionTest.java index 15a643c81d..07b2182a3e 100644 --- a/tls/src/test/java/org/bouncycastle/test/JVMVersionTest.java +++ b/tls/src/test/java/org/bouncycastle/test/JVMVersionTest.java @@ -34,12 +34,17 @@ public void testAssertExpectedJVM() // It is important for multi-release jars to be exercised on a representative JVM for each JVM they support. // // - assertNotNull(String.format("property %s is not set, see comment in test for reason why.", expectedVersionPropName), System.getProperty(expectedVersionPropName)); - - String version = System.getProperty("java.version"); String expectedPrefix = System.getProperty(expectedVersionPropName); + if ("any".equals(expectedPrefix)) { + assertTrue(true); + return; + } + + assertNotNull(String.format("property %s is not set, see comment in test for reason why.", expectedVersionPropName), expectedPrefix); + + String version = System.getProperty("java.version"); assertTrue(String.format("JVM Version: '%s' did not start with '%s' see comment in test", version, expectedPrefix), version.startsWith(expectedPrefix)); diff --git a/tls/src/test/java/org/bouncycastle/test/TestResourceFinder.java b/tls/src/test/java/org/bouncycastle/test/TestResourceFinder.java new file mode 100644 index 0000000000..14214bafae --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/test/TestResourceFinder.java @@ -0,0 +1,39 @@ +package org.bouncycastle.test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; + +public class TestResourceFinder +{ + private static final String dataDirName = "bc-test-data"; + + /** + * We search starting at the working directory looking for the bc-test-data directory. + * + * @throws FileNotFoundException + */ + public static InputStream findTestResource(String homeDir, String fileName) + throws FileNotFoundException + { + String wrkDirName = System.getProperty("user.dir"); + String separator = System.getProperty("file.separator"); + File wrkDir = new File(wrkDirName); + File dataDir = new File(wrkDir, dataDirName); + while (!dataDir.exists() && wrkDirName.length() > 1) + { + wrkDirName = wrkDirName.substring(0, wrkDirName.lastIndexOf(separator)); + wrkDir = new File(wrkDirName); + dataDir = new File(wrkDir, dataDirName); + } + + if (!dataDir.exists()) + { + String ln = System.getProperty("line.separator"); + throw new FileNotFoundException("Test data directory " + dataDirName + " not found." + ln + "Test data available from: https://github.com/bcgit/bc-test-data.git"); + } + + return new FileInputStream(new File(dataDir, homeDir + separator + fileName)); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/crypto/test/BcTlsCryptoTest.java b/tls/src/test/java/org/bouncycastle/tls/crypto/test/BcTlsCryptoTest.java index 96f70b3903..5f9917cf77 100644 --- a/tls/src/test/java/org/bouncycastle/tls/crypto/test/BcTlsCryptoTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/crypto/test/BcTlsCryptoTest.java @@ -1,7 +1,5 @@ package org.bouncycastle.tls.crypto.test; -import java.security.SecureRandom; - import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto; public class BcTlsCryptoTest diff --git a/tls/src/test/java/org/bouncycastle/tls/crypto/test/TlsCryptoTest.java b/tls/src/test/java/org/bouncycastle/tls/crypto/test/TlsCryptoTest.java index 2c4e063ab5..a5ffbc4c30 100644 --- a/tls/src/test/java/org/bouncycastle/tls/crypto/test/TlsCryptoTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/crypto/test/TlsCryptoTest.java @@ -154,7 +154,7 @@ protected TlsCredentialedSigner loadCredentialedSigner12(TlsCryptoParameters cry case SignatureAlgorithm.rsa_pss_rsae_sha512: return loadCredentialedSigner(cryptoParams, "rsa-sign", signatureAndHashAlgorithm); - // TODO[draft-smyshlyaev-tls12-gost-suites-10] Add test resources for these + // TODO[RFC 9189] Add test resources for these case SignatureAlgorithm.gostr34102012_256: case SignatureAlgorithm.gostr34102012_512: @@ -195,6 +195,9 @@ protected TlsCredentialedSigner loadCredentialedSigner13(TlsCryptoParameters cry case SignatureScheme.ecdsa_secp384r1_sha384: case SignatureScheme.ecdsa_secp521r1_sha512: case SignatureScheme.sm2sig_sm3: + case SignatureScheme.DRAFT_mldsa44: + case SignatureScheme.DRAFT_mldsa65: + case SignatureScheme.DRAFT_mldsa87: default: return null; @@ -218,6 +221,14 @@ public void testDHDomain() throws Exception implTestDHDomain(new TlsDHConfig(namedGroup, false)); implTestDHDomain(new TlsDHConfig(namedGroup, true)); } + } + + public void testDHExplicit() throws Exception + { + if (!crypto.hasDHAgreement()) + { + return; + } new DefaultTlsDHGroupVerifier() {{ @@ -233,9 +244,10 @@ public void testDHDomain() throws Exception assertSame(dhGroup, TlsDHUtils.getStandardGroupForDHParameters(p, g)); int namedGroup = TlsDHUtils.getNamedGroupForDHParameters(p, g); + + // Named groups tested elsewhere if (NamedGroup.refersToASpecificFiniteField(namedGroup)) { - // Already tested the named groups continue; } @@ -444,9 +456,9 @@ public void testHKDF() throws IOException public void testHKDFExpandLimit() { - int[] hashes = new int[] { CryptoHashAlgorithm.md5, CryptoHashAlgorithm.sha1, CryptoHashAlgorithm.sha224, + int[] hashes = new int[]{ CryptoHashAlgorithm.md5, CryptoHashAlgorithm.sha1, CryptoHashAlgorithm.sha224, CryptoHashAlgorithm.sha256, CryptoHashAlgorithm.sha384, CryptoHashAlgorithm.sha512, - CryptoHashAlgorithm.sm3 }; + CryptoHashAlgorithm.sm3, CryptoHashAlgorithm.gostr3411_2012_256 }; for (int i = 0; i < hashes.length; ++i) { @@ -561,7 +573,7 @@ public void testSignatures12() throws Exception } // Signature algorithms usable with HashAlgorithm.Intrinsic in TLS 1.2 - short[] intrinsicSignatureAlgorithms = new short[] { SignatureAlgorithm.ed25519, SignatureAlgorithm.ed448, + short[] intrinsicSignatureAlgorithms = new short[]{ SignatureAlgorithm.ed25519, SignatureAlgorithm.ed448, SignatureAlgorithm.gostr34102012_256, SignatureAlgorithm.gostr34102012_512, SignatureAlgorithm.rsa_pss_pss_sha256, SignatureAlgorithm.rsa_pss_pss_sha384, SignatureAlgorithm.rsa_pss_pss_sha512, SignatureAlgorithm.rsa_pss_rsae_sha256, @@ -587,13 +599,14 @@ public void testSignatures12() throws Exception public void testSignatures13() throws Exception { - int[] signatureSchemes = new int[] { SignatureScheme.ecdsa_brainpoolP256r1tls13_sha256, + int[] signatureSchemes = new int[]{ SignatureScheme.ecdsa_brainpoolP256r1tls13_sha256, SignatureScheme.ecdsa_brainpoolP384r1tls13_sha384, SignatureScheme.ecdsa_brainpoolP512r1tls13_sha512, SignatureScheme.ecdsa_secp256r1_sha256, SignatureScheme.ecdsa_secp384r1_sha384, SignatureScheme.ecdsa_secp521r1_sha512, SignatureScheme.ed25519, SignatureScheme.ed448, SignatureScheme.rsa_pss_pss_sha256, SignatureScheme.rsa_pss_pss_sha384, SignatureScheme.rsa_pss_pss_sha512, SignatureScheme.rsa_pss_rsae_sha256, SignatureScheme.rsa_pss_rsae_sha384, - SignatureScheme.rsa_pss_rsae_sha512, SignatureScheme.sm2sig_sm3, + SignatureScheme.rsa_pss_rsae_sha512, SignatureScheme.sm2sig_sm3, SignatureScheme.DRAFT_mldsa44, + SignatureScheme.DRAFT_mldsa65, SignatureScheme.DRAFT_mldsa87, // These are only used for certs in 1.3 (cert verification is not done by TlsCrypto) // SignatureScheme.ecdsa_sha1, SignatureScheme.rsa_pkcs1_sha1, SignatureScheme.rsa_pkcs1_sha256, // SignatureScheme.rsa_pkcs1_sha384, SignatureScheme.rsa_pkcs1_sha512, diff --git a/tls/src/test/java/org/bouncycastle/tls/test/AllTests.java b/tls/src/test/java/org/bouncycastle/tls/test/AllTests.java index 64b985fe45..224d241e9b 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/AllTests.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/AllTests.java @@ -22,12 +22,16 @@ public static Test suite() TestSuite suite = new TestSuite("TLS tests"); suite.addTestSuite(BasicTlsTest.class); + suite.addTestSuite(BcTlsProtocolHybridTest.class); + suite.addTestSuite(BcTlsProtocolKemTest.class); suite.addTestSuite(ByteQueueInputStreamTest.class); suite.addTestSuite(DTLSAggregatedHandshakeRetransmissionTest.class); suite.addTestSuite(DTLSHandshakeRetransmissionTest.class); suite.addTestSuite(DTLSProtocolTest.class); suite.addTestSuite(DTLSPSKProtocolTest.class); suite.addTestSuite(DTLSRawKeysProtocolTest.class); + suite.addTestSuite(JcaTlsProtocolHybridTest.class); + suite.addTestSuite(JcaTlsProtocolKemTest.class); suite.addTestSuite(OCSPTest.class); suite.addTestSuite(PRFTest.class); suite.addTestSuite(Tls13PSKProtocolTest.class); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/BcTlsProtocolHybridTest.java b/tls/src/test/java/org/bouncycastle/tls/test/BcTlsProtocolHybridTest.java new file mode 100644 index 0000000000..8499f7ad5e --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/BcTlsProtocolHybridTest.java @@ -0,0 +1,12 @@ +package org.bouncycastle.tls.test; + +import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto; + +public class BcTlsProtocolHybridTest + extends TlsProtocolHybridTest +{ + public BcTlsProtocolHybridTest() + { + super(new BcTlsCrypto()); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/BcTlsProtocolKemTest.java b/tls/src/test/java/org/bouncycastle/tls/test/BcTlsProtocolKemTest.java new file mode 100644 index 0000000000..e99d8d01e3 --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/BcTlsProtocolKemTest.java @@ -0,0 +1,12 @@ +package org.bouncycastle.tls.test; + +import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto; + +public class BcTlsProtocolKemTest + extends TlsProtocolKemTest +{ + public BcTlsProtocolKemTest() + { + super(new BcTlsCrypto()); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/DTLSRawKeysProtocolTest.java b/tls/src/test/java/org/bouncycastle/tls/test/DTLSRawKeysProtocolTest.java index c833062fe1..98565948ba 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/DTLSRawKeysProtocolTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/DTLSRawKeysProtocolTest.java @@ -41,7 +41,7 @@ private void testClientSendsExtensionButServerDoesNotSupportIt(ProtocolVersion t MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.X509, (short) -1, - new short[] {CertificateType.RawPublicKey, CertificateType.X509}, + new short[]{ CertificateType.RawPublicKey, CertificateType.X509 }, null, generateKeyPair(), tlsVersion); @@ -70,14 +70,14 @@ private void testExtensionsAreOmittedIfSpecifiedButOnlyContainX509(ProtocolVersi MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.X509, CertificateType.X509, - new short[] {CertificateType.X509}, - new short[] {CertificateType.X509}, + new short[]{ CertificateType.X509 }, + new short[]{ CertificateType.X509 }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.X509, - new short[] {CertificateType.X509}, + new short[]{ CertificateType.X509 }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -106,14 +106,14 @@ private void testBothSidesUseRawKey(ProtocolVersion tlsVersion) throws Exception MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -135,7 +135,7 @@ private void testServerUsesRawKeyAndClientIsAnonymous(ProtocolVersion tlsVersion MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, (short) -1, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, null, generateKeyPair(), tlsVersion); @@ -164,7 +164,7 @@ private void testServerUsesRawKeyAndClientUsesX509(ProtocolVersion tlsVersion) t MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.X509, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, null, generateKeyPair(), tlsVersion); @@ -194,13 +194,13 @@ private void testServerUsesX509AndClientUsesRawKey(ProtocolVersion tlsVersion) t CertificateType.X509, CertificateType.RawPublicKey, null, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -227,13 +227,13 @@ private void testClientSendsClientCertExtensionButServerHasNoCommonTypes(Protoco CertificateType.X509, CertificateType.RawPublicKey, null, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.X509, - new short[] {CertificateType.X509}, + new short[]{ CertificateType.X509 }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -266,14 +266,14 @@ private void testClientSendsServerCertExtensionButServerHasNoCommonTypes(Protoco MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, null, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); pumpData(client, server); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/JcaTlsProtocolHybridTest.java b/tls/src/test/java/org/bouncycastle/tls/test/JcaTlsProtocolHybridTest.java new file mode 100644 index 0000000000..85c35d87be --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/JcaTlsProtocolHybridTest.java @@ -0,0 +1,15 @@ +package org.bouncycastle.tls.test; + +import java.security.SecureRandom; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider; + +public class JcaTlsProtocolHybridTest + extends TlsProtocolHybridTest +{ + public JcaTlsProtocolHybridTest() + { + super(new JcaTlsCryptoProvider().setProvider(new BouncyCastleProvider()).create(new SecureRandom())); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/JcaTlsProtocolKemTest.java b/tls/src/test/java/org/bouncycastle/tls/test/JcaTlsProtocolKemTest.java new file mode 100644 index 0000000000..ae23d5a57f --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/JcaTlsProtocolKemTest.java @@ -0,0 +1,15 @@ +package org.bouncycastle.tls.test; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider; + +import java.security.SecureRandom; + +public class JcaTlsProtocolKemTest + extends TlsProtocolKemTest +{ + public JcaTlsProtocolKemTest() + { + super(new JcaTlsCryptoProvider().setProvider(new BouncyCastleProvider()).create(new SecureRandom())); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockPSKDTLSClient.java b/tls/src/test/java/org/bouncycastle/tls/test/MockPSKDTLSClient.java index 7eb0f0b2cb..c4efb99fa4 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockPSKDTLSClient.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockPSKDTLSClient.java @@ -101,7 +101,7 @@ public void notifyServerCertificate(TlsServerCertificate serverCertificate) thro throw new TlsFatalAlert(AlertDescription.bad_certificate); } - String[] trustedCertResources = new String[] { "x509-server-rsa-enc.pem" }; + String[] trustedCertResources = new String[]{ "x509-server-rsa-enc.pem" }; TlsCertificate[] certPath = TlsTestUtils.getTrustedCertPath(context.getCrypto(), chain[0], trustedCertResources); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Client.java b/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Client.java index d6a3e515f9..6efd1815ac 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Client.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Client.java @@ -36,7 +36,7 @@ class MockPSKTls13Client // public short[] getPskKeyExchangeModes() // { -// return new short[] { PskKeyExchangeMode.psk_dhe_ke, PskKeyExchangeMode.psk_ke }; +// return new short[]{ PskKeyExchangeMode.psk_dhe_ke, PskKeyExchangeMode.psk_ke }; // } protected Vector getProtocolNames() diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Server.java b/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Server.java index 54ed274df8..b177af6e77 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Server.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockPSKTls13Server.java @@ -46,7 +46,7 @@ protected Vector getProtocolNames() protected int[] getSupportedCipherSuites() { return TlsUtils.getSupportedCipherSuites(getCrypto(), - new int[] { CipherSuite.TLS_AES_128_CCM_8_SHA256, CipherSuite.TLS_AES_128_CCM_SHA256, + new int[]{ CipherSuite.TLS_AES_128_CCM_8_SHA256, CipherSuite.TLS_AES_128_CCM_SHA256, CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_CHACHA20_POLY1305_SHA256 }); } diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockRawKeysTlsClient.java b/tls/src/test/java/org/bouncycastle/tls/test/MockRawKeysTlsClient.java index 05a41ce611..e60ad1a1b4 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockRawKeysTlsClient.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockRawKeysTlsClient.java @@ -55,7 +55,7 @@ class MockRawKeysTlsClient protected ProtocolVersion[] getSupportedVersions() { - return new ProtocolVersion[] {tlsVersion}; + return new ProtocolVersion[]{tlsVersion}; } protected int[] getSupportedCipherSuites() diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockSRPTlsClient.java b/tls/src/test/java/org/bouncycastle/tls/test/MockSRPTlsClient.java index bafec7bd69..74126f1b40 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockSRPTlsClient.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockSRPTlsClient.java @@ -124,7 +124,7 @@ public void notifyServerCertificate(TlsServerCertificate serverCertificate) thro throw new TlsFatalAlert(AlertDescription.bad_certificate); } - String[] trustedCertResources = new String[] { "x509-server-dsa.pem", "x509-server-rsa_pss_256.pem", + String[] trustedCertResources = new String[]{ "x509-server-dsa.pem", "x509-server-rsa_pss_256.pem", "x509-server-rsa_pss_384.pem", "x509-server-rsa_pss_512.pem", "x509-server-rsa-sign.pem" }; TlsCertificate[] certPath = TlsTestUtils.getTrustedCertPath(context.getCrypto(), chain[0], diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockTlsHybridClient.java b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsHybridClient.java new file mode 100644 index 0000000000..cf0d48519b --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsHybridClient.java @@ -0,0 +1,244 @@ +package org.bouncycastle.tls.test; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Vector; + +import org.bouncycastle.asn1.x509.Certificate; +import org.bouncycastle.tls.AlertDescription; +import org.bouncycastle.tls.AlertLevel; +import org.bouncycastle.tls.CertificateRequest; +import org.bouncycastle.tls.ChannelBinding; +import org.bouncycastle.tls.ClientCertificateType; +import org.bouncycastle.tls.DefaultTlsClient; +import org.bouncycastle.tls.MaxFragmentLength; +import org.bouncycastle.tls.NamedGroup; +import org.bouncycastle.tls.NamedGroupRole; +import org.bouncycastle.tls.ProtocolName; +import org.bouncycastle.tls.ProtocolVersion; +import org.bouncycastle.tls.SignatureAlgorithm; +import org.bouncycastle.tls.TlsAuthentication; +import org.bouncycastle.tls.TlsCredentials; +import org.bouncycastle.tls.TlsExtensionsUtils; +import org.bouncycastle.tls.TlsFatalAlert; +import org.bouncycastle.tls.TlsServerCertificate; +import org.bouncycastle.tls.TlsSession; +import org.bouncycastle.tls.TlsUtils; +import org.bouncycastle.tls.crypto.TlsCertificate; +import org.bouncycastle.tls.crypto.TlsCrypto; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.Integers; +import org.bouncycastle.util.encoders.Hex; + +class MockTlsHybridClient + extends DefaultTlsClient +{ + TlsSession session; + + int[] namedGroups = new int[] + { + NamedGroup.SecP256r1MLKEM768, + NamedGroup.X25519MLKEM768, + NamedGroup.SecP384r1MLKEM1024, + }; + + MockTlsHybridClient(TlsCrypto crypto, TlsSession session) + { + super(crypto); + + this.session = session; + } + + protected Vector getProtocolNames() + { + Vector protocolNames = new Vector(); + protocolNames.addElement(ProtocolName.HTTP_1_1); + protocolNames.addElement(ProtocolName.HTTP_2_TLS); + return protocolNames; + } + + void setNamedGroups(int[] namedGroups) + { + this.namedGroups = namedGroups; + } + + protected Vector getSupportedGroups(Vector namedGroupRoles) { + TlsCrypto crypto = getCrypto(); + Vector supportedGroups = new Vector(); + + if (namedGroupRoles.contains(Integers.valueOf(NamedGroupRole.kem))) + { + TlsUtils.addIfSupported(supportedGroups, crypto, this.namedGroups); + } + return supportedGroups; + } + + public TlsSession getSessionToResume() + { + return this.session; + } + + public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause) + { + PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; + out.println("TLS hybrid client raised alert: " + AlertLevel.getText(alertLevel) + + ", " + AlertDescription.getText(alertDescription)); + if (message != null) + { + out.println("> " + message); + } + if (cause != null) + { + cause.printStackTrace(out); + } + } + + public void notifyAlertReceived(short alertLevel, short alertDescription) + { + PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; + out.println("TLS hybrid client received alert: " + AlertLevel.getText(alertLevel) + + ", " + AlertDescription.getText(alertDescription)); + } + + public Hashtable getClientExtensions() throws IOException + { + if (context.getSecurityParametersHandshake().getClientRandom() == null) + { + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + Hashtable clientExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(super.getClientExtensions()); + { + /* + * NOTE: If you are copying test code, do not blindly set these extensions in your own client. + */ + TlsExtensionsUtils.addMaxFragmentLengthExtension(clientExtensions, MaxFragmentLength.pow2_9); + TlsExtensionsUtils.addPaddingExtension(clientExtensions, context.getCrypto().getSecureRandom().nextInt(16)); + TlsExtensionsUtils.addTruncatedHMacExtension(clientExtensions); + } + return clientExtensions; + } + + public void notifyServerVersion(ProtocolVersion serverVersion) throws IOException + { + super.notifyServerVersion(serverVersion); + + System.out.println("TLS hybrid client negotiated " + serverVersion); + } + + public TlsAuthentication getAuthentication() throws IOException + { + return new TlsAuthentication() + { + public void notifyServerCertificate(TlsServerCertificate serverCertificate) throws IOException + { + TlsCertificate[] chain = serverCertificate.getCertificate().getCertificateList(); + + System.out.println("TLS hybrid client received server certificate chain of length " + chain.length); + for (int i = 0; i != chain.length; i++) + { + Certificate entry = Certificate.getInstance(chain[i].getEncoded()); + // TODO Create fingerprint based on certificate signature algorithm digest + System.out.println(" fingerprint:SHA-256 " + TlsTestUtils.fingerprint(entry) + " (" + + entry.getSubject() + ")"); + } + + boolean isEmpty = serverCertificate == null || serverCertificate.getCertificate() == null + || serverCertificate.getCertificate().isEmpty(); + + if (isEmpty) + { + throw new TlsFatalAlert(AlertDescription.bad_certificate); + } + + String[] trustedCertResources = new String[]{ "x509-server-dsa.pem", "x509-server-ecdh.pem", + "x509-server-ecdsa.pem", "x509-server-ed25519.pem", "x509-server-ed448.pem", + "x509-server-rsa_pss_256.pem", "x509-server-rsa_pss_384.pem", "x509-server-rsa_pss_512.pem", + "x509-server-rsa-enc.pem", "x509-server-rsa-sign.pem" }; + + TlsCertificate[] certPath = TlsTestUtils.getTrustedCertPath(context.getCrypto(), chain[0], + trustedCertResources); + + if (null == certPath) + { + throw new TlsFatalAlert(AlertDescription.bad_certificate); + } + + TlsUtils.checkPeerSigAlgs(context, certPath); + } + + public TlsCredentials getClientCredentials(CertificateRequest certificateRequest) throws IOException + { + short[] certificateTypes = certificateRequest.getCertificateTypes(); + if (certificateTypes == null || !Arrays.contains(certificateTypes, ClientCertificateType.rsa_sign)) + { + return null; + } + + return TlsTestUtils.loadSignerCredentials(context, certificateRequest.getSupportedSignatureAlgorithms(), + SignatureAlgorithm.rsa, "x509-client-rsa.pem", "x509-client-key-rsa.pem"); + } + }; + } + + public void notifyHandshakeComplete() throws IOException + { + super.notifyHandshakeComplete(); + + ProtocolName protocolName = context.getSecurityParametersConnection().getApplicationProtocol(); + if (protocolName != null) + { + System.out.println("Client ALPN: " + protocolName.getUtf8Decoding()); + } + + TlsSession newSession = context.getSession(); + if (newSession != null) + { + if (newSession.isResumable()) + { + byte[] newSessionID = newSession.getSessionID(); + String hex = hex(newSessionID); + + if (this.session != null && Arrays.areEqual(this.session.getSessionID(), newSessionID)) + { + System.out.println("Client resumed session: " + hex); + } + else + { + System.out.println("Client established session: " + hex); + } + + this.session = newSession; + } + + byte[] tlsServerEndPoint = context.exportChannelBinding(ChannelBinding.tls_server_end_point); + if (null != tlsServerEndPoint) + { + System.out.println("Client 'tls-server-end-point': " + hex(tlsServerEndPoint)); + } + + byte[] tlsUnique = context.exportChannelBinding(ChannelBinding.tls_unique); + System.out.println("Client 'tls-unique': " + hex(tlsUnique)); + + byte[] tlsExporter = context.exportChannelBinding(ChannelBinding.tls_exporter); + System.out.println("Client 'tls-exporter': " + hex(tlsExporter)); + } + } + + public void processServerExtensions(Hashtable serverExtensions) throws IOException + { + if (context.getSecurityParametersHandshake().getServerRandom() == null) + { + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + super.processServerExtensions(serverExtensions); + } + + protected String hex(byte[] data) + { + return data == null ? "(null)" : Hex.toHexString(data); + } +} + diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockTlsHybridServer.java b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsHybridServer.java new file mode 100644 index 0000000000..6ca3846ca0 --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsHybridServer.java @@ -0,0 +1,245 @@ +package org.bouncycastle.tls.test; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Vector; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.Certificate; +import org.bouncycastle.tls.AlertDescription; +import org.bouncycastle.tls.AlertLevel; +import org.bouncycastle.tls.CertificateRequest; +import org.bouncycastle.tls.ChannelBinding; +import org.bouncycastle.tls.ClientCertificateType; +import org.bouncycastle.tls.DefaultTlsServer; +import org.bouncycastle.tls.NamedGroup; +import org.bouncycastle.tls.ProtocolName; +import org.bouncycastle.tls.ProtocolVersion; +import org.bouncycastle.tls.SignatureAlgorithm; +import org.bouncycastle.tls.TlsCredentialedDecryptor; +import org.bouncycastle.tls.TlsCredentialedSigner; +import org.bouncycastle.tls.TlsCredentials; +import org.bouncycastle.tls.TlsFatalAlert; +import org.bouncycastle.tls.TlsUtils; +import org.bouncycastle.tls.crypto.TlsCertificate; +import org.bouncycastle.tls.crypto.TlsCrypto; +import org.bouncycastle.util.encoders.Hex; + +class MockTlsHybridServer + extends DefaultTlsServer +{ + int[] namedGroups = new int[] + { + NamedGroup.SecP256r1MLKEM768, + NamedGroup.X25519MLKEM768, + NamedGroup.SecP384r1MLKEM1024, + NamedGroup.x25519, + }; + + MockTlsHybridServer(TlsCrypto crypto) + { + super(crypto); + } + + protected Vector getProtocolNames() + { + Vector protocolNames = new Vector(); + protocolNames.addElement(ProtocolName.HTTP_2_TLS); + protocolNames.addElement(ProtocolName.HTTP_1_1); + return protocolNames; + } + + void setNamedGroups(int[] namedGroups) + { + this.namedGroups = namedGroups; + } + + public int[] getSupportedGroups() throws IOException + { + return namedGroups; + } + + public TlsCredentials getCredentials() throws IOException + { + /* + * TODO[tls13] Should really be finding the first client-supported signature scheme that the + * server also supports and has credentials for. + */ + if (TlsUtils.isTLSv13(context)) + { + return getRSASignerCredentials(); + } + + return super.getCredentials(); + } + + public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause) + { + PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; + out.println("TLS hybrid server raised alert: " + AlertLevel.getText(alertLevel) + + ", " + AlertDescription.getText(alertDescription)); + if (message != null) + { + out.println("> " + message); + } + if (cause != null) + { + cause.printStackTrace(out); + } + } + + public void notifyAlertReceived(short alertLevel, short alertDescription) + { + PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; + out.println("TLS hybrid server received alert: " + AlertLevel.getText(alertLevel) + + ", " + AlertDescription.getText(alertDescription)); + } + + public ProtocolVersion getServerVersion() throws IOException + { + ProtocolVersion serverVersion = super.getServerVersion(); + + System.out.println("TLS hybrid server negotiated " + serverVersion); + + return serverVersion; + } + + public CertificateRequest getCertificateRequest() throws IOException + { + Vector serverSigAlgs = null; + if (TlsUtils.isSignatureAlgorithmsExtensionAllowed(context.getServerVersion())) + { + serverSigAlgs = TlsUtils.getDefaultSupportedSignatureAlgorithms(context); + } + + Vector certificateAuthorities = new Vector(); +// certificateAuthorities.addElement(TlsTestUtils.loadBcCertificateResource("x509-ca-dsa.pem").getSubject()); +// certificateAuthorities.addElement(TlsTestUtils.loadBcCertificateResource("x509-ca-ecdsa.pem").getSubject()); +// certificateAuthorities.addElement(TlsTestUtils.loadBcCertificateResource("x509-ca-rsa.pem").getSubject()); + + // All the CA certificates are currently configured with this subject + certificateAuthorities.addElement(new X500Name("CN=BouncyCastle TLS Test CA")); + + if (TlsUtils.isTLSv13(context)) + { + // TODO[tls13] Support for non-empty request context + byte[] certificateRequestContext = TlsUtils.EMPTY_BYTES; + + // TODO[tls13] Add TlsTestConfig.serverCertReqSigAlgsCert + Vector serverSigAlgsCert = null; + + return new CertificateRequest(certificateRequestContext, serverSigAlgs, serverSigAlgsCert, + certificateAuthorities); + } + else + { + short[] certificateTypes = new short[]{ ClientCertificateType.rsa_sign, + ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign }; + + return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities); + } + } + + public void notifyClientCertificate(org.bouncycastle.tls.Certificate clientCertificate) throws IOException + { + TlsCertificate[] chain = clientCertificate.getCertificateList(); + + System.out.println("TLS hybrid server received client certificate chain of length " + chain.length); + for (int i = 0; i != chain.length; i++) + { + Certificate entry = Certificate.getInstance(chain[i].getEncoded()); + // TODO Create fingerprint based on certificate signature algorithm digest + System.out.println(" fingerprint:SHA-256 " + TlsTestUtils.fingerprint(entry) + " (" + + entry.getSubject() + ")"); + } + + boolean isEmpty = (clientCertificate == null || clientCertificate.isEmpty()); + + if (isEmpty) + { + return; + } + + String[] trustedCertResources = new String[]{ "x509-client-dsa.pem", "x509-client-ecdh.pem", + "x509-client-ecdsa.pem", "x509-client-ed25519.pem", "x509-client-ed448.pem", "x509-client-rsa_pss_256.pem", + "x509-client-rsa_pss_384.pem", "x509-client-rsa_pss_512.pem", "x509-client-rsa.pem" }; + + TlsCertificate[] certPath = TlsTestUtils.getTrustedCertPath(context.getCrypto(), chain[0], + trustedCertResources); + + if (null == certPath) + { + throw new TlsFatalAlert(AlertDescription.bad_certificate); + } + + TlsUtils.checkPeerSigAlgs(context, certPath); + } + + public void notifyHandshakeComplete() throws IOException + { + super.notifyHandshakeComplete(); + + ProtocolName protocolName = context.getSecurityParametersConnection().getApplicationProtocol(); + if (protocolName != null) + { + System.out.println("Server ALPN: " + protocolName.getUtf8Decoding()); + } + + byte[] tlsServerEndPoint = context.exportChannelBinding(ChannelBinding.tls_server_end_point); + System.out.println("Server 'tls-server-end-point': " + hex(tlsServerEndPoint)); + + byte[] tlsUnique = context.exportChannelBinding(ChannelBinding.tls_unique); + System.out.println("Server 'tls-unique': " + hex(tlsUnique)); + + byte[] tlsExporter = context.exportChannelBinding(ChannelBinding.tls_exporter); + System.out.println("Server 'tls-exporter': " + hex(tlsExporter)); + } + + public void processClientExtensions(Hashtable clientExtensions) throws IOException + { + if (context.getSecurityParametersHandshake().getClientRandom() == null) + { + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + super.processClientExtensions(clientExtensions); + } + + public Hashtable getServerExtensions() throws IOException + { + if (context.getSecurityParametersHandshake().getServerRandom() == null) + { + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + return super.getServerExtensions(); + } + + public void getServerExtensionsForConnection(Hashtable serverExtensions) throws IOException + { + if (context.getSecurityParametersHandshake().getServerRandom() == null) + { + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + super.getServerExtensionsForConnection(serverExtensions); + } + + protected TlsCredentialedDecryptor getRSAEncryptionCredentials() throws IOException + { + return TlsTestUtils.loadEncryptionCredentials(context, new String[]{ "x509-server-rsa-enc.pem", "x509-ca-rsa.pem" }, + "x509-server-key-rsa-enc.pem"); + } + + protected TlsCredentialedSigner getRSASignerCredentials() throws IOException + { + Vector clientSigAlgs = context.getSecurityParametersHandshake().getClientSigAlgs(); + return TlsTestUtils.loadSignerCredentialsServer(context, clientSigAlgs, SignatureAlgorithm.rsa); + } + + protected String hex(byte[] data) + { + return data == null ? "(null)" : Hex.toHexString(data); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemClient.java b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemClient.java index a69fbf77ce..9893b905dc 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemClient.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemClient.java @@ -27,19 +27,25 @@ import org.bouncycastle.tls.TlsUtils; import org.bouncycastle.tls.crypto.TlsCertificate; import org.bouncycastle.tls.crypto.TlsCrypto; -import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; import org.bouncycastle.util.encoders.Hex; class MockTlsKemClient - extends DefaultTlsClient + extends DefaultTlsClient { TlsSession session; - MockTlsKemClient(TlsSession session) + int[] namedGroups = new int[] { - super(new BcTlsCrypto()); + NamedGroup.MLKEM512, + NamedGroup.MLKEM768, + NamedGroup.MLKEM1024, + }; + + MockTlsKemClient(TlsCrypto crypto, TlsSession session) + { + super(crypto); this.session = session; } @@ -52,25 +58,19 @@ protected Vector getProtocolNames() return protocolNames; } - public int[] supportedGroups = new int[] { - NamedGroup.OQS_mlkem512, - NamedGroup.OQS_mlkem768, - NamedGroup.OQS_mlkem1024 - }; - - public void setSupportedGroups(int[] supportedGroups) + void setNamedGroups(int[] namedGroups) { - this.supportedGroups = supportedGroups; + this.namedGroups = namedGroups; } protected Vector getSupportedGroups(Vector namedGroupRoles) { TlsCrypto crypto = getCrypto(); Vector supportedGroups = new Vector(); - if (namedGroupRoles.contains(Integers.valueOf(NamedGroupRole.kem))) { - TlsUtils.addIfSupported(supportedGroups, crypto, - this.supportedGroups); - }; + if (namedGroupRoles.contains(Integers.valueOf(NamedGroupRole.kem))) + { + TlsUtils.addIfSupported(supportedGroups, crypto, this.namedGroups); + } return supportedGroups; } @@ -82,8 +82,8 @@ public TlsSession getSessionToResume() public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause) { PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; - out.println("TLS client raised alert: " + AlertLevel.getText(alertLevel) - + ", " + AlertDescription.getText(alertDescription)); + out.println("TLS KEM client raised alert: " + AlertLevel.getText(alertLevel) + + ", " + AlertDescription.getText(alertDescription)); if (message != null) { out.println("> " + message); @@ -98,7 +98,7 @@ public void notifyAlertReceived(short alertLevel, short alertDescription) { PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; out.println("TLS KEM client received alert: " + AlertLevel.getText(alertLevel) - + ", " + AlertDescription.getText(alertDescription)); + + ", " + AlertDescription.getText(alertDescription)); } public Hashtable getClientExtensions() throws IOException @@ -141,11 +141,11 @@ public void notifyServerCertificate(TlsServerCertificate serverCertificate) thro Certificate entry = Certificate.getInstance(chain[i].getEncoded()); // TODO Create fingerprint based on certificate signature algorithm digest System.out.println(" fingerprint:SHA-256 " + TlsTestUtils.fingerprint(entry) + " (" - + entry.getSubject() + ")"); + + entry.getSubject() + ")"); } boolean isEmpty = serverCertificate == null || serverCertificate.getCertificate() == null - || serverCertificate.getCertificate().isEmpty(); + || serverCertificate.getCertificate().isEmpty(); if (isEmpty) { @@ -153,12 +153,12 @@ public void notifyServerCertificate(TlsServerCertificate serverCertificate) thro } String[] trustedCertResources = new String[]{ "x509-server-dsa.pem", "x509-server-ecdh.pem", - "x509-server-ecdsa.pem", "x509-server-ed25519.pem", "x509-server-ed448.pem", - "x509-server-rsa_pss_256.pem", "x509-server-rsa_pss_384.pem", "x509-server-rsa_pss_512.pem", - "x509-server-rsa-enc.pem", "x509-server-rsa-sign.pem" }; + "x509-server-ecdsa.pem", "x509-server-ed25519.pem", "x509-server-ed448.pem", + "x509-server-rsa_pss_256.pem", "x509-server-rsa_pss_384.pem", "x509-server-rsa_pss_512.pem", + "x509-server-rsa-enc.pem", "x509-server-rsa-sign.pem" }; TlsCertificate[] certPath = TlsTestUtils.getTrustedCertPath(context.getCrypto(), chain[0], - trustedCertResources); + trustedCertResources); if (null == certPath) { @@ -177,7 +177,7 @@ public TlsCredentials getClientCredentials(CertificateRequest certificateRequest } return TlsTestUtils.loadSignerCredentials(context, certificateRequest.getSupportedSignatureAlgorithms(), - SignatureAlgorithm.rsa, "x509-client-rsa.pem", "x509-client-key-rsa.pem"); + SignatureAlgorithm.rsa, "x509-client-rsa.pem", "x509-client-key-rsa.pem"); } }; } @@ -189,7 +189,7 @@ public void notifyHandshakeComplete() throws IOException ProtocolName protocolName = context.getSecurityParametersConnection().getApplicationProtocol(); if (protocolName != null) { - System.out.println("KEM Client ALPN: " + protocolName.getUtf8Decoding()); + System.out.println("Client ALPN: " + protocolName.getUtf8Decoding()); } TlsSession newSession = context.getSession(); @@ -202,11 +202,11 @@ public void notifyHandshakeComplete() throws IOException if (this.session != null && Arrays.areEqual(this.session.getSessionID(), newSessionID)) { - System.out.println("KEM Client resumed session: " + hex); + System.out.println("Client resumed session: " + hex); } else { - System.out.println("KEM Client established session: " + hex); + System.out.println("Client established session: " + hex); } this.session = newSession; @@ -215,14 +215,14 @@ public void notifyHandshakeComplete() throws IOException byte[] tlsServerEndPoint = context.exportChannelBinding(ChannelBinding.tls_server_end_point); if (null != tlsServerEndPoint) { - System.out.println("KEM Client 'tls-server-end-point': " + hex(tlsServerEndPoint)); + System.out.println("Client 'tls-server-end-point': " + hex(tlsServerEndPoint)); } byte[] tlsUnique = context.exportChannelBinding(ChannelBinding.tls_unique); - System.out.println("KEM Client 'tls-unique': " + hex(tlsUnique)); + System.out.println("Client 'tls-unique': " + hex(tlsUnique)); byte[] tlsExporter = context.exportChannelBinding(ChannelBinding.tls_exporter); - System.out.println("KEM Client 'tls-exporter': " + hex(tlsExporter)); + System.out.println("Client 'tls-exporter': " + hex(tlsExporter)); } } @@ -240,4 +240,5 @@ protected String hex(byte[] data) { return data == null ? "(null)" : Hex.toHexString(data); } -} \ No newline at end of file +} + diff --git a/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemServer.java b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemServer.java index 198f3a826d..333af53f90 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemServer.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/MockTlsKemServer.java @@ -23,15 +23,23 @@ import org.bouncycastle.tls.TlsFatalAlert; import org.bouncycastle.tls.TlsUtils; import org.bouncycastle.tls.crypto.TlsCertificate; -import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto; +import org.bouncycastle.tls.crypto.TlsCrypto; import org.bouncycastle.util.encoders.Hex; class MockTlsKemServer - extends DefaultTlsServer + extends DefaultTlsServer { - MockTlsKemServer() + int[] namedGroups = new int[] { - super(new BcTlsCrypto()); + NamedGroup.MLKEM512, + NamedGroup.MLKEM768, + NamedGroup.MLKEM1024, + NamedGroup.x25519, + }; + + MockTlsKemServer(TlsCrypto crypto) + { + super(crypto); } protected Vector getProtocolNames() @@ -42,20 +50,14 @@ protected Vector getProtocolNames() return protocolNames; } - public int[] supportedGroups = new int[] { - NamedGroup.OQS_mlkem512, - NamedGroup.OQS_mlkem768, - NamedGroup.OQS_mlkem1024, - NamedGroup.x25519 - }; - - public void setSupportedGroups(int[] supportedGroups) + void setNamedGroups(int[] namedGroups) { - this.supportedGroups = supportedGroups; + this.namedGroups = namedGroups; } - public int[] getSupportedGroups() throws IOException { - return supportedGroups; + public int[] getSupportedGroups() throws IOException + { + return namedGroups; } public TlsCredentials getCredentials() throws IOException @@ -76,7 +78,7 @@ public void notifyAlertRaised(short alertLevel, short alertDescription, String m { PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; out.println("TLS KEM server raised alert: " + AlertLevel.getText(alertLevel) - + ", " + AlertDescription.getText(alertDescription)); + + ", " + AlertDescription.getText(alertDescription)); if (message != null) { out.println("> " + message); @@ -91,7 +93,7 @@ public void notifyAlertReceived(short alertLevel, short alertDescription) { PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; out.println("TLS KEM server received alert: " + AlertLevel.getText(alertLevel) - + ", " + AlertDescription.getText(alertDescription)); + + ", " + AlertDescription.getText(alertDescription)); } public ProtocolVersion getServerVersion() throws IOException @@ -128,12 +130,12 @@ public CertificateRequest getCertificateRequest() throws IOException Vector serverSigAlgsCert = null; return new CertificateRequest(certificateRequestContext, serverSigAlgs, serverSigAlgsCert, - certificateAuthorities); + certificateAuthorities); } else { short[] certificateTypes = new short[]{ ClientCertificateType.rsa_sign, - ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign }; + ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign }; return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities); } @@ -149,7 +151,7 @@ public void notifyClientCertificate(org.bouncycastle.tls.Certificate clientCerti Certificate entry = Certificate.getInstance(chain[i].getEncoded()); // TODO Create fingerprint based on certificate signature algorithm digest System.out.println(" fingerprint:SHA-256 " + TlsTestUtils.fingerprint(entry) + " (" - + entry.getSubject() + ")"); + + entry.getSubject() + ")"); } boolean isEmpty = (clientCertificate == null || clientCertificate.isEmpty()); @@ -160,11 +162,11 @@ public void notifyClientCertificate(org.bouncycastle.tls.Certificate clientCerti } String[] trustedCertResources = new String[]{ "x509-client-dsa.pem", "x509-client-ecdh.pem", - "x509-client-ecdsa.pem", "x509-client-ed25519.pem", "x509-client-ed448.pem", "x509-client-rsa_pss_256.pem", - "x509-client-rsa_pss_384.pem", "x509-client-rsa_pss_512.pem", "x509-client-rsa.pem" }; + "x509-client-ecdsa.pem", "x509-client-ed25519.pem", "x509-client-ed448.pem", "x509-client-rsa_pss_256.pem", + "x509-client-rsa_pss_384.pem", "x509-client-rsa_pss_512.pem", "x509-client-rsa.pem" }; TlsCertificate[] certPath = TlsTestUtils.getTrustedCertPath(context.getCrypto(), chain[0], - trustedCertResources); + trustedCertResources); if (null == certPath) { @@ -181,17 +183,17 @@ public void notifyHandshakeComplete() throws IOException ProtocolName protocolName = context.getSecurityParametersConnection().getApplicationProtocol(); if (protocolName != null) { - System.out.println("KEM Server ALPN: " + protocolName.getUtf8Decoding()); + System.out.println("Server ALPN: " + protocolName.getUtf8Decoding()); } byte[] tlsServerEndPoint = context.exportChannelBinding(ChannelBinding.tls_server_end_point); - System.out.println("KEM Server 'tls-server-end-point': " + hex(tlsServerEndPoint)); + System.out.println("Server 'tls-server-end-point': " + hex(tlsServerEndPoint)); byte[] tlsUnique = context.exportChannelBinding(ChannelBinding.tls_unique); - System.out.println("KEM Server 'tls-unique': " + hex(tlsUnique)); + System.out.println("Server 'tls-unique': " + hex(tlsUnique)); byte[] tlsExporter = context.exportChannelBinding(ChannelBinding.tls_exporter); - System.out.println("KEM Server 'tls-exporter': " + hex(tlsExporter)); + System.out.println("Server 'tls-exporter': " + hex(tlsExporter)); } public void processClientExtensions(Hashtable clientExtensions) throws IOException @@ -227,7 +229,7 @@ public void getServerExtensionsForConnection(Hashtable serverExtensions) throws protected TlsCredentialedDecryptor getRSAEncryptionCredentials() throws IOException { return TlsTestUtils.loadEncryptionCredentials(context, new String[]{ "x509-server-rsa-enc.pem", "x509-ca-rsa.pem" }, - "x509-server-key-rsa-enc.pem"); + "x509-server-key-rsa-enc.pem"); } protected TlsCredentialedSigner getRSASignerCredentials() throws IOException @@ -240,4 +242,4 @@ protected String hex(byte[] data) { return data == null ? "(null)" : Hex.toHexString(data); } -} \ No newline at end of file +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/OCSPTest.java b/tls/src/test/java/org/bouncycastle/tls/test/OCSPTest.java index 9a05f4d70b..8aefe9a06e 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/OCSPTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/OCSPTest.java @@ -111,7 +111,7 @@ public void testOCSPResponder() OCSPResponder responder = new TestOCSPResponderImpl(server); - Certificate certs = new Certificate(new TlsCertificate[] { + Certificate certs = new Certificate(new TlsCertificate[]{ crypto.createCertificate(cert1.getEncoded()), crypto.createCertificate(cert2.getEncoded())}); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TestAEADGeneratorFactory.java b/tls/src/test/java/org/bouncycastle/tls/test/TestAEADGeneratorFactory.java new file mode 100644 index 0000000000..98ee98976b --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/TestAEADGeneratorFactory.java @@ -0,0 +1,20 @@ +package org.bouncycastle.tls.test; + +import org.bouncycastle.tls.crypto.impl.AEADNonceGenerator; +import org.bouncycastle.tls.crypto.impl.AEADNonceGeneratorFactory; + +public class TestAEADGeneratorFactory + implements AEADNonceGeneratorFactory +{ + public static final AEADNonceGeneratorFactory INSTANCE = new TestAEADGeneratorFactory(); + + private TestAEADGeneratorFactory() + { + // no op + } + + public AEADNonceGenerator create(byte[] baseNonce, int counterSizeInBits) + { + return new TestAEADNonceGenerator(baseNonce, counterSizeInBits); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TestAEADNonceGenerator.java b/tls/src/test/java/org/bouncycastle/tls/test/TestAEADNonceGenerator.java new file mode 100644 index 0000000000..3bff720c2a --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/TestAEADNonceGenerator.java @@ -0,0 +1,48 @@ +package org.bouncycastle.tls.test; + +import org.bouncycastle.tls.crypto.impl.AEADNonceGenerator; +import org.bouncycastle.util.Arrays; + +class TestAEADNonceGenerator + implements AEADNonceGenerator +{ + private final byte[] baseNonce; + private final long counterMask; + private final int counterBytes; + + private long counterValue; + private boolean counterExhausted; + + TestAEADNonceGenerator(byte[] baseNonce, int counterBits) + { + this.baseNonce = Arrays.copyOf(baseNonce, baseNonce.length); + this.counterMask = -1L >>> (64 - counterBits); + this.counterBytes = (counterBits + 7) / 8; + + this.counterValue = 0L; + this.counterExhausted = false; + } + + public void generateNonce(byte[] nonce) + { + if (nonce.length != baseNonce.length) + { + throw new IllegalArgumentException("requested length is not equal to the length of the base nonce."); + } + + if (counterExhausted) + { + throw new IllegalStateException("TLS nonce generator exhausted"); + } + + System.arraycopy(baseNonce, 0, nonce, 0, baseNonce.length); + int offset = baseNonce.length - counterBytes; + + for (int i = 0; i < counterBytes; i++) + { + nonce[offset + i] ^= (byte)(counterValue >>> ((counterBytes - 1 - i) * 8)); + } + + counterExhausted |= ((++counterValue & counterMask) == 0); + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TestOCSPCertServer.java b/tls/src/test/java/org/bouncycastle/tls/test/TestOCSPCertServer.java index 56f0e427ae..5f622e4ba2 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/TestOCSPCertServer.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/TestOCSPCertServer.java @@ -66,7 +66,7 @@ public TestOCSPCertServer() X509Certificate ocspCert = CertChainUtil.createEndEntityCert( "CN=OCSP Signing Certificate", signKP.getPublic(), interKP.getPrivate(), interCert, KeyPurposeId.id_kp_OCSPSigning); - this.chain = new X509CertificateHolder[] { + this.chain = new X509CertificateHolder[]{ new X509CertificateHolder(ocspCert.getEncoded()), new X509CertificateHolder(interCert.getEncoded()) }; } @@ -100,7 +100,7 @@ public PKIXIdentity issueClientCert(String subjectName, boolean markRevoked) } return new PKIXIdentity(PrivateKeyInfo.getInstance(eeKP.getPrivate().getEncoded()), - new X509CertificateHolder[] { + new X509CertificateHolder[]{ new X509CertificateHolder(endEntityCert.getEncoded()), new X509CertificateHolder(interCert.getEncoded())}); } diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TlsClientRawKeysTest.java b/tls/src/test/java/org/bouncycastle/tls/test/TlsClientRawKeysTest.java index 7f932947da..ad2ce85ebe 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/TlsClientRawKeysTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/TlsClientRawKeysTest.java @@ -40,8 +40,8 @@ static void runTest(InetAddress address, int port, ProtocolVersion tlsVersion) t MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, + new short[]{ CertificateType.RawPublicKey }, new Ed25519PrivateKeyParameters(new SecureRandom()), tlsVersion); TlsClientProtocol protocol = openTlsConnection(address, port, client); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolHybridTest.java b/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolHybridTest.java new file mode 100644 index 0000000000..7ebbe7af26 --- /dev/null +++ b/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolHybridTest.java @@ -0,0 +1,165 @@ +package org.bouncycastle.tls.test; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; + +import org.bouncycastle.tls.NamedGroup; +import org.bouncycastle.tls.TlsClientProtocol; +import org.bouncycastle.tls.TlsServerProtocol; +import org.bouncycastle.tls.crypto.TlsCrypto; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.io.Streams; + +import junit.framework.TestCase; + +public abstract class TlsProtocolHybridTest + extends TestCase +{ + protected final TlsCrypto crypto; + + protected TlsProtocolHybridTest(TlsCrypto crypto) + { + this.crypto = crypto; + } + + // mismatched hybrid groups w/o non-hybrids + public void testMismatchedGroups() throws Exception + { + PipedInputStream clientRead = TlsTestUtils.createPipedInputStream(); + PipedInputStream serverRead = TlsTestUtils.createPipedInputStream(); + PipedOutputStream clientWrite = new PipedOutputStream(serverRead); + PipedOutputStream serverWrite = new PipedOutputStream(clientRead); + + TlsClientProtocol clientProtocol = new TlsClientProtocol(clientRead, clientWrite); + TlsServerProtocol serverProtocol = new TlsServerProtocol(serverRead, serverWrite); + + ServerThread serverThread = new ServerThread(crypto, serverProtocol, new int[]{ NamedGroup.X25519MLKEM768 }, true); + try + { + serverThread.start(); + } + catch (Exception ignored) + { + } + + MockTlsHybridClient client = new MockTlsHybridClient(crypto, null); + client.setNamedGroups(new int[]{ NamedGroup.SecP256r1MLKEM768 }); + try + { + clientProtocol.connect(client); + fail(); + } + catch (Exception ignored) + { + } + + serverThread.join(); + } + + public void testSecP256r1MLKEM768() throws Exception + { + implTestClientServer(NamedGroup.SecP256r1MLKEM768); + } + + public void testSecP384r1MLKEM1024() throws Exception + { + implTestClientServer(NamedGroup.SecP384r1MLKEM1024); + } + + public void testX25519MLKEM768() throws Exception + { + implTestClientServer(NamedGroup.X25519MLKEM768); + } + + private void implTestClientServer(int hybridGroup) throws Exception + { + PipedInputStream clientRead = TlsTestUtils.createPipedInputStream(); + PipedInputStream serverRead = TlsTestUtils.createPipedInputStream(); + PipedOutputStream clientWrite = new PipedOutputStream(serverRead); + PipedOutputStream serverWrite = new PipedOutputStream(clientRead); + + TlsClientProtocol clientProtocol = new TlsClientProtocol(clientRead, clientWrite); + TlsServerProtocol serverProtocol = new TlsServerProtocol(serverRead, serverWrite); + + ServerThread serverThread = new ServerThread(crypto, serverProtocol, new int[]{ hybridGroup }, false); + serverThread.start(); + + MockTlsHybridClient client = new MockTlsHybridClient(crypto, null); + client.setNamedGroups(new int[]{ hybridGroup }); + + clientProtocol.connect(client); + + // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity + int length = 1000; + + byte[] data = new byte[length]; + client.getCrypto().getSecureRandom().nextBytes(data); + + OutputStream output = clientProtocol.getOutputStream(); + output.write(data); + + byte[] echo = new byte[data.length]; + int count = Streams.readFully(clientProtocol.getInputStream(), echo); + + assertEquals(count, data.length); + assertTrue(Arrays.areEqual(data, echo)); + + output.close(); + + serverThread.join(); + } + + static class ServerThread + extends Thread + { + private final TlsCrypto crypto; + private final TlsServerProtocol serverProtocol; + private final int[] namedGroups; + private boolean shouldFail = false; + + ServerThread(TlsCrypto crypto, TlsServerProtocol serverProtocol, int[] namedGroups, boolean shouldFail) + { + this.crypto = crypto; + this.serverProtocol = serverProtocol; + this.namedGroups = namedGroups; + this.shouldFail = shouldFail; + } + + public void run() + { + try + { + MockTlsHybridServer server = new MockTlsHybridServer(crypto); + if (namedGroups != null) + { + server.setNamedGroups(namedGroups); + } + + try + { + serverProtocol.accept(server); + if (shouldFail) + { + fail(); + } + } + catch (IOException ignored) + { + if (!shouldFail) + { + fail(); + } + } + + Streams.pipeAll(serverProtocol.getInputStream(), serverProtocol.getOutputStream()); + serverProtocol.close(); + } + catch (Exception e) + { +// throw new RuntimeException(e); + } + } + } +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolKemTest.java b/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolKemTest.java index 358edd16f4..2dcaedca6d 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolKemTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/TlsProtocolKemTest.java @@ -8,17 +8,24 @@ import org.bouncycastle.tls.NamedGroup; import org.bouncycastle.tls.TlsClientProtocol; import org.bouncycastle.tls.TlsServerProtocol; +import org.bouncycastle.tls.crypto.TlsCrypto; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.io.Streams; import junit.framework.TestCase; -public class TlsProtocolKemTest - extends TestCase +public abstract class TlsProtocolKemTest + extends TestCase { + protected final TlsCrypto crypto; - // mismatched ML-KEM strengths w/o classical crypto - public void testMismatchStrength() throws Exception + protected TlsProtocolKemTest(TlsCrypto crypto) + { + this.crypto = crypto; + } + + // mismatched ML-KEM groups w/o classical crypto + public void testMismatchedGroups() throws Exception { PipedInputStream clientRead = TlsTestUtils.createPipedInputStream(); PipedInputStream serverRead = TlsTestUtils.createPipedInputStream(); @@ -28,7 +35,7 @@ public void testMismatchStrength() throws Exception TlsClientProtocol clientProtocol = new TlsClientProtocol(clientRead, clientWrite); TlsServerProtocol serverProtocol = new TlsServerProtocol(serverRead, serverWrite); - ServerThread serverThread = new ServerThread(serverProtocol, new int[] {NamedGroup.OQS_mlkem768}, true); + ServerThread serverThread = new ServerThread(crypto, serverProtocol, new int[]{ NamedGroup.MLKEM768 }, true); try { serverThread.start(); @@ -36,21 +43,37 @@ public void testMismatchStrength() throws Exception catch (Exception ignored) { } - MockTlsKemClient client = new MockTlsKemClient(null); - client.setSupportedGroups(new int[] {NamedGroup.OQS_mlkem512}); + + MockTlsKemClient client = new MockTlsKemClient(crypto, null); + client.setNamedGroups(new int[]{ NamedGroup.MLKEM512 }); try { clientProtocol.connect(client); fail(); } - catch (Exception ex) + catch (Exception ignored) { } serverThread.join(); } - public void testClientServer() throws Exception + public void testMLKEM512() throws Exception + { + implTestClientServer(NamedGroup.MLKEM512); + } + + public void testMLKEM768() throws Exception + { + implTestClientServer(NamedGroup.MLKEM768); + } + + public void testMLKEM1024() throws Exception + { + implTestClientServer(NamedGroup.MLKEM1024); + } + + private void implTestClientServer(int kemGroup) throws Exception { PipedInputStream clientRead = TlsTestUtils.createPipedInputStream(); PipedInputStream serverRead = TlsTestUtils.createPipedInputStream(); @@ -60,10 +83,12 @@ public void testClientServer() throws Exception TlsClientProtocol clientProtocol = new TlsClientProtocol(clientRead, clientWrite); TlsServerProtocol serverProtocol = new TlsServerProtocol(serverRead, serverWrite); - ServerThread serverThread = new ServerThread(serverProtocol, false); + ServerThread serverThread = new ServerThread(crypto, serverProtocol, new int[]{ kemGroup }, false); serverThread.start(); - MockTlsKemClient client = new MockTlsKemClient(null); + MockTlsKemClient client = new MockTlsKemClient(crypto, null); + client.setNamedGroups(new int[]{ kemGroup }); + clientProtocol.connect(client); // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity @@ -87,34 +112,29 @@ public void testClientServer() throws Exception } static class ServerThread - extends Thread + extends Thread { + private final TlsCrypto crypto; private final TlsServerProtocol serverProtocol; - private final int[] supportedGroups; - + private final int[] namedGroups; private boolean shouldFail = false; - ServerThread(TlsServerProtocol serverProtocol, int[] supportedGroups, boolean fail) - { - this.serverProtocol = serverProtocol; - this.supportedGroups = supportedGroups; - this.shouldFail = fail; - } - ServerThread(TlsServerProtocol serverProtocol, boolean fail) + ServerThread(TlsCrypto crypto, TlsServerProtocol serverProtocol, int[] namedGroups, boolean shouldFail) { + this.crypto = crypto; this.serverProtocol = serverProtocol; - this.supportedGroups = null; - this.shouldFail = fail; + this.namedGroups = namedGroups; + this.shouldFail = shouldFail; } public void run() { try { - MockTlsKemServer server = new MockTlsKemServer(); - if (supportedGroups != null) + MockTlsKemServer server = new MockTlsKemServer(crypto); + if (namedGroups != null) { - server.setSupportedGroups(supportedGroups); + server.setNamedGroups(namedGroups); } try @@ -138,7 +158,8 @@ public void run() } catch (Exception e) { +// throw new RuntimeException(e); } } } -} \ No newline at end of file +} diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TlsRawKeysProtocolTest.java b/tls/src/test/java/org/bouncycastle/tls/test/TlsRawKeysProtocolTest.java index 4d99e7f63c..de761c87d4 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/TlsRawKeysProtocolTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/TlsRawKeysProtocolTest.java @@ -40,7 +40,7 @@ private void testClientSendsExtensionButServerDoesNotSupportIt(ProtocolVersion t MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.X509, (short) -1, - new short[] {CertificateType.RawPublicKey, CertificateType.X509}, + new short[]{ CertificateType.RawPublicKey, CertificateType.X509 }, null, generateKeyPair(), tlsVersion); @@ -68,14 +68,14 @@ private void testExtensionsAreOmittedIfSpecifiedButOnlyContainX509(ProtocolVersi MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.X509, CertificateType.X509, - new short[] {CertificateType.X509}, - new short[] {CertificateType.X509}, + new short[]{ CertificateType.X509 }, + new short[]{ CertificateType.X509 }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.X509, - new short[] {CertificateType.X509}, + new short[]{ CertificateType.X509 }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -103,14 +103,14 @@ private void testBothSidesUseRawKey(ProtocolVersion tlsVersion) throws Exception MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -131,7 +131,7 @@ private void testServerUsesRawKeyAndClientIsAnonymous(ProtocolVersion tlsVersion MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, (short) -1, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, null, generateKeyPair(), tlsVersion); @@ -159,7 +159,7 @@ private void testServerUsesRawKeyAndClientUsesX509(ProtocolVersion tlsVersion) t MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.X509, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, null, generateKeyPair(), tlsVersion); @@ -188,13 +188,13 @@ private void testServerUsesX509AndClientUsesRawKey(ProtocolVersion tlsVersion) t CertificateType.X509, CertificateType.RawPublicKey, null, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -218,13 +218,13 @@ private void testClientSendsClientCertExtensionButServerHasNoCommonTypes(Protoco CertificateType.X509, CertificateType.RawPublicKey, null, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.X509, - new short[] {CertificateType.X509}, + new short[]{ CertificateType.X509 }, generateKeyPair(), tlsVersion); pumpData(client, server); @@ -253,14 +253,14 @@ private void testClientSendsServerCertExtensionButServerHasNoCommonTypes(Protoco MockRawKeysTlsClient client = new MockRawKeysTlsClient( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, null, generateKeyPair(), tlsVersion); MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.X509, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, generateKeyPair(), tlsVersion); pumpData(client, server); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TlsServerRawKeysTest.java b/tls/src/test/java/org/bouncycastle/tls/test/TlsServerRawKeysTest.java index 716a428b40..1375748a1d 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/TlsServerRawKeysTest.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/TlsServerRawKeysTest.java @@ -66,7 +66,7 @@ public void run() MockRawKeysTlsServer server = new MockRawKeysTlsServer( CertificateType.RawPublicKey, CertificateType.RawPublicKey, - new short[] {CertificateType.RawPublicKey}, + new short[]{ CertificateType.RawPublicKey }, new Ed25519PrivateKeyParameters(new SecureRandom()), tlsVersion); TlsServerProtocol serverProtocol = new TlsServerProtocol(s.getInputStream(), s.getOutputStream()); diff --git a/tls/src/test/java/org/bouncycastle/tls/test/TlsTestUtils.java b/tls/src/test/java/org/bouncycastle/tls/test/TlsTestUtils.java index 55059c8ebc..84ab7539ee 100644 --- a/tls/src/test/java/org/bouncycastle/tls/test/TlsTestUtils.java +++ b/tls/src/test/java/org/bouncycastle/tls/test/TlsTestUtils.java @@ -29,6 +29,7 @@ import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.crypto.util.PrivateKeyFactory; +import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.Certificate; import org.bouncycastle.tls.CertificateEntry; @@ -197,6 +198,11 @@ static String getResourceName(short signatureAlgorithm) throws IOException return "rsa_pss_384"; case SignatureAlgorithm.rsa_pss_pss_sha512: return "rsa_pss_512"; + + // TODO[RFC 9189] Choose names here and apply reverse mappings in getCACertResource(String) + case SignatureAlgorithm.gostr34102012_256: + case SignatureAlgorithm.gostr34102012_512: + default: throw new TlsFatalAlert(AlertDescription.internal_error); } @@ -488,7 +494,7 @@ else if (EdECObjectIdentifiers.id_Ed448.equals(oid)) static PemObject loadPemResource(String resource) throws IOException { - InputStream s = TlsTestUtils.class.getResourceAsStream(resource); + InputStream s = TestResourceFinder.findTestResource("tls/credentials", resource); PemReader p = new PemReader(new InputStreamReader(s)); PemObject o = p.readPemObject(); p.close(); diff --git a/tls/src/test/jdk1.4/org/bouncycastle/tls/test/TlsTestUtils.java b/tls/src/test/jdk1.4/org/bouncycastle/tls/test/TlsTestUtils.java index 761a06d9b0..79c3e344d0 100644 --- a/tls/src/test/jdk1.4/org/bouncycastle/tls/test/TlsTestUtils.java +++ b/tls/src/test/jdk1.4/org/bouncycastle/tls/test/TlsTestUtils.java @@ -29,6 +29,7 @@ import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.crypto.util.PrivateKeyFactory; +import org.bouncycastle.test.TestResourceFinder; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.Certificate; import org.bouncycastle.tls.CertificateEntry; @@ -488,7 +489,7 @@ else if (EdECObjectIdentifiers.id_Ed448.equals(oid)) static PemObject loadPemResource(String resource) throws IOException { - InputStream s = TlsTestUtils.class.getResourceAsStream(resource); + InputStream s = TestResourceFinder.findTestResource("tls/credentials", resource); PemReader p = new PemReader(new InputStreamReader(s)); PemObject o = p.readPemObject(); p.close(); diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/README.txt b/tls/src/test/resources/org/bouncycastle/tls/test/README.txt deleted file mode 100755 index 538325645f..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/README.txt +++ /dev/null @@ -1,181 +0,0 @@ -# The key and certificate .pem files here were generated using GnuTLS certtool and the accompanying -# template files. (Note that the ed25519 files needed GnuTLS 3.6+, 3.6.12+ for ed448) - -# CA (signing) credentials: - - certtool --generate-privkey --outfile x509-ca-key-dsa.pem \ - --pkcs8 --password '' --dsa --bits 2048 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-dsa.pem \ - --load-privkey x509-ca-key-dsa.pem --hash sha256 - - certtool --generate-privkey --outfile x509-ca-key-ecdsa.pem \ - --pkcs8 --password '' --ecdsa --curve secp256r1 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-ecdsa.pem \ - --load-privkey x509-ca-key-ecdsa.pem --hash sha256 - - certtool --generate-privkey --outfile x509-ca-key-ed25519.pem \ - --pkcs8 --password '' --key-type=ed25519 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-ed25519.pem \ - --load-privkey x509-ca-key-ed25519.pem - - certtool --generate-privkey --outfile x509-ca-key-ed448.pem \ - --pkcs8 --password '' --key-type=ed448 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-ed448.pem \ - --load-privkey x509-ca-key-ed448.pem - - certtool --generate-privkey --outfile x509-ca-key-rsa.pem \ - --pkcs8 --password '' --rsa --bits 2048 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-rsa.pem \ - --load-privkey x509-ca-key-rsa.pem --hash sha256 - - certtool --generate-privkey --outfile x509-ca-key-rsa_pss_256.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha256 --salt-size=32 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-rsa_pss_256.pem \ - --load-privkey x509-ca-key-rsa_pss_256.pem - - certtool --generate-privkey --outfile x509-ca-key-rsa_pss_384.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha384 --salt-size=48 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-rsa_pss_384.pem \ - --load-privkey x509-ca-key-rsa_pss_384.pem - - certtool --generate-privkey --outfile x509-ca-key-rsa_pss_512.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha512 --salt-size=64 - certtool --generate-self-signed --template ca.tmpl --outfile x509-ca-rsa_pss_512.pem \ - --load-privkey x509-ca-key-rsa_pss_512.pem - -# Client agreement credentials: - - certtool --generate-privkey --outfile x509-client-key-ecdh.pem \ - --pkcs8 --password '' --ecc --curve secp256r1 - certtool --generate-certificate --template client_agree.tmpl --outfile x509-client-ecdh.pem \ - --load-privkey x509-client-key-ecdh.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-ecdsa.pem --load-ca-certificate x509-ca-ecdsa.pem - -# Client signing credentials: - - certtool --generate-privkey --outfile x509-client-key-dsa.pem \ - --pkcs8 --password '' --dsa --bits 2048 - certtool --generate-certificate --template client_sign.tmpl --outfile x509-client-dsa.pem \ - --load-privkey x509-client-key-dsa.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-dsa.pem --load-ca-certificate x509-ca-dsa.pem - - certtool --generate-privkey --outfile x509-client-key-ecdsa.pem \ - --pkcs8 --password '' --ecdsa --curve secp256r1 - certtool --generate-certificate --template client_sign.tmpl --outfile x509-client-ecdsa.pem \ - --load-privkey x509-client-key-ecdsa.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-ecdsa.pem --load-ca-certificate x509-ca-ecdsa.pem - - certtool --generate-privkey --outfile x509-client-key-ed25519.pem \ - --pkcs8 --password '' --key-type=ed25519 - certtool --generate-certificate --template client_sign.tmpl --outfile x509-client-ed25519.pem \ - --load-privkey x509-client-key-ed25519.pem \ - --load-ca-privkey x509-ca-key-ed25519.pem --load-ca-certificate x509-ca-ed25519.pem - - certtool --generate-privkey --outfile x509-client-key-ed448.pem \ - --pkcs8 --password '' --key-type=ed448 - certtool --generate-certificate --template client_sign.tmpl --outfile x509-client-ed448.pem \ - --load-privkey x509-client-key-ed448.pem \ - --load-ca-privkey x509-ca-key-ed448.pem --load-ca-certificate x509-ca-ed448.pem - - certtool --generate-privkey --outfile x509-client-key-rsa.pem \ - --pkcs8 --password '' --rsa --bits 2048 - certtool --generate-certificate --template client_sign.tmpl --outfile x509-client-rsa.pem \ - --load-privkey x509-client-key-rsa.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-rsa.pem --load-ca-certificate x509-ca-rsa.pem - - certtool --generate-privkey --outfile x509-client-key-rsa_pss_256.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha256 --salt-size=32 - certtool --generate-certificate --template client_sign.tmpl \ - --outfile x509-client-rsa_pss_256.pem \ - --load-privkey x509-client-key-rsa_pss_256.pem \ - --load-ca-privkey x509-ca-key-rsa_pss_256.pem \ - --load-ca-certificate x509-ca-rsa_pss_256.pem - - certtool --generate-privkey --outfile x509-client-key-rsa_pss_384.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha384 --salt-size=48 - certtool --generate-certificate --template client_sign.tmpl \ - --outfile x509-client-rsa_pss_384.pem \ - --load-privkey x509-client-key-rsa_pss_384.pem \ - --load-ca-privkey x509-ca-key-rsa_pss_384.pem \ - --load-ca-certificate x509-ca-rsa_pss_384.pem - - certtool --generate-privkey --outfile x509-client-key-rsa_pss_512.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha512 --salt-size=64 - certtool --generate-certificate --template client_sign.tmpl \ - --outfile x509-client-rsa_pss_512.pem \ - --load-privkey x509-client-key-rsa_pss_512.pem \ - --load-ca-privkey x509-ca-key-rsa_pss_512.pem \ - --load-ca-certificate x509-ca-rsa_pss_512.pem - -# Server agreement credentials: - - certtool --generate-privkey --outfile x509-server-key-ecdh.pem \ - --pkcs8 --password '' --ecc --curve secp256r1 - certtool --generate-certificate --template server_agree.tmpl --outfile x509-server-ecdh.pem \ - --load-privkey x509-server-key-ecdh.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-ecdsa.pem --load-ca-certificate x509-ca-ecdsa.pem - -# Server encryption credentials: - - certtool --generate-privkey --outfile x509-server-key-rsa-enc.pem \ - --pkcs8 --password '' --rsa --bits 2048 - certtool --generate-certificate --outfile x509-server-rsa-enc.pem \ - --load-privkey x509-server-key-rsa-enc.pem --template server_enc.tmpl \ - --load-ca-privkey x509-ca-key-rsa.pem --load-ca-certificate x509-ca-rsa.pem \ - --hash sha256 - -# Server signing credentials: - - certtool --generate-privkey --outfile x509-server-key-dsa.pem \ - --pkcs8 --password '' --dsa --bits 2048 - certtool --generate-certificate --template server_sign.tmpl --outfile x509-server-dsa.pem \ - --load-privkey x509-server-key-dsa.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-dsa.pem --load-ca-certificate x509-ca-dsa.pem - - certtool --generate-privkey --outfile x509-server-key-ecdsa.pem \ - --pkcs8 --password '' --ecdsa --curve secp256r1 - certtool --generate-certificate --template server_sign.tmpl --outfile x509-server-ecdsa.pem \ - --load-privkey x509-server-key-ecdsa.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-ecdsa.pem --load-ca-certificate x509-ca-ecdsa.pem - - certtool --generate-privkey --outfile x509-server-key-ed25519.pem \ - --pkcs8 --password '' --key-type=ed25519 - certtool --generate-certificate --template server_sign.tmpl --outfile x509-server-ed25519.pem \ - --load-privkey x509-server-key-ed25519.pem \ - --load-ca-privkey x509-ca-key-ed25519.pem --load-ca-certificate x509-ca-ed25519.pem - - certtool --generate-privkey --outfile x509-server-key-ed448.pem \ - --pkcs8 --password '' --key-type=ed448 - certtool --generate-certificate --template server_sign.tmpl --outfile x509-server-ed448.pem \ - --load-privkey x509-server-key-ed448.pem \ - --load-ca-privkey x509-ca-key-ed448.pem --load-ca-certificate x509-ca-ed448.pem - - certtool --generate-privkey --outfile x509-server-key-rsa-sign.pem \ - --pkcs8 --password '' --rsa --bits 2048 - certtool --generate-certificate --template server_sign.tmpl --outfile x509-server-rsa-sign.pem \ - --load-privkey x509-server-key-rsa-sign.pem --hash sha256 \ - --load-ca-privkey x509-ca-key-rsa.pem --load-ca-certificate x509-ca-rsa.pem - - certtool --generate-privkey --outfile x509-server-key-rsa_pss_256.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha256 --salt-size=32 - certtool --generate-certificate --template server_sign.tmpl \ - --outfile x509-server-rsa_pss_256.pem \ - --load-privkey x509-server-key-rsa_pss_256.pem \ - --load-ca-privkey x509-ca-key-rsa_pss_256.pem \ - --load-ca-certificate x509-ca-rsa_pss_256.pem - - certtool --generate-privkey --outfile x509-server-key-rsa_pss_384.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha384 --salt-size=48 - certtool --generate-certificate --template server_sign.tmpl \ - --outfile x509-server-rsa_pss_384.pem \ - --load-privkey x509-server-key-rsa_pss_384.pem \ - --load-ca-privkey x509-ca-key-rsa_pss_384.pem \ - --load-ca-certificate x509-ca-rsa_pss_384.pem - - certtool --generate-privkey --outfile x509-server-key-rsa_pss_512.pem \ - --pkcs8 --password '' --key-type='rsa-pss' --bits=2048 --hash=sha512 --salt-size=64 - certtool --generate-certificate --template server_sign.tmpl \ - --outfile x509-server-rsa_pss_512.pem \ - --load-privkey x509-server-key-rsa_pss_512.pem \ - --load-ca-privkey x509-ca-key-rsa_pss_512.pem \ - --load-ca-certificate x509-ca-rsa_pss_512.pem diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/ca.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/ca.tmpl deleted file mode 100644 index 72e41e69ee..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/ca.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle TLS Test CA -ca -cert_signing_key -expiration_days = 7301 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/client_agree.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/client_agree.tmpl deleted file mode 100644 index 1718041888..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/client_agree.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle Test Client -tls_www_client -key_agreement -expiration_days = 7300 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/client_enc.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/client_enc.tmpl deleted file mode 100644 index 1a6f2efd8d..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/client_enc.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle Test Client -tls_www_client -encryption_key -expiration_days = 7300 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/client_sign.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/client_sign.tmpl deleted file mode 100644 index 5a320b1113..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/client_sign.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle Test Client -tls_www_client -signing_key -expiration_days = 7300 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/server_agree.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/server_agree.tmpl deleted file mode 100644 index 44f12f6509..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/server_agree.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle Test Server -tls_www_server -key_agreement -expiration_days = 7300 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/server_enc.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/server_enc.tmpl deleted file mode 100644 index 4bfc58e073..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/server_enc.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle Test Server -tls_www_server -encryption_key -expiration_days = 7300 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/server_sign.tmpl b/tls/src/test/resources/org/bouncycastle/tls/test/server_sign.tmpl deleted file mode 100644 index 1d12addabc..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/server_sign.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -cn = BouncyCastle Test Server -tls_www_server -signing_key -expiration_days = 7300 diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-dsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-dsa.pem deleted file mode 100644 index d9cb013a2a..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-dsa.pem +++ /dev/null @@ -1,26 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEdDCCBBqgAwIBAgIMWYGU7zZX3YAzRZ8VMAsGCWCGSAFlAwQDAjAjMSEwHwYD -VQQDExhCb3VuY3lDYXN0bGUgVExTIFRlc3QgQ0EwHhcNMTcwODAyMDkwMTM1WhcN -MzcwNzI5MDkwMTM1WjAjMSEwHwYDVQQDExhCb3VuY3lDYXN0bGUgVExTIFRlc3Qg -Q0EwggNHMIICOQYHKoZIzjgEATCCAiwCggEBAO5dNk+YfyPOeIK54F9Wg6Zl5+cu -80tSk1fZBSQE1nFBblnGifl39LTmwkHL7XNZmUUFtrScY7Qlk0/cRsEqsl647fAy -XNhqpZAOMPJs4NBx6nzQvKlprxU9JYO5kvTIoJNBR4GCUDxX/DWLffFqvwbBmrZ3 -BgNAHhAHj/wDm0sfxKDXHgfUwmVJgBOne7xwh86SJJojw+MN33ILuSfNFePv2AeQ -kw+bY93tPpouyfskyBLdWs7DeGXmjftFSmpS68j36RAL0+4QZVwDyX/aIwK1bxAH -XLgRnono7NfGxzqlPiQXfb5ewUmZPyjJ3P06WMU3kgj6ZMoyfmJOHCSwjAECIQCg -NiET6OM1ljsc4tvOXtDSyXXqQ4YtRT5o41Gal8kv+QKCAQAbvM2Az1+PzOhrySA5 -PATwWWDMIXlxFx3U1gXIczu4lGGRaoVzfmSGsDZ6A/0j+/ZtmpjGH3B+jb0Rab0n -yZBDUzK+39w+YI7s+K6yGkKlSuyhpB/UokDP0h5Pf6MEVAU2bIcuuWTLMJmleWLw -zHKJTjUDnrC6txeVAbsW+O4l04jMHLTZMXg2OTk9urUtJzeJNkEEMNA8sv7h+yrA -oX2FqvhfDg/oLdfwXQULkKJc/ec6IQaXrtHm+oYwDQxsr9ap4FlET1nz91MMAXon -hB2Yfl7dRKJtKMUKGWGbCliTnJAPUHI1URltnEg387G/YbnnEBUnZlNBJeDrpZFg -+v2ZA4IBBgACggEBAJQi1dv4plwRKrP2fU/76FLcx++60cA4oajNm0f4Vyyaz2xF -7hPiFNj2H0nLNJAtPtdn/wC7KHNWmDx0OiUFIseAqPPoQvfaSrFun1F2iUJhlrKU -FOJ3RC2URoD+M7IbR1SXAyuWOVenhoYyky1mausApUhUjoLO3mMOyBDdXMGWMq7p -SHfyziAnySzwZ2bwOrVz4XL41w4cPbjdEzd4MLIfpPaqqW43y4MNlgLLspm9vBO5 -6Fbq9c0bDUa18jkSi7DU7uH43S9tq3HrPQh127XZ5SstNPU2uV0o+ZXAS8V9sBOM -LGZMjkiQ8bozYtUVAlhLFBnzMB/BOCWxe2yJGSyjQzBBMA8GA1UdEwEB/wQFMAMB -Af8wDwYDVR0PAQH/BAUDAwcEADAdBgNVHQ4EFgQUAOVmarDrz1YtyjvnX4C9cDcX -lagwCwYJYIZIAWUDBAMCA0cAMEQCIFEz1ogza6zKwImQS9tKVlPNjU4QSDEfPjZP -aSwIVMCyAiB+TcGoJvBEAdkzIeQQDdQLldrR+tO/WbayMeqPZHG6ww== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ecdsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ecdsa.pem deleted file mode 100644 index 019ada2707..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ecdsa.pem +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBgzCCASmgAwIBAgIMWYGU7zek17Bcz64zMAoGCCqGSM49BAMCMCMxITAfBgNV -BAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzVaFw0z -NzA3MjkwOTAxMzVaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBD -QTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABDOjvFecZj9RsxsIZSygfmv/GX9M -oJkQeMk+sI6QRVv7YbzL7QUxKa4gRb2x2e3iKPi+Mi2x2wGAPJajJO6nj8ujQzBB -MA8GA1UdEwEB/wQFMAMBAf8wDwYDVR0PAQH/BAUDAwcEADAdBgNVHQ4EFgQU0ma/ -FGcW5gGlL//B26Xmj0JISecwCgYIKoZIzj0EAwIDSAAwRQIhAJPFYIENHNONgDNy -1565P/2N0TMAkcENL2zyCEDnYVG4AiBiA3BuThR1Rgnvn1qRGaivzoIiMvDVRQb7 -p76OkZ8Igw== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ed25519.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ed25519.pem deleted file mode 100644 index c117a2649f..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ed25519.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBSjCB/aADAgECAhQ4EsBmtAbEpUqx/8m96XRPinrybTAFBgMrZXAwIzEhMB8G -A1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MDgyMzA5Mjk0N1oX -DTM4MDgxOTA5Mjk0N1owIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0 -IENBMCowBQYDK2VwAyEA8ZleePPCqzYeCARxwHP10sYfQhcCQ4YXjyOxrb53I0qj -QzBBMA8GA1UdEwEB/wQFMAMBAf8wDwYDVR0PAQH/BAUDAwcEADAdBgNVHQ4EFgQU -6nm+PvoHITBuh26gdYBbNqOczWYwBQYDK2VwA0EAoUgBYkz0bcLAC+kTmbwE05ga -u2SmQtPaiXGykqY+3RhoZVthxQyEzWT0N5KJ322l6mjs0CZRat0ai4hR1Yj7BA== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ed448.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ed448.pem deleted file mode 100644 index e72fcc6d98..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-ed448.pem +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBljCCARagAwIBAgIUWxqMqdy/tO71K3Iz4GYJiWrc42wwBQYDK2VxMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0yMDAyMTMwNzMzMDJa -Fw00MDAyMDkwNzMzMDJaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVz -dCBDQTBDMAUGAytlcQM6AKSetNrq+LCrx62FFnDlmUG/gZUa6LkaIHnfVM3w7/Wl -c1RONMpgGRUeNMqM8YBlgDzUrHjVkHfOAKNDMEEwDwYDVR0TAQH/BAUwAwEB/zAP -BgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBS+BSv++BEWlTJ53q6rwnDLVnR5JTAF -BgMrZXEDcwCFAtJNOZDtSYHm/Mf/L2PEbXNDDNrieJGWbixz/QXYoXjNBFB0D521 -IGH0o6Gdh0ZaQvdktpXc9wDs9xAbzh/w6+hLROTj8UvxyvPuZbGgVYH/tvE++NH/ -H0EQMi0FnLI/iBGv/bEPm8VJ1e24qEiEAAA= ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-dsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-dsa.pem deleted file mode 100644 index 4c378da7a6..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-dsa.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICZQIBADCCAjkGByqGSM44BAEwggIsAoIBAQDuXTZPmH8jzniCueBfVoOmZefn -LvNLUpNX2QUkBNZxQW5Zxon5d/S05sJBy+1zWZlFBba0nGO0JZNP3EbBKrJeuO3w -MlzYaqWQDjDybODQcep80Lypaa8VPSWDuZL0yKCTQUeBglA8V/w1i33xar8GwZq2 -dwYDQB4QB4/8A5tLH8Sg1x4H1MJlSYATp3u8cIfOkiSaI8PjDd9yC7knzRXj79gH -kJMPm2Pd7T6aLsn7JMgS3VrOw3hl5o37RUpqUuvI9+kQC9PuEGVcA8l/2iMCtW8Q -B1y4EZ6J6OzXxsc6pT4kF32+XsFJmT8oydz9OljFN5II+mTKMn5iThwksIwBAiEA -oDYhE+jjNZY7HOLbzl7Q0sl16kOGLUU+aONRmpfJL/kCggEAG7zNgM9fj8zoa8kg -OTwE8FlgzCF5cRcd1NYFyHM7uJRhkWqFc35khrA2egP9I/v2bZqYxh9wfo29EWm9 -J8mQQ1Myvt/cPmCO7PiushpCpUrsoaQf1KJAz9IeT3+jBFQFNmyHLrlkyzCZpXli -8MxyiU41A56wurcXlQG7FvjuJdOIzBy02TF4Njk5Pbq1LSc3iTZBBDDQPLL+4fsq -wKF9har4Xw4P6C3X8F0FC5CiXP3nOiEGl67R5vqGMA0MbK/WqeBZRE9Z8/dTDAF6 -J4QdmH5e3USibSjFChlhmwpYk5yQD1ByNVEZbZxIN/Oxv2G55xAVJ2ZTQSXg66WR -YPr9mQQjAiEAnZYHGZPTcKWTzPTfMa5UQkZgqKU1jqyOOWWtHc50fPE= ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ecdsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ecdsa.pem deleted file mode 100644 index 42132d48f5..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ecdsa.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgXP0gFZhM/8/F0imI -9EPD/er+bEFS8m2nY9JzJlricXigCgYIKoZIzj0DAQehRANCAAQzo7xXnGY/UbMb -CGUsoH5r/xl/TKCZEHjJPrCOkEVb+2G8y+0FMSmuIEW9sdnt4ij4vjItsdsBgDyW -oyTup4/L ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ed25519.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ed25519.pem deleted file mode 100644 index 027bb835ea..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ed25519.pem +++ /dev/null @@ -1,25 +0,0 @@ -Public Key Info: - Public Key Algorithm: EdDSA (Ed25519) - Key Security Level: High (256 bits) - -curve: Ed25519 -private key: - a9:19:76:8a:f7:cf:95:c7:e3:94:3c:ce:3c:71:59:44 - 89:08:34:e5:49:0b:0a:44:56:d6:1d:05:f4:af:5d:85 - - -x: - f1:99:5e:78:f3:c2:ab:36:1e:08:04:71:c0:73:f5:d2 - c6:1f:42:17:02:43:86:17:8f:23:b1:ad:be:77:23:4a - - - -Public Key PIN: - pin-sha256:XFgN/8/bw68mn6K+U4zDmMa+HSGjXI0bejzTOxFQf0U= -Public Key ID: - sha256:5c580dffcfdbc3af269fa2be538cc398c6be1d21a35c8d1b7a3cd33b11507f45 - sha1:ea79be3efa0721306e876ea075805b36a39ccd66 - ------BEGIN PRIVATE KEY----- -MC4CAQAwBQYDK2VwBCIEIKkZdor3z5XH45Q8zjxxWUSJCDTlSQsKRFbWHQX0r12F ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ed448.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ed448.pem deleted file mode 100644 index 6974289736..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-ed448.pem +++ /dev/null @@ -1,28 +0,0 @@ -Public Key Info: - Public Key Algorithm: EdDSA (Ed448) - Key Security Level: Ultra (456 bits) - -curve: Ed448 -private key: - d8:36:a1:a6:12:8b:25:7a:86:eb:8a:b2:93:4a:71:df - 44:b7:9e:be:59:09:61:58:43:d2:3f:80:04:59:7b:37 - 89:cc:d9:6b:84:26:ae:b9:75:3c:b7:6d:eb:4b:c9:d8 - 36:94:5e:63:44:7b:7f:4b:e0: - -x: - a4:9e:b4:da:ea:f8:b0:ab:c7:ad:85:16:70:e5:99:41 - bf:81:95:1a:e8:b9:1a:20:79:df:54:cd:f0:ef:f5:a5 - 73:54:4e:34:ca:60:19:15:1e:34:ca:8c:f1:80:65:80 - 3c:d4:ac:78:d5:90:77:ce:00: - - -Public Key PIN: - pin-sha256:fnp0p/r6DXkqUgGSXDJih9BAOy/+ImGTT5dCbfH6H4w= -Public Key ID: - sha256:7e7a74a7fafa0d792a5201925c326287d0403b2ffe2261934f97426df1fa1f8c - sha1:be052bfef81116953279deaeabc270cb56747925 - ------BEGIN PRIVATE KEY----- -MEcCAQAwBQYDK2VxBDsEOdg2oaYSiyV6huuKspNKcd9Et56+WQlhWEPSP4AEWXs3 -iczZa4Qmrrl1PLdt60vJ2DaUXmNEe39L4A== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa.pem deleted file mode 100644 index 9b51726a1a..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDjLlJpiydqUOH2 -IxH7iI9dUzJxvHaknGqXP8lPcxwg5+Q0CRjmv1+Y2KCV+JNj215OW23JNnGguCe/ -xlkboBnOCnDlSLQJp8W1cyarabHUa1VL086nL2kmTRxIElj+91ppQAl+sSB0cgba -/j8KYoO93mZDlXBjrG7FpYn31UNH9H8/wBrGIeSFgTZSHwTlsDhAQyWr5bGK1RgM -NTLl8ZJ8m7I1xUashTTxOkoXd1t3rXqPhTr0LMqKZl+hXD/hDmhUMUkO8kfsTbK3 -gssYuNIT37MDuk4oTfYS3VbdwvjhwycNsEdsTPksLFvB7uIxIttbmpEJfOOs/l3Y -FaPg9793AgMBAAECggEBANR2XtacMFmKmTijZc7y0Pk7tKKP2flq23jmS7QE+FqB -5HcRxvsOIS6F8fEvz1AFObZYZV1XkH75mxsMOgvO+DMsqpaUHuQkxo9CyPhoWcpK -MzQ+Ozc57MHIPdndZuPUmvZx0C9vIeYlOeoW+wgQSBsK4mL0YG6nNdWcUmK4TTr9 -V62ZvqDYoZjtTsAoLkUVJAgByN3XNzc70RQKN5OyCC8iib0JpLEeLdOkGgxWE7/n -KNLZ/9tbK9O4Mn3BWwZsTt8Hve0m/G9CbjlriEz9PYRBEg+JP6FmQIB5l0mjyRMQ -F5uRqiZt6r1uUGwUifNDOqNyJzSolj32u+OG3m8/6qkCgYEA+Tof5Wtuq9Oc5zCF -oVzm3cT1DZy3kJdGZWlMekLC9NMXhnA2huuNkln8Ph2qRx5pxmomRvX8ThaHNUdg -IRjzUomTQ0IWPkn+7TT6CmeSIEOoT4Tyw/xVvBHKm/yHKxHsCkcSIzt1cXS1SGU7 -Dfsy2C+FBjkcW6UBHkNKUMxce/0CgYEA6VrShFfora0fUOibaas/YG7XnqQzFyvw -mcBpqAbUXTneFdyssZDyfmQpE44KCywfPczz+34zIRkjnBX6mLyWx5rINE0KpOBK -uwS2ob1g6J1x6I6btBzIhhgR+Zj9zxhD5f+jYmmBCU3yTvWMXL4c5YsaWvlG8doq -bNo40cQykYMCgYEAmK8pV03n8VClMWWimGbn8Tl2v64hL23d7McD2WsJMSAZq30X -irTIeL60MAHQjd1uA+aIKLUOq3BVySg/FkfI2en61BuqsOJ4US5BeRpWhXmtpXnX -mIYAqEVmEQY2cQZ7yxgbXoZQvv83CHEsKraYQaVrI5Ldcq+17apf3vw0NKkCgYBH -u6WPDT73dIp14qszlnLLAAfEOpGCA/3YJa/U+RR6+/jrG4TyqK4CcGO4ISexO4T3 -CHPP0YGCISozJwZ7wS1QeqIkgbJN8KzIRLCnk4GgwBVt+bifa2Gw5uFPqtoKuVjV -8PmWnPwPkih0YUMel0pmvZYCdTJ70ibMg2CICxnIZQKBgQC7aMgcL5ORB/8fgOdy -g0at1fmz5kKKbv0Z9cmk7trKW67NDM5kwVyFdUuc5Vp7alkRyW4SZPtwpOG+d5Xt -M0DM77Qvom+sIYq5C5eSHPU6py2Ipn5HZzkHRnAM8qw3OrL6+iFklQUKEBXeqVEq -6MfsH8P1/RIRfvcOMhPrNEzpTg== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_256.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_256.pem deleted file mode 100644 index 9243a1e32a..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_256.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA256 - Salt Length: 32 - Key Security Level: Medium (2048 bits) - -modulus: - 00:b7:b4:9a:4d:2d:3f:08:b8:1e:55:d6:b0:b2:b7:d0 - 33:cc:bb:de:56:24:04:1d:73:ac:6a:32:db:af:26:4f - ef:b1:d6:10:90:79:dc:89:ac:60:e3:94:54:19:04:54 - 17:ea:18:0e:d9:46:be:60:9f:e6:33:ff:6e:60:6a:35 - c6:2d:dd:06:82:d5:80:c9:88:07:2f:27:4b:04:13:ba - 4b:69:92:ce:bc:00:be:42:2c:e2:35:8d:60:11:66:3c - 24:f8:3a:13:ad:49:e7:12:ca:c6:2a:52:84:ed:3d:7d - 1e:06:de:a4:64:d6:17:14:b1:19:63:a0:e1:7c:49:d3 - 41:73:29:f8:b5:75:e0:93:fa:e3:df:3b:82:77:5e:83 - cb:da:52:26:eb:c3:20:13:11:6d:e9:aa:a5:d7:b6:c3 - a1:a5:04:fa:6e:ee:4f:39:52:4d:18:f9:ab:87:4a:4e - d9:34:a7:c4:df:f5:1b:b6:57:71:7f:c3:c8:4f:2c:00 - c0:6e:e8:74:35:e2:71:1f:ef:c6:c1:62:7a:65:e7:c9 - c7:42:14:5f:16:c1:ab:4d:32:e5:e2:7c:38:a2:21:02 - 69:a3:81:f4:c8:78:48:58:0a:5d:99:85:f5:e6:2a:37 - be:23:e5:ff:15:ba:39:42:ac:9d:d0:11:7e:e4:2b:55 - db: - -public exponent: - 01:00:01: - -private exponent: - 00:9a:2e:3e:02:e0:22:b3:52:b4:43:1e:f9:16:46:27 - bc:11:ec:eb:62:28:c0:3b:67:c6:21:2b:a6:2d:8e:5e - 30:b2:75:13:59:ee:ad:25:ef:43:32:3e:5f:86:cf:97 - 34:ab:08:9e:0d:c5:ce:2a:92:89:46:c2:ef:04:84:9f - b5:40:f0:ec:72:0a:77:18:ad:ce:39:c9:24:b0:bb:4d - f3:d5:1b:9d:df:34:50:7a:81:e9:29:41:0a:8c:0f:de - 12:b9:33:25:28:9f:8a:0c:bf:9b:2a:12:2f:f6:5d:51 - 11:4e:7a:b6:46:db:58:6b:c9:67:a1:b2:79:0d:33:78 - d5:5d:69:38:91:d9:f0:37:28:da:67:56:96:dd:77:d4 - f0:cd:33:9a:a3:7d:cc:6a:5c:44:c1:bd:e3:d3:34:71 - 70:b1:ed:67:56:cc:02:28:3b:e2:2b:6d:d0:eb:69:9b - e5:d9:27:e8:fc:2a:03:14:e1:f7:76:3f:b7:a7:87:1c - 78:84:9e:17:60:71:84:b7:67:83:c5:41:27:40:18:96 - 3c:c5:13:9f:ff:fd:3f:ac:30:cd:e5:f7:b5:cb:ac:16 - 39:85:05:c1:59:46:ce:df:e8:67:9a:a2:56:88:73:a8 - 34:23:b2:54:2d:18:2c:c9:16:0c:d0:f6:46:55:9f:2a - 01: - -prime1: - 00:e1:11:b3:58:64:b9:77:3c:b9:f2:95:df:bb:0b:66 - f6:81:31:03:22:cb:eb:5a:a9:38:63:31:ff:f2:75:46 - 9a:dd:be:a7:d0:d4:c8:30:18:bf:6f:bf:c0:01:ba:27 - 0e:34:b2:7f:75:f0:aa:05:69:71:68:03:41:9b:47:5b - 6a:7b:89:ef:f4:e0:84:c0:01:67:5c:46:c6:29:40:3d - 55:15:48:d6:19:e9:22:d2:fd:88:1d:f6:cd:7e:9c:04 - c6:b0:d7:3d:1d:ea:42:44:8c:10:a8:6c:8a:d2:70:6d - b6:fb:9b:1f:ce:d9:ec:3e:1a:3f:ee:02:17:e3:37:74 - 9b: - -prime2: - 00:d0:f3:a9:3a:80:a3:ac:1f:e9:d8:29:f4:2f:1a:7c - d6:61:77:c8:82:cb:fa:64:a0:ce:ef:ec:5c:e9:97:a0 - 1d:28:a6:49:5d:34:59:92:96:c1:b2:c2:14:f5:02:a2 - 2e:b9:ab:df:a7:79:e6:b3:fa:5c:3e:bd:50:b2:e4:c1 - ee:d3:b5:5d:38:a4:f6:d0:81:8a:e1:5a:45:da:19:06 - a3:fa:6a:84:8f:04:f4:56:2a:00:13:2b:76:8d:c1:c8 - d4:eb:42:c0:02:d5:c5:b4:83:7f:36:32:27:93:fc:49 - 11:f4:a3:4d:7d:bd:03:61:e7:40:28:15:10:ad:8f:97 - c1: - -coefficient: - 00:d6:d9:e8:05:2e:4f:3c:27:59:e4:3a:5a:1a:15:59 - 0c:b7:fd:fa:23:ad:c1:64:07:e4:22:ae:35:9b:ac:e8 - 95:34:46:be:38:ba:99:07:4b:52:0f:f2:f9:cd:32:e7 - 99:2d:66:15:f1:f3:51:b5:4e:4a:d5:49:8f:a3:97:43 - ad:60:31:c7:c7:a7:4a:e0:2f:07:fe:40:24:22:5a:4e - 76:ee:ef:df:95:85:e4:5a:81:7a:ab:61:e9:da:51:7e - 2f:dd:d7:83:46:b2:76:13:ef:18:3a:64:45:31:e1:4f - af:6e:f0:6e:34:d2:cf:59:e3:ee:88:f2:22:1e:c8:06 - f6: - -exp1: - 00:96:25:00:c7:cf:2a:0a:e9:70:02:ed:08:bb:f6:f7 - 51:2b:0e:4f:51:3f:48:5a:ca:d8:db:13:d7:f3:1f:59 - 62:a6:db:31:88:96:ea:95:6b:6d:0a:57:98:f7:8d:ff - cf:f2:47:c1:d0:24:24:c8:47:77:68:34:03:e8:5a:ca - 19:57:20:c5:fb:4e:6c:40:ca:ae:f1:58:25:8a:0f:58 - db:11:bf:ed:54:8b:ba:b7:96:7a:df:c2:6d:84:31:00 - de:ab:ca:6a:f3:31:fb:d3:4e:bd:2e:1e:7a:dd:b8:32 - f9:07:10:8d:3f:a9:11:78:bc:7a:39:85:1b:fa:70:5c - 51: - -exp2: - 42:c5:ca:cb:8e:36:3f:98:07:33:73:dc:bb:7c:bc:6e - 09:c1:ac:8a:d7:c2:51:8b:ed:f5:4f:d4:35:35:a6:0e - 0b:62:70:49:5f:a4:4c:2a:ef:05:3f:ee:50:89:a1:e8 - 4a:9f:39:1e:9c:de:f3:9e:cb:01:a5:9f:f7:3b:11:1a - 4f:ff:42:26:0a:d9:70:b2:24:fe:74:c9:a3:b3:a1:a2 - 9f:30:90:e1:df:54:71:80:84:7b:9b:c5:0b:f1:e4:4a - de:4f:7b:6a:ac:83:bc:76:d5:1d:2d:93:e6:3f:95:de - 2e:0e:4d:82:23:f7:c3:be:91:8a:fd:88:51:de:74:41 - - - -Public Key PIN: - pin-sha256:O4J2O7fbEdphitrCWZG7Jyi8t5S4daRsB8YQZknFYWk= -Public Key ID: - sha256:3b82763bb7db11da618adac25991bb2728bcb794b875a46c07c6106649c56169 - sha1:211a88b6de03c00180aadb708899a68f17ceaa6c - ------BEGIN PRIVATE KEY----- -MIIE7wIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgGiAwIBIASCBKkwggSlAgEAAoIBAQC3tJpNLT8IuB5V -1rCyt9AzzLveViQEHXOsajLbryZP77HWEJB53ImsYOOUVBkEVBfqGA7ZRr5gn+Yz -/25gajXGLd0GgtWAyYgHLydLBBO6S2mSzrwAvkIs4jWNYBFmPCT4OhOtSecSysYq -UoTtPX0eBt6kZNYXFLEZY6DhfEnTQXMp+LV14JP64987gndeg8vaUibrwyATEW3p -qqXXtsOhpQT6bu5POVJNGPmrh0pO2TSnxN/1G7ZXcX/DyE8sAMBu6HQ14nEf78bB -Ynpl58nHQhRfFsGrTTLl4nw4oiECaaOB9Mh4SFgKXZmF9eYqN74j5f8VujlCrJ3Q -EX7kK1XbAgMBAAECggEBAJouPgLgIrNStEMe+RZGJ7wR7OtiKMA7Z8YhK6Ytjl4w -snUTWe6tJe9DMj5fhs+XNKsIng3FziqSiUbC7wSEn7VA8OxyCncYrc45ySSwu03z -1Rud3zRQeoHpKUEKjA/eErkzJSifigy/myoSL/ZdURFOerZG21hryWehsnkNM3jV -XWk4kdnwNyjaZ1aW3XfU8M0zmqN9zGpcRMG949M0cXCx7WdWzAIoO+IrbdDraZvl -2Sfo/CoDFOH3dj+3p4cceISeF2BxhLdng8VBJ0AYljzFE5///T+sMM3l97XLrBY5 -hQXBWUbO3+hnmqJWiHOoNCOyVC0YLMkWDND2RlWfKgECgYEA4RGzWGS5dzy58pXf -uwtm9oExAyLL61qpOGMx//J1RprdvqfQ1MgwGL9vv8ABuicONLJ/dfCqBWlxaANB -m0dbanuJ7/TghMABZ1xGxilAPVUVSNYZ6SLS/Ygd9s1+nATGsNc9HepCRIwQqGyK -0nBttvubH87Z7D4aP+4CF+M3dJsCgYEA0POpOoCjrB/p2Cn0Lxp81mF3yILL+mSg -zu/sXOmXoB0opkldNFmSlsGywhT1AqIuuavfp3nms/pcPr1QsuTB7tO1XTik9tCB -iuFaRdoZBqP6aoSPBPRWKgATK3aNwcjU60LAAtXFtIN/NjInk/xJEfSjTX29A2Hn -QCgVEK2Pl8ECgYEAliUAx88qCulwAu0Iu/b3USsOT1E/SFrK2NsT1/MfWWKm2zGI -luqVa20KV5j3jf/P8kfB0CQkyEd3aDQD6FrKGVcgxftObEDKrvFYJYoPWNsRv+1U -i7q3lnrfwm2EMQDeq8pq8zH70069Lh563bgy+QcQjT+pEXi8ejmFG/pwXFECgYBC -xcrLjjY/mAczc9y7fLxuCcGsitfCUYvt9U/UNTWmDgticElfpEwq7wU/7lCJoehK -nzkenN7znssBpZ/3OxEaT/9CJgrZcLIk/nTJo7Ohop8wkOHfVHGAhHubxQvx5Ere -T3tqrIO8dtUdLZPmP5XeLg5NgiP3w76Riv2IUd50QQKBgQDW2egFLk88J1nkOloa -FVkMt/36I63BZAfkIq41m6zolTRGvji6mQdLUg/y+c0y55ktZhXx81G1TkrVSY+j -l0OtYDHHx6dK4C8H/kAkIlpOdu7v35WF5FqBeqth6dpRfi/d14NGsnYT7xg6ZEUx -4U+vbvBuNNLPWePuiPIiHsgG9g== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_384.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_384.pem deleted file mode 100644 index b83a1059cf..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_384.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA384 - Salt Length: 48 - Key Security Level: Medium (2048 bits) - -modulus: - 00:ee:6d:c0:c9:44:dd:94:f8:40:af:9a:f4:43:3e:78 - 45:61:5f:6a:15:23:42:f4:f8:a0:c2:eb:6a:0a:ae:0c - 43:a7:dc:e9:ac:ce:42:c4:c8:f5:4c:de:6c:52:4b:e5 - d3:2b:42:b8:f9:e5:5c:5f:5c:53:2f:0f:f7:f5:3d:04 - ed:2b:50:c9:ab:6b:74:2d:4b:42:71:57:7a:04:83:38 - 97:fa:5b:22:4a:14:d2:0d:dd:5c:66:c9:25:7d:e3:ff - 05:84:02:ea:3c:82:97:45:0f:7c:b3:71:8e:7f:31:8d - b5:eb:5e:b6:0d:91:9b:5d:51:bc:f7:e2:81:a2:5f:46 - 35:cf:9e:64:c4:3c:65:63:f6:ff:15:b0:e7:11:49:fa - c1:cc:d9:54:9b:f8:13:3d:95:ce:f4:7f:58:66:23:cd - bc:11:af:e1:3f:af:d8:5e:16:85:cd:7d:b7:7f:59:fa - ff:29:e6:ef:4f:6e:6b:ef:b0:91:ef:81:63:6f:b2:0c - 2b:47:a6:21:f7:1f:4b:fb:1d:e7:6f:f8:6f:0e:6a:8f - 8a:54:5f:4b:a2:6d:36:20:bb:ba:11:87:06:f3:8d:95 - 6a:10:b7:27:8e:1d:02:b4:ce:1e:c2:09:73:c4:b6:5d - c7:5f:e2:26:bd:4f:cd:7a:b0:c5:c0:d6:82:1f:d4:2e - 59: - -public exponent: - 01:00:01: - -private exponent: - 6a:cf:72:10:f8:2f:c7:9f:9a:e2:d0:28:e2:c2:e6:80 - 36:49:d7:2d:16:f9:d4:e2:58:aa:59:69:cc:d5:01:9b - 81:64:9e:ae:12:4c:a8:f9:59:a2:90:f5:b7:bc:56:7d - ce:20:7a:db:40:1b:ac:80:a0:a7:31:a1:24:14:ac:d3 - 4e:97:47:70:ea:97:45:ff:34:09:b0:65:72:06:12:e1 - 4a:7f:6f:11:fe:d7:c6:ec:46:8b:a9:4a:89:66:0d:05 - bc:88:cd:c4:43:c0:5e:68:bc:b5:6a:86:aa:86:59:74 - 88:b7:8a:18:f4:04:c4:be:6c:48:24:09:6c:e2:ff:81 - 18:5f:a8:85:db:79:b0:14:66:1c:fb:f7:8f:a8:29:79 - 83:79:aa:65:45:05:5a:0f:03:30:e5:75:43:23:23:e1 - eb:09:5d:e6:be:0a:10:bd:34:4a:02:d5:60:f6:51:90 - 30:b5:2d:95:37:0e:aa:fb:8e:f3:4f:b4:2f:54:a4:c1 - 8c:a8:5a:46:0c:85:f0:d5:94:d0:ee:71:a2:c6:d7:b0 - de:81:04:66:43:4c:10:ba:ba:ec:91:57:93:bd:74:4f - d4:ea:96:3b:53:a1:0c:0f:be:7d:70:9c:c2:ae:b2:13 - 4b:2b:c3:c9:8a:56:12:a0:ab:55:e4:4e:90:df:0c:01 - - -prime1: - 00:f8:f5:75:8a:5e:fb:0f:2a:09:42:dc:eb:1e:0d:c9 - 97:6f:30:c9:55:28:af:15:4e:4a:db:9e:cd:17:6a:7f - d1:be:1e:53:2b:79:d9:83:de:96:c9:9b:1f:7e:93:ce - 02:f3:fb:9d:56:a2:19:cf:f2:d0:f2:3b:80:5f:b5:7b - cb:df:d6:26:fb:e8:ba:2b:db:e5:c1:47:98:1d:2e:57 - 5d:26:19:72:2f:48:77:00:1d:8d:72:f6:48:68:97:62 - 0f:5d:30:e0:95:a4:00:34:e4:77:b9:47:81:30:63:48 - 29:64:a0:2f:4f:c0:42:4b:bb:a2:60:7b:ba:e4:79:6b - 81: - -prime2: - 00:f5:2c:0d:7a:8c:17:59:ac:95:20:ca:29:3e:45:23 - 23:6f:25:fe:a3:56:df:23:74:47:cd:38:47:a3:4d:06 - 0e:66:7a:9f:74:cc:86:3e:86:e3:c8:4b:45:09:93:2b - 81:d3:fc:56:a2:29:b3:52:4d:f1:45:69:e2:d3:a3:b1 - 4e:1a:25:bd:1a:6c:2b:57:8a:93:11:b9:e9:6d:11:43 - 2c:aa:22:e9:20:10:bf:e4:fe:a6:c5:30:ec:42:5a:5c - d9:3d:1d:e9:18:7e:10:5b:9d:59:cd:7f:7e:51:5c:c8 - 65:63:8b:4a:54:e8:c1:fa:5c:e9:36:23:20:20:87:0e - d9: - -coefficient: - 00:9f:a9:37:76:c0:24:33:8e:18:92:c5:4c:1e:05:fd - 82:39:d9:40:4d:15:95:7e:92:59:44:1a:99:81:4b:0f - 16:e0:16:99:23:45:91:04:76:f0:98:d7:f5:92:e4:af - 39:3b:6f:49:0b:8f:22:02:aa:3a:da:72:04:9c:a4:cb - 11:1a:44:f4:47:19:ed:a0:9c:94:58:06:cd:ca:b1:ff - 48:7f:bf:2e:23:66:63:0e:cd:0b:a5:43:ee:23:75:32 - d5:93:08:23:51:e3:9e:d2:82:be:9b:c4:6d:53:a9:50 - 66:74:af:11:dd:f2:d5:a6:9f:6e:ca:11:ac:6d:a6:ca - 0b: - -exp1: - 00:ba:47:87:9c:72:77:2e:20:88:ef:73:b7:a5:34:31 - cb:d2:91:d1:83:9b:be:6d:95:b8:63:5e:0e:1d:60:3d - a5:a5:b8:b1:08:8d:d2:d8:5d:db:bb:9c:0b:53:bd:aa - 5f:01:4a:1a:af:30:f9:59:64:59:3d:76:92:16:8b:07 - c7:43:83:cc:85:9e:dc:76:66:c2:21:fd:bc:ee:d0:b6 - e3:e6:d7:11:5e:19:bd:98:e3:83:ec:2a:25:81:c5:0b - c5:6d:38:5e:42:f9:84:82:0f:15:1a:18:4b:ac:f6:0c - 8f:94:50:5b:36:34:28:26:dc:8d:a1:dd:d2:b8:93:b5 - 81: - -exp2: - 5c:07:25:28:12:dd:d0:f3:4f:26:f7:bb:73:7c:50:2c - 44:d4:66:38:b9:ab:18:8b:d5:47:db:10:48:e3:e8:9a - 0f:2d:88:1d:37:88:4c:80:25:90:51:70:a0:9f:75:7d - 4e:2d:31:f7:bc:df:6a:cd:86:fb:1f:3b:dd:65:5c:70 - 8c:b0:0d:c3:95:46:cf:9d:5c:87:12:d9:e3:ee:ce:e0 - 3d:1c:cd:95:13:b4:74:28:82:41:12:94:1c:73:fe:d6 - 2c:72:c5:c4:43:cd:b0:15:e8:57:92:bb:bf:9e:ac:3a - 22:9b:6e:53:60:eb:2f:27:21:03:09:3c:4d:f9:64:41 - - - -Public Key PIN: - pin-sha256:wv5nADHzPA1LzmxBzNO9BTLNYGb9g0W8L55XearJ5C8= -Public Key ID: - sha256:c2fe670031f33c0d4bce6c41ccd3bd0532cd6066fd8345bc2f9e5779aac9e42f - sha1:a9f05d6f61a0f001e874b25a7ed411431c2a89e7 - ------BEGIN PRIVATE KEY----- -MIIE7gIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAqEaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgKiAwIBMASCBKgwggSkAgEAAoIBAQDubcDJRN2U+ECv -mvRDPnhFYV9qFSNC9PigwutqCq4MQ6fc6azOQsTI9UzebFJL5dMrQrj55VxfXFMv -D/f1PQTtK1DJq2t0LUtCcVd6BIM4l/pbIkoU0g3dXGbJJX3j/wWEAuo8gpdFD3yz -cY5/MY216162DZGbXVG89+KBol9GNc+eZMQ8ZWP2/xWw5xFJ+sHM2VSb+BM9lc70 -f1hmI828Ea/hP6/YXhaFzX23f1n6/ynm709ua++wke+BY2+yDCtHpiH3H0v7Hedv -+G8Oao+KVF9Lom02ILu6EYcG842VahC3J44dArTOHsIJc8S2Xcdf4ia9T816sMXA -1oIf1C5ZAgMBAAECggEAas9yEPgvx5+a4tAo4sLmgDZJ1y0W+dTiWKpZaczVAZuB -ZJ6uEkyo+VmikPW3vFZ9ziB620AbrICgpzGhJBSs006XR3Dql0X/NAmwZXIGEuFK -f28R/tfG7EaLqUqJZg0FvIjNxEPAXmi8tWqGqoZZdIi3ihj0BMS+bEgkCWzi/4EY -X6iF23mwFGYc+/ePqCl5g3mqZUUFWg8DMOV1QyMj4esJXea+ChC9NEoC1WD2UZAw -tS2VNw6q+47zT7QvVKTBjKhaRgyF8NWU0O5xosbXsN6BBGZDTBC6uuyRV5O9dE/U -6pY7U6EMD759cJzCrrITSyvDyYpWEqCrVeROkN8MAQKBgQD49XWKXvsPKglC3Ose -DcmXbzDJVSivFU5K257NF2p/0b4eUyt52YPelsmbH36TzgLz+51WohnP8tDyO4Bf -tXvL39Ym++i6K9vlwUeYHS5XXSYZci9IdwAdjXL2SGiXYg9dMOCVpAA05He5R4Ew -Y0gpZKAvT8BCS7uiYHu65HlrgQKBgQD1LA16jBdZrJUgyik+RSMjbyX+o1bfI3RH -zThHo00GDmZ6n3TMhj6G48hLRQmTK4HT/FaiKbNSTfFFaeLTo7FOGiW9GmwrV4qT -EbnpbRFDLKoi6SAQv+T+psUw7EJaXNk9HekYfhBbnVnNf35RXMhlY4tKVOjB+lzp -NiMgIIcO2QKBgQC6R4eccncuIIjvc7elNDHL0pHRg5u+bZW4Y14OHWA9paW4sQiN -0thd27ucC1O9ql8BShqvMPlZZFk9dpIWiwfHQ4PMhZ7cdmbCIf287tC24+bXEV4Z -vZjjg+wqJYHFC8VtOF5C+YSCDxUaGEus9gyPlFBbNjQoJtyNod3SuJO1gQKBgFwH -JSgS3dDzTyb3u3N8UCxE1GY4uasYi9VH2xBI4+iaDy2IHTeITIAlkFFwoJ91fU4t -Mfe832rNhvsfO91lXHCMsA3DlUbPnVyHEtnj7s7gPRzNlRO0dCiCQRKUHHP+1ixy -xcRDzbAV6FeSu7+erDoim25TYOsvJyEDCTxN+WRBAoGBAJ+pN3bAJDOOGJLFTB4F -/YI52UBNFZV+kllEGpmBSw8W4BaZI0WRBHbwmNf1kuSvOTtvSQuPIgKqOtpyBJyk -yxEaRPRHGe2gnJRYBs3Ksf9If78uI2ZjDs0LpUPuI3Uy1ZMII1HjntKCvpvEbVOp -UGZ0rxHd8tWmn27KEaxtpsoL ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_512.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_512.pem deleted file mode 100644 index 1bd1bcfc95..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-key-rsa_pss_512.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA512 - Salt Length: 64 - Key Security Level: Medium (2048 bits) - -modulus: - 00:ea:1f:fc:30:5f:ff:19:db:9a:30:46:1b:fa:34:de - 6b:56:44:ff:a1:06:d1:5c:6a:a7:b9:f8:7d:ac:bc:0f - 2b:9c:d8:9b:90:2d:31:a0:41:c7:74:73:01:ba:ea:e4 - c6:9e:bf:9b:41:62:07:54:b4:53:cb:a2:d7:8b:df:3a - a4:6d:b6:95:71:32:21:ee:3c:9a:9d:9b:9b:4d:d5:ef - d3:70:84:ba:c2:0e:a7:2f:07:aa:29:69:20:46:f8:da - 87:49:e0:cf:00:d3:c0:26:a0:71:35:00:06:45:56:56 - 8f:93:60:75:42:f5:78:61:ee:ad:fb:d2:38:de:79:2d - 9b:5b:07:e6:2b:be:b5:a8:a7:95:df:9f:2a:1a:9f:62 - 55:26:35:53:88:33:8c:1c:f9:93:e6:ea:45:39:3c:09 - 7a:e1:4a:41:de:a6:38:fd:56:e4:d5:0d:ee:ff:28:81 - dc:b0:ca:a9:84:42:5f:7a:68:72:32:1e:05:4f:07:36 - 58:71:76:a4:c8:b3:d2:18:3e:c8:3d:7b:2e:18:44:8c - dc:df:b4:53:54:72:ee:78:11:68:94:92:f6:de:41:5b - 1c:e8:dc:1b:41:fe:8f:b4:7d:8d:59:56:ed:07:96:20 - bd:0b:18:cb:3f:40:d3:02:62:7a:50:2e:52:66:68:ab - a1: - -public exponent: - 01:00:01: - -private exponent: - 33:87:46:a1:fe:fe:ce:5a:1e:dd:71:10:c7:48:cb:8b - 24:39:9b:69:7d:6e:a6:c0:72:99:e3:af:05:4d:7e:a9 - 42:a4:09:d8:f9:99:6a:84:0f:b9:f9:75:f0:05:b2:c4 - 64:3c:17:97:94:53:b8:b8:d7:98:82:06:9e:aa:4a:e5 - d5:9f:d1:d4:50:0c:57:ba:ce:ec:d1:4a:a5:1e:e8:e1 - c8:69:ee:10:b7:d8:e3:e8:f3:f2:99:48:99:56:3c:02 - 7a:a8:17:e7:3e:b3:93:cc:cc:1d:b6:1b:ab:37:0d:66 - 1c:31:a6:9d:4e:19:68:b4:77:66:6d:26:47:10:b4:90 - 88:f9:af:65:d3:16:07:f2:6b:59:6e:ba:03:20:ba:a5 - 80:87:75:ae:92:42:bd:64:e1:5a:48:7b:73:33:c3:70 - 74:cc:14:05:c0:d2:42:01:7f:82:4e:e0:8b:f9:2b:12 - 4d:71:4f:55:86:fd:28:0a:8f:a6:ad:66:32:4b:5e:f3 - 22:58:b1:09:51:1f:77:b5:d8:76:e9:80:ea:25:24:09 - 2d:70:ef:5d:89:20:7d:49:4b:52:c1:26:36:c4:c3:95 - 38:80:ef:6d:15:43:5e:dc:bd:5e:06:56:42:6a:59:00 - 13:e3:99:3f:b1:c0:a6:e3:d5:fc:72:38:d1:ea:0d:61 - - -prime1: - 00:f1:54:7d:6d:25:84:c2:37:16:bc:18:04:8b:a2:5e - 09:bd:cc:98:4c:44:ef:8a:9f:b4:6a:72:ac:cf:c8:2f - b4:6b:a6:fd:e9:df:6e:98:42:6c:b4:95:b5:72:21:e0 - 21:e9:71:99:c6:8a:66:f5:06:96:35:9f:15:87:46:7a - 66:cd:3d:ba:1e:96:28:35:ab:fd:07:fd:ab:11:31:50 - 93:a6:6c:67:5e:dd:b6:a9:87:f0:9c:c6:46:cb:7d:83 - 5e:58:c6:16:81:03:64:f5:c6:01:a6:e2:54:7c:be:93 - 65:02:66:89:86:e8:c8:56:bd:cb:d0:bc:7e:df:cb:9c - f7: - -prime2: - 00:f8:5b:5f:19:24:20:60:41:4c:86:07:70:c7:2a:7d - dd:98:bc:f5:e8:ba:c3:7b:5b:2c:50:b3:fa:be:17:04 - 27:6e:75:3f:61:4f:3d:11:aa:f2:73:6a:f8:2f:da:59 - 65:b8:60:13:74:0e:d1:7e:01:07:d6:7e:fd:fb:f9:ca - 4f:9c:e9:c5:49:62:a7:99:36:ed:0f:1e:86:cb:e6:d3 - 87:d0:2c:93:3e:d6:b5:59:a6:b4:f3:2d:38:85:dc:ca - 5c:cd:e1:e9:3e:69:c4:04:25:5e:12:16:86:7f:30:3b - 84:63:80:78:77:d4:45:dd:f7:f0:cc:d2:b5:7e:53:ce - 27: - -coefficient: - 54:6b:6a:51:c7:7e:e2:d9:0b:b8:7e:ea:c8:1b:1b:a8 - 97:06:67:87:da:6a:f7:b2:15:7c:ae:91:4a:46:4a:bd - 79:3b:3a:d7:80:c6:95:2d:e7:92:97:76:cf:24:04:09 - e3:5c:11:68:77:0a:67:21:5a:82:57:80:d1:66:42:d5 - a7:03:1a:20:56:90:c2:e6:97:31:21:3e:a0:4f:41:43 - f8:07:41:92:48:39:ac:1c:8d:c1:a6:0d:be:5d:45:96 - 65:4b:b7:31:0c:c8:2d:f0:72:ca:ba:0e:f0:5a:7c:1a - 7e:23:20:98:1e:c0:55:72:f2:18:b3:22:de:ec:47:21 - - -exp1: - 00:90:e0:d8:2b:9e:4a:85:0d:ed:68:1e:43:1c:50:ed - 83:8b:9e:38:10:11:92:7c:f6:43:a9:64:0e:ba:ee:c3 - 34:dd:2b:f3:63:63:ef:51:19:0f:89:9a:16:c3:dd:f2 - 60:69:74:f9:8c:67:aa:47:8f:1c:be:34:33:08:73:17 - 28:80:2e:7e:7d:be:47:85:71:2b:06:91:13:11:cf:39 - 40:6a:b8:c9:95:fa:24:9e:c2:2d:80:f0:c7:af:82:3a - 4b:79:9f:f2:02:a1:b7:0a:95:44:88:9b:77:7d:2c:2b - f0:87:f0:66:bf:c7:1f:fe:73:12:d8:cd:50:9d:a9:ef - 21: - -exp2: - 2f:9e:a5:6f:56:a3:f6:90:ce:b1:6c:3f:cd:90:72:2d - c9:19:82:35:2b:8a:4b:de:c1:72:7f:ef:f5:fe:c7:c7 - 1f:c0:cf:74:43:13:3c:8e:00:8a:ec:d9:c5:a3:22:3d - 04:cb:37:2f:ab:9f:b3:7f:53:17:67:a6:1f:68:57:c8 - 48:17:f2:c2:0d:6e:81:4c:2c:cc:17:58:55:44:5f:0e - cd:75:9e:8e:0f:f1:19:cd:83:28:95:65:1f:15:a4:9f - 82:c2:6c:4c:91:4f:0a:54:77:e3:13:fa:99:ec:8f:9c - e4:cf:3f:4a:0a:a3:92:d9:f5:8b:f0:62:e8:63:fd:45 - - - -Public Key PIN: - pin-sha256:rS98yeSr3aoarf12o4jbIXeADc53+k2lu/+TB71kG0w= -Public Key ID: - sha256:ad2f7cc9e4abddaa1aadfd76a388db2177800dce77fa4da5bbff9307bd641b4c - sha1:a558e1b80dd69fbc34e5e83dd8fa0ca583b1c045 - ------BEGIN PRIVATE KEY----- -MIIE7QIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCA6EaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgOiAwIBQASCBKcwggSjAgEAAoIBAQDqH/wwX/8Z25ow -Rhv6NN5rVkT/oQbRXGqnufh9rLwPK5zYm5AtMaBBx3RzAbrq5Maev5tBYgdUtFPL -oteL3zqkbbaVcTIh7jyanZubTdXv03CEusIOpy8HqilpIEb42odJ4M8A08AmoHE1 -AAZFVlaPk2B1QvV4Ye6t+9I43nktm1sH5iu+tainld+fKhqfYlUmNVOIM4wc+ZPm -6kU5PAl64UpB3qY4/Vbk1Q3u/yiB3LDKqYRCX3pocjIeBU8HNlhxdqTIs9IYPsg9 -ey4YRIzc37RTVHLueBFolJL23kFbHOjcG0H+j7R9jVlW7QeWIL0LGMs/QNMCYnpQ -LlJmaKuhAgMBAAECggEAM4dGof7+zloe3XEQx0jLiyQ5m2l9bqbAcpnjrwVNfqlC -pAnY+ZlqhA+5+XXwBbLEZDwXl5RTuLjXmIIGnqpK5dWf0dRQDFe6zuzRSqUe6OHI -ae4Qt9jj6PPymUiZVjwCeqgX5z6zk8zMHbYbqzcNZhwxpp1OGWi0d2ZtJkcQtJCI -+a9l0xYH8mtZbroDILqlgId1rpJCvWThWkh7czPDcHTMFAXA0kIBf4JO4Iv5KxJN -cU9Vhv0oCo+mrWYyS17zIlixCVEfd7XYdumA6iUkCS1w712JIH1JS1LBJjbEw5U4 -gO9tFUNe3L1eBlZCalkAE+OZP7HApuPV/HI40eoNYQKBgQDxVH1tJYTCNxa8GASL -ol4JvcyYTETvip+0anKsz8gvtGum/enfbphCbLSVtXIh4CHpcZnGimb1BpY1nxWH -RnpmzT26HpYoNav9B/2rETFQk6ZsZ17dtqmH8JzGRst9g15YxhaBA2T1xgGm4lR8 -vpNlAmaJhujIVr3L0Lx+38uc9wKBgQD4W18ZJCBgQUyGB3DHKn3dmLz16LrDe1ss -ULP6vhcEJ251P2FPPRGq8nNq+C/aWWW4YBN0DtF+AQfWfv37+cpPnOnFSWKnmTbt -Dx6Gy+bTh9Askz7WtVmmtPMtOIXcylzN4ek+acQEJV4SFoZ/MDuEY4B4d9RF3ffw -zNK1flPOJwKBgQCQ4NgrnkqFDe1oHkMcUO2Di544EBGSfPZDqWQOuu7DNN0r82Nj -71EZD4maFsPd8mBpdPmMZ6pHjxy+NDMIcxcogC5+fb5HhXErBpETEc85QGq4yZX6 -JJ7CLYDwx6+COkt5n/ICobcKlUSIm3d9LCvwh/Bmv8cf/nMS2M1QnanvIQKBgC+e -pW9Wo/aQzrFsP82Qci3JGYI1K4pL3sFyf+/1/sfHH8DPdEMTPI4AiuzZxaMiPQTL -Ny+rn7N/Uxdnph9oV8hIF/LCDW6BTCzMF1hVRF8OzXWejg/xGc2DKJVlHxWkn4LC -bEyRTwpUd+MT+pnsj5zkzz9KCqOS2fWL8GLoY/1FAoGAVGtqUcd+4tkLuH7qyBsb -qJcGZ4faaveyFXyukUpGSr15OzrXgMaVLeeSl3bPJAQJ41wRaHcKZyFagleA0WZC -1acDGiBWkMLmlzEhPqBPQUP4B0GSSDmsHI3Bpg2+XUWWZUu3MQzILfByyroO8Fp8 -Gn4jIJgewFVy8hizIt7sRyE= ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa.pem deleted file mode 100644 index ffda4f2e40..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDDzCCAfegAwIBAgIMWYGU7zoymvg+Z63iMA0GCSqGSIb3DQEBCwUAMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzVa -Fw0zNzA3MjkwOTAxMzVaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVz -dCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOMuUmmLJ2pQ4fYj -EfuIj11TMnG8dqScapc/yU9zHCDn5DQJGOa/X5jYoJX4k2PbXk5bbck2caC4J7/G -WRugGc4KcOVItAmnxbVzJqtpsdRrVUvTzqcvaSZNHEgSWP73WmlACX6xIHRyBtr+ -Pwpig73eZkOVcGOsbsWliffVQ0f0fz/AGsYh5IWBNlIfBOWwOEBDJavlsYrVGAw1 -MuXxknybsjXFRqyFNPE6Shd3W3eteo+FOvQsyopmX6FcP+EOaFQxSQ7yR+xNsreC -yxi40hPfswO6TihN9hLdVt3C+OHDJw2wR2xM+SwsW8Hu4jEi21uakQl846z+XdgV -o+D3v3cCAwEAAaNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQA -MB0GA1UdDgQWBBQrQlWadXqqzBV+2iw7BZXrvFHaQjANBgkqhkiG9w0BAQsFAAOC -AQEArUVXn2oI5hgSkDwDrhQFijHBT3d37SX0eji//lkLPTHSEXHv+6kAoxVKmSnG -hAAxuLKxtAjNlXi4FAxSpQPX17/199JHUd/Ue63Tetc8DfaFc6MaFNxWkNrY6LUX -bEhbI/vB1kBu7sc8SW7N694WSpe/OmD/lB6GYW6ZV68hrTB0gfmfB6SfcGbQ69ss -YUsNU7Yo1GZnJTz0FZzybjx/T85NnVvpfVqjjaGRFeSva9GAU+5uO5DdbSpbkCcw -6QFFfvcJ7VD6qFqtLG1TfcdOuCaUB8cmDhDtTB/Ax96wGdJvp6ca3YaboZag9HOZ -4csuzHIJQyd5HT6xLbUBeskgWw== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_256.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_256.pem deleted file mode 100644 index 0e5966a77c..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_256.pem +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDpzCCAl+gAwIBAgIUIyISxx5PRQREJEmN08CNp74twmcwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogMC -ASAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0MloXDTM4MTAyMDA2MDY0MlowIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRMUyBUZXN0IENBMIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQ8AMIIBCgKCAQEAt7Sa -TS0/CLgeVdawsrfQM8y73lYkBB1zrGoy268mT++x1hCQedyJrGDjlFQZBFQX6hgO -2Ua+YJ/mM/9uYGo1xi3dBoLVgMmIBy8nSwQTuktpks68AL5CLOI1jWARZjwk+DoT -rUnnEsrGKlKE7T19HgbepGTWFxSxGWOg4XxJ00FzKfi1deCT+uPfO4J3XoPL2lIm -68MgExFt6aql17bDoaUE+m7uTzlSTRj5q4dKTtk0p8Tf9Ru2V3F/w8hPLADAbuh0 -NeJxH+/GwWJ6ZefJx0IUXxbBq00y5eJ8OKIhAmmjgfTIeEhYCl2ZhfXmKje+I+X/ -Fbo5Qqyd0BF+5CtV2wIDAQABo0MwQTAPBgNVHRMBAf8EBTADAQH/MA8GA1UdDwEB -/wQFAwMHBAAwHQYDVR0OBBYEFCEaiLbeA8ABgKrbcIiZpo8XzqpsMD0GCSqGSIb3 -DQEBCjAwoA0wCwYJYIZIAWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQC -AaIDAgEgA4IBAQCpl2XsRpIAR5cD0YRWOg2hNg1+oMNAj1wtuBOiaD84doN07sFl -ta3lnweoA1rZZNLtAOUu5Fs7FwetzhuA5+iHVRAU8qqoSojP5fZgTriOFK/7rEUu -ZTxL1IzXEuiQO2iCkTXslg5HP5QAsYV4iqGe6erSAgzD5tP2mpgQJudUiuvCdWGz -lgroWjDAklQHIXITCrLgnMieYIbILZXXMZLfIrMfZOPCd7IDPTjb8/k1j3N4Wuld -qZWSPeNhuUUTKniXy4GVBE1obMDyBRarR4jkeeKdsuYbdf0oSTMK/rcuZMrZfjAR -uH3sqZ1Ovw4rbYzjk/ET4QlolFnFexgZ5QcH ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_384.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_384.pem deleted file mode 100644 index 5e8bb89007..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_384.pem +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDpzCCAl+gAwIBAgIUWplyXkxgG/630tCmc0xgpFKshNYwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgKhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAICogMC -ATAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0MloXDTM4MTAyMDA2MDY0MlowIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRMUyBUZXN0IENBMIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAqEa -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgKiAwIBMAOCAQ8AMIIBCgKCAQEA7m3A -yUTdlPhAr5r0Qz54RWFfahUjQvT4oMLragquDEOn3OmszkLEyPVM3mxSS+XTK0K4 -+eVcX1xTLw/39T0E7StQyatrdC1LQnFXegSDOJf6WyJKFNIN3VxmySV94/8FhALq -PIKXRQ98s3GOfzGNtetetg2Rm11RvPfigaJfRjXPnmTEPGVj9v8VsOcRSfrBzNlU -m/gTPZXO9H9YZiPNvBGv4T+v2F4Whc19t39Z+v8p5u9PbmvvsJHvgWNvsgwrR6Yh -9x9L+x3nb/hvDmqPilRfS6JtNiC7uhGHBvONlWoQtyeOHQK0zh7CCXPEtl3HX+Im -vU/NerDFwNaCH9QuWQIDAQABo0MwQTAPBgNVHRMBAf8EBTADAQH/MA8GA1UdDwEB -/wQFAwMHBAAwHQYDVR0OBBYEFKnwXW9hoPAB6HSyWn7UEUMcKonnMD0GCSqGSIb3 -DQEBCjAwoA0wCwYJYIZIAWUDBAICoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQC -AqIDAgEwA4IBAQAwyVTh4HCTN1FnLLY3iUSEWHNqYNCdAmP/qMYDgwZAdS3hRHEt -9mE0a0/52bYEY9QMol4eGIGKjiXuxZpJKjK2WBgnUvyV7fEDcKy8UqB+ULFGNRxR -9tR3MRMSFrQl+W6q2ABPwmqvAtJHSiIRA30ZuwxSyX4ulzxThRYnkfp2eSKKHp2x -J6xUEnN5vnoXvpa1sFccKorPITF0r8OWzIi+GGzHz4Wq0Fqov4TOhnU/u6Xqw0xX -CXshQ0pN6+XWT0Ea0OuZk1/cKy2nyk+oHSmo/HhKJ8lGc3P2dLgCV9jjbM2WYCHs -O2rKlDWMxkd1Zx/I0ZzUI3Km+Qb8a+88KOtg ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_512.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_512.pem deleted file mode 100644 index 690d25654a..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-ca-rsa_pss_512.pem +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDpzCCAl+gAwIBAgIUJ6gfVYLgx1UAxuxNNmuo6mUQP/gwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgOhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIDogMC -AUAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0M1oXDTM4MTAyMDA2MDY0M1owIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRMUyBUZXN0IENBMIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCA6Ea -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgOiAwIBQAOCAQ8AMIIBCgKCAQEA6h/8 -MF//GduaMEYb+jTea1ZE/6EG0Vxqp7n4fay8Dyuc2JuQLTGgQcd0cwG66uTGnr+b -QWIHVLRTy6LXi986pG22lXEyIe48mp2bm03V79NwhLrCDqcvB6opaSBG+NqHSeDP -ANPAJqBxNQAGRVZWj5NgdUL1eGHurfvSON55LZtbB+YrvrWop5Xfnyoan2JVJjVT -iDOMHPmT5upFOTwJeuFKQd6mOP1W5NUN7v8ogdywyqmEQl96aHIyHgVPBzZYcXak -yLPSGD7IPXsuGESM3N+0U1Ry7ngRaJSS9t5BWxzo3BtB/o+0fY1ZVu0HliC9CxjL -P0DTAmJ6UC5SZmiroQIDAQABo0MwQTAPBgNVHRMBAf8EBTADAQH/MA8GA1UdDwEB -/wQFAwMHBAAwHQYDVR0OBBYEFKVY4bgN1p+8NOXoPdj6DKWDscBFMD0GCSqGSIb3 -DQEBCjAwoA0wCwYJYIZIAWUDBAIDoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQC -A6IDAgFAA4IBAQAIi+3zyTk8NR5w5a109GHz4wpACxafirJkr6wkAIzzU95OKLiw -fogX/ECW9UaIfJMHrnEADhKcMSRd7HcNpDg/E8GKr4IhtbkFhNjAjE10Ham6fLzw -SgvN34QpDT6iVP83Cx+SzlSDQLjq4es8diZXP39C0T2a9iskDXMF+ZcaZMwd1TLe -MI7HMIiLCoyVP7LOI39e6E0ho0W0FRrMtZuXIIvZjwkb+SGhAmlJiATmpLmtzuoK -oI/UE1gNglJFjA6HWHStHd7hEJrtGHNa061G130kOFGIJhGf8fHiGaWvWYfZ5/jc -egUo5t7rA6wg6KPwA2JjH2jxUp3NUzTRzV72 ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-dsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-dsa.pem deleted file mode 100644 index 782fe4ef98..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-dsa.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEpzCCBE2gAwIBAgIMWYGU8Awsp0jsH7C+MAsGCWCGSAFlAwQDAjAjMSEwHwYD -VQQDExhCb3VuY3lDYXN0bGUgVExTIFRlc3QgQ0EwHhcNMTcwODAyMDkwMTM2WhcN -MzcwNzI4MDkwMTM2WjAjMSEwHwYDVQQDExhCb3VuY3lDYXN0bGUgVGVzdCBDbGll -bnQwggNHMIICOQYHKoZIzjgEATCCAiwCggEBANIzNyBmt0q+w79byPcXWN5ETG80 -4OJFYhOAdUl5gv90ACofvnojmLaOu2AnbwEUVMlV5xBdeuanPl0ESmH+yFoDwwwA -3uNhPutZ91Yml5PPpks48Fj8IV8Mnnp+0LGC1Ug9IgeXkPSrGm1aIJjMNvK3xc7q -MGI8aeL//pFSoH4vNvRqi+QzZBW/FaXeWdRvkT0c1YACvdl0rnF3SPbi7bn45ceG -GEenq6dFjbZZG1e+bZyzd8/UGO01BLZxftG0IiWWqKi1BlP1Lgc8LyUIrza+Ie1a -vLk0jbjuhhQsYebpvnO84uhDOdavpxnHCqcEm8sElRctIFYY1xB3PD3bG8ECIQCI -pXijcj1zNsncR7roSHNeer5B3c1N92F2hTLedYbzwQKCAQB7PCrFF3u7oJq/64EL -8EMlnv81vgWnet/Ux5zzY2OEdtDOOR4YnrWXcs/rsjio/blHTf/CeMX3pTVV8GE3 -f0C4+Hx6mWb+okL7UgEPmen8dGHD//yn3e6wYBG7aqd8DtBkicmgd9eKlY+xgbww -rDN8dz9RbJ9oAOXbzASw1GvLbZ6UWsMTZ7WWoAbLOf+0gfiA+eRjC9x0HbaN0jLy -ztQJhEvWqGSynNfkB2xopRtoyYCvtEVDtQEC9H6PtIG9oKyiwLAtVOmbj6pf1/V3 -ZJJEPiFfKD8CHcS8Z87JXMbjTolIf1A+/Bjn+FKOS2zdIQ+rAOFdptUyU68CWkAV -6trbA4IBBgACggEBAKprryuOBKnrY00s9y+HM6UMvS/exCjzmQrlQ9rQMuwVG+lz -GKKWFu7shIQqneaNNUuNAXRK0NABkPjIBLfvdDmkXweU4/oi2mZQaIUPEWceHrmL -FliI3+VtqC3rPvXzVGvbBdUvqSCJrYD84EK6Ahs3LGIB0OC1Wldi6x8FtKewbn7B -23twnAsvNx4QzFt7W6j05EorWCvs+cwbTttptRiruNcPYLQweMIrcNvzApq+sgoW -traZdTS7rBklrgfi7/4JJNN+jV21XqDQYGugN8PnbORyuETGHEf1wk4HFL7eweHO -4KzTpaNeqsJfilOe9PV1SgDhv9oyKj6957xK1WSjdjB0MAwGA1UdEwEB/wQCMAAw -EwYDVR0lBAwwCgYIKwYBBQUHAwIwDwYDVR0PAQH/BAUDAweAADAdBgNVHQ4EFgQU -iU8ApXTLLe07mPDvg7O9CsNwS0EwHwYDVR0jBBgwFoAUAOVmarDrz1YtyjvnX4C9 -cDcXlagwCwYJYIZIAWUDBAMCA0cAMEQCIGlXUYEccybo2azMk3f6Zl6bpxERr/FU -+/2k+mbBeo7TAiA9/aIWf0bdED8AH0KNKFfcpKMsvnJHTCOPr7fBPU84lQ== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ecdh.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ecdh.pem deleted file mode 100644 index a3b1b346b9..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ecdh.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBtTCCAVygAwIBAgIMWYGU7ztLkMAhmmRDMAoGCCqGSM49BAMCMCMxITAfBgNV -BAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzVaFw0z -NzA3MjgwOTAxMzVaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IENsaWVu -dDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABLRekMsBjYf7GXhy7ZqnX9lAvXyL -sC9VfMUIcfGNluSN2C3O9fjqN5FMary/eU49ij6L2mRUjZz6kQK0ZM68pL6jdjB0 -MAwGA1UdEwEB/wQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDwYDVR0PAQH/BAUD -AweIADAdBgNVHQ4EFgQU7ZRZoI8czdH0szeb+t3EwaXNUG8wHwYDVR0jBBgwFoAU -0ma/FGcW5gGlL//B26Xmj0JISecwCgYIKoZIzj0EAwIDRwAwRAIgVij5xSPQrUgo -VsbOgVdLGLJeiHo065dtdt87PSCJtusCID+c1QShYOgBkI/Bv3gotVhTP4mtjhp2 -2v442jTclSfT ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ecdsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ecdsa.pem deleted file mode 100644 index 261db1ce00..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ecdsa.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBtTCCAVygAwIBAgIMWYGU8A09KQDW+svJMAoGCCqGSM49BAMCMCMxITAfBgNV -BAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzZaFw0z -NzA3MjgwOTAxMzZaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IENsaWVu -dDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABLenUtWqfkGp0iFncfdsvBsfaXHv -Ne5gV7U/zUO0OQ71V1c8WpOx9f0rhpOSCN9GCqQNL3yd+nWf+pu40JMMrZKjdjB0 -MAwGA1UdEwEB/wQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDwYDVR0PAQH/BAUD -AweAADAdBgNVHQ4EFgQUtK5VEuBZJUDbU8gN9dleZeXDf2swHwYDVR0jBBgwFoAU -0ma/FGcW5gGlL//B26Xmj0JISecwCgYIKoZIzj0EAwIDRwAwRAIgNnj/nlAbCd0R -fCG6n5s5Sdsh4dR7KRhncCj8wjGYZMYCICUXU05FIr3bM9bELX2We3rv1ookK9rC -7ZVjCgt7YbHi ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ed25519.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ed25519.pem deleted file mode 100644 index e419a7b32a..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ed25519.pem +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBfjCCATCgAwIBAgIUO1XUdvEupfCQwrrPHXE28BoO+TswBQYDK2VwMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xODA4MjMwOTI5NDda -Fw0zODA4MTgwOTI5NDdaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IENs -aWVudDAqMAUGAytlcAMhAJe53GEkXEVP7L7FbVZ1BCGvvIZac+6k41CncucJ3BJ2 -o3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoGCCsGAQUFBwMCMA8GA1UdDwEB -/wQFAwMHgAAwHQYDVR0OBBYEFNo2OYJ4FLTBdu5lozbqL2aAXsqzMB8GA1UdIwQY -MBaAFOp5vj76ByEwboduoHWAWzajnM1mMAUGAytlcANBAJrgAof3yetck8DDLNTG -dwLQdCNjEg5/xgvKVcTPuUC4rirgCoYtPY36lfPhd0v5Ev8v1Jjrxshyi/yVCsLb -mQ8= ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ed448.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ed448.pem deleted file mode 100644 index e7442fce53..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-ed448.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIByTCCAUmgAwIBAgIUbl3fESW+2UIW9SzaxnhuhiGygLIwBQYDK2VxMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0yMDAyMTMwNzMzMDJa -Fw00MDAyMDgwNzMzMDJaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IENs -aWVudDBDMAUGAytlcQM6AFbp8qV7nVhmDWZUsXTfqU8aOaP4XSmGUnKqdlQPR5O4 -3lMlUukbrclV5v5+b4Z8Qy4Abe+PZU+AgKN2MHQwDAYDVR0TAQH/BAIwADATBgNV -HSUEDDAKBggrBgEFBQcDAjAPBgNVHQ8BAf8EBQMDB4AAMB0GA1UdDgQWBBSlCh5L -f6BeaHQxiEe5B9ZjbbCKODAfBgNVHSMEGDAWgBS+BSv++BEWlTJ53q6rwnDLVnR5 -JTAFBgMrZXEDcwAC3Tugpa+pS0ExsLdh/6GsVAVvhYICLc+tWGExM+f3gzFU7yvO -uM7xwRR78ItbQyRkfLeL+6GYGgDzhjwQ6XzilwGibLtGuooLAMo3uOgW8N4mQslf -GqEW2V3VocPjmNYanAMJnTd68t5Wc0ow153cNgA= ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-dsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-dsa.pem deleted file mode 100644 index fd1a45b906..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-dsa.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICZAIBADCCAjkGByqGSM44BAEwggIsAoIBAQDSMzcgZrdKvsO/W8j3F1jeRExv -NODiRWITgHVJeYL/dAAqH756I5i2jrtgJ28BFFTJVecQXXrmpz5dBEph/shaA8MM -AN7jYT7rWfdWJpeTz6ZLOPBY/CFfDJ56ftCxgtVIPSIHl5D0qxptWiCYzDbyt8XO -6jBiPGni//6RUqB+Lzb0aovkM2QVvxWl3lnUb5E9HNWAAr3ZdK5xd0j24u25+OXH -hhhHp6unRY22WRtXvm2cs3fP1BjtNQS2cX7RtCIllqiotQZT9S4HPC8lCK82viHt -Wry5NI247oYULGHm6b5zvOLoQznWr6cZxwqnBJvLBJUXLSBWGNcQdzw92xvBAiEA -iKV4o3I9czbJ3Ee66EhzXnq+Qd3NTfdhdoUy3nWG88ECggEAezwqxRd7u6Cav+uB -C/BDJZ7/Nb4Fp3rf1Mec82NjhHbQzjkeGJ61l3LP67I4qP25R03/wnjF96U1VfBh -N39AuPh8eplm/qJC+1IBD5np/HRhw//8p93usGARu2qnfA7QZInJoHfXipWPsYG8 -MKwzfHc/UWyfaADl28wEsNRry22elFrDE2e1lqAGyzn/tIH4gPnkYwvcdB22jdIy -8s7UCYRL1qhkspzX5AdsaKUbaMmAr7RFQ7UBAvR+j7SBvaCsosCwLVTpm4+qX9f1 -d2SSRD4hXyg/Ah3EvGfOyVzG406JSH9QPvwY5/hSjkts3SEPqwDhXabVMlOvAlpA -Fera2wQiAiAFTXpu+duj6u8P3wMsd7fOOStBEV6hPUh+RLdOjGslXw== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ecdh.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ecdh.pem deleted file mode 100644 index 2a28a9f102..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ecdh.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgAuAT+3hSra1qS+XA -iAUT+W6MSZ2rnoeQGjFe6FX7z8qgCgYIKoZIzj0DAQehRANCAAS0XpDLAY2H+xl4 -cu2ap1/ZQL18i7AvVXzFCHHxjZbkjdgtzvX46jeRTGq8v3lOPYo+i9pkVI2c+pEC -tGTOvKS+ ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ecdsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ecdsa.pem deleted file mode 100644 index d9aceb301e..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ecdsa.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGUAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHoweAIBAQQhAJxpy2FD0ePz3c9j -6fVPTSpHAmdiRIqnskVP0PjiBAEvoAoGCCqGSM49AwEHoUQDQgAEt6dS1ap+QanS -IWdx92y8Gx9pce817mBXtT/NQ7Q5DvVXVzxak7H1/SuGk5II30YKpA0vfJ36dZ/6 -m7jQkwytkg== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ed25519.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ed25519.pem deleted file mode 100644 index a08f3c44a8..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ed25519.pem +++ /dev/null @@ -1,25 +0,0 @@ -Public Key Info: - Public Key Algorithm: EdDSA (Ed25519) - Key Security Level: High (256 bits) - -curve: Ed25519 -private key: - b6:9d:94:c8:9d:c9:7a:5d:b3:58:92:af:67:8e:c2:bd - 63:c1:81:55:3d:b2:5c:e0:c8:91:f1:40:34:5a:6d:b9 - - -x: - 97:b9:dc:61:24:5c:45:4f:ec:be:c5:6d:56:75:04:21 - af:bc:86:5a:73:ee:a4:e3:50:a7:72:e7:09:dc:12:76 - - - -Public Key PIN: - pin-sha256:aWaJiTGI21SUAEt2VgTiRGAnczFMD8axA/4hrKMpfno= -Public Key ID: - sha256:696689893188db5494004b765604e244602773314c0fc6b103fe21aca3297e7a - sha1:da3639827814b4c176ee65a336ea2f66805ecab3 - ------BEGIN PRIVATE KEY----- -MC4CAQAwBQYDK2VwBCIEILadlMidyXpds1iSr2eOwr1jwYFVPbJc4MiR8UA0Wm25 ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ed448.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ed448.pem deleted file mode 100644 index be3c8638b2..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-ed448.pem +++ /dev/null @@ -1,28 +0,0 @@ -Public Key Info: - Public Key Algorithm: EdDSA (Ed448) - Key Security Level: Ultra (456 bits) - -curve: Ed448 -private key: - b1:9c:73:a3:54:a0:33:05:b1:b0:ad:6f:1f:c0:ad:14 - db:d4:55:bb:eb:fa:d4:33:8c:e5:bc:68:03:d1:ca:25 - 19:75:0f:94:4f:e3:fd:3a:62:b5:77:23:d7:b0:d6:75 - 92:9c:98:86:2a:08:c5:b2:6e: - -x: - 56:e9:f2:a5:7b:9d:58:66:0d:66:54:b1:74:df:a9:4f - 1a:39:a3:f8:5d:29:86:52:72:aa:76:54:0f:47:93:b8 - de:53:25:52:e9:1b:ad:c9:55:e6:fe:7e:6f:86:7c:43 - 2e:00:6d:ef:8f:65:4f:80:80: - - -Public Key PIN: - pin-sha256:4r2UflhSms9yYj4SMc7tE9lkFxXR/ziPw1bhZGfI/qw= -Public Key ID: - sha256:e2bd947e58529acf72623e1231ceed13d9641715d1ff388fc356e16467c8feac - sha1:a50a1e4b7fa05e6874318847b907d6636db08a38 - ------BEGIN PRIVATE KEY----- -MEcCAQAwBQYDK2VxBDsEObGcc6NUoDMFsbCtbx/ArRTb1FW76/rUM4zlvGgD0col -GXUPlE/j/TpitXcj17DWdZKcmIYqCMWybg== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa.pem deleted file mode 100644 index d2d19bf0eb..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDP8Yo5l5ez1W2c -EgROodwNqRLL+ALvOorSEuKm+xiTbzmdqcMdtvwDhq/yb7GBhpzrFcUOt5hPcQc9 -pYz7Khg4UHiw+wqbV2QHMGGupNs+kvdUndBgjToD7hYlyhV7fUovNrjQeNq+5Bxt -OHsZmO7ilHTKdSMVG2eO5XgZk+1uSOuZStmnMZM0Sum3TxK5zRs2beLf5OhNDqMH -+hJVH9FL4bF9LaxQfTvMrwnIqgEKBlMO29cs1gPW1otQEFD4MefHhjK0YEF3xZ7r -hnnx6lPv5wFQLeaRx1NBqgdPY3L9ZSUkKQzLQgWubbKK1b8vDookicdebSMjTrVX -HPcv6B93AgMBAAECggEAQZZe0cGFwNwdoW9xWlflL43Xduw4CLq/VHlOcfqbCs23 -L4p/F11C6d3Omzotk7wgvGl2aSjxaoUtEn2oFQR29TQ0jSXxd4O98iKJfOtUl80F -I/RO6FVDKkArTioKUpP3FSM+ccrcu/75FF4PPcil+GN43u7JbPvi0wh/tBmbdwAJ -aK2wskjaJAbQz8lnIEVZkz3uYLc32BD2FoCC+HyIPAYFbryus1m+TsXWVk3rDKst -85x4jadS7g3a1OvsDXqj8lHlom9dlxcMqTtSaJr1XJgMwztnc0FVuMOqs0MZpa2U -Mu/0EJQYLW98a1bDkXbLtbXjx2gWpO64gZqQn6aYAQKBgQDfgA2xVv7nmVuOkojJ -rJTS4muPG1BhXY7/MD13eopmjPk8rpVZt97RHfMHp3CCzuQVy9g398kBvCBtO9Ba -3/ab9ZrNMN3Rwm7vwUa4TBOvN17bRSeIPUenJJ42SDM2fmN4m8c91iiSyb9AVPmk -zSksQYtZr/8m9mQ0VOguzOxcAQKBgQDuLmDFSYDl4DO4cOZANpDYk1MkCtrW37xM -IUS6vnPFkRg3t57Og9tddj81VoMNeakGRvWmcDA1yuVdo52pqjlSXzQuSYAh7ZTC -KMzesLt1uilXQW2MNNvmZMjltgkHMiuY1cIvQLFC0o4AI5DLR5+5/w/lm/Qe9pfU -++B3XVVbdwKBgF5Yfu86ixYW/bg8kTOY/6XZ4I+jdxXy2ZdNtNTHzL6nidqc0/zw -ikV6QAoeG3eMgGnXB+nwVlC+Km4SDs0dt8t0LSmrFCgkzJG24/SOYMzZMdib46k2 -PRYIdiTx63R4e+MA12V6DtyP/4TXmh6AYH4HGRz+F1ZKMliI8w42gRwBAoGAN9sG -dJ21LbNzTZikVoC1XSTHhZdKFMPpO409ufF54uYQ4Ngd1N5VLkjRr+d22k0il0dC -ymJa2/KV8WyyR5yUzr1m1kgEVXCKxzGcQcj+XTBoC39belrXCuOtvTkASwC3+qJ+ -ZGhuaXZJOL0ecp18Vrj6+GSnTi+UEa1zyWpI3ycCgYAxJgHa3CGaGqbdzgkRTnWd -FMptvqaNd4POyy/TJ1Jf0ydZwgRpRMZTv8hJKZHh4lUkSOF6bE0qDhrxzUjpI9GT -SGYYX27pfVThoM421S7bvgVmneeLSz1S50Hg0jawHA2ixjne/7kQcMjQzYjjMfDy -FgVOrBIQnpUddGEpu1z5pw== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_256.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_256.pem deleted file mode 100644 index 86f66f7d25..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_256.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA256 - Salt Length: 32 - Key Security Level: Medium (2048 bits) - -modulus: - 00:d7:7a:3a:01:8b:5e:59:0f:10:7d:95:5c:ce:c6:ea - c8:29:2e:75:6e:fe:6c:f9:83:d5:3e:72:6c:fc:56:95 - 43:d4:62:34:df:05:7c:b3:b3:a6:4a:37:ca:b6:e0:23 - 44:19:fc:2c:ea:cf:fc:f9:26:1a:ac:5a:8d:83:f8:4f - d9:0b:ae:fc:e9:9d:75:37:2d:a4:93:02:5d:69:10:df - b7:7a:4c:b6:05:64:73:46:45:b2:fe:a4:b3:33:9e:68 - 6b:14:35:8e:ee:df:bb:e0:77:23:76:b8:6e:fd:fc:f2 - dd:02:59:5e:dc:a1:b3:5d:93:c6:2c:e2:4a:85:21:7f - ca:59:36:e8:77:dd:fe:cd:fe:f6:b0:96:fe:14:6a:5c - 68:4c:cf:bc:fd:fe:ec:e3:2f:51:10:cf:46:db:1d:3a - 3d:cd:87:ec:67:4a:7d:20:5e:79:6c:ea:d3:24:d3:82 - 05:bc:d9:79:e5:cd:df:6a:bb:62:9b:20:b3:35:34:61 - ae:69:a9:ab:b9:b6:27:ac:7b:33:f5:be:df:9a:b4:12 - 68:06:55:79:b3:ba:52:f0:91:90:69:b1:f1:5a:11:e3 - 8b:de:dd:f1:99:ca:5a:ad:87:ba:65:52:27:a6:07:12 - 60:10:24:93:4b:df:12:db:49:0f:fc:21:ff:9f:e6:92 - 75: - -public exponent: - 01:00:01: - -private exponent: - 3f:9d:f9:84:3d:36:84:ca:ba:ce:a9:0b:76:8d:2a:02 - 20:8e:73:e3:6a:40:98:46:40:ee:27:f0:5f:6b:dc:b3 - e2:ff:7f:a6:9c:c3:1d:77:1b:d0:6b:ba:70:d5:a9:f3 - d0:4c:30:a2:be:f7:6c:43:c0:ba:44:1d:e5:e9:a9:01 - 66:be:aa:32:fa:e7:01:7c:7b:4b:5f:f6:5e:2f:ba:2d - 3c:71:6b:88:1a:09:22:a5:2f:5c:99:19:c3:52:b0:77 - 74:c6:ff:45:2d:4f:15:cd:76:ed:f5:33:e7:cf:07:91 - 12:c1:7a:0d:5f:bc:4a:13:77:fe:06:6d:83:f2:c8:fc - 55:3b:f2:3f:9d:48:4b:b5:1b:22:ad:a5:7f:c6:29:b0 - 05:b8:e2:82:5c:b9:66:48:8e:05:d1:5a:ea:3d:63:c7 - 94:81:0e:c3:0a:33:d2:a8:a5:2f:a2:83:26:59:19:1b - 89:bc:8d:02:e1:c7:0c:53:64:6b:a2:d1:8b:ef:70:d6 - d5:94:bb:df:5b:49:4b:a5:cf:d4:df:0c:0c:ac:ed:8a - 39:61:b8:15:cb:64:b6:02:6f:21:e2:46:d6:c9:d1:d8 - 62:ca:1b:f6:3f:3b:74:c0:5a:ca:cb:a5:c5:aa:80:89 - e2:66:a8:7a:57:61:5e:5d:e3:0c:b2:4f:48:01:18:21 - - -prime1: - 00:e8:cf:45:ff:39:35:03:62:2f:2a:63:b6:14:95:22 - e7:30:6f:a1:d3:65:f1:8c:0e:13:a3:67:a2:1a:86:24 - 70:1c:97:64:15:9b:12:1b:59:66:de:05:42:6e:fe:ee - 77:a0:bd:1e:8c:5b:de:45:c7:4b:05:ff:ce:39:45:ee - 96:15:4b:96:df:b3:20:62:0c:90:bd:f8:1d:0a:ac:83 - 47:34:cb:63:0e:cf:1a:b9:20:62:59:1c:7b:a2:52:b0 - 4d:d7:c3:d5:90:32:9a:a5:3f:26:d6:66:f9:45:16:7d - a4:4f:2e:4d:87:4c:d3:8b:b4:00:5e:d8:5b:29:cc:a3 - 3d: - -prime2: - 00:ec:f0:f9:c9:43:a9:c5:fd:56:bc:57:d2:6d:18:9d - 90:bb:17:74:19:80:1f:e2:21:b9:b6:13:6b:b5:02:62 - b3:51:97:4d:29:dc:85:ee:bf:15:98:f8:21:78:00:0f - 3d:78:94:23:27:2f:52:a8:35:82:02:73:44:21:07:c6 - ab:61:fc:d1:1f:67:8f:43:5a:33:fd:ee:fe:d8:5c:a1 - 1e:b0:7d:6f:0b:6f:d6:47:25:1d:71:5f:b8:77:2f:8f - 4c:6a:0f:8e:03:ce:f3:cd:dc:02:fc:21:c6:ce:10:07 - 0d:ee:1f:d1:82:94:21:41:10:9a:76:62:80:cc:f1:3f - 99: - -coefficient: - 4b:89:17:37:c2:77:4d:99:ec:95:4d:d7:7f:c7:0b:8a - fc:67:ee:59:0d:66:7d:5c:33:36:6d:90:00:6e:3b:d4 - 79:9e:94:05:61:e6:e5:8d:f9:70:3d:7b:4d:be:7d:7f - 0f:ef:e8:e3:93:1e:42:da:d1:9f:12:6b:51:d9:7c:ef - 5b:c6:f1:e9:ab:9f:87:6f:d6:eb:29:4d:51:2b:f9:0d - b7:e5:96:fb:c9:4a:21:a4:b0:4a:af:b3:2b:3c:41:45 - 19:d5:3d:cb:fe:15:4a:f7:a4:52:e6:d6:0c:c9:cc:5b - 62:fd:b0:1d:ed:98:13:0f:9a:27:92:5e:a8:6b:bc:b8 - - -exp1: - 00:8a:f6:c6:32:5d:24:5e:bb:a9:a9:a4:d1:17:a2:19 - ae:64:04:0e:55:50:21:89:57:11:b3:d4:f5:36:dd:e1 - 3c:26:64:db:71:e6:19:3d:c7:f4:96:0c:0f:a6:8f:77 - 2a:63:00:e0:0e:29:fc:18:2c:a8:84:91:37:b8:8a:1c - aa:eb:55:2e:5e:a2:de:6e:88:4f:91:85:5b:58:76:b6 - f9:b6:f2:bc:53:27:9e:2c:e8:be:ab:b0:4b:c0:0d:99 - 7d:2d:90:90:96:bd:0e:00:1b:1d:04:97:7c:ad:17:8a - b1:9c:2d:e8:4b:1d:b9:9c:47:3a:7d:62:a9:af:de:9d - 85: - -exp2: - 6c:52:0a:4f:b9:b0:3e:c4:7f:c7:a0:fa:a1:47:74:99 - 3a:ff:10:e3:ab:90:67:e7:f5:27:c9:1f:1f:64:54:cd - 17:ca:ec:ca:eb:77:0b:5b:ae:3a:fd:8d:07:78:37:7f - 69:c5:87:80:9d:80:d3:47:8b:05:25:bf:0a:be:ac:53 - a3:7b:59:fb:5a:73:c3:5d:d4:91:0d:96:d2:41:1e:a3 - 92:19:f6:0f:2b:74:b1:97:c5:2b:14:90:97:64:55:c5 - a0:63:36:10:85:a7:2e:00:9c:18:ba:34:51:f6:3f:d3 - 5d:7e:8c:60:7e:e9:e8:fd:f7:2f:91:fe:c2:32:b4:59 - - - -Public Key PIN: - pin-sha256:V1OZkBgmgMWlbg+RZ0Dx3sw/b4WHbrN4NHttN6QbsGM= -Public Key ID: - sha256:57539990182680c5a56e0f916740f1decc3f6f85876eb378347b6d37a41bb063 - sha1:028b616b894849cbca9103fcf919fdda20ca101e - ------BEGIN PRIVATE KEY----- -MIIE7QIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgGiAwIBIASCBKcwggSjAgEAAoIBAQDXejoBi15ZDxB9 -lVzOxurIKS51bv5s+YPVPnJs/FaVQ9RiNN8FfLOzpko3yrbgI0QZ/Czqz/z5Jhqs -Wo2D+E/ZC6786Z11Ny2kkwJdaRDft3pMtgVkc0ZFsv6kszOeaGsUNY7u37vgdyN2 -uG79/PLdAlle3KGzXZPGLOJKhSF/ylk26Hfd/s3+9rCW/hRqXGhMz7z9/uzjL1EQ -z0bbHTo9zYfsZ0p9IF55bOrTJNOCBbzZeeXN32q7YpsgszU0Ya5pqau5tiesezP1 -vt+atBJoBlV5s7pS8JGQabHxWhHji97d8ZnKWq2HumVSJ6YHEmAQJJNL3xLbSQ/8 -If+f5pJ1AgMBAAECggEAP535hD02hMq6zqkLdo0qAiCOc+NqQJhGQO4n8F9r3LPi -/3+mnMMddxvQa7pw1anz0Ewwor73bEPAukQd5empAWa+qjL65wF8e0tf9l4vui08 -cWuIGgkipS9cmRnDUrB3dMb/RS1PFc127fUz588HkRLBeg1fvEoTd/4GbYPyyPxV -O/I/nUhLtRsiraV/ximwBbjigly5ZkiOBdFa6j1jx5SBDsMKM9KopS+igyZZGRuJ -vI0C4ccMU2RrotGL73DW1ZS731tJS6XP1N8MDKztijlhuBXLZLYCbyHiRtbJ0dhi -yhv2Pzt0wFrKy6XFqoCJ4maoeldhXl3jDLJPSAEYIQKBgQDoz0X/OTUDYi8qY7YU -lSLnMG+h02XxjA4To2eiGoYkcByXZBWbEhtZZt4FQm7+7negvR6MW95Fx0sF/845 -Re6WFUuW37MgYgyQvfgdCqyDRzTLYw7PGrkgYlkce6JSsE3Xw9WQMpqlPybWZvlF -Fn2kTy5Nh0zTi7QAXthbKcyjPQKBgQDs8PnJQ6nF/Va8V9JtGJ2Quxd0GYAf4iG5 -thNrtQJis1GXTSnche6/FZj4IXgADz14lCMnL1KoNYICc0QhB8arYfzRH2ePQ1oz -/e7+2FyhHrB9bwtv1kclHXFfuHcvj0xqD44DzvPN3AL8IcbOEAcN7h/RgpQhQRCa -dmKAzPE/mQKBgQCK9sYyXSReu6mppNEXohmuZAQOVVAhiVcRs9T1Nt3hPCZk23Hm -GT3H9JYMD6aPdypjAOAOKfwYLKiEkTe4ihyq61UuXqLebohPkYVbWHa2+bbyvFMn -nizovquwS8ANmX0tkJCWvQ4AGx0El3ytF4qxnC3oSx25nEc6fWKpr96dhQKBgGxS -Ck+5sD7Ef8eg+qFHdJk6/xDjq5Bn5/UnyR8fZFTNF8rsyut3C1uuOv2NB3g3f2nF -h4CdgNNHiwUlvwq+rFOje1n7WnPDXdSRDZbSQR6jkhn2Dyt0sZfFKxSQl2RVxaBj -NhCFpy4AnBi6NFH2P9Ndfoxgfuno/fcvkf7CMrRZAoGAS4kXN8J3TZnslU3Xf8cL -ivxn7lkNZn1cMzZtkABuO9R5npQFYebljflwPXtNvn1/D+/o45MeQtrRnxJrUdl8 -71vG8emrn4dv1uspTVEr+Q235Zb7yUohpLBKr7MrPEFFGdU9y/4VSvekUubWDMnM -W2L9sB3tmBMPmieSXqhrvLg= ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_384.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_384.pem deleted file mode 100644 index 5cdedc5ad2..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_384.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA384 - Salt Length: 48 - Key Security Level: Medium (2048 bits) - -modulus: - 00:dd:07:da:a8:65:55:09:ee:be:0b:c6:9d:95:05:28 - f6:d6:0b:d6:dd:31:7f:e9:b4:3c:53:0b:2d:ef:f1:bf - 92:13:14:9f:09:11:08:a1:d4:49:ff:8a:51:5e:45:62 - e0:63:7e:9d:18:68:bd:93:fe:42:a5:46:de:5b:06:d6 - 90:28:98:10:fd:ef:5d:0b:f9:a4:7c:f9:ce:68:2a:6c - 5d:78:5a:11:a7:d3:77:3a:49:c9:01:73:80:40:50:56 - df:1e:e6:21:d7:7b:9b:14:0b:00:fc:09:f7:97:9a:39 - 50:6d:ea:e9:c1:b1:47:ca:1a:c5:49:79:8e:42:2a:74 - e9:51:81:14:07:f2:51:59:72:b1:de:5a:09:72:de:77 - 90:62:e0:f7:96:64:07:7f:6d:83:c0:ed:82:6f:61:20 - 65:2a:09:ef:bd:8a:66:74:4c:2a:60:63:b9:91:6f:f7 - 55:aa:bd:d4:a0:a1:d5:a2:2f:20:8f:f8:19:45:60:93 - ba:19:2d:b4:eb:cf:8c:ea:1d:3b:2e:1f:99:82:66:79 - cb:c8:1b:1c:b2:a9:1d:bd:67:a0:39:e4:a2:59:14:67 - 69:0e:62:45:53:e2:8b:63:9f:38:cf:c0:dd:d1:c6:76 - b8:a2:87:78:08:31:38:28:e9:cc:25:98:69:fa:20:c8 - f1: - -public exponent: - 01:00:01: - -private exponent: - 54:12:88:b9:44:d1:f3:d5:3b:b4:7e:f7:b1:97:24:dd - be:cd:02:0d:60:a6:a6:de:47:93:ce:cc:ca:57:c9:e6 - 66:1b:91:e2:80:f8:27:95:f8:0f:9b:2d:18:0e:8c:6d - 8d:6a:bb:96:6d:40:ae:ea:27:af:76:25:5d:ba:5c:22 - b9:4e:1e:28:78:c3:8b:aa:89:46:80:3e:62:a0:c0:57 - 4d:4f:f5:27:40:e8:38:e3:97:f1:55:5d:93:18:fb:f2 - 22:6e:a6:b0:af:f3:6c:cc:42:b3:9b:96:f1:b3:57:d9 - 9f:f5:9a:b4:72:1a:3c:65:b2:65:20:37:5c:33:8a:03 - ff:ee:a7:73:42:38:40:0f:3e:af:73:c0:38:b0:21:c0 - 24:30:04:85:d5:01:0e:4e:4b:98:db:19:fb:88:39:de - c1:b0:ca:94:1a:f6:be:8d:c3:bb:b7:10:34:6f:53:c3 - 77:b8:ed:f2:b1:66:8f:f6:6e:a8:b4:d2:70:51:8c:b2 - 27:59:5e:01:9e:7e:b2:4d:a4:2a:7a:09:2f:cb:e7:f7 - d8:dd:a1:f7:97:61:cb:17:2c:5f:02:19:84:1c:54:c8 - 31:e3:50:b0:26:26:4f:7a:d9:c0:fe:4e:7b:b6:7d:b5 - bb:86:d9:67:10:47:7d:62:7b:e4:b4:9a:5e:c9:aa:01 - - -prime1: - 00:dd:5c:98:01:6c:e3:b1:f0:37:8b:d1:37:78:77:9b - 1a:f2:26:c2:b5:8a:58:9b:f0:f2:bb:cc:66:23:ea:8a - 9c:50:62:e6:d6:ea:11:ba:f3:ee:84:fd:9d:45:3e:ca - 55:65:11:46:46:1e:03:58:23:54:44:03:d9:85:50:43 - ac:97:27:bf:e1:5e:a9:17:a9:43:cf:e4:6e:d3:09:0c - 6c:11:74:8c:7d:dd:ed:be:96:bb:5b:d3:b9:c1:83:b3 - a3:70:52:d4:74:1c:d5:78:31:73:2b:1b:c0:dc:28:f8 - 51:55:4a:cf:16:b3:03:b1:58:d2:b7:df:bc:cb:6f:5f - bd: - -prime2: - 00:ff:9e:00:1d:18:dd:09:08:e6:20:10:b5:ea:c9:d5 - b8:17:2c:ce:c7:9c:d1:08:22:95:e0:41:1f:59:3e:2b - 91:07:80:21:7f:61:73:ae:74:24:c1:7d:a6:33:e0:e8 - 20:07:ed:e4:fd:d9:55:65:ae:7b:76:a3:c9:10:35:26 - 47:78:0b:d1:45:a1:31:dc:d7:a3:52:17:24:ff:55:4b - d0:c0:9e:12:73:f5:51:d1:89:ab:75:6a:0b:08:b7:8d - 9a:d3:d6:3b:c3:ee:e3:0c:47:8e:7a:01:4c:57:d2:cc - 7d:b7:bf:3d:02:cf:8e:0a:b0:43:4b:b4:15:d0:aa:17 - 45: - -coefficient: - 00:d2:c8:fc:3a:8c:28:d3:15:6f:0b:7b:51:7f:a9:8b - 3c:f5:ed:f5:6b:d1:d7:e4:e9:c8:46:16:80:1c:f8:78 - fc:10:bf:55:13:67:5a:a2:e6:2b:51:86:ca:d1:53:20 - 1e:e4:f8:82:ca:cd:4a:56:ba:bc:7a:dc:16:ba:16:43 - ca:66:21:f2:73:1b:ca:de:60:95:d1:b8:7b:ad:e1:1d - d5:48:2f:87:83:40:00:a4:ea:ac:2e:4b:a6:c8:b1:4a - 90:16:aa:e5:9c:91:a9:ee:57:ec:5d:13:b6:6d:bc:a6 - ef:b9:1b:b5:7c:44:21:24:06:c7:08:97:16:57:22:5f - d3: - -exp1: - 35:1f:b3:9b:23:f6:c1:0d:55:47:48:be:77:3a:bd:0e - 8a:6e:a2:eb:ce:77:d5:74:cd:cc:24:11:9f:2c:fa:76 - e9:13:d3:32:60:9a:40:b3:a9:da:60:c3:0d:8b:34:23 - aa:4d:aa:ff:c8:d4:24:a2:d5:e6:3c:c6:47:28:2c:15 - 8f:71:0a:ab:9b:7c:19:21:96:14:9e:4d:ba:77:c1:73 - 6d:fc:fa:7a:7a:78:43:f5:08:a1:d0:fe:13:62:f8:09 - 91:3b:4f:a1:4e:0a:2c:fe:31:15:77:63:a1:72:73:a5 - 91:42:92:d0:6f:c5:c3:19:fd:f8:02:c9:dc:48:ae:41 - - -exp2: - 00:b4:33:35:8f:4d:ac:dd:26:a9:dc:a7:0b:28:06:bb - a4:b8:a9:bc:e8:59:b3:be:d1:6a:e9:19:df:b8:b1:2c - 53:64:7f:3e:9e:27:1c:3f:3a:df:82:8c:4a:b3:bd:f4 - c6:47:f0:bc:82:fc:48:c8:92:f5:b4:d0:87:f8:e6:0f - 23:49:0c:c3:ae:1b:92:24:46:dc:7b:0d:97:e6:6c:c2 - 32:da:e7:54:c8:ec:83:8e:7d:48:23:50:eb:90:6c:9d - e6:2d:3a:95:0d:6e:86:1f:6c:fe:93:22:01:28:d4:91 - 96:7b:07:d5:41:fb:01:fe:a4:fd:fc:0b:6b:69:9b:cf - 25: - - -Public Key PIN: - pin-sha256:KV163ICyMOUr6z/cxe1yQ1x2GIwCrmZAG9iOyW244lg= -Public Key ID: - sha256:295d7adc80b230e52beb3fdcc5ed72435c76188c02ae66401bd88ec96db8e258 - sha1:0c3cb2bad4f2115a013b50d9cb9f7ddf183e6012 - ------BEGIN PRIVATE KEY----- -MIIE7gIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAqEaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgKiAwIBMASCBKgwggSkAgEAAoIBAQDdB9qoZVUJ7r4L -xp2VBSj21gvW3TF/6bQ8Uwst7/G/khMUnwkRCKHUSf+KUV5FYuBjfp0YaL2T/kKl -Rt5bBtaQKJgQ/e9dC/mkfPnOaCpsXXhaEafTdzpJyQFzgEBQVt8e5iHXe5sUCwD8 -CfeXmjlQberpwbFHyhrFSXmOQip06VGBFAfyUVlysd5aCXLed5Bi4PeWZAd/bYPA -7YJvYSBlKgnvvYpmdEwqYGO5kW/3Vaq91KCh1aIvII/4GUVgk7oZLbTrz4zqHTsu -H5mCZnnLyBscsqkdvWegOeSiWRRnaQ5iRVPii2OfOM/A3dHGdriih3gIMTgo6cwl -mGn6IMjxAgMBAAECggEAVBKIuUTR89U7tH73sZck3b7NAg1gpqbeR5POzMpXyeZm -G5HigPgnlfgPmy0YDoxtjWq7lm1Aruonr3YlXbpcIrlOHih4w4uqiUaAPmKgwFdN -T/UnQOg445fxVV2TGPvyIm6msK/zbMxCs5uW8bNX2Z/1mrRyGjxlsmUgN1wzigP/ -7qdzQjhADz6vc8A4sCHAJDAEhdUBDk5LmNsZ+4g53sGwypQa9r6Nw7u3EDRvU8N3 -uO3ysWaP9m6otNJwUYyyJ1leAZ5+sk2kKnoJL8vn99jdofeXYcsXLF8CGYQcVMgx -41CwJiZPetnA/k57tn21u4bZZxBHfWJ75LSaXsmqAQKBgQDdXJgBbOOx8DeL0Td4 -d5sa8ibCtYpYm/Dyu8xmI+qKnFBi5tbqEbrz7oT9nUU+ylVlEUZGHgNYI1REA9mF -UEOslye/4V6pF6lDz+Ru0wkMbBF0jH3d7b6Wu1vTucGDs6NwUtR0HNV4MXMrG8Dc -KPhRVUrPFrMDsVjSt9+8y29fvQKBgQD/ngAdGN0JCOYgELXqydW4FyzOx5zRCCKV -4EEfWT4rkQeAIX9hc650JMF9pjPg6CAH7eT92VVlrnt2o8kQNSZHeAvRRaEx3Nej -Uhck/1VL0MCeEnP1UdGJq3VqCwi3jZrT1jvD7uMMR456AUxX0sx9t789As+OCrBD -S7QV0KoXRQKBgDUfs5sj9sENVUdIvnc6vQ6KbqLrznfVdM3MJBGfLPp26RPTMmCa -QLOp2mDDDYs0I6pNqv/I1CSi1eY8xkcoLBWPcQqrm3wZIZYUnk26d8Fzbfz6enp4 -Q/UIodD+E2L4CZE7T6FOCiz+MRV3Y6Fyc6WRQpLQb8XDGf34AsncSK5BAoGBALQz -NY9NrN0mqdynCygGu6S4qbzoWbO+0WrpGd+4sSxTZH8+niccPzrfgoxKs730xkfw -vIL8SMiS9bTQh/jmDyNJDMOuG5IkRtx7DZfmbMIy2udUyOyDjn1II1DrkGyd5i06 -lQ1uhh9s/pMiASjUkZZ7B9VB+wH+pP38C2tpm88lAoGBANLI/DqMKNMVbwt7UX+p -izz17fVr0dfk6chGFoAc+Hj8EL9VE2daouYrUYbK0VMgHuT4gsrNSla6vHrcFroW -Q8pmIfJzG8reYJXRuHut4R3VSC+Hg0AApOqsLkumyLFKkBaq5ZyRqe5X7F0Ttm28 -pu+5G7V8RCEkBscIlxZXIl/T ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_512.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_512.pem deleted file mode 100644 index 82ab5d95bb..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-key-rsa_pss_512.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA512 - Salt Length: 64 - Key Security Level: Medium (2048 bits) - -modulus: - 00:d4:ed:b5:a7:85:5a:ba:9c:02:b8:fc:02:46:1e:e3 - 6c:54:34:72:3c:fc:56:eb:0b:ad:9d:95:83:a3:09:15 - 9d:f1:e7:1a:93:21:3e:b5:b3:64:7f:98:83:97:a2:b7 - ca:02:c4:48:a2:55:3f:29:b8:b1:87:61:6d:72:5f:7a - 9f:20:69:f4:82:2c:7e:48:0d:d6:57:40:92:2c:13:9f - e5:44:75:d4:ad:41:f6:c9:f4:74:c4:31:14:dd:44:8c - ec:25:5b:4f:07:51:bc:4e:21:bd:47:c9:e8:56:b2:1e - f1:5d:e0:56:36:c8:18:18:86:71:41:bb:c2:3c:06:ca - e4:71:f2:cd:ec:9f:09:a0:05:6e:b4:d9:32:65:53:9b - 5a:7a:b9:a2:30:7a:cd:06:a6:47:3f:f4:05:9e:87:b7 - 2f:b2:e0:fc:63:c5:ec:2c:19:ed:32:ad:ee:71:9c:37 - d1:34:f3:aa:1a:ba:ed:cf:40:28:82:43:11:54:83:74 - 42:db:70:f7:58:12:c5:11:af:1a:05:26:24:ef:81:8a - 26:ee:2c:f3:8a:c4:2c:0c:47:cc:76:2b:7a:ce:e0:bb - 80:d2:d0:5e:c8:8f:1d:03:c5:4c:47:1b:7b:90:c4:d3 - 0b:9f:8b:6e:29:bd:ab:25:cd:aa:1e:ad:72:19:02:c0 - 11: - -public exponent: - 01:00:01: - -private exponent: - 01:23:1b:db:3f:2d:12:de:0e:6d:aa:7a:e0:a0:fd:99 - f0:81:2f:33:00:2d:fe:a7:5b:50:02:22:67:d6:7e:95 - 0f:5b:aa:9a:aa:8c:c9:2f:a2:13:c4:5e:bf:8a:90:ec - b5:43:13:18:3a:d8:51:82:b8:ff:fe:17:35:8b:28:fe - 7c:8f:d4:4c:75:ac:5e:fa:23:f0:e7:59:60:7e:e2:55 - b9:1d:df:fa:e4:e5:4a:82:d1:b4:d2:86:48:00:3b:b8 - 6f:22:a3:b3:68:4e:57:24:7a:fc:4d:29:be:7c:c9:09 - 84:f4:d3:c1:0b:24:85:cd:02:01:d5:dc:dd:b1:33:98 - 2e:3c:e5:7c:69:e2:e7:e4:02:83:b5:e8:d0:05:c5:cd - 5b:8e:72:f7:ee:b2:d4:11:15:85:b3:b3:4f:ac:cf:77 - 81:73:68:a9:70:fc:b3:94:24:f9:77:f5:38:4f:af:ab - cb:4e:7f:c2:79:76:87:f9:0f:a3:3b:5c:95:61:64:11 - 3a:40:98:28:51:86:48:11:41:30:e2:1a:94:94:06:d0 - 0a:15:de:19:13:9f:f3:06:b8:03:68:8f:87:b2:3a:4f - f3:75:bc:f7:5a:e4:1e:b4:49:29:09:da:57:e4:43:ea - 96:bd:74:e3:f3:38:5a:bd:b3:da:cc:09:99:f6:09:19 - - -prime1: - 00:f0:d9:0a:ee:11:50:da:c9:01:1f:5c:3d:c8:82:3b - 1c:0c:27:17:80:69:fa:d1:9d:ca:d2:7f:12:90:e9:a8 - e5:36:f0:b7:8f:8e:90:f0:0a:78:53:0f:93:51:f0:f4 - 72:a3:1a:de:ea:0f:5e:8f:84:c3:57:39:38:93:73:cf - 94:6e:1a:56:ef:36:d9:22:39:75:76:5b:4e:f6:54:e7 - 02:32:9f:54:5f:1b:02:37:50:f0:49:1b:e0:e6:d1:bd - b8:07:9b:7f:15:fd:ea:53:08:59:e8:17:66:d5:10:e4 - a2:f1:3e:c3:c8:7e:68:a2:a1:5f:04:f1:7b:a6:c5:3c - 73: - -prime2: - 00:e2:53:03:dd:5d:f1:fc:27:a6:d7:01:b1:5e:f3:26 - 5d:9e:fc:f2:45:85:4b:10:86:97:a5:9d:2b:19:3b:35 - 8e:91:36:67:50:d0:da:16:de:c7:13:99:76:b8:9b:2f - 44:fc:6b:c3:29:ec:a7:11:38:05:de:3d:2e:85:1a:49 - 88:28:b6:e0:1b:8f:6a:0a:21:56:ec:ee:56:34:b5:20 - e6:a2:c0:b0:08:c1:48:13:60:e3:65:b1:4a:b9:6c:9b - a4:63:92:2f:5a:e6:6d:80:2a:c2:97:53:87:05:dd:08 - 1d:98:52:c9:88:a9:d3:5d:18:d7:2b:5e:0c:63:e0:94 - 6b: - -coefficient: - 00:8e:60:92:ac:a2:02:d9:67:c7:c5:70:13:d2:b6:2f - 5d:b2:a1:68:0e:46:db:33:f6:8a:a4:bd:06:07:db:5b - 39:62:14:e6:81:95:32:ca:89:b7:dd:87:60:bd:98:33 - 5d:a8:21:25:d9:64:fb:5f:52:a5:28:e8:05:e2:7b:5d - 43:ae:fd:d2:98:fe:20:9e:4e:65:96:11:c4:ae:91:a7 - 36:cb:3d:8d:fe:29:7c:91:bf:8b:45:17:f6:7c:29:41 - 1a:4b:87:85:c2:95:96:d5:8d:c7:5b:7a:29:6e:c3:6a - c6:6f:38:55:f7:9f:aa:27:c4:a7:18:8c:42:f1:b2:94 - 9d: - -exp1: - 7c:76:ed:9b:11:ff:c2:d0:d5:6f:ab:6f:92:4b:1a:d8 - e7:be:db:fa:54:ca:75:c1:21:ab:9e:57:ad:e3:d2:90 - 81:cf:ec:4c:97:d4:76:f8:32:2e:5a:82:3b:7a:56:19 - 58:08:ee:e1:ee:87:63:8b:ac:97:4a:ce:de:04:9f:65 - 89:70:bb:34:6c:17:d2:03:f7:9b:ee:9b:e3:d9:04:78 - b2:48:7c:85:99:a3:8f:8a:98:62:6f:b1:ce:16:de:00 - 58:8e:17:22:fa:51:3a:0f:ba:c6:a2:31:56:32:a0:b5 - 44:0e:b7:86:c9:2c:b1:be:cb:27:f6:d3:7b:df:b9:d9 - - -exp2: - 32:88:88:9f:5f:bf:8d:26:a9:58:ee:76:d5:15:83:66 - 79:fe:4e:75:f9:5a:16:59:86:f8:a2:8c:21:f9:17:6f - 3a:bb:23:fc:66:75:9b:8f:a8:71:96:dd:6c:40:b2:20 - 3c:20:2f:96:67:d1:b1:c5:89:81:e2:b5:45:60:e6:34 - 31:ab:0b:84:fb:d3:98:69:73:48:39:bb:23:cf:a1:85 - fd:a6:fa:67:2a:08:d6:d2:d6:53:39:6f:ce:d1:12:3b - 75:44:09:b0:c9:2c:7f:e6:8c:46:4f:8f:21:5f:05:d5 - dd:d1:f6:4f:be:63:84:30:ec:b2:31:30:a1:08:5e:fb - - - -Public Key PIN: - pin-sha256:xZynWKbgc/clJ1vmaUuUrDqVNLkKBsbEVke+Uj4T30M= -Public Key ID: - sha256:c59ca758a6e073f725275be6694b94ac3a9534b90a06c6c45647be523e13df43 - sha1:c19f5569864001b25aad7ff9de9d200574d2b257 - ------BEGIN PRIVATE KEY----- -MIIE7QIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCA6EaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgOiAwIBQASCBKcwggSjAgEAAoIBAQDU7bWnhVq6nAK4 -/AJGHuNsVDRyPPxW6wutnZWDowkVnfHnGpMhPrWzZH+Yg5eit8oCxEiiVT8puLGH -YW1yX3qfIGn0gix+SA3WV0CSLBOf5UR11K1B9sn0dMQxFN1EjOwlW08HUbxOIb1H -yehWsh7xXeBWNsgYGIZxQbvCPAbK5HHyzeyfCaAFbrTZMmVTm1p6uaIwes0Gpkc/ -9AWeh7cvsuD8Y8XsLBntMq3ucZw30TTzqhq67c9AKIJDEVSDdELbcPdYEsURrxoF -JiTvgYom7izzisQsDEfMdit6zuC7gNLQXsiPHQPFTEcbe5DE0wufi24pvaslzaoe -rXIZAsARAgMBAAECggEAASMb2z8tEt4Obap64KD9mfCBLzMALf6nW1ACImfWfpUP -W6qaqozJL6ITxF6/ipDstUMTGDrYUYK4//4XNYso/nyP1Ex1rF76I/DnWWB+4lW5 -Hd/65OVKgtG00oZIADu4byKjs2hOVyR6/E0pvnzJCYT008ELJIXNAgHV3N2xM5gu -POV8aeLn5AKDtejQBcXNW45y9+6y1BEVhbOzT6zPd4FzaKlw/LOUJPl39ThPr6vL -Tn/CeXaH+Q+jO1yVYWQROkCYKFGGSBFBMOIalJQG0AoV3hkTn/MGuANoj4eyOk/z -dbz3WuQetEkpCdpX5EPqlr104/M4Wr2z2swJmfYJGQKBgQDw2QruEVDayQEfXD3I -gjscDCcXgGn60Z3K0n8SkOmo5Tbwt4+OkPAKeFMPk1Hw9HKjGt7qD16PhMNXOTiT -c8+UbhpW7zbZIjl1dltO9lTnAjKfVF8bAjdQ8Ekb4ObRvbgHm38V/epTCFnoF2bV -EOSi8T7DyH5ooqFfBPF7psU8cwKBgQDiUwPdXfH8J6bXAbFe8yZdnvzyRYVLEIaX -pZ0rGTs1jpE2Z1DQ2hbexxOZdribL0T8a8Mp7KcROAXePS6FGkmIKLbgG49qCiFW -7O5WNLUg5qLAsAjBSBNg42WxSrlsm6Rjki9a5m2AKsKXU4cF3QgdmFLJiKnTXRjX -K14MY+CUawKBgHx27ZsR/8LQ1W+rb5JLGtjnvtv6VMp1wSGrnlet49KQgc/sTJfU -dvgyLlqCO3pWGVgI7uHuh2OLrJdKzt4En2WJcLs0bBfSA/eb7pvj2QR4skh8hZmj -j4qYYm+xzhbeAFiOFyL6UToPusaiMVYyoLVEDreGySyxvssn9tN737nZAoGAMoiI -n1+/jSapWO521RWDZnn+TnX5WhZZhviijCH5F286uyP8ZnWbj6hxlt1sQLIgPCAv -lmfRscWJgeK1RWDmNDGrC4T705hpc0g5uyPPoYX9pvpnKgjW0tZTOW/O0RI7dUQJ -sMksf+aMRk+PIV8F1d3R9k++Y4Qw7LIxMKEIXvsCgYEAjmCSrKIC2WfHxXAT0rYv -XbKhaA5G2zP2iqS9BgfbWzliFOaBlTLKibfdh2C9mDNdqCEl2WT7X1KlKOgF4ntd -Q6790pj+IJ5OZZYRxK6RpzbLPY3+KXyRv4tFF/Z8KUEaS4eFwpWW1Y3HW3opbsNq -xm84VfefqifEpxiMQvGylJ0= ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa.pem deleted file mode 100644 index d49498959c..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgIMWYGU8BDBJ3AgFnsvMA0GCSqGSIb3DQEBCwUAMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzZa -Fw0zNzA3MjgwOTAxMzZaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IENs -aWVudDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM/xijmXl7PVbZwS -BE6h3A2pEsv4Au86itIS4qb7GJNvOZ2pwx22/AOGr/JvsYGGnOsVxQ63mE9xBz2l -jPsqGDhQeLD7CptXZAcwYa6k2z6S91Sd0GCNOgPuFiXKFXt9Si82uNB42r7kHG04 -exmY7uKUdMp1IxUbZ47leBmT7W5I65lK2acxkzRK6bdPErnNGzZt4t/k6E0Oowf6 -ElUf0UvhsX0trFB9O8yvCciqAQoGUw7b1yzWA9bWi1AQUPgx58eGMrRgQXfFnuuG -efHqU+/nAVAt5pHHU0GqB09jcv1lJSQpDMtCBa5tsorVvy8OiiSJx15tIyNOtVcc -9y/oH3cCAwEAAaN2MHQwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcD -AjAPBgNVHQ8BAf8EBQMDB4AAMB0GA1UdDgQWBBSoiZsEL0tgug7IyLHTI1fA+tNH -OjAfBgNVHSMEGDAWgBQrQlWadXqqzBV+2iw7BZXrvFHaQjANBgkqhkiG9w0BAQsF -AAOCAQEAx3E9wM3ASFrxZ8Zw/036WHeJUjgOL+W9TM4Y4GZpQDkyMqKxs3pmyqcU -xuXWV+SmTCkOAvrH/kWhmgDxSs3eGrGBsRPEZcUolcedDWqPJpy0qZH6mv3Ge0+v -V+YOcd0qSVHaLpR1LQHrDnatASaVVRF4Ohk2IRSvjzYYJ158D3+erB79Txt4kqK2 -oDMp59uI2K4VwNiXeuWQgolaoKTEtPSrjuuKzetrwLN8ajii5rkiOKyuKlkZ2SyE -BYp/ye1hzmqXRHNrObbfMmggwimrShYWUSwHp0/gKMEhen+yqd9C2KEVj7dqm+oL -Jo+TGr6L77LBgZ5r7vfzj4tzL877mg== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_256.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_256.pem deleted file mode 100644 index 77ec9737dd..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_256.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID2jCCApKgAwIBAgIUej61CoI5BANd5v/ceHNxIOtR8d0wPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogMC -ASAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0MloXDTM4MTAxOTA2MDY0MlowIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRlc3QgQ2xpZW50MIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQ8AMIIBCgKCAQEA13o6 -AYteWQ8QfZVczsbqyCkudW7+bPmD1T5ybPxWlUPUYjTfBXyzs6ZKN8q24CNEGfws -6s/8+SYarFqNg/hP2Quu/OmddTctpJMCXWkQ37d6TLYFZHNGRbL+pLMznmhrFDWO -7t+74Hcjdrhu/fzy3QJZXtyhs12TxiziSoUhf8pZNuh33f7N/vawlv4UalxoTM+8 -/f7s4y9REM9G2x06Pc2H7GdKfSBeeWzq0yTTggW82Xnlzd9qu2KbILM1NGGuaamr -ubYnrHsz9b7fmrQSaAZVebO6UvCRkGmx8VoR44ve3fGZylqth7plUiemBxJgECST -S98S20kP/CH/n+aSdQIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoG -CCsGAQUFBwMCMA8GA1UdDwEB/wQFAwMHgAAwHQYDVR0OBBYEFAKLYWuJSEnLypED -/PkZ/dogyhAeMB8GA1UdIwQYMBaAFCEaiLbeA8ABgKrbcIiZpo8XzqpsMD0GCSqG -SIb3DQEBCjAwoA0wCwYJYIZIAWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFl -AwQCAaIDAgEgA4IBAQCFjsx2JQ+AtT2AD7harhhhuCH8ah9hTLz1n+ynkmq1lmYP -JCudOJfgWjMFlSv1ptzkvOst+Ig2BCCJrwX1akMX1cMsR/eoDUxxkqREU/irEYPj -ePvVk0+bd6C4+nCvs/J0bv5P/16z2NLmAq8BUidi4ULPyzVn/+nAAUpAVlYi/mHP -RQCy8UMj2ENACc4LIP1tek9cp+t5JMjsv2ogy+SPCXtq7VTMAFrckrALv9b1QLE6 -J06bp7+Q7GIkn0gTm+Z5AaddHH1ZDjqpYFcngx7wVuQCbZwTqnVJx5nQrKz+HQYt -87KWIhR2nbtygp2oZESXQg9huH395f/h+foYArPG ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_384.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_384.pem deleted file mode 100644 index dda273d859..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_384.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID2jCCApKgAwIBAgIUbdDLDIxL8QBkB4RFPZ3TaeInTUcwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgKhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAICogMC -ATAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0MloXDTM4MTAxOTA2MDY0MlowIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRlc3QgQ2xpZW50MIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAqEa -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgKiAwIBMAOCAQ8AMIIBCgKCAQEA3Qfa -qGVVCe6+C8adlQUo9tYL1t0xf+m0PFMLLe/xv5ITFJ8JEQih1En/ilFeRWLgY36d -GGi9k/5CpUbeWwbWkCiYEP3vXQv5pHz5zmgqbF14WhGn03c6SckBc4BAUFbfHuYh -13ubFAsA/An3l5o5UG3q6cGxR8oaxUl5jkIqdOlRgRQH8lFZcrHeWgly3neQYuD3 -lmQHf22DwO2Cb2EgZSoJ772KZnRMKmBjuZFv91WqvdSgodWiLyCP+BlFYJO6GS20 -68+M6h07Lh+ZgmZ5y8gbHLKpHb1noDnkolkUZ2kOYkVT4otjnzjPwN3Rxna4ood4 -CDE4KOnMJZhp+iDI8QIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoG -CCsGAQUFBwMCMA8GA1UdDwEB/wQFAwMHgAAwHQYDVR0OBBYEFAw8srrU8hFaATtQ -2cuffd8YPmASMB8GA1UdIwQYMBaAFKnwXW9hoPAB6HSyWn7UEUMcKonnMD0GCSqG -SIb3DQEBCjAwoA0wCwYJYIZIAWUDBAICoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFl -AwQCAqIDAgEwA4IBAQAHS+4AoR5A0sNaCrhuB8rfDfI+kcO0SqwT98d5QTJnsiqu -/2OHecJbN7nkYKh9K+8ccWVCWncWV1dFP1fVnCibFpAF+750wLhSpb/RVfm8Gd8F -CLuZNC6i9w7ssQzus7SpBx2viY615zxRJ6kdhGhPSxc98tPAHkdkdWGWq0R8Q3u9 -hP/mj/oAxskhvF/Lofwk5uyYSNIcZ9w3YPmb70OUWDH1yreF7s0J3hOPZZiC7ZA4 -Nao6UPpwKk1IdZix63xHFwCN21AtQIHoL/aRcVSlHlol5VOgaWbetb1BTBqEoKux -s4hJIMFIslA++GDX/qj7JrYr+FJTOqFF2B+Rm7wO ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_512.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_512.pem deleted file mode 100644 index 2bc13ae96f..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-client-rsa_pss_512.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID2jCCApKgAwIBAgIUWlbiagMGpRhGjEwawdwRz964ObEwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgOhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIDogMC -AUAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0M1oXDTM4MTAxOTA2MDY0M1owIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRlc3QgQ2xpZW50MIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCA6Ea -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgOiAwIBQAOCAQ8AMIIBCgKCAQEA1O21 -p4VaupwCuPwCRh7jbFQ0cjz8VusLrZ2Vg6MJFZ3x5xqTIT61s2R/mIOXorfKAsRI -olU/Kbixh2Ftcl96nyBp9IIsfkgN1ldAkiwTn+VEddStQfbJ9HTEMRTdRIzsJVtP -B1G8TiG9R8noVrIe8V3gVjbIGBiGcUG7wjwGyuRx8s3snwmgBW602TJlU5taermi -MHrNBqZHP/QFnoe3L7Lg/GPF7CwZ7TKt7nGcN9E086oauu3PQCiCQxFUg3RC23D3 -WBLFEa8aBSYk74GKJu4s84rELAxHzHYres7gu4DS0F7Ijx0DxUxHG3uQxNMLn4tu -Kb2rJc2qHq1yGQLAEQIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoG -CCsGAQUFBwMCMA8GA1UdDwEB/wQFAwMHgAAwHQYDVR0OBBYEFMGfVWmGQAGyWq1/ -+d6dIAV00rJXMB8GA1UdIwQYMBaAFKVY4bgN1p+8NOXoPdj6DKWDscBFMD0GCSqG -SIb3DQEBCjAwoA0wCwYJYIZIAWUDBAIDoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFl -AwQCA6IDAgFAA4IBAQBm9QAlG/xd8O6/TgJwnxmjKcSNhWgFHz4yY2uSMRP51VR/ -SzoXIY3drTWz3fuXSxbjAcVSlfmSX3KMVm1M6IKOw37PwUD8C5oVpLEY/NpwTjfb -WS5RR0XpAi2JJhPa9vJEO8PMdDV5C07u3fs5QvysNPZqJJvn+i2rU44JTeeJzBf8 -hesUVx4m+16C4cdU80prTnq9QYnZi08vIJ0iW0czxrsRikcqAnb+FEsrnbl1t3Wy -PcdYUq7SkQ3B3pnreOMRnRGGP0dq4YOPto6nKD2h70TQ2rH2JhSlDy7aPNx9jUKO -dwz0hfct7G7Wyoz2U+rI7ulHt3Mck4DyOam+TMEJ ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-dsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-dsa.pem deleted file mode 100644 index 029d88ac24..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-dsa.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEpjCCBEygAwIBAgIMWYGU8C09TIACbzDkMAsGCWCGSAFlAwQDAjAjMSEwHwYD -VQQDExhCb3VuY3lDYXN0bGUgVExTIFRlc3QgQ0EwHhcNMTcwODAyMDkwMTM2WhcN -MzcwNzI4MDkwMTM2WjAjMSEwHwYDVQQDExhCb3VuY3lDYXN0bGUgVGVzdCBTZXJ2 -ZXIwggNGMIICOQYHKoZIzjgEATCCAiwCggEBAKIJ4msqhhMj/QtISZhmqwZzwvxo -9G4/z6zraDROzwt4KfCM+4Iplzb54xi4iifAKFjzegL066KAYuZEu3c5oU+1t2WT -Uz4WaD/F8jpA/p8/iMp7d/Aj+qwHoIewZmtFN7OyTvIgPFUtzKShwsA/FGxQzDbw -XOtsQ77WFdLa7B+1ZjFC776KbzNzZG0iClfZL0NweKYAGjdkJ6GKDJsKwkzWJ/wV -2fKew8GzvUKiUVamMN6QXVx8x7odGETBu5FB0bP4wCKqnQKLarfHRspynA8rCNHF -mW5CMGDQm+zaehpcgIOnsJE8xb9C7bzzFmkWxEy5DJmYPtnKEBDWz6XjdmUCIQCn -T2W/xqEt+tix4k4f/a/0D3i7iawNewwccUb4C5RcYQKCAQAs4tv1yBjpGvsspRpL -rxdAcIXhCeBQCzoYMI4CFH3lSjotUT5T30h2fA3qi3bm0GhnuAw7a1s3H749MAKm -P9RgskHkeyFoWWKJ5rVqz+KOBXQkhRDkGND5hYdBgMq5YnnDQ7O0D0621AovPOex -UQFVl2/4bJ/FRCPZ3NL790XwZNL0v/XFTDU1eL5CcSOwsENTfCpPa+6nnO4K/Gtr -QV4mCpY8dwtQB9lTB6BuhuMQ5Bmu+JVaVaGDIP8pd1ZXxPg9WQcZY+sFRz5zkiBm -Fs/+rbTnUC6Lx5T3tMBGhWC7+VmJNeT3eVzvMU7tgGGIElsQC1/5xU6pzRAL4/It -ijN3A4IBBQACggEAYi/1HWMttEK5mU2B6IpU6pgUmkUleSVrQo3tdMViiSlGPtB6 -c+yoZc3GxruCUHIYbN+rFNIsdoJQ2k9Ah4VkX6mBytopd5eulwG63DDrXCRgxqMm -BHFNvcZ/OG1Lj8Upnf9x9GbJwzoV+4J/tF/al9XlUk9gJf2zfr7oq6NAqvHXsaHj -4oC3FQV0enQdfnC325wVie+BrV5hE/YUgcYF5m2R3a0o4UokGqyJzxDjxLlrtMHe -6Rn7JngDfq7oFNXN1BMu9RD0Ll2KwZFURzZMAzj5DNc8eAScTC7omVrk6/lsQ1TW -tnlOm7QXoBcRINwrA9hoTAgPh7iyqr8497M2yqN2MHQwDAYDVR0TAQH/BAIwADAT -BgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHQ8BAf8EBQMDB4AAMB0GA1UdDgQWBBQL -IkWyCawkb1V1BkwW61qMAd3TnTAfBgNVHSMEGDAWgBQA5WZqsOvPVi3KO+dfgL1w -NxeVqDALBglghkgBZQMEAwIDRwAwRAIgUHB/GqyakK8awZlbR6MsLGDz0UiCvfCR -eK2qrGSqsfICICKrf9+KyfiDh5HoB4pPZDOAAd5yQIEclw/aOD1yq0wT ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ecdh.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ecdh.pem deleted file mode 100644 index 7c8f044352..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ecdh.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBtjCCAVygAwIBAgIMWYGU8BHdfIBy0aZkMAoGCCqGSM49BAMCMCMxITAfBgNV -BAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzZaFw0z -NzA3MjgwOTAxMzZaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IFNlcnZl -cjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABLWCgejCbKGDGpoTzBtYGeQt3OSZ -B3aPwiAaQog3VfsSsERXWAiUdogMibtR4lLl6s9QbWDorQWXhejIUi7woY2jdjB0 -MAwGA1UdEwEB/wQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0PAQH/BAUD -AweIADAdBgNVHQ4EFgQU0L5LXF6oiQE1eNyzRztmBOoHiR0wHwYDVR0jBBgwFoAU -0ma/FGcW5gGlL//B26Xmj0JISecwCgYIKoZIzj0EAwIDSAAwRQIhAM6F/DDKK7H9 -HbkqCcUsxTCTakQ1wcAkkRDMCI/lKLxCAiAUjBMndyVRzNlY6h4+2NP0A3RT2Q87 -2mnmiPSuW9Q4iw== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ecdsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ecdsa.pem deleted file mode 100644 index ffaa81e9f6..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ecdsa.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBtjCCAVygAwIBAgIMWYGU8C5XSABmYVGJMAoGCCqGSM49BAMCMCMxITAfBgNV -BAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzZaFw0z -NzA3MjgwOTAxMzZaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IFNlcnZl -cjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABKzro1Qhiu2IrXTK1X9xZ20T0eL0 -vxwmwTGcr7EvI9kRnhXDsV5Har9CmzInfIcOhL9VlS4K2WUhxNMuLYr5EIKjdjB0 -MAwGA1UdEwEB/wQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0PAQH/BAUD -AweAADAdBgNVHQ4EFgQUNjGYYKninT7GGg2A3pGsO2xPByIwHwYDVR0jBBgwFoAU -0ma/FGcW5gGlL//B26Xmj0JISecwCgYIKoZIzj0EAwIDSAAwRQIgWYw3r0KqlS60 -h4RON2Ycq7oH2qxf+b9mWaehP8sebHoCIQDJyu+qUegmitkVqbenVV2ypPL7x2nP -qvghAKPod/72bg== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ed25519.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ed25519.pem deleted file mode 100644 index df3a379c4b..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ed25519.pem +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBfjCCATCgAwIBAgIUEOZLZhsVbmqCJUugm0oRFrWPO8swBQYDK2VwMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xODA4MjMwOTI5NDda -Fw0zODA4MTgwOTI5NDdaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IFNl -cnZlcjAqMAUGAytlcAMhAM2PquzCzWQdU5dEG7JMCCfvaaNyfRlcIhsCzF8RLWiw -o3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1UdDwEB -/wQFAwMHgAAwHQYDVR0OBBYEFFsSy04J6VkN2IiqBJKGV26iMRYyMB8GA1UdIwQY -MBaAFOp5vj76ByEwboduoHWAWzajnM1mMAUGAytlcANBAOhCpwpdClN4+DFhtwLf -br8//ymNpCOf8W4vE4pZACueKIooh2S4WnbkFwBloOntxX+4TXnD06SBlpcmoQg2 -NwY= ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ed448.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ed448.pem deleted file mode 100644 index 3ba371f662..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-ed448.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIByTCCAUmgAwIBAgIUdWna0n25+zzo6pW93hOpSKLfU0swBQYDK2VxMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0yMDAyMTMwNzMzMDJa -Fw00MDAyMDgwNzMzMDJaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IFNl -cnZlcjBDMAUGAytlcQM6AETFuJ7D3g4EgZnNVbPW3j81X6VpJane2pY04n8bzYcs -kAvfb5lGogDBoczMsB9opnPMdSwZQs6CAKN2MHQwDAYDVR0TAQH/BAIwADATBgNV -HSUEDDAKBggrBgEFBQcDATAPBgNVHQ8BAf8EBQMDB4AAMB0GA1UdDgQWBBTHz9U/ -S0PulhuJNX8vOdBOjnLCqjAfBgNVHSMEGDAWgBS+BSv++BEWlTJ53q6rwnDLVnR5 -JTAFBgMrZXEDcwAp/84ZggkOUHT0qCL/8a3Qmj6HyXeb8NNVyPNSbBgW6HVQsn9c -wquAbara1d9VFJ+ucpSdQfYPs4DVfxADVcVfaunEGujBoL9U3q/9XIJ5IT70HL1O -+PUERelTyKywKQI8Y2YYKUH6UYsesLhcAQ8DBwA= ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-dsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-dsa.pem deleted file mode 100644 index 73247089ce..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-dsa.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICZAIBADCCAjkGByqGSM44BAEwggIsAoIBAQCiCeJrKoYTI/0LSEmYZqsGc8L8 -aPRuP8+s62g0Ts8LeCnwjPuCKZc2+eMYuIonwChY83oC9OuigGLmRLt3OaFPtbdl -k1M+Fmg/xfI6QP6fP4jKe3fwI/qsB6CHsGZrRTezsk7yIDxVLcykocLAPxRsUMw2 -8FzrbEO+1hXS2uwftWYxQu++im8zc2RtIgpX2S9DcHimABo3ZCehigybCsJM1if8 -FdnynsPBs71ColFWpjDekF1cfMe6HRhEwbuRQdGz+MAiqp0Ci2q3x0bKcpwPKwjR -xZluQjBg0Jvs2noaXICDp7CRPMW/Qu288xZpFsRMuQyZmD7ZyhAQ1s+l43ZlAiEA -p09lv8ahLfrYseJOH/2v9A94u4msDXsMHHFG+AuUXGECggEALOLb9cgY6Rr7LKUa -S68XQHCF4QngUAs6GDCOAhR95Uo6LVE+U99IdnwN6ot25tBoZ7gMO2tbNx++PTAC -pj/UYLJB5HshaFliiea1as/ijgV0JIUQ5BjQ+YWHQYDKuWJ5w0OztA9OttQKLzzn -sVEBVZdv+GyfxUQj2dzS+/dF8GTS9L/1xUw1NXi+QnEjsLBDU3wqT2vup5zuCvxr -a0FeJgqWPHcLUAfZUwegbobjEOQZrviVWlWhgyD/KXdWV8T4PVkHGWPrBUc+c5Ig -ZhbP/q2051Aui8eU97TARoVgu/lZiTXk93lc7zFO7YBhiBJbEAtf+cVOqc0QC+Py -LYozdwQiAiAxcsCPJCsRaG0j1eDW0xomfipUvAM3Ws9MZ38R8fxQ/A== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ecdh.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ecdh.pem deleted file mode 100644 index 669fc5cd0d..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ecdh.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGUAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHoweAIBAQQhAJsXqInsRDYS26zX -d4tHYu+WKbw2gyrnMvDOamsRyZg5oAoGCCqGSM49AwEHoUQDQgAEtYKB6MJsoYMa -mhPMG1gZ5C3c5JkHdo/CIBpCiDdV+xKwRFdYCJR2iAyJu1HiUuXqz1BtYOitBZeF -6MhSLvChjQ== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ecdsa.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ecdsa.pem deleted file mode 100644 index ca898da2fe..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ecdsa.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgHJsLqw/ZeIlLMmMZ -u+LqjbxD7OY2VhD055Icbpp5HBmgCgYIKoZIzj0DAQehRANCAASs66NUIYrtiK10 -ytV/cWdtE9Hi9L8cJsExnK+xLyPZEZ4Vw7FeR2q/QpsyJ3yHDoS/VZUuCtllIcTT -Li2K+RCC ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ed25519.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ed25519.pem deleted file mode 100644 index e1784c5efd..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ed25519.pem +++ /dev/null @@ -1,25 +0,0 @@ -Public Key Info: - Public Key Algorithm: EdDSA (Ed25519) - Key Security Level: High (256 bits) - -curve: Ed25519 -private key: - f8:32:a1:54:10:e9:b2:b2:31:10:9d:05:c0:3b:58:c5 - 1d:1b:7a:67:d1:53:5e:6b:58:fe:85:1f:4a:4e:71:13 - - -x: - cd:8f:aa:ec:c2:cd:64:1d:53:97:44:1b:b2:4c:08:27 - ef:69:a3:72:7d:19:5c:22:1b:02:cc:5f:11:2d:68:b0 - - - -Public Key PIN: - pin-sha256:tt5u5+ynOHjlD3uadUUmN2V5yZLekOkkwyyk8sZH7cI= -Public Key ID: - sha256:b6de6ee7eca73878e50f7b9a754526376579c992de90e924c32ca4f2c647edc2 - sha1:5b12cb4e09e9590dd888aa049286576ea2311632 - ------BEGIN PRIVATE KEY----- -MC4CAQAwBQYDK2VwBCIEIPgyoVQQ6bKyMRCdBcA7WMUdG3pn0VNea1j+hR9KTnET ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ed448.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ed448.pem deleted file mode 100644 index 382cdd6189..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-ed448.pem +++ /dev/null @@ -1,28 +0,0 @@ -Public Key Info: - Public Key Algorithm: EdDSA (Ed448) - Key Security Level: Ultra (456 bits) - -curve: Ed448 -private key: - af:0f:44:88:c8:11:f7:e4:87:19:b2:e5:f2:17:a4:e5 - 0a:69:78:ed:1c:34:f1:dd:8a:b1:c6:92:92:64:26:94 - 8f:46:45:af:b6:58:d5:b1:20:ce:5e:d6:b7:8e:48:e9 - 0e:14:a7:94:56:d5:14:c8:9d: - -x: - 44:c5:b8:9e:c3:de:0e:04:81:99:cd:55:b3:d6:de:3f - 35:5f:a5:69:25:a9:de:da:96:34:e2:7f:1b:cd:87:2c - 90:0b:df:6f:99:46:a2:00:c1:a1:cc:cc:b0:1f:68:a6 - 73:cc:75:2c:19:42:ce:82:00: - - -Public Key PIN: - pin-sha256:un7RlIHaUdVuKc7nlN4TlmbH42dUsl+RH5jeVUKSyiA= -Public Key ID: - sha256:ba7ed19481da51d56e29cee794de139666c7e36754b25f911f98de554292ca20 - sha1:c7cfd53f4b43ee961b89357f2f39d04e8e72c2aa - ------BEGIN PRIVATE KEY----- -MEcCAQAwBQYDK2VxBDsEOa8PRIjIEffkhxmy5fIXpOUKaXjtHDTx3YqxxpKSZCaU -j0ZFr7ZY1bEgzl7Wt45I6Q4Up5RW1RTInQ== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa-enc.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa-enc.pem deleted file mode 100644 index d1e835252a..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa-enc.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC3mOPbXv2BWujn -fNGxYw/JNbyW7qQTaKnZogE/aIh5m86hinj7agtV2UDsBXvaQSTrp8vXwKNr9IYX -VLEvT5lM8mj+GDlJ1jhKbo1ODbZPY7b1q5e1RtMUhNX3GgZDevrLL0Tt/g912KD4 -U7vTsS2TQ35hXOQ6bknN9VWNhat0lQ/L60q2QofPdk9PydFZV9CxkoGvwV1BqiTp -JiEloFAf3h07Gim/e3K6OlU2ci+Lb6/uvSDPiOIVYPBURmVjs49sLha2jDj51II4 -9KpPbJwNUT902VrvoRwhrWP8FxYO0QxG9J07IdsNLQLzVWBxz03qK3v+U/akO1QQ -uyrWmw69AgMBAAECggEBAJd3t2RgddymV8fDHmyuQXPKtY//ybWJf7dhBI5/ezh4 -5nw3daBV2Iw29GzECW4CmKcig/W3pBuIXKga4yMZFGx7AUvASGM2LLKbilB+142f -wm3j5wFTMQmYnb2C5u/9IbNHiCKgm7ipxAObcTYw0lzQLg+9Rz09h/43DSH4yX8f -ov1ANiERjkjTMYfaoMbdVrik3MrzBx3lNa0wShS3WebdLIBGv1pk6U2b0bCVJUPP -OJ9n9bs4+kzJBofDHad6N1UszQoHB+1xHthKC5YHyEbnkWlJoyiNWELcADCKYxWY -lsbH1b6zUXlQ+/IYe7uD9Y9nOa/6kXwmyPGuFVBXGgECgYEAwMvMRVkFArycrgd1 -mmYyewuGKQyOonj6qlKDjpuZ829CPwZ7xEpSBNQcKn1vHW52IxJizVh5fHWG/8ga -p2uVGdNUbtjlazrZXDm7xBEAYke+vxgrLHzwCvk3MxFF639nmN9khX+cceLkAaZm -AEye8thr6IN7TVMt43E4G7Bd5OECgYEA88kWgFRvY7rB3oRnMEuLKaTIAdJM81Tt -lQ3PQNTAdt9HenJE5E5y884xQsYCfmvkTGrd7bWHBzRgA0slJQExAaLBNrqm2evw -AshQRVY2mR4TUuKadrWVDV6IF9IDeGZpCEmz1A0RY5M77l2jJ+pAd8Pd8wM07QLV -KqjpDRLTCV0CgYA8xkGPPr+QnEo7pchRspOJLBnPiNDRsJc756Tm6HAAR/s3COEt -AEyYjxCN6FqFiZOd/Ka+mnw5WocCzF5yljw7Ft4PzzmKstNf+icRaFaZpIohjQnX -DU9R9juLUo+a69+JVipG1vJHCEHdr0mKIJ0ealChzAirWGQnxUHtoIwIoQKBgGH1 -JWN/ihrKymf9T/FqCYs8OVnyBRWpxKWmHOdyFbwuT+x1yhTrKOmqqsSoCAyAkgXa -0z5XOOC+PO5V3aEW73g2y+iP68eZNKIJl6ek0t+H5D/j6ilVIYVzvL/Flbtle0Ln -Sqkkbx5R5T0MxyicyjbVr3OckEHEZ59yq+Ki88XJAoGAIrVxwcg+b7FKvBhjrx68 -kBK0rFwTdcqq+82G5R5DGfK5nK9RON01aOM3ddZNy+q/xe5O0kzFPkEQhSsGXTJ2 -+O0cBtTSrQ8hMZKHH6Ol4y6rWjDObmhNZR5ms76l5Fi3EzUKcLbTcl1NXlihanmU -rmQcSs0PKSGpZdraqdH+YrU= ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa-sign.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa-sign.pem deleted file mode 100644 index 975638e550..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa-sign.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC8Xwb2eeVqVUHg -obVcnfjv7C7nhlZAZWFEbrJJXCwqnbYTOUEywVTDkNr7cVp2Q0h1iLz1Dwpz8UfC -LD77DPAVKkI8o9nfQnL7jTYMCjCM1ANdG0Cz0OumnNU+zFP9gOEfscSTeWTqeAfl -MBMDQHgFX0PV2V/h5JlQIyjyYkc5o3c6ALJUEdBecy9dYI5kvEk8GbiftjKVIdPV -RnRyfiwdQjVX5xMcD6kd8HdU0D1C12Tdw8fn9Ftu4JgOBkYrTLS5bQJY72cxrevs -YW8iiSYzJ0wVpcxRYj/4IKXD7PqtoVvYt7zwhOXjhnZGw51yYt2ogcWKUynkueMB -nPzpE7+VAgMBAAECggEBAJDChltL+d3pfyLdor52OCRI4RLTzdzXDBTG7QQrbVWi -tZW4Xj5fDIDuBRtOVTKlKj4Iww2gbWwEdBzoW84adzYMr7JiSMCmFC70qiA+hGj1 -VVBr7SFC4JW92LLV24XpURhGSMb8d20oqQicFUBeft3CBCOHVYQHZTqMip8an5nO -jWPEcxgp2hU5R1BzliMtpwtP3yLN8UD281CEdKy/nG5AfyI882mLbpiFtr0gymhw -CEqJd62vmK1mvSYDYA2QHy3ki9CxCNog0raQy/sOX4JtgCDhmy06FOOqzyo3LFcN -I7Ng2D3R+d7tCEJ8A3C7Z/HbET0MsZDolVljBoNEMlECgYEA+Kznpbm0Vd0Oew9S -5HRzXeZbCnc1fjTOhrtL8o+gyZsXiJQfDWUJ+Mlac2GFDK2FhQofnpfRHlyJRr0b -PSMzPMEB2nj/7Im0LpOUBt2TD69zK8INHIyFmu76ARgqE/rwyuxv+fyqDgUmQShP -8XC2joqejZchvvtX9REj6lQ650sCgYEAwetol/72hrrLNycaVntq7GMmLZCtqIc9 -YcLwQQVjFPkf2eiAHrsdZSnOUYXUJfvsRY4OZ7IkOQp0isU8FqED9CCoLwZ7B67c -DPhUYN6JgIqsH3CuxE9q/5sYb+d8HM9450pk8JrKHJDbBE3nwftLcay5iudkArjw -2hCi4CqzSJ8CgYAdqjKwGGkk3Qv/LiLLUgD5MKOnqfTdq1r/w5QZyXx60F+MUW8q -3+TCovKBVR7UFlcZOc3v01iE8LEHmUOIlYxlMPkRoOGWzA6Mh9pev0vt0RZCIBIE -V9cQVnXIb6OFYqga7P2mqrd2mLKpjy+KM9HzSyIC7gZ+i+lAON059PZZ5QKBgBbA -UMgscK4D8l2pJ8zns/bB9zO3WriADXKP1XI7eJF4XQVK4uU4HM3Gpt8nrWk7clAC -x6vg2aEbmerCEzewcm9M+Y5y2zJekJCw/e1TjpxXKLSTmt2LV8lfX/GZHhWfPdcd -AlS8RGQvlpKdtUgr/ID8u9QRK8mp+xAKjaFxQRGPAoGBALIBTZMU/kmvnO0PrzVL -eR3yojWI/+743kMFxPYfD2sPo/3Dd9qg8J7d1B6wu36vSP2rWVWVGShY6qxiDINi -RnLHzQILuztRbWnxRijP19KtmQctfw7/QIyUMkJ/Ur1bU2JpCjnRdoDVudk8nLvp -dAVR+0swGkDk8ffY+jwZ4gMM ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_256.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_256.pem deleted file mode 100644 index 40f795a162..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_256.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA256 - Salt Length: 32 - Key Security Level: Medium (2048 bits) - -modulus: - 00:a1:d4:bd:d5:9f:ca:7e:e5:d4:7f:49:52:78:33:d6 - b0:2f:37:a4:a2:f8:4b:32:b5:ef:d5:29:9c:7d:2e:ac - 69:b0:b1:1a:09:7d:f1:92:3a:ae:c4:d1:29:63:1b:5d - 60:d3:4d:06:3f:bc:7f:46:c7:22:c2:98:e0:2c:32:fb - 9a:94:f1:ea:b9:3b:37:4b:44:8b:bf:60:28:13:6b:e9 - 31:a6:0f:e2:3d:82:60:9d:28:8b:d4:63:7f:e1:06:cf - d6:81:a1:24:ef:b4:a5:3a:05:95:16:e5:c6:9d:e1:6e - 31:56:92:13:16:c4:2b:53:20:73:57:96:9d:7a:4b:be - e8:f0:50:1a:55:18:1e:d9:69:f2:f6:b5:e5:3a:98:b6 - 77:7b:ff:30:74:9f:6d:81:55:50:b5:3e:81:8d:54:f6 - cc:17:3d:1b:10:bf:69:77:09:d1:d8:be:79:11:ac:3b - be:19:69:5c:b1:50:4d:ba:04:09:98:74:7a:e3:96:48 - 4d:fc:67:7a:34:73:76:48:5e:41:05:61:5a:68:59:39 - b3:86:aa:78:28:f4:a6:4a:db:6f:85:47:75:75:a2:24 - e9:21:3f:18:c9:46:87:91:80:1a:f5:fa:ed:2b:ab:03 - e8:ed:c3:dd:67:ad:46:eb:9b:7e:44:d2:5c:76:4b:3d - 5f: - -public exponent: - 01:00:01: - -private exponent: - 69:92:00:19:18:f9:9f:98:cc:ec:10:68:05:54:43:ec - 81:90:fa:0c:fa:8f:0b:d0:d6:59:27:a1:17:a4:d8:02 - c6:aa:72:02:d9:2f:3b:26:9f:16:74:20:5c:af:e0:55 - a6:e2:6b:7e:2e:b8:94:f2:99:81:7a:fb:5a:ba:13:9a - bf:29:a5:e7:1a:73:32:dd:cf:90:93:e8:f0:ea:87:a0 - c4:e5:3d:c0:c4:89:c4:5c:4c:03:cc:b9:02:92:50:09 - 6e:5d:32:5c:51:6b:2c:13:b2:33:d2:c7:a3:fd:08:c6 - 94:e4:0c:21:e0:ed:26:78:57:e6:3e:b2:12:b2:d1:21 - d8:93:90:f5:8f:2f:c8:97:6b:f0:e6:b0:2a:df:02:18 - 7e:ce:98:8b:63:0c:15:7c:21:39:f9:6c:e2:61:93:fc - 49:36:cd:9d:29:d8:a4:ed:65:12:6d:11:72:f8:13:47 - 6d:8e:20:d7:9f:01:29:3b:8f:dc:d5:b8:f5:58:6f:c1 - 5c:8b:36:40:c5:80:9c:1e:4b:9f:03:55:b5:ff:1c:46 - 1f:e3:b0:12:0c:44:f0:91:07:41:20:08:6a:99:5c:f2 - 11:50:30:4b:4a:84:8e:03:87:89:4e:60:5f:69:01:94 - 5f:82:41:1c:dc:7d:34:f9:02:02:ee:e0:e7:59:63:c9 - - -prime1: - 00:c0:9b:4b:2f:d6:57:df:59:31:87:2a:4c:42:fa:4c - 0c:f2:4d:17:07:90:9b:9c:db:8e:b4:aa:68:96:d1:16 - 01:27:92:e9:8a:26:d1:73:fd:68:21:c7:19:7c:46:f0 - 33:de:21:46:9c:0d:eb:84:8c:b9:6f:cb:47:d0:c5:b8 - 95:1a:e3:18:03:99:81:39:54:2f:c3:a1:14:74:c7:5f - 82:2c:e8:b9:a9:7f:4c:ff:ac:a7:4f:7f:39:20:ee:3d - b1:0f:83:33:fa:76:57:68:4d:8b:99:24:69:d2:08:1b - 1c:36:e7:c9:be:ea:db:1d:38:61:a4:4c:7a:44:e1:82 - 53: - -prime2: - 00:d7:18:59:39:b2:de:4d:0b:58:69:8c:33:af:51:ee - c1:e2:3b:64:b6:36:dd:31:c5:9d:33:39:e2:88:c4:35 - b0:93:8a:6a:b2:c2:8b:ca:c0:0b:21:94:69:90:ae:19 - ab:7b:b8:48:eb:f3:27:3b:96:5c:17:1e:71:89:e7:c5 - 14:d8:d7:de:2b:89:1e:58:f4:4f:1a:95:a7:34:65:48 - 6a:94:f2:bb:33:3c:90:d6:99:4d:36:48:8f:0b:30:d9 - 5f:59:26:60:f0:97:8e:3e:d0:31:99:6f:93:c9:c4:ea - 25:08:f9:48:2f:2a:77:57:93:03:d6:6a:22:fe:16:cf - 45: - -coefficient: - 5b:5d:58:5d:f8:be:1f:31:c4:e9:23:1e:34:41:60:1b - 2d:57:2b:d7:3f:39:74:5f:fa:d6:71:4e:46:02:2d:1a - cc:51:d5:96:7b:d7:0c:f1:8a:a9:31:e7:61:bd:0c:31 - 31:e3:5c:27:32:0b:bd:4a:67:ad:c0:31:db:91:a4:96 - b0:a4:9e:81:0e:75:2e:5f:0c:c5:9b:8e:4d:6c:b4:7e - 2c:44:53:2d:b7:d7:82:20:ba:59:38:df:ec:99:8d:63 - 5f:e9:24:d1:8e:6e:e0:5b:fa:f2:12:16:75:ad:f3:a7 - 2d:fd:8f:55:5f:09:a3:42:4b:44:d2:c8:c8:41:7c:c8 - - -exp1: - 7f:cc:4a:e6:31:e5:da:67:d7:4a:25:51:b6:bb:57:8c - db:95:35:2b:aa:d2:e6:10:74:af:01:c7:26:13:13:f3 - ae:2b:77:d4:58:0f:70:53:fb:2d:36:6b:7d:9f:a0:2f - fa:3a:c0:1c:39:cc:45:06:0e:e0:d3:d4:11:fd:af:8d - 17:eb:08:fb:12:76:c0:f0:50:45:10:f3:7e:cc:ef:5d - 73:a8:f3:d0:38:8c:81:b5:30:ca:b9:d2:d1:3b:e3:29 - 41:ee:bf:a5:77:b2:65:9d:d6:7b:c5:c2:85:3f:25:a5 - e1:f4:88:53:aa:87:ba:ea:b7:37:0a:1b:b2:ea:a2:cb - - -exp2: - 63:04:e8:7e:71:63:79:20:51:f1:35:03:ce:1f:ef:c3 - fd:bb:cd:df:3c:5e:93:bd:1f:63:27:b0:ab:b9:77:e5 - f3:e5:f2:bc:9c:66:f2:4d:7a:52:59:1a:47:ea:7e:12 - bd:7f:d6:c2:18:4b:e5:58:90:c8:6b:d1:64:e4:f7:8b - 63:4f:ed:0d:29:b0:78:ce:ef:63:93:a5:47:af:a0:a8 - c0:2d:06:14:ce:3a:f7:2f:d7:a5:b7:bd:72:2f:68:c2 - 46:2e:2e:ce:53:56:be:7f:e5:75:77:32:17:de:b8:d3 - 97:cf:fa:75:0c:1d:a8:89:1b:69:27:af:38:3d:93:e9 - - - -Public Key PIN: - pin-sha256:KBIg1VxV9p1XXyGsX+MwqaE2DenjfwcmJzw2z8jOeT4= -Public Key ID: - sha256:281220d55c55f69d575f21ac5fe330a9a1360de9e37f0726273c36cfc8ce793e - sha1:06c5f6d2f4f448fa67ba12fe955efbe15febd164 - ------BEGIN PRIVATE KEY----- -MIIE7AIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgGiAwIBIASCBKYwggSiAgEAAoIBAQCh1L3Vn8p+5dR/ -SVJ4M9awLzekovhLMrXv1SmcfS6sabCxGgl98ZI6rsTRKWMbXWDTTQY/vH9GxyLC -mOAsMvualPHquTs3S0SLv2AoE2vpMaYP4j2CYJ0oi9Rjf+EGz9aBoSTvtKU6BZUW -5cad4W4xVpITFsQrUyBzV5adeku+6PBQGlUYHtlp8va15TqYtnd7/zB0n22BVVC1 -PoGNVPbMFz0bEL9pdwnR2L55Eaw7vhlpXLFQTboECZh0euOWSE38Z3o0c3ZIXkEF -YVpoWTmzhqp4KPSmSttvhUd1daIk6SE/GMlGh5GAGvX67SurA+jtw91nrUbrm35E -0lx2Sz1fAgMBAAECggEAaZIAGRj5n5jM7BBoBVRD7IGQ+gz6jwvQ1lknoRek2ALG -qnIC2S87Jp8WdCBcr+BVpuJrfi64lPKZgXr7WroTmr8ppecaczLdz5CT6PDqh6DE -5T3AxInEXEwDzLkCklAJbl0yXFFrLBOyM9LHo/0IxpTkDCHg7SZ4V+Y+shKy0SHY -k5D1jy/Il2vw5rAq3wIYfs6Yi2MMFXwhOfls4mGT/Ek2zZ0p2KTtZRJtEXL4E0dt -jiDXnwEpO4/c1bj1WG/BXIs2QMWAnB5LnwNVtf8cRh/jsBIMRPCRB0EgCGqZXPIR -UDBLSoSOA4eJTmBfaQGUX4JBHNx9NPkCAu7g51ljyQKBgQDAm0sv1lffWTGHKkxC -+kwM8k0XB5CbnNuOtKpoltEWASeS6Yom0XP9aCHHGXxG8DPeIUacDeuEjLlvy0fQ -xbiVGuMYA5mBOVQvw6EUdMdfgizoual/TP+sp09/OSDuPbEPgzP6dldoTYuZJGnS -CBscNufJvurbHThhpEx6ROGCUwKBgQDXGFk5st5NC1hpjDOvUe7B4jtktjbdMcWd -MzniiMQ1sJOKarLCi8rACyGUaZCuGat7uEjr8yc7llwXHnGJ58UU2NfeK4keWPRP -GpWnNGVIapTyuzM8kNaZTTZIjwsw2V9ZJmDwl44+0DGZb5PJxOolCPlILyp3V5MD -1moi/hbPRQKBgH/MSuYx5dpn10olUba7V4zblTUrqtLmEHSvAccmExPzrit31FgP -cFP7LTZrfZ+gL/o6wBw5zEUGDuDT1BH9r40X6wj7EnbA8FBFEPN+zO9dc6jz0DiM -gbUwyrnS0TvjKUHuv6V3smWd1nvFwoU/JaXh9IhTqoe66rc3Chuy6qLLAoGAYwTo -fnFjeSBR8TUDzh/vw/27zd88XpO9H2MnsKu5d+Xz5fK8nGbyTXpSWRpH6n4SvX/W -whhL5ViQyGvRZOT3i2NP7Q0psHjO72OTpUevoKjALQYUzjr3L9elt71yL2jCRi4u -zlNWvn/ldXcyF96405fP+nUMHaiJG2knrzg9k+kCgYBbXVhd+L4fMcTpIx40QWAb -LVcr1z85dF/61nFORgItGsxR1ZZ71wzxiqkx52G9DDEx41wnMgu9SmetwDHbkaSW -sKSegQ51Ll8MxZuOTWy0fixEUy2314Igulk43+yZjWNf6STRjm7gW/ryEhZ1rfOn -Lf2PVV8Jo0JLRNLIyEF8yA== ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_384.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_384.pem deleted file mode 100644 index 49f5ca8c5d..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_384.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA384 - Salt Length: 48 - Key Security Level: Medium (2048 bits) - -modulus: - 00:e7:f5:99:8b:69:95:62:3a:54:80:b9:4c:21:a3:dc - 50:b9:ac:8d:50:a4:98:ea:da:87:55:82:2c:c6:68:e4 - 36:6c:7a:b8:1e:21:db:e6:fa:1f:c2:54:3a:c0:8d:2d - 94:ce:15:66:76:82:d3:27:39:ff:11:f8:19:99:95:6d - 63:7e:35:3d:17:b6:2d:59:3f:c2:b4:b3:73:75:b8:b2 - e7:9d:4d:7d:0d:98:e3:bb:da:e2:44:69:bd:15:52:0c - 45:eb:24:70:5d:47:55:79:67:56:1e:4f:2f:d5:e2:8e - c2:96:db:5f:2b:6e:c5:cf:4f:20:61:6f:22:50:05:8c - e5:ef:5d:e2:bb:e9:af:79:9d:89:ec:19:b4:ed:7d:e7 - f7:f7:20:b4:b0:7c:57:a2:c4:66:67:bb:e2:29:e3:9c - 07:9c:b0:df:30:36:40:b2:45:12:ed:53:5d:75:4d:a6 - 04:e4:2f:db:92:96:94:be:cb:e8:ac:ee:8d:28:5d:95 - a6:9f:9c:28:d3:c2:87:5e:7b:72:de:f1:ff:16:f8:49 - e4:9d:de:e7:7a:20:23:69:a4:9f:68:b2:db:b0:fc:fb - c2:77:0d:41:0a:ff:66:02:ea:9e:6b:c3:09:dd:7c:bc - 1f:47:66:66:8b:a3:72:e9:94:50:62:97:50:5a:5e:2e - d3: - -public exponent: - 01:00:01: - -private exponent: - 69:3a:96:ec:92:fa:8c:f4:4f:4f:92:40:42:66:96:d5 - 1c:56:76:49:66:52:65:00:bc:32:83:7a:92:8c:15:33 - c7:64:a8:d0:2a:a6:1b:13:cf:82:96:39:8d:0e:be:e5 - e9:d3:f5:86:bf:f4:d0:af:d3:d2:30:0e:55:09:5f:f5 - a9:d4:b7:21:61:a9:12:fb:04:f6:7b:0e:5f:12:6a:3e - fe:b2:9f:8f:a2:93:75:ae:67:c5:87:7e:9b:04:7c:c2 - df:58:c9:8c:d7:86:a4:2b:c7:fa:ba:0b:c6:69:20:40 - 90:b5:76:68:3a:b9:8c:41:a6:3b:ed:71:d0:81:a4:17 - f2:a1:1d:b8:b4:6b:01:6d:a2:e7:9a:6e:9f:b5:a1:14 - 61:7c:66:50:dc:e8:27:67:55:36:50:cc:19:d4:c7:71 - d5:8f:a7:5f:96:f1:74:90:a1:38:1c:8d:b6:37:04:23 - 81:70:24:29:62:b6:e4:85:8d:46:e9:4a:a0:26:12:0f - 40:69:42:25:eb:18:0a:97:93:dc:50:12:85:ff:74:6d - 71:31:d8:45:f8:94:74:ff:43:55:f6:fc:a3:ce:1e:cb - b9:d7:b8:2b:e5:c6:ab:d3:ab:77:60:9c:6b:4c:8e:c0 - 67:a2:37:41:a0:b8:ad:4a:bd:20:1c:29:c8:49:cc:69 - - -prime1: - 00:ed:49:8c:54:96:6b:fe:77:60:f1:93:dd:3d:bc:46 - b2:ec:9e:35:20:cc:8f:63:55:66:90:a4:1e:e3:50:b1 - 51:a3:a7:8b:b1:81:cd:93:cf:0d:4a:ac:c0:a1:81:49 - cb:71:0e:6b:4f:16:75:04:ae:89:53:c1:1d:ac:44:bc - ae:9d:85:85:e9:8c:aa:8e:b9:a8:3e:3d:86:28:b5:c3 - da:35:98:67:70:5a:8b:1f:c2:18:ed:b0:6a:0c:74:b9 - 33:6b:08:e5:93:87:39:b0:44:79:5c:eb:4c:f0:f1:db - c1:41:76:b0:12:46:38:4f:bd:68:db:70:53:13:e8:5f - 95: - -prime2: - 00:fa:40:7d:45:ec:7b:68:68:31:02:9a:ef:b7:a4:35 - a5:7d:d0:be:75:82:39:44:5f:31:98:4d:ff:3b:ec:76 - ce:c3:32:f9:d4:ce:bc:be:4c:3a:72:2f:1d:f6:2c:85 - 0d:15:50:2e:14:19:bb:cc:b5:ad:6c:bc:59:3f:a0:ba - 8b:82:e3:9d:36:93:40:b8:ec:d4:eb:15:59:da:ca:a7 - 10:1e:8e:de:22:c0:96:a5:cb:d3:37:37:4a:4b:58:aa - 13:76:84:58:21:0b:be:8a:b7:c9:04:fd:d9:99:0e:0c - 8a:28:52:50:23:9e:df:80:54:db:16:46:34:18:3b:da - c7: - -coefficient: - 7e:b9:c8:22:2e:b4:07:cd:a1:11:43:4d:48:79:e6:86 - a2:6d:3e:41:85:1e:01:3e:05:77:3d:88:2e:8c:a1:43 - b1:5c:03:3c:d9:37:d8:48:06:fa:bf:de:3e:ad:33:63 - b4:03:f7:84:02:26:22:95:66:03:1d:91:73:20:42:97 - 0e:5d:dd:37:1e:f3:60:80:1b:e4:19:0c:cb:75:bf:30 - fd:38:73:67:9c:c2:68:4c:ff:70:cb:78:6c:b7:5a:1c - a3:a2:cb:a1:f1:f4:17:06:9b:53:96:c3:19:0f:36:98 - 1e:11:f9:ba:a6:cb:5d:d5:82:ae:43:4f:cd:9e:e3:66 - - -exp1: - 2e:c1:d9:67:29:a4:ea:25:b7:f2:a2:82:6c:11:d7:94 - 96:4f:ae:84:62:0a:b7:36:32:d9:b9:9d:64:89:98:07 - 50:4a:49:9a:96:cb:5d:9e:e5:2d:9b:d0:f1:82:3a:7a - 5e:32:cb:2e:70:6c:6a:99:c1:f1:c1:12:09:ca:19:ac - 06:da:32:c3:0c:b6:e7:1c:ea:6c:29:4f:70:62:30:cf - a4:d3:fd:3e:04:79:79:ae:93:9e:f2:ae:52:fa:05:2c - 7e:a0:e8:2c:23:ef:58:2e:86:03:ab:52:24:00:64:9f - 36:39:1f:04:da:d5:69:d1:17:02:76:a5:c8:3c:77:e9 - - -exp2: - 00:84:d4:6a:2a:0d:45:cb:bb:52:18:51:e8:df:8e:d7 - b2:c9:bf:5c:f8:be:70:6b:2c:24:04:f5:91:7e:5b:1b - 0c:d0:6b:64:54:62:8f:a8:6a:89:b3:45:f3:1f:51:ae - 25:ad:a4:6b:70:db:df:e4:de:a1:f8:cf:58:87:ff:66 - 44:da:ea:b9:ed:d7:e7:48:c0:dc:9b:13:30:28:83:dc - 7d:1f:db:31:69:3c:d4:39:98:a0:b9:f4:2d:09:25:3c - d1:2b:dd:3f:71:fa:eb:de:71:82:cf:95:76:44:59:42 - aa:aa:90:56:5d:31:dc:ec:1f:1e:53:0a:5c:68:68:8c - cd: - - -Public Key PIN: - pin-sha256:ehI/YLeqtW2fBULTjESCxxpNnhvQYw9LOVxfrWzyV/g= -Public Key ID: - sha256:7a123f60b7aab56d9f0542d38c4482c71a4d9e1bd0630f4b395c5fad6cf257f8 - sha1:7ec2c93bfa8195429459015e334ef8d5735430b0 - ------BEGIN PRIVATE KEY----- -MIIE7QIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAqEaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgKiAwIBMASCBKcwggSjAgEAAoIBAQDn9ZmLaZViOlSA -uUwho9xQuayNUKSY6tqHVYIsxmjkNmx6uB4h2+b6H8JUOsCNLZTOFWZ2gtMnOf8R -+BmZlW1jfjU9F7YtWT/CtLNzdbiy551NfQ2Y47va4kRpvRVSDEXrJHBdR1V5Z1Ye -Ty/V4o7ClttfK27Fz08gYW8iUAWM5e9d4rvpr3mdiewZtO195/f3ILSwfFeixGZn -u+Ip45wHnLDfMDZAskUS7VNddU2mBOQv25KWlL7L6KzujShdlaafnCjTwodee3Le -8f8W+Enknd7neiAjaaSfaLLbsPz7wncNQQr/ZgLqnmvDCd18vB9HZmaLo3LplFBi -l1BaXi7TAgMBAAECggEAaTqW7JL6jPRPT5JAQmaW1RxWdklmUmUAvDKDepKMFTPH -ZKjQKqYbE8+CljmNDr7l6dP1hr/00K/T0jAOVQlf9anUtyFhqRL7BPZ7Dl8Saj7+ -sp+PopN1rmfFh36bBHzC31jJjNeGpCvH+roLxmkgQJC1dmg6uYxBpjvtcdCBpBfy -oR24tGsBbaLnmm6ftaEUYXxmUNzoJ2dVNlDMGdTHcdWPp1+W8XSQoTgcjbY3BCOB -cCQpYrbkhY1G6UqgJhIPQGlCJesYCpeT3FAShf90bXEx2EX4lHT/Q1X2/KPOHsu5 -17gr5car06t3YJxrTI7AZ6I3QaC4rUq9IBwpyEnMaQKBgQDtSYxUlmv+d2Dxk909 -vEay7J41IMyPY1VmkKQe41CxUaOni7GBzZPPDUqswKGBSctxDmtPFnUErolTwR2s -RLyunYWF6YyqjrmoPj2GKLXD2jWYZ3Baix/CGO2wagx0uTNrCOWThzmwRHlc60zw -8dvBQXawEkY4T71o23BTE+hflQKBgQD6QH1F7HtoaDECmu+3pDWlfdC+dYI5RF8x -mE3/O+x2zsMy+dTOvL5MOnIvHfYshQ0VUC4UGbvMta1svFk/oLqLguOdNpNAuOzU -6xVZ2sqnEB6O3iLAlqXL0zc3SktYqhN2hFghC76Kt8kE/dmZDgyKKFJQI57fgFTb -FkY0GDvaxwKBgC7B2WcppOolt/KigmwR15SWT66EYgq3NjLZuZ1kiZgHUEpJmpbL -XZ7lLZvQ8YI6el4yyy5wbGqZwfHBEgnKGawG2jLDDLbnHOpsKU9wYjDPpNP9PgR5 -ea6TnvKuUvoFLH6g6Cwj71guhgOrUiQAZJ82OR8E2tVp0RcCdqXIPHfpAoGBAITU -aioNRcu7UhhR6N+O17LJv1z4vnBrLCQE9ZF+WxsM0GtkVGKPqGqJs0XzH1GuJa2k -a3Db3+TeofjPWIf/ZkTa6rnt1+dIwNybEzAog9x9H9sxaTzUOZigufQtCSU80Svd -P3H6695xgs+VdkRZQqqqkFZdMdzsHx5TClxoaIzNAoGAfrnIIi60B82hEUNNSHnm -hqJtPkGFHgE+BXc9iC6MoUOxXAM82TfYSAb6v94+rTNjtAP3hAImIpVmAx2RcyBC -lw5d3Tce82CAG+QZDMt1vzD9OHNnnMJoTP9wy3hst1oco6LLofH0FwabU5bDGQ82 -mB4R+bqmy13Vgq5DT82e42Y= ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_512.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_512.pem deleted file mode 100644 index 923f6f92ea..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-key-rsa_pss_512.pem +++ /dev/null @@ -1,138 +0,0 @@ -Public Key Info: - Public Key Algorithm: RSA-PSS - Hash Algorithm: SHA512 - Salt Length: 64 - Key Security Level: Medium (2048 bits) - -modulus: - 00:c2:ce:73:69:95:63:26:85:bd:a0:23:25:5c:94:41 - 04:11:84:78:6c:c9:a3:47:13:47:3b:c4:fe:f3:27:6c - eb:d7:41:a9:4c:e3:15:40:b8:bd:99:02:df:93:a9:bf - 07:de:a2:f1:d1:1e:49:39:2b:64:c7:5e:bb:c7:dd:30 - 07:3c:10:2c:c9:bd:d9:8f:1e:04:60:c1:92:72:44:e6 - 3c:6e:6d:7f:b7:6f:fa:ab:2f:e3:69:7b:0d:1c:31:d5 - 5e:dd:ab:99:0d:4e:80:69:53:3d:d3:63:04:1f:d6:83 - fa:d7:04:c9:3f:75:9c:95:bd:45:34:39:1d:a0:1d:d7 - 06:8e:60:17:a3:94:8f:e9:30:1e:d2:ee:05:42:a4:08 - 86:b7:93:c2:5c:c2:5e:bc:c0:26:5e:98:56:c3:76:87 - e9:9b:1a:3b:f6:bf:c1:6a:4f:f8:46:ba:0b:a8:3a:5e - bb:1d:af:e3:f3:9b:f1:b6:18:70:6d:af:30:62:5f:07 - a9:ff:7b:a2:dd:5f:7e:ff:33:19:80:a2:d7:f9:9e:c5 - a5:22:e7:79:3c:b7:ee:4a:33:c7:c4:72:e6:69:fd:ec - 43:8b:85:86:07:95:15:b9:fe:ed:1c:12:38:ca:ed:cc - 71:ef:9b:69:11:16:e5:1e:78:e0:b3:4d:4c:b4:79:ea - 9f: - -public exponent: - 01:00:01: - -private exponent: - 00:84:ed:bb:73:60:ac:b7:ac:ab:28:8a:d3:03:c9:66 - 54:10:60:04:8c:b7:4a:e3:45:14:66:84:96:33:f5:c3 - 2d:6b:45:32:f1:74:43:1c:56:f3:89:65:9c:8a:76:5a - 14:54:a7:7b:ba:e6:9f:b0:93:1b:c1:af:b3:13:3e:ab - 77:44:55:05:3a:e4:81:80:57:4b:45:7a:d1:23:88:40 - 53:1c:47:3b:cf:40:6a:1c:46:21:37:e8:ef:99:3d:a8 - 0b:83:d7:84:28:c0:58:7f:86:7d:b9:b0:e7:2f:92:81 - 9c:b8:fc:5b:17:22:7a:26:f3:70:35:a2:83:c4:ae:97 - fa:7e:c6:3f:d2:39:9b:fe:f1:e9:c6:d1:68:3e:ac:26 - b4:69:27:c6:1f:50:fc:ab:32:bb:3c:90:13:7e:5c:c0 - 52:0c:34:5d:f7:bd:dd:84:ca:7c:c7:fe:91:8d:60:fe - d7:a7:e3:95:46:b2:ce:a1:4b:af:ba:81:e5:52:7c:68 - 65:5b:9c:84:a5:b6:44:0c:28:b7:c4:19:aa:f5:f7:06 - 35:ac:92:fe:1b:12:f9:17:8f:28:b7:d0:66:3b:a8:5e - 91:6e:c1:06:65:69:97:4e:75:26:59:12:76:3a:3d:9e - ee:21:b4:df:1e:e5:c1:73:5f:cd:e7:4a:2b:66:d8:cc - 81: - -prime1: - 00:c8:9b:6c:7f:a0:08:ce:09:9b:2a:ea:f3:2c:62:d1 - ec:1e:61:7f:da:d1:3a:38:a8:31:4c:57:fa:b9:1c:d8 - 27:fc:ff:d7:79:82:f1:3b:3a:b6:93:f3:61:c8:17:e2 - 73:c8:bc:66:ff:98:9d:5e:31:4f:6b:d5:98:d3:1a:eb - cc:30:ab:f6:ed:1b:62:a4:24:6c:cd:eb:20:9e:d8:52 - 8e:49:b9:47:11:97:2d:0c:89:6c:01:0a:f2:0e:6f:cf - 57:57:7c:57:ce:06:4b:a2:d1:e4:97:91:b2:3b:ef:2a - 38:d1:64:ea:6e:b0:57:c0:93:ed:d6:27:ba:dd:9e:53 - 0b: - -prime2: - 00:f8:98:fc:b3:55:a0:27:40:a8:e2:62:3d:80:4b:13 - 10:1c:a7:22:af:3d:47:57:c4:34:8c:76:4e:95:d7:ff - e8:03:bb:cf:ac:9d:52:3a:c2:d0:91:5f:1c:1d:36:4a - 7e:9d:6d:81:4a:6e:00:f8:96:85:a1:ab:3f:54:d2:03 - ad:0e:d2:c8:c6:fc:b4:62:7e:ab:57:aa:b7:2c:6b:10 - 01:66:5d:ab:d0:5a:9e:02:5b:ad:e1:ab:be:6e:b4:b4 - d1:61:d1:5f:19:22:5c:f5:4e:9e:bd:25:ab:94:a6:be - 8c:a5:7a:2d:2f:f9:5f:55:d3:b8:d8:6d:e9:7c:b5:03 - 3d: - -coefficient: - 7a:dc:e4:d8:ed:ce:71:72:63:b3:a8:4d:c0:1d:fa:a2 - 8a:c4:9f:77:1e:5a:e1:17:d3:1a:f8:20:32:54:30:a7 - 0d:69:40:92:d7:d6:43:bf:b5:83:7e:d5:19:44:bd:3c - 8d:ff:31:ad:8b:bd:6d:ab:a7:34:d7:e3:75:57:02:85 - 8a:c0:78:2d:10:0f:6f:28:da:f7:22:69:40:f4:04:9f - a5:f9:e2:a9:0d:88:06:b4:f3:3c:5e:c6:8c:96:69:7e - f6:09:fa:9c:c6:87:de:a2:a5:9b:4d:22:2a:0b:27:7c - 25:31:26:60:b6:6d:0f:97:6f:48:f2:bf:88:dc:f3:83 - - -exp1: - 1a:20:e4:48:db:37:4a:5e:c5:ef:19:1b:03:34:fb:d2 - 9d:42:65:bc:c2:73:aa:dd:7d:4e:4c:47:43:c5:16:02 - 5f:59:93:5f:28:46:f3:47:fa:6f:da:cb:69:9c:72:ca - 51:e2:f8:27:62:61:5c:db:5f:54:d4:45:4b:79:be:2c - a2:4a:43:a7:2e:61:f2:af:2b:dc:c6:3b:41:75:3b:8b - 7c:de:bc:fa:f5:8d:d0:8c:35:9d:0d:27:e9:e9:76:40 - 12:0d:08:02:b5:9f:34:5d:d2:40:4b:a1:c3:5c:ab:4b - 2b:3a:d1:ae:09:19:e4:e3:5f:9e:fd:1d:c1:af:d5:71 - - -exp2: - 00:f0:6c:55:08:c3:a8:ee:0d:74:c7:ec:a6:fa:2a:a1 - 37:15:de:f6:86:70:47:4d:34:6e:75:e1:fd:42:a1:f1 - d6:db:b5:89:b5:b1:38:d3:a7:91:ba:e6:36:f4:71:8b - 3e:44:d6:a1:11:f0:ad:73:bd:6f:63:d9:90:98:61:bc - 38:64:7b:aa:bd:f7:ac:25:0d:c8:7c:32:98:90:96:c2 - 95:f8:00:63:a8:4f:db:3d:00:99:7c:05:73:58:f1:df - 66:18:aa:3a:c4:be:1d:15:09:82:2f:ff:fc:9e:f9:5c - 93:fd:7d:d9:b1:ea:05:2f:a6:61:c0:bf:1b:ef:05:c9 - 29: - - -Public Key PIN: - pin-sha256:ucGhof6fwEGIty3XlESZXFYnapJIa30Xc+yIYUtVbKY= -Public Key ID: - sha256:b9c1a1a1fe9fc04188b72dd79444995c56276a92486b7d1773ec88614b556ca6 - sha1:f0f7effab3260ffefd0c2c57c196d20d0fd4bd3b - ------BEGIN PRIVATE KEY----- -MIIE7gIBADA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCA6EaMBgGCSqGSIb3 -DQEBCDALBglghkgBZQMEAgOiAwIBQASCBKgwggSkAgEAAoIBAQDCznNplWMmhb2g -IyVclEEEEYR4bMmjRxNHO8T+8yds69dBqUzjFUC4vZkC35OpvwfeovHRHkk5K2TH -XrvH3TAHPBAsyb3Zjx4EYMGSckTmPG5tf7dv+qsv42l7DRwx1V7dq5kNToBpUz3T -YwQf1oP61wTJP3Wclb1FNDkdoB3XBo5gF6OUj+kwHtLuBUKkCIa3k8Jcwl68wCZe -mFbDdofpmxo79r/Bak/4RroLqDpeux2v4/Ob8bYYcG2vMGJfB6n/e6LdX37/MxmA -otf5nsWlIud5PLfuSjPHxHLmaf3sQ4uFhgeVFbn+7RwSOMrtzHHvm2kRFuUeeOCz -TUy0eeqfAgMBAAECggEBAITtu3NgrLesqyiK0wPJZlQQYASMt0rjRRRmhJYz9cMt -a0Uy8XRDHFbziWWcinZaFFSne7rmn7CTG8GvsxM+q3dEVQU65IGAV0tFetEjiEBT -HEc7z0BqHEYhN+jvmT2oC4PXhCjAWH+Gfbmw5y+SgZy4/FsXInom83A1ooPErpf6 -fsY/0jmb/vHpxtFoPqwmtGknxh9Q/KsyuzyQE35cwFIMNF33vd2EynzH/pGNYP7X -p+OVRrLOoUuvuoHlUnxoZVuchKW2RAwot8QZqvX3BjWskv4bEvkXjyi30GY7qF6R -bsEGZWmXTnUmWRJ2Oj2e7iG03x7lwXNfzedKK2bYzIECgYEAyJtsf6AIzgmbKurz -LGLR7B5hf9rROjioMUxX+rkc2Cf8/9d5gvE7OraT82HIF+JzyLxm/5idXjFPa9WY -0xrrzDCr9u0bYqQkbM3rIJ7YUo5JuUcRly0MiWwBCvIOb89XV3xXzgZLotHkl5Gy -O+8qONFk6m6wV8CT7dYnut2eUwsCgYEA+Jj8s1WgJ0Co4mI9gEsTEBynIq89R1fE -NIx2TpXX/+gDu8+snVI6wtCRXxwdNkp+nW2BSm4A+JaFoas/VNIDrQ7SyMb8tGJ+ -q1eqtyxrEAFmXavQWp4CW63hq75utLTRYdFfGSJc9U6evSWrlKa+jKV6LS/5X1XT -uNht6Xy1Az0CgYAaIORI2zdKXsXvGRsDNPvSnUJlvMJzqt19TkxHQ8UWAl9Zk18o -RvNH+m/ay2mccspR4vgnYmFc219U1EVLeb4sokpDpy5h8q8r3MY7QXU7i3zevPr1 -jdCMNZ0NJ+npdkASDQgCtZ80XdJAS6HDXKtLKzrRrgkZ5ONfnv0dwa/VcQKBgQDw -bFUIw6juDXTH7Kb6KqE3Fd72hnBHTTRudeH9QqHx1tu1ibWxONOnkbrmNvRxiz5E -1qER8K1zvW9j2ZCYYbw4ZHuqvfesJQ3IfDKYkJbClfgAY6hP2z0AmXwFc1jx32YY -qjrEvh0VCYIv//ye+VyT/X3ZseoFL6ZhwL8b7wXJKQKBgHrc5NjtznFyY7OoTcAd -+qKKxJ93HlrhF9Ma+CAyVDCnDWlAktfWQ7+1g37VGUS9PI3/Ma2LvW2rpzTX43VX -AoWKwHgtEA9vKNr3ImlA9ASfpfniqQ2IBrTzPF7GjJZpfvYJ+pzGh96ipZtNIioL -J3wlMSZgtm0Pl29I8r+I3POD ------END PRIVATE KEY----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa-enc.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa-enc.pem deleted file mode 100644 index bd4bee0a74..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa-enc.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgIMWYGU8Ba6TGDaJ+vVMA0GCSqGSIb3DQEBCwUAMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzZa -Fw0zNzA3MjgwOTAxMzZaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IFNl -cnZlcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALeY49te/YFa6Od8 -0bFjD8k1vJbupBNoqdmiAT9oiHmbzqGKePtqC1XZQOwFe9pBJOuny9fAo2v0hhdU -sS9PmUzyaP4YOUnWOEpujU4Ntk9jtvWrl7VG0xSE1fcaBkN6+ssvRO3+D3XYoPhT -u9OxLZNDfmFc5DpuSc31VY2Fq3SVD8vrSrZCh892T0/J0VlX0LGSga/BXUGqJOkm -ISWgUB/eHTsaKb97cro6VTZyL4tvr+69IM+I4hVg8FRGZWOzj2wuFraMOPnUgjj0 -qk9snA1RP3TZWu+hHCGtY/wXFg7RDEb0nTsh2w0tAvNVYHHPTeore/5T9qQ7VBC7 -KtabDr0CAwEAAaN2MHQwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcD -ATAPBgNVHQ8BAf8EBQMDByAAMB0GA1UdDgQWBBQwgymoaNHkuh20njTXz48/R+kl -yDAfBgNVHSMEGDAWgBQrQlWadXqqzBV+2iw7BZXrvFHaQjANBgkqhkiG9w0BAQsF -AAOCAQEA3kf9yAMYuPlBW2/y7UiKZGu6IVuxpmy+IFKeNIH6MNN9AsEHM1Yx4F1O -c4UGHxEPoKj5k1cEjiNH4hcaAR/Gukq7efHtf98WGlEp8E8ctjkK6Eu3+hOLHQ01 -YjV76BOkWzOI6DwFYNa71Jae44A8QUFhdq3c874KwwX2VkKcfenb7SzfWn/93DpR -L899PIzXWggADuRGb2S6L35DNk6sHQR8CwkT/HxZr/xqeAVP0qaXtkSPoPntVw6Z -MIUFcmC7XbDuyo1Or3iCMgdsuqP88KWDqP7vF2Bu8deES4wQeIGBSl4e6kweesbY -ASRKL9Qf3tPtKVGp0zvJbfSsOc+wig== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa-sign.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa-sign.pem deleted file mode 100644 index 09818af868..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa-sign.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgIMWYGU8DJRSWC13gO8MA0GCSqGSIb3DQEBCwUAMCMxITAf -BgNVBAMTGEJvdW5jeUNhc3RsZSBUTFMgVGVzdCBDQTAeFw0xNzA4MDIwOTAxMzZa -Fw0zNzA3MjgwOTAxMzZaMCMxITAfBgNVBAMTGEJvdW5jeUNhc3RsZSBUZXN0IFNl -cnZlcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALxfBvZ55WpVQeCh -tVyd+O/sLueGVkBlYURusklcLCqdthM5QTLBVMOQ2vtxWnZDSHWIvPUPCnPxR8Is -PvsM8BUqQjyj2d9CcvuNNgwKMIzUA10bQLPQ66ac1T7MU/2A4R+xxJN5ZOp4B+Uw -EwNAeAVfQ9XZX+HkmVAjKPJiRzmjdzoAslQR0F5zL11gjmS8STwZuJ+2MpUh09VG -dHJ+LB1CNVfnExwPqR3wd1TQPULXZN3Dx+f0W27gmA4GRitMtLltAljvZzGt6+xh -byKJJjMnTBWlzFFiP/ggpcPs+q2hW9i3vPCE5eOGdkbDnXJi3aiBxYpTKeS54wGc -/OkTv5UCAwEAAaN2MHQwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcD -ATAPBgNVHQ8BAf8EBQMDB4AAMB0GA1UdDgQWBBTXwO7kKzgzAOC9j607abavBMKy -aTAfBgNVHSMEGDAWgBQrQlWadXqqzBV+2iw7BZXrvFHaQjANBgkqhkiG9w0BAQsF -AAOCAQEAAYRsE0f2BkOlNWj1SNiwoWkw4Ic6WW1X43yh3L17c5hRLOGPupDngJBA -EYTmsEfq26XX4mGlKXKgKZW2ijcrIQSkHEjkXHYdU+OI+4xufeNtGMYLijcwVKXM -mmSe8ERWODdCfzDJSRdLx/NgLeWphMQLaym1TkK29lASyqIbCNATXGnMw3bcMLvU -cXnjHtNU1tlYtVNCStvm2buy+vdVEGIsusqk+aetniEttBlQcPwuRMvbYmIDuRJP -Bxsst/t32W+s8Eb2dqbSKm6TucOG5o7oXKH6l15d+ARRJJ3C3nODBvsYgSqg1Vtm -7H0K9I4dLZoMUb4tWjSA9ckNU0nuKQ== ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_256.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_256.pem deleted file mode 100644 index 0ebfa2e204..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_256.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID2jCCApKgAwIBAgIUODLkLENJ2mZJLwlk5OXY6ebyHp8wPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogMC -ASAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0MloXDTM4MTAxOTA2MDY0MlowIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRlc3QgU2VydmVyMIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQ8AMIIBCgKCAQEAodS9 -1Z/KfuXUf0lSeDPWsC83pKL4SzK179UpnH0urGmwsRoJffGSOq7E0SljG11g000G -P7x/RsciwpjgLDL7mpTx6rk7N0tEi79gKBNr6TGmD+I9gmCdKIvUY3/hBs/WgaEk -77SlOgWVFuXGneFuMVaSExbEK1Mgc1eWnXpLvujwUBpVGB7ZafL2teU6mLZ3e/8w -dJ9tgVVQtT6BjVT2zBc9GxC/aXcJ0di+eRGsO74ZaVyxUE26BAmYdHrjlkhN/Gd6 -NHN2SF5BBWFaaFk5s4aqeCj0pkrbb4VHdXWiJOkhPxjJRoeRgBr1+u0rqwPo7cPd -Z61G65t+RNJcdks9XwIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoG -CCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHgAAwHQYDVR0OBBYEFAbF9tL09Ej6Z7oS -/pVe++Ff69FkMB8GA1UdIwQYMBaAFCEaiLbeA8ABgKrbcIiZpo8XzqpsMD0GCSqG -SIb3DQEBCjAwoA0wCwYJYIZIAWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFl -AwQCAaIDAgEgA4IBAQBQJnvKt+zUFenmqBo8zGAUQdNYcIp5JhmTP2JbgWlNjTkj -Tsc3i/rWKA0pxydWgQPL6VKBPiqFIQcuPEw6D9zQxRQpnOveRDTkDzcLbt/c5asO -6TpHYqlSujeW7TEH0WLBg0uAHuRUclKYB1/2gSU0MUVtG/sZkh213vEx56F56iqx -sXFDnt9pyu0tLE0nWWtY3dxGAYJpL1HGZ2ey//Tf0+lsS0t8iH0vAtUmssKJpA79 -76biXCHAVcL07O5jMwrF4v7ki/G7RQRQ+qrL03xBifAzKuczu4Ls++Wg7V4MUERj -mpw4pbRBam9Sz3uwc1qA+Ul0TCHzMDAFWyMod0ND ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_384.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_384.pem deleted file mode 100644 index 3506f48b27..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_384.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID2jCCApKgAwIBAgIUBSXp/i1JJIcj2ytjBNKJ0tbxKjYwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgKhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAICogMC -ATAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA3NTY0OVoXDTM4MTAxOTA3NTY0OVowIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRlc3QgU2VydmVyMIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAqEa -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgKiAwIBMAOCAQ8AMIIBCgKCAQEA5/WZ -i2mVYjpUgLlMIaPcULmsjVCkmOrah1WCLMZo5DZsergeIdvm+h/CVDrAjS2UzhVm -doLTJzn/EfgZmZVtY341PRe2LVk/wrSzc3W4suedTX0NmOO72uJEab0VUgxF6yRw -XUdVeWdWHk8v1eKOwpbbXytuxc9PIGFvIlAFjOXvXeK76a95nYnsGbTtfef39yC0 -sHxXosRmZ7viKeOcB5yw3zA2QLJFEu1TXXVNpgTkL9uSlpS+y+is7o0oXZWmn5wo -08KHXnty3vH/FvhJ5J3e53ogI2mkn2iy27D8+8J3DUEK/2YC6p5rwwndfLwfR2Zm -i6Ny6ZRQYpdQWl4u0wIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoG -CCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHgAAwHQYDVR0OBBYEFH7CyTv6gZVClFkB -XjNO+NVzVDCwMB8GA1UdIwQYMBaAFKnwXW9hoPAB6HSyWn7UEUMcKonnMD0GCSqG -SIb3DQEBCjAwoA0wCwYJYIZIAWUDBAICoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFl -AwQCAqIDAgEwA4IBAQAt1xrrBujilh2NVclsaRoqD+QJ7QhDdFVbS2zBJTVz7nds -TMu9iU/dXAp2zdsmpXi3mKStgYWS1yjSdyKyBy4v7EwGx5qHrcnMzyfX2BelGDk7 -OYCXGaFweAqRUh8SchYA1+Dlwg7ub+SpGkDnA76LgBcHFoC7AMozLOeY6GNT4qdq -64+jFvCFrDVC4xMvMB3+vwdlDIIyr9uY3z9Axw35IRPyVHJnyiLu/OIwD7Vw9A4n -11WrUXZ2fvqJUcSvwqdHRAy1kj9LsagfEXatJ79ZC2En2XhEs+PHTgtqw5UdPk16 -dVIlgPTQ/Te+ttubJPsKOpgKj8YOiNtnEZdzpJUP ------END CERTIFICATE----- diff --git a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_512.pem b/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_512.pem deleted file mode 100644 index 51e323b43c..0000000000 --- a/tls/src/test/resources/org/bouncycastle/tls/test/x509-server-rsa_pss_512.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID2jCCApKgAwIBAgIUV12PGXPx0Jj7USRKsKNrWFqJRHEwPQYJKoZIhvcNAQEK -MDCgDTALBglghkgBZQMEAgOhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIDogMC -AUAwIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxlIFRMUyBUZXN0IENBMB4XDTE4MTAy -NDA2MDY0M1oXDTM4MTAxOTA2MDY0M1owIzEhMB8GA1UEAxMYQm91bmN5Q2FzdGxl -IFRlc3QgU2VydmVyMIIBUjA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCA6Ea -MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgOiAwIBQAOCAQ8AMIIBCgKCAQEAws5z -aZVjJoW9oCMlXJRBBBGEeGzJo0cTRzvE/vMnbOvXQalM4xVAuL2ZAt+Tqb8H3qLx -0R5JOStkx167x90wBzwQLMm92Y8eBGDBknJE5jxubX+3b/qrL+Npew0cMdVe3auZ -DU6AaVM902MEH9aD+tcEyT91nJW9RTQ5HaAd1waOYBejlI/pMB7S7gVCpAiGt5PC -XMJevMAmXphWw3aH6ZsaO/a/wWpP+Ea6C6g6Xrsdr+Pzm/G2GHBtrzBiXwep/3ui -3V9+/zMZgKLX+Z7FpSLneTy37kozx8Ry5mn97EOLhYYHlRW5/u0cEjjK7cxx75tp -ERblHnjgs01MtHnqnwIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoG -CCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHgAAwHQYDVR0OBBYEFPD37/qzJg/+/Qws -V8GW0g0P1L07MB8GA1UdIwQYMBaAFKVY4bgN1p+8NOXoPdj6DKWDscBFMD0GCSqG -SIb3DQEBCjAwoA0wCwYJYIZIAWUDBAIDoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFl -AwQCA6IDAgFAA4IBAQCVRYStZNCUKNzu+kBiHBVJn5Dbu97s3jHBw0ACphUp+M75 -O1ohoT+ny3wgIJx4sN1Fc80cT24o1V48nI4nJTlgAhYyjYjaMilHpwLP4oLclQX8 -OUoyoTPIIRfP4UNRmxAtH+2eEGieO1QDsYyqsGKR9DeWme4t4dc/NTuZ8/E3UW9C -m0VO0ev3m8ZGfWANRP0yyjnvke4I5awFur9ncGn3vwZYJLDlV9dwi3B68VUzt4Um -jz4yhgCU+kOqID/HXgWUCosreQGN+KqungUlENOVvBV4sTfQpnaAJaKpT4zkEYMP -sRkBrV12dCYh4NIpqDsnjSpWEuDlpT4F3hJx2BqU ------END CERTIFICATE----- diff --git a/util/build.gradle b/util/build.gradle index 6fc6cc7792..60e3361bdc 100644 --- a/util/build.gradle +++ b/util/build.gradle @@ -17,11 +17,8 @@ sourceSets { dependencies { - implementation project(':core') + implementation project(':prov') - implementation files("${bc_prov}") - // implementation project(path: ':core') - implementation project(path: ':prov') testImplementation group: 'junit', name: 'junit', version: '4.11' @@ -29,27 +26,24 @@ dependencies { builtBy compileJava } java9Implementation project(':prov') - // java9Implementation project(':core') - java9Implementation project(path:':prov') + } +evaluationDependsOn(":prov") + compileJava { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } - targetCompatibility = 1.8; - sourceCompatibility = 1.8; + options.release = 8 } compileJava9Java { - javaCompiler = javaToolchains.compilerFor { - languageVersion = JavaLanguageVersion.of(17) - } + + + def prov_jar="${project(":prov").jar.outputs.files.getFiles().getAt(0)}" options.compilerArgs += [ - '--module-path', "${bc_prov}" + '--module-path', "${prov_jar}" ] sourceCompatibility = 9 @@ -64,16 +58,26 @@ jar { from sourceSets.java9.output } String packages = 'org.bouncycastle.asn1.{bsi|cmc|cmp|cms|crmf|cryptlib|dvcs|eac|edec|esf|ess|est|gnu|iana|icao|isara|isismtt|iso|kisa|microsoft|misc|mozilla|nsri|ntt|oiw|rosstandart|smime|tsp}.*' - + String v = "${rootProject.extensions.ext.bundle_version}" manifest.attributes('Multi-Release': 'true') manifest.attributes('Bundle-Name': 'bcutil') manifest.attributes('Bundle-SymbolicName': 'bcutil') manifest.attributes('Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8') - manifest.attributes('Export-Package': "${packages},org.bouncycastle.oer.*") - manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!${packages},!org.bouncycastle.oer.*,org.bouncycastle.*;version=\"[${version},${maxVersion})\"") + manifest.attributes('Export-Package': "${packages};version=${v},org.bouncycastle.oer.*;version=${v}") + manifest.attributes('Import-Package': "java.*;resolution:=optional,javax.*;resolution:=optional,!${packages},!org.bouncycastle.oer.*,org.bouncycastle.*;version=\"[${v},${maxVersion})\"") + manifest.attributes('Bundle-Version': "${v}") +} + +jar.doLast { + if (System.getenv("SIGNJAR_CMD") != null ) { + exec { + commandLine(System.getenv("SIGNJAR_CMD"),jar.archiveFile) + } + } } + task sourcesJar(type: Jar) { archiveBaseName = jar.archiveBaseName archiveClassifier = 'sources' @@ -96,6 +100,21 @@ artifacts { archives sourcesJar } +publishing { + publications { + maven(MavenPublication) { + groupId = 'org.bouncycastle' + artifactId = "bcutil-$vmrange" + from components.java + + artifact(javadocJar) + artifact(sourcesJar) + } + + } +} + + test { forkEvery = 1; maxParallelForks = 8; diff --git a/util/src/main/java/org/bouncycastle/asn1/bsi/BSIObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/bsi/BSIObjectIdentifiers.java index 290b3f2640..ec27b05e1f 100644 --- a/util/src/main/java/org/bouncycastle/asn1/bsi/BSIObjectIdentifiers.java +++ b/util/src/main/java/org/bouncycastle/asn1/bsi/BSIObjectIdentifiers.java @@ -93,23 +93,23 @@ public interface BSIObjectIdentifiers static final ASN1ObjectIdentifier ecka_eg_SessionKDF_AES192 = ecka_eg_SessionKDF.branch("3"); static final ASN1ObjectIdentifier ecka_eg_SessionKDF_AES256 = ecka_eg_SessionKDF.branch("4"); - /** AES encryption (CBC) and authentication (CMAC) + /* AES encryption (CBC) and authentication (CMAC) * OID: 0.4.0.127.0.7.1.x */ //TODO: replace "1" with correct OID //static final ASN1ObjectIdentifier aes_cbc_cmac = algorithm.branch("1"); - /** AES encryption (CBC) and authentication (CMAC) with 128 bit + /* AES encryption (CBC) and authentication (CMAC) with 128 bit * OID: 0.4.0.127.0.7.1.x.y1 */ //TODO: replace "1" with correct OID //static final ASN1ObjectIdentifier id_aes128_CBC_CMAC = aes_cbc_cmac.branch("1"); - /** AES encryption (CBC) and authentication (CMAC) with 192 bit + /* AES encryption (CBC) and authentication (CMAC) with 192 bit * OID: 0.4.0.127.0.7.1.x.y2 */ //TODO: replace "1" with correct OID //static final ASN1ObjectIdentifier id_aes192_CBC_CMAC = aes_cbc_cmac.branch("1"); - /** AES encryption (CBC) and authentication (CMAC) with 256 bit + /* AES encryption (CBC) and authentication (CMAC) with 256 bit * OID: 0.4.0.127.0.7.1.x.y3 */ //TODO: replace "1" with correct OID //static final ASN1ObjectIdentifier id_aes256_CBC_CMAC = aes_cbc_cmac.branch("1"); diff --git a/util/src/main/java/org/bouncycastle/asn1/bsi/package-info.java b/util/src/main/java/org/bouncycastle/asn1/bsi/package-info.java new file mode 100644 index 0000000000..429c2b313b --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/bsi/package-info.java @@ -0,0 +1,4 @@ +/** + * ASN.1 classes specific to the Bundesamt für Sicherheit in der Informationstechnik (BSI) standards. + */ +package org.bouncycastle.asn1.bsi; diff --git a/util/src/main/java/org/bouncycastle/asn1/cmc/GetCert.java b/util/src/main/java/org/bouncycastle/asn1/cmc/GetCert.java index 5b0fbba29c..4b274849a2 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmc/GetCert.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmc/GetCert.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -67,11 +66,6 @@ public BigInteger getSerialNumber() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(issuerName); - v.add(new ASN1Integer(serialNumber)); - - return new DERSequence(v); + return new DERSequence(issuerName, new ASN1Integer(serialNumber)); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cmc/LraPopWitness.java b/util/src/main/java/org/bouncycastle/asn1/cmc/LraPopWitness.java index ae022c7221..e486bd32b1 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmc/LraPopWitness.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmc/LraPopWitness.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cmc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -73,11 +72,6 @@ public BodyPartID[] getBodyIds() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(pkiDataBodyid); - v.add(bodyIds); - - return new DERSequence(v); + return new DERSequence(pkiDataBodyid, bodyIds); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cmc/PendInfo.java b/util/src/main/java/org/bouncycastle/asn1/cmc/PendInfo.java index ec0f3680ac..ad4febfec2 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmc/PendInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmc/PendInfo.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cmc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; @@ -57,12 +56,7 @@ public static PendInfo getInstance(Object o) public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(new DEROctetString(pendToken)); - v.add(pendTime); - - return new DERSequence(v); + return new DERSequence(new DEROctetString(pendToken), pendTime); } public byte[] getPendToken() diff --git a/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedCertificationRequest.java b/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedCertificationRequest.java index 81ecc6f599..953df3460b 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedCertificationRequest.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedCertificationRequest.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cmc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -71,11 +70,6 @@ public CertificationRequest getCertificationRequest() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(bodyPartID); - v.add(certificationRequest); - - return new DERSequence(v); + return new DERSequence(bodyPartID, certificationRequest); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedContentInfo.java b/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedContentInfo.java index cae87cf571..b62a36b91f 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedContentInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmc/TaggedContentInfo.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cmc; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -62,12 +61,7 @@ public static TaggedContentInfo getInstance( public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(bodyPartID); - v.add(contentInfo); - - return new DERSequence(v); + return new DERSequence(bodyPartID, contentInfo); } public BodyPartID getBodyPartID() diff --git a/util/src/main/java/org/bouncycastle/asn1/cmc/package-info.java b/util/src/main/java/org/bouncycastle/asn1/cmc/package-info.java new file mode 100644 index 0000000000..4271e1d487 --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/cmc/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for Certificate Management over CMS (CMC) - RFC 5272 and RFC 6402. + */ +package org.bouncycastle.asn1.cmc; diff --git a/util/src/main/java/org/bouncycastle/asn1/cmp/CMPObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/cmp/CMPObjectIdentifiers.java index dfe71835ef..74de80e35d 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmp/CMPObjectIdentifiers.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmp/CMPObjectIdentifiers.java @@ -1,7 +1,9 @@ package org.bouncycastle.asn1.cmp; import org.bouncycastle.asn1.ASN1ObjectIdentifier; - +import org.bouncycastle.asn1.crmf.CRMFObjectIdentifiers; +import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; public interface CMPObjectIdentifiers { @@ -10,12 +12,17 @@ public interface CMPObjectIdentifiers /** * id-PasswordBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 13} */ - ASN1ObjectIdentifier passwordBasedMac = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13"); + ASN1ObjectIdentifier passwordBasedMac = CRMFObjectIdentifiers.passwordBasedMac; + + /* + * id-KemBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 16} + */ + ASN1ObjectIdentifier kemBasedMac = MiscObjectIdentifiers.entrust.branch("66.16"); /** * id-DHBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 30} */ - ASN1ObjectIdentifier dhBasedMac = new ASN1ObjectIdentifier("1.2.840.113533.7.66.30"); + ASN1ObjectIdentifier dhBasedMac = MiscObjectIdentifiers.entrust.branch("66.30"); // Example InfoTypeAndValue contents include, but are not limited // to, the following (un-comment in this ASN.1 module and use as @@ -60,7 +67,7 @@ public interface CMPObjectIdentifiers // id-it OBJECT IDENTIFIER ::= {id-pkix 4} /** RFC 4120: id-it: PKIX.4 = 1.3.6.1.5.5.7.4 */ - ASN1ObjectIdentifier id_it = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.4"); + ASN1ObjectIdentifier id_it = X509ObjectIdentifiers.id_pkix.branch("4"); /** * RFC 4120: 1.3.6.1.5.5.7.4.1 @@ -179,57 +186,71 @@ public interface CMPObjectIdentifiers /** * RFC 4211: it-pkip: PKIX.5 = 1.3.6.1.5.5.7.5 */ - ASN1ObjectIdentifier id_pkip = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5"); + ASN1ObjectIdentifier id_pkip = CRMFObjectIdentifiers.id_pkip; /** * RFC 4211: it-regCtrl: 1.3.6.1.5.5.7.5.1 */ - ASN1ObjectIdentifier id_regCtrl = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1"); + ASN1ObjectIdentifier id_regCtrl = CRMFObjectIdentifiers.id_regCtrl; /** * RFC 4211: it-regInfo: 1.3.6.1.5.5.7.5.2 */ - ASN1ObjectIdentifier id_regInfo = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.2"); + ASN1ObjectIdentifier id_regInfo = CRMFObjectIdentifiers.id_regInfo; /** * 1.3.6.1.5.5.7.5.1.1 */ - ASN1ObjectIdentifier regCtrl_regToken = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.1"); + ASN1ObjectIdentifier regCtrl_regToken = CRMFObjectIdentifiers.id_regCtrl_regToken; /** * 1.3.6.1.5.5.7.5.1.2 */ - ASN1ObjectIdentifier regCtrl_authenticator = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.2"); + ASN1ObjectIdentifier regCtrl_authenticator = CRMFObjectIdentifiers.id_regCtrl_authenticator; /** * 1.3.6.1.5.5.7.5.1.3 */ - ASN1ObjectIdentifier regCtrl_pkiPublicationInfo = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.3"); + ASN1ObjectIdentifier regCtrl_pkiPublicationInfo = CRMFObjectIdentifiers.id_regCtrl_pkiPublicationInfo; /** * 1.3.6.1.5.5.7.5.1.4 */ - ASN1ObjectIdentifier regCtrl_pkiArchiveOptions = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.4"); + ASN1ObjectIdentifier regCtrl_pkiArchiveOptions = CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions; /** * 1.3.6.1.5.5.7.5.1.5 */ - ASN1ObjectIdentifier regCtrl_oldCertID = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.5"); + ASN1ObjectIdentifier regCtrl_oldCertID = CRMFObjectIdentifiers.id_regCtrl_oldCertID; /** * 1.3.6.1.5.5.7.5.1.6 */ - ASN1ObjectIdentifier regCtrl_protocolEncrKey = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.6"); + ASN1ObjectIdentifier regCtrl_protocolEncrKey = CRMFObjectIdentifiers.id_regCtrl_protocolEncrKey; /** * From RFC4210: * id-regCtrl-altCertTemplate OBJECT IDENTIFIER ::= {id-regCtrl 7}; 1.3.6.1.5.5.7.1.7 */ - ASN1ObjectIdentifier regCtrl_altCertTemplate = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.1.7"); + ASN1ObjectIdentifier regCtrl_altCertTemplate = id_regCtrl.branch("7"); + + /** + * id-regCtrl-algId OBJECT IDENTIFIER ::= { iso(1) + * identified-organization(3) dod(6) internet(1) security(5) + * mechanisms(5) pkix(7) pkip(5) regCtrl(1) 11 } + */ + ASN1ObjectIdentifier id_regCtrl_algId = id_regCtrl.branch("11"); + + /** + * id-regCtrl-rsaKeyLen OBJECT IDENTIFIER ::= { iso(1) + * identified-organization(3) dod(6) internet(1) security(5) + * mechanisms(5) pkix(7) pkip(5) regCtrl(1) 12 } + */ + ASN1ObjectIdentifier id_regCtrl_rsaKeyLen = id_regCtrl.branch("12"); /** * RFC 4211: it-regInfo-utf8Pairs: 1.3.6.1.5.5.7.5.2.1 */ - ASN1ObjectIdentifier regInfo_utf8Pairs = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.2.1"); + ASN1ObjectIdentifier regInfo_utf8Pairs = CRMFObjectIdentifiers.id_regInfo_utf8Pairs; /** * RFC 4211: it-regInfo-certReq: 1.3.6.1.5.5.7.5.2.1 */ - ASN1ObjectIdentifier regInfo_certReq = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.5.2.2"); + ASN1ObjectIdentifier regInfo_certReq = CRMFObjectIdentifiers.id_regInfo_certReq; /** * 1.2.840.113549.1.9.16.1.21 @@ -238,26 +259,5 @@ public interface CMPObjectIdentifiers *

      * id-ct-encKeyWithID OBJECT IDENTIFIER ::= {id-ct 21} */ - ASN1ObjectIdentifier ct_encKeyWithID = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.1.21"); - - - /** - * id-regCtrl-algId OBJECT IDENTIFIER ::= { iso(1) - * identified-organization(3) dod(6) internet(1) security(5) - * mechanisms(5) pkix(7) pkip(5) regCtrl(1) 11 } - */ - ASN1ObjectIdentifier id_regCtrl_algId = id_pkip.branch("1.11"); - - /** - * id-regCtrl-rsaKeyLen OBJECT IDENTIFIER ::= { iso(1) - * identified-organization(3) dod(6) internet(1) security(5) - * mechanisms(5) pkix(7) pkip(5) regCtrl(1) 12 } - */ - ASN1ObjectIdentifier id_regCtrl_rsaKeyLen = id_pkip.branch("1.12"); - - // TODO Update once OID allocated. - /* - * id-KemBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 TBD4} - */ -// ASN1ObjectIdentifier id_KemBasedMac = new ASN1ObjectIdentifier("1.2.840.113533.7.66.TBD4"); + ASN1ObjectIdentifier ct_encKeyWithID = CRMFObjectIdentifiers.id_ct_encKeyWithID; } diff --git a/util/src/main/java/org/bouncycastle/asn1/cmp/KemCiphertextInfo.java b/util/src/main/java/org/bouncycastle/asn1/cmp/KemCiphertextInfo.java index c6da437184..7d477cfe05 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmp/KemCiphertextInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmp/KemCiphertextInfo.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cmp; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; @@ -79,11 +78,6 @@ public ASN1OctetString getCt() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(kem); - v.add(ct); - - return new DERSequence(v); + return new DERSequence(kem, ct); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cmp/PKIStatusInfo.java b/util/src/main/java/org/bouncycastle/asn1/cmp/PKIStatusInfo.java index 7e656e0770..595e02934a 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmp/PKIStatusInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmp/PKIStatusInfo.java @@ -110,6 +110,11 @@ public BigInteger getStatus() return status.getValue(); } + public ASN1Integer getStatusObject() + { + return status; + } + public PKIFreeText getStatusString() { return statusString; diff --git a/util/src/main/java/org/bouncycastle/asn1/cmp/ProtectedPart.java b/util/src/main/java/org/bouncycastle/asn1/cmp/ProtectedPart.java index 48471eb0de..718ab3957d 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cmp/ProtectedPart.java +++ b/util/src/main/java/org/bouncycastle/asn1/cmp/ProtectedPart.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cmp; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -69,11 +68,6 @@ public PKIBody getBody() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(header); - v.add(body); - - return new DERSequence(v); + return new DERSequence(header, body); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cmp/package-info.java b/util/src/main/java/org/bouncycastle/asn1/cmp/package-info.java new file mode 100644 index 0000000000..80c194a53f --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/cmp/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and supporting PKIX-CMP as described RFC 4210. + */ +package org.bouncycastle.asn1.cmp; diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/Attribute.java b/util/src/main/java/org/bouncycastle/asn1/cms/Attribute.java index f5995b0709..ff4c42dad7 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/Attribute.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/Attribute.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.cms; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -100,11 +99,6 @@ public ASN1Encodable[] getAttributeValues() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(attrType); - v.add(attrValues); - - return new DERSequence(v); + return new DERSequence(attrType, attrValues); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/AuthenticatedData.java b/util/src/main/java/org/bouncycastle/asn1/cms/AuthenticatedData.java index 4577d81929..8883199e28 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/AuthenticatedData.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/AuthenticatedData.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.cms; -import java.util.Enumeration; - +import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; @@ -256,54 +255,68 @@ public ASN1Primitive toASN1Primitive() public static int calculateVersion(OriginatorInfo origInfo) { - if (origInfo == null) - { - return 0; - } - else + /* + * IF (originatorInfo is present) AND + * ((any certificates with a type of other are present) OR + * (any crls with a type of other are present)) + * THEN version is 3 + * ELSE + * IF ((originatorInfo is present) AND + * (any version 2 attribute certificates are present)) + * THEN version is 1 + * ELSE version is 0 + */ + + if (origInfo != null) { - int ver = 0; - - for (Enumeration e = origInfo.getCertificates().getObjects(); e.hasMoreElements();) + ASN1Set crls = origInfo.getCRLs(); + if (crls != null) { - Object obj = e.nextElement(); - - if (obj instanceof ASN1TaggedObject) + for (int i = 0, count = crls.size(); i < count; ++i) { - ASN1TaggedObject tag = (ASN1TaggedObject)obj; - - if (tag.getTagNo() == 2) - { - ver = 1; - } - else if (tag.getTagNo() == 3) + ASN1Encodable element = crls.getObjectAt(i); + if (element instanceof ASN1TaggedObject) { - ver = 3; - break; + ASN1TaggedObject tagged = (ASN1TaggedObject)element; + + // RevocationInfoChoice.other + if (tagged.hasContextTag(1)) + { + return 3; + } } } } - if (origInfo.getCRLs() != null) + ASN1Set certs = origInfo.getCertificates(); + if (certs != null) { - for (Enumeration e = origInfo.getCRLs().getObjects(); e.hasMoreElements();) - { - Object obj = e.nextElement(); + boolean anyV2AttrCerts = false; - if (obj instanceof ASN1TaggedObject) + for (int i = 0, count = certs.size(); i < count; ++i) + { + ASN1Encodable element = certs.getObjectAt(i); + if (element instanceof ASN1TaggedObject) { - ASN1TaggedObject tag = (ASN1TaggedObject)obj; + ASN1TaggedObject tagged = (ASN1TaggedObject)element; - if (tag.getTagNo() == 1) + // CertificateChoices.other + if (tagged.hasContextTag(3)) { - ver = 3; - break; + return 3; } + + // CertificateChoices.v2AttrCert + anyV2AttrCerts = anyV2AttrCerts || tagged.hasContextTag(2); } } - } - return ver; + if (anyV2AttrCerts) + { + return 1; + } + } } + return 0; } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/CMSORIforKEMOtherInfo.java b/util/src/main/java/org/bouncycastle/asn1/cms/CMSORIforKEMOtherInfo.java index 9543360cad..332a0c7630 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/CMSORIforKEMOtherInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/CMSORIforKEMOtherInfo.java @@ -13,7 +13,7 @@ *

        *  CMSORIforKEMOtherInfo ::= SEQUENCE {
        *     wrap KeyEncryptionAlgorithmIdentifier,
      - *     kekLength INTEGER (1..MAX),
      + *     kekLength INTEGER (1..65535),
        *     ukm [0] EXPLICIT UserKeyingMaterial OPTIONAL
        *   }
        *
      @@ -34,6 +34,10 @@ public CMSORIforKEMOtherInfo(AlgorithmIdentifier wrap, int kekLength)
       
           public CMSORIforKEMOtherInfo(AlgorithmIdentifier wrap, int kekLength, byte[] ukm)
           {
      +        if (kekLength > 65535)
      +        {
      +            throw new IllegalArgumentException("kekLength must be <= 65535");
      +        }
               this.wrap = wrap;
               this.kekLength = kekLength;
               this.ukm = ukm;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/CMSObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/cms/CMSObjectIdentifiers.java
      index c2e910bcef..593eae2ddd 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/cms/CMSObjectIdentifiers.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/cms/CMSObjectIdentifiers.java
      @@ -2,6 +2,7 @@
       
       import org.bouncycastle.asn1.ASN1ObjectIdentifier;
       import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
      +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
       
       public interface CMSObjectIdentifiers
       {
      @@ -35,7 +36,7 @@ public interface CMSObjectIdentifiers
            *        dod(6) internet(1) security(5) mechanisms(5) pkix(7) ri(16) }
            * 
      */ - ASN1ObjectIdentifier id_ri = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.16"); + ASN1ObjectIdentifier id_ri = X509ObjectIdentifiers.id_pkix.branch("16"); /** 1.3.6.1.5.5.7.16.2 */ ASN1ObjectIdentifier id_ri_ocsp_response = id_ri.branch("2"); @@ -43,20 +44,20 @@ public interface CMSObjectIdentifiers ASN1ObjectIdentifier id_ri_scvp = id_ri.branch("4"); /** 1.3.6.1.5.5.7.6 */ - ASN1ObjectIdentifier id_alg = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.6"); + ASN1ObjectIdentifier id_alg = X509ObjectIdentifiers.pkix_algorithms; - ASN1ObjectIdentifier id_RSASSA_PSS_SHAKE128 = id_alg.branch("30"); + ASN1ObjectIdentifier id_RSASSA_PSS_SHAKE128 = X509ObjectIdentifiers.id_rsassa_pss_shake128; - ASN1ObjectIdentifier id_RSASSA_PSS_SHAKE256 = id_alg.branch("31"); + ASN1ObjectIdentifier id_RSASSA_PSS_SHAKE256 = X509ObjectIdentifiers.id_rsassa_pss_shake256; - ASN1ObjectIdentifier id_ecdsa_with_shake128 = id_alg.branch("32"); + ASN1ObjectIdentifier id_ecdsa_with_shake128 = X509ObjectIdentifiers.id_ecdsa_with_shake128; - ASN1ObjectIdentifier id_ecdsa_with_shake256 = id_alg.branch("33"); + ASN1ObjectIdentifier id_ecdsa_with_shake256 = X509ObjectIdentifiers.id_ecdsa_with_shake256; /** * OtherRecipientInfo types */ - ASN1ObjectIdentifier id_ori = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.13"); + ASN1ObjectIdentifier id_ori = PKCSObjectIdentifiers.id_smime.branch("13"); ASN1ObjectIdentifier id_ori_kem = id_ori.branch("3"); @@ -64,5 +65,5 @@ public interface CMSObjectIdentifiers * id-alg-cek-hkdf-sha256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) * us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) alg(3) 31 } */ - ASN1ObjectIdentifier id_alg_cek_hkdf_sha256 = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.3.31"); + ASN1ObjectIdentifier id_alg_cek_hkdf_sha256 = PKCSObjectIdentifiers.smime_alg.branch("31"); } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/ContentInfo.java b/util/src/main/java/org/bouncycastle/asn1/cms/ContentInfo.java index a728dace24..53c9347311 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/ContentInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/ContentInfo.java @@ -71,7 +71,7 @@ public static ContentInfo getInstance( ASN1TaggedObject obj, boolean explicit) { - return getInstance(ASN1Sequence.getInstance(obj, explicit)); + return new ContentInfo(ASN1Sequence.getInstance(obj, explicit)); } private ContentInfo( @@ -104,6 +104,11 @@ public ContentInfo( ASN1ObjectIdentifier contentType, ASN1Encodable content) { + if (contentType == null) + { + throw new NullPointerException("'contentType' cannot be null"); + } + this.contentType = contentType; this.content = content; if (content != null) diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/EnvelopedData.java b/util/src/main/java/org/bouncycastle/asn1/cms/EnvelopedData.java index 8d5738ab2c..29c4845111 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/EnvelopedData.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/EnvelopedData.java @@ -1,7 +1,5 @@ package org.bouncycastle.asn1.cms; -import java.util.Enumeration; - import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; @@ -184,42 +182,100 @@ public ASN1Primitive toASN1Primitive() public static int calculateVersion(OriginatorInfo originatorInfo, ASN1Set recipientInfos, ASN1Set unprotectedAttrs) { - // TODO: still not quite correct - Enumeration e = recipientInfos.getObjects(); - - boolean nonZeroFound = false; - boolean pwriOrOri = false; + /* + * IF (originatorInfo is present) AND + * ((any certificates with a type of other are present) OR + * (any crls with a type of other are present)) + * THEN version is 4 + * ELSE + * IF ((originatorInfo is present) AND + * (any version 2 attribute certificates are present)) OR + * (any RecipientInfo structures include pwri) OR + * (any RecipientInfo structures include ori) + * THEN version is 3 + * ELSE + * IF (originatorInfo is absent) AND + * (unprotectedAttrs is absent) AND + * (all RecipientInfo structures are version 0) + * THEN version is 0 + * ELSE version is 2 + */ - while (e.hasMoreElements()) + if (originatorInfo != null) { - RecipientInfo ri = RecipientInfo.getInstance(e.nextElement()); - - if (!ri.getVersion().hasValue(0)) + ASN1Set crls = originatorInfo.getCRLs(); + if (crls != null) { - nonZeroFound = true; + for (int i = 0, count = crls.size(); i < count; ++i) + { + ASN1Encodable element = crls.getObjectAt(i); + if (element instanceof ASN1TaggedObject) + { + ASN1TaggedObject tagged = (ASN1TaggedObject)element; + + // RevocationInfoChoice.other + if (tagged.hasContextTag(1)) + { + return 4; + } + } + } } - ASN1Encodable info = ri.getInfo(); - if (info instanceof PasswordRecipientInfo || info instanceof OtherRecipientInfo) + + ASN1Set certs = originatorInfo.getCertificates(); + if (certs != null) { - pwriOrOri = true; + boolean anyV2AttrCerts = false; + + for (int i = 0, count = certs.size(); i < count; ++i) + { + ASN1Encodable element = certs.getObjectAt(i); + if (element instanceof ASN1TaggedObject) + { + ASN1TaggedObject tagged = (ASN1TaggedObject)element; + + // CertificateChoices.other + if (tagged.hasContextTag(3)) + { + return 4; + } + + // CertificateChoices.v2AttrCert + anyV2AttrCerts = anyV2AttrCerts || tagged.hasContextTag(2); + } + } + + if (anyV2AttrCerts) + { + return 3; + } } } - if (pwriOrOri) + boolean allV0Recipients = true; + for (int i = 0, count = recipientInfos.size(); i < count; ++i) { - return 3; - } + RecipientInfo recipientInfo = RecipientInfo.getInstance(recipientInfos.getObjectAt(i)); - if (nonZeroFound) - { - return 2; + // (any RecipientInfo structures include pwri) OR + // (any RecipientInfo structures include ori) + if (recipientInfo.isPasswordOrOther()) + { + return 3; + } + + // (all RecipientInfo structures are version 0) + // -- 'kari.version' is always 3 + // -- 'kekri.version' is always 4 + // -- 'pwri' and 'ori' have already been excluded + allV0Recipients = allV0Recipients && recipientInfo.isKeyTransV0(); } - if (originatorInfo != null || unprotectedAttrs != null) + if (originatorInfo == null && unprotectedAttrs == null && allV0Recipients) { - return 2; + return 0; } - return 0; + return 2; } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/GenericHybridParameters.java b/util/src/main/java/org/bouncycastle/asn1/cms/GenericHybridParameters.java index a4edceb8bd..f87cedb39b 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/GenericHybridParameters.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/GenericHybridParameters.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cms; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -69,11 +68,6 @@ public AlgorithmIdentifier getKem() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(kem); - v.add(dem); - - return new DERSequence(v); + return new DERSequence(kem, dem); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/IssuerAndSerialNumber.java b/util/src/main/java/org/bouncycastle/asn1/cms/IssuerAndSerialNumber.java index 960ee7a65c..6e59f168f7 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/IssuerAndSerialNumber.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/IssuerAndSerialNumber.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -128,11 +127,6 @@ public ASN1Integer getSerialNumber() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(name); - v.add(serialNumber); - - return new DERSequence(v); + return new DERSequence(name, serialNumber); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/KEMRecipientInfo.java b/util/src/main/java/org/bouncycastle/asn1/cms/KEMRecipientInfo.java index aeb2df8aa4..7f8e8e462c 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/KEMRecipientInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/KEMRecipientInfo.java @@ -12,16 +12,21 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; /** + *

      + * Defined in RFC 9629. + *

      + *
        *   KEMRecipientInfo ::= SEQUENCE {
        *     version CMSVersion,  -- always set to 0
        *     rid RecipientIdentifier,
        *     kem KEMAlgorithmIdentifier,
        *     kemct OCTET STRING,
        *     kdf KeyDerivationAlgorithmIdentifier,
      - *     kekLength INTEGER (1..MAX),
      + *     kekLength INTEGER (1..65535),
        *     ukm [0] EXPLICIT UserKeyingMaterial OPTIONAL,
        *     wrap KeyEncryptionAlgorithmIdentifier,
        *     encryptedKey EncryptedKey }
      + * 
      */ public class KEMRecipientInfo extends ASN1Object @@ -47,6 +52,10 @@ public KEMRecipientInfo(RecipientIdentifier rid, AlgorithmIdentifier kem, ASN1Oc { throw new NullPointerException("wrap cannot be null"); } + if (kekLength.intValueExact() > 65535) + { + throw new IllegalArgumentException("kekLength must be <= 65535"); + } this.cmsVersion = new ASN1Integer(0); this.rid = rid; this.kem = kem; @@ -74,9 +83,9 @@ else if (o != null) private KEMRecipientInfo(ASN1Sequence seq) { - if (seq.size() != 3) + if (seq.size() < 8 || seq.size() > 9) { - throw new IllegalArgumentException("sequence must consist of 3 elements"); + throw new IllegalArgumentException("bad sequence size: " + seq.size()); } cmsVersion = ASN1Integer.getInstance(seq.getObjectAt(0)); @@ -86,6 +95,11 @@ private KEMRecipientInfo(ASN1Sequence seq) kdf = AlgorithmIdentifier.getInstance(seq.getObjectAt(4)); kekLength = ASN1Integer.getInstance(seq.getObjectAt(5)); + if (kekLength.intValueExact() > 65535) + { + throw new IllegalArgumentException("kekLength must be <= 65535"); + } + int elt = 6; if (seq.getObjectAt(6) instanceof ASN1TaggedObject) { @@ -125,14 +139,14 @@ public AlgorithmIdentifier getWrap() } public byte[] getUkm() - { - if (ukm == null) - { - return null; - } - - return ukm.getOctets(); - } + { + if (ukm == null) + { + return null; + } + + return ukm.getOctets(); + } public ASN1OctetString getEncryptedKey() { diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/KeyAgreeRecipientIdentifier.java b/util/src/main/java/org/bouncycastle/asn1/cms/KeyAgreeRecipientIdentifier.java index f67d3b88a3..98ca19a504 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/KeyAgreeRecipientIdentifier.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/KeyAgreeRecipientIdentifier.java @@ -3,8 +3,8 @@ import org.bouncycastle.asn1.ASN1Choice; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; +import org.bouncycastle.asn1.ASN1Util; import org.bouncycastle.asn1.DERTaggedObject; /** @@ -37,9 +37,14 @@ public static KeyAgreeRecipientIdentifier getInstance( ASN1TaggedObject obj, boolean explicit) { - return getInstance(ASN1Sequence.getInstance(obj, explicit)); + if (!explicit) + { + throw new IllegalArgumentException("choice item must be explicitly tagged"); + } + + return getInstance(obj.getExplicitBaseObject()); } - + /** * Return an KeyAgreeRecipientIdentifier object from the given object. *

      @@ -62,19 +67,20 @@ public static KeyAgreeRecipientIdentifier getInstance( { return (KeyAgreeRecipientIdentifier)obj; } - - if (obj instanceof ASN1Sequence) - { - return new KeyAgreeRecipientIdentifier(IssuerAndSerialNumber.getInstance(obj)); - } - - if (obj instanceof ASN1TaggedObject && ((ASN1TaggedObject)obj).getTagNo() == 0) + + if (obj instanceof ASN1TaggedObject) { - return new KeyAgreeRecipientIdentifier(RecipientKeyIdentifier.getInstance( - (ASN1TaggedObject)obj, false)); + ASN1TaggedObject taggedObject = (ASN1TaggedObject)obj; + if (taggedObject.hasContextTag(0)) + { + return new KeyAgreeRecipientIdentifier(RecipientKeyIdentifier.getInstance(taggedObject, false)); + } + + throw new IllegalArgumentException("Invalid KeyAgreeRecipientIdentifier tag: " + + ASN1Util.getTagText(taggedObject)); } - - throw new IllegalArgumentException("Invalid KeyAgreeRecipientIdentifier: " + obj.getClass().getName()); + + return new KeyAgreeRecipientIdentifier(IssuerAndSerialNumber.getInstance(obj)); } public KeyAgreeRecipientIdentifier( diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/OriginatorPublicKey.java b/util/src/main/java/org/bouncycastle/asn1/cms/OriginatorPublicKey.java index c35f9c0ac3..7719ef009c 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/OriginatorPublicKey.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/OriginatorPublicKey.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.cms; import org.bouncycastle.asn1.ASN1BitString; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -118,11 +117,6 @@ public ASN1BitString getPublicKeyData() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(algorithm); - v.add(publicKey); - - return new DERSequence(v); + return new DERSequence(algorithm, publicKey); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/OtherKeyAttribute.java b/util/src/main/java/org/bouncycastle/asn1/cms/OtherKeyAttribute.java index c141a54b82..ca97ae7dc8 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/OtherKeyAttribute.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/OtherKeyAttribute.java @@ -57,7 +57,11 @@ private OtherKeyAttribute( ASN1Sequence seq) { keyAttrId = (ASN1ObjectIdentifier)seq.getObjectAt(0); - keyAttr = seq.getObjectAt(1); + + if (seq.size() > 1) + { + keyAttr = seq.getObjectAt(1); + } } public OtherKeyAttribute( @@ -86,7 +90,11 @@ public ASN1Primitive toASN1Primitive() ASN1EncodableVector v = new ASN1EncodableVector(2); v.add(keyAttrId); - v.add(keyAttr); + + if (keyAttr != null) + { + v.add(keyAttr); + } return new DERSequence(v); } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/OtherRecipientInfo.java b/util/src/main/java/org/bouncycastle/asn1/cms/OtherRecipientInfo.java index 0685c8284b..90db62699f 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/OtherRecipientInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/OtherRecipientInfo.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.cms; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -99,11 +98,6 @@ public ASN1Encodable getValue() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(oriType); - v.add(oriValue); - - return new DERSequence(v); + return new DERSequence(oriType, oriValue); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/OtherRevocationInfoFormat.java b/util/src/main/java/org/bouncycastle/asn1/cms/OtherRevocationInfoFormat.java index 5ad18bf97a..c65daca9ca 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/OtherRevocationInfoFormat.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/OtherRevocationInfoFormat.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.cms; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -99,11 +98,6 @@ public ASN1Encodable getInfo() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(otherRevInfoFormat); - v.add(otherRevInfo); - - return new DERSequence(v); + return new DERSequence(otherRevInfoFormat, otherRevInfo); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/RecipientEncryptedKey.java b/util/src/main/java/org/bouncycastle/asn1/cms/RecipientEncryptedKey.java index 4ee16da365..2e06e0b902 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/RecipientEncryptedKey.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/RecipientEncryptedKey.java @@ -1,6 +1,5 @@ package org.bouncycastle.asn1.cms; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; @@ -99,11 +98,6 @@ public ASN1OctetString getEncryptedKey() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(identifier); - v.add(encryptedKey); - - return new DERSequence(v); + return new DERSequence(identifier, encryptedKey); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/RecipientInfo.java b/util/src/main/java/org/bouncycastle/asn1/cms/RecipientInfo.java index 01ea91a670..23f6c0a043 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/RecipientInfo.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/RecipientInfo.java @@ -98,69 +98,68 @@ else if (o instanceof ASN1TaggedObject) + o.getClass().getName()); } + /** @deprecated Will be removed */ public ASN1Integer getVersion() { - if (info instanceof ASN1TaggedObject) + if (!(info instanceof ASN1TaggedObject)) { - ASN1TaggedObject o = (ASN1TaggedObject)info; + return KeyTransRecipientInfo.getInstance(info).getVersion(); + } - switch (o.getTagNo()) + ASN1TaggedObject tagged = (ASN1TaggedObject)info; + if (tagged.hasContextTag()) + { + switch (tagged.getTagNo()) { case 1: - return KeyAgreeRecipientInfo.getInstance(o, false).getVersion(); + return KeyAgreeRecipientInfo.getInstance(tagged, false).getVersion(); case 2: - return getKEKInfo(o).getVersion(); + return getKEKInfo(tagged).getVersion(); case 3: - return PasswordRecipientInfo.getInstance(o, false).getVersion(); + return PasswordRecipientInfo.getInstance(tagged, false).getVersion(); case 4: return new ASN1Integer(0); // no syntax version for OtherRecipientInfo - default: - throw new IllegalStateException("unknown tag"); } } - - return KeyTransRecipientInfo.getInstance(info).getVersion(); + throw new IllegalStateException("unknown tag"); } public boolean isTagged() { - return (info instanceof ASN1TaggedObject); + return info instanceof ASN1TaggedObject; } public ASN1Encodable getInfo() { - if (info instanceof ASN1TaggedObject) + if (!(info instanceof ASN1TaggedObject)) { - ASN1TaggedObject o = (ASN1TaggedObject)info; + return KeyTransRecipientInfo.getInstance(info); + } - switch (o.getTagNo()) + ASN1TaggedObject tagged = (ASN1TaggedObject)info; + if (tagged.hasContextTag()) + { + switch (tagged.getTagNo()) { case 1: - return KeyAgreeRecipientInfo.getInstance(o, false); + return KeyAgreeRecipientInfo.getInstance(tagged, false); case 2: - return getKEKInfo(o); + return getKEKInfo(tagged); case 3: - return PasswordRecipientInfo.getInstance(o, false); + return PasswordRecipientInfo.getInstance(tagged, false); case 4: - return OtherRecipientInfo.getInstance(o, false); - default: - throw new IllegalStateException("unknown tag"); + return OtherRecipientInfo.getInstance(tagged, false); } } - - return KeyTransRecipientInfo.getInstance(info); + throw new IllegalStateException("unknown tag"); } private KEKRecipientInfo getKEKInfo(ASN1TaggedObject o) { - if (o.isExplicit()) - { // compatibilty with erroneous version - return KEKRecipientInfo.getInstance(o, true); - } - else - { - return KEKRecipientInfo.getInstance(o, false); - } + // For compatibility with erroneous version, we don't always pass 'false' here + boolean declaredExplicit = o.isExplicit(); + + return KEKRecipientInfo.getInstance(o, declaredExplicit); } /** @@ -170,4 +169,34 @@ public ASN1Primitive toASN1Primitive() { return info.toASN1Primitive(); } + + boolean isKeyTransV0() + { + if (info instanceof ASN1TaggedObject) + { + return false; + } + + KeyTransRecipientInfo ktri = KeyTransRecipientInfo.getInstance(info); + + return ktri.getVersion().hasValue(0); + } + + boolean isPasswordOrOther() + { + if (info instanceof ASN1TaggedObject) + { + ASN1TaggedObject tagged = (ASN1TaggedObject)info; + if (tagged.hasContextTag()) + { + switch (tagged.getTagNo()) + { + case 3: + case 4: + return true; + } + } + } + return false; + } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/RsaKemParameters.java b/util/src/main/java/org/bouncycastle/asn1/cms/RsaKemParameters.java index 63ce88e752..ff1292e2f1 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/RsaKemParameters.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/RsaKemParameters.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -77,11 +76,6 @@ public BigInteger getKeyLength() public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(keyDerivationFunction); - v.add(new ASN1Integer(keyLength)); - - return new DERSequence(v); + return new DERSequence(keyDerivationFunction, new ASN1Integer(keyLength)); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/TimeStampAndCRL.java b/util/src/main/java/org/bouncycastle/asn1/cms/TimeStampAndCRL.java index dfa97a9433..3a89834d46 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cms/TimeStampAndCRL.java +++ b/util/src/main/java/org/bouncycastle/asn1/cms/TimeStampAndCRL.java @@ -24,8 +24,14 @@ public class TimeStampAndCRL private CertificateList crl; public TimeStampAndCRL(ContentInfo timeStamp) + { + this(timeStamp, null); + } + + public TimeStampAndCRL(ContentInfo timeStamp, CertificateList crl) { this.timeStamp = timeStamp; + this.crl = crl; } private TimeStampAndCRL(ASN1Sequence seq) diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/ecc/package-info.java b/util/src/main/java/org/bouncycastle/asn1/cms/ecc/package-info.java new file mode 100644 index 0000000000..c8d5543e62 --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/cms/ecc/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes for CMS ECC - RFC 5753/3278. + */ +package org.bouncycastle.asn1.cms.ecc; diff --git a/util/src/main/java/org/bouncycastle/asn1/cms/package-info.java b/util/src/main/java/org/bouncycastle/asn1/cms/package-info.java new file mode 100644 index 0000000000..f0b7f69770 --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/cms/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and supporting Cryptographic Message Syntax as described in PKCS#7 and RFC 3369 (formerly RFC 2630). + */ +package org.bouncycastle.asn1.cms; diff --git a/util/src/main/java/org/bouncycastle/asn1/crmf/AttributeTypeAndValue.java b/util/src/main/java/org/bouncycastle/asn1/crmf/AttributeTypeAndValue.java index aa46b8454f..2a81f6a913 100644 --- a/util/src/main/java/org/bouncycastle/asn1/crmf/AttributeTypeAndValue.java +++ b/util/src/main/java/org/bouncycastle/asn1/crmf/AttributeTypeAndValue.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.crmf; import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; @@ -70,11 +69,6 @@ public ASN1Encodable getValue() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(type); - v.add(value); - - return new DERSequence(v); + return new DERSequence(type, value); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/crmf/CRMFObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/crmf/CRMFObjectIdentifiers.java index 9db240c8c6..c2d24b745a 100644 --- a/util/src/main/java/org/bouncycastle/asn1/crmf/CRMFObjectIdentifiers.java +++ b/util/src/main/java/org/bouncycastle/asn1/crmf/CRMFObjectIdentifiers.java @@ -1,36 +1,51 @@ package org.bouncycastle.asn1.crmf; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; public interface CRMFObjectIdentifiers { + ASN1ObjectIdentifier passwordBasedMac = MiscObjectIdentifiers.entrust.branch("66.13"); + /** 1.3.6.1.5.5.7 */ - static final ASN1ObjectIdentifier id_pkix = new ASN1ObjectIdentifier("1.3.6.1.5.5.7"); + ASN1ObjectIdentifier id_pkix = X509ObjectIdentifiers.id_pkix; // arc for Internet X.509 PKI protocols and their components /** 1.3.6.1.5.5.7.5 */ - static final ASN1ObjectIdentifier id_pkip = id_pkix.branch("5"); + ASN1ObjectIdentifier id_pkip = id_pkix.branch("5"); /** 1.3.6.1.5.5.7.1 */ - static final ASN1ObjectIdentifier id_regCtrl = id_pkip.branch("1"); + ASN1ObjectIdentifier id_regCtrl = id_pkip.branch("1"); /** 1.3.6.1.5.5.7.1.1 */ - static final ASN1ObjectIdentifier id_regCtrl_regToken = id_regCtrl.branch("1"); + ASN1ObjectIdentifier id_regCtrl_regToken = id_regCtrl.branch("1"); /** 1.3.6.1.5.5.7.1.2 */ - static final ASN1ObjectIdentifier id_regCtrl_authenticator = id_regCtrl.branch("2"); + ASN1ObjectIdentifier id_regCtrl_authenticator = id_regCtrl.branch("2"); /** 1.3.6.1.5.5.7.1.3 */ - static final ASN1ObjectIdentifier id_regCtrl_pkiPublicationInfo = id_regCtrl.branch("3"); + ASN1ObjectIdentifier id_regCtrl_pkiPublicationInfo = id_regCtrl.branch("3"); /** 1.3.6.1.5.5.7.1.4 */ - static final ASN1ObjectIdentifier id_regCtrl_pkiArchiveOptions = id_regCtrl.branch("4"); + ASN1ObjectIdentifier id_regCtrl_pkiArchiveOptions = id_regCtrl.branch("4"); + /** 1.3.6.1.5.5.7.1.5 */ + ASN1ObjectIdentifier id_regCtrl_oldCertID = id_regCtrl.branch("5"); + /** 1.3.6.1.5.5.7.1.6 */ + ASN1ObjectIdentifier id_regCtrl_protocolEncrKey = id_regCtrl.branch("6"); + + /** 1.3.6.1.5.5.7.2 */ + ASN1ObjectIdentifier id_regInfo = id_pkip.branch("2"); + /** 1.3.6.1.5.5.7.2.1 */ + ASN1ObjectIdentifier id_regInfo_utf8Pairs = id_regInfo.branch("1"); + /** 1.3.6.1.5.5.7.2.2 */ + ASN1ObjectIdentifier id_regInfo_certReq = id_regInfo.branch("2"); /** 1.2.840.113549.1.9.16.1,21 */ - static final ASN1ObjectIdentifier id_ct_encKeyWithID = PKCSObjectIdentifiers.id_ct.branch("21"); + ASN1ObjectIdentifier id_ct_encKeyWithID = PKCSObjectIdentifiers.id_ct.branch("21"); /** 1.3.6.1.5.5.7.6 */ - static final ASN1ObjectIdentifier id_alg = id_pkix.branch("6"); + ASN1ObjectIdentifier id_alg = X509ObjectIdentifiers.pkix_algorithms; - static final ASN1ObjectIdentifier id_dh_sig_hmac_sha1 = id_alg.branch("3"); + ASN1ObjectIdentifier id_dh_sig_hmac_sha1 = id_alg.branch("3"); - static final ASN1ObjectIdentifier id_alg_dh_pop = id_alg.branch("4"); + ASN1ObjectIdentifier id_alg_dh_pop = id_alg.branch("4"); } diff --git a/util/src/main/java/org/bouncycastle/asn1/crmf/CertId.java b/util/src/main/java/org/bouncycastle/asn1/crmf/CertId.java index a431312647..df5ec7bf17 100644 --- a/util/src/main/java/org/bouncycastle/asn1/crmf/CertId.java +++ b/util/src/main/java/org/bouncycastle/asn1/crmf/CertId.java @@ -2,7 +2,6 @@ import java.math.BigInteger; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; @@ -74,11 +73,6 @@ public ASN1Integer getSerialNumber() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(issuer); - v.add(serialNumber); - - return new DERSequence(v); + return new DERSequence(issuer, serialNumber); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/crmf/PKMACValue.java b/util/src/main/java/org/bouncycastle/asn1/crmf/PKMACValue.java index de83c6a5d8..ad1d7033ff 100644 --- a/util/src/main/java/org/bouncycastle/asn1/crmf/PKMACValue.java +++ b/util/src/main/java/org/bouncycastle/asn1/crmf/PKMACValue.java @@ -1,7 +1,6 @@ package org.bouncycastle.asn1.crmf; import org.bouncycastle.asn1.ASN1BitString; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; @@ -95,11 +94,6 @@ public ASN1BitString getValue() */ public ASN1Primitive toASN1Primitive() { - ASN1EncodableVector v = new ASN1EncodableVector(2); - - v.add(algId); - v.add(value); - - return new DERSequence(v); + return new DERSequence(algId, value); } } diff --git a/util/src/main/java/org/bouncycastle/asn1/crmf/package-info.java b/util/src/main/java/org/bouncycastle/asn1/crmf/package-info.java new file mode 100644 index 0000000000..22e0a82313 --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/crmf/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and supporting PKIX-CRMF as described RFC 4211. + */ +package org.bouncycastle.asn1.crmf; diff --git a/util/src/main/java/org/bouncycastle/asn1/cryptlib/CryptlibObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/cryptlib/CryptlibObjectIdentifiers.java index 88dd03f5c1..7be99482d7 100644 --- a/util/src/main/java/org/bouncycastle/asn1/cryptlib/CryptlibObjectIdentifiers.java +++ b/util/src/main/java/org/bouncycastle/asn1/cryptlib/CryptlibObjectIdentifiers.java @@ -8,5 +8,11 @@ public class CryptlibObjectIdentifiers public static final ASN1ObjectIdentifier ecc = cryptlib.branch("1").branch("5"); + /** + * Curve25519Legacy for use with ECDH. + * + * @see + * RFC9580 - ECC Curves for OpenPGP + */ public static final ASN1ObjectIdentifier curvey25519 = ecc.branch("1"); } diff --git a/util/src/main/java/org/bouncycastle/asn1/dvcs/package-info.java b/util/src/main/java/org/bouncycastle/asn1/dvcs/package-info.java new file mode 100644 index 0000000000..56050549ab --- /dev/null +++ b/util/src/main/java/org/bouncycastle/asn1/dvcs/package-info.java @@ -0,0 +1,4 @@ +/** + * Support classes useful for encoding and processing Data Validation and Certification Server (DVCS) protocols as described in RFC 3029. + */ +package org.bouncycastle.asn1.dvcs; diff --git a/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificate.java b/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificate.java index 085ea6c388..4e6cdd52f2 100644 --- a/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificate.java +++ b/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificate.java @@ -1,10 +1,8 @@ package org.bouncycastle.asn1.eac; - import java.io.IOException; import java.util.Enumeration; -import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; @@ -17,7 +15,6 @@ import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.util.Arrays; - /** * an iso7816Certificate structure. *

      @@ -199,12 +196,10 @@ public CertificateBody getBody()
            */
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -
      -        v.add(certificateBody);
      -        v.add(EACTagged.create(EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP, signature));
      +        DERSequence seq = new DERSequence(certificateBody,
      +            EACTagged.create(EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP, signature));
       
      -        return EACTagged.create(EACTags.CARDHOLDER_CERTIFICATE, new DERSequence(v));
      +        return EACTagged.create(EACTags.CARDHOLDER_CERTIFICATE, seq);
           }
       
           /**
      diff --git a/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificateRequest.java b/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificateRequest.java
      index 8a11b2c902..f170625a02 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificateRequest.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/eac/CVCertificateRequest.java
      @@ -3,7 +3,6 @@
       import java.io.IOException;
       import java.util.Enumeration;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1OctetString;
       import org.bouncycastle.asn1.ASN1ParsingException;
      @@ -146,12 +145,10 @@ public ASN1Primitive toASN1Primitive()
               }
               else
               {
      -            ASN1EncodableVector v = new ASN1EncodableVector(2);
      +            DERSequence seq = new DERSequence(certificateBody,
      +                EACTagged.create(EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP, innerSignature));
       
      -            v.add(certificateBody);
      -            v.add(EACTagged.create(EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP, innerSignature));
      -
      -            return EACTagged.create(EACTags.CARDHOLDER_CERTIFICATE, new DERSequence(v));
      +            return EACTagged.create(EACTags.CARDHOLDER_CERTIFICATE, seq);
               }
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/eac/CertificateHolderAuthorization.java b/util/src/main/java/org/bouncycastle/asn1/eac/CertificateHolderAuthorization.java
      index ae5f0ccd66..bfcd020de7 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/eac/CertificateHolderAuthorization.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/eac/CertificateHolderAuthorization.java
      @@ -4,7 +4,6 @@
       import java.util.HashMap;
       import java.util.Map;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1ObjectIdentifier;
       import org.bouncycastle.asn1.ASN1OctetString;
      @@ -172,11 +171,9 @@ private void setOid(ASN1ObjectIdentifier oid)
            */
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      +        DERSequence seq = new DERSequence(oid,
      +            EACTagged.create(EACTags.DISCRETIONARY_DATA, new byte[]{ accessRights }));
       
      -        v.add(oid);
      -        v.add(EACTagged.create(EACTags.DISCRETIONARY_DATA, new byte[] { accessRights }));
      -
      -        return EACTagged.create(EACTags.CERTIFICATE_HOLDER_AUTHORIZATION_TEMPLATE, new DERSequence(v));
      +        return EACTagged.create(EACTags.CERTIFICATE_HOLDER_AUTHORIZATION_TEMPLATE, seq);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/eac/package-info.java b/util/src/main/java/org/bouncycastle/asn1/eac/package-info.java
      new file mode 100644
      index 0000000000..59c830ad2c
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/eac/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * ASN.1 classes specific to the Bundesamt für Sicherheit in der Informationstechnik (BSI) Technical Guideline Advanced Security Mechanisms for Machine Readable Travel Documents.
      + */
      +package org.bouncycastle.asn1.eac;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/esf/OcspIdentifier.java b/util/src/main/java/org/bouncycastle/asn1/esf/OcspIdentifier.java
      index 5a334220e9..38b9db5ddd 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/esf/OcspIdentifier.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/esf/OcspIdentifier.java
      @@ -1,6 +1,5 @@
       package org.bouncycastle.asn1.esf;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1GeneralizedTime;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1Primitive;
      @@ -65,9 +64,6 @@ public ASN1GeneralizedTime getProducedAt()
       
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -        v.add(this.ocspResponderID);
      -        v.add(this.producedAt);
      -        return new DERSequence(v);
      +        return new DERSequence(ocspResponderID, producedAt);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevRefs.java b/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevRefs.java
      index c564599684..38572a3635 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevRefs.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevRefs.java
      @@ -3,7 +3,6 @@
       import java.io.IOException;
       
       import org.bouncycastle.asn1.ASN1Encodable;
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Encoding;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1ObjectIdentifier;
      @@ -79,9 +78,6 @@ public ASN1Encodable getOtherRevRefs()
       
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -        v.add(this.otherRevRefType);
      -        v.add(this.otherRevRefs);
      -        return new DERSequence(v);
      +        return new DERSequence(otherRevRefType, otherRevRefs);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevVals.java b/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevVals.java
      index c2fc838bc5..466f8ea72f 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevVals.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/esf/OtherRevVals.java
      @@ -3,7 +3,6 @@
       import java.io.IOException;
       
       import org.bouncycastle.asn1.ASN1Encodable;
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Encoding;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1ObjectIdentifier;
      @@ -81,9 +80,6 @@ public ASN1Encodable getOtherRevVals()
       
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -        v.add(this.otherRevValType);
      -        v.add(this.otherRevVals);
      -        return new DERSequence(v);
      +        return new DERSequence(otherRevValType, otherRevVals);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/esf/package-info.java b/util/src/main/java/org/bouncycastle/asn1/esf/package-info.java
      new file mode 100644
      index 0000000000..ebbdcc0d61
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/esf/package-info.java
      @@ -0,0 +1,5 @@
      +/**
      + * Support classes useful for encoding and supporting [ESF] RFC3126 
      + * Electronic Signature Formats for long term electronic signatures.
      + */
      +package org.bouncycastle.asn1.esf;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertID.java b/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertID.java
      index 4004934351..ec09ba01f2 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertID.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertID.java
      @@ -63,6 +63,22 @@ public ESSCertID(
               this.issuerSerial = issuerSerial;
           }
       
      +    public ESSCertID(ASN1OctetString certHash, IssuerSerial issuerSerial)
      +    {
      +        if (certHash == null)
      +        {
      +            throw new NullPointerException("'certHash' cannot be null");
      +        }
      +
      +        this.certHash = certHash;
      +        this.issuerSerial = issuerSerial;
      +    }
      +
      +    public ASN1OctetString getCertHashObject()
      +    {
      +        return certHash;
      +    }
      +
           public byte[] getCertHash()
           {
               return certHash.getOctets();
      diff --git a/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertIDv2.java b/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertIDv2.java
      index 367f3efc1f..62f3676801 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertIDv2.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/ess/ESSCertIDv2.java
      @@ -8,6 +8,7 @@
       import org.bouncycastle.asn1.DEROctetString;
       import org.bouncycastle.asn1.DERSequence;
       import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
      +import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
       import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
       import org.bouncycastle.asn1.x509.IssuerSerial;
       import org.bouncycastle.util.Arrays;
      @@ -15,10 +16,19 @@
       public class ESSCertIDv2
           extends ASN1Object
       {
      +    private static final AlgorithmIdentifier DEFAULT_HASH_ALGORITHM =
      +        new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);
      +
      +    public static ESSCertIDv2 from(ESSCertID essCertID)
      +    {
      +        AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1);
      +
      +        return new ESSCertIDv2(hashAlgorithm, essCertID.getCertHashObject(), essCertID.getIssuerSerial());
      +    }
      +
           private AlgorithmIdentifier hashAlgorithm;
      -    private byte[]              certHash;
      -    private IssuerSerial        issuerSerial;
      -    private static final AlgorithmIdentifier DEFAULT_ALG_ID = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);
      +    private ASN1OctetString certHash;
      +    private IssuerSerial issuerSerial;
       
           public static ESSCertIDv2 getInstance(
               Object o)
      @@ -48,14 +58,14 @@ private ESSCertIDv2(
               if (seq.getObjectAt(0) instanceof ASN1OctetString)
               {
                   // Default value
      -            this.hashAlgorithm = DEFAULT_ALG_ID;
      +            this.hashAlgorithm = DEFAULT_HASH_ALGORITHM;
               }
               else
               {
      -            this.hashAlgorithm = AlgorithmIdentifier.getInstance(seq.getObjectAt(count++).toASN1Primitive());
      +            this.hashAlgorithm = AlgorithmIdentifier.getInstance(seq.getObjectAt(count++));
               }
       
      -        this.certHash = ASN1OctetString.getInstance(seq.getObjectAt(count++).toASN1Primitive()).getOctets();
      +        this.certHash = ASN1OctetString.getInstance(seq.getObjectAt(count++));
       
               if (seq.size() > count)
               {
      @@ -90,15 +100,27 @@ public ESSCertIDv2(
           {
               if (algId == null)
               {
      -            // Default value
      -            this.hashAlgorithm = DEFAULT_ALG_ID;
      +            algId = DEFAULT_HASH_ALGORITHM;
               }
      -        else
      +
      +        this.hashAlgorithm = algId;
      +        this.certHash = new DEROctetString(Arrays.clone(certHash));
      +        this.issuerSerial = issuerSerial;
      +    }
      +
      +    public ESSCertIDv2(AlgorithmIdentifier hashAlgorithm, ASN1OctetString certHash, IssuerSerial issuerSerial)
      +    {
      +        if (hashAlgorithm == null)
      +        {
      +            hashAlgorithm = DEFAULT_HASH_ALGORITHM;
      +        }
      +        if (certHash == null)
               {
      -            this.hashAlgorithm = algId;
      +            throw new NullPointerException("'certHash' cannot be null");
               }
       
      -        this.certHash = Arrays.clone(certHash);
      +        this.hashAlgorithm = hashAlgorithm;
      +        this.certHash = certHash;
               this.issuerSerial = issuerSerial;
           }
       
      @@ -107,9 +129,14 @@ public AlgorithmIdentifier getHashAlgorithm()
               return this.hashAlgorithm;
           }
       
      +    public ASN1OctetString getCertHashObject()
      +    {
      +        return certHash;
      +    }
      +
           public byte[] getCertHash()
           {
      -        return Arrays.clone(certHash);
      +        return Arrays.clone(certHash.getOctets());
           }
       
           public IssuerSerial getIssuerSerial()
      @@ -138,12 +165,12 @@ public ASN1Primitive toASN1Primitive()
           {
               ASN1EncodableVector v = new ASN1EncodableVector(3);
       
      -        if (!hashAlgorithm.equals(DEFAULT_ALG_ID))
      +        if (!DEFAULT_HASH_ALGORITHM.equals(hashAlgorithm))
               {
                   v.add(hashAlgorithm);
               }
       
      -        v.add(new DEROctetString(certHash).toASN1Primitive());
      +        v.add(certHash);
       
               if (issuerSerial != null)
               {
      @@ -152,5 +179,4 @@ public ASN1Primitive toASN1Primitive()
       
               return new DERSequence(v);
           }
      -
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/ess/package-info.java b/util/src/main/java/org/bouncycastle/asn1/ess/package-info.java
      new file mode 100644
      index 0000000000..39144cdc3d
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/ess/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes useful for encoding and supporting Enhanced Security Services for S/MIME as described RFC 2634 and RFC 5035.
      + */
      +package org.bouncycastle.asn1.ess;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/est/package-info.java b/util/src/main/java/org/bouncycastle/asn1/est/package-info.java
      new file mode 100644
      index 0000000000..7bdfaa71f5
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/est/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes for Enrollment over Secure Transport (EST) - RFC 7030.
      + */
      +package org.bouncycastle.asn1.est;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/gnu/GNUObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/gnu/GNUObjectIdentifiers.java
      index 0f82da0b00..1ca3b61ef5 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/gnu/GNUObjectIdentifiers.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/gnu/GNUObjectIdentifiers.java
      @@ -65,7 +65,7 @@ public interface GNUObjectIdentifiers
            */
           ASN1ObjectIdentifier Serpent_192_ECB = new ASN1ObjectIdentifier("1.3.6.1.4.1.11591.13.2.21"); // Serpent-192-ECB
           /**
      -     * 1.3.6.1.4.1.11591.13.2.22 -- Serpent-192-CCB
      +     * 1.3.6.1.4.1.11591.13.2.22 -- Serpent-192-CBC
            */
           ASN1ObjectIdentifier Serpent_192_CBC = new ASN1ObjectIdentifier("1.3.6.1.4.1.11591.13.2.22"); // Serpent-192-CBC
           /**
      @@ -107,5 +107,11 @@ public interface GNUObjectIdentifiers
            */
           ASN1ObjectIdentifier ellipticCurve = new ASN1ObjectIdentifier("1.3.6.1.4.1.11591.15");
       
      +    /**
      +     * Ed25519Legacy for use with EdDSALegacy.
      +     *
      +     * @see 
      +     * RFC9580 - ECC Curves for OpenPGP
      +     */
           ASN1ObjectIdentifier Ed25519 = ellipticCurve.branch("1");
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/iana/IANAObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/iana/IANAObjectIdentifiers.java
      index 5bfdbab891..3be353ca22 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/iana/IANAObjectIdentifiers.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/iana/IANAObjectIdentifiers.java
      @@ -37,9 +37,8 @@ public interface IANAObjectIdentifiers
           /** IANA security nametypes;  1.3.6.1.5.6 */
           static final ASN1ObjectIdentifier    security_nametypes   = security.branch("6");
       
      -    /** PKIX base OID:            1.3.6.1.5.6.6 */
      -    static final ASN1ObjectIdentifier    pkix                 = security_mechanisms.branch("6");
      -
      +    /** PKIX base OID:            1.3.6.1.5.5.7 */
      +    static final ASN1ObjectIdentifier    pkix                 = security_mechanisms.branch("7");
       
           /** IPSEC base OID:                        1.3.6.1.5.5.8 */
           static final ASN1ObjectIdentifier    ipsec                = security_mechanisms.branch("8");
      diff --git a/util/src/main/java/org/bouncycastle/asn1/icao/CscaMasterList.java b/util/src/main/java/org/bouncycastle/asn1/icao/CscaMasterList.java
      index 98ba135f27..50f8351f36 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/icao/CscaMasterList.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/icao/CscaMasterList.java
      @@ -1,6 +1,5 @@
       package org.bouncycastle.asn1.icao;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Integer;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1Primitive;
      @@ -98,11 +97,6 @@ private Certificate[] copyCertList(Certificate[] orig)
       
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector seq = new ASN1EncodableVector(2);
      -
      -        seq.add(version);
      -        seq.add(new DERSet(certList));
      -
      -        return new DERSequence(seq);
      +        return new DERSequence(version, new DERSet(certList));
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/icao/DataGroupHash.java b/util/src/main/java/org/bouncycastle/asn1/icao/DataGroupHash.java
      index 5464d0808a..ae86174364 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/icao/DataGroupHash.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/icao/DataGroupHash.java
      @@ -2,7 +2,6 @@
       
       import java.util.Enumeration;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Integer;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1OctetString;
      @@ -88,10 +87,6 @@ public ASN1OctetString getDataGroupHashValue()
           
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector seq = new ASN1EncodableVector(2);
      -        seq.add(dataGroupNumber);
      -        seq.add(dataGroupHashValue);  
      -
      -        return new DERSequence(seq);
      +        return new DERSequence(dataGroupNumber, dataGroupHashValue);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/icao/LDSVersionInfo.java b/util/src/main/java/org/bouncycastle/asn1/icao/LDSVersionInfo.java
      index 1cb47b9955..3df560c42f 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/icao/LDSVersionInfo.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/icao/LDSVersionInfo.java
      @@ -1,6 +1,5 @@
       package org.bouncycastle.asn1.icao;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1Primitive;
       import org.bouncycastle.asn1.ASN1PrintableString;
      @@ -66,11 +65,6 @@ public String getUnicodeVersion()
            */
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -
      -        v.add(ldsVersion);
      -        v.add(unicodeVersion);
      -
      -        return new DERSequence(v);
      +        return new DERSequence(ldsVersion, unicodeVersion);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/icao/package-info.java b/util/src/main/java/org/bouncycastle/asn1/icao/package-info.java
      new file mode 100644
      index 0000000000..b6464ad138
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/icao/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * ICAO ASN.1 classes for electronic passport.
      + */
      +package org.bouncycastle.asn1.icao;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/CertHash.java b/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/CertHash.java
      index 3e6b83c703..e625f15fab 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/CertHash.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/CertHash.java
      @@ -1,6 +1,5 @@
       package org.bouncycastle.asn1.isismtt.ocsp;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1Primitive;
       import org.bouncycastle.asn1.ASN1Sequence;
      @@ -113,9 +112,6 @@ public byte[] getCertificateHash()
            */
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector vec = new ASN1EncodableVector(2);
      -        vec.add(hashAlgorithm);
      -        vec.add(new DEROctetString(certificateHash));
      -        return new DERSequence(vec);
      +        return new DERSequence(hashAlgorithm, new DEROctetString(certificateHash));
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/package-info.java b/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/package-info.java
      new file mode 100644
      index 0000000000..4b5743c928
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/isismtt/ocsp/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes for the ISIS-MTT profile for OCSP.
      + */
      +package org.bouncycastle.asn1.isismtt.ocsp;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/isismtt/package-info.java b/util/src/main/java/org/bouncycastle/asn1/isismtt/package-info.java
      new file mode 100644
      index 0000000000..48da9b6b82
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/isismtt/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes for the ISIS-MTT Project.
      + */
      +package org.bouncycastle.asn1.isismtt;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/DeclarationOfMajority.java b/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/DeclarationOfMajority.java
      index 7530244339..f7eca1511b 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/DeclarationOfMajority.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/DeclarationOfMajority.java
      @@ -2,7 +2,6 @@
       
       import org.bouncycastle.asn1.ASN1Boolean;
       import org.bouncycastle.asn1.ASN1Choice;
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1GeneralizedTime;
       import org.bouncycastle.asn1.ASN1Integer;
       import org.bouncycastle.asn1.ASN1Object;
      @@ -57,16 +56,13 @@ public DeclarationOfMajority(boolean fullAge, String country)
       
               if (fullAge)
               {
      -            declaration = new DERTaggedObject(false, 1, new DERSequence(new DERPrintableString(country, true)));
      +            declaration = new DERTaggedObject(false, 1,
      +                new DERSequence(new DERPrintableString(country, true)));
               }
               else
               {
      -            ASN1EncodableVector v = new ASN1EncodableVector(2);
      -
      -            v.add(ASN1Boolean.FALSE);
      -            v.add(new DERPrintableString(country, true));
      -
      -            declaration = new DERTaggedObject(false, 1, new DERSequence(v));
      +            declaration = new DERTaggedObject(false, 1,
      +                new DERSequence(ASN1Boolean.FALSE, new DERPrintableString(country, true)));
               }
           }
       
      diff --git a/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/package-info.java b/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/package-info.java
      new file mode 100644
      index 0000000000..8d22278319
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/isismtt/x509/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes for the ISIS-MTT X.509 Certificate Extensions.
      + */
      +package org.bouncycastle.asn1.isismtt.x509;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/iso/package-info.java b/util/src/main/java/org/bouncycastle/asn1/iso/package-info.java
      new file mode 100644
      index 0000000000..0ca65bced4
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/iso/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes for various ISO Standards.
      + */
      +package org.bouncycastle.asn1.iso;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/kisa/KISAObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/kisa/KISAObjectIdentifiers.java
      index a4611333f0..1cdb668bba 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/kisa/KISAObjectIdentifiers.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/kisa/KISAObjectIdentifiers.java
      @@ -25,7 +25,4 @@ public interface KISAObjectIdentifiers
       
           /** RFC 4010: id-npki-app-cmsSeed-wrap; OID 1.2.410.200004.7.1.1.1 */
           static final ASN1ObjectIdentifier id_npki_app_cmsSeed_wrap = new ASN1ObjectIdentifier("1.2.410.200004.7.1.1.1");
      -
      -    /** RFC 4010: SeedEncryptionAlgorithmInCMS; OID 1.2.840.113549.1.9.16.0.24 */
      -    static final ASN1ObjectIdentifier id_mod_cms_seed = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.0.24");
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/kisa/package-info.java b/util/src/main/java/org/bouncycastle/asn1/kisa/package-info.java
      new file mode 100644
      index 0000000000..df74df651f
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/kisa/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes for the Korea Information Security Agency (KISA) standard - SEED algorithm.
      + */
      +package org.bouncycastle.asn1.kisa;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/microsoft/package-info.java b/util/src/main/java/org/bouncycastle/asn1/microsoft/package-info.java
      new file mode 100644
      index 0000000000..cd8cbaf36a
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/microsoft/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support for Microsoft specific ASN.1 classes and object identifiers.
      + */
      +package org.bouncycastle.asn1.microsoft;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/misc/CAST5CBCParameters.java b/util/src/main/java/org/bouncycastle/asn1/misc/CAST5CBCParameters.java
      index 5e00980fa2..1137eda46e 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/misc/CAST5CBCParameters.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/misc/CAST5CBCParameters.java
      @@ -1,6 +1,5 @@
       package org.bouncycastle.asn1.misc;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Integer;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1OctetString;
      @@ -69,11 +68,6 @@ public int getKeyLength()
            */
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -
      -        v.add(iv);
      -        v.add(keyLength);
      -
      -        return new DERSequence(v);
      +        return new DERSequence(iv, keyLength);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/misc/MiscObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/misc/MiscObjectIdentifiers.java
      index 8608d2c0a7..5dc5517b54 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/misc/MiscObjectIdentifiers.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/misc/MiscObjectIdentifiers.java
      @@ -170,25 +170,34 @@ public interface MiscObjectIdentifiers
           // Composite signature related OIDs. Based https://www.ietf.org/archive/id/draft-ounsworth-pq-composite-sigs-13.html
           // The current OIDs are EXPERIMENTAL and are going to change.
           ASN1ObjectIdentifier id_composite_signatures = new ASN1ObjectIdentifier("2.16.840.1.114027.80.8.1");
      -    ASN1ObjectIdentifier id_MLDSA44_RSA2048_PSS_SHA256 = id_composite_signatures.branch("1");
      -    ASN1ObjectIdentifier id_MLDSA44_RSA2048_PKCS15_SHA256 = id_composite_signatures.branch("2");
      -    ASN1ObjectIdentifier id_MLDSA44_Ed25519_SHA512 = id_composite_signatures.branch("3");
      -    ASN1ObjectIdentifier id_MLDSA44_ECDSA_P256_SHA256 = id_composite_signatures.branch("4");
      -    ASN1ObjectIdentifier id_MLDSA44_ECDSA_brainpoolP256r1_SHA256 = id_composite_signatures.branch("5");
      -    ASN1ObjectIdentifier id_MLDSA65_RSA3072_PSS_SHA512 = id_composite_signatures.branch("6");
      -    ASN1ObjectIdentifier id_MLDSA65_RSA3072_PKCS15_SHA512 = id_composite_signatures.branch("7");
      -    ASN1ObjectIdentifier id_MLDSA65_ECDSA_P256_SHA512 = id_composite_signatures.branch("8");
      -    ASN1ObjectIdentifier id_MLDSA65_ECDSA_brainpoolP256r1_SHA512 = id_composite_signatures.branch("9");
      -    ASN1ObjectIdentifier id_MLDSA65_Ed25519_SHA512 = id_composite_signatures.branch("10");
      -    ASN1ObjectIdentifier id_MLDSA87_ECDSA_P384_SHA512 = id_composite_signatures.branch("11");
      -    ASN1ObjectIdentifier id_MLDSA87_ECDSA_brainpoolP384r1_SHA512 = id_composite_signatures.branch("12");
      -    ASN1ObjectIdentifier id_MLDSA87_Ed448_SHA512 = id_composite_signatures.branch("13");
      -
      -    // Falcon-based composites below were removed from the IETF draft in version 13 and are expected to be included in a later/separate standard.
      -    // Most likely due to the fact that the Falcon (FN-DSA) NIST standard is going to be released after the Dilithium (ML-DSA) standard.
      -    // However, we still leave their implementation for experimental usage.
      -    ASN1ObjectIdentifier id_Falcon512_ECDSA_P256_SHA256 = id_composite_signatures.branch("14");
      -    ASN1ObjectIdentifier id_Falcon512_ECDSA_brainpoolP256r1_SHA256 = id_composite_signatures.branch("15");
      -    ASN1ObjectIdentifier id_Falcon512_Ed25519_SHA512 = id_composite_signatures.branch("16");
      +    ASN1ObjectIdentifier id_MLDSA44_RSA2048_PSS_SHA256 = id_composite_signatures.branch("21");
      +    ASN1ObjectIdentifier id_MLDSA44_RSA2048_PKCS15_SHA256 = id_composite_signatures.branch("22");
      +    ASN1ObjectIdentifier id_MLDSA44_Ed25519_SHA512 = id_composite_signatures.branch("23");
      +    ASN1ObjectIdentifier id_MLDSA44_ECDSA_P256_SHA256 = id_composite_signatures.branch("24");
      +    ASN1ObjectIdentifier id_MLDSA65_RSA3072_PSS_SHA256 = id_composite_signatures.branch("26");
      +    ASN1ObjectIdentifier id_MLDSA65_RSA3072_PKCS15_SHA256 = id_composite_signatures.branch("27");
      +    ASN1ObjectIdentifier id_MLDSA65_RSA4096_PSS_SHA384 = id_composite_signatures.branch("34");
      +    ASN1ObjectIdentifier id_MLDSA65_RSA4096_PKCS15_SHA384 = id_composite_signatures.branch("35");
      +    ASN1ObjectIdentifier id_MLDSA65_ECDSA_P384_SHA384 = id_composite_signatures.branch("28");
      +    ASN1ObjectIdentifier id_MLDSA65_ECDSA_brainpoolP256r1_SHA256 = id_composite_signatures.branch("29");
      +    ASN1ObjectIdentifier id_MLDSA65_Ed25519_SHA512 = id_composite_signatures.branch("30");
      +    ASN1ObjectIdentifier id_MLDSA87_ECDSA_P384_SHA384 = id_composite_signatures.branch("31");
      +    ASN1ObjectIdentifier id_MLDSA87_ECDSA_brainpoolP384r1_SHA384 = id_composite_signatures.branch("32");
      +    ASN1ObjectIdentifier id_MLDSA87_Ed448_SHA512 = id_composite_signatures.branch("33");
      +
      +    ASN1ObjectIdentifier id_HashMLDSA44_RSA2048_PSS_SHA256 = id_composite_signatures.branch("40");
      +    ASN1ObjectIdentifier id_HashMLDSA44_RSA2048_PKCS15_SHA256 = id_composite_signatures.branch("41");
      +    ASN1ObjectIdentifier id_HashMLDSA44_Ed25519_SHA512 = id_composite_signatures.branch("42");
      +    ASN1ObjectIdentifier id_HashMLDSA44_ECDSA_P256_SHA256 = id_composite_signatures.branch("43");
      +    ASN1ObjectIdentifier id_HashMLDSA65_RSA3072_PSS_SHA512 = id_composite_signatures.branch("44");
      +    ASN1ObjectIdentifier id_HashMLDSA65_RSA3072_PKCS15_SHA512 = id_composite_signatures.branch("45");
      +    ASN1ObjectIdentifier id_HashMLDSA65_RSA4096_PSS_SHA512 = id_composite_signatures.branch("46");
      +    ASN1ObjectIdentifier id_HashMLDSA65_RSA4096_PKCS15_SHA512 = id_composite_signatures.branch("47");
      +    ASN1ObjectIdentifier id_HashMLDSA65_ECDSA_P384_SHA512 = id_composite_signatures.branch("48");
      +    ASN1ObjectIdentifier id_HashMLDSA65_ECDSA_brainpoolP256r1_SHA512 = id_composite_signatures.branch("49");
      +    ASN1ObjectIdentifier id_HashMLDSA65_Ed25519_SHA512 = id_composite_signatures.branch("50");
      +    ASN1ObjectIdentifier id_HashMLDSA87_ECDSA_P384_SHA512 = id_composite_signatures.branch("51");
      +    ASN1ObjectIdentifier id_HashMLDSA87_ECDSA_brainpoolP384r1_SHA512 = id_composite_signatures.branch("52");
      +    ASN1ObjectIdentifier id_HashMLDSA87_Ed448_SHA512 = id_composite_signatures.branch("53");
           // COMPOSITE SIGNATURES END
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/misc/package-info.java b/util/src/main/java/org/bouncycastle/asn1/misc/package-info.java
      new file mode 100644
      index 0000000000..16395dc644
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/misc/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Miscellaneous object identifiers and objects.
      + */
      +package org.bouncycastle.asn1.misc;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/mod/ModObjectIdentifiers.java b/util/src/main/java/org/bouncycastle/asn1/mod/ModObjectIdentifiers.java
      new file mode 100644
      index 0000000000..0b58e1528f
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/mod/ModObjectIdentifiers.java
      @@ -0,0 +1,22 @@
      +package org.bouncycastle.asn1.mod;
      +
      +import org.bouncycastle.asn1.ASN1ObjectIdentifier;
      +
      +public interface ModObjectIdentifiers
      +{
      +    //TODO: add more from RFC 6268, RFC 5911
      +
      +    //   id_mod OBJECT IDENTIFIER  ::= { iso(1) identified_organization(3)
      +    //       dod(6) internet(1) security(5) mechanisms(5) pkix(7) mod(0) }
      +    ASN1ObjectIdentifier id_mod = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.0");
      +
      +    /**
      +     * PUBLIC-KEY, SIGNATURE-ALGORITHM, SMIME-CAPS
      +     *      FROM AlgorithmInformation-2009  -- RFC 5911 [CMSASN1]
      +     *      { iso(1) identified-organization(3) dod(6) internet(1)
      +     *      security(5) mechanisms(5) pkix(7) id-mod(0)
      +     *      id-mod-algorithmInformation-02(58) } ;
      +     *      1.3.6.1.5.5.7.0.58
      +     */
      +    ASN1ObjectIdentifier id_mod_algorithmInformation_02 = id_mod.branch("58");
      +}
      diff --git a/util/src/main/java/org/bouncycastle/asn1/nsri/package-info.java b/util/src/main/java/org/bouncycastle/asn1/nsri/package-info.java
      new file mode 100644
      index 0000000000..359700589a
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/nsri/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes algorithms from the Korean National Security Research Institute.
      + */
      +package org.bouncycastle.asn1.nsri;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/ntt/package-info.java b/util/src/main/java/org/bouncycastle/asn1/ntt/package-info.java
      new file mode 100644
      index 0000000000..db2651db1d
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/ntt/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * ASN.1 classes relevant to the standards produced by Nippon Telegraph and Telephone.
      + */
      +package org.bouncycastle.asn1.ntt;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/oiw/ElGamalParameter.java b/util/src/main/java/org/bouncycastle/asn1/oiw/ElGamalParameter.java
      index c60546c1b5..efd538f6e3 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/oiw/ElGamalParameter.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/oiw/ElGamalParameter.java
      @@ -3,7 +3,6 @@
       import java.math.BigInteger;
       import java.util.Enumeration;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Integer;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1Primitive;
      @@ -58,11 +57,6 @@ public BigInteger getG()
       
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -
      -        v.add(p);
      -        v.add(g);
      -
      -        return new DERSequence(v);
      +        return new DERSequence(p, g);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/oiw/package-info.java b/util/src/main/java/org/bouncycastle/asn1/oiw/package-info.java
      new file mode 100644
      index 0000000000..5dda424302
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/oiw/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Objects and OID for the support of ISO OIW.
      + */
      +package org.bouncycastle.asn1.oiw;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/package-info.java b/util/src/main/java/org/bouncycastle/asn1/package-info.java
      new file mode 100644
      index 0000000000..00a57d59e7
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * A library for parsing and writing ASN.1 objects. Support is provided for DER and BER encoding.
      + */
      +package org.bouncycastle.asn1;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/rosstandart/package-info.java b/util/src/main/java/org/bouncycastle/asn1/rosstandart/package-info.java
      new file mode 100644
      index 0000000000..a31182824e
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/rosstandart/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes algorithms from the Russian Federal Agency on Technical Regulating and Metrology - Rosstandart.
      + */
      +package org.bouncycastle.asn1.rosstandart;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/smime/SMIMECapabilityVector.java b/util/src/main/java/org/bouncycastle/asn1/smime/SMIMECapabilityVector.java
      index 5065d1f081..673a745e4e 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/smime/SMIMECapabilityVector.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/smime/SMIMECapabilityVector.java
      @@ -23,24 +23,14 @@ public void addCapability(
               ASN1ObjectIdentifier capability,
               int                 value)
           {
      -        ASN1EncodableVector  v = new ASN1EncodableVector(2);
      -
      -        v.add(capability);
      -        v.add(new ASN1Integer(value));
      -
      -        capabilities.add(new DERSequence(v));
      +        capabilities.add(new DERSequence(capability, new ASN1Integer(value)));
           }
       
           public void addCapability(
               ASN1ObjectIdentifier capability,
               ASN1Encodable params)
           {
      -        ASN1EncodableVector  v = new ASN1EncodableVector(2);
      -
      -        v.add(capability);
      -        v.add(params);
      -
      -        capabilities.add(new DERSequence(v));
      +        capabilities.add(new DERSequence(capability, params));
           }
       
           public ASN1EncodableVector toASN1EncodableVector()
      diff --git a/util/src/main/java/org/bouncycastle/asn1/smime/package-info.java b/util/src/main/java/org/bouncycastle/asn1/smime/package-info.java
      new file mode 100644
      index 0000000000..7189163e2d
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/smime/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes useful for encoding and supporting S/MIME.
      + */
      +package org.bouncycastle.asn1.smime;
      diff --git a/util/src/main/java/org/bouncycastle/asn1/tsp/EncryptionInfo.java b/util/src/main/java/org/bouncycastle/asn1/tsp/EncryptionInfo.java
      index 0157084acf..27275873b9 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/tsp/EncryptionInfo.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/tsp/EncryptionInfo.java
      @@ -1,7 +1,6 @@
       package org.bouncycastle.asn1.tsp;
       
       import org.bouncycastle.asn1.ASN1Encodable;
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1ObjectIdentifier;
       import org.bouncycastle.asn1.ASN1Primitive;
      @@ -105,10 +104,6 @@ public ASN1Encodable getEncryptionInfoValue()
       
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -        v.add(encryptionInfoType);
      -        v.add(encryptionInfoValue);
      -
      -        return new DLSequence(v);
      +        return new DLSequence(encryptionInfoType, encryptionInfoValue);
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/tsp/MessageImprint.java b/util/src/main/java/org/bouncycastle/asn1/tsp/MessageImprint.java
      index c6dc0b4bb9..56b9e09c68 100644
      --- a/util/src/main/java/org/bouncycastle/asn1/tsp/MessageImprint.java
      +++ b/util/src/main/java/org/bouncycastle/asn1/tsp/MessageImprint.java
      @@ -1,6 +1,5 @@
       package org.bouncycastle.asn1.tsp;
       
      -import org.bouncycastle.asn1.ASN1EncodableVector;
       import org.bouncycastle.asn1.ASN1Object;
       import org.bouncycastle.asn1.ASN1OctetString;
       import org.bouncycastle.asn1.ASN1Primitive;
      @@ -63,12 +62,17 @@ public AlgorithmIdentifier getHashAlgorithm()
           {
               return hashAlgorithm;
           }
      -    
      +
           public byte[] getHashedMessage()
           {
               return Arrays.clone(hashedMessage);
           }
      -    
      +
      +    public int getHashedMessageLength()
      +    {
      +        return hashedMessage.length;
      +    }
      +
           /**
            * 
            *    MessageImprint ::= SEQUENCE  {
      @@ -78,11 +82,6 @@ public byte[] getHashedMessage()
            */
           public ASN1Primitive toASN1Primitive()
           {
      -        ASN1EncodableVector v = new ASN1EncodableVector(2);
      -
      -        v.add(hashAlgorithm);
      -        v.add(new DEROctetString(hashedMessage));
      -
      -        return new DERSequence(v);
      +        return new DERSequence(hashAlgorithm, new DEROctetString(hashedMessage));
           }
       }
      diff --git a/util/src/main/java/org/bouncycastle/asn1/tsp/package-info.java b/util/src/main/java/org/bouncycastle/asn1/tsp/package-info.java
      new file mode 100644
      index 0000000000..2df71cdbdb
      --- /dev/null
      +++ b/util/src/main/java/org/bouncycastle/asn1/tsp/package-info.java
      @@ -0,0 +1,4 @@
      +/**
      + * Support classes useful for encoding and supporting Time Stamp Protocol as described RFC 3161.
      + */
      +package org.bouncycastle.asn1.tsp;
      diff --git a/util/src/main/java/org/bouncycastle/oer/its/template/etsi102941/EtsiTs102941TypesAuthorization.java b/util/src/main/java/org/bouncycastle/oer/its/template/etsi102941/EtsiTs102941TypesAuthorization.java
      index 79cdaf59aa..099d73b15a 100644
      --- a/util/src/main/java/org/bouncycastle/oer/its/template/etsi102941/EtsiTs102941TypesAuthorization.java
      +++ b/util/src/main/java/org/bouncycastle/oer/its/template/etsi102941/EtsiTs102941TypesAuthorization.java
      @@ -130,7 +130,8 @@ public class EtsiTs102941TypesAuthorization
               EtsiTs102941BaseTypes.PublicKeys.label("publicKeys"),
               OERDefinition.octets(32).label("hmacKey"),
               SharedAtRequest.label("sharedAtRequest"),
      -        EtsiTs102941BaseTypes.EcSignature.label("ecSignature")
      +        EtsiTs102941BaseTypes.EcSignature.label("ecSignature"),
      +        OERDefinition.extension()
           ).typeName("InnerAtRequest");
       
       
      diff --git a/util/src/main/java/org/bouncycastle/oer/its/template/ieee1609dot2/IEEE1609dot2.java b/util/src/main/java/org/bouncycastle/oer/its/template/ieee1609dot2/IEEE1609dot2.java
      index fc36d74429..37bf6add62 100644
      --- a/util/src/main/java/org/bouncycastle/oer/its/template/ieee1609dot2/IEEE1609dot2.java
      +++ b/util/src/main/java/org/bouncycastle/oer/its/template/ieee1609dot2/IEEE1609dot2.java
      @@ -259,7 +259,8 @@ public Element result(SwitchIndexer indexer)
            * EndEntityType ::= BIT STRING {app (0), enrol (1) } (SIZE (8))
            */
           public static final OERDefinition.Builder EndEntityType =
      -        OERDefinition.bitString(8).defaultValue(new DERBitString(new byte[]{0}, 0))
      +        OERDefinition.bitString(8)
      +                .defaultValue(new DERBitString(org.bouncycastle.oer.its.ieee1609dot2.EndEntityType.app))
                   .typeName("EndEntityType");
       
           /**
      diff --git a/util/src/test/java/org/bouncycastle/asn1/cms/test/KEMRecipientInfoTest.java b/util/src/test/java/org/bouncycastle/asn1/cms/test/KEMRecipientInfoTest.java
      new file mode 100644
      index 0000000000..acb796978b
      --- /dev/null
      +++ b/util/src/test/java/org/bouncycastle/asn1/cms/test/KEMRecipientInfoTest.java
      @@ -0,0 +1,122 @@
      +package org.bouncycastle.asn1.cms.test;
      +
      +import junit.framework.TestCase;
      +import org.bouncycastle.asn1.ASN1Encodable;
      +import org.bouncycastle.asn1.ASN1Integer;
      +import org.bouncycastle.asn1.ASN1Primitive;
      +import org.bouncycastle.asn1.DEROctetString;
      +import org.bouncycastle.asn1.DERSequence;
      +import org.bouncycastle.asn1.cms.KEMRecipientInfo;
      +import org.bouncycastle.asn1.cms.RecipientIdentifier;
      +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
      +import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
      +import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
      +import org.bouncycastle.util.encoders.Base64;
      +
      +public class KEMRecipientInfoTest
      +    extends TestCase
      +{
      +    private static byte[] outOfRangeEnc = Base64.decode("MDoCAQCAADALBglghkgBZQMEBAEEADAMBgorgQUQhkgJLAECAgMKrmCgAgQAMAsGCWCGSAFlAwQBMAQA");
      +
      +    public void testOutOfRange()
      +        throws Exception
      +    {
      +        try
      +        {
      +            new KEMRecipientInfo(
      +                new RecipientIdentifier(new DEROctetString(new byte[0])),
      +                new AlgorithmIdentifier(NISTObjectIdentifiers.id_alg_ml_kem_512),
      +                new DEROctetString(new byte[0]),
      +                new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3),
      +                new ASN1Integer(700000), new DEROctetString(new byte[0]),
      +                new AlgorithmIdentifier(NISTObjectIdentifiers.id_aes256_wrap_pad),
      +                new DEROctetString(new byte[0]));
      +            fail("no exception");
      +        }
      +        catch (IllegalArgumentException e)
      +        {
      +            assertEquals("kekLength must be <= 65535", e.getMessage());
      +        }
      +
      +        try
      +        {
      +            KEMRecipientInfo.getInstance(ASN1Primitive.fromByteArray(outOfRangeEnc));
      +            fail("no exception");
      +        }
      +        catch (IllegalArgumentException e)
      +        {
      +            assertEquals("kekLength must be <= 65535", e.getMessage());
      +        }
      +    }
      +
      +    public void testNullWrap()
      +        throws Exception
      +    {
      +        try
      +        {
      +            new KEMRecipientInfo(
      +                new RecipientIdentifier(new DEROctetString(new byte[0])),
      +                new AlgorithmIdentifier(NISTObjectIdentifiers.id_alg_ml_kem_512),
      +                new DEROctetString(new byte[0]),
      +                new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3),
      +                new ASN1Integer(7000), new DEROctetString(new byte[0]),
      +                null,
      +                new DEROctetString(new byte[0]));
      +            fail("no exception");
      +        }
      +        catch (NullPointerException e)
      +        {
      +            assertEquals("wrap cannot be null", e.getMessage());
      +        }
      +    }
      +
      +    public void testNullKem()
      +        throws Exception
      +    {
      +        try
      +        {
      +            new KEMRecipientInfo(
      +                new RecipientIdentifier(new DEROctetString(new byte[0])),
      +                null,
      +                new DEROctetString(new byte[0]),
      +                new AlgorithmIdentifier(X9ObjectIdentifiers.id_kdf_kdf3),
      +                new ASN1Integer(7000), new DEROctetString(new byte[0]),
      +                new AlgorithmIdentifier(NISTObjectIdentifiers.id_aes256_wrap_pad),
      +                new DEROctetString(new byte[0]));
      +            fail("no exception");
      +        }
      +        catch (NullPointerException e)
      +        {
      +            assertEquals("kem cannot be null", e.getMessage());
      +        }
      +    }
      +
      +    public void testSequenceSize()
      +        throws Exception
      +    {
      +        try
      +        {
      +            KEMRecipientInfo.getInstance(new DERSequence(new RecipientIdentifier(new DEROctetString(new byte[0]))));
      +            fail("no exception");
      +        }
      +        catch (IllegalArgumentException e)
      +        {
      +            assertEquals("bad sequence size: 1", e.getMessage());
      +        }
      +
      +        try
      +        {
      +            ASN1Encodable[] elements = new ASN1Encodable[10];
      +            for (int i = 0; i != elements.length; i++)
      +            {
      +                elements[i] = new ASN1Integer(1);
      +            }
      +            KEMRecipientInfo.getInstance(new DERSequence(elements));
      +            fail("no exception");
      +        }
      +        catch (IllegalArgumentException e)
      +        {
      +            assertEquals("bad sequence size: 10", e.getMessage());
      +        }
      +    }
      +}
      diff --git a/util/src/test/java/org/bouncycastle/asn1/misc/test/CMPUpdates16Test.java b/util/src/test/java/org/bouncycastle/asn1/misc/test/CMPUpdates16Test.java
      index 4e760e1792..7e1ebafeb0 100644
      --- a/util/src/test/java/org/bouncycastle/asn1/misc/test/CMPUpdates16Test.java
      +++ b/util/src/test/java/org/bouncycastle/asn1/misc/test/CMPUpdates16Test.java
      @@ -61,7 +61,7 @@ public void testCRLSource()
               }
               catch (IllegalArgumentException ilex)
               {
      -            assertEquals("unknown tag 3", ilex.getMessage());
      +            assertEquals("unknown tag [CONTEXT 3]", ilex.getMessage());
               }
       
               // Check that both values are not set at construction