diff --git a/.github/workflows/mvn.yml b/.github/workflows/mvn.yml
index f0ad74c..e76d9ca 100644
--- a/.github/workflows/mvn.yml
+++ b/.github/workflows/mvn.yml
@@ -6,35 +6,38 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
with:
submodules: true
- name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v1
+ uses: docker/setup-buildx-action@v3
+ - name: Install socat tool
+ run: |
+ sudo apt-get update
+ sudo apt-get install socat
- name: Cache Docker layers
- uses: actions/cache@v2
+ uses: actions/cache@v4
with:
path: ./parsec-docker-test-image/parsec_docker_cache
key: ${{ runner.os }}-parsec_docker_cache-${{ github.sha }}
restore-keys: |
${{ runner.os }}-parsec_docker_cache-
- name: Set up JDK 16
- uses: actions/setup-java@v2
+ uses: actions/setup-java@v4
with:
- java-version: '16'
- distribution: 'zulu'
+ java-version: "16"
+ distribution: "zulu"
architecture: x64
cache: maven
- name: Build with Maven
# still needs work to get tests running on java 16
run: ./mvnw --batch-mode clean verify -DskipTests=true
- name: Set up JDK 8
- uses: actions/setup-java@v2
+ uses: actions/setup-java@v4
with:
- java-version: '8'
- distribution: 'zulu'
+ java-version: "8"
+ distribution: "zulu"
architecture: x64
cache: maven
- name: Build with Maven
run: ./mvnw --batch-mode clean verify
-
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..f5eb29b
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,4 @@
+{
+ "java.configuration.updateBuildConfiguration": "automatic",
+ "maven.view": "hierarchical"
+}
diff --git a/README.md b/README.md
index 3f5f08d..3876541 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
This repository contains a Java Client and a [JCA provider](https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html) for Parsec. The client exposes the [PSA Crypto API](https://github.com/ARMmbed/mbed-crypto/blob/psa-crypto-api/docs/PSA_Cryptography_API_Specification.pdf) to Java Applications and the JCA Provider allows existing applications that employ JCA to switch to Parsec.
-*Note*: this client is at an early stage of development and not yet ready for production use. We welcome contributions!
+_Note_: this client is at an early stage of development and not yet ready for production use. We welcome contributions!
## In this repository
@@ -12,16 +12,31 @@ The repository contains the following packages:
- parsec-jca-java: JCA Provider
- parsec-interface-java: Private wrapper for protobuf classes and socket communication
- parsec-protobuf-java: Java Protobuf classes (generated)
-- parsec-testcontainers: Collection of Docker test containers for development & testing
+- parsec-testcontainers: Collection of Docker test containers for development & testing
# How to use this library
+
TODO
# How to develop the Parsec Java Client
-TODO
+
+Check out this repo's submodules:
+
+```sh
+git submodule update --init --recursive
+```
+
+You can use `act` to run the github action locally. On OSX, you need to set the container architecture, and for testcontainers to work, you may need to set the env var `TESTCONTAINERS_HOST_OVERRIDE`.
+
+Example CLI input:
+
+```sh
+act --container-architecture linux/amd64 --env TESTCONTAINERS_HOST_OVERRIDE=`ipconfig getifaddr en0`
+```
# Example Implementations
-There are a number of example implementations of both the basic java client and JCA provider along with a demo (separate repository)
+
+There are a number of example implementations of both the basic java client and JCA provider along with a demo (separate repository)
Both the tests and workshop demo cover the basic functionality of the current implementation:
- Parsec JCA Tests [**Link**](/parsec-jca-test)
@@ -34,10 +49,8 @@ The software is provided under Apache-2.0. Contributions to this project are acc
## Contributing
-We welcome contributing, both in the use of this client library and programming,extending of this library code base.
+We welcome contributing, both in the use of this client library and programming,extending of this library code base.
Please check the [**Contribution Guidelines**](https://parallaxsecond.github.io/parsec-book/contributing/index.html)
to know more about the contribution process.
-*Copyright 2021 Contributors to the Parsec project.*
-
-
+_Copyright 2021 Contributors to the Parsec project._
diff --git a/build_demo.sh b/build_demo.sh
index 6dbda81..a0d9ea8 100755
--- a/build_demo.sh
+++ b/build_demo.sh
@@ -16,58 +16,57 @@ function dirty_build_on_new_comits() {
awslabs/aws-crt-java \
aws/aws-iot-device-sdk-java-v2 \
revaultch/aws-greengrass-nucleus; do
- curl -S https://api.github.com/repos/${repo}/commits/key-op-prototype
- done | ${md5_cmd} | cut -d" " -f1 > greengrass_demo/dirty_repo.txt
+ curl -S https://api.github.com/repos/${repo}/commits/key-op-prototype
+ done | ${md5_cmd} | cut -d" " -f1 >greengrass_demo/dirty_repo.txt
touch -t 190001010000 greengrass_demo/dirty_repo.txt
export DIRTY_TS=$(cat greengrass_demo/dirty_repo.txt)
}
function build_greengrass_patched() {
-pushd examples/greengrass/parsec-greengrass-run-config/docker/
-docker build . \
- --build-arg BUILD_TS=${DIRTY_TS} \
- --tag parallaxsecond/greengrass_patched:latest \
- --progress plain
-popd
+ pushd examples/greengrass/parsec-greengrass-run-config/docker/
+ docker build . \
+ --build-arg BUILD_TS=${DIRTY_TS} \
+ --tag parallaxsecond/greengrass_patched:latest \
+ --progress plain
+ popd
}
function copy_deps_from_greengrass_patched_to_local() {
docker run -v ~/.m2/repository:/host_m2_repository parallaxsecond/greengrass_patched:latest \
- /bin/bash -c "cp -r ~/.m2/repository/* /host_m2_repository"
+ /bin/bash -c "cp -r ~/.m2/repository/* /host_m2_repository"
}
function build_parsec_containers() {
-pushd ./parsec-testcontainers/
-./build.sh
-popd
+ pushd ./parsec-testcontainers/
+ ./build.sh
+ popd
}
function build_greengrass_with_provider() {
- docker build . -f greengrass_demo/Dockerfile --tag parallaxsecond/greengrass_demo:latest --progress plain
+ docker build . -f greengrass_demo/Dockerfile --tag parallaxsecond/greengrass_demo:latest --progress plain
}
function parsec_run() {
- docker rm -f parsec_docker_run 2> /dev/null
- docker run -d --name parsec_docker_run \
- -ti \
- -v GG_PARSEC_STORE:/var/lib/parsec/mappings \
- -v GG_PARSEC_SOCK:/run/parsec \
- parallaxsecond/parsec:0.8.1
+ docker rm -f parsec_docker_run 2>/dev/null
+ docker run -d --name parsec_docker_run \
+ -ti \
+ -v GG_PARSEC_STORE:/parsec/quickstart/mappings\ -v GG_PARSEC_SOCK:/run/parsec \
+ parallaxsecond/parsec:latest
}
function gg_run() {
- docker rm -f "${1}" 2> /dev/null
+ docker rm -f "${1}" 2>/dev/null
# shellcheck disable=SC2086
docker run ${3} \
- --name "${1}" \
- -e GG_THING_NAME="${GG_THING_NAME}" \
- -e GG_ADDITIONAL_CMD_ARGS="--trusted-plugin /provider.jar" \
- -e AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID}" \
- -e AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}" \
- -e AWS_REGION="${AWS_REGION}" \
- -e AWS_SESSION_TOKEN="${AWS_SESSION_TOKEN}" \
- -v GG_PARSEC_SOCK:/run/parsec \
- -v GG_HOME:/home/ggc_user \
- parallaxsecond/greengrass_demo:latest "${2}"
+ --name "${1}" \
+ -e GG_THING_NAME="${GG_THING_NAME}" \
+ -e GG_ADDITIONAL_CMD_ARGS="--trusted-plugin /provider.jar" \
+ -e AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID}" \
+ -e AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}" \
+ -e AWS_REGION="${AWS_REGION}" \
+ -e AWS_SESSION_TOKEN="${AWS_SESSION_TOKEN}" \
+ -v GG_PARSEC_SOCK:/run/parsec \
+ -v GG_HOME:/home/ggc_user \
+ parallaxsecond/greengrass_demo:latest "${2}"
}
function run_demo() {
parsec_run
diff --git a/parsec-client-java/pom.xml b/parsec-client-java/pom.xml
index ed6d357..c84960e 100644
--- a/parsec-client-java/pom.xml
+++ b/parsec-client-java/pom.xml
@@ -1,7 +1,6 @@
The client exposes low-level functionality for using the Parsec service. Below you can see - * code examples for a few of the operations supported. + *
+ * The client exposes low-level functionality for using the Parsec service. Below you can see code + * examples for a few of the operations supported. * - *
Providers are abstracted representations of the secure elements that Parsec offers abstraction + *
+ * Providers are abstracted representations of the secure elements that Parsec offers abstraction * over. Providers are the ones to execute the cryptographic operations requested by the user. * - *
For all cryptographic operations an implicit provider is used which can be changed between + *
+ * For all cryptographic operations an implicit provider is used which can be changed between * operations. The client starts with the default provider, the first one returned by the * ListProviders operation. * - *
For crypto operations, if the implicit client provider is `ProviderId.CORE`, a client error of + *
+ * For crypto operations, if the implicit client provider is `ProviderId.CORE`, a client error of * `InvalidProvider` type is returned. See the operation-specific response codes returned by the * service in the operation's page * [here](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/index.html). @@ -44,27 +53,35 @@ @Slf4j @SuppressWarnings("unused") public class BasicClient { + private OperationClient operationClient; private Authentication authData; private ProviderId implicitProvider; + /** * Create a new Parsec client. * - *
The client will be initialised with default values obtained from the service for the - * implicit provider and for application identity. + *
+ * The client will be initialised with default values obtained from the service for the implicit + * provider and for application identity. * - *
* `app_name` is the application name to be used if direct authentication is the default + *
+ * * `app_name` is the application name to be used if direct authentication is the default * authentication choice * - *
This client will use the default configuration. That includes using a Protobuf converter for + *
+ * This client will use the default configuration. That includes using a Protobuf converter for * message bodies and a Unix Domain Socket IPC handler. The default timeout length is 60 seconds. * - *
# Example + *
+ * # Example * - *
```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); # Ok(())} ```
+ *
+ * let client: BasicClient = BasicClient::new(None); # Ok(())} ```
*/
public static BasicClient client(String appName) {
return client(appName, null);
@@ -78,10 +95,6 @@ public static BasicClient client(String appName, IpcHandler ipcHandler) {
}
client.setDefaultProvider();
client.setDefaultAuth(appName);
- log.debug(
- "Parsec BasicClient created with implicit provider \"{}\" and authentication data \"{}\"",
- client.implicitProvider(),
- client.authData());
return client;
}
@@ -89,37 +102,48 @@ public static BasicClient client(String appName, IpcHandler ipcHandler) {
* Create a client that can initially only be used with Core operations not necessitating
* authentication (eg ping).
*
- * Setting an authentication method and an implicit provider is needed before calling crypto
+ *
+ * Setting an authentication method and an implicit provider is needed before calling crypto
* operations.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box * `app_name` is to be used if direct authentication is the default choice
+ *
+ * * `app_name` is to be used if direct authentication is the default choice
*
- * # Errors
+ *
+ * # Errors
*
- * If no authenticator is reported by the service, a `NoAuthenticator` error kind is returned.
+ *
+ * If no authenticator is reported by the service, a `NoAuthenticator` error kind is returned.
*
- * If the default authenticator is `DirectAuthenticator` and `app_name` was set to `None`, an
+ *
+ * If the default authenticator is `DirectAuthenticator` and `app_name` was set to `None`, an
* error of type `MissingParam` is returned.
*
- * If none of the authenticators returned by the service is supported, `NoAuthenticator` is
+ *
+ * If none of the authenticators returned by the service is supported, `NoAuthenticator` is
* returned.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box This is useful if you want to use a different authentication method than the default one.
+ *
+ * This is useful if you want to use a different authentication method than the default one.
*
- * # Example
+ *
+ * # Example
*
- * See [`set_default_provider`].
+ *
+ * See [`set_default_provider`].
*/
public void setAuthData(Authentication authData) {
this.authData = authData;
@@ -172,9 +197,11 @@ public void setAuthData(Authentication authData) {
/**
* Retrieve authentication data of the client.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box # Errors
+ *
+ * # Errors
*
- * If no provider is returned by the service, an client error of `NoProvider` type is returned.
+ *
+ * If no provider is returned by the service, an client error of `NoProvider` type is returned.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box # Example
+ *
+ * # Example
*
- * See [`set_default_auth`].
+ *
+ * See [`set_default_auth`].
*/
public void setImplicitProvider(ProviderId provider) {
this.implicitProvider = provider;
@@ -218,9 +253,11 @@ public void setImplicitProvider(ProviderId provider) {
/**
* Retrieve client's implicit provider.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let opcodes =
+ *
+ * let client: BasicClient = BasicClient::new(None); let opcodes =
* client.list_opcodes(ProviderId::Pkcs11); if opcodes.contains(&Opcode::PsaGenerateRandom) { let
* random_bytes = client.psa_generate_random(10); } # Ok(())} # Ok(())} ```
*/
public NativeResult.ListOpcodesResult listOpcodes(ProviderId provider) {
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.ListOpcodesOperation.builder().providerId(provider).build(),
- ProviderId.CORE,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.ListOpcodesOperation.builder().providerId(provider).build(),
+ ProviderId.CORE, this.authData);
if (res instanceof NativeResult.ListOpcodesResult) {
return (NativeResult.ListOpcodesResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -260,25 +299,26 @@ public NativeResult.ListOpcodesResult listOpcodes(ProviderId provider) {
/**
* **[Core Operation]** List the providers that are supported by the service.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let mut client: BasicClient = BasicClient::new_naked(); let providers =
+ *
+ * let mut client: BasicClient = BasicClient::new_naked(); let providers =
* client.list_providers(); Set the second most prioritary provider
* client.set_implicitProvider(providers[1].id); # Ok(())} ```
*/
public NativeResult.ListProvidersResult listProviders() {
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.ListProvidersOperation.builder().build(),
- ProviderId.CORE,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.ListProvidersOperation.builder().build(), ProviderId.CORE, this.authData);
if (res instanceof NativeResult.ListProvidersResult) {
return (NativeResult.ListProvidersResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -287,142 +327,161 @@ public NativeResult.ListProvidersResult listProviders() {
/**
* **[Core Operation]** List the authenticators that are supported by the service.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let opcodes =
- * client.list_authenticators(); # Ok(())} ```
+ *
+ * let client: BasicClient = BasicClient::new(None); let opcodes = client.list_authenticators(); #
+ * Ok(())} ```
*/
public NativeResult.ListAuthenticatorsResult listAuthenticators() {
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.ListAuthenticatorsOperation.builder().build(),
- ProviderId.CORE,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.ListAuthenticatorsOperation.builder().build(), ProviderId.CORE,
+ this.authData);
if (res instanceof NativeResult.ListAuthenticatorsResult) {
return (NativeResult.ListAuthenticatorsResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
}
+
/**
* **[Core Operation]** List all keys belonging to the application.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let keys = client.list_keys(); # Ok(())}
- * ```
+ *
+ * let client: BasicClient = BasicClient::new(None); let keys = client.list_keys(); # Ok(())} ```
*/
public NativeResult.ListKeysResult listKeys() {
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.ListKeysOperation.builder().build(), ProviderId.CORE, this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.ListKeysOperation.builder().build(), ProviderId.CORE, this.authData);
if (res instanceof NativeResult.ListKeysResult) {
return (NativeResult.ListKeysResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
}
+
/**
* Get the key attributes.
*
- * This is a convenience method that uses `list_keys` underneath.
+ *
+ * This is a convenience method that uses `list_keys` underneath.
*
- * # Errors
+ *
+ * # Errors
*
- * Returns `NotFound` if a key with this name does not exist.
+ *
+ * Returns `NotFound` if a key with this name does not exist.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let attributes =
+ *
+ * let client: BasicClient = BasicClient::new(None); let attributes =
* client.key_attributes("my_key"); # Ok(())} ```
*/
public PsaKeyAttributes.KeyAttributes keyAttributes(String keyName) {
- return listKeys().getKeys().stream()
- .filter(ki -> ki.getName().equals(keyName))
- .findFirst()
- .orElseThrow(NotFoundException::new)
- .getAttributes();
+ return listKeys().getKeys().stream().filter(ki -> ki.getName().equals(keyName)).findFirst()
+ .orElseThrow(NotFoundException::new).getAttributes();
}
+
/**
* **[Core Operation, Admin Operation]** Lists all clients currently having data in the service.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let clients = client.list_clients(); #
+ *
+ * let client: BasicClient = BasicClient::new(None); let clients = client.list_clients(); #
* Ok(())} ```
*/
public NativeResult.ListClientsResult listClients() {
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.ListClientsOperation.builder().build(), ProviderId.CORE, this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.ListClientsOperation.builder().build(), ProviderId.CORE, this.authData);
if (res instanceof NativeResult.ListClientsResult) {
return (NativeResult.ListClientsResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
}
+
/**
* **[Core Operation, Admin Operation]** Delete all data a client has in the service.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); client.delete_client("main_client"); #
+ *
+ * let client: BasicClient = BasicClient::new(None); client.delete_client("main_client"); #
* Ok(())} ```
*/
public void deleteClient(String client) {
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.DeleteClientOperation.builder().client(client).build(),
- ProviderId.CORE,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.DeleteClientOperation.builder().client(client).build(), ProviderId.CORE,
+ this.authData);
if (!(res instanceof NativeResult.DeleteClientResult)) {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
}
+
/**
* **[Core Operation]** Send a ping request to the service.
*
- * This operation is intended for testing connectivity to the service and for retrieving the
+ *
+ * This operation is intended for testing connectivity to the service and for retrieving the
* maximum wire protocol version it supports.
*
- * # Example
+ *
+ * # Example
*
- * See [`new_naked`].
+ *
+ * See [`new_naked`].
*/
public NativeResult.PingResult ping() {
NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PingOperation.builder().build(),
- ProviderId.CORE,
- new Authentication.None());
+ this.operationClient.processOperation(NativeOperation.PingOperation.builder().build(),
+ ProviderId.CORE, new Authentication.None());
if (res instanceof NativeResult.PingResult) {
return (NativeResult.PingResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -431,24 +490,30 @@ public NativeResult.PingResult ping() {
/**
* **[Cryptographic Operation]** Generate a key.
*
- * Creates a new key with the given name within the namespace of the implicit client provider.
- * Any UTF-8 string is considered a valid key name, however names must be unique per provider.
+ *
+ * Creates a new key with the given name within the namespace of the implicit client provider. Any
+ * UTF-8 string is considered a valid key name, however names must be unique per provider.
*
- * Persistence of keys is implemented at provider level, and currently all providers persist
- * all the keys users create.
+ *
+ * Persistence of keys is implemented at provider level, and currently all providers persist all
+ * the keys users create.
*
- * If this method returns an error, no key will have been generated and the name used will
- * still be available for another key.
+ *
+ * If this method returns an error, no key will have been generated and the name used will still
+ * be available for another key.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let key_attrs = Attributes { lifetime:
+ *
+ * let client: BasicClient = BasicClient::new(None); let key_attrs = Attributes { lifetime:
* Lifetime::Persistent, key_type: Type::RsaKeyPair, bits: 2048, policy: Policy { usage_flags:
* UsageFlags::default(), permitted_algorithms: AsymmetricSignature::RsaPkcs1v15Sign { hash_alg:
* Hash::Sha256.into(), }.into(), }, }; client.psa_generate_key("my_key", key_attrs); # Ok(())}
@@ -457,15 +522,9 @@ public NativeResult.PingResult ping() {
public void psaGenerateKey(String keyName, PsaKeyAttributes.KeyAttributes keyAttributes) {
ProviderId cryptoProvider = this.canProvideCrypto();
-
NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaGenerateKeyOperation.builder()
- .keyName(keyName)
- .attributes(keyAttributes)
- .build(),
- cryptoProvider,
- this.authData);
+ this.operationClient.processOperation(NativeOperation.PsaGenerateKeyOperation.builder()
+ .keyName(keyName).attributes(keyAttributes).build(), cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaGenerateKeyResult) {
return;
}
@@ -475,25 +534,27 @@ public void psaGenerateKey(String keyName, PsaKeyAttributes.KeyAttributes keyAtt
/**
* **[Cryptographic Operation]** Destroy a key.
*
- * Given that keys are namespaced at a provider level, it is important to call
- * `psa_destroy_key` on the correct combination of implicit client provider and `keyName`.
+ *
+ * Given that keys are namespaced at a provider level, it is important to call `psa_destroy_key`
+ * on the correct combination of implicit client provider and `keyName`.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); client.psa_destroy_key("my_key"); #
- * Ok(())} ```
+ *
+ * let client: BasicClient = BasicClient::new(None); client.psa_destroy_key("my_key"); # Ok(())}
+ * ```
*/
public void psaDestroyKey(String keyName) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaDestroyKeyOperation.builder().keyName(keyName).build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaDestroyKeyOperation.builder().keyName(keyName).build(), cryptoProvider,
+ this.authData);
if (res instanceof NativeResult.PsaDestroyKeyResult) {
return;
}
@@ -503,46 +564,48 @@ public void psaDestroyKey(String keyName) {
/**
* **[Cryptographic Operation]** Import a key.
*
- * Creates a new key with the given name within the namespace of the implicit client provider
+ *
+ * Creates a new key with the given name within the namespace of the implicit client provider
* using the user-provided data. Any UTF-8 string is considered a valid key name, however names
* must be unique per provider.
*
- * The key material should follow the appropriate binary format expressed
+ *
+ * The key material should follow the appropriate binary format expressed
* [here](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_export_public_key.html).
* Several crates (e.g. [`picky-asn1`](https://crates.io/crates/picky-asn1)) can greatly help in
* dealing with binary encodings.
*
- * If this method returns an error, no key will have been imported and the name used will still
- * be available for another key.
+ *
+ * If this method returns an error, no key will have been imported and the name used will still be
+ * available for another key.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let ecc_private_key = vec![ 0x26, 0xc8,
- * 0x82, 0x9e, 0x22, 0xe3, 0x0c, 0xa6, 0x3d, 0x29, 0xf5, 0xf7, 0x27, 0x39, 0x58, 0x47, 0x41, 0x81,
- * 0xf6, 0x57, 0x4f, 0xdb, 0xcb, 0x4d, 0xbb, 0xdd, 0x52, 0xff, 0x3a, 0xc0, 0xf6, 0x0d, ]; let
- * key_attrs = Attributes { lifetime: Lifetime::Persistent, key_type: Type::EccKeyPair {
- * curve_family: EccFamily::SecpR1, }, bits: 256, policy: Policy { usage_flags:
- * UsageFlags::default(), permitted_algorithms: AsymmetricSignature::RsaPkcs1v15Sign { hash_alg:
- * Hash::Sha256.into(), }.into(), }, }; client.psa_import_key("my_key", &ecc_private_key,
- * key_attrs); # Ok(())} ```
+ *
+ * let client: BasicClient = BasicClient::new(None); let ecc_private_key = vec![ 0x26, 0xc8, 0x82,
+ * 0x9e, 0x22, 0xe3, 0x0c, 0xa6, 0x3d, 0x29, 0xf5, 0xf7, 0x27, 0x39, 0x58, 0x47, 0x41, 0x81, 0xf6,
+ * 0x57, 0x4f, 0xdb, 0xcb, 0x4d, 0xbb, 0xdd, 0x52, 0xff, 0x3a, 0xc0, 0xf6, 0x0d, ]; let key_attrs
+ * = Attributes { lifetime: Lifetime::Persistent, key_type: Type::EccKeyPair { curve_family:
+ * EccFamily::SecpR1, }, bits: 256, policy: Policy { usage_flags: UsageFlags::default(),
+ * permitted_algorithms: AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha256.into(),
+ * }.into(), }, }; client.psa_import_key("my_key", &ecc_private_key, key_attrs); # Ok(())} ```
*/
- public void psaImportKey(String keyName, byte[] keyMaterial, PsaKeyAttributes.KeyAttributes keyAttributes) {
+ public void psaImportKey(String keyName, byte[] keyMaterial,
+ PsaKeyAttributes.KeyAttributes keyAttributes) {
ProviderId cryptoProvider = this.canProvideCrypto();
NativeResult res =
this.operationClient.processOperation(
- NativeOperation.PsaImportKeyOperation.builder()
- .keyName(keyName)
- .attributes(keyAttributes)
- .data(keyMaterial)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeOperation.PsaImportKeyOperation.builder().keyName(keyName)
+ .attributes(keyAttributes).data(keyMaterial).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaImportKeyResult) {
return;
}
@@ -552,32 +615,35 @@ public void psaImportKey(String keyName, byte[] keyMaterial, PsaKeyAttributes.Ke
/**
* **[Cryptographic Operation]** Export a public key or the public part of a key pair.
*
- * The returned key material will follow the appropriate binary format expressed
+ *
+ * The returned key material will follow the appropriate binary format expressed
* [here](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_export_public_key.html).
* Several crates (e.g. [`picky-asn1`](https://crates.io/crates/picky-asn1)) can greatly help in
* dealing with binary encodings.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let public_key_data =
+ *
+ * let client: BasicClient = BasicClient::new(None); let public_key_data =
* client.psa_export_public_key("my_key"); # Ok(())} ```
*/
public NativeResult.PsaExportPublicKeyResult psaExportPublicKey(String keyName) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaExportPublicKeyOperation.builder().keyName(keyName).build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaExportPublicKeyOperation.builder().keyName(keyName).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaExportPublicKeyResult) {
return (NativeResult.PsaExportPublicKeyResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -586,81 +652,86 @@ public NativeResult.PsaExportPublicKeyResult psaExportPublicKey(String keyName)
/**
* **[Cryptographic Operation]** Export a key.
*
- * The returned key material will follow the appropriate binary format expressed
+ *
+ * The returned key material will follow the appropriate binary format expressed
* [here](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_export_key.html).
* Several crates (e.g. [`picky-asn1`](https://crates.io/crates/picky-asn1)) can greatly help in
* dealing with binary encodings.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let key_data =
+ *
+ * let client: BasicClient = BasicClient::new(None); let key_data =
* client.psa_export_key("my_key"); # Ok(())} ```
*/
public NativeResult.PsaExportKeyResult psaExportKey(String keyName) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaExportKeyOperation.builder().keyName(keyName).build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaExportKeyOperation.builder().keyName(keyName).build(), cryptoProvider,
+ this.authData);
if (res instanceof NativeResult.PsaExportKeyResult) {
return (NativeResult.PsaExportKeyResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
}
+
/**
* **[Cryptographic Operation]** Create an asymmetric signature on a pre-computed message digest.
*
- * The key intended for signing **must** have its `sign_hash` flag set to `true` in its [key
+ *
+ * The key intended for signing **must** have its `sign_hash` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The signature will be created with the algorithm defined in `signAlgorithm`, but only after
+ *
+ * The signature will be created with the algorithm defined in `signAlgorithm`, but only after
* checking that the key policy and type conform with it.
*
- * `hash` must be a hash pre-computed over the message of interest with the algorithm specified
+ *
+ * `hash` must be a hash pre-computed over the message of interest with the algorithm specified
* within `signAlgorithm`.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); Hash of a message pre-calculated with
+ *
+ * let client: BasicClient = BasicClient::new(None); Hash of a message pre-calculated with
* SHA-256. let hash = vec![ 0x69, 0x3E, 0xDB, 0x1B, 0x22, 0x79, 0x03, 0xF4, 0xC0, 0xBF, 0xD6,
* 0x91, 0x76, 0x37, 0x84, 0xA2, 0x94, 0x8E, 0x92, 0x50, 0x35, 0xC2, 0x8C, 0x5C, 0x3C, 0xCA, 0xFE,
* 0x18, 0xE8, 0x81, 0x37, 0x78, ]; let signature = client.psa_sign_hash("my_key", &hash,
* AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha256.into(), }); # Ok(())} ```
*/
- public NativeResult.PsaSignHashResult psaSignHash(
- String keyName, byte[] hash, PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm) {
+ public NativeResult.PsaSignHashResult psaSignHash(String keyName, byte[] hash,
+ PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm) {
ProviderId cryptoProvider = this.canProvideCrypto();
NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaSignHashOperation.builder()
- .keyName(keyName)
- .alg(signAlgorithm)
- .hash(hash)
- .build(),
- cryptoProvider,
- this.authData);
+ this.operationClient.processOperation(NativeOperation.PsaSignHashOperation.builder()
+ .keyName(keyName).alg(signAlgorithm).hash(hash).build(), cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaSignHashResult) {
return (NativeResult.PsaSignHashResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -670,48 +741,44 @@ public NativeResult.PsaSignHashResult psaSignHash(
* **[Cryptographic Operation]** Verify an existing asymmetric signature over a pre-computed
* message digest.
*
- * The key intended for signing **must** have its `verify_hash` flag set to `true` in its [key
+ *
+ * The key intended for signing **must** have its `verify_hash` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The signature will be verifyied with the algorithm defined in `sign_algorithm`, but only
- * after checking that the key policy and type conform with it.
+ *
+ * The signature will be verifyied with the algorithm defined in `sign_algorithm`, but only after
+ * checking that the key policy and type conform with it.
*
- * `hash` must be a hash pre-computed over the message of interest with the algorithm specified
+ *
+ * `hash` must be a hash pre-computed over the message of interest with the algorithm specified
* within `sign_algorithm`.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); Hash of a message pre-calculated with
+ *
+ * let client: BasicClient = BasicClient::new(None); Hash of a message pre-calculated with
* SHA-256. let hash = vec![ 0x69, 0x3E, 0xDB, 0x1B, 0x22, 0x79, 0x03, 0xF4, 0xC0, 0xBF, 0xD6,
* 0x91, 0x76, 0x37, 0x84, 0xA2, 0x94, 0x8E, 0x92, 0x50, 0x35, 0xC2, 0x8C, 0x5C, 0x3C, 0xCA, 0xFE,
* 0x18, 0xE8, 0x81, 0x37, 0x78, ]; let alg = AsymmetricSignature::RsaPkcs1v15Sign { hash_alg:
* Hash::Sha256.into(), }; let signature = client.psa_sign_hash("my_key", &hash, alg);
* client.psa_verify_hash("my_key", &hash, alg, &signature); # Ok(())} ```
*/
- public NativeResult.PsaVerifyHashResult psaVerifyHash(
- String keyName,
- byte[] hash,
- PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm,
- byte[] signature) {
+ public NativeResult.PsaVerifyHashResult psaVerifyHash(String keyName, byte[] hash,
+ PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm, byte[] signature) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaVerifyHashOperation.builder()
- .keyName(keyName)
- .alg(signAlgorithm)
- .hash(hash)
- .signature(signature)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(NativeOperation.PsaVerifyHashOperation
+ .builder().keyName(keyName).alg(signAlgorithm).hash(hash).signature(signature).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaVerifyHashResult) {
return (NativeResult.PsaVerifyHashResult) res;
}
@@ -721,43 +788,43 @@ public NativeResult.PsaVerifyHashResult psaVerifyHash(
/**
* [Cryptographic Operation]** Create an asymmetric signature on a message.
*
- * The key intended for signing **must** have its `sign_message` flag set to `true` in its [key
+ *
+ * The key intended for signing **must** have its `sign_message` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The signature will be created with the algorithm defined in `sign_algorithm`, but only after
+ *
+ * The signature will be created with the algorithm defined in `sign_algorithm`, but only after
* checking that the key policy and type conform with it.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let message = "This is the message to sign
+ *
+ * let client: BasicClient = BasicClient::new(None); let message = "This is the message to sign
* which can be of any size!".as_bytes(); let signature = client.psa_sign_message( "my_key",
* message, AsymmetricSignature::RsaPkcs1v15Sign { hash_alg: Hash::Sha256.into(), } ); # Ok(())}
* ```
*/
- public NativeResult.PsaSignMessageResult psaSignMessage(
- String keyName, byte[] message, PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm) {
+ public NativeResult.PsaSignMessageResult psaSignMessage(String keyName, byte[] message,
+ PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaSignMessageOperation.builder()
- .keyName(keyName)
- .alg(signAlgorithm)
- .message(message)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(NativeOperation.PsaSignMessageOperation
+ .builder().keyName(keyName).alg(signAlgorithm).message(message).build(), cryptoProvider,
+ this.authData);
if (res instanceof NativeResult.PsaSignMessageResult) {
return (NativeResult.PsaSignMessageResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -766,43 +833,40 @@ public NativeResult.PsaSignMessageResult psaSignMessage(
/**
* [Cryptographic Operation]** Verify an existing asymmetric signature over a message.
*
- * The key intended for signing **must** have its `verify_message` flag set to `true` in its
- * [key
+ *
+ * The key intended for signing **must** have its `verify_message` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The signature will be verifyied with the algorithm defined in `sign_algorithm`, but only
- * after checking that the key policy and type conform with it.
+ *
+ * The signature will be verifyied with the algorithm defined in `sign_algorithm`, but only after
+ * checking that the key policy and type conform with it.
*
- * # Example
+ *
+ * # Example
*
- * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box
+ * ```no_run # use std::error::Error; # # fn main() -> Result<(), Box let client: BasicClient = BasicClient::new(None); let message = "This is the message to sign
+ *
+ * let client: BasicClient = BasicClient::new(None); let message = "This is the message to sign
* which can be of any size!".as_bytes(); let alg = AsymmetricSignature::RsaPkcs1v15Sign {
* hash_alg: Hash::Sha256.into(), }; let signature = client.psa_sign_message("my_key", message,
* alg); client.psa_verify_message("my_key", message, alg, &signature); # Ok(())} ```
*/
- public NativeResult psaVerifyMessage(
- String keyName,
- byte[] msg,
- PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm,
- byte[] signature) {
+ public NativeResult psaVerifyMessage(String keyName, byte[] msg,
+ PsaAlgorithm.Algorithm.AsymmetricSignature signAlgorithm, byte[] signature) {
ProviderId cryptoProvider = this.canProvideCrypto();
NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaVerifyMessageOperation.builder()
- .keyName(keyName)
- .alg(signAlgorithm)
- .message(msg)
- .signature(signature)
- .build(),
- cryptoProvider,
- this.authData);
+ this.operationClient
+ .processOperation(
+ NativeOperation.PsaVerifyMessageOperation.builder().keyName(keyName)
+ .alg(signAlgorithm).message(msg).signature(signature).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaVerifyMessageResult) {
return res;
@@ -813,39 +877,36 @@ public NativeResult psaVerifyMessage(
/**
* [Cryptographic Operation]** Encrypt a short message.
*
- * The key intended for encrypting **must** have its `encrypt` flag set to `true` in its [key
+ *
+ * The key intended for encrypting **must** have its `encrypt` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The encryption will be performed with the algorithm defined in `alg`, but only after
- * checking that the key policy and type conform with it.
+ *
+ * The encryption will be performed with the algorithm defined in `alg`, but only after checking
+ * that the key policy and type conform with it.
*
- * `salt` can be provided if supported by the algorithm. If the algorithm does not support
- * salt, pass an empty vector. If the algorithm supports optional salt, pass an empty vector to
- * indicate no salt. For RSA PKCS#1 v1.5 encryption, no salt is supported.
+ *
+ * `salt` can be provided if supported by the algorithm. If the algorithm does not support salt,
+ * pass an empty vector. If the algorithm supports optional salt, pass an empty vector to indicate
+ * no salt. For RSA PKCS#1 v1.5 encryption, no salt is supported.
*/
- public NativeResult.PsaAsymmetricEncryptResult psaAsymmetricEncrypt(
- String keyName,
- PsaAlgorithm.Algorithm.AsymmetricEncryption encryptAlg,
- byte[] plaintext,
- byte[] salt) {
+ public NativeResult.PsaAsymmetricEncryptResult psaAsymmetricEncrypt(String keyName,
+ PsaAlgorithm.Algorithm.AsymmetricEncryption encryptAlg, byte[] plaintext, byte[] salt) {
ProviderId cryptoProvider = this.canProvideCrypto();
NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaAsymmetricEncryptOperation.builder()
- .keyName(keyName)
- .alg(encryptAlg)
- .plaintext(plaintext)
- .salt(salt)
- .build(),
- cryptoProvider,
- this.authData);
+ this.operationClient
+ .processOperation(
+ NativeOperation.PsaAsymmetricEncryptOperation.builder().keyName(keyName)
+ .alg(encryptAlg).plaintext(plaintext).salt(salt).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaAsymmetricEncryptResult) {
return (NativeResult.PsaAsymmetricEncryptResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -854,61 +915,59 @@ public NativeResult.PsaAsymmetricEncryptResult psaAsymmetricEncrypt(
/**
* [Cryptographic Operation]** Decrypt a short message.
*
- * The key intended for decrypting **must** have its `decrypt` flag set to `true` in its [key
+ *
+ * The key intended for decrypting **must** have its `decrypt` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * `salt` can be provided if supported by the algorithm. If the algorithm does not support
- * salt, pass an empty vector. If the algorithm supports optional salt, pass an empty vector to
- * indicate no salt. For RSA PKCS#1 v1.5 encryption, no salt is supported.
+ *
+ * `salt` can be provided if supported by the algorithm. If the algorithm does not support salt,
+ * pass an empty vector. If the algorithm supports optional salt, pass an empty vector to indicate
+ * no salt. For RSA PKCS#1 v1.5 encryption, no salt is supported.
*
- * The decryption will be performed with the algorithm defined in `alg`, but only after
- * checking that the key policy and type conform with it.
+ *
+ * The decryption will be performed with the algorithm defined in `alg`, but only after checking
+ * that the key policy and type conform with it.
*/
- public NativeResult.PsaAeadDecryptResult psaAsymmetricDecrypt(
- String keyName,
- PsaAlgorithm.Algorithm.AsymmetricEncryption encryptAlg,
- byte[] ciphertext,
- byte[] salt) {
+ public NativeResult.PsaAeadDecryptResult psaAsymmetricDecrypt(String keyName,
+ PsaAlgorithm.Algorithm.AsymmetricEncryption encryptAlg, byte[] ciphertext, byte[] salt) {
ProviderId cryptoProvider = this.canProvideCrypto();
NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaAsymmetricDecryptOperation.builder()
- .keyName(keyName)
- .alg(encryptAlg)
- .ciphertext(ciphertext)
- .salt(salt)
- .build(),
- cryptoProvider,
- this.authData);
+ this.operationClient
+ .processOperation(
+ NativeOperation.PsaAsymmetricDecryptOperation.builder().keyName(keyName)
+ .alg(encryptAlg).ciphertext(ciphertext).salt(salt).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaAeadDecryptResult) {
return (NativeResult.PsaAeadDecryptResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
}
+
/**
* [Cryptographic Operation]** Compute hash of a message.
*
- * The hash computation will be performed with the algorithm defined in `alg`.
+ *
+ * The hash computation will be performed with the algorithm defined in `alg`.
*/
- public NativeResult.PsaHashComputeResult psaHashCompute(
- PsaAlgorithm.Algorithm.Hash alg, byte[] input) {
+ public NativeResult.PsaHashComputeResult psaHashCompute(PsaAlgorithm.Algorithm.Hash alg,
+ byte[] input) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaHashComputeOperation.builder().alg(alg).input(input).build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaHashComputeOperation.builder().alg(alg).input(input).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaHashComputeResult) {
return (NativeResult.PsaHashComputeResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -917,23 +976,19 @@ public NativeResult.PsaHashComputeResult psaHashCompute(
/**
* [Cryptographic Operation]** Compute hash of a message and compare it with a reference value.
*
- * The hash computation will be performed with the algorithm defined in `alg`.
+ *
+ * The hash computation will be performed with the algorithm defined in `alg`.
*
- * If this operation returns no error, the hash was computed successfully and it matches the
+ *
+ * If this operation returns no error, the hash was computed successfully and it matches the
* reference value.
*/
- public NativeResult.PsaHashCompareResult psaHashCompare(
- PsaAlgorithm.Algorithm.Hash alg, byte[] input, byte[] hash) {
+ public NativeResult.PsaHashCompareResult psaHashCompare(PsaAlgorithm.Algorithm.Hash alg,
+ byte[] input, byte[] hash) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaHashCompareOperation.builder()
- .alg(alg)
- .input(input)
- .hash(hash)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaHashCompareOperation.builder().alg(alg).input(input).hash(hash).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaHashCompareResult) {
return (NativeResult.PsaHashCompareResult) res;
}
@@ -943,42 +998,37 @@ public NativeResult.PsaHashCompareResult psaHashCompare(
/**
* [Cryptographic Operation]** Authenticate and encrypt a short message.
*
- * The key intended for decrypting **must** have its `encrypt` flag set to `true` in its [key
+ *
+ * The key intended for decrypting **must** have its `encrypt` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The encryption will be performed with the algorithm defined in `alg`, but only after
- * checking that the key policy and type conform with it.
+ *
+ * The encryption will be performed with the algorithm defined in `alg`, but only after checking
+ * that the key policy and type conform with it.
*
- * `nonce` must be appropriate for the selected `alg`.
+ *
+ * `nonce` must be appropriate for the selected `alg`.
*
- * For algorithms where the encrypted data and the authentication tag are defined as separate
+ *
+ * For algorithms where the encrypted data and the authentication tag are defined as separate
* outputs, the returned buffer will contain the encrypted data followed by the authentication
* data.
*/
- public NativeResult.PsaAeadEncryptResult psaAeadEncrypt(
- String keyName,
- PsaAlgorithm.Algorithm.Aead encryptAlg,
- byte[] nonce,
- byte[] additionalData,
+ public NativeResult.PsaAeadEncryptResult psaAeadEncrypt(String keyName,
+ PsaAlgorithm.Algorithm.Aead encryptAlg, byte[] nonce, byte[] additionalData,
byte[] plaintext) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaAeadEncryptOperation.builder()
- .keyName(keyName)
- .alg(encryptAlg)
- .nonce(nonce)
- .additionalData(additionalData)
- .plaintext(plaintext)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaAeadEncryptOperation.builder().keyName(keyName).alg(encryptAlg)
+ .nonce(nonce).additionalData(additionalData).plaintext(plaintext).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaAeadEncryptResult) {
return (NativeResult.PsaAeadEncryptResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -987,41 +1037,36 @@ public NativeResult.PsaAeadEncryptResult psaAeadEncrypt(
/**
* [Cryptographic Operation]** Decrypt and authenticate a short message.
*
- * The key intended for decrypting **must** have its `decrypt` flag set to `true` in its [key
+ *
+ * The key intended for decrypting **must** have its `decrypt` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The decryption will be performed with the algorithm defined in `alg`, but only after
- * checking that the key policy and type conform with it.
+ *
+ * The decryption will be performed with the algorithm defined in `alg`, but only after checking
+ * that the key policy and type conform with it.
*
- * `nonce` must be appropriate for the selected `alg`.
+ *
+ * `nonce` must be appropriate for the selected `alg`.
*
- * For algorithms where the encrypted data and the authentication tag are defined as separate
+ *
+ * For algorithms where the encrypted data and the authentication tag are defined as separate
* inputs, `ciphertext` must contain the encrypted data followed by the authentication data.
*/
- public NativeResult.PsaAeadDecryptResult psaAeadDecrypt(
- String keyName,
- PsaAlgorithm.Algorithm.Aead encryptAlg,
- byte[] nonce,
- byte[] additionalData,
+ public NativeResult.PsaAeadDecryptResult psaAeadDecrypt(String keyName,
+ PsaAlgorithm.Algorithm.Aead encryptAlg, byte[] nonce, byte[] additionalData,
byte[] ciphertext) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaAeadDecryptOperation.builder()
- .keyName(keyName)
- .alg(encryptAlg)
- .nonce(nonce)
- .additionalData(additionalData)
- .ciphertext(ciphertext)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaAeadDecryptOperation.builder().keyName(keyName).alg(encryptAlg)
+ .nonce(nonce).additionalData(additionalData).ciphertext(ciphertext).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaAeadDecryptResult) {
return (NativeResult.PsaAeadDecryptResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -1030,32 +1075,31 @@ public NativeResult.PsaAeadDecryptResult psaAeadDecrypt(
/**
* [Cryptographic Operation]** Perform a raw key agreement.
*
- * The provided private key **must** have its `derive` flag set to `true` in its [key
+ *
+ * The provided private key **must** have its `derive` flag set to `true` in its [key
* policy](https://docs.rs/parsec-interface//parsec_interface/operations/psa_key_attributes/struct.Policy.html).
*
- * The raw_key_agreement will be performed with the algorithm defined in `alg`, but only after
+ *
+ * The raw_key_agreement will be performed with the algorithm defined in `alg`, but only after
* checking that the key policy and type conform with it.
*
- * `peer_key` must be the peer public key to use in the raw key derivation. It must be in a
- * format supported by
+ *
+ * `peer_key` must be the peer public key to use in the raw key derivation. It must be in a format
+ * supported by
* [`PsaImportKey`](https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_import_key.html).
*/
- public NativeResult.PsaRawKeyAgreementResult psaRawKeyAgreement(
- PsaRawKeyAgreement alg, String privateKeyName, byte[] peerKey) {
+ public NativeResult.PsaRawKeyAgreementResult psaRawKeyAgreement(PsaRawKeyAgreement alg,
+ String privateKeyName, byte[] peerKey) {
ProviderId cryptoProvider = this.canProvideCrypto();
- NativeResult res =
- this.operationClient.processOperation(
- NativeOperation.PsaRawKeyAgreementOperation.builder()
- .alg(alg)
- .peerKey(peerKey)
- .privateKeyName(privateKeyName)
- .build(),
- cryptoProvider,
- this.authData);
+ NativeResult res = this.operationClient.processOperation(
+ NativeOperation.PsaRawKeyAgreementOperation.builder().alg(alg).peerKey(peerKey)
+ .privateKeyName(privateKeyName).build(),
+ cryptoProvider, this.authData);
if (res instanceof NativeResult.PsaRawKeyAgreementResult) {
return (NativeResult.PsaRawKeyAgreementResult) res;
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
@@ -1064,13 +1108,17 @@ public NativeResult.PsaRawKeyAgreementResult psaRawKeyAgreement(
/**
* [Cryptographic Operation]** Generate some random bytes.
*
- * Generates a sequence of random bytes and returns them to the user.
+ *
+ * Generates a sequence of random bytes and returns them to the user.
*
- * If this method returns an error, no bytes will have been generated.
+ *
+ * If this method returns an error, no bytes will have been generated.
*
- * # Example
+ *
+ * # Example
*
- * See [`list_opcodes`].
+ *
+ * See [`list_opcodes`].
*/
public byte[] psaGenerateRandom(long nbytes) {
ProviderId cryptoProvider = this.canProvideCrypto();
@@ -1083,7 +1131,8 @@ public byte[] psaGenerateRandom(long nbytes) {
if (res instanceof NativeResult.PsaGenerateRandomResult) {
return ((NativeResult.PsaGenerateRandomResult) res).getRandomBytes();
} else {
- // Should really not be reached given the checks we do, but it's not impossible if some
+ // Should really not be reached given the checks we do, but it's not impossible
+ // if some
// changes happen in the interface
throw new InvalidServiceResponseTypeException();
}
diff --git a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/OperationClient.java b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/OperationClient.java
index 0511b3e..4b4e0e3 100644
--- a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/OperationClient.java
+++ b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/OperationClient.java
@@ -1,15 +1,18 @@
package org.parallaxsecond.parsec.client.core;
+import java.io.IOException;
+import java.time.Duration;
+
import org.parallaxsecond.parsec.client.Authentication;
import org.parallaxsecond.parsec.client.core.ipc_handler.IpcHandler;
import org.parallaxsecond.parsec.client.exceptions.ClientException;
-import org.parallaxsecond.parsec.protocol.requests.InterfaceException;
import org.parallaxsecond.parsec.client.exceptions.InvalidServiceResponseTypeException;
import org.parallaxsecond.parsec.client.exceptions.ServiceException;
import org.parallaxsecond.parsec.protocol.operations.Convert;
import org.parallaxsecond.parsec.protocol.operations.NativeOperation;
import org.parallaxsecond.parsec.protocol.operations.NativeResult;
import org.parallaxsecond.parsec.protocol.operations_protobuf.ProtobufConverter;
+import org.parallaxsecond.parsec.protocol.requests.InterfaceException;
import org.parallaxsecond.parsec.protocol.requests.Opcode;
import org.parallaxsecond.parsec.protocol.requests.ProviderId;
import org.parallaxsecond.parsec.protocol.requests.ResponseStatus;
@@ -17,14 +20,14 @@
import org.parallaxsecond.parsec.protocol.requests.request.RequestBody;
import org.parallaxsecond.parsec.protocol.requests.request.RequestHeader;
import org.parallaxsecond.parsec.protocol.requests.response.Response;
+
import lombok.Builder;
import lombok.RequiredArgsConstructor;
-
-import java.io.IOException;
-import java.time.Duration;
+import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
@Builder
+@Slf4j
public class OperationClient {
/** Converter that manages request body conversions Defaults to a Protobuf converter */
private final Convert contentConverter;
@@ -34,15 +37,13 @@ public class OperationClient {
private final RequestClient requestClient;
public static OperationClient withDefaults() {
- return OperationClient.builder()
- .contentConverter(new ProtobufConverter())
- .acceptConverter(new ProtobufConverter())
- .requestClient(RequestClient.withDefaults())
+ return OperationClient.builder().contentConverter(new ProtobufConverter())
+ .acceptConverter(new ProtobufConverter()).requestClient(RequestClient.withDefaults())
.build();
}
- public NativeResult processOperation(
- NativeOperation operation, ProviderId providerId, Authentication auth) {
+ public NativeResult processOperation(NativeOperation operation, ProviderId providerId,
+ Authentication auth) {
Opcode reqOpCode = operation.getOpcode();
Request request = operationToRequest(operation, providerId, auth);
Response response = null;
@@ -54,8 +55,8 @@ public NativeResult processOperation(
return responseToResult(response, reqOpCode);
}
- private Request operationToRequest(
- NativeOperation operation, ProviderId providerId, Authentication auth) {
+ private Request operationToRequest(NativeOperation operation, ProviderId providerId,
+ Authentication auth) {
Opcode opcode = operation.getOpcode();
final RequestBody body;
@@ -64,15 +65,10 @@ private Request operationToRequest(
} catch (Exception e) {
throw new InterfaceException(e);
}
- RequestHeader header =
- RequestHeader.builder()
- .provider(providerId)
- .session(0) // no provisioning of sessions yet
- .contentType(contentConverter.bodyType())
- .acceptType(acceptConverter.bodyType())
- .authType(auth.getAuthType())
- .opcode(opcode)
- .build();
+ // no provisioning of sessions yet
+ RequestHeader header = RequestHeader.builder().provider(providerId).session(0)
+ .contentType(contentConverter.bodyType()).acceptType(acceptConverter.bodyType())
+ .authType(auth.getAuthType()).opcode(opcode).build();
return Request.builder().header(header).body(body).auth(auth.createRequestAuth()).build();
}
diff --git a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/RequestClient.java b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/RequestClient.java
index 5579745..e983a4e 100644
--- a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/RequestClient.java
+++ b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/RequestClient.java
@@ -1,19 +1,17 @@
package org.parallaxsecond.parsec.client.core;
+import java.io.IOException;
+import java.nio.channels.ByteChannel;
+import java.time.Duration;
+
import org.parallaxsecond.parsec.client.core.ipc_handler.IpcHandler;
import org.parallaxsecond.parsec.client.core.ipc_handler.UnixSocket;
import org.parallaxsecond.parsec.protocol.requests.request.Request;
import org.parallaxsecond.parsec.protocol.requests.response.Response;
+
import lombok.AllArgsConstructor;
import lombok.Builder;
-
-import java.io.IOException;
-import java.net.URI;
-import java.nio.channels.ByteChannel;
-import java.text.MessageFormat;
-import java.time.Duration;
-
-import static java.util.Optional.ofNullable;
+import lombok.extern.slf4j.Slf4j;
/**
* Low level client structure optimised for communicating with the service at a request level of
@@ -22,35 +20,32 @@
*/
@Builder
@AllArgsConstructor
+@Slf4j
public class RequestClient {
// FIXME taken from the rust code, seems unreasonably big
private static final long DEFAULT_MAX_BODY_SIZE = Long.MAX_VALUE;
- /** Max size for response bodies Defaults to the max value of `usize` on the current platform */
+ /**
+ * Max size for response bodies Defaults to the max value of `usize` on the current platform
+ */
private long maxBodySize;
- /** Handler for IPC-related functionality Defaults to using Unix domain sockets */
+ /**
+ * Handler for IPC-related functionality Defaults to using Unix domain sockets
+ */
private IpcHandler ipcHandler;
- public RequestClient() {
- this(
- DEFAULT_MAX_BODY_SIZE,
- IpcHandler.connectFromUrl(
- URI.create(
- ofNullable(System.getenv("PARSEC_SERVICE_ENDPOINT"))
- .orElse(MessageFormat.format("unix:{0}", UnixSocket.DEFAULT_SOCKET_PATH)))));
- }
-
public static RequestClient withDefaults() {
- return RequestClient.builder()
- .maxBodySize(DEFAULT_MAX_BODY_SIZE)
- .ipcHandler(UnixSocket.withDefaults())
- .build();
+ return RequestClient.builder().maxBodySize(DEFAULT_MAX_BODY_SIZE)
+ .ipcHandler(UnixSocket.withDefaults()).build();
}
/** Send a request and get a response. */
public Response processRequest(Request request) throws IOException {
+ log.info("Processing request: " + request);
// Try to connect once, wait for a timeout until trying again.
try (ByteChannel stream = ipcHandler.connect()) {
+ log.info("Connected to stream");
request.writeToStream(stream);
+ log.info("Wrote request to stream");
return Response.readFromStream(stream, maxBodySize);
}
}
diff --git a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/IpcHandler.java b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/IpcHandler.java
index 0cabffb..65cb769 100644
--- a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/IpcHandler.java
+++ b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/IpcHandler.java
@@ -1,15 +1,16 @@
package org.parallaxsecond.parsec.client.core.ipc_handler;
-import org.parallaxsecond.parsec.client.exceptions.InvalidSocketUrlException;
-import lombok.NonNull;
-
import java.net.URI;
import java.nio.channels.ByteChannel;
import java.time.Duration;
+import org.parallaxsecond.parsec.client.exceptions.InvalidSocketUrlException;
+
+import lombok.NonNull;
+
public interface IpcHandler {
/// Default timeout for client IPC requests.
- Duration DEFAULT_TIMEOUT = Duration.ofSeconds(60);
+ Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10);
static IpcHandler connectFromUrl(@NonNull URI uri) {
switch (uri.getScheme()) {
diff --git a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/UnixSocket.java b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/UnixSocket.java
index 6434573..fa0913c 100644
--- a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/UnixSocket.java
+++ b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/core/ipc_handler/UnixSocket.java
@@ -1,14 +1,15 @@
package org.parallaxsecond.parsec.client.core.ipc_handler;
-import org.parallaxsecond.parsec.client.jna.UnixSocketChannel;
-import lombok.Setter;
-
import java.nio.channels.ByteChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Objects;
+import org.parallaxsecond.parsec.client.jna.UnixSocketChannel;
+
+import lombok.Setter;
+
/** IPC handler for Unix domain sockets */
public class UnixSocket implements IpcHandler {
/** Default socket path used by the service. */
@@ -16,7 +17,8 @@ public class UnixSocket implements IpcHandler {
/** Path at which the socket can be found */
private final Path path;
/** Timeout for reads and writes on the streams */
- @Setter private Duration timeout = DEFAULT_TIMEOUT;
+ @Setter
+ private Duration timeout = DEFAULT_TIMEOUT;
public UnixSocket(String path) {
this(path, DEFAULT_TIMEOUT);
diff --git a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/jna/UnixSocketChannel.java b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/jna/UnixSocketChannel.java
index 712c6fd..e2b33cf 100644
--- a/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/jna/UnixSocketChannel.java
+++ b/parsec-client-java/src/main/java/org/parallaxsecond/parsec/client/jna/UnixSocketChannel.java
@@ -1,10 +1,5 @@
package org.parallaxsecond.parsec.client.jna;
-import org.parallaxsecond.parsec.client.core.FileStat;
-import org.parallaxsecond.parsec.client.exceptions.InvalidSocketAddressException;
-import lombok.NonNull;
-import lombok.extern.slf4j.Slf4j;
-
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
@@ -12,6 +7,12 @@
import java.nio.file.Path;
import java.time.Duration;
+import org.parallaxsecond.parsec.client.core.FileStat;
+import org.parallaxsecond.parsec.client.exceptions.InvalidSocketAddressException;
+
+import lombok.NonNull;
+import lombok.extern.slf4j.Slf4j;
+
@Slf4j
public class UnixSocketChannel implements ByteChannel {
@@ -37,7 +38,7 @@ public int read(ByteBuffer dst) {
while (read < toRead) {
read += (int) UnixSocket.readSocket(this.socket, dst, toRead - read);
log.debug("expected: {}, read: {}", toRead, read);
- ((Buffer)dst).position(pos + read);
+ ((Buffer) dst).position(pos + read);
}
return toRead;
}
@@ -49,7 +50,7 @@ public int write(ByteBuffer src) {
int pos = src.position();
while (written < toWrite) {
written += (int) UnixSocket.writeSocket(socket, src, toWrite - written);
- ((Buffer)src).position(pos + written);
+ ((Buffer) src).position(pos + written);
}
return written;
}
diff --git a/parsec-client-java/src/test/java/org/parallaxsecond/parsec/client/core/BasicClientTest.java b/parsec-client-java/src/test/java/org/parallaxsecond/parsec/client/core/BasicClientTest.java
index 193c1a1..c271ca6 100644
--- a/parsec-client-java/src/test/java/org/parallaxsecond/parsec/client/core/BasicClientTest.java
+++ b/parsec-client-java/src/test/java/org/parallaxsecond/parsec/client/core/BasicClientTest.java
@@ -1,48 +1,128 @@
package org.parallaxsecond.parsec.client.core;
-import lombok.SneakyThrows;
+import java.security.SecureRandom;
+import java.time.Duration;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.parallaxsecond.parsec.client.core.ipc_handler.IpcHandler;
import org.parallaxsecond.parsec.client.jna.Uid;
-import org.parallaxsecond.parsec.protocol.operations.NativeResult;
import org.parallaxsecond.parsec.protobuf.psa_algorithm.PsaAlgorithm;
+import org.parallaxsecond.parsec.protobuf.psa_key_attributes.PsaKeyAttributes;
+import org.parallaxsecond.parsec.protocol.operations.NativeResult;
import org.parallaxsecond.parsec.protocol.requests.Opcode;
import org.parallaxsecond.testcontainers.ParsecContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.shaded.org.awaitility.Awaitility;
-import java.io.File;
-import java.security.SecureRandom;
-
-import static org.junit.jupiter.api.Assertions.*;
+import lombok.SneakyThrows;
+import lombok.extern.slf4j.Slf4j;
@Testcontainers
+@Slf4j
class BasicClientTest {
@Container
- ParsecContainer parsecContainer =
- ParsecContainer.withVersion("0.8.1")
- .withFileSystemBind(
- new File("src/test/resources/mbed-crypto-config.toml").getAbsolutePath(),
- "/etc/parsec/config.toml");
+ ParsecContainer parsecContainer = ParsecContainer.withVersion("latest");
+ // .withCopyToContainer(CONFIG_FILE, "/etc/parsec/config.toml");
private BasicClient client;
private final String eccKey = "eccKey";
private final String rsaKey = "rsaKey";
+ PsaKeyAttributes.KeyAttributes eccKeyAttributes =
+ PsaKeyAttributes.KeyAttributes.newBuilder().setKeyBits(256)
+ .setKeyType(PsaKeyAttributes.KeyType.newBuilder()
+ .setEccKeyPair(PsaKeyAttributes.KeyType.EccKeyPair.newBuilder()
+ .setCurveFamily(PsaKeyAttributes.KeyType.EccFamily.SECP_R1).build())
+ .build())
+ .setKeyPolicy(
+ PsaKeyAttributes.KeyPolicy.newBuilder()
+ .setKeyUsageFlags(
+ PsaKeyAttributes.UsageFlags.newBuilder().setSignHash(true).setVerifyHash(true)
+ .setSignMessage(true).setVerifyMessage(true).setExport(true).build())
+ .setKeyAlgorithm(
+ PsaAlgorithm.Algorithm.newBuilder()
+ .setAsymmetricSignature(PsaAlgorithm.Algorithm.AsymmetricSignature
+ .newBuilder()
+ .setEcdsa(PsaAlgorithm.Algorithm.AsymmetricSignature.Ecdsa
+ .newBuilder()
+ .setHashAlg(PsaAlgorithm.Algorithm.AsymmetricSignature.SignHash
+ .newBuilder().setSpecific(PsaAlgorithm.Algorithm.Hash.SHA_256)
+ .build())
+ .build())
+ .build()))
+ .build())
+ .build();
+
+
+ PsaAlgorithm.Algorithm.AsymmetricSignature eccKeyArgs =
+ PsaAlgorithm.Algorithm.AsymmetricSignature.newBuilder()
+ .setEcdsa(
+ PsaAlgorithm.Algorithm.AsymmetricSignature.Ecdsa
+ .newBuilder().setHashAlg(PsaAlgorithm.Algorithm.AsymmetricSignature.SignHash
+ .newBuilder().setSpecific(PsaAlgorithm.Algorithm.Hash.SHA_256).build())
+ .build())
+ .build();
+
+
+ PsaKeyAttributes.KeyAttributes rsaKeyAttributes = PsaKeyAttributes.KeyAttributes.newBuilder()
+ .setKeyBits(1024)
+ .setKeyType(PsaKeyAttributes.KeyType.newBuilder()
+ .setRsaKeyPair(PsaKeyAttributes.KeyType.RsaKeyPair.newBuilder().build()).build())
+ .setKeyPolicy(PsaKeyAttributes.KeyPolicy.newBuilder()
+ .setKeyUsageFlags(
+ PsaKeyAttributes.UsageFlags.newBuilder().setSignHash(true).setVerifyHash(true)
+ .setSignMessage(true).setVerifyMessage(true).setExport(true).build())
+ .setKeyAlgorithm(PsaAlgorithm.Algorithm.newBuilder()
+ .setAsymmetricSignature(PsaAlgorithm.Algorithm.AsymmetricSignature.newBuilder()
+ .setRsaPkcs1V15Sign(PsaAlgorithm.Algorithm.AsymmetricSignature.RsaPkcs1v15Sign
+ .newBuilder()
+ .setHashAlg(PsaAlgorithm.Algorithm.AsymmetricSignature.SignHash.newBuilder()
+ .setSpecific(PsaAlgorithm.Algorithm.Hash.SHA_256).build())
+ .build())
+ .build()))
+ .build())
+ .build();
+
+
+ PsaAlgorithm.Algorithm.AsymmetricSignature rsaKeyArgs =
+ PsaAlgorithm.Algorithm.AsymmetricSignature.newBuilder()
+ .setRsaPkcs1V15Sign(
+ PsaAlgorithm.Algorithm.AsymmetricSignature.RsaPkcs1v15Sign
+ .newBuilder().setHashAlg(PsaAlgorithm.Algorithm.AsymmetricSignature.SignHash
+ .newBuilder().setSpecific(PsaAlgorithm.Algorithm.Hash.SHA_256).build())
+ .build())
+ .build();
+
+
@BeforeEach
void setup() {
+
+ log.info("Setting up test");
// uid of the parse user in docker
Uid.IMPL.set(() -> 4000);
+
+ // Wait for container to be running
Awaitility.await().until(parsecContainer::isRunning);
- this.client =
- BasicClient.client(
- "parsec-tool", IpcHandler.connectFromUrl(parsecContainer.getSocketUri()));
+
+ // Print container logs for debugging
+ log.info("Container logs:");
+ log.info(parsecContainer.getLogs());
+
+ // Wait a bit for socat to be ready
+ Awaitility.await().pollDelay(Duration.ofSeconds(1)).until(() -> true);
+
+ this.client = BasicClient.client("parsec-tool",
+ IpcHandler.connectFromUrl(parsecContainer.getSocketUri()));
parsecContainer.parsecTool("create-ecc-key", "--key-name", eccKey);
parsecContainer.parsecTool("create-rsa-key", "--key-name", rsaKey);
}
+
/**
* would be good to have this dockerized ssh can forward AF_UNIX sockets
*
@@ -70,34 +150,63 @@ void listKeys() {
@Test
@SneakyThrows
- void hash() {
- PsaAlgorithm.Algorithm.AsymmetricSignature keyargs =
- PsaAlgorithm.Algorithm.AsymmetricSignature.newBuilder()
- .setEcdsa(
- PsaAlgorithm.Algorithm.AsymmetricSignature.Ecdsa.newBuilder()
- .setHashAlg(
- PsaAlgorithm.Algorithm.AsymmetricSignature.SignHash.newBuilder()
- .setSpecific(PsaAlgorithm.Algorithm.Hash.SHA_256)
- .build())
- .build())
- .build();
+ void hashRSAKey() {
+
+ String keyName = "rsa-test-key";
+ client.psaGenerateKey(keyName, rsaKeyAttributes);
byte[] bytes = new byte[1024];
new SecureRandom().nextBytes(bytes);
- NativeResult.PsaSignHashResult hashResult = client.psaSignHash(eccKey, bytes, keyargs);
- byte[] signature = hashResult.getSignature();
- assertNotNull(signature);
+ try {
+ NativeResult.PsaSignHashResult hashResult = client.psaSignHash(keyName, bytes, rsaKeyArgs);
+ byte[] signature = hashResult.getSignature();
+ assertNotNull(signature);
+
+ NativeResult.PsaVerifyHashResult verifiedResult =
+ client.psaVerifyHash(keyName, bytes, rsaKeyArgs, signature);
+ assertNotNull(verifiedResult);
+
+ try {
+ bytes[0] += 1;
+ client.psaVerifyHash(keyName, bytes, rsaKeyArgs, signature);
+ fail("signature must no verify");
+ } catch (Exception e) {
+ // OK
+ }
+ } catch (Exception e) {
+ // wait 60 seconds so I can analyze docker output, then end
+ Thread.sleep(30000L);
+ }
+ }
- NativeResult.PsaVerifyHashResult verifiedResult =
- client.psaVerifyHash(eccKey, bytes, keyargs, signature);
- assertNotNull(verifiedResult);
+ @Test
+ @SneakyThrows
+ void hashECCKey() {
+
+ String keyName = "ecc-test-key";
+ client.psaGenerateKey(keyName, eccKeyAttributes);
+ byte[] bytes = new byte[1024];
+ new SecureRandom().nextBytes(bytes);
try {
- bytes[0] += 1;
- client.psaVerifyHash(eccKey, bytes, keyargs, signature);
- fail("signature must no verify");
+ NativeResult.PsaSignHashResult hashResult = client.psaSignHash(keyName, bytes, eccKeyArgs);
+ byte[] signature = hashResult.getSignature();
+ assertNotNull(signature);
+
+ NativeResult.PsaVerifyHashResult verifiedResult =
+ client.psaVerifyHash(keyName, bytes, eccKeyArgs, signature);
+ assertNotNull(verifiedResult);
+
+ try {
+ bytes[0] += 1;
+ client.psaVerifyHash(keyName, bytes, rsaKeyArgs, signature);
+ fail("signature must no verify");
+ } catch (Exception e) {
+ // OK
+ }
} catch (Exception e) {
- // OK
+ // wait 60 seconds so I can analyze docker output, then end
+ Thread.sleep(30000L);
}
}
@@ -105,10 +214,9 @@ void hash() {
void generateRandom() {
long length = 512L;
- byte[] randomBytes = client.psaGenerateRandom(length);
+ byte[] randomBytes = client.psaGenerateRandom(length);
assertNotNull(randomBytes);
- assertEquals((long)randomBytes.length, length);
+ assertEquals((long) randomBytes.length, length);
}
-
}
diff --git a/parsec-client-java/src/test/resources/cryptoauthlib-config.toml.bak b/parsec-client-java/src/test/resources/cryptoauthlib-config.toml.bak
index 71d0d8f..8d8e5de 100644
--- a/parsec-client-java/src/test/resources/cryptoauthlib-config.toml.bak
+++ b/parsec-client-java/src/test/resources/cryptoauthlib-config.toml.bak
@@ -2,6 +2,7 @@
# The CI already timestamps the logs
log_timestamp = false
log_error_details = true
+log_level = "debug" # Possible values: "debug", "info", "warn", "error", "trace"
# The container runs the Parsec service as root, so make sure we disable root
# checks.
@@ -20,7 +21,7 @@ auth_type = "Direct"
[[key_manager]]
name = "on-disk-manager"
manager_type = "OnDisk"
-store_path = "/var/lib/parsec/mappings"
+store_path = "/parsec/quickstart/mappings\"
[[provider]]
provider_type = "CryptoAuthLib"
diff --git a/parsec-client-java/src/test/resources/logback-test.xml b/parsec-client-java/src/test/resources/logback-test.xml
new file mode 100644
index 0000000..575807d
--- /dev/null
+++ b/parsec-client-java/src/test/resources/logback-test.xml
@@ -0,0 +1,15 @@
+
+ Request header is parsed from its raw form, ensuring that all fields are valid. The
+ *
+ * Request header is parsed from its raw form, ensuring that all fields are valid. The
* `body_len_limit` parameter allows the interface client to reject requests that are longer than
* a predefined limit. The length limit is in bytes.
*
- * # Errors - if reading any of the subfields (header, body or auth) fails, the corresponding
+ *
+ * # Errors - if reading any of the subfields (header, body or auth) fails, the corresponding
* `ResponseStatus` will be returned. - if the request body size specified in the header is larger
* than the limit passed as a parameter, `BodySizeExceedsLimit` will be returned.
*/
@@ -46,11 +49,8 @@ public static Request readFromStream(ReadableByteChannel channel, int bodyLenLim
WireHeader_1_0 rawHeader = WireHeader_1_0.readFromStream(channel);
int bodyLen = rawHeader.getBodyLen();
if (bodyLen > bodyLenLimit) {
- throw new InterfaceException(
- ResponseStatus.BodySizeExceedsLimit,
- MessageFormat.format(
- "Request body length ({0}) bigger than the limit given ({1}).",
- bodyLen, bodyLenLimit));
+ throw new InterfaceException(ResponseStatus.BodySizeExceedsLimit, MessageFormat.format(
+ "Request body length ({0}) bigger than the limit given ({1}).", bodyLen, bodyLenLimit));
}
RequestBody body = RequestBody.readFromStream(channel, bodyLen);
RequestAuth auth = RequestAuth.readFromStream(channel, rawHeader.getAuthLen());
@@ -61,19 +61,22 @@ public static Request readFromStream(ReadableByteChannel channel, int bodyLenLim
/**
* Serialise request and write it to given stream.
*
- * Request header is first converted to its raw format before serialization. # Errors - if an
- * IO operation fails while writing any of the subfields of the request,
+ *
+ * Request header is first converted to its raw format before serialization. # Errors - if an IO
+ * operation fails while writing any of the subfields of the request,
* `ResponseStatus::ConnectionError` is returned. - if encoding any of the fields in the header
* fails, `ResponseStatus::InvalidEncoding` is returned.
*/
public void writeToStream(WritableByteChannel channel) throws IOException {
- header
- .toRaw()
- .bodyLen(body.length())
- .authLen((short) auth.getBuffer().length())
- .build()
+ header.toRaw().bodyLen(body.length()).authLen((short) auth.getBuffer().length()).build()
.writeToStream(channel);
body.writeToStream(channel);
auth.writeToStream(channel);
}
+
+ @Override
+ public String toString() {
+ return "Request{" + "header=" + header + ", body=" + body + ", auth=" + auth + '}';
+ }
+
}
diff --git a/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestBody.java b/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestBody.java
index 91aa5a4..c60067d 100644
--- a/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestBody.java
+++ b/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestBody.java
@@ -1,8 +1,5 @@
package org.parallaxsecond.parsec.protocol.requests.request;
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
-
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
@@ -10,9 +7,13 @@
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
@RequiredArgsConstructor
public class RequestBody {
- @Getter private final ByteBuffer buffer;
+ @Getter
+ private final ByteBuffer buffer;
public RequestBody(byte[] buf) {
this(ByteBuffer.wrap(buf));
@@ -22,7 +23,7 @@ public static RequestBody readFromStream(ReadableByteChannel channel, int len)
throws IOException {
ByteBuffer buf = ByteBuffer.allocate(len).order(ByteOrder.LITTLE_ENDIAN);
channel.read(buf);
- ((Buffer)buf).flip();
+ ((Buffer) buf).flip();
return new RequestBody(buf);
}
@@ -33,4 +34,9 @@ public void writeToStream(WritableByteChannel channel) throws IOException {
public int length() {
return buffer.remaining();
}
+
+ @Override
+ public String toString() {
+ return "RequestBody current length=" + length();
+ }
}
diff --git a/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestHeader.java b/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestHeader.java
index a0b55f1..8404b08 100644
--- a/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestHeader.java
+++ b/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/RequestHeader.java
@@ -5,6 +5,7 @@
import org.parallaxsecond.parsec.protocol.requests.Opcode;
import org.parallaxsecond.parsec.protocol.requests.ProviderId;
import org.parallaxsecond.parsec.protocol.requests.request.common.WireHeader_1_0;
+
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@@ -12,7 +13,8 @@
/**
* A native representation of the request header.
*
- * Fields that are not relevant for application development (e.g. magic number) are not copied
+ *
+ * Fields that are not relevant for application development (e.g. magic number) are not copied
* across from the raw header.
*/
@RequiredArgsConstructor
@@ -33,29 +35,26 @@ public class RequestHeader {
private final Opcode opcode;
public static RequestHeader fromRaw(WireHeader_1_0 wireHeader) {
- return RequestHeader.builder()
- .provider(ProviderId.fromCode(wireHeader.getProvider()))
+ return RequestHeader.builder().provider(ProviderId.fromCode(wireHeader.getProvider()))
.session(wireHeader.getSession())
.contentType(BodyType.fromCode(wireHeader.getContentType()))
.acceptType(BodyType.fromCode(wireHeader.getAcceptType()))
.authType(AuthType.fromCode(wireHeader.getAuthType()))
- .opcode(Opcode.fromCode(wireHeader.getOpcode()))
- .build();
+ .opcode(Opcode.fromCode(wireHeader.getOpcode())).build();
}
public WireHeader_1_0.WireHeader_1_0Builder toRaw() {
- return WireHeader_1_0.builder()
- .flags((short) 0)
- .provider(getProvider().getId())
- .session(getSession())
- .contentType(getContentType().getId())
- .acceptType(getAcceptType().getId())
- .authType(getAuthType().getId())
- .bodyLen(0)
- .authLen((short) 0)
- .opcode(getOpcode().getCode())
- .status((short) 0)
- .reserved1((byte) 0)
+ return WireHeader_1_0.builder().flags((short) 0).provider(getProvider().getId())
+ .session(getSession()).contentType(getContentType().getId())
+ .acceptType(getAcceptType().getId()).authType(getAuthType().getId()).bodyLen(0)
+ .authLen((short) 0).opcode(getOpcode().getCode()).status((short) 0).reserved1((byte) 0)
.reserved2((byte) 0);
}
+
+ @Override
+ public String toString() {
+ return "RequestHeader{" + "provider=" + provider + ", session=" + session + ", contentType="
+ + contentType + ", acceptType=" + acceptType + ", authType=" + authType + ", opcode="
+ + opcode + '}';
+ }
}
diff --git a/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/common/WireHeader_1_0.java b/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/common/WireHeader_1_0.java
index bc3de24..3e0a66b 100644
--- a/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/common/WireHeader_1_0.java
+++ b/parsec-interface-java/src/main/java/org/parallaxsecond/parsec/protocol/requests/request/common/WireHeader_1_0.java
@@ -1,11 +1,5 @@
package org.parallaxsecond.parsec.protocol.requests.request.common;
-import org.parallaxsecond.parsec.protocol.requests.InterfaceException;
-import org.parallaxsecond.parsec.protocol.requests.ResponseStatus;
-import lombok.Builder;
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
-
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
@@ -14,18 +8,29 @@
import java.nio.channels.WritableByteChannel;
import java.text.MessageFormat;
+import org.parallaxsecond.parsec.protocol.requests.InterfaceException;
+import org.parallaxsecond.parsec.protocol.requests.ResponseStatus;
+
+import lombok.Builder;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
/**
* This module defines and implements the raw wire protocol header frame for version 1.0 of the
* protocol.
*
- * Raw representation of a common request/response header, as defined for the wire format.
+ *
+ * Raw representation of a common request/response header, as defined for the wire format.
*
- * Serialisation and deserialisation are handled by `serde`, also in tune with the wire format
- * (i.e. little-endian, native encoding).
+ *
+ * Serialisation and deserialisation are handled by `serde`, also in tune with the wire format (i.e.
+ * little-endian, native encoding).
*/
@RequiredArgsConstructor
@Builder
@Getter
+@Slf4j
public class WireHeader_1_0 {
public static final int MAGIC_NUMBER = 0x5EC0_A710;
public static final byte WIRE_PROTOCOL_VERSION_MAJ = 1;
@@ -63,53 +68,35 @@ public static WireHeader_1_0 readFromStream(ReadableByteChannel channel) throws
ByteBuffer buf = ByteBuffer.allocate(REQUEST_HDR_SIZE + 6).order(ByteOrder.LITTLE_ENDIAN);
channel.read(buf);
- ((Buffer)buf).flip();
+ ((Buffer) buf).flip();
int magicNumber = buf.getInt();
if (magicNumber != MAGIC_NUMBER) {
- throw new InterfaceException(
- ResponseStatus.InvalidHeader,
+ throw new InterfaceException(ResponseStatus.InvalidHeader,
MessageFormat.format("Expected magic number {0}, got {1}", MAGIC_NUMBER, magicNumber));
}
short hdrSize = buf.getShort();
if (hdrSize != REQUEST_HDR_SIZE || buf.remaining() < hdrSize) {
- throw new InterfaceException(
- ResponseStatus.InvalidHeader,
- MessageFormat.format(
- "Expected request header size {0}, got {1}, remaining {2}",
+ throw new InterfaceException(ResponseStatus.InvalidHeader,
+ MessageFormat.format("Expected request header size {0}, got {1}, remaining {2}",
REQUEST_HDR_SIZE, hdrSize, buf.remaining()));
}
int versionMaj = buf.get();
int versionMin = buf.get();
if (versionMaj != WIRE_PROTOCOL_VERSION_MAJ || versionMin != WIRE_PROTOCOL_VERSION_MIN) {
- throw new InterfaceException(
- ResponseStatus.WireProtocolVersionNotSupported,
- MessageFormat.format(
- "Expected wire protocol version {0}.{1}, got {2}.{3} instead",
+ throw new InterfaceException(ResponseStatus.WireProtocolVersionNotSupported,
+ MessageFormat.format("Expected wire protocol version {0}.{1}, got {2}.{3} instead",
WIRE_PROTOCOL_VERSION_MAJ, WIRE_PROTOCOL_VERSION_MIN, versionMaj, versionMin));
}
- WireHeader_1_0 wireHeader =
- WireHeader_1_0.builder()
- .flags(buf.getShort())
- .provider(buf.get())
- .session(buf.getLong())
- .contentType(buf.get())
- .acceptType(buf.get())
- .authType(buf.get())
- .bodyLen(buf.getInt())
- .authLen(buf.getShort())
- .opcode(buf.getInt())
- .status(buf.getShort())
- .reserved1(buf.get())
- .reserved2(buf.get())
- .build();
+ WireHeader_1_0 wireHeader = WireHeader_1_0.builder().flags(buf.getShort()).provider(buf.get())
+ .session(buf.getLong()).contentType(buf.get()).acceptType(buf.get()).authType(buf.get())
+ .bodyLen(buf.getInt()).authLen(buf.getShort()).opcode(buf.getInt()).status(buf.getShort())
+ .reserved1(buf.get()).reserved2(buf.get()).build();
if (wireHeader.reserved1 != 0x00 || wireHeader.reserved2 != 0x00) {
- throw new InterfaceException(
- ResponseStatus.InvalidHeader,
- MessageFormat.format(
- "expected reserved1 0, got {0}, reserved2 0, got {1}",
+ throw new InterfaceException(ResponseStatus.InvalidHeader,
+ MessageFormat.format("expected reserved1 0, got {0}, reserved2 0, got {1}",
wireHeader.reserved1, wireHeader.reserved2));
}
return wireHeader;
@@ -118,30 +105,29 @@ public static WireHeader_1_0 readFromStream(ReadableByteChannel channel) throws
/**
* Serialise the request header and write the corresponding bytes to the given stream.
*
- * # Errors - if marshalling the header fails, `ResponseStatus::InvalidEncoding` is returned. -
- * if writing the header bytes fails, `ResponseStatus::ConnectionError` is returned.
+ *
+ * # Errors - if marshalling the header fails, `ResponseStatus::InvalidEncoding` is returned. - if
+ * writing the header bytes fails, `ResponseStatus::ConnectionError` is returned.
*/
public void writeToStream(WritableByteChannel channel) throws IOException {
- ByteBuffer buf =
- ByteBuffer.allocate(REQUEST_HDR_SIZE + 6)
- .order(ByteOrder.LITTLE_ENDIAN)
- .putInt(MAGIC_NUMBER) // 4
- .putShort(REQUEST_HDR_SIZE) // 6
- .put(WIRE_PROTOCOL_VERSION_MAJ) // 7
- .put(WIRE_PROTOCOL_VERSION_MIN) // 8
- .putShort(flags) // 10
- .put(provider) // 11
- .putLong(session) // 19
- .put(contentType) // 20
- .put(acceptType) // 21
- .put(authType) // 22
- .putInt(bodyLen) // 26
- .putShort(authLen) // 28
- .putInt(opcode) // 32
- .putShort(status) // 34
- .put(reserved1) // 35
- .put(reserved2); // 36
- ((Buffer)buf).flip();
+ ByteBuffer buf = ByteBuffer.allocate(REQUEST_HDR_SIZE + 6).order(ByteOrder.LITTLE_ENDIAN)
+ .putInt(MAGIC_NUMBER) // 4
+ .putShort(REQUEST_HDR_SIZE) // 6
+ .put(WIRE_PROTOCOL_VERSION_MAJ) // 7
+ .put(WIRE_PROTOCOL_VERSION_MIN) // 8
+ .putShort(flags) // 10
+ .put(provider) // 11
+ .putLong(session) // 19
+ .put(contentType) // 20
+ .put(acceptType) // 21
+ .put(authType) // 22
+ .putInt(bodyLen) // 26
+ .putShort(authLen) // 28
+ .putInt(opcode) // 32
+ .putShort(status) // 34
+ .put(reserved1) // 35
+ .put(reserved2); // 36
+ ((Buffer) buf).flip();
channel.write(buf);
}
diff --git a/parsec-jca-java-test/pom.xml b/parsec-jca-java-test/pom.xml
index 8aa1a15..30d5c5a 100644
--- a/parsec-jca-java-test/pom.xml
+++ b/parsec-jca-java-test/pom.xml
@@ -1,7 +1,6 @@